text
stringlengths
8
4.13M
// 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::any::Any; use std::collections::HashSet; use std::fmt::Debug; use std::ops::Range; use common_arrow::arrow::array::Array; use common_arrow::arrow::chunk::Chunk as ArrowChunk; use common_arrow::ArrayRef; use common_exception::ErrorCode; use common_exception::Result; use crate::schema::DataSchema; use crate::types::AnyType; use crate::types::DataType; use crate::Column; use crate::ColumnBuilder; use crate::DataSchemaRef; use crate::Domain; use crate::Scalar; use crate::TableSchemaRef; use crate::Value; pub type SendableDataBlockStream = std::pin::Pin<Box<dyn futures::stream::Stream<Item = Result<DataBlock>> + Send>>; pub type BlockMetaInfoPtr = Box<dyn BlockMetaInfo>; /// DataBlock is a lightweight container for a group of columns. #[derive(Clone)] pub struct DataBlock { columns: Vec<BlockEntry>, num_rows: usize, meta: Option<BlockMetaInfoPtr>, } #[derive(Clone, Debug)] pub struct BlockEntry { pub data_type: DataType, pub value: Value<AnyType>, } #[typetag::serde(tag = "type")] pub trait BlockMetaInfo: Debug + Send + Sync + 'static { fn as_any(&self) -> &dyn Any; #[allow(clippy::borrowed_box)] fn equals(&self, info: &Box<dyn BlockMetaInfo>) -> bool; fn clone_self(&self) -> Box<dyn BlockMetaInfo>; } pub trait BlockMetaInfoDowncast: Sized { fn downcast_from(boxed: BlockMetaInfoPtr) -> Option<Self>; fn downcast_ref_from(boxed: &BlockMetaInfoPtr) -> Option<&Self>; } impl<T: BlockMetaInfo> BlockMetaInfoDowncast for T { fn downcast_from(boxed: BlockMetaInfoPtr) -> Option<Self> { if boxed.as_any().is::<T>() { unsafe { // SAFETY: `is` ensures this type cast is correct let raw_ptr = Box::into_raw(boxed) as *const dyn BlockMetaInfo; return Some(std::ptr::read(raw_ptr as *const Self)); } } None } fn downcast_ref_from(boxed: &BlockMetaInfoPtr) -> Option<&Self> { if boxed.as_any().is::<T>() { unsafe { // SAFETY: `is` ensures this type cast is correct let unboxed = boxed.as_ref(); return Some(&*(unboxed as *const dyn BlockMetaInfo as *const Self)); } } None } } impl DataBlock { #[inline] pub fn new(columns: Vec<BlockEntry>, num_rows: usize) -> Self { DataBlock::new_with_meta(columns, num_rows, None) } #[inline] pub fn new_with_meta( columns: Vec<BlockEntry>, num_rows: usize, meta: Option<BlockMetaInfoPtr>, ) -> Self { debug_assert!(columns.iter().all(|entry| match &entry.value { Value::Scalar(_) => true, Value::Column(c) => c.len() == num_rows && c.data_type() == entry.data_type, })); Self { columns, num_rows, meta, } } #[inline] pub fn new_from_columns(columns: Vec<Column>) -> Self { assert!(!columns.is_empty()); let num_rows = columns[0].len(); debug_assert!(columns.iter().all(|c| c.len() == num_rows)); let columns = columns .into_iter() .map(|col| BlockEntry { data_type: col.data_type(), value: Value::Column(col), }) .collect(); DataBlock::new(columns, num_rows) } #[inline] pub fn empty() -> Self { DataBlock::new(vec![], 0) } #[inline] pub fn empty_with_schema(schema: DataSchemaRef) -> Self { let columns = schema .fields() .iter() .map(|f| { let builder = ColumnBuilder::with_capacity(f.data_type(), 0); let col = builder.build(); BlockEntry { data_type: f.data_type().clone(), value: Value::Column(col), } }) .collect(); DataBlock::new(columns, 0) } #[inline] pub fn empty_with_meta(meta: BlockMetaInfoPtr) -> Self { DataBlock::new_with_meta(vec![], 0, Some(meta)) } #[inline] pub fn take_meta(&mut self) -> Option<BlockMetaInfoPtr> { self.meta.take() } #[inline] pub fn columns(&self) -> &[BlockEntry] { &self.columns } #[inline] pub fn get_by_offset(&self, offset: usize) -> &BlockEntry { &self.columns[offset] } #[inline] pub fn num_rows(&self) -> usize { self.num_rows } #[inline] pub fn num_columns(&self) -> usize { self.columns.len() } #[inline] pub fn is_empty(&self) -> bool { self.num_rows() == 0 } #[inline] pub fn domains(&self) -> Vec<Domain> { self.columns .iter() .map(|entry| entry.value.as_ref().domain(&entry.data_type)) .collect() } #[inline] pub fn memory_size(&self) -> usize { self.columns().iter().map(|entry| entry.memory_size()).sum() } pub fn convert_to_full(&self) -> Self { let columns = self .columns() .iter() .map(|entry| match &entry.value { Value::Scalar(s) => { let builder = ColumnBuilder::repeat(&s.as_ref(), self.num_rows, &entry.data_type); let col = builder.build(); BlockEntry { data_type: entry.data_type.clone(), value: Value::Column(col), } } Value::Column(c) => BlockEntry { data_type: entry.data_type.clone(), value: Value::Column(c.clone()), }, }) .collect(); Self { columns, num_rows: self.num_rows, meta: self.meta.clone(), } } pub fn slice(&self, range: Range<usize>) -> Self { let columns = self .columns() .iter() .map(|entry| match &entry.value { Value::Scalar(s) => BlockEntry { data_type: entry.data_type.clone(), value: Value::Scalar(s.clone()), }, Value::Column(c) => BlockEntry { data_type: entry.data_type.clone(), value: Value::Column(c.slice(range.clone())), }, }) .collect(); Self { columns, num_rows: range.end - range.start, meta: self.meta.clone(), } } #[inline] pub fn add_column(&mut self, entry: BlockEntry) { #[cfg(debug_assertions)] if let Value::Column(col) = &entry.value { assert_eq!(self.num_rows, col.len()); assert_eq!(col.data_type(), entry.data_type); } self.columns.push(entry); } #[inline] pub fn pop_columns(self, num: usize) -> Result<Self> { let mut columns = self.columns.clone(); let len = columns.len(); for _ in 0..num.min(len) { columns.pop().unwrap(); } Ok(Self { columns, num_rows: self.num_rows, meta: self.meta, }) } /// Resort the columns according to the schema. #[inline] pub fn resort(self, src_schema: &DataSchema, dest_schema: &DataSchema) -> Result<Self> { let columns = dest_schema .fields() .iter() .map(|dest_field| { let src_offset = src_schema.index_of(dest_field.name()).map_err(|_| { let valid_fields: Vec<String> = src_schema .fields() .iter() .map(|f| f.name().to_string()) .collect(); ErrorCode::BadArguments(format!( "Unable to get field named \"{}\". Valid fields: {:?}", dest_field.name(), valid_fields )) })?; Ok(self.get_by_offset(src_offset).clone()) }) .collect::<Result<Vec<_>>>()?; Ok(Self { columns, num_rows: self.num_rows, meta: self.meta, }) } #[inline] pub fn add_meta(self, meta: Option<BlockMetaInfoPtr>) -> Result<Self> { if self.meta.is_some() { return Err(ErrorCode::Internal( "Internal error, block meta data is set twice.", )); } Ok(Self { columns: self.columns.clone(), num_rows: self.num_rows, meta, }) } #[inline] pub fn get_meta(&self) -> Option<&BlockMetaInfoPtr> { self.meta.as_ref() } #[inline] pub fn get_owned_meta(self) -> Option<BlockMetaInfoPtr> { self.meta } pub fn from_arrow_chunk<A: AsRef<dyn Array>>( arrow_chunk: &ArrowChunk<A>, schema: &DataSchema, ) -> Result<Self> { let cols = schema .fields .iter() .zip(arrow_chunk.arrays()) .map(|(field, col)| { Ok(BlockEntry { data_type: field.data_type().clone(), value: Value::Column(Column::from_arrow(col.as_ref(), field.data_type())), }) }) .collect::<Result<_>>()?; Ok(DataBlock::new(cols, arrow_chunk.len())) } pub fn from_arrow_chunk_with_types<A: AsRef<dyn Array>>( arrow_chunk: &ArrowChunk<A>, data_types: &[DataType], ) -> Result<Self> { let cols = data_types .iter() .zip(arrow_chunk.arrays()) .map(|(data_type, col)| { Ok(BlockEntry { data_type: data_type.clone(), value: Value::Column(Column::from_arrow(col.as_ref(), data_type)), }) }) .collect::<Result<_>>()?; Ok(DataBlock::new(cols, arrow_chunk.len())) } // If default_vals[i].is_some(), then DataBlock.column[i] = num_rows * default_vals[i]. // Else, DataBlock.column[i] = chuck.column. // For example, Schema.field is [a,b,c] and default_vals is [Some("a"), None, Some("c")], // then the return block column will be ["a"*num_rows, chunk.column[0], "c"*num_rows]. pub fn create_with_default_value_and_chunk<A: AsRef<dyn Array>>( schema: &DataSchema, chuck: &ArrowChunk<A>, default_vals: &[Option<Scalar>], num_rows: usize, ) -> Result<DataBlock> { let mut chunk_idx: usize = 0; let schema_fields = schema.fields(); let chunk_columns = chuck.arrays(); let mut columns = Vec::with_capacity(default_vals.len()); for (i, default_val) in default_vals.iter().enumerate() { let field = &schema_fields[i]; let data_type = field.data_type(); let column = match default_val { Some(default_val) => BlockEntry { data_type: data_type.clone(), value: Value::Scalar(default_val.to_owned()), }, None => { let chunk_column = &chunk_columns[chunk_idx]; chunk_idx += 1; BlockEntry { data_type: data_type.clone(), value: Value::Column(Column::from_arrow(chunk_column.as_ref(), data_type)), } } }; columns.push(column); } Ok(DataBlock::new(columns, num_rows)) } pub fn create_with_default_value( schema: &DataSchema, default_vals: &[Scalar], num_rows: usize, ) -> Result<DataBlock> { let default_opt_vals: Vec<Option<Scalar>> = default_vals .iter() .map(|default_val| Some(default_val.to_owned())) .collect(); Self::create_with_default_value_and_chunk( schema, &ArrowChunk::<ArrayRef>::new(vec![]), &default_opt_vals[0..], num_rows, ) } // If block_column_ids not contain schema.field[i].column_id, // then DataBlock.column[i] = num_rows * default_vals[i]. // Else, DataBlock.column[i] = data_block.column. pub fn create_with_default_value_and_block( schema: &TableSchemaRef, data_block: &DataBlock, block_column_ids: &HashSet<u32>, default_vals: &[Scalar], ) -> Result<DataBlock> { let num_rows = data_block.num_rows(); let mut data_block_columns_idx: usize = 0; let data_block_columns = data_block.columns(); let schema_fields = schema.fields(); let mut columns = Vec::with_capacity(default_vals.len()); for (i, field) in schema_fields.iter().enumerate() { let column_id = field.column_id(); let column = if !block_column_ids.contains(&column_id) { let default_val = &default_vals[i]; let table_data_type = field.data_type(); BlockEntry { data_type: table_data_type.into(), value: Value::Scalar(default_val.to_owned()), } } else { let chunk_column = &data_block_columns[data_block_columns_idx]; data_block_columns_idx += 1; chunk_column.clone() }; columns.push(column); } Ok(DataBlock::new(columns, num_rows)) } } impl TryFrom<DataBlock> for ArrowChunk<ArrayRef> { type Error = ErrorCode; fn try_from(v: DataBlock) -> Result<ArrowChunk<ArrayRef>> { let arrays = v .convert_to_full() .columns() .iter() .map(|val| { let column = val.value.clone().into_column().unwrap(); column.as_arrow() }) .collect(); Ok(ArrowChunk::try_new(arrays)?) } } impl BlockEntry { pub fn memory_size(&self) -> usize { match &self.value { Value::Scalar(s) => std::mem::size_of_val(s), Value::Column(c) => c.memory_size(), } } } impl Eq for Box<dyn BlockMetaInfo> {} impl PartialEq for Box<dyn BlockMetaInfo> { fn eq(&self, other: &Self) -> bool { let this_type_id = self.as_any().type_id(); let other_type_id = other.as_any().type_id(); match this_type_id == other_type_id { true => self.equals(other), false => false, } } } impl Clone for Box<dyn BlockMetaInfo> { fn clone(&self) -> Self { self.clone_self() } }
//! The types: Such as strings or integers use std::fmt; #[cfg(feature = "smol_str")] use smol_str::SmolStr; #[cfg(not(feature = "smol_str"))] type SmolStr = String; /// An anchor point for a path, such as if it's relative or absolute #[derive(Clone, Debug, PartialEq)] pub enum Anchor { Absolute, Relative, Home, Store, Uri } /// A value, such as a string or integer #[derive(Clone, Debug, PartialEq)] pub enum Value { Bool(bool), Float(String), Integer(String), Null, Path(Anchor, String), Str { multiline: bool, original: SmolStr, content: SmolStr } } impl From<bool> for Value { fn from(val: bool) -> Value { Value::Bool(val) } } impl From<i64> for Value { fn from(val: i64) -> Value { Value::Integer(val.to_string()) } } impl From<f64> for Value { fn from(val: f64) -> Value { Value::Float(val.to_string()) } } impl From<String> for Value { fn from(val: String) -> Value { let val = SmolStr::from(val); Value::Str { multiline: false, original: val.clone(), content: val } } } impl From<&str> for Value { fn from(val: &str) -> Value { Value::from(String::from(val)) } } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Value::Bool(val) => write!(f, "{}", val), Value::Float(val) => write!(f, "{}", val), Value::Integer(val) => write!(f, "{}", val), Value::Null => write!(f, "null"), Value::Path(Anchor::Absolute, path) => write!(f, "{}", path), Value::Path(Anchor::Relative, path) => write!(f, "{}", path), Value::Path(Anchor::Home, path) => write!(f, "~/{}", path), Value::Path(Anchor::Store, path) => write!(f, "<{}>", path), Value::Path(Anchor::Uri, path) => write!(f, "{}", path), Value::Str { multiline, original, content: _ } => if *multiline { write!(f, "''{}''", original) } else { write!(f, "\"{}\"", original) } } } }
mod greet; fn main() { println!("Hello,World!"); greet::greet("Alpha"); }
pub mod home; pub mod role_created; pub mod dropdown_viewdetail; pub mod tab_setting; pub mod tab_permission; pub mod tab_users;
use proc_macro::TokenStream; use quote::quote; use syn::{ext::IdentExt, Error, FnArg, ItemFn, Pat}; use crate::{ args, args::{Argument, RenameRuleExt, RenameTarget}, utils::{ generate_default, get_crate_name, get_rustdoc, parse_graphql_attrs, remove_graphql_attrs, visible_fn, GeneratorResult, }, }; pub fn generate( directive_args: &args::Directive, item_fn: &mut ItemFn, ) -> GeneratorResult<TokenStream> { let crate_name = get_crate_name(directive_args.internal); let ident = &item_fn.sig.ident; let vis = &item_fn.vis; let directive_name = if !directive_args.name_type { let name = directive_args .name .clone() .unwrap_or_else(|| item_fn.sig.ident.to_string()); quote!(::std::borrow::Cow::Borrowed(#name)) } else { quote!(<Self as #crate_name::TypeName>::type_name()) }; let desc = get_rustdoc(&item_fn.attrs)? .map(|s| quote!(::std::option::Option::Some(::std::string::ToString::to_string(#s)))) .unwrap_or_else(|| quote!(::std::option::Option::None)); let visible = visible_fn(&directive_args.visible); let repeatable = directive_args.repeatable; let mut get_params = Vec::new(); let mut use_params = Vec::new(); let mut schema_args = Vec::new(); for arg in item_fn.sig.inputs.iter_mut() { let mut arg_info = None; if let FnArg::Typed(pat) = arg { if let Pat::Ident(ident) = &*pat.pat { arg_info = Some((ident.clone(), pat.ty.clone(), pat.attrs.clone())); remove_graphql_attrs(&mut pat.attrs); } } let (arg_ident, arg_ty, arg_attrs) = match arg_info { Some(info) => info, None => { return Err(Error::new_spanned(arg, "Invalid argument type.").into()); } }; let Argument { name, desc, default, default_with, validator, visible, secret, .. } = parse_graphql_attrs::<args::Argument>(&arg_attrs)?.unwrap_or_default(); let name = name.clone().unwrap_or_else(|| { directive_args .rename_args .rename(arg_ident.ident.unraw().to_string(), RenameTarget::Argument) }); let desc = desc .as_ref() .map(|s| quote! {::std::option::Option::Some(::std::string::ToString::to_string(#s))}) .unwrap_or_else(|| quote! {::std::option::Option::None}); let default = generate_default(&default, &default_with)?; let schema_default = default .as_ref() .map(|value| { quote! { ::std::option::Option::Some(::std::string::ToString::to_string( &<#arg_ty as #crate_name::InputType>::to_value(&#value) )) } }) .unwrap_or_else(|| quote! {::std::option::Option::None}); let visible = visible_fn(&visible); schema_args.push(quote! { args.insert(::std::borrow::ToOwned::to_owned(#name), #crate_name::registry::MetaInputValue { name: ::std::string::ToString::to_string(#name), description: #desc, ty: <#arg_ty as #crate_name::InputType>::create_type_info(registry), default_value: #schema_default, visible: #visible, inaccessible: false, tags: ::std::default::Default::default(), is_secret: #secret, }); }); let validators = validator.clone().unwrap_or_default().create_validators( &crate_name, quote!(&#arg_ident), Some(quote!(.map_err(|err| err.into_server_error(__pos)))), )?; let default = match default { Some(default) => { quote! { ::std::option::Option::Some(|| -> #arg_ty { #default }) } } None => quote! { ::std::option::Option::None }, }; get_params.push(quote! { let (__pos, #arg_ident) = ctx.param_value::<#arg_ty>(#name, #default)?; #validators }); use_params.push(quote! { #arg_ident }); } let locations = directive_args .locations .iter() .map(|loc| { let loc = quote::format_ident!("{}", loc.to_string()); quote!(#crate_name::registry::__DirectiveLocation::#loc) }) .collect::<Vec<_>>(); if locations.is_empty() { return Err(Error::new( ident.span(), "At least one location is required for the directive.", ) .into()); } let expanded = quote! { #[allow(non_camel_case_types)] #vis struct #ident; #[#crate_name::async_trait::async_trait] impl #crate_name::CustomDirectiveFactory for #ident { fn name(&self) -> ::std::borrow::Cow<'static, ::std::primitive::str> { #directive_name } fn register(&self, registry: &mut #crate_name::registry::Registry) { let meta = #crate_name::registry::MetaDirective { name: ::std::borrow::Cow::into_owned(#directive_name), description: #desc, locations: vec![#(#locations),*], args: { #[allow(unused_mut)] let mut args = #crate_name::indexmap::IndexMap::new(); #(#schema_args)* args }, is_repeatable: #repeatable, visible: #visible, }; registry.add_directive(meta); } fn create( &self, ctx: &#crate_name::ContextDirective<'_>, directive: &#crate_name::parser::types::Directive, ) -> #crate_name::ServerResult<::std::boxed::Box<dyn #crate_name::CustomDirective>> { #item_fn #(#get_params)* Ok(::std::boxed::Box::new(#ident(#(#use_params),*))) } } }; Ok(expanded.into()) }
mod options; use std::convert::TryInto; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; use crate::runtime::process::monitor::is_down; use crate::runtime::registry::pid_to_process; use crate::erlang::demonitor_2::options::Options; #[native_implemented::function(erlang:demonitor/2)] pub fn result(process: &Process, reference: Term, options: Term) -> exception::Result<Term> { let reference_reference = term_try_into_local_reference!(reference)?; let options_options: Options = options.try_into()?; demonitor(process, &reference_reference, options_options) } // Private pub(in crate::erlang) fn demonitor( monitoring_process: &Process, reference: &Reference, Options { flush, info }: Options, ) -> exception::Result<Term> { match monitoring_process.demonitor(reference) { Some(monitored_pid) => { match pid_to_process(&monitored_pid) { Some(monitored_arc_proces) => match monitored_arc_proces.demonitored(reference) { Some(monitoring_pid) => assert_eq!(monitoring_process.pid(), monitoring_pid), None => (), }, None => (), } if flush { let flushed = self::flush(monitoring_process, reference); if info && flushed { Ok(false.into()) } else { Ok(true.into()) } } else { Ok(true.into()) } } None => { if info { Ok(false.into()) } else { Ok(true.into()) } } } } fn flush(monitoring_process: &Process, reference: &Reference) -> bool { monitoring_process .mailbox .lock() .borrow_mut() .flush(|message| is_down(message, reference)) }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::SSCTL2 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_D0R { bits: bool, } impl ADC_SSCTL2_D0R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_D0W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_D0W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_END0R { bits: bool, } impl ADC_SSCTL2_END0R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_END0W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_END0W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_IE0R { bits: bool, } impl ADC_SSCTL2_IE0R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_IE0W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_IE0W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_TS0R { bits: bool, } impl ADC_SSCTL2_TS0R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_TS0W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_TS0W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_D1R { bits: bool, } impl ADC_SSCTL2_D1R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_D1W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_D1W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_END1R { bits: bool, } impl ADC_SSCTL2_END1R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_END1W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_END1W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_IE1R { bits: bool, } impl ADC_SSCTL2_IE1R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_IE1W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_IE1W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 6); self.w.bits |= ((value as u32) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_TS1R { bits: bool, } impl ADC_SSCTL2_TS1R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_TS1W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_TS1W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 7); self.w.bits |= ((value as u32) & 1) << 7; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_D2R { bits: bool, } impl ADC_SSCTL2_D2R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_D2W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_D2W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 8); self.w.bits |= ((value as u32) & 1) << 8; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_END2R { bits: bool, } impl ADC_SSCTL2_END2R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_END2W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_END2W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 9); self.w.bits |= ((value as u32) & 1) << 9; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_IE2R { bits: bool, } impl ADC_SSCTL2_IE2R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_IE2W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_IE2W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 10); self.w.bits |= ((value as u32) & 1) << 10; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_TS2R { bits: bool, } impl ADC_SSCTL2_TS2R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_TS2W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_TS2W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 11); self.w.bits |= ((value as u32) & 1) << 11; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_D3R { bits: bool, } impl ADC_SSCTL2_D3R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_D3W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_D3W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 12); self.w.bits |= ((value as u32) & 1) << 12; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_END3R { bits: bool, } impl ADC_SSCTL2_END3R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_END3W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_END3W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 13); self.w.bits |= ((value as u32) & 1) << 13; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_IE3R { bits: bool, } impl ADC_SSCTL2_IE3R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_IE3W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_IE3W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 14); self.w.bits |= ((value as u32) & 1) << 14; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSCTL2_TS3R { bits: bool, } impl ADC_SSCTL2_TS3R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSCTL2_TS3W<'a> { w: &'a mut W, } impl<'a> _ADC_SSCTL2_TS3W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 15); self.w.bits |= ((value as u32) & 1) << 15; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - 1st Sample Differential Input Select"] #[inline(always)] pub fn adc_ssctl2_d0(&self) -> ADC_SSCTL2_D0R { let bits = ((self.bits >> 0) & 1) != 0; ADC_SSCTL2_D0R { bits } } #[doc = "Bit 1 - 1st Sample is End of Sequence"] #[inline(always)] pub fn adc_ssctl2_end0(&self) -> ADC_SSCTL2_END0R { let bits = ((self.bits >> 1) & 1) != 0; ADC_SSCTL2_END0R { bits } } #[doc = "Bit 2 - 1st Sample Interrupt Enable"] #[inline(always)] pub fn adc_ssctl2_ie0(&self) -> ADC_SSCTL2_IE0R { let bits = ((self.bits >> 2) & 1) != 0; ADC_SSCTL2_IE0R { bits } } #[doc = "Bit 3 - 1st Sample Temp Sensor Select"] #[inline(always)] pub fn adc_ssctl2_ts0(&self) -> ADC_SSCTL2_TS0R { let bits = ((self.bits >> 3) & 1) != 0; ADC_SSCTL2_TS0R { bits } } #[doc = "Bit 4 - 2nd Sample Differential Input Select"] #[inline(always)] pub fn adc_ssctl2_d1(&self) -> ADC_SSCTL2_D1R { let bits = ((self.bits >> 4) & 1) != 0; ADC_SSCTL2_D1R { bits } } #[doc = "Bit 5 - 2nd Sample is End of Sequence"] #[inline(always)] pub fn adc_ssctl2_end1(&self) -> ADC_SSCTL2_END1R { let bits = ((self.bits >> 5) & 1) != 0; ADC_SSCTL2_END1R { bits } } #[doc = "Bit 6 - 2nd Sample Interrupt Enable"] #[inline(always)] pub fn adc_ssctl2_ie1(&self) -> ADC_SSCTL2_IE1R { let bits = ((self.bits >> 6) & 1) != 0; ADC_SSCTL2_IE1R { bits } } #[doc = "Bit 7 - 2nd Sample Temp Sensor Select"] #[inline(always)] pub fn adc_ssctl2_ts1(&self) -> ADC_SSCTL2_TS1R { let bits = ((self.bits >> 7) & 1) != 0; ADC_SSCTL2_TS1R { bits } } #[doc = "Bit 8 - 3rd Sample Differential Input Select"] #[inline(always)] pub fn adc_ssctl2_d2(&self) -> ADC_SSCTL2_D2R { let bits = ((self.bits >> 8) & 1) != 0; ADC_SSCTL2_D2R { bits } } #[doc = "Bit 9 - 3rd Sample is End of Sequence"] #[inline(always)] pub fn adc_ssctl2_end2(&self) -> ADC_SSCTL2_END2R { let bits = ((self.bits >> 9) & 1) != 0; ADC_SSCTL2_END2R { bits } } #[doc = "Bit 10 - 3rd Sample Interrupt Enable"] #[inline(always)] pub fn adc_ssctl2_ie2(&self) -> ADC_SSCTL2_IE2R { let bits = ((self.bits >> 10) & 1) != 0; ADC_SSCTL2_IE2R { bits } } #[doc = "Bit 11 - 3rd Sample Temp Sensor Select"] #[inline(always)] pub fn adc_ssctl2_ts2(&self) -> ADC_SSCTL2_TS2R { let bits = ((self.bits >> 11) & 1) != 0; ADC_SSCTL2_TS2R { bits } } #[doc = "Bit 12 - 4th Sample Differential Input Select"] #[inline(always)] pub fn adc_ssctl2_d3(&self) -> ADC_SSCTL2_D3R { let bits = ((self.bits >> 12) & 1) != 0; ADC_SSCTL2_D3R { bits } } #[doc = "Bit 13 - 4th Sample is End of Sequence"] #[inline(always)] pub fn adc_ssctl2_end3(&self) -> ADC_SSCTL2_END3R { let bits = ((self.bits >> 13) & 1) != 0; ADC_SSCTL2_END3R { bits } } #[doc = "Bit 14 - 4th Sample Interrupt Enable"] #[inline(always)] pub fn adc_ssctl2_ie3(&self) -> ADC_SSCTL2_IE3R { let bits = ((self.bits >> 14) & 1) != 0; ADC_SSCTL2_IE3R { bits } } #[doc = "Bit 15 - 4th Sample Temp Sensor Select"] #[inline(always)] pub fn adc_ssctl2_ts3(&self) -> ADC_SSCTL2_TS3R { let bits = ((self.bits >> 15) & 1) != 0; ADC_SSCTL2_TS3R { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - 1st Sample Differential Input Select"] #[inline(always)] pub fn adc_ssctl2_d0(&mut self) -> _ADC_SSCTL2_D0W { _ADC_SSCTL2_D0W { w: self } } #[doc = "Bit 1 - 1st Sample is End of Sequence"] #[inline(always)] pub fn adc_ssctl2_end0(&mut self) -> _ADC_SSCTL2_END0W { _ADC_SSCTL2_END0W { w: self } } #[doc = "Bit 2 - 1st Sample Interrupt Enable"] #[inline(always)] pub fn adc_ssctl2_ie0(&mut self) -> _ADC_SSCTL2_IE0W { _ADC_SSCTL2_IE0W { w: self } } #[doc = "Bit 3 - 1st Sample Temp Sensor Select"] #[inline(always)] pub fn adc_ssctl2_ts0(&mut self) -> _ADC_SSCTL2_TS0W { _ADC_SSCTL2_TS0W { w: self } } #[doc = "Bit 4 - 2nd Sample Differential Input Select"] #[inline(always)] pub fn adc_ssctl2_d1(&mut self) -> _ADC_SSCTL2_D1W { _ADC_SSCTL2_D1W { w: self } } #[doc = "Bit 5 - 2nd Sample is End of Sequence"] #[inline(always)] pub fn adc_ssctl2_end1(&mut self) -> _ADC_SSCTL2_END1W { _ADC_SSCTL2_END1W { w: self } } #[doc = "Bit 6 - 2nd Sample Interrupt Enable"] #[inline(always)] pub fn adc_ssctl2_ie1(&mut self) -> _ADC_SSCTL2_IE1W { _ADC_SSCTL2_IE1W { w: self } } #[doc = "Bit 7 - 2nd Sample Temp Sensor Select"] #[inline(always)] pub fn adc_ssctl2_ts1(&mut self) -> _ADC_SSCTL2_TS1W { _ADC_SSCTL2_TS1W { w: self } } #[doc = "Bit 8 - 3rd Sample Differential Input Select"] #[inline(always)] pub fn adc_ssctl2_d2(&mut self) -> _ADC_SSCTL2_D2W { _ADC_SSCTL2_D2W { w: self } } #[doc = "Bit 9 - 3rd Sample is End of Sequence"] #[inline(always)] pub fn adc_ssctl2_end2(&mut self) -> _ADC_SSCTL2_END2W { _ADC_SSCTL2_END2W { w: self } } #[doc = "Bit 10 - 3rd Sample Interrupt Enable"] #[inline(always)] pub fn adc_ssctl2_ie2(&mut self) -> _ADC_SSCTL2_IE2W { _ADC_SSCTL2_IE2W { w: self } } #[doc = "Bit 11 - 3rd Sample Temp Sensor Select"] #[inline(always)] pub fn adc_ssctl2_ts2(&mut self) -> _ADC_SSCTL2_TS2W { _ADC_SSCTL2_TS2W { w: self } } #[doc = "Bit 12 - 4th Sample Differential Input Select"] #[inline(always)] pub fn adc_ssctl2_d3(&mut self) -> _ADC_SSCTL2_D3W { _ADC_SSCTL2_D3W { w: self } } #[doc = "Bit 13 - 4th Sample is End of Sequence"] #[inline(always)] pub fn adc_ssctl2_end3(&mut self) -> _ADC_SSCTL2_END3W { _ADC_SSCTL2_END3W { w: self } } #[doc = "Bit 14 - 4th Sample Interrupt Enable"] #[inline(always)] pub fn adc_ssctl2_ie3(&mut self) -> _ADC_SSCTL2_IE3W { _ADC_SSCTL2_IE3W { w: self } } #[doc = "Bit 15 - 4th Sample Temp Sensor Select"] #[inline(always)] pub fn adc_ssctl2_ts3(&mut self) -> _ADC_SSCTL2_TS3W { _ADC_SSCTL2_TS3W { w: self } } }
#[doc = "Reader of register TTMLM"] pub type R = crate::R<u32, super::TTMLM>; #[doc = "Writer for register TTMLM"] pub type W = crate::W<u32, super::TTMLM>; #[doc = "Register TTMLM `reset()`'s with value 0"] impl crate::ResetValue for super::TTMLM { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `CCM`"] pub type CCM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CCM`"] pub struct CCM_W<'a> { w: &'a mut W, } impl<'a> CCM_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 & !0x3f) | ((value as u32) & 0x3f); self.w } } #[doc = "Reader of field `CSS`"] pub type CSS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CSS`"] pub struct CSS_W<'a> { w: &'a mut W, } impl<'a> CSS_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 & !(0x03 << 6)) | (((value as u32) & 0x03) << 6); self.w } } #[doc = "Reader of field `TXEW`"] pub type TXEW_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TXEW`"] pub struct TXEW_W<'a> { w: &'a mut W, } impl<'a> TXEW_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 & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `ENTT`"] pub type ENTT_R = crate::R<u16, u16>; #[doc = "Write proxy for field `ENTT`"] pub struct ENTT_W<'a> { w: &'a mut W, } impl<'a> ENTT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0fff << 16)) | (((value as u32) & 0x0fff) << 16); self.w } } impl R { #[doc = "Bits 0:5 - Cycle Count Max"] #[inline(always)] pub fn ccm(&self) -> CCM_R { CCM_R::new((self.bits & 0x3f) as u8) } #[doc = "Bits 6:7 - Cycle Start Synchronization"] #[inline(always)] pub fn css(&self) -> CSS_R { CSS_R::new(((self.bits >> 6) & 0x03) as u8) } #[doc = "Bits 8:11 - Tx Enable Window"] #[inline(always)] pub fn txew(&self) -> TXEW_R { TXEW_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 16:27 - Expected Number of Tx Triggers"] #[inline(always)] pub fn entt(&self) -> ENTT_R { ENTT_R::new(((self.bits >> 16) & 0x0fff) as u16) } } impl W { #[doc = "Bits 0:5 - Cycle Count Max"] #[inline(always)] pub fn ccm(&mut self) -> CCM_W { CCM_W { w: self } } #[doc = "Bits 6:7 - Cycle Start Synchronization"] #[inline(always)] pub fn css(&mut self) -> CSS_W { CSS_W { w: self } } #[doc = "Bits 8:11 - Tx Enable Window"] #[inline(always)] pub fn txew(&mut self) -> TXEW_W { TXEW_W { w: self } } #[doc = "Bits 16:27 - Expected Number of Tx Triggers"] #[inline(always)] pub fn entt(&mut self) -> ENTT_W { ENTT_W { w: self } } }
//! Types implementing the [Serializer] trait. //! //! There are currently three implementations: //! //! * SerdeSerializer uses the `serde` and `serde_json` crate to serialize //! the test inputs (of arbitrary Serializable type) to a `.json` file. //! //! * [ByteSerializer] encodes and decodes values of type `Vec<u8>` by simply //! copy/pasting the bytes from/to the files. The extension is customizable. //! //! * [StringSerializer] encodes and decodes values of any type implementing //! `FromStr` and `ToString` into utf-8 encoded text files. #[cfg(feature = "serde_ron_serializer")] mod serde_ron_serializer; #[cfg(feature = "serde_json_serializer")] mod serde_serializer; use std::marker::PhantomData; use std::str::FromStr; #[cfg(feature = "serde_ron_serializer")] pub use serde_ron_serializer::SerdeRonSerializer; #[cfg(feature = "serde_json_serializer")] pub use serde_serializer::SerdeSerializer; use crate::Serializer; /** A Serializer for `Vec<u8>` that simply copies the bytes from/to the files. */ pub struct ByteSerializer { ext: &'static str, } impl ByteSerializer { /// Create a byte serializer. The only argument is the name of the extension /// that the created files should have. For example: /// ``` /// use fuzzcheck::ByteSerializer; /// /// let ser = ByteSerializer::new("png"); /// ```` #[no_coverage] pub fn new(ext: &'static str) -> Self { Self { ext } } } impl crate::traits::Serializer for ByteSerializer { type Value = Vec<u8>; #[no_coverage] fn extension(&self) -> &str { self.ext } #[no_coverage] fn from_data(&self, data: &[u8]) -> Option<Self::Value> { Some(data.into()) } #[no_coverage] fn to_data(&self, value: &Self::Value) -> Vec<u8> { value.clone() } } /** A serializer that encodes and decodes values of any type implementing `FromStr` and `ToString` into utf-8 encoded text files. */ pub struct StringSerializer<StringType> where StringType: ToString + FromStr, { pub extension: &'static str, _phantom: PhantomData<StringType>, } impl<StringType> StringSerializer<StringType> where StringType: ToString + FromStr, { /// Create a string serializer. The only argument is the name of the extension /// that the created files should have. For example: /// ``` /// use fuzzcheck::StringSerializer; /// /// let ser = StringSerializer::<String>::new("txt"); /// ```` #[no_coverage] pub fn new(extension: &'static str) -> Self { Self { extension, _phantom: PhantomData, } } } impl<StringType> Serializer for StringSerializer<StringType> where StringType: ToString + FromStr, { type Value = StringType; #[no_coverage] fn extension(&self) -> &str { self.extension } #[no_coverage] fn from_data(&self, data: &[u8]) -> Option<Self::Value> { let string = String::from_utf8(data.to_vec()).ok()?; let value = Self::Value::from_str(&string).ok()?; Some(value) } #[no_coverage] fn to_data(&self, value: &Self::Value) -> Vec<u8> { value.to_string().into_bytes() } }
// Copyright 2023 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. // The servers module used for external communication with user, such as MySQL wired protocol, etc. mod query; mod service; mod session; use std::pin::Pin; use std::sync::Arc; use arrow_flight::FlightData; use common_sql::plans::Plan; use common_sql::PlanExtras; use dashmap::DashMap; use futures::Stream; use tonic::Status; use uuid::Uuid; use crate::sessions::Session; #[macro_export] macro_rules! status { ($desc:expr, $err:expr) => {{ let msg = format!("{}: {} at {}:{}", $desc, $err, file!(), line!()); tracing::error!(msg); Status::internal(msg) }}; } pub(crate) use status; type DoGetStream = Pin<Box<dyn Stream<Item = Result<FlightData, Status>> + Send + 'static>>; #[derive(Clone)] pub struct FlightSqlServiceImpl { sessions: Arc<DashMap<String, Arc<Session>>>, statements: Arc<DashMap<Uuid, (Plan, PlanExtras)>>, } /// in current official JDBC driver, Statement is based on PreparedStatement too, so we impl it first. impl FlightSqlServiceImpl { pub fn create() -> Self { FlightSqlServiceImpl { sessions: Arc::new(Default::default()), statements: Arc::new(Default::default()), } } }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qlineedit.h // dst-file: /src/widgets/qlineedit.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::qstring::*; // 771 use super::super::core::qcoreevent::*; // 771 use super::qmenu::*; // 773 use super::super::core::qmargins::*; // 771 use super::super::core::qpoint::*; // 771 use super::super::core::qsize::*; // 771 use super::super::gui::qvalidator::*; // 771 use super::qaction::*; // 773 use super::super::core::qobjectdefs::*; // 771 use super::qcompleter::*; // 773 use super::super::gui::qicon::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QLineEdit_Class_Size() -> c_int; // proto: void QLineEdit::cursorBackward(bool mark, int steps); fn C_ZN9QLineEdit14cursorBackwardEbi(qthis: u64 /* *mut c_void*/, arg0: c_char, arg1: c_int); // proto: void QLineEdit::home(bool mark); fn C_ZN9QLineEdit4homeEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: int QLineEdit::selectionStart(); fn C_ZNK9QLineEdit14selectionStartEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QLineEdit::setCursorPosition(int ); fn C_ZN9QLineEdit17setCursorPositionEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: bool QLineEdit::isRedoAvailable(); fn C_ZNK9QLineEdit15isRedoAvailableEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QLineEdit::setModified(bool ); fn C_ZN9QLineEdit11setModifiedEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: void QLineEdit::QLineEdit(const QString & , QWidget * parent); fn C_ZN9QLineEditC2ERK7QStringP7QWidget(arg0: *mut c_void, arg1: *mut c_void) -> u64; // proto: bool QLineEdit::event(QEvent * ); fn C_ZN9QLineEdit5eventEP6QEvent(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; // proto: int QLineEdit::maxLength(); fn C_ZNK9QLineEdit9maxLengthEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: QMenu * QLineEdit::createStandardContextMenu(); fn C_ZN9QLineEdit25createStandardContextMenuEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QLineEdit::setTextMargins(const QMargins & margins); fn C_ZN9QLineEdit14setTextMarginsERK8QMargins(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: int QLineEdit::cursorPositionAt(const QPoint & pos); fn C_ZN9QLineEdit16cursorPositionAtERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_int; // proto: bool QLineEdit::hasSelectedText(); fn C_ZNK9QLineEdit15hasSelectedTextEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QLineEdit::setPlaceholderText(const QString & ); fn C_ZN9QLineEdit18setPlaceholderTextERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QSize QLineEdit::minimumSizeHint(); fn C_ZNK9QLineEdit15minimumSizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QLineEdit::cursorForward(bool mark, int steps); fn C_ZN9QLineEdit13cursorForwardEbi(qthis: u64 /* *mut c_void*/, arg0: c_char, arg1: c_int); // proto: void QLineEdit::insert(const QString & ); fn C_ZN9QLineEdit6insertERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QLineEdit::setText(const QString & ); fn C_ZN9QLineEdit7setTextERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: const QValidator * QLineEdit::validator(); fn C_ZNK9QLineEdit9validatorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QLineEdit::deselect(); fn C_ZN9QLineEdit8deselectEv(qthis: u64 /* *mut c_void*/); // proto: QString QLineEdit::inputMask(); fn C_ZNK9QLineEdit9inputMaskEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QString QLineEdit::placeholderText(); fn C_ZNK9QLineEdit15placeholderTextEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QLineEdit::cut(); fn C_ZN9QLineEdit3cutEv(qthis: u64 /* *mut c_void*/); // proto: QString QLineEdit::text(); fn C_ZNK9QLineEdit4textEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: const QMetaObject * QLineEdit::metaObject(); fn C_ZNK9QLineEdit10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QLineEdit::del(); fn C_ZN9QLineEdit3delEv(qthis: u64 /* *mut c_void*/); // proto: bool QLineEdit::isModified(); fn C_ZNK9QLineEdit10isModifiedEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QLineEdit::cursorWordForward(bool mark); fn C_ZN9QLineEdit17cursorWordForwardEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: void QLineEdit::selectAll(); fn C_ZN9QLineEdit9selectAllEv(qthis: u64 /* *mut c_void*/); // proto: void QLineEdit::setSelection(int , int ); fn C_ZN9QLineEdit12setSelectionEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int); // proto: void QLineEdit::setCompleter(QCompleter * completer); fn C_ZN9QLineEdit12setCompleterEP10QCompleter(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QLineEdit::setMaxLength(int ); fn C_ZN9QLineEdit12setMaxLengthEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: void QLineEdit::~QLineEdit(); fn C_ZN9QLineEditD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QLineEdit::setReadOnly(bool ); fn C_ZN9QLineEdit11setReadOnlyEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: QString QLineEdit::displayText(); fn C_ZNK9QLineEdit11displayTextEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QLineEdit::setFrame(bool ); fn C_ZN9QLineEdit8setFrameEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: bool QLineEdit::hasAcceptableInput(); fn C_ZNK9QLineEdit18hasAcceptableInputEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: bool QLineEdit::hasFrame(); fn C_ZNK9QLineEdit8hasFrameEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: int QLineEdit::cursorPosition(); fn C_ZNK9QLineEdit14cursorPositionEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QLineEdit::cursorWordBackward(bool mark); fn C_ZN9QLineEdit18cursorWordBackwardEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: bool QLineEdit::dragEnabled(); fn C_ZNK9QLineEdit11dragEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QSize QLineEdit::sizeHint(); fn C_ZNK9QLineEdit8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QLineEdit::paste(); fn C_ZN9QLineEdit5pasteEv(qthis: u64 /* *mut c_void*/); // proto: void QLineEdit::setValidator(const QValidator * ); fn C_ZN9QLineEdit12setValidatorEPK10QValidator(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QLineEdit::QLineEdit(QWidget * parent); fn C_ZN9QLineEditC2EP7QWidget(arg0: *mut c_void) -> u64; // proto: QCompleter * QLineEdit::completer(); fn C_ZNK9QLineEdit9completerEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QMargins QLineEdit::textMargins(); fn C_ZNK9QLineEdit11textMarginsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QLineEdit::setClearButtonEnabled(bool enable); fn C_ZN9QLineEdit21setClearButtonEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: QString QLineEdit::selectedText(); fn C_ZNK9QLineEdit12selectedTextEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QLineEdit::clear(); fn C_ZN9QLineEdit5clearEv(qthis: u64 /* *mut c_void*/); // proto: void QLineEdit::copy(); fn C_ZNK9QLineEdit4copyEv(qthis: u64 /* *mut c_void*/); // proto: bool QLineEdit::isUndoAvailable(); fn C_ZNK9QLineEdit15isUndoAvailableEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QLineEdit::undo(); fn C_ZN9QLineEdit4undoEv(qthis: u64 /* *mut c_void*/); // proto: bool QLineEdit::isClearButtonEnabled(); fn C_ZNK9QLineEdit20isClearButtonEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QLineEdit::end(bool mark); fn C_ZN9QLineEdit3endEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: void QLineEdit::setDragEnabled(bool b); fn C_ZN9QLineEdit14setDragEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: void QLineEdit::backspace(); fn C_ZN9QLineEdit9backspaceEv(qthis: u64 /* *mut c_void*/); // proto: void QLineEdit::redo(); fn C_ZN9QLineEdit4redoEv(qthis: u64 /* *mut c_void*/); // proto: void QLineEdit::setTextMargins(int left, int top, int right, int bottom); fn C_ZN9QLineEdit14setTextMarginsEiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int); // proto: void QLineEdit::setInputMask(const QString & inputMask); fn C_ZN9QLineEdit12setInputMaskERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QLineEdit::getTextMargins(int * left, int * top, int * right, int * bottom); fn C_ZNK9QLineEdit14getTextMarginsEPiS0_S0_S0_(qthis: u64 /* *mut c_void*/, arg0: *mut c_int, arg1: *mut c_int, arg2: *mut c_int, arg3: *mut c_int); // proto: bool QLineEdit::isReadOnly(); fn C_ZNK9QLineEdit10isReadOnlyEv(qthis: u64 /* *mut c_void*/) -> c_char; fn QLineEdit_SlotProxy_connect__ZN9QLineEdit11textChangedERK7QString(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QLineEdit_SlotProxy_connect__ZN9QLineEdit15editingFinishedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QLineEdit_SlotProxy_connect__ZN9QLineEdit16selectionChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QLineEdit_SlotProxy_connect__ZN9QLineEdit21cursorPositionChangedEii(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QLineEdit_SlotProxy_connect__ZN9QLineEdit13returnPressedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QLineEdit_SlotProxy_connect__ZN9QLineEdit10textEditedERK7QString(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QLineEdit)=1 #[derive(Default)] pub struct QLineEdit { qbase: QWidget, pub qclsinst: u64 /* *mut c_void*/, pub _textEdited: QLineEdit_textEdited_signal, pub _returnPressed: QLineEdit_returnPressed_signal, pub _selectionChanged: QLineEdit_selectionChanged_signal, pub _cursorPositionChanged: QLineEdit_cursorPositionChanged_signal, pub _editingFinished: QLineEdit_editingFinished_signal, pub _textChanged: QLineEdit_textChanged_signal, } impl /*struct*/ QLineEdit { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QLineEdit { return QLineEdit{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QLineEdit { type Target = QWidget; fn deref(&self) -> &QWidget { return & self.qbase; } } impl AsRef<QWidget> for QLineEdit { fn as_ref(& self) -> & QWidget { return & self.qbase; } } // proto: void QLineEdit::cursorBackward(bool mark, int steps); impl /*struct*/ QLineEdit { pub fn cursorBackward<RetType, T: QLineEdit_cursorBackward<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cursorBackward(self); // return 1; } } pub trait QLineEdit_cursorBackward<RetType> { fn cursorBackward(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::cursorBackward(bool mark, int steps); impl<'a> /*trait*/ QLineEdit_cursorBackward<()> for (i8, Option<i32>) { fn cursorBackward(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit14cursorBackwardEbi()}; let arg0 = self.0 as c_char; let arg1 = (if self.1.is_none() {1} else {self.1.unwrap()}) as c_int; unsafe {C_ZN9QLineEdit14cursorBackwardEbi(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QLineEdit::home(bool mark); impl /*struct*/ QLineEdit { pub fn home<RetType, T: QLineEdit_home<RetType>>(& self, overload_args: T) -> RetType { return overload_args.home(self); // return 1; } } pub trait QLineEdit_home<RetType> { fn home(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::home(bool mark); impl<'a> /*trait*/ QLineEdit_home<()> for (i8) { fn home(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit4homeEb()}; let arg0 = self as c_char; unsafe {C_ZN9QLineEdit4homeEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: int QLineEdit::selectionStart(); impl /*struct*/ QLineEdit { pub fn selectionStart<RetType, T: QLineEdit_selectionStart<RetType>>(& self, overload_args: T) -> RetType { return overload_args.selectionStart(self); // return 1; } } pub trait QLineEdit_selectionStart<RetType> { fn selectionStart(self , rsthis: & QLineEdit) -> RetType; } // proto: int QLineEdit::selectionStart(); impl<'a> /*trait*/ QLineEdit_selectionStart<i32> for () { fn selectionStart(self , rsthis: & QLineEdit) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit14selectionStartEv()}; let mut ret = unsafe {C_ZNK9QLineEdit14selectionStartEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: void QLineEdit::setCursorPosition(int ); impl /*struct*/ QLineEdit { pub fn setCursorPosition<RetType, T: QLineEdit_setCursorPosition<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setCursorPosition(self); // return 1; } } pub trait QLineEdit_setCursorPosition<RetType> { fn setCursorPosition(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setCursorPosition(int ); impl<'a> /*trait*/ QLineEdit_setCursorPosition<()> for (i32) { fn setCursorPosition(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit17setCursorPositionEi()}; let arg0 = self as c_int; unsafe {C_ZN9QLineEdit17setCursorPositionEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QLineEdit::isRedoAvailable(); impl /*struct*/ QLineEdit { pub fn isRedoAvailable<RetType, T: QLineEdit_isRedoAvailable<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isRedoAvailable(self); // return 1; } } pub trait QLineEdit_isRedoAvailable<RetType> { fn isRedoAvailable(self , rsthis: & QLineEdit) -> RetType; } // proto: bool QLineEdit::isRedoAvailable(); impl<'a> /*trait*/ QLineEdit_isRedoAvailable<i8> for () { fn isRedoAvailable(self , rsthis: & QLineEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit15isRedoAvailableEv()}; let mut ret = unsafe {C_ZNK9QLineEdit15isRedoAvailableEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QLineEdit::setModified(bool ); impl /*struct*/ QLineEdit { pub fn setModified<RetType, T: QLineEdit_setModified<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setModified(self); // return 1; } } pub trait QLineEdit_setModified<RetType> { fn setModified(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setModified(bool ); impl<'a> /*trait*/ QLineEdit_setModified<()> for (i8) { fn setModified(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit11setModifiedEb()}; let arg0 = self as c_char; unsafe {C_ZN9QLineEdit11setModifiedEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QLineEdit::QLineEdit(const QString & , QWidget * parent); impl /*struct*/ QLineEdit { pub fn new<T: QLineEdit_new>(value: T) -> QLineEdit { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QLineEdit_new { fn new(self) -> QLineEdit; } // proto: void QLineEdit::QLineEdit(const QString & , QWidget * parent); impl<'a> /*trait*/ QLineEdit_new for (&'a QString, Option<&'a QWidget>) { fn new(self) -> QLineEdit { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEditC2ERK7QStringP7QWidget()}; let ctysz: c_int = unsafe{QLineEdit_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = (if self.1.is_none() {0} else {self.1.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN9QLineEditC2ERK7QStringP7QWidget(arg0, arg1)}; let rsthis = QLineEdit{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: bool QLineEdit::event(QEvent * ); impl /*struct*/ QLineEdit { pub fn event<RetType, T: QLineEdit_event<RetType>>(& self, overload_args: T) -> RetType { return overload_args.event(self); // return 1; } } pub trait QLineEdit_event<RetType> { fn event(self , rsthis: & QLineEdit) -> RetType; } // proto: bool QLineEdit::event(QEvent * ); impl<'a> /*trait*/ QLineEdit_event<i8> for (&'a QEvent) { fn event(self , rsthis: & QLineEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit5eventEP6QEvent()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN9QLineEdit5eventEP6QEvent(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // proto: int QLineEdit::maxLength(); impl /*struct*/ QLineEdit { pub fn maxLength<RetType, T: QLineEdit_maxLength<RetType>>(& self, overload_args: T) -> RetType { return overload_args.maxLength(self); // return 1; } } pub trait QLineEdit_maxLength<RetType> { fn maxLength(self , rsthis: & QLineEdit) -> RetType; } // proto: int QLineEdit::maxLength(); impl<'a> /*trait*/ QLineEdit_maxLength<i32> for () { fn maxLength(self , rsthis: & QLineEdit) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit9maxLengthEv()}; let mut ret = unsafe {C_ZNK9QLineEdit9maxLengthEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: QMenu * QLineEdit::createStandardContextMenu(); impl /*struct*/ QLineEdit { pub fn createStandardContextMenu<RetType, T: QLineEdit_createStandardContextMenu<RetType>>(& self, overload_args: T) -> RetType { return overload_args.createStandardContextMenu(self); // return 1; } } pub trait QLineEdit_createStandardContextMenu<RetType> { fn createStandardContextMenu(self , rsthis: & QLineEdit) -> RetType; } // proto: QMenu * QLineEdit::createStandardContextMenu(); impl<'a> /*trait*/ QLineEdit_createStandardContextMenu<QMenu> for () { fn createStandardContextMenu(self , rsthis: & QLineEdit) -> QMenu { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit25createStandardContextMenuEv()}; let mut ret = unsafe {C_ZN9QLineEdit25createStandardContextMenuEv(rsthis.qclsinst)}; let mut ret1 = QMenu::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QLineEdit::setTextMargins(const QMargins & margins); impl /*struct*/ QLineEdit { pub fn setTextMargins<RetType, T: QLineEdit_setTextMargins<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setTextMargins(self); // return 1; } } pub trait QLineEdit_setTextMargins<RetType> { fn setTextMargins(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setTextMargins(const QMargins & margins); impl<'a> /*trait*/ QLineEdit_setTextMargins<()> for (&'a QMargins) { fn setTextMargins(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit14setTextMarginsERK8QMargins()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QLineEdit14setTextMarginsERK8QMargins(rsthis.qclsinst, arg0)}; // return 1; } } // proto: int QLineEdit::cursorPositionAt(const QPoint & pos); impl /*struct*/ QLineEdit { pub fn cursorPositionAt<RetType, T: QLineEdit_cursorPositionAt<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cursorPositionAt(self); // return 1; } } pub trait QLineEdit_cursorPositionAt<RetType> { fn cursorPositionAt(self , rsthis: & QLineEdit) -> RetType; } // proto: int QLineEdit::cursorPositionAt(const QPoint & pos); impl<'a> /*trait*/ QLineEdit_cursorPositionAt<i32> for (&'a QPoint) { fn cursorPositionAt(self , rsthis: & QLineEdit) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit16cursorPositionAtERK6QPoint()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN9QLineEdit16cursorPositionAtERK6QPoint(rsthis.qclsinst, arg0)}; return ret as i32; // 1 // return 1; } } // proto: bool QLineEdit::hasSelectedText(); impl /*struct*/ QLineEdit { pub fn hasSelectedText<RetType, T: QLineEdit_hasSelectedText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.hasSelectedText(self); // return 1; } } pub trait QLineEdit_hasSelectedText<RetType> { fn hasSelectedText(self , rsthis: & QLineEdit) -> RetType; } // proto: bool QLineEdit::hasSelectedText(); impl<'a> /*trait*/ QLineEdit_hasSelectedText<i8> for () { fn hasSelectedText(self , rsthis: & QLineEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit15hasSelectedTextEv()}; let mut ret = unsafe {C_ZNK9QLineEdit15hasSelectedTextEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QLineEdit::setPlaceholderText(const QString & ); impl /*struct*/ QLineEdit { pub fn setPlaceholderText<RetType, T: QLineEdit_setPlaceholderText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setPlaceholderText(self); // return 1; } } pub trait QLineEdit_setPlaceholderText<RetType> { fn setPlaceholderText(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setPlaceholderText(const QString & ); impl<'a> /*trait*/ QLineEdit_setPlaceholderText<()> for (&'a QString) { fn setPlaceholderText(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit18setPlaceholderTextERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QLineEdit18setPlaceholderTextERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QSize QLineEdit::minimumSizeHint(); impl /*struct*/ QLineEdit { pub fn minimumSizeHint<RetType, T: QLineEdit_minimumSizeHint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.minimumSizeHint(self); // return 1; } } pub trait QLineEdit_minimumSizeHint<RetType> { fn minimumSizeHint(self , rsthis: & QLineEdit) -> RetType; } // proto: QSize QLineEdit::minimumSizeHint(); impl<'a> /*trait*/ QLineEdit_minimumSizeHint<QSize> for () { fn minimumSizeHint(self , rsthis: & QLineEdit) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit15minimumSizeHintEv()}; let mut ret = unsafe {C_ZNK9QLineEdit15minimumSizeHintEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QLineEdit::cursorForward(bool mark, int steps); impl /*struct*/ QLineEdit { pub fn cursorForward<RetType, T: QLineEdit_cursorForward<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cursorForward(self); // return 1; } } pub trait QLineEdit_cursorForward<RetType> { fn cursorForward(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::cursorForward(bool mark, int steps); impl<'a> /*trait*/ QLineEdit_cursorForward<()> for (i8, Option<i32>) { fn cursorForward(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit13cursorForwardEbi()}; let arg0 = self.0 as c_char; let arg1 = (if self.1.is_none() {1} else {self.1.unwrap()}) as c_int; unsafe {C_ZN9QLineEdit13cursorForwardEbi(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QLineEdit::insert(const QString & ); impl /*struct*/ QLineEdit { pub fn insert<RetType, T: QLineEdit_insert<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insert(self); // return 1; } } pub trait QLineEdit_insert<RetType> { fn insert(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::insert(const QString & ); impl<'a> /*trait*/ QLineEdit_insert<()> for (&'a QString) { fn insert(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit6insertERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QLineEdit6insertERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QLineEdit::setText(const QString & ); impl /*struct*/ QLineEdit { pub fn setText<RetType, T: QLineEdit_setText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setText(self); // return 1; } } pub trait QLineEdit_setText<RetType> { fn setText(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setText(const QString & ); impl<'a> /*trait*/ QLineEdit_setText<()> for (&'a QString) { fn setText(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit7setTextERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QLineEdit7setTextERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: const QValidator * QLineEdit::validator(); impl /*struct*/ QLineEdit { pub fn validator<RetType, T: QLineEdit_validator<RetType>>(& self, overload_args: T) -> RetType { return overload_args.validator(self); // return 1; } } pub trait QLineEdit_validator<RetType> { fn validator(self , rsthis: & QLineEdit) -> RetType; } // proto: const QValidator * QLineEdit::validator(); impl<'a> /*trait*/ QLineEdit_validator<QValidator> for () { fn validator(self , rsthis: & QLineEdit) -> QValidator { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit9validatorEv()}; let mut ret = unsafe {C_ZNK9QLineEdit9validatorEv(rsthis.qclsinst)}; let mut ret1 = QValidator::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QLineEdit::deselect(); impl /*struct*/ QLineEdit { pub fn deselect<RetType, T: QLineEdit_deselect<RetType>>(& self, overload_args: T) -> RetType { return overload_args.deselect(self); // return 1; } } pub trait QLineEdit_deselect<RetType> { fn deselect(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::deselect(); impl<'a> /*trait*/ QLineEdit_deselect<()> for () { fn deselect(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit8deselectEv()}; unsafe {C_ZN9QLineEdit8deselectEv(rsthis.qclsinst)}; // return 1; } } // proto: QString QLineEdit::inputMask(); impl /*struct*/ QLineEdit { pub fn inputMask<RetType, T: QLineEdit_inputMask<RetType>>(& self, overload_args: T) -> RetType { return overload_args.inputMask(self); // return 1; } } pub trait QLineEdit_inputMask<RetType> { fn inputMask(self , rsthis: & QLineEdit) -> RetType; } // proto: QString QLineEdit::inputMask(); impl<'a> /*trait*/ QLineEdit_inputMask<QString> for () { fn inputMask(self , rsthis: & QLineEdit) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit9inputMaskEv()}; let mut ret = unsafe {C_ZNK9QLineEdit9inputMaskEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QString QLineEdit::placeholderText(); impl /*struct*/ QLineEdit { pub fn placeholderText<RetType, T: QLineEdit_placeholderText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.placeholderText(self); // return 1; } } pub trait QLineEdit_placeholderText<RetType> { fn placeholderText(self , rsthis: & QLineEdit) -> RetType; } // proto: QString QLineEdit::placeholderText(); impl<'a> /*trait*/ QLineEdit_placeholderText<QString> for () { fn placeholderText(self , rsthis: & QLineEdit) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit15placeholderTextEv()}; let mut ret = unsafe {C_ZNK9QLineEdit15placeholderTextEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QLineEdit::cut(); impl /*struct*/ QLineEdit { pub fn cut<RetType, T: QLineEdit_cut<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cut(self); // return 1; } } pub trait QLineEdit_cut<RetType> { fn cut(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::cut(); impl<'a> /*trait*/ QLineEdit_cut<()> for () { fn cut(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit3cutEv()}; unsafe {C_ZN9QLineEdit3cutEv(rsthis.qclsinst)}; // return 1; } } // proto: QString QLineEdit::text(); impl /*struct*/ QLineEdit { pub fn text<RetType, T: QLineEdit_text<RetType>>(& self, overload_args: T) -> RetType { return overload_args.text(self); // return 1; } } pub trait QLineEdit_text<RetType> { fn text(self , rsthis: & QLineEdit) -> RetType; } // proto: QString QLineEdit::text(); impl<'a> /*trait*/ QLineEdit_text<QString> for () { fn text(self , rsthis: & QLineEdit) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit4textEv()}; let mut ret = unsafe {C_ZNK9QLineEdit4textEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: const QMetaObject * QLineEdit::metaObject(); impl /*struct*/ QLineEdit { pub fn metaObject<RetType, T: QLineEdit_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QLineEdit_metaObject<RetType> { fn metaObject(self , rsthis: & QLineEdit) -> RetType; } // proto: const QMetaObject * QLineEdit::metaObject(); impl<'a> /*trait*/ QLineEdit_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QLineEdit) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit10metaObjectEv()}; let mut ret = unsafe {C_ZNK9QLineEdit10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QLineEdit::del(); impl /*struct*/ QLineEdit { pub fn del<RetType, T: QLineEdit_del<RetType>>(& self, overload_args: T) -> RetType { return overload_args.del(self); // return 1; } } pub trait QLineEdit_del<RetType> { fn del(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::del(); impl<'a> /*trait*/ QLineEdit_del<()> for () { fn del(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit3delEv()}; unsafe {C_ZN9QLineEdit3delEv(rsthis.qclsinst)}; // return 1; } } // proto: bool QLineEdit::isModified(); impl /*struct*/ QLineEdit { pub fn isModified<RetType, T: QLineEdit_isModified<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isModified(self); // return 1; } } pub trait QLineEdit_isModified<RetType> { fn isModified(self , rsthis: & QLineEdit) -> RetType; } // proto: bool QLineEdit::isModified(); impl<'a> /*trait*/ QLineEdit_isModified<i8> for () { fn isModified(self , rsthis: & QLineEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit10isModifiedEv()}; let mut ret = unsafe {C_ZNK9QLineEdit10isModifiedEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QLineEdit::cursorWordForward(bool mark); impl /*struct*/ QLineEdit { pub fn cursorWordForward<RetType, T: QLineEdit_cursorWordForward<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cursorWordForward(self); // return 1; } } pub trait QLineEdit_cursorWordForward<RetType> { fn cursorWordForward(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::cursorWordForward(bool mark); impl<'a> /*trait*/ QLineEdit_cursorWordForward<()> for (i8) { fn cursorWordForward(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit17cursorWordForwardEb()}; let arg0 = self as c_char; unsafe {C_ZN9QLineEdit17cursorWordForwardEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QLineEdit::selectAll(); impl /*struct*/ QLineEdit { pub fn selectAll<RetType, T: QLineEdit_selectAll<RetType>>(& self, overload_args: T) -> RetType { return overload_args.selectAll(self); // return 1; } } pub trait QLineEdit_selectAll<RetType> { fn selectAll(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::selectAll(); impl<'a> /*trait*/ QLineEdit_selectAll<()> for () { fn selectAll(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit9selectAllEv()}; unsafe {C_ZN9QLineEdit9selectAllEv(rsthis.qclsinst)}; // return 1; } } // proto: void QLineEdit::setSelection(int , int ); impl /*struct*/ QLineEdit { pub fn setSelection<RetType, T: QLineEdit_setSelection<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setSelection(self); // return 1; } } pub trait QLineEdit_setSelection<RetType> { fn setSelection(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setSelection(int , int ); impl<'a> /*trait*/ QLineEdit_setSelection<()> for (i32, i32) { fn setSelection(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit12setSelectionEii()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; unsafe {C_ZN9QLineEdit12setSelectionEii(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QLineEdit::setCompleter(QCompleter * completer); impl /*struct*/ QLineEdit { pub fn setCompleter<RetType, T: QLineEdit_setCompleter<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setCompleter(self); // return 1; } } pub trait QLineEdit_setCompleter<RetType> { fn setCompleter(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setCompleter(QCompleter * completer); impl<'a> /*trait*/ QLineEdit_setCompleter<()> for (&'a QCompleter) { fn setCompleter(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit12setCompleterEP10QCompleter()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QLineEdit12setCompleterEP10QCompleter(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QLineEdit::setMaxLength(int ); impl /*struct*/ QLineEdit { pub fn setMaxLength<RetType, T: QLineEdit_setMaxLength<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setMaxLength(self); // return 1; } } pub trait QLineEdit_setMaxLength<RetType> { fn setMaxLength(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setMaxLength(int ); impl<'a> /*trait*/ QLineEdit_setMaxLength<()> for (i32) { fn setMaxLength(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit12setMaxLengthEi()}; let arg0 = self as c_int; unsafe {C_ZN9QLineEdit12setMaxLengthEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QLineEdit::~QLineEdit(); impl /*struct*/ QLineEdit { pub fn free<RetType, T: QLineEdit_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QLineEdit_free<RetType> { fn free(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::~QLineEdit(); impl<'a> /*trait*/ QLineEdit_free<()> for () { fn free(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEditD2Ev()}; unsafe {C_ZN9QLineEditD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QLineEdit::setReadOnly(bool ); impl /*struct*/ QLineEdit { pub fn setReadOnly<RetType, T: QLineEdit_setReadOnly<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setReadOnly(self); // return 1; } } pub trait QLineEdit_setReadOnly<RetType> { fn setReadOnly(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setReadOnly(bool ); impl<'a> /*trait*/ QLineEdit_setReadOnly<()> for (i8) { fn setReadOnly(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit11setReadOnlyEb()}; let arg0 = self as c_char; unsafe {C_ZN9QLineEdit11setReadOnlyEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QString QLineEdit::displayText(); impl /*struct*/ QLineEdit { pub fn displayText<RetType, T: QLineEdit_displayText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.displayText(self); // return 1; } } pub trait QLineEdit_displayText<RetType> { fn displayText(self , rsthis: & QLineEdit) -> RetType; } // proto: QString QLineEdit::displayText(); impl<'a> /*trait*/ QLineEdit_displayText<QString> for () { fn displayText(self , rsthis: & QLineEdit) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit11displayTextEv()}; let mut ret = unsafe {C_ZNK9QLineEdit11displayTextEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QLineEdit::setFrame(bool ); impl /*struct*/ QLineEdit { pub fn setFrame<RetType, T: QLineEdit_setFrame<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setFrame(self); // return 1; } } pub trait QLineEdit_setFrame<RetType> { fn setFrame(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setFrame(bool ); impl<'a> /*trait*/ QLineEdit_setFrame<()> for (i8) { fn setFrame(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit8setFrameEb()}; let arg0 = self as c_char; unsafe {C_ZN9QLineEdit8setFrameEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QLineEdit::hasAcceptableInput(); impl /*struct*/ QLineEdit { pub fn hasAcceptableInput<RetType, T: QLineEdit_hasAcceptableInput<RetType>>(& self, overload_args: T) -> RetType { return overload_args.hasAcceptableInput(self); // return 1; } } pub trait QLineEdit_hasAcceptableInput<RetType> { fn hasAcceptableInput(self , rsthis: & QLineEdit) -> RetType; } // proto: bool QLineEdit::hasAcceptableInput(); impl<'a> /*trait*/ QLineEdit_hasAcceptableInput<i8> for () { fn hasAcceptableInput(self , rsthis: & QLineEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit18hasAcceptableInputEv()}; let mut ret = unsafe {C_ZNK9QLineEdit18hasAcceptableInputEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: bool QLineEdit::hasFrame(); impl /*struct*/ QLineEdit { pub fn hasFrame<RetType, T: QLineEdit_hasFrame<RetType>>(& self, overload_args: T) -> RetType { return overload_args.hasFrame(self); // return 1; } } pub trait QLineEdit_hasFrame<RetType> { fn hasFrame(self , rsthis: & QLineEdit) -> RetType; } // proto: bool QLineEdit::hasFrame(); impl<'a> /*trait*/ QLineEdit_hasFrame<i8> for () { fn hasFrame(self , rsthis: & QLineEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit8hasFrameEv()}; let mut ret = unsafe {C_ZNK9QLineEdit8hasFrameEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: int QLineEdit::cursorPosition(); impl /*struct*/ QLineEdit { pub fn cursorPosition<RetType, T: QLineEdit_cursorPosition<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cursorPosition(self); // return 1; } } pub trait QLineEdit_cursorPosition<RetType> { fn cursorPosition(self , rsthis: & QLineEdit) -> RetType; } // proto: int QLineEdit::cursorPosition(); impl<'a> /*trait*/ QLineEdit_cursorPosition<i32> for () { fn cursorPosition(self , rsthis: & QLineEdit) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit14cursorPositionEv()}; let mut ret = unsafe {C_ZNK9QLineEdit14cursorPositionEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: void QLineEdit::cursorWordBackward(bool mark); impl /*struct*/ QLineEdit { pub fn cursorWordBackward<RetType, T: QLineEdit_cursorWordBackward<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cursorWordBackward(self); // return 1; } } pub trait QLineEdit_cursorWordBackward<RetType> { fn cursorWordBackward(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::cursorWordBackward(bool mark); impl<'a> /*trait*/ QLineEdit_cursorWordBackward<()> for (i8) { fn cursorWordBackward(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit18cursorWordBackwardEb()}; let arg0 = self as c_char; unsafe {C_ZN9QLineEdit18cursorWordBackwardEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QLineEdit::dragEnabled(); impl /*struct*/ QLineEdit { pub fn dragEnabled<RetType, T: QLineEdit_dragEnabled<RetType>>(& self, overload_args: T) -> RetType { return overload_args.dragEnabled(self); // return 1; } } pub trait QLineEdit_dragEnabled<RetType> { fn dragEnabled(self , rsthis: & QLineEdit) -> RetType; } // proto: bool QLineEdit::dragEnabled(); impl<'a> /*trait*/ QLineEdit_dragEnabled<i8> for () { fn dragEnabled(self , rsthis: & QLineEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit11dragEnabledEv()}; let mut ret = unsafe {C_ZNK9QLineEdit11dragEnabledEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QSize QLineEdit::sizeHint(); impl /*struct*/ QLineEdit { pub fn sizeHint<RetType, T: QLineEdit_sizeHint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.sizeHint(self); // return 1; } } pub trait QLineEdit_sizeHint<RetType> { fn sizeHint(self , rsthis: & QLineEdit) -> RetType; } // proto: QSize QLineEdit::sizeHint(); impl<'a> /*trait*/ QLineEdit_sizeHint<QSize> for () { fn sizeHint(self , rsthis: & QLineEdit) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit8sizeHintEv()}; let mut ret = unsafe {C_ZNK9QLineEdit8sizeHintEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QLineEdit::paste(); impl /*struct*/ QLineEdit { pub fn paste<RetType, T: QLineEdit_paste<RetType>>(& self, overload_args: T) -> RetType { return overload_args.paste(self); // return 1; } } pub trait QLineEdit_paste<RetType> { fn paste(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::paste(); impl<'a> /*trait*/ QLineEdit_paste<()> for () { fn paste(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit5pasteEv()}; unsafe {C_ZN9QLineEdit5pasteEv(rsthis.qclsinst)}; // return 1; } } // proto: void QLineEdit::setValidator(const QValidator * ); impl /*struct*/ QLineEdit { pub fn setValidator<RetType, T: QLineEdit_setValidator<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setValidator(self); // return 1; } } pub trait QLineEdit_setValidator<RetType> { fn setValidator(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setValidator(const QValidator * ); impl<'a> /*trait*/ QLineEdit_setValidator<()> for (&'a QValidator) { fn setValidator(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit12setValidatorEPK10QValidator()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QLineEdit12setValidatorEPK10QValidator(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QLineEdit::QLineEdit(QWidget * parent); impl<'a> /*trait*/ QLineEdit_new for (Option<&'a QWidget>) { fn new(self) -> QLineEdit { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEditC2EP7QWidget()}; let ctysz: c_int = unsafe{QLineEdit_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_ZN9QLineEditC2EP7QWidget(arg0)}; let rsthis = QLineEdit{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QCompleter * QLineEdit::completer(); impl /*struct*/ QLineEdit { pub fn completer<RetType, T: QLineEdit_completer<RetType>>(& self, overload_args: T) -> RetType { return overload_args.completer(self); // return 1; } } pub trait QLineEdit_completer<RetType> { fn completer(self , rsthis: & QLineEdit) -> RetType; } // proto: QCompleter * QLineEdit::completer(); impl<'a> /*trait*/ QLineEdit_completer<QCompleter> for () { fn completer(self , rsthis: & QLineEdit) -> QCompleter { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit9completerEv()}; let mut ret = unsafe {C_ZNK9QLineEdit9completerEv(rsthis.qclsinst)}; let mut ret1 = QCompleter::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QMargins QLineEdit::textMargins(); impl /*struct*/ QLineEdit { pub fn textMargins<RetType, T: QLineEdit_textMargins<RetType>>(& self, overload_args: T) -> RetType { return overload_args.textMargins(self); // return 1; } } pub trait QLineEdit_textMargins<RetType> { fn textMargins(self , rsthis: & QLineEdit) -> RetType; } // proto: QMargins QLineEdit::textMargins(); impl<'a> /*trait*/ QLineEdit_textMargins<QMargins> for () { fn textMargins(self , rsthis: & QLineEdit) -> QMargins { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit11textMarginsEv()}; let mut ret = unsafe {C_ZNK9QLineEdit11textMarginsEv(rsthis.qclsinst)}; let mut ret1 = QMargins::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QLineEdit::setClearButtonEnabled(bool enable); impl /*struct*/ QLineEdit { pub fn setClearButtonEnabled<RetType, T: QLineEdit_setClearButtonEnabled<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setClearButtonEnabled(self); // return 1; } } pub trait QLineEdit_setClearButtonEnabled<RetType> { fn setClearButtonEnabled(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setClearButtonEnabled(bool enable); impl<'a> /*trait*/ QLineEdit_setClearButtonEnabled<()> for (i8) { fn setClearButtonEnabled(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit21setClearButtonEnabledEb()}; let arg0 = self as c_char; unsafe {C_ZN9QLineEdit21setClearButtonEnabledEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QString QLineEdit::selectedText(); impl /*struct*/ QLineEdit { pub fn selectedText<RetType, T: QLineEdit_selectedText<RetType>>(& self, overload_args: T) -> RetType { return overload_args.selectedText(self); // return 1; } } pub trait QLineEdit_selectedText<RetType> { fn selectedText(self , rsthis: & QLineEdit) -> RetType; } // proto: QString QLineEdit::selectedText(); impl<'a> /*trait*/ QLineEdit_selectedText<QString> for () { fn selectedText(self , rsthis: & QLineEdit) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit12selectedTextEv()}; let mut ret = unsafe {C_ZNK9QLineEdit12selectedTextEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QLineEdit::clear(); impl /*struct*/ QLineEdit { pub fn clear<RetType, T: QLineEdit_clear<RetType>>(& self, overload_args: T) -> RetType { return overload_args.clear(self); // return 1; } } pub trait QLineEdit_clear<RetType> { fn clear(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::clear(); impl<'a> /*trait*/ QLineEdit_clear<()> for () { fn clear(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit5clearEv()}; unsafe {C_ZN9QLineEdit5clearEv(rsthis.qclsinst)}; // return 1; } } // proto: void QLineEdit::copy(); impl /*struct*/ QLineEdit { pub fn copy<RetType, T: QLineEdit_copy<RetType>>(& self, overload_args: T) -> RetType { return overload_args.copy(self); // return 1; } } pub trait QLineEdit_copy<RetType> { fn copy(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::copy(); impl<'a> /*trait*/ QLineEdit_copy<()> for () { fn copy(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit4copyEv()}; unsafe {C_ZNK9QLineEdit4copyEv(rsthis.qclsinst)}; // return 1; } } // proto: bool QLineEdit::isUndoAvailable(); impl /*struct*/ QLineEdit { pub fn isUndoAvailable<RetType, T: QLineEdit_isUndoAvailable<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isUndoAvailable(self); // return 1; } } pub trait QLineEdit_isUndoAvailable<RetType> { fn isUndoAvailable(self , rsthis: & QLineEdit) -> RetType; } // proto: bool QLineEdit::isUndoAvailable(); impl<'a> /*trait*/ QLineEdit_isUndoAvailable<i8> for () { fn isUndoAvailable(self , rsthis: & QLineEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit15isUndoAvailableEv()}; let mut ret = unsafe {C_ZNK9QLineEdit15isUndoAvailableEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QLineEdit::undo(); impl /*struct*/ QLineEdit { pub fn undo<RetType, T: QLineEdit_undo<RetType>>(& self, overload_args: T) -> RetType { return overload_args.undo(self); // return 1; } } pub trait QLineEdit_undo<RetType> { fn undo(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::undo(); impl<'a> /*trait*/ QLineEdit_undo<()> for () { fn undo(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit4undoEv()}; unsafe {C_ZN9QLineEdit4undoEv(rsthis.qclsinst)}; // return 1; } } // proto: bool QLineEdit::isClearButtonEnabled(); impl /*struct*/ QLineEdit { pub fn isClearButtonEnabled<RetType, T: QLineEdit_isClearButtonEnabled<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isClearButtonEnabled(self); // return 1; } } pub trait QLineEdit_isClearButtonEnabled<RetType> { fn isClearButtonEnabled(self , rsthis: & QLineEdit) -> RetType; } // proto: bool QLineEdit::isClearButtonEnabled(); impl<'a> /*trait*/ QLineEdit_isClearButtonEnabled<i8> for () { fn isClearButtonEnabled(self , rsthis: & QLineEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit20isClearButtonEnabledEv()}; let mut ret = unsafe {C_ZNK9QLineEdit20isClearButtonEnabledEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QLineEdit::end(bool mark); impl /*struct*/ QLineEdit { pub fn end<RetType, T: QLineEdit_end<RetType>>(& self, overload_args: T) -> RetType { return overload_args.end(self); // return 1; } } pub trait QLineEdit_end<RetType> { fn end(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::end(bool mark); impl<'a> /*trait*/ QLineEdit_end<()> for (i8) { fn end(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit3endEb()}; let arg0 = self as c_char; unsafe {C_ZN9QLineEdit3endEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QLineEdit::setDragEnabled(bool b); impl /*struct*/ QLineEdit { pub fn setDragEnabled<RetType, T: QLineEdit_setDragEnabled<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setDragEnabled(self); // return 1; } } pub trait QLineEdit_setDragEnabled<RetType> { fn setDragEnabled(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setDragEnabled(bool b); impl<'a> /*trait*/ QLineEdit_setDragEnabled<()> for (i8) { fn setDragEnabled(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit14setDragEnabledEb()}; let arg0 = self as c_char; unsafe {C_ZN9QLineEdit14setDragEnabledEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QLineEdit::backspace(); impl /*struct*/ QLineEdit { pub fn backspace<RetType, T: QLineEdit_backspace<RetType>>(& self, overload_args: T) -> RetType { return overload_args.backspace(self); // return 1; } } pub trait QLineEdit_backspace<RetType> { fn backspace(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::backspace(); impl<'a> /*trait*/ QLineEdit_backspace<()> for () { fn backspace(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit9backspaceEv()}; unsafe {C_ZN9QLineEdit9backspaceEv(rsthis.qclsinst)}; // return 1; } } // proto: void QLineEdit::redo(); impl /*struct*/ QLineEdit { pub fn redo<RetType, T: QLineEdit_redo<RetType>>(& self, overload_args: T) -> RetType { return overload_args.redo(self); // return 1; } } pub trait QLineEdit_redo<RetType> { fn redo(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::redo(); impl<'a> /*trait*/ QLineEdit_redo<()> for () { fn redo(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit4redoEv()}; unsafe {C_ZN9QLineEdit4redoEv(rsthis.qclsinst)}; // return 1; } } // proto: void QLineEdit::setTextMargins(int left, int top, int right, int bottom); impl<'a> /*trait*/ QLineEdit_setTextMargins<()> for (i32, i32, i32, i32) { fn setTextMargins(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit14setTextMarginsEiiii()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; let arg2 = self.2 as c_int; let arg3 = self.3 as c_int; unsafe {C_ZN9QLineEdit14setTextMarginsEiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; // return 1; } } // proto: void QLineEdit::setInputMask(const QString & inputMask); impl /*struct*/ QLineEdit { pub fn setInputMask<RetType, T: QLineEdit_setInputMask<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setInputMask(self); // return 1; } } pub trait QLineEdit_setInputMask<RetType> { fn setInputMask(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::setInputMask(const QString & inputMask); impl<'a> /*trait*/ QLineEdit_setInputMask<()> for (&'a QString) { fn setInputMask(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QLineEdit12setInputMaskERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QLineEdit12setInputMaskERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QLineEdit::getTextMargins(int * left, int * top, int * right, int * bottom); impl /*struct*/ QLineEdit { pub fn getTextMargins<RetType, T: QLineEdit_getTextMargins<RetType>>(& self, overload_args: T) -> RetType { return overload_args.getTextMargins(self); // return 1; } } pub trait QLineEdit_getTextMargins<RetType> { fn getTextMargins(self , rsthis: & QLineEdit) -> RetType; } // proto: void QLineEdit::getTextMargins(int * left, int * top, int * right, int * bottom); impl<'a> /*trait*/ QLineEdit_getTextMargins<()> for (&'a mut Vec<i32>, &'a mut Vec<i32>, &'a mut Vec<i32>, &'a mut Vec<i32>) { fn getTextMargins(self , rsthis: & QLineEdit) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit14getTextMarginsEPiS0_S0_S0_()}; let arg0 = self.0.as_ptr() as *mut c_int; let arg1 = self.1.as_ptr() as *mut c_int; let arg2 = self.2.as_ptr() as *mut c_int; let arg3 = self.3.as_ptr() as *mut c_int; unsafe {C_ZNK9QLineEdit14getTextMarginsEPiS0_S0_S0_(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; // return 1; } } // proto: bool QLineEdit::isReadOnly(); impl /*struct*/ QLineEdit { pub fn isReadOnly<RetType, T: QLineEdit_isReadOnly<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isReadOnly(self); // return 1; } } pub trait QLineEdit_isReadOnly<RetType> { fn isReadOnly(self , rsthis: & QLineEdit) -> RetType; } // proto: bool QLineEdit::isReadOnly(); impl<'a> /*trait*/ QLineEdit_isReadOnly<i8> for () { fn isReadOnly(self , rsthis: & QLineEdit) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QLineEdit10isReadOnlyEv()}; let mut ret = unsafe {C_ZNK9QLineEdit10isReadOnlyEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } #[derive(Default)] // for QLineEdit_textEdited pub struct QLineEdit_textEdited_signal{poi:u64} impl /* struct */ QLineEdit { pub fn textEdited(&self) -> QLineEdit_textEdited_signal { return QLineEdit_textEdited_signal{poi:self.qclsinst}; } } impl /* struct */ QLineEdit_textEdited_signal { pub fn connect<T: QLineEdit_textEdited_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QLineEdit_textEdited_signal_connect { fn connect(self, sigthis: QLineEdit_textEdited_signal); } #[derive(Default)] // for QLineEdit_returnPressed pub struct QLineEdit_returnPressed_signal{poi:u64} impl /* struct */ QLineEdit { pub fn returnPressed(&self) -> QLineEdit_returnPressed_signal { return QLineEdit_returnPressed_signal{poi:self.qclsinst}; } } impl /* struct */ QLineEdit_returnPressed_signal { pub fn connect<T: QLineEdit_returnPressed_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QLineEdit_returnPressed_signal_connect { fn connect(self, sigthis: QLineEdit_returnPressed_signal); } #[derive(Default)] // for QLineEdit_selectionChanged pub struct QLineEdit_selectionChanged_signal{poi:u64} impl /* struct */ QLineEdit { pub fn selectionChanged(&self) -> QLineEdit_selectionChanged_signal { return QLineEdit_selectionChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QLineEdit_selectionChanged_signal { pub fn connect<T: QLineEdit_selectionChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QLineEdit_selectionChanged_signal_connect { fn connect(self, sigthis: QLineEdit_selectionChanged_signal); } #[derive(Default)] // for QLineEdit_cursorPositionChanged pub struct QLineEdit_cursorPositionChanged_signal{poi:u64} impl /* struct */ QLineEdit { pub fn cursorPositionChanged(&self) -> QLineEdit_cursorPositionChanged_signal { return QLineEdit_cursorPositionChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QLineEdit_cursorPositionChanged_signal { pub fn connect<T: QLineEdit_cursorPositionChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QLineEdit_cursorPositionChanged_signal_connect { fn connect(self, sigthis: QLineEdit_cursorPositionChanged_signal); } #[derive(Default)] // for QLineEdit_editingFinished pub struct QLineEdit_editingFinished_signal{poi:u64} impl /* struct */ QLineEdit { pub fn editingFinished(&self) -> QLineEdit_editingFinished_signal { return QLineEdit_editingFinished_signal{poi:self.qclsinst}; } } impl /* struct */ QLineEdit_editingFinished_signal { pub fn connect<T: QLineEdit_editingFinished_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QLineEdit_editingFinished_signal_connect { fn connect(self, sigthis: QLineEdit_editingFinished_signal); } #[derive(Default)] // for QLineEdit_textChanged pub struct QLineEdit_textChanged_signal{poi:u64} impl /* struct */ QLineEdit { pub fn textChanged(&self) -> QLineEdit_textChanged_signal { return QLineEdit_textChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QLineEdit_textChanged_signal { pub fn connect<T: QLineEdit_textChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QLineEdit_textChanged_signal_connect { fn connect(self, sigthis: QLineEdit_textChanged_signal); } // textChanged(const class QString &) extern fn QLineEdit_textChanged_signal_connect_cb_0(rsfptr:fn(QString), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QString::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QLineEdit_textChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QString)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QString::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QLineEdit_textChanged_signal_connect for fn(QString) { fn connect(self, sigthis: QLineEdit_textChanged_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 = QLineEdit_textChanged_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QLineEdit_SlotProxy_connect__ZN9QLineEdit11textChangedERK7QString(arg0, arg1, arg2)}; } } impl /* trait */ QLineEdit_textChanged_signal_connect for Box<Fn(QString)> { fn connect(self, sigthis: QLineEdit_textChanged_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 = QLineEdit_textChanged_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QLineEdit_SlotProxy_connect__ZN9QLineEdit11textChangedERK7QString(arg0, arg1, arg2)}; } } // editingFinished() extern fn QLineEdit_editingFinished_signal_connect_cb_1(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QLineEdit_editingFinished_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 */ QLineEdit_editingFinished_signal_connect for fn() { fn connect(self, sigthis: QLineEdit_editingFinished_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 = QLineEdit_editingFinished_signal_connect_cb_1 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QLineEdit_SlotProxy_connect__ZN9QLineEdit15editingFinishedEv(arg0, arg1, arg2)}; } } impl /* trait */ QLineEdit_editingFinished_signal_connect for Box<Fn()> { fn connect(self, sigthis: QLineEdit_editingFinished_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 = QLineEdit_editingFinished_signal_connect_cb_box_1 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QLineEdit_SlotProxy_connect__ZN9QLineEdit15editingFinishedEv(arg0, arg1, arg2)}; } } // selectionChanged() extern fn QLineEdit_selectionChanged_signal_connect_cb_2(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QLineEdit_selectionChanged_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QLineEdit_selectionChanged_signal_connect for fn() { fn connect(self, sigthis: QLineEdit_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 = QLineEdit_selectionChanged_signal_connect_cb_2 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QLineEdit_SlotProxy_connect__ZN9QLineEdit16selectionChangedEv(arg0, arg1, arg2)}; } } impl /* trait */ QLineEdit_selectionChanged_signal_connect for Box<Fn()> { fn connect(self, sigthis: QLineEdit_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 = QLineEdit_selectionChanged_signal_connect_cb_box_2 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QLineEdit_SlotProxy_connect__ZN9QLineEdit16selectionChangedEv(arg0, arg1, arg2)}; } } // cursorPositionChanged(int, int) extern fn QLineEdit_cursorPositionChanged_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 QLineEdit_cursorPositionChanged_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 */ QLineEdit_cursorPositionChanged_signal_connect for fn(i32, i32) { fn connect(self, sigthis: QLineEdit_cursorPositionChanged_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 = QLineEdit_cursorPositionChanged_signal_connect_cb_3 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QLineEdit_SlotProxy_connect__ZN9QLineEdit21cursorPositionChangedEii(arg0, arg1, arg2)}; } } impl /* trait */ QLineEdit_cursorPositionChanged_signal_connect for Box<Fn(i32, i32)> { fn connect(self, sigthis: QLineEdit_cursorPositionChanged_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 = QLineEdit_cursorPositionChanged_signal_connect_cb_box_3 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QLineEdit_SlotProxy_connect__ZN9QLineEdit21cursorPositionChangedEii(arg0, arg1, arg2)}; } } // returnPressed() extern fn QLineEdit_returnPressed_signal_connect_cb_4(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QLineEdit_returnPressed_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QLineEdit_returnPressed_signal_connect for fn() { fn connect(self, sigthis: QLineEdit_returnPressed_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 = QLineEdit_returnPressed_signal_connect_cb_4 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QLineEdit_SlotProxy_connect__ZN9QLineEdit13returnPressedEv(arg0, arg1, arg2)}; } } impl /* trait */ QLineEdit_returnPressed_signal_connect for Box<Fn()> { fn connect(self, sigthis: QLineEdit_returnPressed_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 = QLineEdit_returnPressed_signal_connect_cb_box_4 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QLineEdit_SlotProxy_connect__ZN9QLineEdit13returnPressedEv(arg0, arg1, arg2)}; } } // textEdited(const class QString &) extern fn QLineEdit_textEdited_signal_connect_cb_5(rsfptr:fn(QString), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QString::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QLineEdit_textEdited_signal_connect_cb_box_5(rsfptr_raw:*mut Box<Fn(QString)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QString::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QLineEdit_textEdited_signal_connect for fn(QString) { fn connect(self, sigthis: QLineEdit_textEdited_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 = QLineEdit_textEdited_signal_connect_cb_5 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QLineEdit_SlotProxy_connect__ZN9QLineEdit10textEditedERK7QString(arg0, arg1, arg2)}; } } impl /* trait */ QLineEdit_textEdited_signal_connect for Box<Fn(QString)> { fn connect(self, sigthis: QLineEdit_textEdited_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 = QLineEdit_textEdited_signal_connect_cb_box_5 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QLineEdit_SlotProxy_connect__ZN9QLineEdit10textEditedERK7QString(arg0, arg1, arg2)}; } } // <= body block end
use nalgebra as na; use na::{ Vector3, Matrix3, Matrix3x1, Matrix1x3, Matrix1, VectorN, MatrixN, }; use na::{DefaultAllocator, DimName, RealField}; use na::allocator::Allocator; use super::Timestamp; use crate::dwt_utils::{ dwt_ticks_to_us, // dwt_us_to_ticks, dwt_time_diff, }; type T = f64; #[allow(non_upper_case_globals)] const TrackerDim: usize = 3; // Tracker Status #[derive(Default)] pub struct CONSTRUCTED; #[derive(Default)] pub struct INITIALIZED; #[allow(non_snake_case)] #[derive(Debug)] pub struct ClockTracker<S> { timestamp_noise: f64, acceleration_nosie: f64, x: Vector3<T>, P: Matrix3<T>, t: Timestamp, outlier_ratio_th: f64, status: S, } #[allow(non_snake_case)] impl<S> ClockTracker<S> { pub fn new(acc_noise: f64, ts_noise: f64) -> ClockTracker<CONSTRUCTED> { assert!(acc_noise > 0.0 && ts_noise > 0.0); ClockTracker { timestamp_noise: ts_noise, acceleration_nosie: acc_noise, x: Vector3::<T>::zeros(), P: 8e8 * Matrix3::<T>::identity(), t: Timestamp::default(), outlier_ratio_th: 2.8, status: CONSTRUCTED, } } fn clone<S2: Default>(&self) -> ClockTracker<S2> { ClockTracker { timestamp_noise: self.timestamp_noise, acceleration_nosie: self.acceleration_nosie, x: self.x.clone(), P: self.P.clone(), t: self.t, outlier_ratio_th: self.outlier_ratio_th, status: S2::default(), } } pub fn t(&self) -> &Timestamp { &self.t } pub fn x(&self) -> &Vector3<T> { &self.x } pub fn P(&self) -> &Matrix3<T> { &self.P } pub fn set_outlier_ratio_th(&mut self, outlier_ratio_th: f64) { assert!(outlier_ratio_th > 0.0); self.outlier_ratio_th = outlier_ratio_th; } } impl ClockTracker<CONSTRUCTED> { #[allow(non_snake_case)] pub fn init_with_mat(self, t0: Timestamp, x0: &Vector3<T>, P0: &Matrix3<T>) -> ClockTracker<INITIALIZED> { ClockTracker { x: x0.clone(), P: P0.clone(), t: t0, ..self.clone::<INITIALIZED>() } } pub fn init_with_matdiag(self, t0: Timestamp, x0: &Vector3<T>, p0: &Vector3<T>) -> ClockTracker<INITIALIZED> { self.init_with_mat(t0, &x0, &Matrix3::<T>::from_diagonal(&p0)) } } #[allow(non_snake_case)] impl ClockTracker<INITIALIZED> { pub fn predict_x(self: &Self, t: Timestamp) -> Vector3<T> { assert!(t >= self.t); let mut new_x = self.x.clone(); if t == self.t { return new_x; } let dt = dwt_ticks_to_us::<_, f64>(dwt_time_diff(t, self.t)) * 1e-6; let dx_no_last = self.x.rows(1, TrackerDim - 1) * dt; let new_x_no_last = dx_no_last + self.x.rows(0, TrackerDim - 1); new_x.rows_mut(0, TrackerDim - 1).copy_from(&new_x_no_last); new_x } pub fn predict_P(self: &Self, t: Timestamp) -> Matrix3<T> { assert!(t >= self.t); if t == self.t { return self.P.clone(); } let dt = dwt_ticks_to_us::<_, f64>(dwt_time_diff(t, self.t)) * 1e-6; let mut A: Matrix3<T> = Matrix3::<T>::new( 1.0, dt, 0.5 * dt * dt, 0.0, 1.0, dt, 0.0, 0.0, 1.0, ); let dt2 = dt * dt; let dt3 = dt * dt2; let dt4 = dt * dt3; let dt5 = dt * dt4; let Q: Matrix3<T> = Matrix3::<T>::new( dt5 / 20.0, dt4 / 8.0, dt3 / 6.0, dt4 / 8.0, dt3 / 3.0, dt2 / 2.0, dt3 / 6.0, dt2 / 2.0, dt, ) * self.acceleration_nosie * self.acceleration_nosie; let new_P = A * self.P * A.transpose() + Q; new_P } pub fn predict_mut(self: &mut Self, t: Timestamp) -> bool { let new_x = self.predict_x(t); let new_P = self.predict_P(t); self.x = new_x; self.P = new_P; self.t = t; // println!("pred: {}", self.x().transpose()); true } pub fn update(self: &mut Self, ts: Timestamp) -> bool { let H: Matrix1x3<T> = Matrix1x3::new(1.0, 0.0, 0.0); // let err = Matrix1::new(dwt_ticks_to_us::<_, T>(ts) * 1e-6) - H * self.x; let err = Matrix1::new(dwt_ticks_to_us::<_, T>(ts) * 1e-6 - self.x[0]); let PHt = self.P * H.transpose(); let s2 = H * PHt + Matrix1::new(self.timestamp_noise * self.timestamp_noise); let is_outlier = err[0] * err[0] > self.outlier_ratio_th * self.outlier_ratio_th * s2[0]; if is_outlier { // println!("outlier: err: {:e}, {}", err[0], err[0] * err[0] / s2[0]); false } else { let K: Matrix3x1<T> = PHt * Matrix1::new(1.0 / s2[0]); let new_x = self.x + K * err; let new_P = (Matrix3::<T>::identity() - K * H) * self.P; self.x = new_x; self.P = new_P; // println!("correct: {}", self.x().transpose()); true } } }
pub fn demo() { println!("变量与可变性"); let v = 123; println!("创建 v = {}", v); let mut v = true; println!("隐藏后 v = {}", v); v = false; println!("添加mut关键字可修改变量 mut v = {}", v); const NUM: i32 = 456; println!("常量NUM: {} 不可变且全部大写命名,需在创建时声明类型且不可变更", NUM); }
foreigner_class!(class One { self_type One; private constructor = empty; }); foreigner_class!(class Two { self_type Two; private constructor = empty; }); foreigner_class!(class Foo { self_type Foo; private constructor = empty; method Foo::f(&self) -> (One, Two); });
mod with_local_pid; use proptest::strategy::{Just, Strategy}; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Encoded; use crate::erlang::unlink_1::result; use crate::test::strategy; use crate::test::{with_process, with_process_arc}; #[test] fn without_pid_or_port_errors_badarg() { run!( |arc_process| { ( Just(arc_process.clone()), strategy::term(arc_process.clone()) .prop_filter("Cannot be pid or port", |pid_or_port| { !(pid_or_port.is_pid() || pid_or_port.is_port()) }), ) }, |(arc_process, pid_or_port)| { prop_assert_badarg!( result(&arc_process, pid_or_port), format!("pid_or_port ({}) is neither a pid nor a port", pid_or_port) ); Ok(()) }, ); } fn link_count(process: &Process) -> usize { process.linked_pid_set.len() }
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkCommandBufferInheritanceInfo { pub sType: VkStructureType, pub pNext: *const c_void, pub renderPass: VkRenderPass, pub subpass: u32, pub framebuffer: VkFramebuffer, pub occlusionQueryEnable: VkBool32, pub queryFlagBits: VkQueryControlFlagBits, pub pipelineStatistics: VkQueryPipelineStatisticFlagBits, } impl VkCommandBufferInheritanceInfo { pub fn new(renderpass: VkRenderPass, subpass: u32, framebuffer: VkFramebuffer) -> Self { VkCommandBufferInheritanceInfo { sType: VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, pNext: ptr::null(), renderPass: renderpass, subpass, framebuffer, occlusionQueryEnable: VK_FALSE, queryFlagBits: 0u32.into(), pipelineStatistics: 0u32.into(), } } pub fn set_query<T, U>( &mut self, occlusion_query_enable: bool, query_flag: T, pipeline_statisctics: U, ) where T: Into<VkQueryControlFlagBits>, U: Into<VkQueryPipelineStatisticFlagBits>, { self.occlusionQueryEnable = occlusion_query_enable.into(); self.queryFlagBits = query_flag.into(); self.pipelineStatistics = pipeline_statisctics.into(); } }
//! Work with HTTP bodies as streams of Kubernetes resources. use super::multi_response_decoder::MultiResponseDecoder; use crate::internal_events::kubernetes::stream as internal_events; use async_stream::try_stream; use bytes05::Buf; use futures::pin_mut; use futures::stream::Stream; use hyper::body::HttpBody as Body; use k8s_openapi::{Response, ResponseError}; use snafu::{ResultExt, Snafu}; /// Converts the HTTP response [`Body`] to a stream of parsed Kubernetes /// [`Response`]s. pub fn body<B, T>(body: B) -> impl Stream<Item = Result<T, Error<<B as Body>::Error>>> where T: Response + Unpin + 'static, B: Body, <B as Body>::Error: std::error::Error + 'static + Unpin, { try_stream! { let mut decoder: MultiResponseDecoder<T> = MultiResponseDecoder::new(); debug!(message = "streaming the HTTP body"); pin_mut!(body); while let Some(buf) = body.data().await { let mut buf = buf.context(Reading)?; let chunk = buf.to_bytes(); let responses = decoder.process_next_chunk(chunk.as_ref()); emit!(internal_events::ChunkProcessed{ byte_size: chunk.len() }); for response in responses { let response = response.context(Parsing)?; yield response; } } decoder.finish().map_err(|data| Error::UnparsedDataUponCompletion { data })?; } } /// Errors that can occur in the stream. #[derive(Debug, Snafu)] pub enum Error<ReadError> where ReadError: std::error::Error + 'static, { /// An error occured while reading the response body. #[snafu(display("reading the data chunk failed"))] Reading { /// The error we got while reading. source: ReadError, }, /// An error occured while parsing the response body. #[snafu(display("data parsing failed"))] Parsing { /// Response parsing error. source: ResponseError, }, /// An incomplete response remains in the buffer, but we don't expect /// any more data. #[snafu(display("unparsed data remaining upon completion"))] UnparsedDataUponCompletion { /// The unparsed data. data: Vec<u8>, }, } #[cfg(test)] mod tests { use super::*; use crate::test_util; use futures::StreamExt; use k8s_openapi::{api::core::v1::Pod, WatchResponse}; fn hyper_body_from_chunks( chunks: Vec<Result<&'static str, std::io::Error>>, ) -> hyper::body::Body { let in_stream = futures::stream::iter(chunks); hyper::body::Body::wrap_stream(in_stream) } #[test] fn test_body() { test_util::trace_init(); test_util::block_on_std(async move { let data = r#"{ "type": "ADDED", "object": { "kind": "Pod", "apiVersion": "v1", "metadata": { "uid": "uid0" } } }"#; let chunks: Vec<Result<_, std::io::Error>> = vec![Ok(data)]; let sample_body = hyper_body_from_chunks(chunks); let out_stream = body::<_, WatchResponse<Pod>>(sample_body); pin_mut!(out_stream); assert!(out_stream.next().await.unwrap().is_ok()); assert!(out_stream.next().await.is_none()); }) } #[test] fn test_body_passes_reading_error() { test_util::trace_init(); test_util::block_on_std(async move { let err = std::io::Error::new(std::io::ErrorKind::Other, "test error"); let chunks: Vec<Result<_, std::io::Error>> = vec![Err(err)]; let sample_body = hyper_body_from_chunks(chunks); let out_stream = body::<_, WatchResponse<Pod>>(sample_body); pin_mut!(out_stream); { let err = out_stream.next().await.unwrap().unwrap_err(); assert!(matches!(err, Error::Reading { source: hyper::Error { .. } })); } assert!(out_stream.next().await.is_none()); }) } #[test] fn test_body_passes_parsing_error() { test_util::trace_init(); test_util::block_on_std(async move { let chunks: Vec<Result<_, std::io::Error>> = vec![Ok("qwerty")]; let sample_body = hyper_body_from_chunks(chunks); let out_stream = body::<_, WatchResponse<Pod>>(sample_body); pin_mut!(out_stream); { let err = out_stream.next().await.unwrap().unwrap_err(); assert!(matches!(err, Error::Parsing { source: ResponseError::Json(_) })); } assert!(out_stream.next().await.is_none()); }) } #[test] fn test_body_uses_finish() { test_util::trace_init(); test_util::block_on_std(async move { let chunks: Vec<Result<_, std::io::Error>> = vec![Ok("{")]; let sample_body = hyper_body_from_chunks(chunks); let out_stream = body::<_, WatchResponse<Pod>>(sample_body); pin_mut!(out_stream); { let err = out_stream.next().await.unwrap().unwrap_err(); assert!(matches!( err, Error::UnparsedDataUponCompletion { data } if data == vec![b'{'] )); } assert!(out_stream.next().await.is_none()); }) } }
pub mod state; use state::{CaseState, Direction, State}; extern crate sdl2; use sdl2::event::Event; use sdl2::image::{InitFlag, LoadTexture}; use sdl2::keyboard::Keycode; //use sdl2::mouse::MouseButton; //use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::Texture; //use sdl2::video::{Window, WindowContext}; //use std::env; use std::path::Path; fn render( canvas: &mut sdl2::render::Canvas<sdl2::video::Window>, state: &State, textures_map: &enum_map::EnumMap<CaseState, Option<Texture>>, textures_mario: &enum_map::EnumMap<Direction, Texture>, texture_spot: &Texture, texture_box_on_spot: &Texture, ) { for x in 0..state.map.width { for y in 0..state.map.width { if let Some(texture) = textures_map[*state.map.get(x, y).expect("error1")].as_ref() { canvas .copy( &texture, None, Some(Rect::new((x as i32) * 34 as i32, (y as i32) * 34, 34, 34)), ) .expect("error2"); } } } for spot in state.spots.iter() { if let Some(case) = state.map.get(spot.0, spot.1) { let texture = match case { CaseState::Wall | CaseState::Empty => texture_spot, CaseState::Box => texture_box_on_spot, }; canvas .copy( &texture, None, Some(Rect::new( (spot.0 as i32) * 34, (spot.1 as i32) * 34, 34, 34, )), ) .expect("error2"); } } canvas .copy( &textures_mario[state.mario_orientation], None, Some(Rect::new( (state.mario_x as i32) * 34, (state.mario_y as i32) * 34, 34, 34, )), ) .expect("error2"); } #[derive(Clone)] pub struct Level { state: State, } fn map_direction(keycode: Keycode) -> Option<Direction> { match keycode { Keycode::Right => Some(Direction::Right), Keycode::Left => Some(Direction::Left), Keycode::Up => Some(Direction::Up), Keycode::Down => Some(Direction::Down), _ => None, } } pub enum EndLevel { Restart, NextLevel, PreviousLevel, Exit, } impl Level { pub fn new(state: State) -> Level { Level {state} } pub fn run(&mut self) -> Result<EndLevel, String> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let _image_context = sdl2::image::init(InitFlag::PNG | InitFlag::JPG)?; let window = video_subsystem .window( "rust-sdl2 demo: Video", 34 * (self.state.map.width as u32), 34 * (self.state.map.width as u32), ) .position_centered() .build() .map_err(|e| e.to_string())?; let mut canvas = window .into_canvas() .software() .build() .map_err(|e| e.to_string())?; let texture_creator = canvas.texture_creator(); let load_texture = |path| texture_creator.load_texture(Path::new(path)).unwrap(); let textures_map = enum_map::enum_map! { CaseState::Empty => None, CaseState::Box => Some(load_texture("assets/box.jpg")), CaseState::Wall => Some(load_texture("assets/wall.jpg")), }; let texture_spot = load_texture("assets/spot.png"); let texture_box_on_spot = load_texture("assets/box_on_spot.jpg"); let textures_mario: enum_map::EnumMap<Direction, Texture> = enum_map::enum_map! { Direction::Up => load_texture("assets/mario_up.gif"), Direction::Down => load_texture("assets/mario_down.gif"), Direction::Left => load_texture("assets/mario_left.gif"), Direction::Right => load_texture("assets/mario_right.gif"), }; let mut update = move |state: &State| { canvas.clear(); render( &mut canvas, state, &textures_map, &textures_mario, &texture_spot, &texture_box_on_spot, ); canvas.present(); }; (update)(&self.state); loop { for event in sdl_context.event_pump()?.poll_iter() { match event { Event::Quit { .. } | Event::KeyDown { keycode: Option::Some(Keycode::Escape), .. } => return Ok(EndLevel::Exit), Event::KeyDown { keycode: Option::Some(Keycode::R), .. } => return Ok(EndLevel::Restart), Event::KeyDown { keycode: Option::Some(Keycode::N), .. } => return Ok(EndLevel::NextLevel), Event::KeyDown { keycode: Option::Some(Keycode::P), .. } => return Ok(EndLevel::PreviousLevel), Event::KeyUp { keycode, .. } => { if let Some(keycode) = keycode { if let Some(direction) = map_direction(keycode) { self.state.move_mario(direction); } update(&self.state); if self.state.is_solved() { return Ok(EndLevel::NextLevel); } } }, _ => {} } } } } }
pub mod names; pub mod string; pub mod prelude;
use crate::ast::Literal; use crate::lexer::*; use crate::parsers::expression::recursing_primary_expression; use crate::parsers::token::identifier::*; /// *pseudo_variable* | *variable* pub(crate) fn variable_reference(i: Input) -> NodeResult { alt((pseudo_variable, map(variable, |v| Node::from(v))))(i) } /// *constant_identifier* | *global_variable_identifier* | *class_variable_identifier* | *instance_variable_identifier* | *local_variable_identifier* pub(crate) fn variable(i: Input) -> IdentifierResult { alt(( constant_identifier, global_variable_identifier, class_variable_identifier, instance_variable_identifier, local_variable_identifier, ))(i) } /// *nil_expression* | *true_expression* | *false_expression* | *self_expression* pub(crate) fn pseudo_variable(i: Input) -> NodeResult { alt(( nil_expression, true_expression, false_expression, self_expression, ))(i) } /// `::` *constant_identifier* pub(crate) fn simple_scoped_constant_reference(i: Input) -> NodeResult { map(tuple((tag("::"), ws0, constant_identifier)), |_| { Node::Placeholder })(i) } /// `::` *constant_identifier* pub(crate) fn _scoped_constant_reference(i: Input) -> NodeResult { map( tuple(( tag("::"), ws0, constant_identifier, opt(recursing_primary_expression), )), |_| Node::Placeholder, )(i) } /// `nil` pub(crate) fn nil_expression(i: Input) -> NodeResult { map(tuple((tag("nil"), not(peek(identifier_character)))), |_| { Node::Nil })(i) } /// `true` pub(crate) fn true_expression(i: Input) -> NodeResult { map( tuple((tag("true"), not(peek(identifier_character)))), |_| Node::Literal(Literal::Boolean(true)), )(i) } /// `false` pub(crate) fn false_expression(i: Input) -> NodeResult { map( tuple((tag("false"), not(peek(identifier_character)))), |_| Node::Literal(Literal::Boolean(false)), )(i) } /// `self` pub(crate) fn self_expression(i: Input) -> NodeResult { map( tuple((tag("self"), not(peek(identifier_character)))), |_| Node::Self_, )(i) } #[cfg(test)] mod tests { use super::*; #[test] fn test_variable_reference() { use_parser!(variable_reference); // Parse errors assert_err!(""); assert_err!("nil "); assert_err!("bar\n"); // Success cases assert_ok!("nil", Node::Nil); assert_ok!("true", Node::boolean(true)); assert_ok!("false", Node::boolean(false)); assert_ok!("self", Node::Self_); assert_ok!("TRUE", Node::ident("TRUE", IdentifierKind::Constant)); assert_ok!("False", Node::ident("False", IdentifierKind::Constant)); assert_ok!("nil_", Node::ident("nil_", IdentifierKind::LocalVariable)); assert_ok!( "$true", Node::ident("$true", IdentifierKind::GlobalVariable) ); } }
test_stdout!( without_pid_returns_false, "false\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\nfalse\n" ); test_stdout!(with_pid_returns_true, "true\n");
// source: https://github.com/extrawurst/godot-vs-rapier/blob/master/logic/src/utils.rs use gdnative::prelude::*; pub trait NodeExt { /// Gets a node at `path`, assumes that it's safe to use, and casts it to `T`. /// /// # Safety /// /// See `Ptr::assume_safe`. fn get_typed_node<T, P>(&self, path: P) -> TRef<'_, T, Shared> where T: GodotObject + SubClass<Node>, P: Into<NodePath>; } impl NodeExt for Node { fn get_typed_node<T, P>(&self, path: P) -> TRef<'_, T, Shared> where T: GodotObject + SubClass<Node>, P: Into<NodePath>, { unsafe { self.get_node(path.into()) .expect("node should exist") .assume_safe() .cast() .expect("node should be of the correct type") } } }
use chrono::{DateTime, Utc}; use diesel::{self, ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl}; use serde::{Deserialize, Serialize}; use auth::{create_jwt, PrivateClaim, Role}; use errors::Error; use crate::schema::games; use crate::utils::create_slug_from_id; #[derive(Debug, Identifiable, Serialize, Deserialize, Queryable)] pub struct Game { pub id: i32, pub slug: Option<String>, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, pub creator: Option<String>, } impl Game { pub fn create(conn: &PgConnection) -> Result<Game, Error> { use games::{dsl, table}; let game: Game = diesel::insert_into(table) .default_values() .get_result(conn)?; let new_slug = create_slug_from_id(game.id); let jwt = create_jwt(PrivateClaim::new( game.id, new_slug.clone(), game.id, Role::Owner, ))?; let updated_game = diesel::update(dsl::games.find(game.id)) .set((dsl::slug.eq(new_slug), dsl::creator.eq(jwt))) .get_result::<Game>(conn)?; Ok(updated_game) } pub fn find_by_id(conn: &PgConnection, id: i32) -> Result<Game, Error> { use crate::schema::games::dsl::games; let game = games.find(id).first(conn)?; Ok(game) } pub fn find_by_slug(conn: &PgConnection, slug_value: &str) -> Result<Game, Error> { use crate::schema::games::dsl::{games, slug}; let game = games.filter(slug.eq(slug_value)).first::<Game>(conn)?; Ok(game) } }
extern crate num; extern crate nue; use super::{Com, Core, SenderBus, Permission}; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::io::Read; use std::collections::VecDeque; struct Bus<W> { sender: SenderBus<W>, selected: bool, enabled: bool, } #[derive(Default)] struct DStack<W> { stack: Vec<W>, } impl<W> DStack<W> where W: Copy { fn rotate(&mut self, pos: u8) { let last = self.stack.len() - 1; // TODO: Introduce debug on out of range let v = self.stack.remove(last - pos as usize); self.stack.push(v); } fn copy(&mut self, pos: u8) { let last = self.stack.len() - 1; // TODO: Introduce debug on out of range let v = self.stack[last - pos as usize]; self.stack.push(v); } fn replace<F>(&mut self, c: F) where F: FnOnce(W) -> W { let v = match self.stack.pop() { Some(v) => v, None => { // TODO: Add proper debugging here panic!("core0: Attempted to consume a value when none was available."); }, }; self.stack.push(c(v)); } } struct CStackElement<W> { pc: W, dcs: [W; 4], interrupt: bool, } pub struct Core0<W> { permission: Permission, running: bool, pc: W, dcs: [W; 4], carry: bool, overflow: bool, interrupt: bool, program: Vec<u8>, data: Vec<W>, // Buses including senders buses: Vec<Bus<W>>, // Incoming streams incoming_streams: Vec<Receiver<Com<Box<Read>>>>, // The channel that must be used to incept this core incept_channel: (SyncSender<Com<(Permission, Box<Read>)>>, Receiver<Com<(Permission, Box<Read>)>>), // The channel that must be used to send interrupts to this core send_channel: (SyncSender<Com<W>>, Receiver<Com<W>>), // The channel that must be used to kill this core kill_channel: (SyncSender<Com<()>>, Receiver<Com<()>>), dstack: DStack<W>, cstack: Vec<CStackElement<W>>, conveyor: VecDeque<W>, } impl<W> Core0<W> where W: num::PrimInt + Default { pub fn new(memory: usize) -> Self { Core0{ permission: Permission::default(), running: false, pc: W::zero(), dcs: [W::zero(); 4], carry: false, overflow: false, interrupt: false, program: Vec::new(), data: vec![W::zero(); memory], incoming_streams: Vec::new(), buses: Vec::new(), incept_channel: sync_channel(0), send_channel: sync_channel(0), kill_channel: sync_channel(0), dstack: DStack::default(), cstack: Vec::new(), conveyor: { use std::iter::repeat; let mut v = VecDeque::new(); v.extend(repeat(W::zero()).take(16)); v }, } } } impl<W> Core<W> for Core0<W> where W: Copy + num::PrimInt + num::Signed + nue::Decode + nue::Encode, usize: From<W> + Into<W> { fn append_sender(&mut self, sender: SenderBus<W>) { self.buses.push(Bus{ sender: sender, selected: false, enabled: false, }); } fn aquire_sender(&mut self) -> SenderBus<W> { let stream_channel = sync_channel(0); self.incoming_streams.push(stream_channel.1); SenderBus{ bus: self.incoming_streams.len() - 1, stream: stream_channel.0, incept: self.incept_channel.0.clone(), send: self.send_channel.0.clone(), kill: self.kill_channel.0.clone(), } } fn begin(&mut self) { assert_eq!(self.incoming_streams.len(), self.buses.len()); // Get disjoint references so borrows can occur simultaneously let running = &mut self.running; let dstack = &mut self.dstack; let cstack = &mut self.cstack; let conveyor = &mut self.conveyor; let buses = &mut self.buses; let data = &mut self.data; let prog = &mut self.program; let pc = &mut self.pc; let dcs = &mut self.dcs; let permission = &mut self.permission; let carry = &mut self.carry; let overflow = &mut self.overflow; let interrupt = &mut self.interrupt; let send_channel = &mut self.send_channel; let incoming_streams = &mut self.incoming_streams; // Repeat loop of reinception perpetually loop { // Accept inception // TODO: Implement { let com = match self.incept_channel.1.recv() { Ok(v) => v, Err(_) => panic!("core0: Inception channel broken"), }; *permission = com.data.0; let mut receiver = com.data.1; // Clear any previous program before loading the new one prog.clear(); receiver.read_to_end(prog).expect("core0: Inception stream failed"); *running = true; } // Run until core is killed loop { // Poll for any sort of communication // TODO: Implement // Execute instruction match prog[usize::from(*pc)] { // rread# x @ 0x00...0x03 => { let select = x as usize; dstack.replace(|v| { data[usize::from(dcs[select] + v)] }); }, // add# x @ 0x04...0x07 => { let select = x as usize - 0x04; dstack.replace(|v| { let dc_val = data[usize::from(dcs[select])]; let new = dc_val + v; let old_signs = (v.is_negative(), dc_val.is_negative()); let new_sign = new < W::zero(); *overflow = if old_signs.0 != old_signs.1 { false } else { new_sign != old_signs.0 }; *carry = old_signs.0 && old_signs.1 && !new_sign; new }); }, // inc 0x08 => { dstack.replace(|v| { let new = v + W::one(); let old_sign = v.is_negative(); let new_sign = new.is_negative(); // Going from positive to negative is overflow *overflow = !old_sign && new_sign; // If the new value wrapped back to zero we carry *carry = new == W::zero(); new }); }, // dec 0x09 => { dstack.replace(|v| { let new = v - W::one(); let old_sign = v.is_negative(); let new_sign = new.is_negative(); // Going from negative to positive is overflow *overflow = old_sign && !new_sign; // If the original value is zero, decrementing borrows let borrow = v == W::zero(); *carry = !borrow; new }); }, // carry 0x0A => { if *carry { dstack.replace(|v| { let new = v + W::one(); let old_sign = v.is_negative(); let new_sign = new.is_negative(); // Going from positive to negative is overflow *overflow = !old_sign && new_sign; // If the new value wrapped back to zero we carry *carry = new == W::zero(); new }); } else { *overflow = false; *carry = false; } }, // borrow 0x0B => { if *carry { *overflow = false; *carry = true; } else { dstack.replace(|v| { let new = v - W::one(); let old_sign = v.is_negative(); let new_sign = new.is_negative(); // Going from negative to positive is overflow *overflow = old_sign && !new_sign; // If the original value is zero, decrementing borrows let borrow = v == W::zero(); *carry = !borrow; new }); } }, // inv 0x0C => { dstack.replace(|v| { !v }); }, // flush 0x0D => {}, // reads 0x0E => { dstack.replace(|v| { data[usize::from(v)] }); }, // ret 0x0F => { let elem = cstack.pop().expect("core0: Tried to return with empty return stack"); if elem.interrupt { *interrupt = true; } *pc = elem.pc; *dcs = elem.dcs; }, // ien 0x10 => { for bus in buses.iter_mut() { bus.enabled |= bus.selected; } }, // idi 0x11 => { for bus in buses.iter_mut() { bus.enabled = false; } }, // recv 0x12 => { // Wait for an enabled interrupt (place the rest in a vec to send them back) let mut msg; loop { msg = send_channel.1.recv().expect("core0: Interrupt/send channel closed"); if buses[msg.bus].enabled { break; } // Drop any messages that arent enabled } // Remove 2 values from back of conveyor conveyor.pop_back(); conveyor.pop_back(); // Add the values to the conveyor in the correct order conveyor.push_front(usize::into(msg.bus)); conveyor.push_front(msg.data); }, // in 0x13 => { 'outer: loop { use std::thread::yield_now; for (b, o) in buses.iter_mut().zip(incoming_streams.iter_mut()) { if b.enabled { use std::sync::mpsc::TryRecvError::{Empty, Disconnected}; match o.try_recv() { Ok(msg) => { let mut read = msg.data; let bus = usize::into(msg.bus); dstack.replace(|v| { use std::mem::{transmute, size_of}; let loc = usize::from(v); match read.read_to_end(unsafe{transmute(&mut data[loc])}) { Ok(n) => { if n % size_of::<W>() != 0 { panic!("core0: Read was not aligned properly!"); } }, Err(e) => { panic!("core0: Unable to read to end on in: {}", e); }, } bus }); // Got a message successfully, so exit the loop break 'outer; }, Err(Empty) => {}, Err(Disconnected) => { panic!("core0: Incoming streams channel closed"); }, } } } yield_now(); } }, // TODO: Add all instructions _ => {}, } } } } }
// adc.rs - contains all 8 functions to support adc instructions use super::addressing::{self, Operation}; use crate::memory::{RAM, *}; pub fn adc_immediate( operand: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, cycles_until_next: &mut u8, ) { *accumulator = addressing::immediate(*accumulator, operand, &mut status_flags, Operation::Add); *pc_reg += 2; *cycles_until_next = 2; } pub fn adc_zero_page( operand: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::zero_page( *accumulator, operand, memory, &mut status_flags, Operation::Add, ); *pc_reg += 2; *cycles_until_next = 3; } pub fn adc_zero_page_x( operand: u8, x_reg: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::zero_page_x( *accumulator, x_reg, operand, memory, &mut status_flags, Operation::Add, ); *pc_reg += 2; *cycles_until_next = 4; } pub fn adc_absolute( operand: u16, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::absolute( *accumulator, operand, memory, &mut status_flags, Operation::Add, ); *pc_reg += 3; *cycles_until_next = 4; } pub fn adc_absolute_reg( operand: u16, reg: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::absolute_reg( *accumulator, reg, operand, memory, &mut status_flags, Operation::Add, ); *pc_reg += 3; *cycles_until_next = 4; } pub fn adc_indexed_indirect( operand: u8, x_val: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::indexed_indirect( *accumulator, x_val, operand, memory, &mut status_flags, Operation::Add, ); *pc_reg += 2; *cycles_until_next = 6; } pub fn adc_indirect_indexed( operand: u8, y_val: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::indirect_indexed( *accumulator, y_val, operand, memory, &mut status_flags, Operation::Add, ); *pc_reg += 2; *cycles_until_next = 5; } #[cfg(test)] mod tests { use super::*; use crate::cpu::flags; use crate::memory; #[test] fn adc_tests() { let operand = 12; let mut pc_reg = 0; let mut accumulator = 0; let mut status: u8 = 0; let mut test_memory: memory::RAM = memory::RAM::new(); let mut cycles = 0; // init mem for i in 0..2048 { test_memory.write_mem_value(i, (i * 2) as u8); } adc_immediate( operand, &mut pc_reg, &mut accumulator, &mut status, &mut cycles, ); assert_eq!(pc_reg, 2); assert_eq!(accumulator, 12); assert_eq!(status, 0); let operand2 = 230; adc_immediate( operand2, &mut pc_reg, &mut accumulator, &mut status, &mut cycles, ); assert_eq!(pc_reg, 4); assert_eq!(accumulator, 242); //-ve should be set assert_eq!(status, 0x40); accumulator = 0; status = 0; adc_zero_page( 12, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 6); assert_eq!(accumulator, 24); assert_eq!(status, 0); adc_zero_page( 120, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 8); assert_eq!(accumulator, 8); assert_eq!(status, 1); accumulator = 0; status = 0; adc_zero_page( 0, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 10); assert_eq!(accumulator, 0); assert_eq!(status, 2); accumulator = 0; status = 0; adc_zero_page_x( 255, 2, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 12); assert_eq!(accumulator, 2); adc_absolute( 257, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 15); assert_eq!(accumulator, 4); adc_absolute_reg( 257, 2, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 18); assert_eq!(accumulator, 10); accumulator = 0; adc_indexed_indirect( 127, 3, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 20); assert_eq!(accumulator, 8); accumulator = 0; adc_indirect_indexed( 1, 3, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 22); assert_eq!(accumulator, 10); //test overflow flag! accumulator = 0b0111_1111; let operand = 0b0111_1111; adc_immediate( operand, &mut pc_reg, &mut accumulator, &mut status, &mut cycles, ); assert_eq!(status & flags::OVERFLOW_BIT, flags::OVERFLOW_BIT); assert_eq!(status & flags::NEGATIVE_BIT, flags::NEGATIVE_BIT); accumulator = 0b0111_1111; let operand = 0b1000_0001; adc_immediate( operand, &mut pc_reg, &mut accumulator, &mut status, &mut cycles, ); assert_eq!(status & flags::CARRY_BIT, flags::CARRY_BIT); status = flags::CARRY_BIT; accumulator = 0; let operand = 0; adc_immediate( operand, &mut pc_reg, &mut accumulator, &mut status, &mut cycles, ); assert_eq!(accumulator, 1); accumulator = 0b1000_0000; let operand = 0b1000_0000; adc_immediate( operand, &mut pc_reg, &mut accumulator, &mut status, &mut cycles, ); assert_eq!(status & flags::OVERFLOW_BIT, flags::OVERFLOW_BIT); } }
use std::fs::read_to_string; fn main() { let (img, mut min_n0, mut num_1x2, mut render) = (read_to_string("in8.txt").unwrap(), 151, 0, [[2; 25]; 6]); let mut digits = img.chars(); for _ in 0 .. img.len() / 150 { let mut nums = [0; 3]; for y in 0..6 { for x in 0..25 { let dig = digits.next().unwrap().to_digit(10).unwrap(); nums[dig as usize] += 1; if render[y][x] == 2 { render[y][x] = dig; } } } if nums[0] < min_n0 { min_n0 = nums[0]; num_1x2 = nums[1] * nums[2]; } } println!("Part A: {}", num_1x2); // 2016 println!("Part B:"); // HZCZU for y in 0..6 { for x in 0..25 { print!(" {}", match render[y][x] { // # # # # # # # # # # # # # # 0 => ' ', // # # # # # # # # 1 => '#', // # # # # # # # # # _ => panic!("missing pixel"), // # # # # # # # }); } // # # # # # # # # println!(); // # # # # # # # # # # # # # # } }
// region: lmake_readme include "readme.md" //! A //! **mem4 is a simple memory game made primarily for learning the Rust programming language and Wasm/WebAssembly with Virtual Dom Dodrio and WebSocket communication** //! //! version: 19.9.10 //! Look also at the workspace readme on https://github.com/LucianoBestia/mem4_game //! //! # Idea //! //! Playing the memory game alone is boring. //! Playing it with friends is better. //! But if all friends just stare in their smartphones, it is still boring. //! What makes memory games (and other board games) entertaining is the company of friends. //! There must be many friends around the table watching one another and stealing moves and laughing and screaming at each other. //! Today I assume everybody has a decent smartphone. If all friends open the mem4 game and put their smartphones on the center of the table one near the other so that everybody can see them and touch them, this is the closest it gets to a classic board game. //! All the phones will have a small card grid (ex. 3x3). But the combined card grid from all these phones together is not so small anymore. It is now much more interesting to play for the players. //! It can be played with as many friends as there are: 3,4,5,... //! More friends - more fun. //! //! ## Rust and Wasm/WebAssembly //! //! Rust is a pretty new language created by Mozilla for really low level programming. //! It is a step forward from the C language with functionality and features that are best practice today. //! It is pretty hard to learn. Some concepts are so different from other languages it makes it //! hard for beginners. Lifetimes are the strangest and most confusing concept. //! The Rust language has been made from the ground up with an ecosystem that makes it productive. //! The language and most of the libraries are Open Source. That is good and bad, but mostly good. //! Rust is the best language today to compile into Wasm/WebAssembly. //! That compiled code works inside a browser directly with the JavaScript engine. //! So finally no need for JavaScript to make cross-platform applications inside browsers. //! I have a lot of hope here. //! ## Virtual DOM //! Constructing a HTML page with Virtual DOM (vdom) is easier //! because it is rendered completely on every tick (animation frame). //! Sometimes is hard for the developer to think what should change in the UI when some data changes. //! The data can change from many different events and very chaotically (asynchronously). //! It is easier to think how to render the complete DOM for the given data. //! The Rust Dodrio library has ticks, time intervals when it do something. //! If a rendering is scheduled, it will be done on the next tick. //! If a rendering is not scheduled I believe nothing happens. //! This enables asynchronous changing of data and rendering. They cannot happen theoretically in the //! same exact moment. So, no data race here. //! When GameData change and we know it will affect the DOM, then rendering must be scheduled. //! The main component of the Dodrio Virtual Dom is the root rendering component. //! It is the component that renders the complete user interface (HTML). //! The root rendering component is easily splitted into sub-components. //! ![](https://github.com/LucianoBestia/mem4_game/raw/master/docs/img/subcomponents.png) //! Some subcomponents don't need any extra data and can be coded as simple functions. //! The subcomponent "players and scores" has its own data. This data is cached from the GameData. //! When this data does not match, invalidation is called to cache them. //! That also schedules the rendering of the subcomponent. //! If no data has changed, the cached subcomponent Node is used. This is more efficient and performant. //! ##GameData //! All the game data are in this simple struct. //! ## WebSocket communication //! HTML5 has finally bring a true stateful bidirectional communication. //! Most of the programming problems are more easily and effectively solved this way. //! The old unidirectional stateless communication is very good for static html pages, //! but is terrible for any dynamic page. The WebSocket is very rudimental and often the //! communication breaks for many different reasons. The programmer must deal with it inside the application. //! The protocol has nothing that can be used to deal with reconnections. //! I send simple structs text messages in json format between the players. //! They are all in the WsMsg enum and therefore interchangeable. //! The WebSocket server is coded especially for this game and recognizes 3 types of msg: //! - msg to broadcast to every other player //! - msg to send only to the actual game players //! ## WS reconnect //! TODO: It looks that plain web sockets have often connection problems and they disconnect here and there. Creating a good reconnect is pretty challenging. //! ## The game flow //! In a few words: Status1 - User action - Status2, Status1 - WsMessage - Status2 //! In one moment the game is in a certain Game Status. The user then makes an action. //! This action changes the GameData and the GameStatus. //! Then a message is sent to other players so they can also change their local GameData and GameStatus. //! The rendering is scheduled and it will happen shortly (async). //! //! | Game Status1 | Render | User action | Condition | GameStatus2 t.p. | Sends Msg | On rcv Msg o.p. | GameStatus2 o.p. | //! | ------------------ | -------------------------- | ------------------------------------------- | ------------------------------------ | ---------------- | ---------------- | -------------------------- | -------------------------------- | //! | InviteAskBegin | div_invite_ask_begin | div_invite_ask_begin_on_click | - | InviteAsking | Invite | on_msg_invite | InviteAsked | //! | InviteAsked | div_invite_asked, div_play_accepted | div_invite_asked_on_click | - | PlayAccepted | PlayAccept | on_msg_play_accept | - | //! | InviteAsking | div_invite_asking | game_data_init | - | PlayBefore1stCard | GameDataInit | on_msg_game_data_init | PlayBefore1stCard | //! | PlayBefore1stCard | div_grid_container | div_grid_item_on_click, on_click_1st_card();| - | PlayBefore2ndCard | PlayerClick1stCard | on_msg_player_click_1st_card | PlayBefore2ndCard | //! | PlayBefore2ndCard | div_grid_container | div_grid_item_on_click, on_click_2nd_card();| If card match and points<all point | PlayBefore1stCard | PlayerClick2ndCard | on_msg_player_click_2nd_card | PlayBefore1stCard | //! | -II- | -II- | -II- | If card match and points=>all points | GameOverPlayAgainBegin | GameOverPlayAgainBegin | on_msg_play_again | GameOverPlayAgainBegin | //! | -II- | -II- | -II- | else | TakeTurnBegin | TakeTurnBegin | on_msg_take_turn | TakeTurnBegin | //! | TakeTurnBegin | div_take_turn_begin | div_take_turn_begin_on_click | - | PlayBefore1stCard | TakeTurnEnd | on_msg_take_turn_end | PlayBefore1stCard, the next player | //! | GameOverPlayAgainBegin | div_play_again | window.location().reload() | - | - | - | - | - | //! | | | | | | | | | //! //! t.p. = this player, o.p. = other players, rrc = root_rendering_component, rcv = receive //! 1. Some actions can have different results. For example the condition card match or card don’t match. //! 2. one action must be only for one status1. This action changes Status for this player and sends Msg to other players. //! 3. on receive msg can produce only one status2. //! 4. in this table I ignore msgs for the server like GetConfig //! //! ## Futures and Promises, Rust and JavaScript //! JavaScript is all asynchronous. Wasm is nothing else then a shortcut to the JavaScript engine. //! So everything is asynchronous too. This is pretty hard to grasp. Everything is Promises and Futures. //! There is a constant jumping from thinking in Rust to thinking is JavaScript and back. That is pretty confusing. //! JavaScript does not have a good idea of Rust datatypes. All there is is a generic JSValue type. //! The library `wasm-bindgen` has made a fantastic job of giving Rust the ability to call //! anything JavaScript can call, but the way of doing it is sometimes very hard to understand. //! ## Typed html //! Writing html inside Rust code is much easier with the macro `html!` from the `crate typed-html` //! https://github.com/bodil/typed-html //! It has also a macro `dodrio!` created exclusively for the dodrio vdom. //! Everything is done in compile time, so the runtime is nothing slower. //! ## Browser console //! At least in modern browsers (Firefox and Chrome) we have the developer tools F12 and there is a //! console we can output to. So we can debug what is going on with our Wasm program. //! But not on smartphones that are the only target for this app. //! ## Safari on iOS and FullScreen //! Apple is very restrictive and does not allow fullscreen Safari on iPhones. //! The workaround is to make a shortcut for the webapp on the homescreen. //! ## mem4 as webapp on HomeScreen //! On both android and iPhone is possible to "Add to homescreen" the webapp. //! Then it will open in fullscreen and be beautiful. //! In safari the share icon (a square with arrow up) has "Add to home screen". //! https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html //! ## Modules //! Rust code is splitted into modules. They are not exactly like classes, but can be similar. //! Rust has much more freedom to group code in different ways. So that is best suits the problem. //! I splitted the rendering into sub-components. //! And then I splitted the User Actions by the Status1 to easy follow the flow of the game. //! ## Clippy //! Clippy is very useful to teach us how to program in a better way. //! These are not syntax errors, but hints how to do it in a more Rusty way (idiomatic). //! Some lints are problematic and they are explicitly allowed here. //! ## Cargo make //! I prepared some flows and tasks for Cargo make. //! `cargo make` - lists the possible available/public flows/tasks //! `cargo make dev` - builds the development version and runs the server and the browser //! `cargo make release` - builds the release version and runs the server and the browser //! `cargo make doc` - build the `/target/doc` folder and copy to the `../docs` folder. // endregion: lmake_readme include "readme.md" //! A //needed for dodrio! macro (typed-html) #![recursion_limit = "512"] //region: Clippy #![warn( clippy::all, clippy::restriction, clippy::pedantic, clippy::nursery, clippy::cargo, //variable shadowing is idiomatic to Rust, but unnatural to me. clippy::shadow_reuse, clippy::shadow_same, clippy::shadow_unrelated, )] #![allow( //library from dependencies have this clippy warnings. Not my code. //Why is this bad: It will be more difficult for users to discover the purpose of the crate, //and key information related to it. clippy::cargo_common_metadata, //Why is this bad : This bloats the size of targets, and can lead to confusing error messages when //structs or traits are used interchangeably between different versions of a crate. clippy::multiple_crate_versions, //Why is this bad : As the edition guide says, it is highly unlikely that you work with any possible //version of your dependency, and wildcard dependencies would cause unnecessary //breakage in the ecosystem. clippy::wildcard_dependencies, //Rust is more idiomatic without return statement //Why is this bad : Actually omitting the return keyword is idiomatic Rust code. //Programmers coming from other languages might prefer the expressiveness of return. //It’s possible to miss the last returning statement because the only difference //is a missing ;. Especially in bigger code with multiple return paths having a //return keyword makes it easier to find the corresponding statements. clippy::implicit_return, //I have private function inside a function. Self does not work there. //Why is this bad: Unnecessary repetition. Mixed use of Self and struct name feels inconsistent. clippy::use_self, //Cannot add #[inline] to the start function with #[wasm_bindgen(start)] //because then wasm-pack build --target web returns an error: export run not found //Why is this bad: In general, it is not. Functions can be inlined across crates when that’s profitable //as long as any form of LTO is used. When LTO is disabled, functions that are not #[inline] //cannot be inlined across crates. Certain types of crates might intend for most of the //methods in their public API to be able to be inlined across crates even when LTO is disabled. //For these types of crates, enabling this lint might make sense. It allows the crate to //require all exported methods to be #[inline] by default, and then opt out for specific //methods where this might not make sense. clippy::missing_inline_in_public_items, //Why is this bad: This is only checked against overflow in debug builds. In some applications one wants explicitly checked, wrapping or saturating arithmetic. //clippy::integer_arithmetic, //Why is this bad: For some embedded systems or kernel development, it can be useful to rule out floating-point numbers. clippy::float_arithmetic, //Why is this bad : Doc is good. rustc has a MISSING_DOCS allowed-by-default lint for public members, but has no way to enforce documentation of private items. This lint fixes that. clippy::doc_markdown, //Why is this bad : Splitting the implementation of a type makes the code harder to navigate. clippy::multiple_inherent_impl, )] //endregion //region: mod is used only in lib file. All the rest use use crate mod divcardmoniker; mod divfordebugging; mod divgridcontainer; mod divplayeractions; mod divplayersandscores; mod divrulesanddescription; mod fetchmod; mod fetchgameconfig; mod gamedata; mod javascriptimportmod; mod logmod; mod rootrenderingcomponent; mod statusinviteaskbegin; mod statusinviteasked; mod statusinviteasking; mod statusplayagain; mod statusplaybefore1stcard; mod statusplaybefore2ndcard; mod statustaketurnbegin; mod websocketcommunication; mod websocketreconnect; //endregion //region: extern and use statements //Strum is a set of macros and traits for working with enums and strings easier in Rust. extern crate console_error_panic_hook; extern crate log; extern crate serde; #[macro_use] extern crate serde_derive; extern crate mem4_common; extern crate serde_json; extern crate strum; extern crate strum_macros; extern crate web_sys; #[macro_use] extern crate unwrap; extern crate conv; use rand::rngs::SmallRng; use rand::FromEntropy; use rand::Rng; use wasm_bindgen::prelude::*; //endregion //region: wasm_bindgen(start) is where everything starts #[wasm_bindgen(start)] ///To start the Wasm application, wasm_bindgen runs this functions pub fn run() -> Result<(), JsValue> { // Initialize debugging for when/if something goes wrong. console_error_panic_hook::set_once(); // Get the document's container to render the virtual Dom component. let window = unwrap!(web_sys::window(), "error: web_sys::window"); let document = unwrap!(window.document(), "error: window.document"); let div_for_virtual_dom = unwrap!( document.get_element_by_id("div_for_virtual_dom"), "No #div_for_virtual_dom" ); let mut rng = SmallRng::from_entropy(); //my_ws_uid is random generated on the client and sent to //WebSocket server with an url param let my_ws_uid: usize = rng.gen_range(1, 9999); //find out URL let location_href = unwrap!(window.location().href(), "href not known"); //WebSocket connection let ws = websocketcommunication::setup_ws_connection(location_href.clone(), my_ws_uid); //I don't know why is needed to clone the WebSocket connection let ws_c = ws.clone(); // Construct a new RootRenderingComponent. //I added ws_c so that I can send messages on WebSocket let mut root_rendering_component = rootrenderingcomponent::RootRenderingComponent::new(ws_c, my_ws_uid); root_rendering_component.game_data.href = location_href; // Mount the component to the `<div id="div_for_virtual_dom">`. let vdom = dodrio::Vdom::new(&div_for_virtual_dom, root_rendering_component); websocketcommunication::setup_all_ws_events(&ws, vdom.weak()); // Run the component forever. Forget to drop the memory. vdom.forget(); Ok(()) } //endregion /// Get the top-level window's session storage. /// TODO: to save user preferences maybe? pub fn session_storage() -> web_sys::Storage { let window = unwrap!(web_sys::window(), "error: web_sys::window"); window.session_storage().unwrap_throw().unwrap_throw() } //endregion
use crate::builder; use eosio::AccountName; use serde::{Deserialize, Serialize}; builder!("/v1/chain/get_info", GetInfo, Info); #[derive(Serialize, Clone)] pub struct GetInfo {} pub const fn get_info() -> GetInfo { GetInfo {} } pub type ChainId = String; pub type BlockId = String; pub type BlockNum = u32; pub type ServerVersion = String; pub type BlockTimestamp = String; #[derive(Deserialize, Serialize, Debug, PartialEq)] pub struct Info { pub server_version: ServerVersion, pub server_version_string: String, pub chain_id: ChainId, pub head_block_num: BlockNum, pub head_block_id: BlockId, pub head_block_time: BlockTimestamp, pub head_block_producer: AccountName, pub last_irreversible_block_num: BlockNum, pub last_irreversible_block_id: BlockId, pub virtual_block_cpu_limit: u32, pub virtual_block_net_limit: u32, pub block_cpu_limit: u32, pub block_net_limit: u32, }
#[macro_use] extern crate glium; extern crate image; mod player; fn main() { player::play(); }
use super::{ get_span_of_entire_for_loop, make_iterator_snippet, IncrementVisitor, InitializeVisitor, EXPLICIT_COUNTER_LOOP, }; use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::{get_enclosing_block, is_integer_const}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::intravisit::{walk_block, walk_expr}; use rustc_hir::{Expr, Pat}; use rustc_lint::LateContext; use rustc_middle::ty::{self, UintTy}; // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be // incremented exactly once in the loop body, and initialized to zero // at the start of the loop. pub(super) fn check<'tcx>( cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, arg: &'tcx Expr<'_>, body: &'tcx Expr<'_>, expr: &'tcx Expr<'_>, ) { // Look for variables that are incremented once per loop iteration. let mut increment_visitor = IncrementVisitor::new(cx); walk_expr(&mut increment_visitor, body); // For each candidate, check the parent block to see if // it's initialized to zero at the start of the loop. if let Some(block) = get_enclosing_block(cx, expr.hir_id) { for id in increment_visitor.into_results() { let mut initialize_visitor = InitializeVisitor::new(cx, expr, id); walk_block(&mut initialize_visitor, block); if_chain! { if let Some((name, ty, initializer)) = initialize_visitor.get_result(); if is_integer_const(cx, initializer, 0); then { let mut applicability = Applicability::MachineApplicable; let for_span = get_span_of_entire_for_loop(expr); let int_name = match ty.map(ty::TyS::kind) { // usize or inferred Some(ty::Uint(UintTy::Usize)) | None => { span_lint_and_sugg( cx, EXPLICIT_COUNTER_LOOP, for_span.with_hi(arg.span.hi()), &format!("the variable `{}` is used as a loop counter", name), "consider using", format!( "for ({}, {}) in {}.enumerate()", name, snippet_with_applicability(cx, pat.span, "item", &mut applicability), make_iterator_snippet(cx, arg, &mut applicability), ), applicability, ); return; } Some(ty::Int(int_ty)) => int_ty.name_str(), Some(ty::Uint(uint_ty)) => uint_ty.name_str(), _ => return, }; span_lint_and_then( cx, EXPLICIT_COUNTER_LOOP, for_span.with_hi(arg.span.hi()), &format!("the variable `{}` is used as a loop counter", name), |diag| { diag.span_suggestion( for_span.with_hi(arg.span.hi()), "consider using", format!( "for ({}, {}) in (0_{}..).zip({})", name, snippet_with_applicability(cx, pat.span, "item", &mut applicability), int_name, make_iterator_snippet(cx, arg, &mut applicability), ), applicability, ); diag.note(&format!( "`{}` is of type `{}`, making it ineligible for `Iterator::enumerate`", name, int_name )); }, ); } } } } }
#![allow(warnings, unused_unsafe)] use abi_stable::StableAbi; #[repr(u8)] #[derive(StableAbi)] #[sabi(kind(WithNonExhaustive( size = 1, align = 1, assert_nonexhaustive = TooLarge, )))] #[sabi(with_constructor)] pub enum TooLarge { Foo, Bar, Baz(u8), } #[repr(u8)] #[derive(StableAbi)] #[sabi(kind(WithNonExhaustive( size = 32, align = 1, assert_nonexhaustive = Unaligned, )))] #[sabi(with_constructor)] pub enum Unaligned { Foo, Bar, Baz(u64), } #[repr(u8)] #[derive(StableAbi)] #[sabi(kind(WithNonExhaustive( size = 1, align = 1, assert_nonexhaustive = UnalignedAndTooLarge, )))] #[sabi(with_constructor)] pub enum UnalignedAndTooLarge { Foo, Bar, Baz(u64), } fn main(){}
use super::combine::Combine; pub trait PrimeChecker { type Value; // returns // false if |value| is not a prime // true otherwise fn check(&self, value: &Self::Value) -> bool; fn combine<C>(self, checker: C) -> Combine<Self::Value, Self, C> where Self: Sized, C: PrimeChecker<Value=Self::Value> { Combine::new(self, checker) } }
#![allow(dead_code)] use crate::{ components::*, ecs::{systems::ParallelRunnable, *}, }; use smallvec::SmallVec; use std::collections::HashMap; pub fn build() -> impl ParallelRunnable { SystemBuilder::<()>::new("ParentUpdateSystem") // Entities with a removed `Parent` .with_query(<(Entity, Read<PreviousParent>)>::query().filter(!component::<Parent>())) // Entities with a changed `Parent` .with_query( <(Entity, Read<Parent>, Write<PreviousParent>)>::query().filter( component::<LocalToParent>() & component::<LocalToWorld>() & maybe_changed::<Parent>(), ), ) // Deleted Parents (ie Entities with `Children` and without a `LocalToWorld`). .with_query(<(Entity, Read<Children>)>::query().filter(!component::<LocalToWorld>())) .write_component::<Children>() .build(move |commands, world, _resource, queries| { // Entities with a missing `Parent` (ie. ones that have a `PreviousParent`), remove // them from the `Children` of the `PreviousParent`. let (ref mut left, ref mut right) = world.split::<Write<Children>>(); for (entity, previous_parent) in queries.0.iter(right) { log::trace!("Parent was removed from {:?}", entity); if let Some(previous_parent_entity) = previous_parent.0 { if let Some(previous_parent_children) = left .entry_mut(previous_parent_entity) .and_then(|entry| entry.into_component_mut::<Children>().ok()) { log::trace!(" > Removing {:?} from it's prev parent's children", entity); previous_parent_children.0.retain(|e| e != entity); } } } // Tracks all newly created `Children` Components this frame. let mut children_additions = HashMap::<Entity, SmallVec<[Entity; 8]>>::with_capacity(16); // Entities with a changed Parent (that also have a PreviousParent, even if None) for (entity, parent, previous_parent) in queries.1.iter_mut(right) { log::trace!("Parent changed for {:?}", entity); // If the `PreviousParent` is not None. if let Some(previous_parent_entity) = previous_parent.0 { // New and previous point to the same Entity, carry on, nothing to see here. if previous_parent_entity == parent.0 { log::trace!(" > But the previous parent is the same, ignoring..."); continue; } // Remove from `PreviousParent.Children`. if let Some(previous_parent_children) = left .entry_mut(previous_parent_entity) .and_then(|entry| entry.into_component_mut::<Children>().ok()) { log::trace!(" > Removing {:?} from prev parent's children", entity); previous_parent_children.0.retain(|e| e != entity); } } // Set `PreviousParent = Parent`. *previous_parent = PreviousParent(Some(parent.0)); // Add to the parent's `Children` (either the real component, or // `children_additions`). log::trace!("Adding {:?} to it's new parent {:?}", entity, parent.0); if let Some(new_parent_children) = left .entry_mut(parent.0) .and_then(|entry| entry.into_component_mut::<Children>().ok()) { // This is the parent log::trace!( " > The new parent {:?} already has a `Children`, adding to it.", parent.0 ); new_parent_children.0.push(*entity); } else { // The parent doesn't have a children entity, lets add it log::trace!( "The new parent {:?} doesn't yet have `Children` component.", parent.0 ); children_additions .entry(parent.0) .or_insert_with(Default::default) .push(*entity); } } // Deleted `Parents` (ie. Entities with a `Children` but no `LocalToWorld`). for (entity, children) in queries.2.iter(world) { log::trace!("The entity {:?} doesn't have a LocalToWorld", entity); if children_additions.remove(&entity).is_none() { log::trace!(" > It needs to be remove from the ECS."); for child_entity in children.0.iter() { commands.remove_component::<Parent>(*child_entity); commands.remove_component::<PreviousParent>(*child_entity); commands.remove_component::<LocalToParent>(*child_entity); } commands.remove_component::<Children>(*entity); } else { log::trace!(" > It was a new addition, removing it from additions map"); } } // Flush the `children_additions` to the command buffer. It is stored separate to // collect multiple new children that point to the same parent into the same // SmallVec, and to prevent redundant add+remove operations. children_additions.iter().for_each(|(k, v)| { log::trace!( "Flushing: Entity {:?} adding `Children` component {:?}", k, v ); commands.add_component(*k, Children::with(v)); }); }) } #[cfg(test)] mod test { use super::*; use crate::missing_previous_parent_system; #[test] fn correct_children() { let _ = env_logger::builder().is_test(true).try_init(); let mut resources = Resources::default(); let mut world = World::default(); let mut schedule = Schedule::builder() .add_system(missing_previous_parent_system::build()) .flush() .add_system(build()) .build(); // Add parent entities let parent = world.push((Translation::identity(), LocalToWorld::identity())); let children = world.extend(vec![ ( Translation::identity(), LocalToParent::identity(), LocalToWorld::identity(), ), ( Translation::identity(), LocalToParent::identity(), LocalToWorld::identity(), ), ]); let (e1, e2) = (children[0], children[1]); // Parent `e1` and `e2` to `parent`. world.entry(e1).unwrap().add_component(Parent(parent)); world.entry(e2).unwrap().add_component(Parent(parent)); schedule.execute(&mut world, &mut resources); assert_eq!( world .entry(parent) .unwrap() .get_component::<Children>() .unwrap() .0 .iter() .cloned() .collect::<Vec<_>>(), vec![e1, e2] ); // Parent `e1` to `e2`. world .entry_mut(e1) .unwrap() .get_component_mut::<Parent>() .unwrap() .0 = e2; // Run the systems schedule.execute(&mut world, &mut resources); assert_eq!( world .entry(parent) .unwrap() .get_component::<Children>() .unwrap() .0 .iter() .cloned() .collect::<Vec<_>>(), vec![e2] ); assert_eq!( world .entry(e2) .unwrap() .get_component::<Children>() .unwrap() .0 .iter() .cloned() .collect::<Vec<_>>(), vec![e1] ); world.remove(e1); // Run the systems schedule.execute(&mut world, &mut resources); assert_eq!( world .entry(parent) .unwrap() .get_component::<Children>() .unwrap() .0 .iter() .cloned() .collect::<Vec<_>>(), vec![e2] ); } }
//! Common functions, definitions and extensions for parsing and code generation //! of `#[graphql(rename_all = ...)]` attribute. use std::str::FromStr; use syn::parse::{Parse, ParseStream}; /// Possible ways to rename all [GraphQL fields][1] or [GrqphQL enum values][2]. /// /// [1]: https://spec.graphql.org/October2021#sec-Language.Fields /// [2]: https://spec.graphql.org/October2021#sec-Enum-Value #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum Policy { /// Do nothing, and use the default conventions renaming. None, /// Rename in `camelCase` style. CamelCase, /// Rename in `SCREAMING_SNAKE_CASE` style. ScreamingSnakeCase, } impl Policy { /// Applies this [`Policy`] to the given `name`. pub(crate) fn apply(&self, name: &str) -> String { match self { Self::None => name.into(), Self::CamelCase => to_camel_case(name), Self::ScreamingSnakeCase => to_upper_snake_case(name), } } } impl FromStr for Policy { type Err = (); fn from_str(rule: &str) -> Result<Self, Self::Err> { match rule { "none" => Ok(Self::None), "camelCase" => Ok(Self::CamelCase), "SCREAMING_SNAKE_CASE" => Ok(Self::ScreamingSnakeCase), _ => Err(()), } } } impl TryFrom<syn::LitStr> for Policy { type Error = syn::Error; fn try_from(lit: syn::LitStr) -> syn::Result<Self> { Self::from_str(&lit.value()) .map_err(|_| syn::Error::new(lit.span(), "unknown renaming policy")) } } impl Parse for Policy { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { Self::try_from(input.parse::<syn::LitStr>()?) } } // NOTE: duplicated from juniper crate! fn to_camel_case(s: &str) -> String { let mut dest = String::new(); // Handle `_` and `__` to be more friendly with the `_var` convention for // unused variables, and GraphQL introspection identifiers. let s_iter = if let Some(s) = s.strip_prefix("__") { dest.push_str("__"); s } else { s.strip_prefix('_').unwrap_or(s) } .split('_') .enumerate(); for (i, part) in s_iter { if i > 0 && part.len() == 1 { dest.push_str(&part.to_uppercase()); } else if i > 0 && part.len() > 1 { let first = part .chars() .next() .unwrap() .to_uppercase() .collect::<String>(); let second = &part[1..]; dest.push_str(&first); dest.push_str(second); } else if i == 0 { dest.push_str(part); } } dest } fn to_upper_snake_case(s: &str) -> String { let mut last_lower = false; let mut upper = String::new(); for c in s.chars() { if c == '_' { last_lower = false; } else if c.is_lowercase() { last_lower = true; } else if c.is_uppercase() { if last_lower { upper.push('_'); } last_lower = false; } for u in c.to_uppercase() { upper.push(u); } } upper } #[cfg(test)] mod to_camel_case_tests { use super::to_camel_case; #[test] fn converts_correctly() { for (input, expected) in [ ("test", "test"), ("_test", "test"), ("__test", "__test"), ("first_second", "firstSecond"), ("first_", "first"), ("a_b_c", "aBC"), ("a_bc", "aBc"), ("a_b", "aB"), ("a", "a"), ("", ""), ] { assert_eq!(to_camel_case(input), expected); } } } #[cfg(test)] mod to_upper_snake_case_tests { use super::to_upper_snake_case; #[test] fn converts_correctly() { for (input, expected) in [ ("abc", "ABC"), ("a_bc", "A_BC"), ("ABC", "ABC"), ("A_BC", "A_BC"), ("SomeInput", "SOME_INPUT"), ("someInput", "SOME_INPUT"), ("someINpuT", "SOME_INPU_T"), ("some_INpuT", "SOME_INPU_T"), ] { assert_eq!(to_upper_snake_case(input), expected); } } }
use std::string::CowString; use std::fmt; use std::collections::HashMap; use std::rc::Rc; use std::ops::Deref; use error::{CompileError, CompileErrorKind, RuntimeError}; use datum::Datum; use runtime::{Inst, MemRef, RDatum, RuntimeData, Closure}; /// Syntax variables #[derive(Copy, Clone, PartialEq)] pub enum Syntax { /// `lambda` syntax Lambda } /// Environment variables in the global environment pub enum EnvVar { /// Syntax variables Syntax(Syntax), /// Primitive functions PrimFunc(&'static str, Rc<fn(&[RDatum]) -> Result<RDatum, RuntimeError>>), /// Compiled library functions Closure(Closure) } /// Compiler compiles Datum into a bytecode evaluates it pub struct Compiler<'g> { /// Global environment global_env: &'g HashMap<CowString<'static>, EnvVar> } impl<'g> Compiler<'g> { /// Creates a new compiler with given environment pub fn new<'a>(global_env: &'a HashMap<CowString<'static>, EnvVar>) -> Compiler<'a> { Compiler { global_env: global_env } } /// Compiles the datum into a bytecode evaluates it pub fn compile(&mut self, datum: &RDatum) -> Result<Vec<Inst>, CompileError> { let mut link_size = 0; let mut code = try!(self.compile_expr(&[], &[], &mut link_size, datum)); code.push(Inst::Return); return Ok(code); } fn compile_call(&mut self, static_scope: &[Vec<CowString<'static>>], args: &[CowString<'static>], link_size: &mut usize, datum: &RDatum) -> Result<Vec<Inst>, CompileError> { let mut code = Vec::new(); let mut arg_count = 0; for d in datum.iter() { match d { Ok(d) => { code.push_all(try!(self.compile_expr(static_scope, args, link_size, &d)).as_slice()); arg_count += 1; }, Err(()) => return Err(CompileError { kind: CompileErrorKind::DottedEval }) } } if arg_count == 0 { Err(CompileError { kind: CompileErrorKind::NullEval }) } else { code.push(Inst::Call(arg_count - 1)); Ok(code) } } fn compile_expr(&mut self, static_scope: &[Vec<CowString<'static>>], args: &[CowString<'static>], link_size: &mut usize, datum: &RDatum) -> Result<Vec<Inst>, CompileError> { match datum { &Datum::Cons(ref h, ref t) => if let &Datum::Sym(ref n) = h.borrow().deref() { if let Some(&EnvVar::Syntax(Syntax::Lambda)) = self.global_env.get(n) { if let &Datum::Cons(ref cur_args, ref body) = t.borrow().deref() { let new_stackenv = { let mut nenv = static_scope.to_vec(); nenv.push(args.to_vec()); nenv }; let new_args = { let mut nargs = Vec::new(); for arg in cur_args.borrow().iter() { if let Ok(Datum::Sym(s)) = arg { nargs.push(s) } else { return Err(CompileError { kind: CompileErrorKind::BadLambdaSyntax }); } } nargs }; let mut new_link_size = 0; let mut code = Vec::new(); for expr in body.borrow().iter() { if let Ok(e) = expr { let piece = try!(self.compile_expr( new_stackenv.as_slice(), new_args.as_slice(), &mut new_link_size, &e)); code.push_all(piece.as_slice()); } else { return Err(CompileError { kind: CompileErrorKind::DottedBody }); } } code.push(Inst::Return); return Ok(vec![Inst::PushArg(MemRef::Closure(Rc::new(code), new_link_size))]); } else { return Err(CompileError { kind: CompileErrorKind::BadLambdaSyntax }) } } else { self.compile_call(static_scope, args, link_size, datum) } } else { self.compile_call(static_scope, args, link_size, datum) }, &Datum::Nil => Err(CompileError { kind: CompileErrorKind::NullEval }), &Datum::Sym(ref sym) => { if let Some(i) = range(0, args.len()).find(|&i| args[i] == *sym) { return Ok(vec![Inst::PushArg(MemRef::Arg(i))]) } // (0, static_scope[-1]), (1, static_scope[-2]), (2, static_scope[-3]), ... for (i, up_args) in static_scope.iter().rev().enumerate() { for (j, arg) in up_args.iter().enumerate() { if *arg == *sym { if *link_size < i+1 { *link_size = i+1; } return Ok(vec![Inst::PushArg(MemRef::UpValue(i, j))]); } } } match self.global_env.get(sym) { Some(data) => match data { &EnvVar::Syntax(_) => Err(CompileError { kind: CompileErrorKind::SyntaxReference }), &EnvVar::PrimFunc(ref name, ref func) => Ok(vec![Inst::PushArg(MemRef::Const(Datum::Ext(RuntimeData::PrimFunc(name.clone(), func.clone()))))]), &EnvVar::Closure(ref closure) => Ok(vec![Inst::PushArg(MemRef::Const(Datum::Ext(RuntimeData::Closure(closure.clone()))))]) }, None => Err(CompileError { kind: CompileErrorKind::UnboundVariable }) } }, _ => Ok(vec![Inst::PushArg(MemRef::Const(datum.clone()))]) } } } impl fmt::Show for Syntax { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "lambda") } } #[cfg(test)] mod test { use std::borrow::Cow; use std::rc::Rc; use datum::Datum; use runtime::{Inst, MemRef, RuntimeData}; use base::libbase; use primitive::PRIM_ADD; use super::Compiler; #[test] fn test_simple_expr() { let env = libbase(); let mut compiler = Compiler::new(&env); let expected = Ok(vec![ Inst::PushArg(MemRef::Const(Datum::Ext(RuntimeData::PrimFunc("+", Rc::new(PRIM_ADD))))), Inst::PushArg(MemRef::Const(Datum::Num(1))), Inst::PushArg(MemRef::Const(Datum::Num(2))), Inst::Call(2), Inst::Return ]); let code = compiler.compile(&list![sym!("+"), num!(1), num!(2)]); assert_eq!(expected, code); } #[test] fn test_nested_expr() { let env = libbase(); let mut compiler = Compiler::new(&env); let expected = Ok(vec![ Inst::PushArg(MemRef::Const(Datum::Ext(RuntimeData::PrimFunc("+", Rc::new(PRIM_ADD))))), Inst::PushArg(MemRef::Const(Datum::Num(3))), Inst::PushArg(MemRef::Const(Datum::Ext(RuntimeData::PrimFunc("+", Rc::new(PRIM_ADD))))), Inst::PushArg(MemRef::Const(Datum::Num(1))), Inst::PushArg(MemRef::Const(Datum::Num(2))), Inst::Call(2), Inst::Call(2), Inst::Return ]); let code = compiler.compile(&list![sym!("+"), num!(3), list![sym!("+"), num!(1), num!(2)]]); assert_eq!(expected, code); } #[test] fn test_lambda() { let env = libbase(); let mut compiler = Compiler::new(&env); let f = vec![ Inst::PushArg(MemRef::Const(Datum::Ext(RuntimeData::PrimFunc("+", Rc::new(PRIM_ADD))))), Inst::PushArg(MemRef::Arg(0)), Inst::PushArg(MemRef::Const(Datum::Num(2))), Inst::Call(2), Inst::Return ]; let expected = Ok(vec![ Inst::PushArg(MemRef::Closure(Rc::new(f), 0)), Inst::PushArg(MemRef::Const(Datum::Num(1))), Inst::Call(1), Inst::Return ]); let code = compiler.compile(&list![ list![sym!("lambda"), list![sym!("x")], list![sym!("+"), sym!("x"), num!(2)]], num!(1)]); assert_eq!(expected, code); } #[test] fn test_upvalue() { let env = libbase(); let mut compiler = Compiler::new(&env); let f = vec![ Inst::PushArg(MemRef::Const(Datum::Ext(RuntimeData::PrimFunc("+", Rc::new(PRIM_ADD))))), Inst::PushArg(MemRef::UpValue(0, 0)), Inst::PushArg(MemRef::Arg(0)), Inst::Call(2), Inst::Return ]; let g = vec![ Inst::PushArg(MemRef::Closure(Rc::new(f), 1)), Inst::Return ]; let expected = Ok(vec![ Inst::PushArg(MemRef::Closure(Rc::new(g), 0)), Inst::PushArg(MemRef::Const(Datum::Num(2))), Inst::Call(1), Inst::PushArg(MemRef::Const(Datum::Num(3))), Inst::Call(1), Inst::Return ]); // (( // (lambda (x) # = g // (lambda (y) (+ x y)) # = f // ) 2) 3) let code = compiler.compile(&list![ list![ list![sym!("lambda"), list![sym!("x")], list![sym!("lambda"), list![sym!("y")], list![sym!("+"), sym!("x"), sym!("y")]]], num!(2)], num!(3) ]); assert_eq!(expected, code) } }
use std::process::Command; use std::io::{self, Write}; // use std::env; fn main() { let output = Command::new("php.exe") .env("PATH", r#"C:\Applications\phpstack\php74"#) .arg("-v") .output() .expect("Gagal menjalankan perintah"); io::stdout().write_all(&output.stdout).unwrap(); }
use bit_set::BitSet; use fxhash::FxHashMap; use std::default::Default; use aspect::{Aspect, Matcher}; use component::{Component, ComponentManager}; pub type Entity = usize; pub struct EntityEditor<'a> { pub entity: Entity, entity_manager: &'a mut EntityManager, } impl<'a> EntityEditor<'a> { fn new(entity: Entity, entity_manager: &'a mut EntityManager) -> Self { EntityEditor { entity, entity_manager, } } pub fn add<T: Component>(&mut self, component: T) { self.entity_manager.add(self.entity, component); } pub fn remove<T: Component>(&mut self) -> T { self.entity_manager.remove(self.entity) } pub fn contains<T: Component>(&self) -> bool { self.entity_manager.contains::<T>(self.entity) } pub fn get<T: Component>(&self) -> Option<&T> { self.entity_manager.get::<T>(self.entity) } pub fn get_mut<T: Component>(&mut self) -> Option<&mut T> { self.entity_manager.get_mut::<T>(self.entity) } pub fn destroy(mut self) { self.entity_manager.destroy(self.entity); } pub fn commit(mut self) { self.entity_manager.commit(self.entity); } } #[derive(Default)] pub(crate) struct EntityManager { entity_storage: EntityStorage, states: EntityStates, index: AspectIndex, pub component_manager: ComponentManager, } impl EntityManager { pub fn new() -> Self { Default::default() } pub fn create(&mut self) -> EntityEditor { let entity = self.entity_storage.create(); // fuck the borrow checker { let bits = self.states.get(entity, true); self.index.update(&self.component_manager, entity, bits); } self.editor(entity) } pub fn editor(&mut self, entity: Entity) -> EntityEditor { if !self.entity_storage.is_alive(entity) { panic!("Entity {} not alived!", entity); } EntityEditor::new(entity, self) } pub fn entities<T: Aspect>(&self) -> Vec<Entity> { self.index.entities::<T>(&self.component_manager) } pub fn is_alive(&self, entity: Entity) -> bool { self.entity_storage.is_alive(entity) } pub fn register<T: Aspect>(&mut self) { self.index.register::<T>(&self.component_manager) } // entity manipulation methods fn add<T: Component>(&mut self, entity: Entity, component: T) { unimplemented!(); } fn remove<T: Component>(&mut self, entity: Entity) -> T { unimplemented!(); } fn contains<T: Component>(&self, entity: Entity) -> bool { unimplemented!(); } fn get<T: Component>(&self, entity: Entity) -> Option<&T> { unimplemented!(); } fn get_mut<T: Component>(&mut self, entity: Entity) -> Option<&mut T> { unimplemented!(); } fn destroy(&mut self, entity: Entity) { self.entity_storage.destroy(entity); // clear state self.states.get(entity, true); self.index.remove(&self.component_manager, entity); } fn commit(&mut self, entity: Entity) { let bits = self.states.get(entity, false); self.index.update(&self.component_manager, entity, bits); } } #[derive(Default)] struct EntityStates { state: FxHashMap<Entity, BitSet>, } impl EntityStates { fn new() -> Self { Default::default() } fn get(&mut self, entity: Entity, reset: bool) -> &mut BitSet { if !self.state.contains_key(&entity) || reset { self.state.insert(entity, BitSet::new()); } self.state.get_mut(&entity).expect("state not found!") } } #[derive(Default)] struct AspectIndex { index: FxHashMap<Matcher, BitSet>, } impl AspectIndex { fn new() -> Self { Default::default() } fn register<T: Aspect>(&mut self, component_manager: &ComponentManager) { let matcher = Matcher::new::<T>(component_manager); // TODO: should we fail if it exists? if !self.index.contains_key(&matcher) { self.index.insert(matcher, BitSet::new()); } } fn update(&mut self, component_manager: &ComponentManager, entity: Entity, bits: &BitSet) { for (matcher, entities) in self.index.iter_mut() { if entities.contains(entity) { if !matcher.check(component_manager, bits) { entities.remove(entity); } } else { if matcher.check(component_manager, bits) { entities.insert(entity); } } } } fn remove(&mut self, component_manager: &ComponentManager, entity: Entity) { for (_, entities) in self.index.iter_mut() { entities.remove(entity); } } fn entities<T: Aspect>(&self, component_manager: &ComponentManager) -> Vec<Entity> { let matcher = Matcher::new::<T>(component_manager); if self.index.contains_key(&matcher) { let mut result = Vec::new(); let index = self.index.get(&matcher).unwrap(); for entity in index.iter() { result.push(entity); } return result; } panic!("Aspect not registered!"); } } #[derive(Default)] struct EntityStorage { next_id: usize, alive: BitSet, limbo: Vec<Entity>, } impl EntityStorage { fn new() -> Self { Default::default() } fn is_alive(&self, entity: Entity) -> bool { self.alive.contains(entity) } fn create(&mut self) -> Entity { let id = if self.limbo.is_empty() { self.next_id() } else { self.limbo.remove(0) }; self.alive.insert(id); id } fn destroy(&mut self, entity: Entity) { if self.is_alive(entity) { self.limbo.push(entity); self.alive.remove(entity); } else { panic!("Entity is not alive!"); } } fn next_id(&mut self) -> Entity { self.next_id = self.next_id + 1; self.next_id } } trait ComponentSetter { fn set_bit(component_manager: &ComponentManager, bits: &mut BitSet); fn unset_bit(component_manager: &ComponentManager, bits: &mut BitSet); } impl<T> ComponentSetter for T where T: Component + 'static, { fn set_bit(component_manager: &ComponentManager, bits: &mut BitSet) { bits.insert(component_manager.id::<T>()); } fn unset_bit(component_manager: &ComponentManager, bits: &mut BitSet) { bits.remove(component_manager.id::<T>()); } } #[cfg(test)] mod tests { use super::*; #[test] fn entity_storage_create_unique() { let mut storage = EntityStorage::new(); assert_ne!(storage.create(), storage.create()); } #[test] fn entity_storage_alive() { let mut storage = EntityStorage::new(); let entity = storage.create(); assert!(storage.is_alive(entity)); } #[test] fn entity_storage_reuse_entity() { let mut storage = EntityStorage::new(); let entity = storage.create(); storage.destroy(entity); let new_entity = storage.create(); assert_eq!(entity, new_entity); } #[test] fn entity_storage_destroy() { let mut storage = EntityStorage::new(); let entity = storage.create(); storage.destroy(entity); assert!(!storage.is_alive(entity)); } #[test] #[should_panic] fn entity_storage_destroy_dead() { let mut storage = EntityStorage::new(); storage.destroy(1); } #[test] fn entity_states_get_not_existing() { let mut states = EntityStates::new(); assert_eq!(0, states.get(0, false).len()); } #[test] fn entity_states_get_existing() { let mut states = EntityStates::new(); states.get(0, false).insert(1); assert!(states.get(0, false).contains(1)); } #[test] fn entity_states_get_existing_init() { let mut states = EntityStates::new(); states.get(0, false).insert(1); assert!(!states.get(0, true).contains(1)); } use super::super::storage::VecStorage; #[derive(Default)] struct MyComponent; impl Component for MyComponent { type Storage = VecStorage<Self>; } #[derive(Default)] struct AnotherComponent; impl Component for AnotherComponent { type Storage = VecStorage<Self>; } #[test] fn aspect_index_initially_empty() { let mut component_manager = ComponentManager::new(); component_manager.register::<MyComponent>(); component_manager.register::<AnotherComponent>(); let mut index = AspectIndex::new(); type MyAspect = (MyComponent, AnotherComponent); index.register::<MyAspect>(&component_manager); assert!(index.entities::<MyAspect>(&component_manager).is_empty()); } #[test] #[should_panic] fn aspect_index_not_registered() { let mut component_manager = ComponentManager::new(); component_manager.register::<MyComponent>(); component_manager.register::<AnotherComponent>(); let mut index = AspectIndex::new(); type MyAspect = (MyComponent, AnotherComponent); index.entities::<MyAspect>(&component_manager); } #[test] fn aspect_index_insert() { let mut component_manager = ComponentManager::new(); component_manager.register::<MyComponent>(); component_manager.register::<AnotherComponent>(); let mut index = AspectIndex::new(); type MyAspect = (MyComponent, AnotherComponent); index.register::<MyAspect>(&component_manager); let entity = 1; let mut bits = BitSet::new(); MyComponent::set_bit(&component_manager, &mut bits); AnotherComponent::set_bit(&component_manager, &mut bits); index.update(&component_manager, entity, &bits); assert!( index .entities::<MyAspect>(&component_manager) .contains(&entity) ); } #[test] fn aspect_index_removal() { let mut component_manager = ComponentManager::new(); component_manager.register::<MyComponent>(); component_manager.register::<AnotherComponent>(); let mut index = AspectIndex::new(); type MyAspect = (MyComponent, AnotherComponent); index.register::<MyAspect>(&component_manager); let entity = 1; let mut bits = BitSet::new(); // first pass MyComponent::set_bit(&component_manager, &mut bits); AnotherComponent::set_bit(&component_manager, &mut bits); index.update(&component_manager, entity, &bits); // sometime later AnotherComponent::unset_bit(&component_manager, &mut bits); index.update(&component_manager, entity, &bits); assert!(!index .entities::<MyAspect>(&component_manager) .contains(&entity)); } #[test] fn aspect_index_explicit_removal() { let mut component_manager = ComponentManager::new(); component_manager.register::<MyComponent>(); component_manager.register::<AnotherComponent>(); let mut index = AspectIndex::new(); type MyAspect = (MyComponent, AnotherComponent); index.register::<MyAspect>(&component_manager); let entity = 1; let mut bits = BitSet::new(); // first pass MyComponent::set_bit(&component_manager, &mut bits); AnotherComponent::set_bit(&component_manager, &mut bits); index.update(&component_manager, entity, &bits); // sometime later index.remove(&component_manager, entity); assert!(!index .entities::<MyAspect>(&component_manager) .contains(&entity)); } #[test] fn entity_manager_existing() { let mut entity_manager = EntityManager::new(); let entity = entity_manager.create().entity; assert_eq!(entity, entity_manager.editor(entity).entity); } #[test] #[should_panic] fn entity_manager_not_existing() { let mut entity_manager = EntityManager::new(); entity_manager.editor(1); } }
extern crate advent_lib; use advent_lib::chris::day_1::{Direction, TurnDirection, direction_now_facing, string_to_turn_direction, day_1}; use advent_lib::input_reader; #[test] fn direction_facing_test() { assert_eq!(direction_now_facing(TurnDirection::Left, Direction::South), Direction::East); assert_eq!(direction_now_facing(TurnDirection::Left, Direction::North), Direction::West); assert_eq!(direction_now_facing(TurnDirection::Left, Direction::West), Direction::South); assert_eq!(direction_now_facing(TurnDirection::Left, Direction::East), Direction::North); assert_eq!(direction_now_facing(TurnDirection::Right, Direction::South), Direction::West); assert_eq!(direction_now_facing(TurnDirection::Right, Direction::North), Direction::East); assert_eq!(direction_now_facing(TurnDirection::Right, Direction::West), Direction::North); assert_eq!(direction_now_facing(TurnDirection::Right, Direction::East), Direction::South); } #[test] fn turn_string_to_turn_direction_test() { assert_eq!(string_to_turn_direction('L'), TurnDirection::Left); assert_eq!(string_to_turn_direction('R'), TurnDirection::Right); } #[test] fn day_1_test() { let mut s = String::new(); input_reader::read_file("src/resources/day1/chris_input.txt", &mut s); day_1(s); // Uncomment to see output of day_1 // assert_eq!(true, false); }
use mime_guess::Mime; use orfail::OrFail; use std::io::{BufRead, BufReader, Read, Write}; use url::Url; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum HttpMethod { Head, Get, // rofis original method. Watch, } #[derive(Debug)] pub struct HttpRequest { method: HttpMethod, path: String, } impl HttpRequest { pub fn from_reader<R: Read>(reader: R) -> orfail::Result<Result<Self, HttpResponse>> { let mut reader = BufReader::new(reader); let mut buf = String::new(); reader.read_line(&mut buf).or_fail()?; let mut line = &buf[..]; if !line.ends_with(" HTTP/1.1\r\n") { return Ok(Err(HttpResponse::bad_request())); } // Method. let method = if line.starts_with("GET ") { line = &line["GET ".len()..]; HttpMethod::Get } else if line.starts_with("HEAD ") { line = &line["HEAD ".len()..]; HttpMethod::Head } else if line.starts_with("WATCH ") { line = &line["WATCH ".len()..]; HttpMethod::Watch } else { return Ok(Err(HttpResponse::method_not_allowed())); }; // Path. if !line.starts_with('/') { return Ok(Err(HttpResponse::bad_request())); } let path = &line[..line.find(" HTTP/1.1\r\n").or_fail()?]; let Ok(url) = Url::options() .base_url(Some(&Url::parse("http://localhost/").or_fail()?)) .parse(path) else { return Ok(Err(HttpResponse::bad_request())); }; // Header. loop { buf.clear(); reader.read_line(&mut buf).or_fail()?; if buf == "\r\n" { break; } } Ok(Ok(Self { method, path: url.path().to_owned(), })) } pub fn method(&self) -> HttpMethod { self.method } pub fn path(&self) -> &str { &self.path } } pub struct HttpResponse { status: &'static str, header: Vec<(&'static str, String)>, body: HttpResponseBody, } impl HttpResponse { pub fn bad_request() -> Self { Self { status: "400 Bad Request", header: Vec::new(), body: HttpResponseBody::Content(b"Bad Request".to_vec()), } } pub fn not_found() -> Self { Self { status: "404 Not Found", header: Vec::new(), body: HttpResponseBody::Content(b"Not Found".to_vec()), } } pub fn method_not_allowed() -> Self { Self { status: "405 Method Not Allowed", header: vec![("Allow", "GET, HEAD".to_owned())], body: HttpResponseBody::Content(b"Method Not Allowed".to_vec()), } } pub fn multiple_choices(candidates: usize) -> Self { Self { status: "303 Multiple Choices", header: Vec::new(), body: HttpResponseBody::Content( format!("Multiple Choices: {candidates} candidates").into_bytes(), ), } } pub fn internal_server_error() -> Self { Self { status: "500 Internal Server Error", header: Vec::new(), body: HttpResponseBody::Content(b"Internal Server Error".to_vec()), } } pub fn ok(mime: Mime, body: HttpResponseBody) -> Self { Self { status: "200 OK", header: vec![("Content-Type", mime.to_string())], body, } } pub fn is_not_found(&self) -> bool { self.status == "404 Not Found" } pub fn to_writer<W: Write>(&self, writer: &mut W) -> orfail::Result<()> { write!(writer, "HTTP/1.1 {}\r\n", self.status).or_fail()?; write!(writer, "Content-Length: {}\r\n", self.body.len()).or_fail()?; write!(writer, "Connection: close\r\n").or_fail()?; for (name, value) in &self.header { write!(writer, "{name}: {value}\r\n").or_fail()?; } write!(writer, "\r\n").or_fail()?; if let HttpResponseBody::Content(content) = &self.body { writer.write_all(content).or_fail()?; } Ok(()) } } impl std::fmt::Debug for HttpResponse { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "HttpResponse {{ status: {:?}, body: {} bytes }}", self.status, self.body.len() ) } } #[derive(Debug)] pub enum HttpResponseBody { Content(Vec<u8>), Length(usize), } impl HttpResponseBody { pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn len(&self) -> usize { match self { HttpResponseBody::Content(x) => x.len(), HttpResponseBody::Length(x) => *x, } } }
#[doc = r"Value read from the register"] pub struct R { bits: u16, } #[doc = r"Value to write to the register"] pub struct W { bits: u16, } impl super::DMACTL5 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u16 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct USB_DMACTL5_ENABLER { bits: bool, } impl USB_DMACTL5_ENABLER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DMACTL5_ENABLEW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL5_ENABLEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u16) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct USB_DMACTL5_DIRR { bits: bool, } impl USB_DMACTL5_DIRR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DMACTL5_DIRW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL5_DIRW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u16) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct USB_DMACTL5_MODER { bits: bool, } impl USB_DMACTL5_MODER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DMACTL5_MODEW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL5_MODEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u16) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct USB_DMACTL5_IER { bits: bool, } impl USB_DMACTL5_IER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DMACTL5_IEW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL5_IEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u16) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct USB_DMACTL5_EPR { bits: u8, } impl USB_DMACTL5_EPR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _USB_DMACTL5_EPW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL5_EPW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(15 << 4); self.w.bits |= ((value as u16) & 15) << 4; self.w } } #[doc = r"Value of the field"] pub struct USB_DMACTL5_ERRR { bits: bool, } impl USB_DMACTL5_ERRR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DMACTL5_ERRW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL5_ERRW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 8); self.w.bits |= ((value as u16) & 1) << 8; self.w } } #[doc = "Possible values of the field `USB_DMACTL5_BRSTM`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USB_DMACTL5_BRSTMR { #[doc = "Bursts of unspecified length"] USB_DMACTL5_BRSTM_ANY, #[doc = "INCR4 or unspecified length"] USB_DMACTL5_BRSTM_INC4, #[doc = "INCR8, INCR4 or unspecified length"] USB_DMACTL5_BRSTM_INC8, #[doc = "INCR16, INCR8, INCR4 or unspecified length"] USB_DMACTL5_BRSTM_INC16, } impl USB_DMACTL5_BRSTMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { USB_DMACTL5_BRSTMR::USB_DMACTL5_BRSTM_ANY => 0, USB_DMACTL5_BRSTMR::USB_DMACTL5_BRSTM_INC4 => 1, USB_DMACTL5_BRSTMR::USB_DMACTL5_BRSTM_INC8 => 2, USB_DMACTL5_BRSTMR::USB_DMACTL5_BRSTM_INC16 => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> USB_DMACTL5_BRSTMR { match value { 0 => USB_DMACTL5_BRSTMR::USB_DMACTL5_BRSTM_ANY, 1 => USB_DMACTL5_BRSTMR::USB_DMACTL5_BRSTM_INC4, 2 => USB_DMACTL5_BRSTMR::USB_DMACTL5_BRSTM_INC8, 3 => USB_DMACTL5_BRSTMR::USB_DMACTL5_BRSTM_INC16, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `USB_DMACTL5_BRSTM_ANY`"] #[inline(always)] pub fn is_usb_dmactl5_brstm_any(&self) -> bool { *self == USB_DMACTL5_BRSTMR::USB_DMACTL5_BRSTM_ANY } #[doc = "Checks if the value of the field is `USB_DMACTL5_BRSTM_INC4`"] #[inline(always)] pub fn is_usb_dmactl5_brstm_inc4(&self) -> bool { *self == USB_DMACTL5_BRSTMR::USB_DMACTL5_BRSTM_INC4 } #[doc = "Checks if the value of the field is `USB_DMACTL5_BRSTM_INC8`"] #[inline(always)] pub fn is_usb_dmactl5_brstm_inc8(&self) -> bool { *self == USB_DMACTL5_BRSTMR::USB_DMACTL5_BRSTM_INC8 } #[doc = "Checks if the value of the field is `USB_DMACTL5_BRSTM_INC16`"] #[inline(always)] pub fn is_usb_dmactl5_brstm_inc16(&self) -> bool { *self == USB_DMACTL5_BRSTMR::USB_DMACTL5_BRSTM_INC16 } } #[doc = "Values that can be written to the field `USB_DMACTL5_BRSTM`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USB_DMACTL5_BRSTMW { #[doc = "Bursts of unspecified length"] USB_DMACTL5_BRSTM_ANY, #[doc = "INCR4 or unspecified length"] USB_DMACTL5_BRSTM_INC4, #[doc = "INCR8, INCR4 or unspecified length"] USB_DMACTL5_BRSTM_INC8, #[doc = "INCR16, INCR8, INCR4 or unspecified length"] USB_DMACTL5_BRSTM_INC16, } impl USB_DMACTL5_BRSTMW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { USB_DMACTL5_BRSTMW::USB_DMACTL5_BRSTM_ANY => 0, USB_DMACTL5_BRSTMW::USB_DMACTL5_BRSTM_INC4 => 1, USB_DMACTL5_BRSTMW::USB_DMACTL5_BRSTM_INC8 => 2, USB_DMACTL5_BRSTMW::USB_DMACTL5_BRSTM_INC16 => 3, } } } #[doc = r"Proxy"] pub struct _USB_DMACTL5_BRSTMW<'a> { w: &'a mut W, } impl<'a> _USB_DMACTL5_BRSTMW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USB_DMACTL5_BRSTMW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Bursts of unspecified length"] #[inline(always)] pub fn usb_dmactl5_brstm_any(self) -> &'a mut W { self.variant(USB_DMACTL5_BRSTMW::USB_DMACTL5_BRSTM_ANY) } #[doc = "INCR4 or unspecified length"] #[inline(always)] pub fn usb_dmactl5_brstm_inc4(self) -> &'a mut W { self.variant(USB_DMACTL5_BRSTMW::USB_DMACTL5_BRSTM_INC4) } #[doc = "INCR8, INCR4 or unspecified length"] #[inline(always)] pub fn usb_dmactl5_brstm_inc8(self) -> &'a mut W { self.variant(USB_DMACTL5_BRSTMW::USB_DMACTL5_BRSTM_INC8) } #[doc = "INCR16, INCR8, INCR4 or unspecified length"] #[inline(always)] pub fn usb_dmactl5_brstm_inc16(self) -> &'a mut W { self.variant(USB_DMACTL5_BRSTMW::USB_DMACTL5_BRSTM_INC16) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 9); self.w.bits |= ((value as u16) & 3) << 9; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u16 { self.bits } #[doc = "Bit 0 - DMA Transfer Enable"] #[inline(always)] pub fn usb_dmactl5_enable(&self) -> USB_DMACTL5_ENABLER { let bits = ((self.bits >> 0) & 1) != 0; USB_DMACTL5_ENABLER { bits } } #[doc = "Bit 1 - DMA Direction"] #[inline(always)] pub fn usb_dmactl5_dir(&self) -> USB_DMACTL5_DIRR { let bits = ((self.bits >> 1) & 1) != 0; USB_DMACTL5_DIRR { bits } } #[doc = "Bit 2 - DMA Transfer Mode"] #[inline(always)] pub fn usb_dmactl5_mode(&self) -> USB_DMACTL5_MODER { let bits = ((self.bits >> 2) & 1) != 0; USB_DMACTL5_MODER { bits } } #[doc = "Bit 3 - DMA Interrupt Enable"] #[inline(always)] pub fn usb_dmactl5_ie(&self) -> USB_DMACTL5_IER { let bits = ((self.bits >> 3) & 1) != 0; USB_DMACTL5_IER { bits } } #[doc = "Bits 4:7 - Endpoint number"] #[inline(always)] pub fn usb_dmactl5_ep(&self) -> USB_DMACTL5_EPR { let bits = ((self.bits >> 4) & 15) as u8; USB_DMACTL5_EPR { bits } } #[doc = "Bit 8 - Bus Error Bit"] #[inline(always)] pub fn usb_dmactl5_err(&self) -> USB_DMACTL5_ERRR { let bits = ((self.bits >> 8) & 1) != 0; USB_DMACTL5_ERRR { bits } } #[doc = "Bits 9:10 - Burst Mode"] #[inline(always)] pub fn usb_dmactl5_brstm(&self) -> USB_DMACTL5_BRSTMR { USB_DMACTL5_BRSTMR::_from(((self.bits >> 9) & 3) as u8) } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - DMA Transfer Enable"] #[inline(always)] pub fn usb_dmactl5_enable(&mut self) -> _USB_DMACTL5_ENABLEW { _USB_DMACTL5_ENABLEW { w: self } } #[doc = "Bit 1 - DMA Direction"] #[inline(always)] pub fn usb_dmactl5_dir(&mut self) -> _USB_DMACTL5_DIRW { _USB_DMACTL5_DIRW { w: self } } #[doc = "Bit 2 - DMA Transfer Mode"] #[inline(always)] pub fn usb_dmactl5_mode(&mut self) -> _USB_DMACTL5_MODEW { _USB_DMACTL5_MODEW { w: self } } #[doc = "Bit 3 - DMA Interrupt Enable"] #[inline(always)] pub fn usb_dmactl5_ie(&mut self) -> _USB_DMACTL5_IEW { _USB_DMACTL5_IEW { w: self } } #[doc = "Bits 4:7 - Endpoint number"] #[inline(always)] pub fn usb_dmactl5_ep(&mut self) -> _USB_DMACTL5_EPW { _USB_DMACTL5_EPW { w: self } } #[doc = "Bit 8 - Bus Error Bit"] #[inline(always)] pub fn usb_dmactl5_err(&mut self) -> _USB_DMACTL5_ERRW { _USB_DMACTL5_ERRW { w: self } } #[doc = "Bits 9:10 - Burst Mode"] #[inline(always)] pub fn usb_dmactl5_brstm(&mut self) -> _USB_DMACTL5_BRSTMW { _USB_DMACTL5_BRSTMW { w: self } } }
//! O2Jam chart parser module use nom::*; use crate::chart::{Note, TimingPoint}; fn string_from_slice(s: &[u8]) -> String { String::from_utf8_lossy(s).into_owned() } macro_rules! string_block { ($i:expr, $n:expr) => (flat_map!($i, take!($n), map!(take_until!("\0"), string_from_slice))); } mod ojm; // TODO temporary for testing pub use self::ojm::dump_data as ojm_dump; #[derive(Debug)] struct Header { songid: i32, //signature: [u8; 4], encode_version: f32, genre: i32, bpm: f32, level: [i16; 4], event_count: [i32; 3], note_count: [i32; 3], measure_count: [i32; 3], package_count: [i32; 3], old_encode_version: i16, old_songid: i16, old_genre: String, bmp_size: i32, old_file_version: i32, title: String, artist: String, noter: String, ojm_file: String, cover_size: i32, time: [i32; 3], note_offset: [i32; 3], cover_offset: i32, } named!(header(&[u8]) -> Header, do_parse!( songid: le_i32 >> tag!("ojn\0") >> encode_version: le_f32 >> genre: le_i32 >> bpm: le_f32 >> level: count_fixed!(i16, le_i16, 4) >> event_count: count_fixed!(i32, le_i32, 3) >> note_count: count_fixed!(i32, le_i32, 3) >> measure_count: count_fixed!(i32, le_i32, 3) >> package_count: count_fixed!(i32, le_i32, 3) >> old_encode_version: le_i16 >> old_songid: le_i16 >> old_genre: string_block!(20) >> bmp_size: le_i32 >> old_file_version: le_i32 >> title: string_block!(64) >> artist: string_block!(32) >> noter: string_block!(32) >> ojm_file: string_block!(32) >> cover_size: le_i32 >> time: count_fixed!(i32, le_i32, 3) >> note_offset: count_fixed!(i32, le_i32, 3) >> cover_offset: le_i32 >> (Header { songid, encode_version, genre, bpm, level, event_count, note_count, measure_count, package_count, old_encode_version, old_songid, old_genre, bmp_size, old_file_version, title, artist, noter, ojm_file, cover_size, time, note_offset, cover_offset, }) ) ); /// Documentation largely copied from https://open2jam.wordpress.com/2010/10/05/the-notes-section/ #[derive(Debug)] struct PackageHeader { /// This is the measure in which the events inside this package will appear. measure: i32, /// channel meaning /// /// 0 measure fraction /// /// 1 BPM change /// /// 2 note on 1st lane /// /// 3 note on 2nd lane /// /// 4 note on 3rd lane /// /// 5 note on 4th lane(middle button) /// /// 6 note on 5th lane /// /// 7 note on 6th lane /// /// 8 note on 7th lane /// /// 9~22 auto-play samples(?) channel: i16, /// The number of events inside this package events: i16, } named!(package_header(&[u8]) -> PackageHeader, do_parse!( measure: le_i32 >> channel: le_i16 >> events: le_i16 >> (PackageHeader { measure, channel, events }) ) ); /// Documentation largely copied from https://open2jam.wordpress.com/2010/10/05/the-notes-section/ #[derive(Debug)] struct NoteEvent { /// Reference to the sample in the OJM file, unless this value is 0, in which case the entire /// event is ignored value: i16, /// 0..=15, 0 is max volume, volume: u8, /// The panning of the sample, although this can also be controlled using stereo samples, /// further control can be given by using different pans with the same sample (I guess). /// /// 1~7 = left -> center, 0 or 8 = center, 9~15 = center -> right. pan: u8, /// 0 = normal note /// /// 2 = long note start /// /// 3 = long note end /// /// 4 = "OGG sample" (???) note_type: u8, } #[derive(Debug)] enum Events { MeasureFraction(Vec<f32>), BpmChange(Vec<f32>), /// The first `usize` specifies the column NoteEvent(usize, Vec<NoteEvent>), /// The first i16 specifies the event id Unknown(i16, Vec<[u8; 4]>), } named!(note_event(&[u8]) -> NoteEvent, do_parse!( value: le_i16 >> volume_pan: le_u8 >> note_type: le_u8 >> (NoteEvent { value, volume: volume_pan >> 4, pan: volume_pan & 0xF, note_type }) ) ); #[derive(Debug)] struct Package { measure: i32, events: Events, } fn events(input: &[u8], channel: i16, event_count: i16) -> IResult<&[u8], Events> { let event_count = event_count as usize; match channel { 0 => map!(input, count!(le_f32, event_count), |v| Events::MeasureFraction(v)), 1 => map!(input, count!(le_f32, event_count), |v| Events::BpmChange(v)), n @ 2..=8 => map!(input, count!(note_event, event_count), |v| Events::NoteEvent(n as usize, v)), n => map!(input, count!(count_fixed!(u8, le_u8, 4), event_count), |v| Events::Unknown(n, v)), } } named!(package(&[u8]) -> Package, do_parse!( header: package_header >> events: apply!(events, header.channel, header.events) >> (Package { measure: header.measure, events }) ) ); fn notes_section(input: &[u8], package_count: usize) -> IResult<&[u8], Vec<Package>> { count!(input, package, package_count) } use std::{ fs::File, io::{Read, Seek, SeekFrom}, path::Path, }; enum Difficulty { Easy, Normal, Hard, } impl From<Difficulty> for &'static str { fn from(t: Difficulty) -> &'static str { match t { Difficulty::Easy => "Easy", Difficulty::Normal => "Normal", Difficulty::Hard => "Hard", } } } // TODO struct O2mChart { notes: Vec<Note>, bpm_changes: Vec<TimingPoint>, creator: String, artist: String, song_name: String, difficulty: Difficulty, } fn print_packages(packages: &[Package]) { let mut note_count = 0; let mut bpm_change_count = 0; let mut measure_fraction = 0; for package in packages { match package.events { Events::NoteEvent(..) => note_count += 1, Events::BpmChange(..) => bpm_change_count += 1, Events::MeasureFraction(..) => measure_fraction += 1, _ => (), } } println!("Note count: {}", note_count); println!("BPM change count: {}", bpm_change_count); println!("Measure fraction: {}", measure_fraction); } pub fn dump_data<P: AsRef<Path>>(path: P) { let mut hdr_buffer = [0; 300]; let mut file = File::open(path).expect("Failed to open ojn file"); file.read_exact(&mut hdr_buffer).expect("error reading ojn file"); let (_, hdr) = header(&hdr_buffer).unwrap(); // println!("header: {:#?}", hdr); let easy_len = (hdr.note_offset[1] - hdr.note_offset[0]) as usize; let normal_len = (hdr.note_offset[2] - hdr.note_offset[1]) as usize; let hard_len = (hdr.cover_offset - hdr.note_offset[2]) as usize; let mut notesection_buffer = vec![0; easy_len.max(normal_len).max(hard_len)]; file.seek(SeekFrom::Start(hdr.note_offset[0] as u64)).unwrap(); file.read_exact(&mut notesection_buffer[0..easy_len]).expect("Error reading ojn file"); let (_, easy_packages) = notes_section(&notesection_buffer, hdr.package_count[0] as usize).unwrap(); file.seek(SeekFrom::Start(hdr.note_offset[1] as u64)).unwrap(); file.read_exact(&mut notesection_buffer[0..normal_len]).expect("Error reading ojn file"); let (_, normal_packages) = notes_section(&notesection_buffer, hdr.package_count[1] as usize).unwrap(); file.seek(SeekFrom::Start(hdr.note_offset[2] as u64)).unwrap(); file.read_exact(&mut notesection_buffer[0..hard_len]).expect("Error reading ojn file"); let (_, hard_packages) = notes_section(&notesection_buffer, hdr.package_count[2] as usize).unwrap(); println!("Easy difficulty info"); println!("Length: {}:{:02}", hdr.time[0] / 60, hdr.time[0] % 60); println!("Level: {}", hdr.level[0]); print_packages(&easy_packages); println!(); println!("Normal difficulty info"); println!("Length: {}:{:02}", hdr.time[1] / 60, hdr.time[1] % 60); println!("Level: {}", hdr.level[1]); print_packages(&normal_packages); println!(); println!("Hard difficulty info"); println!("Length: {}:{:02}", hdr.time[2] / 60, hdr.time[2] % 60); println!("Level: {}", hdr.level[2]); print_packages(&hard_packages); }
use std::fs; use std::time::Instant; use regex::Regex; fn main() { let start = Instant::now(); let tst_tickets = TicketValidator::from_file("example.txt"); let mut tickets = TicketValidator::from_file("input.txt"); // part 1 let mut tst_scanning_error_rate = 0; for nearby_ticket in &tst_tickets.nearby_tickets { tst_scanning_error_rate += tst_tickets.invalid_field(nearby_ticket); } assert_eq!(71, tst_scanning_error_rate); let mut scanning_error_rate = 0; for nearby_ticket in &tickets.nearby_tickets { scanning_error_rate += tickets.invalid_field(nearby_ticket); } println!("Scanning error rate = {}", scanning_error_rate); // part2 let mut tst2_tickets = TicketValidator::from_file("example2.txt"); assert_eq!(vec!["row", "class", "seat"], tst2_tickets.find_order()); let order = tickets.find_order(); let mut result = 1; let mut field_idx = 0; for ordered_field in order { if ordered_field.starts_with("departure") { result *= tickets.your_ticket.get(field_idx).unwrap(); } field_idx += 1; } println!("Result = {}", result); // exec time let duration = start.elapsed(); println!("Finished after {:?}", duration); } struct FieldRules { name: String, idx: Vec<usize>, min_1: usize, max_1: usize, min_2: usize, max_2: usize } impl FieldRules { fn is_valid(&self, field: &usize) -> bool { return *field >= self.min_1 && *field <= self.max_1 || *field >= self.min_2 && *field <= self.max_2; } } struct TicketValidator { rules: Vec<FieldRules>, your_ticket: Vec<usize>, nearby_tickets: Vec<Vec<usize>> } impl TicketValidator { fn invalid_field(&self, ticket: &Vec<usize>) -> usize { // matching any of the rules is enough 'field_loop: for field in ticket { 'rule_loop: for rule in &self.rules { if rule.is_valid(field) { continue 'field_loop;} continue 'rule_loop; } return *field; // invalid field! } 0 // valid ticket } fn find_order(&mut self) -> Vec<String> { // 1. Keep only the valid tickets // 2. For each ticket // for each field // for each rule : is it a valid field? // If no, remove that field index from the list of possible index, for this rule // At the end of 2. we should have only 1 rule with only one possible index // 3. Then, we must reduce the possible index for all the other rules, starting by the // the most constrained one, ie.e the one with only one possible index. // 4. Create a vector containing the fields in order. // Step 1. Keep valid tickets only let mut valid_tickets = Vec::new(); for nearby_ticket in &self.nearby_tickets { if self.invalid_field(nearby_ticket) == 0 { valid_tickets.push(nearby_ticket.clone()); } } // Step 2. Compute all the possible field index for each rule for ticket in valid_tickets { for field_idx in 0..self.rules.len() { let field = ticket.get(field_idx).unwrap(); 'rule_loop: for rule_idx in 0..self.rules.len() { let rule = self.rules.get_mut(rule_idx).unwrap(); if ! rule.is_valid(field) { rule.idx.retain(|&x| x != field_idx); // remove that field index } continue 'rule_loop; } } } // Step 3. Reduce by starting from the rule that has only one possible index, and propagate to other rules let mut unvisited_rule :Vec<usize> = (0..self.rules.len()).collect(); 'reduce: loop { // There must be at least one rule that have only one possible index. Find it, and remove that field index from all the other rules let mut index_to_remove : usize = 0; let mut visiting_rule_name = "".to_string(); let mut visiting_rule_idx = 0; 'find_most_constrained_rule: for visiting_idx in &unvisited_rule { let rule = self.rules.get(visiting_idx.clone()).unwrap(); if rule.idx.len() == 1 { index_to_remove = rule.idx.first().unwrap().clone(); visiting_rule_name = rule.name.clone(); visiting_rule_idx = visiting_idx.clone(); break 'find_most_constrained_rule; } } unvisited_rule.retain(|&x| x != visiting_rule_idx); 'edit_other_rules: for rule_idx in 0..self.rules.len() { let rule = self.rules.get_mut(rule_idx).unwrap(); if rule.name == visiting_rule_name { // don't remove it from the reference rule continue 'edit_other_rules; } else { // remove that field index rule.idx.retain(|&x| x != index_to_remove); } } // loop while there is at least one rule with more than 1 index for rule_idx in &unvisited_rule { let rule = self.rules.get(rule_idx.clone()).unwrap(); if rule.idx.len() > 1 { continue 'reduce; } } // if there's only rule with one idx candidate, break break 'reduce; } // Step 4. Create a vector containing the fields in order let mut order : Vec<String> = Vec::new(); // find the rule corresponding to the index from 0 to rules.len() for i in 0..self.rules.len() { for rule in &self.rules { if rule.idx.contains(&i) { order.push(rule.name.clone()); } } } //println!("order = {:?}", order); order } fn from_file(f_name: &str) -> TicketValidator { let str_in = fs::read_to_string(f_name).expect("Error in reading file"); // split by empty line: // 1. Field rules // 2. Your ticket // 3. Nearby tickets let mut rules : Vec<FieldRules> = Vec::new(); let parts:Vec<&str> = str_in.split("\r\n\r\n").collect(); let re = Regex::new(r"(\d+)-(\d+) or (\d+)-(\d+)").unwrap(); let rules_cnt = parts[0].lines().count(); for rule in parts[0].lines() { let name_and_rules:Vec<&str> = rule.split(":").collect(); if name_and_rules.len() < 2 { break;} let name = name_and_rules[0].to_string(); let cap = re.captures(name_and_rules[1]).unwrap(); let min_1 = cap[1].parse::<usize>().unwrap(); let max_1 = cap[2].parse::<usize>().unwrap(); let min_2 = cap[3].parse::<usize>().unwrap(); let max_2 = cap[4].parse::<usize>().unwrap(); let idx : Vec<usize> = (0..rules_cnt).collect(); rules.push(FieldRules{name, idx, min_1, max_1, min_2, max_2}); } let your_ticket_str = parts[1].lines().nth(1).unwrap(); let your_ticket = TicketValidator::parse_ticket(your_ticket_str); let mut nearby_tickets : Vec<Vec<usize>> = Vec::new(); for l in parts[2].lines() { if l.starts_with("nearby") {continue;} nearby_tickets.push(TicketValidator::parse_ticket(l)); } TicketValidator { rules, your_ticket, nearby_tickets } } fn parse_ticket(str_in: &str) -> Vec<usize> { let mut ticket : Vec<usize> = Vec::new(); let fields : Vec<&str> = str_in.split(",").collect(); for field in fields { ticket.push(field.parse::<usize>().unwrap()); } ticket } }
//! `ast` contains the Abstract Syntax Tree (`AST`) representation. use crate::{Identifier, Position}; /// An Abstract Syntax Tree with the position in the file. #[derive(Debug, Clone, PartialEq)] pub struct AST { /// The `AST` type. pub ast: ASTType, /// The position in a file of the `AST`. pub position: Position, } /// The Abstract Syntax Tree (`AST`) representation. #[derive(Debug, Clone, PartialEq)] pub enum ASTType { /// A `define` expression. This expression has two forms: /// /// 1. `(define x foo)`, to give `x` the value of `foo`. /// 2. `(define (f x) (foo x))`, to give `f` the value of a function on `x`. Define { name: Identifier, arguments: Option<Vec<Identifier>>, value: Box<AST>, }, /// An `if` expression, in the form `(if condition consequence alternative)`. If { condition: Box<AST>, consequence: Box<AST>, alternative: Box<AST>, }, /// A function call, in the form `(function param1 param2 ...)`. FunctionCall { name: Identifier, arguments: Vec<AST>, }, /// An identifier. Identifier(Identifier), /// An integer. Integer(i64), }
// -*- rust -*- // error-pattern: mismatched types fn f(x: &int) { log_err x; } fn h(x: int) { log_err x; } fn main() { let g: fn(int) = f; g(10); g = h; g(10); }
use NodeId; /// /// A `Node` builder that provides more control over how a `Node` is created. /// pub struct NodeBuilder<T> { data: T, child_capacity: usize, } impl<T> NodeBuilder<T> { /// /// Creates a new `NodeBuilder` with the required data. /// /// ``` /// use id_tree::NodeBuilder; /// /// let _node_builder = NodeBuilder::new(5); /// ``` /// pub fn new(data: T) -> NodeBuilder<T> { NodeBuilder { data: data, child_capacity: 0, } } /// /// Set the child capacity of the `NodeBuilder`. /// /// As `Node`s are added to a `Tree`, parent and child references must be maintained. To do /// this, an allocation must be made every time a child is added to a `Node`. Using this /// setting allows the `Node` to pre-allocate space for its children so that the allocations /// aren't made as children are added. /// /// _Use of this setting is recommended if you know the **maximum number** of children (not /// including grandchildren, great-grandchildren, etc.) that a `Node` will have **at any given /// time**_. /// /// ``` /// use id_tree::NodeBuilder; /// /// let _node_builder = NodeBuilder::new(5).with_child_capacity(3); /// ``` /// pub fn with_child_capacity(mut self, child_capacity: usize) -> NodeBuilder<T> { self.child_capacity = child_capacity; self } /// /// Build a `Node` based upon the current settings in the `NodeBuilder`. /// /// ``` /// use id_tree::NodeBuilder; /// use id_tree::Node; /// /// let node: Node<i32> = NodeBuilder::new(5) /// .with_child_capacity(3) /// .build(); /// /// assert_eq!(node.data(), &5); /// assert_eq!(node.children().capacity(), 3); /// ``` /// pub fn build(self) -> Node<T> { Node { data: self.data, parent: None, children: Vec::with_capacity(self.child_capacity), } } } /// /// A container that wraps data in a given `Tree`. /// #[derive(Debug)] pub struct Node<T> { pub(crate) data: T, pub(crate) parent: Option<NodeId>, pub(crate) children: Vec<NodeId>, } impl<T> PartialEq for Node<T> where T: PartialEq, { fn eq(&self, other: &Node<T>) -> bool { self.data == other.data } } impl<T> Node<T> { /// /// Creates a new `Node` with the data provided. /// /// ``` /// use id_tree::Node; /// /// let _one: Node<i32> = Node::new(1); /// ``` /// pub fn new(data: T) -> Node<T> { NodeBuilder::new(data).build() } /// /// Returns an immutable reference to the data contained within the `Node`. /// /// ``` /// use id_tree::Node; /// /// let node_three: Node<i32> = Node::new(3); /// let three = 3; /// /// assert_eq!(node_three.data(), &three); /// ``` /// pub fn data(&self) -> &T { &self.data } /// /// Returns a mutable reference to the data contained within the `Node`. /// /// ``` /// use id_tree::Node; /// /// let mut node_four: Node<i32> = Node::new(4); /// let mut four = 4; /// /// assert_eq!(node_four.data_mut(), &mut four); /// ``` /// pub fn data_mut(&mut self) -> &mut T { &mut self.data } /// /// Replaces this `Node`s data with the data provided. /// /// Returns the old value of data. /// /// ``` /// use id_tree::Node; /// /// let mut node_four: Node<i32> = Node::new(3); /// /// // ops! lets correct this /// let three = node_four.replace_data(4); /// /// assert_eq!(node_four.data(), &4); /// assert_eq!(three, 3); /// ``` /// pub fn replace_data(&mut self, mut data: T) -> T { ::std::mem::swap(&mut data, self.data_mut()); data } /// /// Returns a `Some` value containing the `NodeId` of this `Node`'s parent if it exists; returns /// `None` if it does not. /// /// **Note:** A `Node` cannot have a parent until after it has been inserted into a `Tree`. /// /// ``` /// use id_tree::Node; /// /// let five: Node<i32> = Node::new(5); /// /// assert!(five.parent().is_none()); /// ``` /// pub fn parent(&self) -> Option<&NodeId> { self.parent.as_ref() } /// /// Returns an immutable reference to a `Vec` containing the `NodeId`s of this `Node`'s /// children. /// /// **Note:** A `Node` cannot have any children until after it has been inserted into a `Tree`. /// /// ``` /// use id_tree::Node; /// /// let six: Node<i32> = Node::new(6); /// /// assert_eq!(six.children().len(), 0); /// ``` /// pub fn children(&self) -> &Vec<NodeId> { &self.children } pub(crate) fn set_parent(&mut self, parent: Option<NodeId>) { self.parent = parent; } pub(crate) fn add_child(&mut self, child: NodeId) { self.children.push(child); } pub(crate) fn replace_child(&mut self, old: NodeId, new: NodeId) { let index = self .children() .iter() .enumerate() .find(|&(_, id)| id == &old) .unwrap() .0; let children = self.children_mut(); children.push(new); children.swap_remove(index); } pub(crate) fn children_mut(&mut self) -> &mut Vec<NodeId> { &mut self.children } pub(crate) fn set_children(&mut self, children: Vec<NodeId>) { self.children = children; } pub(crate) fn take_children(&mut self) -> Vec<NodeId> { use std::mem; let mut empty = Vec::with_capacity(0); mem::swap(&mut self.children, &mut empty); empty //not so empty anymore } } #[cfg(test)] mod node_builder_tests { use super::NodeBuilder; #[test] fn test_new() { let five = 5; let node = NodeBuilder::new(5).build(); assert_eq!(node.data(), &five); assert_eq!(node.children.capacity(), 0); } #[test] fn test_with_child_capacity() { let five = 5; let node = NodeBuilder::new(5).with_child_capacity(10).build(); assert_eq!(node.data(), &five); assert_eq!(node.children.capacity(), 10); } } #[cfg(test)] mod node_tests { use super::super::snowflake::ProcessUniqueId; use super::super::NodeId; use super::Node; #[test] fn test_new() { let node = Node::new(5); assert_eq!(node.children.capacity(), 0); } #[test] fn test_data() { let five = 5; let node = Node::new(five); assert_eq!(node.data(), &five); } #[test] fn test_data_mut() { let mut five = 5; let mut node = Node::new(five); assert_eq!(node.data_mut(), &mut five); } #[test] fn test_parent() { let mut node = Node::new(5); assert!(node.parent().is_none()); let parent_id: NodeId = NodeId { tree_id: ProcessUniqueId::new(), index: 0, }; node.set_parent(Some(parent_id.clone())); assert!(node.parent().is_some()); assert_eq!(node.parent().unwrap().clone(), parent_id); } #[test] fn test_children() { let mut node = Node::new(5); assert_eq!(node.children().len(), 0); let child_id: NodeId = NodeId { tree_id: ProcessUniqueId::new(), index: 0, }; node.add_child(child_id.clone()); assert_eq!(node.children().len(), 1); assert_eq!(node.children().get(0).unwrap(), &child_id); let mut node = Node::new(5); assert_eq!(node.children().len(), 0); let child_id: NodeId = NodeId { tree_id: ProcessUniqueId::new(), index: 0, }; node.children_mut().push(child_id.clone()); assert_eq!(node.children().len(), 1); assert_eq!(node.children().get(0).unwrap(), &child_id); } #[test] fn test_partial_eq() { let node1 = Node::new(42); let node2 = Node::new(42); let node3 = Node::new(23); assert_eq!(node1, node2); assert_ne!(node1, node3); assert_ne!(node2, node3); } }
use serde::{Serialize, Serializer, Deserialize, Deserializer}; use serde::de::Visitor; #[derive(Debug, Clone)] pub struct Uuid(pub uuid::Uuid); impl Into<uuid::Uuid> for Uuid { #[inline] fn into(self) -> uuid::Uuid { self.0 } } impl From<uuid::Uuid> for Uuid { #[inline] fn from(u: uuid::Uuid) -> Self { Uuid(u) } } impl Serialize for Uuid { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer { serializer.serialize_str(&*self.0.to_hyphenated().to_string()) } } impl<'de> Deserialize<'de> for Uuid { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { struct UUIDVisitor; impl<'a> Visitor<'a> for UUIDVisitor { type Value = Uuid; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { Ok(()) } fn visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: serde::de::Error, { use std::str::FromStr; uuid::Uuid::from_str(&*v) .map(|v| Uuid(v)) .map_err(|e| serde::de::Error::custom(e.to_string())) } } deserializer.deserialize_string(UUIDVisitor) } } #[derive(Debug, Clone)] pub struct Uuidi128(pub uuid::Uuid); impl Into<uuid::Uuid> for Uuidi128 { #[inline] fn into(self) -> uuid::Uuid { self.0 } } impl From<uuid::Uuid> for Uuidi128 { #[inline] fn from(u: uuid::Uuid) -> Self { Uuidi128(u) } } impl Serialize for Uuidi128 { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer { let mut bytes = self.0.as_bytes().as_ref(); let uuid = byteorder::ReadBytesExt::read_u128::<byteorder::NativeEndian>(&mut bytes).unwrap(); serializer.serialize_u128(uuid) } } impl<'de> Deserialize<'de> for Uuidi128 { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { struct UUIDVisitor; impl<'a> Visitor<'a> for UUIDVisitor { type Value = Uuidi128; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { Ok(()) } serde::serde_if_integer128! { fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(Uuidi128(uuid::Uuid::from(v))) } } } deserializer.deserialize_u128(UUIDVisitor) } }
/* | bin.rs - | Index for the bot | */ /* ! Remember ! This bot is fully annotated */ /* | Imports the discord crate. | Note ~ This crate must be specified in Cargo.toml, like with any other crate. */ extern crate discord; /* | As follows: | 1. Client for Discord Rest API | 2. Enum of Event Received over a websocket connection | 3. Used for inspection purposes of the code environment. More in the std documentation */ use discord::{Discord, State, ChannelRef, Connection}; use discord::model::{Event, Game}; use std::env; /* | main() - | handles main processes */ pub fn main() { /* | from_bot_token(token: &str) -> Result<Discord> : | @params : token must be of type str (String). | Log in as a bot account using the given authentication token. | expect(" ") : If there is an error with from_bot_token(), throw an error with label "" */ let discord = Discord::from_bot_token("TOKEN") .expect("Login Failed."); /* | connect(&self) -> Result<(Connection, ReadyEvent)> | @params : ignore &self, and instead, don't write anything in the () | Simply establishes a web socket connection to receive events (in this case, || the discord server) | (mut connection, _) <- we are using a tuple as connect() returns a tuple. | ready = the ready even that is returned from using connect() */ let (mut connection, ready) = discord.connect().expect("Connection Failed"); let mut state = State::new(ready); connection.set_game_name("Development".to_owned()); // set game playing to : Development println!("[Gelbot]: Ready! {} has logged into {} servers", state.user().username, state.servers().len()); loop { /* | connection.recv_event(&mut self) -> Result<Event> : | Receives an event over the web socket. | match's use is very similar to that of switch in other languages. | | ! The following code framework is taken from logbot.rs example (discord-rs) */ let event = match connection.recv_event() { Ok(event) => event, Err(discord::Error::Closed(code, body)) => { println!("[Gelbot]: (Error!) Connection closed with status {:?}: {}", code, String::from_utf8_lossy(&body)); break } Err(err) => { println!("[Gelbot]: (Warning!) Received error: {:?}", err); continue } }; state.update(&event); match event { /* | Event::MessageCreate(message)) (enum Event) : | A message as been edited or updated by a user or the system. */ Event::MessageCreate(message) => { if message.content == "+test" { let _ = discord.send_message(&message.channel_id, "This is a reply to the test.", "", false); } else if message.content == "+quit" { println!("[Gelbot]: Quitting!"); break } } Event::Unknown(name, data) => { // log unknown event types for later study println!("[Unknown Event] {}: {:?}", name, data); } _ => {}, // discard other known events } } /* | logout(&self) -> Result<()> | Log out from the Discord Rest API | In other words, log the bot out. */ discord.logout().expect("Logout failed"); }
// Based on schedule.wsdl.xml // targetNamespace="http://www.onvif.org/ver10/schedule/wsdl" // xmlns:xs="http://www.w3.org/2001/XMLSchema" // xmlns:pt="http://www.onvif.org/ver10/pacs" // xmlns:tsc="http://www.onvif.org/ver10/schedule/wsdl" // <xs:import namespace="http://www.onvif.org/ver10/pacs" schemaLocation="../../pacs/types.xsd"/> use crate::schema::types as pt; use std::io::{Read, Write}; use yaserde::{YaDeserialize, YaSerialize};
use ggez::{GameResult, Context}; use ggez::graphics::Image; use std::collections::HashMap; use rand::{self,Rng}; use bomb::{self,Bomb,FuseLength}; use car::{self,Car}; use center::draw_centered; use checkpoint::*; use globals::*; use hex::{HexPoint, HexVector}; #[derive(Debug)] pub struct Assets { checkpoint_line: Image, finish_line: Image, future_bomb: Image, wall: Image, } pub fn load_assets(ctx: &mut Context) -> GameResult<Assets> { Ok( Assets { checkpoint_line: Image::new(ctx, "/checkpoint-line.png")?, finish_line: Image::new(ctx, "/finish-line.png")?, future_bomb: Image::new(ctx, "/future-bomb.png")?, wall: Image::new(ctx, "/wall.png")?, } ) } #[allow(dead_code)] #[derive(Clone, Copy, Debug)] pub enum FloorContents { CheckpointLine(f32), FinishLine(f32), FutureBomb(FuseLength), } impl FloorContents { pub fn draw(self, ctx: &mut Context, assets: &Assets, dest: HexPoint) -> GameResult<()> { match self { FloorContents::CheckpointLine(rotation) => draw_centered(ctx, &assets.checkpoint_line, image_size(), dest.to_point(), rotation), FloorContents::FinishLine(rotation) => draw_centered(ctx, &assets.finish_line, image_size(), dest.to_point(), rotation), FloorContents::FutureBomb(_) => draw_centered(ctx, &assets.future_bomb, image_size(), dest.to_point(), 0.0), } } } #[allow(dead_code)] #[derive(Clone, Copy, Debug)] pub enum CellContents { Bomb(Bomb), Car(Car), Wall, } impl CellContents { pub fn draw(self, ctx: &mut Context, assets: &Assets, bomb_assets: &bomb::Assets, car_assets: &car::Assets, dest: HexPoint) -> GameResult<()> { match self { CellContents::Bomb(bomb) => bomb.draw(ctx, bomb_assets, dest.to_point()), CellContents::Car(car) => car.draw(ctx, car_assets, dest.to_point()), CellContents::Wall => draw_centered(ctx, &assets.wall, image_size(), dest.to_point(), 0.0), } } } #[derive(Clone, Debug)] pub struct Map { cells: HashMap<HexPoint, CellContents>, floor: HashMap<HexPoint, FloorContents>, } impl Map { pub fn load() -> Map { let cells: HashMap<HexPoint, CellContents> = HashMap::with_capacity(100); let mut floor: HashMap<HexPoint, FloorContents> = HashMap::with_capacity(100); for distance in CENTRAL_OBSTACLE_RADIUS+1..MAP_RADIUS+1 { for direction_index in 0..6 { floor.insert( HexPoint::new(0, 0) + HexVector::from_index(direction_index) * distance, if direction_index == 0 { FloorContents::FinishLine(HexVector::from_index(direction_index).to_rotation()) } else { FloorContents::CheckpointLine(HexVector::from_index(direction_index).to_rotation()) }, ); } } Map {cells, floor} } #[allow(dead_code)] pub fn get(&self, hex_point: HexPoint) -> Option<CellContents> { let distance_from_center = hex_point.distance_from_center(); if distance_from_center > CENTRAL_OBSTACLE_RADIUS && distance_from_center <= MAP_RADIUS { self.cells.get(&hex_point).map (|x| *x) } else { Some(CellContents::Wall) } } // prefer an empty spot, or a non-car spot if neccessary. pub fn find_spot_at_checkpoint(&self, checkpoint: Checkpoint) -> HexPoint { let section = checkpoint_to_section(checkpoint); let direction = HexVector::from_index(section); for distance in (CENTRAL_OBSTACLE_RADIUS+1..MAP_RADIUS+1).rev() { let hex_point = HexPoint::new(0, 0) + direction * distance; match self.get(hex_point) { None => return hex_point, Some(_) => (), } } for distance in (CENTRAL_OBSTACLE_RADIUS+1..MAP_RADIUS+1).rev() { let hex_point = HexPoint::new(0, 0) + direction * distance; match self.get(hex_point) { Some(CellContents::Car(_)) => (), Some(_) => return hex_point, None => unreachable!(), } } panic!("no spots left!"); // should not happen unless there are more than 3 cars in the game } // a location whose floor and cell are both empty. pub fn is_available(&self, hex_point: HexPoint) -> bool { self.floor.get(&hex_point).is_none() && self.get(hex_point).is_none() } pub fn random_available_spot(&self) -> Option<HexPoint> { let mut spots: Vec<HexPoint> = Vec::with_capacity(100); for r in -MAP_RADIUS..MAP_RADIUS+1 { for q in -MAP_RADIUS..MAP_RADIUS+1 { let hex_point = HexPoint::new(q, r); if self.is_available(hex_point) { spots.push(hex_point); } } } if spots.is_empty() { None } else { let mut rng = rand::thread_rng(); let i = rng.gen_range(0, spots.len()); Some(spots[i]) } } pub fn decrement_all_bombs(&mut self) { let mut bomb_changes: Vec<(HexPoint, Option<Bomb>)> = Vec::with_capacity(100); let mut future_bomb_changes: Vec<(HexPoint, FuseLength)> = Vec::with_capacity(100); for (hex_point, cell_contents) in self.cells.iter() { match cell_contents { &CellContents::Bomb(bomb) => bomb_changes.push((*hex_point, bomb.decrement())), _ => (), } } for (hex_point, option_bomb) in bomb_changes { self.remove(hex_point); match option_bomb { Some(bomb) => { self.insert(hex_point, CellContents::Bomb(bomb)); }, None => { match self.random_available_spot() { Some(new_spot) => { future_bomb_changes.push((new_spot, MAX_FUSE_LENGTH)); }, None => (), } }, } } for (hex_point, floor_contents) in self.floor.iter() { match floor_contents { &FloorContents::FutureBomb(fuse_length) => { future_bomb_changes.push((*hex_point, fuse_length - 1)); }, _ => (), } } for (hex_point, fuse_length) in future_bomb_changes { self.floor.remove(&hex_point); self.insert_bomb(hex_point, fuse_length); } } pub fn insert(&mut self, hex_point: HexPoint, cell_contents: CellContents) { self.cells.insert(hex_point, cell_contents); } pub fn insert_bomb(&mut self, hex_point: HexPoint, fuse_length: FuseLength) { if fuse_length <= 3 { match self.get(hex_point) { None => { self.insert(hex_point, CellContents::Bomb(Bomb::new(fuse_length))); }, Some(_) => { // delay the appearance of the bomb until the obstacle moves away self.floor.insert(hex_point, FloorContents::FutureBomb(fuse_length + 1)); }, } } else { self.floor.insert(hex_point, FloorContents::FutureBomb(fuse_length)); } } pub fn remove(&mut self, hex_point: HexPoint) { self.cells.remove(&hex_point); } pub fn draw(&self, ctx: &mut Context, assets: &Assets, bomb_assets: &bomb::Assets, car_assets: &car::Assets) -> GameResult<()> { for (dest, floor_contents) in &self.floor { floor_contents.draw(ctx, assets, *dest)?; } for (dest, cell_contents) in &self.cells { cell_contents.draw(ctx, assets, bomb_assets, car_assets, *dest)?; } for r in -CENTRAL_OBSTACLE_RADIUS..CENTRAL_OBSTACLE_RADIUS+1 { for q in -CENTRAL_OBSTACLE_RADIUS..CENTRAL_OBSTACLE_RADIUS+1 { let hex_point = HexPoint::new(q, r); let distance_from_center = hex_point.distance_from_center(); if distance_from_center == CENTRAL_OBSTACLE_RADIUS { CellContents::Wall.draw(ctx, assets, bomb_assets, car_assets, hex_point)?; } } } Ok(()) } }
// 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::collections::BTreeMap; use std::collections::HashSet; use std::sync::Arc; use common_ast::ast::AlterTableAction; use common_ast::ast::AlterTableStmt; use common_ast::ast::AnalyzeTableStmt; use common_ast::ast::ColumnDefinition; use common_ast::ast::CompactTarget; use common_ast::ast::CreateTableSource; use common_ast::ast::CreateTableStmt; use common_ast::ast::DescribeTableStmt; use common_ast::ast::DropTableStmt; use common_ast::ast::Engine; use common_ast::ast::ExistsTableStmt; use common_ast::ast::Expr; use common_ast::ast::Identifier; use common_ast::ast::Literal; use common_ast::ast::OptimizeTableAction as AstOptimizeTableAction; use common_ast::ast::OptimizeTableStmt; use common_ast::ast::RenameTableStmt; use common_ast::ast::ShowCreateTableStmt; use common_ast::ast::ShowLimit; use common_ast::ast::ShowTablesStatusStmt; use common_ast::ast::ShowTablesStmt; use common_ast::ast::Statement; use common_ast::ast::TableReference; use common_ast::ast::TruncateTableStmt; use common_ast::ast::UndropTableStmt; use common_ast::ast::UriLocation; use common_ast::parser::parse_sql; use common_ast::parser::tokenize_sql; use common_ast::walk_expr_mut; use common_ast::Dialect; use common_config::GlobalConfig; use common_exception::ErrorCode; use common_exception::Result; use common_expression::infer_schema_type; use common_expression::infer_table_schema; use common_expression::types::DataType; use common_expression::ConstantFolder; use common_expression::DataField; use common_expression::DataSchemaRefExt; use common_expression::TableField; use common_expression::TableSchemaRef; use common_expression::TableSchemaRefExt; use common_functions::BUILTIN_FUNCTIONS; use common_meta_app::storage::StorageParams; use common_storage::DataOperator; use common_storages_view::view_table::QUERY; use common_storages_view::view_table::VIEW_ENGINE; use storages_common_table_meta::table::is_reserved_opt_key; use storages_common_table_meta::table::OPT_KEY_DATABASE_ID; use storages_common_table_meta::table::OPT_KEY_STORAGE_FORMAT; use storages_common_table_meta::table::OPT_KEY_TABLE_COMPRESSION; use tracing::debug; use crate::binder::location::parse_uri_location; use crate::binder::scalar::ScalarBinder; use crate::binder::Binder; use crate::binder::Visibility; use crate::optimizer::optimize; use crate::optimizer::OptimizerConfig; use crate::optimizer::OptimizerContext; use crate::planner::semantic::normalize_identifier; use crate::planner::semantic::resolve_type_name; use crate::planner::semantic::IdentifierNormalizer; use crate::plans::AddTableColumnPlan; use crate::plans::AlterTableClusterKeyPlan; use crate::plans::AnalyzeTablePlan; use crate::plans::CastExpr; use crate::plans::CreateTablePlan; use crate::plans::DescribeTablePlan; use crate::plans::DropTableClusterKeyPlan; use crate::plans::DropTableColumnPlan; use crate::plans::DropTablePlan; use crate::plans::ExistsTablePlan; use crate::plans::OptimizeTableAction; use crate::plans::OptimizeTablePlan; use crate::plans::Plan; use crate::plans::ReclusterTablePlan; use crate::plans::RenameTablePlan; use crate::plans::RevertTablePlan; use crate::plans::RewriteKind; use crate::plans::ShowCreateTablePlan; use crate::plans::TruncateTablePlan; use crate::plans::UndropTablePlan; use crate::BindContext; use crate::ColumnBinding; use crate::Planner; use crate::ScalarExpr; use crate::SelectBuilder; impl Binder { pub(in crate::planner::binder) async fn bind_show_tables( &mut self, bind_context: &mut BindContext, stmt: &ShowTablesStmt, ) -> Result<Plan> { let ShowTablesStmt { catalog, database, full, limit, with_history, } = stmt; let database = self.check_database_exist(catalog, database).await?; let mut select_builder = if stmt.with_history { SelectBuilder::from("system.tables_with_history") } else { SelectBuilder::from("system.tables") }; if *full { select_builder .with_column("name AS Tables") .with_column("'BASE TABLE' AS Table_type") .with_column("database AS Database") .with_column("catalog AS Catalog") .with_column("engine") .with_column("created_on AS create_time"); if *with_history { select_builder.with_column("dropped_on AS drop_time"); } select_builder .with_column("num_rows") .with_column("data_size") .with_column("data_compressed_size") .with_column("index_size"); } else { select_builder.with_column(format!("name AS Tables_in_{database}")); if *with_history { select_builder.with_column("dropped_on AS drop_time"); }; } select_builder .with_order_by("catalog") .with_order_by("database") .with_order_by("name"); select_builder.with_filter(format!("database = '{database}'")); if let Some(catalog) = catalog { let catalog = normalize_identifier(catalog, &self.name_resolution_ctx).name; select_builder.with_filter(format!("catalog = '{catalog}'")); } let query = match limit { None => select_builder.build(), Some(ShowLimit::Like { pattern }) => { select_builder.with_filter(format!("name LIKE '{pattern}'")); select_builder.build() } Some(ShowLimit::Where { selection }) => { select_builder.with_filter(format!("({selection})")); select_builder.build() } }; debug!("show tables rewrite to: {:?}", query); self.bind_rewrite_to_query(bind_context, query.as_str(), RewriteKind::ShowTables) .await } pub(in crate::planner::binder) async fn bind_show_create_table( &mut self, stmt: &ShowCreateTableStmt, ) -> Result<Plan> { let ShowCreateTableStmt { catalog, database, table, } = stmt; let (catalog, database, table) = self.normalize_object_identifier_triple(catalog, database, table); let schema = DataSchemaRefExt::create(vec![ DataField::new("Table", DataType::String), DataField::new("Create Table", DataType::String), ]); Ok(Plan::ShowCreateTable(Box::new(ShowCreateTablePlan { catalog, database, table, schema, }))) } pub(in crate::planner::binder) async fn bind_describe_table( &mut self, stmt: &DescribeTableStmt, ) -> Result<Plan> { let DescribeTableStmt { catalog, database, table, } = stmt; let (catalog, database, table) = self.normalize_object_identifier_triple(catalog, database, table); let schema = DataSchemaRefExt::create(vec![ DataField::new("Field", DataType::String), DataField::new("Type", DataType::String), DataField::new("Null", DataType::String), DataField::new("Default", DataType::String), DataField::new("Extra", DataType::String), ]); Ok(Plan::DescribeTable(Box::new(DescribeTablePlan { catalog, database, table, schema, }))) } pub(in crate::planner::binder) async fn bind_show_tables_status( &mut self, bind_context: &mut BindContext, stmt: &ShowTablesStatusStmt, ) -> Result<Plan> { let ShowTablesStatusStmt { database, limit } = stmt; let database = self.check_database_exist(&None, database).await?; let select_cols = "name AS Name, engine AS Engine, 0 AS Version, \ NULL AS Row_format, num_rows AS Rows, NULL AS Avg_row_length, data_size AS Data_length, \ NULL AS Max_data_length, index_size AS Index_length, NULL AS Data_free, NULL AS Auto_increment, \ created_on AS Create_time, NULL AS Update_time, NULL AS Check_time, NULL AS Collation, \ NULL AS Checksum, '' AS Comment" .to_string(); // Use `system.tables` AS the "base" table to construct the result-set of `SHOW TABLE STATUS ..` // // To constraint the schema of the final result-set, // `(select ${select_cols} from system.tables where ..)` // is used AS a derived table. // (unlike mysql, alias of derived table is not required in databend). let query = match limit { None => format!( "SELECT * from (SELECT {} FROM system.tables WHERE database = '{}') \ ORDER BY Name", select_cols, database ), Some(ShowLimit::Like { pattern }) => format!( "SELECT * from (SELECT {} FROM system.tables WHERE database = '{}') \ WHERE Name LIKE '{}' ORDER BY Name", select_cols, database, pattern ), Some(ShowLimit::Where { selection }) => format!( "SELECT * from (SELECT {} FROM system.tables WHERE database = '{}') \ WHERE ({}) ORDER BY Name", select_cols, database, selection ), }; let tokens = tokenize_sql(query.as_str())?; let (stmt, _) = parse_sql(&tokens, Dialect::PostgreSQL)?; self.bind_statement(bind_context, &stmt).await } async fn check_database_exist( &mut self, catalog: &Option<Identifier>, database: &Option<Identifier>, ) -> Result<String> { let ctl_name = match catalog { Some(ctl) => ctl.to_string(), None => self.ctx.get_current_catalog(), }; match database { None => Ok(self.ctx.get_current_database()), Some(ident) => { let database = normalize_identifier(ident, &self.name_resolution_ctx).name; self.ctx .get_catalog(&ctl_name)? .get_database(&self.ctx.get_tenant(), &database) .await?; Ok(database) } } } pub(in crate::planner::binder) async fn bind_create_table( &mut self, stmt: &CreateTableStmt, ) -> Result<Plan> { let CreateTableStmt { if_not_exists, catalog, database, table, source, table_options, cluster_by, as_query, transient, engine, uri_location, } = stmt; let (catalog, database, table) = self.normalize_object_identifier_triple(catalog, database, table); // Take FUSE engine AS default engine let engine = engine.unwrap_or(Engine::Fuse); let mut options: BTreeMap<String, String> = BTreeMap::new(); for table_option in table_options.iter() { self.insert_table_option_with_validation( &mut options, table_option.0.to_lowercase(), table_option.1.to_string(), )?; } let (storage_params, part_prefix) = match uri_location { Some(uri) => { let mut uri = UriLocation { protocol: uri.protocol.clone(), name: uri.name.clone(), path: uri.path.clone(), part_prefix: uri.part_prefix.clone(), connection: uri.connection.clone(), }; let (sp, _) = parse_uri_location(&mut uri)?; // create a temporary op to check if params is correct DataOperator::try_create(&sp).await?; // Path ends with "/" means it's a directory. let fp = if uri.path.ends_with('/') { uri.part_prefix.clone() } else { "".to_string() }; (Some(sp), fp) } None => (None, "".to_string()), }; // If table is TRANSIENT, set a flag in table option if *transient { options.insert("TRANSIENT".to_owned(), "T".to_owned()); } // Build table schema let (schema, field_default_exprs, field_comments) = match (&source, &as_query) { (Some(source), None) => { // `CREATE TABLE` without `AS SELECT ...` self.analyze_create_table_schema(source).await? } (None, Some(query)) => { // `CREATE TABLE AS SELECT ...` without column definitions let mut init_bind_context = BindContext::new(); let (_, bind_context) = self.bind_query(&mut init_bind_context, query).await?; let fields = bind_context .columns .iter() .map(|column_binding| { Ok(TableField::new( &column_binding.column_name, infer_schema_type(&column_binding.data_type)?, )) }) .collect::<Result<Vec<_>>>()?; let schema = TableSchemaRefExt::create(fields); Self::validate_create_table_schema(&schema)?; (schema, vec![], vec![]) } (Some(source), Some(query)) => { // e.g. `CREATE TABLE t (i INT) AS SELECT * from old_t` with columns specified let (source_schema, source_default_exprs, source_comments) = self.analyze_create_table_schema(source).await?; let mut init_bind_context = BindContext::new(); let (_, bind_context) = self.bind_query(&mut init_bind_context, query).await?; let query_fields: Vec<TableField> = bind_context .columns .iter() .map(|column_binding| { Ok(TableField::new( &column_binding.column_name, infer_schema_type(&column_binding.data_type)?, )) }) .collect::<Result<Vec<_>>>()?; if source_schema.fields().len() != query_fields.len() { return Err(ErrorCode::BadArguments("Number of columns does not match")); } Self::validate_create_table_schema(&source_schema)?; (source_schema, source_default_exprs, source_comments) } _ => Err(ErrorCode::BadArguments( "Incorrect CREATE query: required list of column descriptions or AS section or SELECT..", ))?, }; if engine == Engine::Fuse { // Currently, [Table] can not accesses its database id yet, thus // here we keep the db id AS an entry of `table_meta.options`. // // To make the unit/stateless test cases (`show create ..`) easier, // here we care about the FUSE engine only. // // Later, when database id is kept, let say in `TableInfo`, we can // safely eliminate this "FUSE" constant and the table meta option entry. let catalog = self.ctx.get_catalog(&catalog)?; let db = catalog .get_database(&self.ctx.get_tenant(), &database) .await?; let db_id = db.get_db_info().ident.db_id; options.insert(OPT_KEY_DATABASE_ID.to_owned(), db_id.to_string()); let config = GlobalConfig::instance(); let is_blocking_fs = matches!( storage_params.as_ref().unwrap_or(&config.storage.params), StorageParams::Fs(_) ); // we should persist the storage format and compression type instead of using the default value in fuse table if !options.contains_key(OPT_KEY_STORAGE_FORMAT) { let default_storage_format = match config.query.default_storage_format.as_str() { "" | "auto" => { if is_blocking_fs { "native" } else { "parquet" } } _ => config.query.default_storage_format.as_str(), }; options.insert( OPT_KEY_STORAGE_FORMAT.to_owned(), default_storage_format.to_owned(), ); } if !options.contains_key(OPT_KEY_TABLE_COMPRESSION) { let default_compression = match config.query.default_compression.as_str() { "" | "auto" => { if is_blocking_fs { "lz4" } else { "zstd" } } _ => config.query.default_compression.as_str(), }; options.insert( OPT_KEY_TABLE_COMPRESSION.to_owned(), default_compression.to_owned(), ); } } let cluster_key = { let keys = self .analyze_cluster_keys(cluster_by, schema.clone()) .await?; if keys.is_empty() { None } else { Some(format!("({})", keys.join(", "))) } }; let plan = CreateTablePlan { if_not_exists: *if_not_exists, tenant: self.ctx.get_tenant(), catalog: catalog.clone(), database: database.clone(), table, schema: schema.clone(), engine, storage_params, part_prefix, options, field_default_exprs, field_comments, cluster_key, as_select: if let Some(query) = as_query { let mut bind_context = BindContext::new(); let stmt = Statement::Query(Box::new(*query.clone())); let select_plan = self.bind_statement(&mut bind_context, &stmt).await?; // Don't enable distributed optimization for `CREATE TABLE ... AS SELECT ...` for now let opt_ctx = Arc::new(OptimizerContext::new(OptimizerConfig::default())); let optimized_plan = optimize(self.ctx.clone(), opt_ctx, select_plan)?; Some(Box::new(optimized_plan)) } else { None }, }; Ok(Plan::CreateTable(Box::new(plan))) } pub(in crate::planner::binder) async fn bind_drop_table( &mut self, stmt: &DropTableStmt, ) -> Result<Plan> { let DropTableStmt { if_exists, catalog, database, table, all, } = stmt; let tenant = self.ctx.get_tenant(); let (catalog, database, table) = self.normalize_object_identifier_triple(catalog, database, table); Ok(Plan::DropTable(Box::new(DropTablePlan { if_exists: *if_exists, tenant, catalog, database, table, all: *all, }))) } pub(in crate::planner::binder) async fn bind_undrop_table( &mut self, stmt: &UndropTableStmt, ) -> Result<Plan> { let UndropTableStmt { catalog, database, table, } = stmt; let tenant = self.ctx.get_tenant(); let (catalog, database, table) = self.normalize_object_identifier_triple(catalog, database, table); Ok(Plan::UndropTable(Box::new(UndropTablePlan { tenant, catalog, database, table, }))) } pub(in crate::planner::binder) async fn bind_alter_table( &mut self, bind_context: &mut BindContext, stmt: &AlterTableStmt, ) -> Result<Plan> { let AlterTableStmt { if_exists, table_reference, action, } = stmt; let tenant = self.ctx.get_tenant(); let (catalog, database, table) = if let TableReference::Table { catalog, database, table, .. } = table_reference { self.normalize_object_identifier_triple(catalog, database, table) } else { return Err(ErrorCode::Internal( "should not happen, parser should have report error already", )); }; match action { AlterTableAction::RenameTable { new_table } => { Ok(Plan::RenameTable(Box::new(RenameTablePlan { tenant, if_exists: *if_exists, new_database: database.clone(), new_table: normalize_identifier(new_table, &self.name_resolution_ctx).name, catalog, database, table, }))) } AlterTableAction::AddColumn { column } => { let (schema, field_default_exprs, field_comments) = self .analyze_create_table_schema_by_columns(&[column.clone()]) .await?; Ok(Plan::AddTableColumn(Box::new(AddTableColumnPlan { catalog, database, table, schema, field_default_exprs, field_comments, }))) } AlterTableAction::DropColumn { column } => { Ok(Plan::DropTableColumn(Box::new(DropTableColumnPlan { catalog, database, table, column: column.to_string(), }))) } AlterTableAction::AlterTableClusterKey { cluster_by } => { let schema = self .ctx .get_table(&catalog, &database, &table) .await? .schema(); let cluster_keys = self.analyze_cluster_keys(cluster_by, schema).await?; Ok(Plan::AlterTableClusterKey(Box::new( AlterTableClusterKeyPlan { tenant, catalog, database, table, cluster_keys, }, ))) } AlterTableAction::DropTableClusterKey => Ok(Plan::DropTableClusterKey(Box::new( DropTableClusterKeyPlan { tenant, catalog, database, table, }, ))), AlterTableAction::ReclusterTable { is_final, selection, } => { let (_, mut context) = self .bind_table_reference(bind_context, table_reference) .await?; let mut scalar_binder = ScalarBinder::new( &mut context, self.ctx.clone(), &self.name_resolution_ctx, self.metadata.clone(), &[], ); let push_downs = if let Some(expr) = selection { let (scalar, _) = scalar_binder.bind(expr).await?; Some(scalar) } else { None }; Ok(Plan::ReclusterTable(Box::new(ReclusterTablePlan { tenant, catalog, database, table, is_final: *is_final, metadata: self.metadata.clone(), push_downs, }))) } AlterTableAction::RevertTo { point } => { let point = self.resolve_data_travel_point(bind_context, point).await?; Ok(Plan::RevertTable(Box::new(RevertTablePlan { tenant, catalog, database, table, point, }))) } } } pub(in crate::planner::binder) async fn bind_rename_table( &mut self, stmt: &RenameTableStmt, ) -> Result<Plan> { let RenameTableStmt { if_exists, catalog, database, table, new_catalog, new_database, new_table, } = stmt; let tenant = self.ctx.get_tenant(); let (catalog, database, table) = self.normalize_object_identifier_triple(catalog, database, table); let (new_catalog, new_database, new_table) = self.normalize_object_identifier_triple(new_catalog, new_database, new_table); if new_catalog != catalog { return Err(ErrorCode::BadArguments( "alter catalog not allowed while rename table", )); } Ok(Plan::RenameTable(Box::new(RenameTablePlan { tenant, if_exists: *if_exists, catalog, database, table, new_database, new_table, }))) } pub(in crate::planner::binder) async fn bind_truncate_table( &mut self, stmt: &TruncateTableStmt, ) -> Result<Plan> { let TruncateTableStmt { catalog, database, table, purge, } = stmt; let (catalog, database, table) = self.normalize_object_identifier_triple(catalog, database, table); Ok(Plan::TruncateTable(Box::new(TruncateTablePlan { catalog, database, table, purge: *purge, }))) } pub(in crate::planner::binder) async fn bind_optimize_table( &mut self, bind_context: &mut BindContext, stmt: &OptimizeTableStmt, ) -> Result<Plan> { let OptimizeTableStmt { catalog, database, table, action: ast_action, } = stmt; let (catalog, database, table) = self.normalize_object_identifier_triple(catalog, database, table); let action = match ast_action { AstOptimizeTableAction::All => OptimizeTableAction::All, AstOptimizeTableAction::Purge { before } => { let p = if let Some(point) = before { let point = self.resolve_data_travel_point(bind_context, point).await?; Some(point) } else { None }; OptimizeTableAction::Purge(p) } AstOptimizeTableAction::Compact { target, limit } => { let limit_cnt = match limit { Some(Expr::Literal { lit: Literal::UInt64(uint), .. }) => Some(*uint as usize), Some(_) => { return Err(ErrorCode::IllegalDataType("Unsupported limit type")); } _ => None, }; match target { CompactTarget::Block => OptimizeTableAction::CompactBlocks(limit_cnt), CompactTarget::Segment => OptimizeTableAction::CompactSegments(limit_cnt), } } }; Ok(Plan::OptimizeTable(Box::new(OptimizeTablePlan { catalog, database, table, action, }))) } pub(in crate::planner::binder) async fn bind_analyze_table( &mut self, stmt: &AnalyzeTableStmt, ) -> Result<Plan> { let AnalyzeTableStmt { catalog, database, table, } = stmt; let (catalog, database, table) = self.normalize_object_identifier_triple(catalog, database, table); Ok(Plan::AnalyzeTable(Box::new(AnalyzeTablePlan { catalog, database, table, }))) } pub(in crate::planner::binder) async fn bind_exists_table( &mut self, stmt: &ExistsTableStmt, ) -> Result<Plan> { let ExistsTableStmt { catalog, database, table, } = stmt; let (catalog, database, table) = self.normalize_object_identifier_triple(catalog, database, table); Ok(Plan::ExistsTable(Box::new(ExistsTablePlan { catalog, database, table, }))) } async fn analyze_create_table_schema_by_columns( &self, columns: &[ColumnDefinition], ) -> Result<(TableSchemaRef, Vec<Option<String>>, Vec<String>)> { let mut bind_context = BindContext::new(); let mut scalar_binder = ScalarBinder::new( &mut bind_context, self.ctx.clone(), &self.name_resolution_ctx, self.metadata.clone(), &[], ); let mut fields = Vec::with_capacity(columns.len()); let mut fields_default_expr = Vec::with_capacity(columns.len()); let mut fields_comments = Vec::with_capacity(columns.len()); for column in columns.iter() { let name = normalize_identifier(&column.name, &self.name_resolution_ctx).name; let schema_data_type = resolve_type_name(&column.data_type)?; fields.push(TableField::new(&name, schema_data_type.clone())); fields_default_expr.push({ if let Some(default_expr) = &column.default_expr { let (expr, _) = scalar_binder.bind(default_expr).await?; let is_try = schema_data_type.is_nullable(); let cast_expr_to_field_type = ScalarExpr::CastExpr(CastExpr { span: expr.span(), is_try, target_type: Box::new(DataType::from(&schema_data_type)), argument: Box::new(expr), }) .as_expr_with_col_index()?; let (fold_to_constant, _) = ConstantFolder::fold( &cast_expr_to_field_type, self.ctx.get_function_context()?, &BUILTIN_FUNCTIONS, ); if let common_expression::Expr::Constant { .. } = fold_to_constant { Some(default_expr.to_string()) } else { return Err(ErrorCode::SemanticError(format!( "default expression {cast_expr_to_field_type} is not a valid constant", ))); } } else { None } }); fields_comments.push(column.comment.clone().unwrap_or_default()); } let schema = TableSchemaRefExt::create(fields); Self::validate_create_table_schema(&schema)?; Ok((schema, fields_default_expr, fields_comments)) } async fn analyze_create_table_schema( &self, source: &CreateTableSource, ) -> Result<(TableSchemaRef, Vec<Option<String>>, Vec<String>)> { match source { CreateTableSource::Columns(columns) => { self.analyze_create_table_schema_by_columns(columns).await } CreateTableSource::Like { catalog, database, table, } => { let (catalog, database, table) = self.normalize_object_identifier_triple(catalog, database, table); let table = self.ctx.get_table(&catalog, &database, &table).await?; if table.engine() == VIEW_ENGINE { let query = table.get_table_info().options().get(QUERY).unwrap(); let mut planner = Planner::new(self.ctx.clone()); let (plan, _) = planner.plan_sql(query).await?; Ok((infer_table_schema(&plan.schema())?, vec![], vec![])) } else { Ok((table.schema(), vec![], table.field_comments().clone())) } } } } /// Validate the schema of the table to be created. fn validate_create_table_schema(schema: &TableSchemaRef) -> Result<()> { // Check if there are duplicated column names let mut name_set = HashSet::new(); for field in schema.fields() { if !name_set.insert(field.name().clone()) { return Err(ErrorCode::BadArguments(format!( "Duplicated column name: {}", field.name() ))); } } Ok(()) } fn insert_table_option_with_validation( &self, options: &mut BTreeMap<String, String>, key: String, value: String, ) -> Result<()> { if is_reserved_opt_key(&key) { Err(ErrorCode::TableOptionInvalid(format!( "table option {key} reserved, please do not specify in the CREATE TABLE statement", ))) } else if options.insert(key.clone(), value).is_some() { Err(ErrorCode::TableOptionInvalid(format!( "table option {key} duplicated" ))) } else { Ok(()) } } async fn analyze_cluster_keys( &mut self, cluster_by: &[Expr], schema: TableSchemaRef, ) -> Result<Vec<String>> { // Build a temporary BindContext to resolve the expr let mut bind_context = BindContext::new(); for (index, field) in schema.fields().iter().enumerate() { let column = ColumnBinding { database_name: None, table_name: None, column_name: field.name().clone(), index, data_type: Box::new(DataType::from(field.data_type())), visibility: Visibility::Visible, }; bind_context.columns.push(column); } let mut scalar_binder = ScalarBinder::new( &mut bind_context, self.ctx.clone(), &self.name_resolution_ctx, self.metadata.clone(), &[], ); let mut cluster_keys = Vec::with_capacity(cluster_by.len()); for cluster_by in cluster_by.iter() { let (cluster_key, _) = scalar_binder.bind(cluster_by).await?; let expr = cluster_key.as_expr_with_col_index()?; if !expr.is_deterministic(&BUILTIN_FUNCTIONS) { return Err(ErrorCode::InvalidClusterKeys(format!( "Cluster by expression `{:#}` is not deterministic", cluster_by ))); } let mut cluster_by = cluster_by.clone(); walk_expr_mut( &mut IdentifierNormalizer { ctx: &self.name_resolution_ctx, }, &mut cluster_by, ); cluster_keys.push(format!("{:#}", &cluster_by)); } Ok(cluster_keys) } }
/*! This crate provides an implementation of the [Snappy compression format](https://github.com/google/snappy/blob/master/format_description.txt), as well as the [framing format](https://github.com/google/snappy/blob/master/framing_format.txt). The goal of Snappy is to provide reasonable compression at high speed. On a modern CPU, Snappy can compress data at about 300 MB/sec or more and can decompress data at about 800 MB/sec or more. # Install To use this crate with [Cargo](https://doc.rust-lang.org/cargo/), simply add it as a dependency to your `Cargo.toml`: ```ignore [dependencies] snap = "1" ``` # Overview This crate provides two ways to use Snappy. The first way is through the [`read::FrameDecoder`](read/struct.FrameDecoder.html) and [`write::FrameEncoder`](write/struct.FrameEncoder.html) types, which implement the `std::io::Read` and `std::io::Write` traits with the Snappy frame format. Unless you have a specific reason to the contrary, you should only use the Snappy frame format. Specifically, the Snappy frame format permits streaming compression or decompression. The second way is through the [`raw::Decoder`](raw/struct.Decoder.html) and [`raw::Encoder`](raw/struct.Encoder.html) types. These types provide lower level control to the raw Snappy format, and don't support a streaming interface directly. You should only use these types if you know you specifically need the Snappy raw format. Finally, the `Error` type in this crate provides an exhaustive list of error conditions that are probably useless in most circumstances. Therefore, `From<snap::Error> for io::Error` is implemented in this crate, which will let you automatically convert a Snappy error to an `std::io::Error` (when using `?`) with an appropriate error message to display to an end user. # Example: compress data on `stdin` This program reads data from `stdin`, compresses it and emits it to `stdout`. This example can be found in `examples/compress.rs`: ```no_run use std::io; fn main() { let stdin = io::stdin(); let stdout = io::stdout(); let mut rdr = stdin.lock(); // Wrap the stdout writer in a Snappy writer. let mut wtr = snap::write::FrameEncoder::new(stdout.lock()); io::copy(&mut rdr, &mut wtr).expect("I/O operation failed"); } ``` # Example: decompress data on `stdin` This program reads data from `stdin`, decompresses it and emits it to `stdout`. This example can be found in `examples/decompress.rs`: ```no_run use std::io; fn main() { let stdin = io::stdin(); let stdout = io::stdout(); // Wrap the stdin reader in a Snappy reader. let mut rdr = snap::read::FrameDecoder::new(stdin.lock()); let mut wtr = stdout.lock(); io::copy(&mut rdr, &mut wtr).expect("I/O operation failed"); } ``` */ #![deny(missing_docs)] #[cfg(test)] doc_comment::doctest!("../README.md"); pub use crate::error::{Error, Result}; /// We don't permit compressing a block bigger than what can fit in a u32. const MAX_INPUT_SIZE: u64 = std::u32::MAX as u64; /// The maximum number of bytes that we process at once. A block is the unit /// at which we scan for candidates for compression. const MAX_BLOCK_SIZE: usize = 1 << 16; mod bytes; mod compress; mod crc32; mod crc32_table; mod decompress; mod error; mod frame; pub mod raw; pub mod read; mod tag; pub mod write;
#[cfg(test)] mod tests { use pygmaea::token_type::TokenType::*; use pygmaea::token_type::*; const TOKEN_TYPES: [TokenType; 27] = [ Plus, Minus, Asterisk, Slash, Assign, Bang, LessThan, GreaterThan, Equal, NotEqual, Comma, Semicolon, LParen, RParen, LBrace, RBrace, True, False, Let, Function, If, Else, Return, Int, Ident, EOF, Illegal, ]; const KEYWORD_TOKEN_TYPES: [TokenType; 8] = [True, False, Let, Function, If, Else, Return, Ident]; #[test] fn test_is_keyword() { TOKEN_TYPES.iter().for_each(|token_type| { assert_eq!( KEYWORD_TOKEN_TYPES.contains(token_type), token_type.is_keyword() ); }) } #[test] fn test_is_int() { TOKEN_TYPES.iter().for_each(|token_type| { assert_eq!(token_type == &Int, token_type.is_int()); }) } #[test] fn test_is_eof() { TOKEN_TYPES.iter().for_each(|token_type| { assert_eq!(token_type == &EOF, token_type.is_eof()); }) } #[test] fn test_default() { let token_type: TokenType = TokenType::default(); assert_eq!(token_type, Illegal); } #[test] fn test_keyword() { KEYWORDS.values().for_each(|keyword| { assert!(KEYWORD_TOKEN_TYPES.contains(keyword)); }) } #[test] fn test_display() { TOKEN_TYPES.iter().for_each(|token_type| match token_type { Plus => assert_eq!("Plus", format!("{}", token_type)), Minus => assert_eq!("Minus", format!("{}", token_type)), Asterisk => assert_eq!("Asterisk", format!("{}", token_type)), Slash => assert_eq!("Slash", format!("{}", token_type)), Assign => assert_eq!("Assign", format!("{}", token_type)), Bang => assert_eq!("Bang", format!("{}", token_type)), LessThan => assert_eq!("LessThan", format!("{}", token_type)), GreaterThan => assert_eq!("GreaterThan", format!("{}", token_type)), Equal => assert_eq!("Equal", format!("{}", token_type)), NotEqual => assert_eq!("NotEqual", format!("{}", token_type)), LParen => assert_eq!("LParen", format!("{}", token_type)), RParen => assert_eq!("RParen", format!("{}", token_type)), LBrace => assert_eq!("LBrace", format!("{}", token_type)), RBrace => assert_eq!("RBrace", format!("{}", token_type)), Comma => assert_eq!("Comma", format!("{}", token_type)), Semicolon => assert_eq!("Semicolon", format!("{}", token_type)), True => assert_eq!("True", format!("{}", token_type)), False => assert_eq!("False", format!("{}", token_type)), Let => assert_eq!("Let", format!("{}", token_type)), Function => assert_eq!("Function", format!("{}", token_type)), If => assert_eq!("If", format!("{}", token_type)), Else => assert_eq!("Else", format!("{}", token_type)), Return => assert_eq!("Return", format!("{}", token_type)), Int => assert_eq!("Int", format!("{}", token_type)), Ident => assert_eq!("Ident", format!("{}", token_type)), EOF => assert_eq!("EOF", format!("{}", token_type)), Illegal => assert_eq!("Illegal", format!("{}", token_type)), }); } }
#![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 BackupEventLogA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(heventlog: Param0, lpbackupfilename: Param1) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn BackupEventLogA(heventlog: super::super::Foundation::HANDLE, lpbackupfilename: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(BackupEventLogA(heventlog.into_param().abi(), lpbackupfilename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn BackupEventLogW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(heventlog: Param0, lpbackupfilename: Param1) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn BackupEventLogW(heventlog: super::super::Foundation::HANDLE, lpbackupfilename: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(BackupEventLogW(heventlog.into_param().abi(), lpbackupfilename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ClearEventLogA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(heventlog: Param0, lpbackupfilename: Param1) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ClearEventLogA(heventlog: super::super::Foundation::HANDLE, lpbackupfilename: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(ClearEventLogA(heventlog.into_param().abi(), lpbackupfilename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ClearEventLogW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(heventlog: Param0, lpbackupfilename: Param1) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ClearEventLogW(heventlog: super::super::Foundation::HANDLE, lpbackupfilename: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(ClearEventLogW(heventlog.into_param().abi(), lpbackupfilename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn CloseEventLog<'a, Param0: ::windows::core::IntoParam<'a, EventLogHandle>>(heventlog: Param0) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CloseEventLog(heventlog: EventLogHandle) -> super::super::Foundation::BOOL; } ::core::mem::transmute(CloseEventLog(heventlog.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DeregisterEventSource<'a, Param0: ::windows::core::IntoParam<'a, EventSourceHandle>>(heventlog: Param0) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DeregisterEventSource(heventlog: EventSourceHandle) -> super::super::Foundation::BOOL; } ::core::mem::transmute(DeregisterEventSource(heventlog.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct EVENTLOGRECORD { pub Length: u32, pub Reserved: u32, pub RecordNumber: u32, pub TimeGenerated: u32, pub TimeWritten: u32, pub EventID: u32, pub EventType: REPORT_EVENT_TYPE, pub NumStrings: u16, pub EventCategory: u16, pub ReservedFlags: u16, pub ClosingRecordNumber: u32, pub StringOffset: u32, pub UserSidLength: u32, pub UserSidOffset: u32, pub DataLength: u32, pub DataOffset: u32, } impl EVENTLOGRECORD {} impl ::core::default::Default for EVENTLOGRECORD { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for EVENTLOGRECORD { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("EVENTLOGRECORD") .field("Length", &self.Length) .field("Reserved", &self.Reserved) .field("RecordNumber", &self.RecordNumber) .field("TimeGenerated", &self.TimeGenerated) .field("TimeWritten", &self.TimeWritten) .field("EventID", &self.EventID) .field("EventType", &self.EventType) .field("NumStrings", &self.NumStrings) .field("EventCategory", &self.EventCategory) .field("ReservedFlags", &self.ReservedFlags) .field("ClosingRecordNumber", &self.ClosingRecordNumber) .field("StringOffset", &self.StringOffset) .field("UserSidLength", &self.UserSidLength) .field("UserSidOffset", &self.UserSidOffset) .field("DataLength", &self.DataLength) .field("DataOffset", &self.DataOffset) .finish() } } impl ::core::cmp::PartialEq for EVENTLOGRECORD { fn eq(&self, other: &Self) -> bool { self.Length == other.Length && self.Reserved == other.Reserved && self.RecordNumber == other.RecordNumber && self.TimeGenerated == other.TimeGenerated && self.TimeWritten == other.TimeWritten && self.EventID == other.EventID && self.EventType == other.EventType && self.NumStrings == other.NumStrings && self.EventCategory == other.EventCategory && self.ReservedFlags == other.ReservedFlags && self.ClosingRecordNumber == other.ClosingRecordNumber && self.StringOffset == other.StringOffset && self.UserSidLength == other.UserSidLength && self.UserSidOffset == other.UserSidOffset && self.DataLength == other.DataLength && self.DataOffset == other.DataOffset } } impl ::core::cmp::Eq for EVENTLOGRECORD {} unsafe impl ::windows::core::Abi for EVENTLOGRECORD { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct EVENTLOG_FULL_INFORMATION { pub dwFull: u32, } impl EVENTLOG_FULL_INFORMATION {} impl ::core::default::Default for EVENTLOG_FULL_INFORMATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for EVENTLOG_FULL_INFORMATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("EVENTLOG_FULL_INFORMATION").field("dwFull", &self.dwFull).finish() } } impl ::core::cmp::PartialEq for EVENTLOG_FULL_INFORMATION { fn eq(&self, other: &Self) -> bool { self.dwFull == other.dwFull } } impl ::core::cmp::Eq for EVENTLOG_FULL_INFORMATION {} unsafe impl ::windows::core::Abi for EVENTLOG_FULL_INFORMATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct EVENTSFORLOGFILE { pub ulSize: u32, pub szLogicalLogFile: [u16; 256], pub ulNumRecords: u32, pub pEventLogRecords: [EVENTLOGRECORD; 1], } impl EVENTSFORLOGFILE {} impl ::core::default::Default for EVENTSFORLOGFILE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for EVENTSFORLOGFILE { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("EVENTSFORLOGFILE").field("ulSize", &self.ulSize).field("szLogicalLogFile", &self.szLogicalLogFile).field("ulNumRecords", &self.ulNumRecords).field("pEventLogRecords", &self.pEventLogRecords).finish() } } impl ::core::cmp::PartialEq for EVENTSFORLOGFILE { fn eq(&self, other: &Self) -> bool { self.ulSize == other.ulSize && self.szLogicalLogFile == other.szLogicalLogFile && self.ulNumRecords == other.ulNumRecords && self.pEventLogRecords == other.pEventLogRecords } } impl ::core::cmp::Eq for EVENTSFORLOGFILE {} unsafe impl ::windows::core::Abi for EVENTSFORLOGFILE { type Abi = Self; } pub const EVT_ALL_ACCESS: u32 = 7u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct EVT_CHANNEL_CLOCK_TYPE(pub i32); pub const EvtChannelClockTypeSystemTime: EVT_CHANNEL_CLOCK_TYPE = EVT_CHANNEL_CLOCK_TYPE(0i32); pub const EvtChannelClockTypeQPC: EVT_CHANNEL_CLOCK_TYPE = EVT_CHANNEL_CLOCK_TYPE(1i32); impl ::core::convert::From<i32> for EVT_CHANNEL_CLOCK_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_CHANNEL_CLOCK_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 EVT_CHANNEL_CONFIG_PROPERTY_ID(pub i32); pub const EvtChannelConfigEnabled: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(0i32); pub const EvtChannelConfigIsolation: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(1i32); pub const EvtChannelConfigType: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(2i32); pub const EvtChannelConfigOwningPublisher: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(3i32); pub const EvtChannelConfigClassicEventlog: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(4i32); pub const EvtChannelConfigAccess: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(5i32); pub const EvtChannelLoggingConfigRetention: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(6i32); pub const EvtChannelLoggingConfigAutoBackup: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(7i32); pub const EvtChannelLoggingConfigMaxSize: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(8i32); pub const EvtChannelLoggingConfigLogFilePath: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(9i32); pub const EvtChannelPublishingConfigLevel: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(10i32); pub const EvtChannelPublishingConfigKeywords: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(11i32); pub const EvtChannelPublishingConfigControlGuid: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(12i32); pub const EvtChannelPublishingConfigBufferSize: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(13i32); pub const EvtChannelPublishingConfigMinBuffers: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(14i32); pub const EvtChannelPublishingConfigMaxBuffers: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(15i32); pub const EvtChannelPublishingConfigLatency: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(16i32); pub const EvtChannelPublishingConfigClockType: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(17i32); pub const EvtChannelPublishingConfigSidType: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(18i32); pub const EvtChannelPublisherList: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(19i32); pub const EvtChannelPublishingConfigFileMax: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(20i32); pub const EvtChannelConfigPropertyIdEND: EVT_CHANNEL_CONFIG_PROPERTY_ID = EVT_CHANNEL_CONFIG_PROPERTY_ID(21i32); impl ::core::convert::From<i32> for EVT_CHANNEL_CONFIG_PROPERTY_ID { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_CHANNEL_CONFIG_PROPERTY_ID { 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 EVT_CHANNEL_ISOLATION_TYPE(pub i32); pub const EvtChannelIsolationTypeApplication: EVT_CHANNEL_ISOLATION_TYPE = EVT_CHANNEL_ISOLATION_TYPE(0i32); pub const EvtChannelIsolationTypeSystem: EVT_CHANNEL_ISOLATION_TYPE = EVT_CHANNEL_ISOLATION_TYPE(1i32); pub const EvtChannelIsolationTypeCustom: EVT_CHANNEL_ISOLATION_TYPE = EVT_CHANNEL_ISOLATION_TYPE(2i32); impl ::core::convert::From<i32> for EVT_CHANNEL_ISOLATION_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_CHANNEL_ISOLATION_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 EVT_CHANNEL_REFERENCE_FLAGS(pub i32); pub const EvtChannelReferenceImported: EVT_CHANNEL_REFERENCE_FLAGS = EVT_CHANNEL_REFERENCE_FLAGS(1i32); impl ::core::convert::From<i32> for EVT_CHANNEL_REFERENCE_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_CHANNEL_REFERENCE_FLAGS { 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 EVT_CHANNEL_SID_TYPE(pub i32); pub const EvtChannelSidTypeNone: EVT_CHANNEL_SID_TYPE = EVT_CHANNEL_SID_TYPE(0i32); pub const EvtChannelSidTypePublishing: EVT_CHANNEL_SID_TYPE = EVT_CHANNEL_SID_TYPE(1i32); impl ::core::convert::From<i32> for EVT_CHANNEL_SID_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_CHANNEL_SID_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 EVT_CHANNEL_TYPE(pub i32); pub const EvtChannelTypeAdmin: EVT_CHANNEL_TYPE = EVT_CHANNEL_TYPE(0i32); pub const EvtChannelTypeOperational: EVT_CHANNEL_TYPE = EVT_CHANNEL_TYPE(1i32); pub const EvtChannelTypeAnalytic: EVT_CHANNEL_TYPE = EVT_CHANNEL_TYPE(2i32); pub const EvtChannelTypeDebug: EVT_CHANNEL_TYPE = EVT_CHANNEL_TYPE(3i32); impl ::core::convert::From<i32> for EVT_CHANNEL_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_CHANNEL_TYPE { type Abi = Self; } pub const EVT_CLEAR_ACCESS: u32 = 4u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct EVT_EVENT_METADATA_PROPERTY_ID(pub i32); pub const EventMetadataEventID: EVT_EVENT_METADATA_PROPERTY_ID = EVT_EVENT_METADATA_PROPERTY_ID(0i32); pub const EventMetadataEventVersion: EVT_EVENT_METADATA_PROPERTY_ID = EVT_EVENT_METADATA_PROPERTY_ID(1i32); pub const EventMetadataEventChannel: EVT_EVENT_METADATA_PROPERTY_ID = EVT_EVENT_METADATA_PROPERTY_ID(2i32); pub const EventMetadataEventLevel: EVT_EVENT_METADATA_PROPERTY_ID = EVT_EVENT_METADATA_PROPERTY_ID(3i32); pub const EventMetadataEventOpcode: EVT_EVENT_METADATA_PROPERTY_ID = EVT_EVENT_METADATA_PROPERTY_ID(4i32); pub const EventMetadataEventTask: EVT_EVENT_METADATA_PROPERTY_ID = EVT_EVENT_METADATA_PROPERTY_ID(5i32); pub const EventMetadataEventKeyword: EVT_EVENT_METADATA_PROPERTY_ID = EVT_EVENT_METADATA_PROPERTY_ID(6i32); pub const EventMetadataEventMessageID: EVT_EVENT_METADATA_PROPERTY_ID = EVT_EVENT_METADATA_PROPERTY_ID(7i32); pub const EventMetadataEventTemplate: EVT_EVENT_METADATA_PROPERTY_ID = EVT_EVENT_METADATA_PROPERTY_ID(8i32); pub const EvtEventMetadataPropertyIdEND: EVT_EVENT_METADATA_PROPERTY_ID = EVT_EVENT_METADATA_PROPERTY_ID(9i32); impl ::core::convert::From<i32> for EVT_EVENT_METADATA_PROPERTY_ID { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_EVENT_METADATA_PROPERTY_ID { 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 EVT_EVENT_PROPERTY_ID(pub i32); pub const EvtEventQueryIDs: EVT_EVENT_PROPERTY_ID = EVT_EVENT_PROPERTY_ID(0i32); pub const EvtEventPath: EVT_EVENT_PROPERTY_ID = EVT_EVENT_PROPERTY_ID(1i32); pub const EvtEventPropertyIdEND: EVT_EVENT_PROPERTY_ID = EVT_EVENT_PROPERTY_ID(2i32); impl ::core::convert::From<i32> for EVT_EVENT_PROPERTY_ID { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_EVENT_PROPERTY_ID { 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 EVT_EXPORTLOG_FLAGS(pub i32); pub const EvtExportLogChannelPath: EVT_EXPORTLOG_FLAGS = EVT_EXPORTLOG_FLAGS(1i32); pub const EvtExportLogFilePath: EVT_EXPORTLOG_FLAGS = EVT_EXPORTLOG_FLAGS(2i32); pub const EvtExportLogTolerateQueryErrors: EVT_EXPORTLOG_FLAGS = EVT_EXPORTLOG_FLAGS(4096i32); pub const EvtExportLogOverwrite: EVT_EXPORTLOG_FLAGS = EVT_EXPORTLOG_FLAGS(8192i32); impl ::core::convert::From<i32> for EVT_EXPORTLOG_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_EXPORTLOG_FLAGS { 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 EVT_FORMAT_MESSAGE_FLAGS(pub i32); pub const EvtFormatMessageEvent: EVT_FORMAT_MESSAGE_FLAGS = EVT_FORMAT_MESSAGE_FLAGS(1i32); pub const EvtFormatMessageLevel: EVT_FORMAT_MESSAGE_FLAGS = EVT_FORMAT_MESSAGE_FLAGS(2i32); pub const EvtFormatMessageTask: EVT_FORMAT_MESSAGE_FLAGS = EVT_FORMAT_MESSAGE_FLAGS(3i32); pub const EvtFormatMessageOpcode: EVT_FORMAT_MESSAGE_FLAGS = EVT_FORMAT_MESSAGE_FLAGS(4i32); pub const EvtFormatMessageKeyword: EVT_FORMAT_MESSAGE_FLAGS = EVT_FORMAT_MESSAGE_FLAGS(5i32); pub const EvtFormatMessageChannel: EVT_FORMAT_MESSAGE_FLAGS = EVT_FORMAT_MESSAGE_FLAGS(6i32); pub const EvtFormatMessageProvider: EVT_FORMAT_MESSAGE_FLAGS = EVT_FORMAT_MESSAGE_FLAGS(7i32); pub const EvtFormatMessageId: EVT_FORMAT_MESSAGE_FLAGS = EVT_FORMAT_MESSAGE_FLAGS(8i32); pub const EvtFormatMessageXml: EVT_FORMAT_MESSAGE_FLAGS = EVT_FORMAT_MESSAGE_FLAGS(9i32); impl ::core::convert::From<i32> for EVT_FORMAT_MESSAGE_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_FORMAT_MESSAGE_FLAGS { 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 EVT_LOGIN_CLASS(pub i32); pub const EvtRpcLogin: EVT_LOGIN_CLASS = EVT_LOGIN_CLASS(1i32); impl ::core::convert::From<i32> for EVT_LOGIN_CLASS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_LOGIN_CLASS { 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 EVT_LOG_PROPERTY_ID(pub i32); pub const EvtLogCreationTime: EVT_LOG_PROPERTY_ID = EVT_LOG_PROPERTY_ID(0i32); pub const EvtLogLastAccessTime: EVT_LOG_PROPERTY_ID = EVT_LOG_PROPERTY_ID(1i32); pub const EvtLogLastWriteTime: EVT_LOG_PROPERTY_ID = EVT_LOG_PROPERTY_ID(2i32); pub const EvtLogFileSize: EVT_LOG_PROPERTY_ID = EVT_LOG_PROPERTY_ID(3i32); pub const EvtLogAttributes: EVT_LOG_PROPERTY_ID = EVT_LOG_PROPERTY_ID(4i32); pub const EvtLogNumberOfLogRecords: EVT_LOG_PROPERTY_ID = EVT_LOG_PROPERTY_ID(5i32); pub const EvtLogOldestRecordNumber: EVT_LOG_PROPERTY_ID = EVT_LOG_PROPERTY_ID(6i32); pub const EvtLogFull: EVT_LOG_PROPERTY_ID = EVT_LOG_PROPERTY_ID(7i32); impl ::core::convert::From<i32> for EVT_LOG_PROPERTY_ID { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_LOG_PROPERTY_ID { 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 EVT_OPEN_LOG_FLAGS(pub i32); pub const EvtOpenChannelPath: EVT_OPEN_LOG_FLAGS = EVT_OPEN_LOG_FLAGS(1i32); pub const EvtOpenFilePath: EVT_OPEN_LOG_FLAGS = EVT_OPEN_LOG_FLAGS(2i32); impl ::core::convert::From<i32> for EVT_OPEN_LOG_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_OPEN_LOG_FLAGS { 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 EVT_PUBLISHER_METADATA_PROPERTY_ID(pub i32); pub const EvtPublisherMetadataPublisherGuid: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(0i32); pub const EvtPublisherMetadataResourceFilePath: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(1i32); pub const EvtPublisherMetadataParameterFilePath: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(2i32); pub const EvtPublisherMetadataMessageFilePath: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(3i32); pub const EvtPublisherMetadataHelpLink: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(4i32); pub const EvtPublisherMetadataPublisherMessageID: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(5i32); pub const EvtPublisherMetadataChannelReferences: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(6i32); pub const EvtPublisherMetadataChannelReferencePath: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(7i32); pub const EvtPublisherMetadataChannelReferenceIndex: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(8i32); pub const EvtPublisherMetadataChannelReferenceID: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(9i32); pub const EvtPublisherMetadataChannelReferenceFlags: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(10i32); pub const EvtPublisherMetadataChannelReferenceMessageID: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(11i32); pub const EvtPublisherMetadataLevels: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(12i32); pub const EvtPublisherMetadataLevelName: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(13i32); pub const EvtPublisherMetadataLevelValue: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(14i32); pub const EvtPublisherMetadataLevelMessageID: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(15i32); pub const EvtPublisherMetadataTasks: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(16i32); pub const EvtPublisherMetadataTaskName: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(17i32); pub const EvtPublisherMetadataTaskEventGuid: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(18i32); pub const EvtPublisherMetadataTaskValue: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(19i32); pub const EvtPublisherMetadataTaskMessageID: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(20i32); pub const EvtPublisherMetadataOpcodes: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(21i32); pub const EvtPublisherMetadataOpcodeName: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(22i32); pub const EvtPublisherMetadataOpcodeValue: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(23i32); pub const EvtPublisherMetadataOpcodeMessageID: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(24i32); pub const EvtPublisherMetadataKeywords: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(25i32); pub const EvtPublisherMetadataKeywordName: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(26i32); pub const EvtPublisherMetadataKeywordValue: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(27i32); pub const EvtPublisherMetadataKeywordMessageID: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(28i32); pub const EvtPublisherMetadataPropertyIdEND: EVT_PUBLISHER_METADATA_PROPERTY_ID = EVT_PUBLISHER_METADATA_PROPERTY_ID(29i32); impl ::core::convert::From<i32> for EVT_PUBLISHER_METADATA_PROPERTY_ID { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_PUBLISHER_METADATA_PROPERTY_ID { 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 EVT_QUERY_FLAGS(pub i32); pub const EvtQueryChannelPath: EVT_QUERY_FLAGS = EVT_QUERY_FLAGS(1i32); pub const EvtQueryFilePath: EVT_QUERY_FLAGS = EVT_QUERY_FLAGS(2i32); pub const EvtQueryForwardDirection: EVT_QUERY_FLAGS = EVT_QUERY_FLAGS(256i32); pub const EvtQueryReverseDirection: EVT_QUERY_FLAGS = EVT_QUERY_FLAGS(512i32); pub const EvtQueryTolerateQueryErrors: EVT_QUERY_FLAGS = EVT_QUERY_FLAGS(4096i32); impl ::core::convert::From<i32> for EVT_QUERY_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_QUERY_FLAGS { 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 EVT_QUERY_PROPERTY_ID(pub i32); pub const EvtQueryNames: EVT_QUERY_PROPERTY_ID = EVT_QUERY_PROPERTY_ID(0i32); pub const EvtQueryStatuses: EVT_QUERY_PROPERTY_ID = EVT_QUERY_PROPERTY_ID(1i32); pub const EvtQueryPropertyIdEND: EVT_QUERY_PROPERTY_ID = EVT_QUERY_PROPERTY_ID(2i32); impl ::core::convert::From<i32> for EVT_QUERY_PROPERTY_ID { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_QUERY_PROPERTY_ID { type Abi = Self; } pub const EVT_READ_ACCESS: u32 = 1u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct EVT_RENDER_CONTEXT_FLAGS(pub i32); pub const EvtRenderContextValues: EVT_RENDER_CONTEXT_FLAGS = EVT_RENDER_CONTEXT_FLAGS(0i32); pub const EvtRenderContextSystem: EVT_RENDER_CONTEXT_FLAGS = EVT_RENDER_CONTEXT_FLAGS(1i32); pub const EvtRenderContextUser: EVT_RENDER_CONTEXT_FLAGS = EVT_RENDER_CONTEXT_FLAGS(2i32); impl ::core::convert::From<i32> for EVT_RENDER_CONTEXT_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_RENDER_CONTEXT_FLAGS { 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 EVT_RENDER_FLAGS(pub i32); pub const EvtRenderEventValues: EVT_RENDER_FLAGS = EVT_RENDER_FLAGS(0i32); pub const EvtRenderEventXml: EVT_RENDER_FLAGS = EVT_RENDER_FLAGS(1i32); pub const EvtRenderBookmark: EVT_RENDER_FLAGS = EVT_RENDER_FLAGS(2i32); impl ::core::convert::From<i32> for EVT_RENDER_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_RENDER_FLAGS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct EVT_RPC_LOGIN { pub Server: super::super::Foundation::PWSTR, pub User: super::super::Foundation::PWSTR, pub Domain: super::super::Foundation::PWSTR, pub Password: super::super::Foundation::PWSTR, pub Flags: u32, } #[cfg(feature = "Win32_Foundation")] impl EVT_RPC_LOGIN {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for EVT_RPC_LOGIN { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for EVT_RPC_LOGIN { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("EVT_RPC_LOGIN").field("Server", &self.Server).field("User", &self.User).field("Domain", &self.Domain).field("Password", &self.Password).field("Flags", &self.Flags).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for EVT_RPC_LOGIN { fn eq(&self, other: &Self) -> bool { self.Server == other.Server && self.User == other.User && self.Domain == other.Domain && self.Password == other.Password && self.Flags == other.Flags } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for EVT_RPC_LOGIN {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for EVT_RPC_LOGIN { 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 EVT_RPC_LOGIN_FLAGS(pub i32); pub const EvtRpcLoginAuthDefault: EVT_RPC_LOGIN_FLAGS = EVT_RPC_LOGIN_FLAGS(0i32); pub const EvtRpcLoginAuthNegotiate: EVT_RPC_LOGIN_FLAGS = EVT_RPC_LOGIN_FLAGS(1i32); pub const EvtRpcLoginAuthKerberos: EVT_RPC_LOGIN_FLAGS = EVT_RPC_LOGIN_FLAGS(2i32); pub const EvtRpcLoginAuthNTLM: EVT_RPC_LOGIN_FLAGS = EVT_RPC_LOGIN_FLAGS(3i32); impl ::core::convert::From<i32> for EVT_RPC_LOGIN_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_RPC_LOGIN_FLAGS { 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 EVT_SEEK_FLAGS(pub i32); pub const EvtSeekRelativeToFirst: EVT_SEEK_FLAGS = EVT_SEEK_FLAGS(1i32); pub const EvtSeekRelativeToLast: EVT_SEEK_FLAGS = EVT_SEEK_FLAGS(2i32); pub const EvtSeekRelativeToCurrent: EVT_SEEK_FLAGS = EVT_SEEK_FLAGS(3i32); pub const EvtSeekRelativeToBookmark: EVT_SEEK_FLAGS = EVT_SEEK_FLAGS(4i32); pub const EvtSeekOriginMask: EVT_SEEK_FLAGS = EVT_SEEK_FLAGS(7i32); pub const EvtSeekStrict: EVT_SEEK_FLAGS = EVT_SEEK_FLAGS(65536i32); impl ::core::convert::From<i32> for EVT_SEEK_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_SEEK_FLAGS { type Abi = Self; } pub type EVT_SUBSCRIBE_CALLBACK = unsafe extern "system" fn(action: EVT_SUBSCRIBE_NOTIFY_ACTION, usercontext: *const ::core::ffi::c_void, event: isize) -> u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct EVT_SUBSCRIBE_FLAGS(pub i32); pub const EvtSubscribeToFutureEvents: EVT_SUBSCRIBE_FLAGS = EVT_SUBSCRIBE_FLAGS(1i32); pub const EvtSubscribeStartAtOldestRecord: EVT_SUBSCRIBE_FLAGS = EVT_SUBSCRIBE_FLAGS(2i32); pub const EvtSubscribeStartAfterBookmark: EVT_SUBSCRIBE_FLAGS = EVT_SUBSCRIBE_FLAGS(3i32); pub const EvtSubscribeOriginMask: EVT_SUBSCRIBE_FLAGS = EVT_SUBSCRIBE_FLAGS(3i32); pub const EvtSubscribeTolerateQueryErrors: EVT_SUBSCRIBE_FLAGS = EVT_SUBSCRIBE_FLAGS(4096i32); pub const EvtSubscribeStrict: EVT_SUBSCRIBE_FLAGS = EVT_SUBSCRIBE_FLAGS(65536i32); impl ::core::convert::From<i32> for EVT_SUBSCRIBE_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_SUBSCRIBE_FLAGS { 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 EVT_SUBSCRIBE_NOTIFY_ACTION(pub i32); pub const EvtSubscribeActionError: EVT_SUBSCRIBE_NOTIFY_ACTION = EVT_SUBSCRIBE_NOTIFY_ACTION(0i32); pub const EvtSubscribeActionDeliver: EVT_SUBSCRIBE_NOTIFY_ACTION = EVT_SUBSCRIBE_NOTIFY_ACTION(1i32); impl ::core::convert::From<i32> for EVT_SUBSCRIBE_NOTIFY_ACTION { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_SUBSCRIBE_NOTIFY_ACTION { 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 EVT_SYSTEM_PROPERTY_ID(pub i32); pub const EvtSystemProviderName: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(0i32); pub const EvtSystemProviderGuid: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(1i32); pub const EvtSystemEventID: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(2i32); pub const EvtSystemQualifiers: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(3i32); pub const EvtSystemLevel: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(4i32); pub const EvtSystemTask: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(5i32); pub const EvtSystemOpcode: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(6i32); pub const EvtSystemKeywords: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(7i32); pub const EvtSystemTimeCreated: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(8i32); pub const EvtSystemEventRecordId: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(9i32); pub const EvtSystemActivityID: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(10i32); pub const EvtSystemRelatedActivityID: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(11i32); pub const EvtSystemProcessID: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(12i32); pub const EvtSystemThreadID: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(13i32); pub const EvtSystemChannel: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(14i32); pub const EvtSystemComputer: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(15i32); pub const EvtSystemUserID: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(16i32); pub const EvtSystemVersion: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(17i32); pub const EvtSystemPropertyIdEND: EVT_SYSTEM_PROPERTY_ID = EVT_SYSTEM_PROPERTY_ID(18i32); impl ::core::convert::From<i32> for EVT_SYSTEM_PROPERTY_ID { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_SYSTEM_PROPERTY_ID { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct EVT_VARIANT { pub Anonymous: EVT_VARIANT_0, pub Count: u32, pub Type: u32, } #[cfg(feature = "Win32_Foundation")] impl EVT_VARIANT {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for EVT_VARIANT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for EVT_VARIANT { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for EVT_VARIANT {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for EVT_VARIANT { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union EVT_VARIANT_0 { pub BooleanVal: super::super::Foundation::BOOL, pub SByteVal: i8, pub Int16Val: i16, pub Int32Val: i32, pub Int64Val: i64, pub ByteVal: u8, pub UInt16Val: u16, pub UInt32Val: u32, pub UInt64Val: u64, pub SingleVal: f32, pub DoubleVal: f64, pub FileTimeVal: u64, pub SysTimeVal: *mut super::super::Foundation::SYSTEMTIME, pub GuidVal: *mut ::windows::core::GUID, pub StringVal: super::super::Foundation::PWSTR, pub AnsiStringVal: super::super::Foundation::PSTR, pub BinaryVal: *mut u8, pub SidVal: super::super::Foundation::PSID, pub SizeTVal: usize, pub BooleanArr: *mut super::super::Foundation::BOOL, pub SByteArr: *mut i8, pub Int16Arr: *mut i16, pub Int32Arr: *mut i32, pub Int64Arr: *mut i64, pub ByteArr: *mut u8, pub UInt16Arr: *mut u16, pub UInt32Arr: *mut u32, pub UInt64Arr: *mut u64, pub SingleArr: *mut f32, pub DoubleArr: *mut f64, pub FileTimeArr: *mut super::super::Foundation::FILETIME, pub SysTimeArr: *mut super::super::Foundation::SYSTEMTIME, pub GuidArr: *mut ::windows::core::GUID, pub StringArr: *mut super::super::Foundation::PWSTR, pub AnsiStringArr: *mut super::super::Foundation::PSTR, pub SidArr: *mut super::super::Foundation::PSID, pub SizeTArr: *mut usize, pub EvtHandleVal: isize, pub XmlVal: super::super::Foundation::PWSTR, pub XmlValArr: *mut super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl EVT_VARIANT_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for EVT_VARIANT_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for EVT_VARIANT_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for EVT_VARIANT_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for EVT_VARIANT_0 { 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 EVT_VARIANT_TYPE(pub i32); pub const EvtVarTypeNull: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(0i32); pub const EvtVarTypeString: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(1i32); pub const EvtVarTypeAnsiString: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(2i32); pub const EvtVarTypeSByte: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(3i32); pub const EvtVarTypeByte: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(4i32); pub const EvtVarTypeInt16: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(5i32); pub const EvtVarTypeUInt16: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(6i32); pub const EvtVarTypeInt32: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(7i32); pub const EvtVarTypeUInt32: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(8i32); pub const EvtVarTypeInt64: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(9i32); pub const EvtVarTypeUInt64: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(10i32); pub const EvtVarTypeSingle: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(11i32); pub const EvtVarTypeDouble: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(12i32); pub const EvtVarTypeBoolean: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(13i32); pub const EvtVarTypeBinary: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(14i32); pub const EvtVarTypeGuid: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(15i32); pub const EvtVarTypeSizeT: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(16i32); pub const EvtVarTypeFileTime: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(17i32); pub const EvtVarTypeSysTime: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(18i32); pub const EvtVarTypeSid: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(19i32); pub const EvtVarTypeHexInt32: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(20i32); pub const EvtVarTypeHexInt64: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(21i32); pub const EvtVarTypeEvtHandle: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(32i32); pub const EvtVarTypeEvtXml: EVT_VARIANT_TYPE = EVT_VARIANT_TYPE(35i32); impl ::core::convert::From<i32> for EVT_VARIANT_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for EVT_VARIANT_TYPE { type Abi = Self; } pub const EVT_VARIANT_TYPE_ARRAY: u32 = 128u32; pub const EVT_VARIANT_TYPE_MASK: u32 = 127u32; pub const EVT_WRITE_ACCESS: u32 = 2u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq)] #[repr(transparent)] pub struct EventLogHandle(pub isize); impl ::core::default::Default for EventLogHandle { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } unsafe impl ::windows::core::Handle for EventLogHandle {} unsafe impl ::windows::core::Abi for EventLogHandle { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq)] #[repr(transparent)] pub struct EventSourceHandle(pub isize); impl ::core::default::Default for EventSourceHandle { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } unsafe impl ::windows::core::Handle for EventSourceHandle {} unsafe impl ::windows::core::Abi for EventSourceHandle { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtArchiveExportedLog<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(session: isize, logfilepath: Param1, locale: u32, flags: u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtArchiveExportedLog(session: isize, logfilepath: super::super::Foundation::PWSTR, locale: u32, flags: u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtArchiveExportedLog(::core::mem::transmute(session), logfilepath.into_param().abi(), ::core::mem::transmute(locale), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtCancel(object: isize) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtCancel(object: isize) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtCancel(::core::mem::transmute(object))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtClearLog<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(session: isize, channelpath: Param1, targetfilepath: Param2, flags: u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtClearLog(session: isize, channelpath: super::super::Foundation::PWSTR, targetfilepath: super::super::Foundation::PWSTR, flags: u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtClearLog(::core::mem::transmute(session), channelpath.into_param().abi(), targetfilepath.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtClose(object: isize) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtClose(object: isize) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtClose(::core::mem::transmute(object))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtCreateBookmark<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(bookmarkxml: Param0) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtCreateBookmark(bookmarkxml: super::super::Foundation::PWSTR) -> isize; } ::core::mem::transmute(EvtCreateBookmark(bookmarkxml.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtCreateRenderContext(valuepathscount: u32, valuepaths: *const super::super::Foundation::PWSTR, flags: u32) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtCreateRenderContext(valuepathscount: u32, valuepaths: *const super::super::Foundation::PWSTR, flags: u32) -> isize; } ::core::mem::transmute(EvtCreateRenderContext(::core::mem::transmute(valuepathscount), ::core::mem::transmute(valuepaths), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtExportLog<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(session: isize, path: Param1, query: Param2, targetfilepath: Param3, flags: u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtExportLog(session: isize, path: super::super::Foundation::PWSTR, query: super::super::Foundation::PWSTR, targetfilepath: super::super::Foundation::PWSTR, flags: u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtExportLog(::core::mem::transmute(session), path.into_param().abi(), query.into_param().abi(), targetfilepath.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtFormatMessage(publishermetadata: isize, event: isize, messageid: u32, valuecount: u32, values: *const EVT_VARIANT, flags: u32, buffersize: u32, buffer: super::super::Foundation::PWSTR, bufferused: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtFormatMessage(publishermetadata: isize, event: isize, messageid: u32, valuecount: u32, values: *const EVT_VARIANT, flags: u32, buffersize: u32, buffer: super::super::Foundation::PWSTR, bufferused: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtFormatMessage( ::core::mem::transmute(publishermetadata), ::core::mem::transmute(event), ::core::mem::transmute(messageid), ::core::mem::transmute(valuecount), ::core::mem::transmute(values), ::core::mem::transmute(flags), ::core::mem::transmute(buffersize), ::core::mem::transmute(buffer), ::core::mem::transmute(bufferused), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtGetChannelConfigProperty(channelconfig: isize, propertyid: EVT_CHANNEL_CONFIG_PROPERTY_ID, flags: u32, propertyvaluebuffersize: u32, propertyvaluebuffer: *mut EVT_VARIANT, propertyvaluebufferused: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtGetChannelConfigProperty(channelconfig: isize, propertyid: EVT_CHANNEL_CONFIG_PROPERTY_ID, flags: u32, propertyvaluebuffersize: u32, propertyvaluebuffer: *mut EVT_VARIANT, propertyvaluebufferused: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtGetChannelConfigProperty(::core::mem::transmute(channelconfig), ::core::mem::transmute(propertyid), ::core::mem::transmute(flags), ::core::mem::transmute(propertyvaluebuffersize), ::core::mem::transmute(propertyvaluebuffer), ::core::mem::transmute(propertyvaluebufferused))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtGetEventInfo(event: isize, propertyid: EVT_EVENT_PROPERTY_ID, propertyvaluebuffersize: u32, propertyvaluebuffer: *mut EVT_VARIANT, propertyvaluebufferused: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtGetEventInfo(event: isize, propertyid: EVT_EVENT_PROPERTY_ID, propertyvaluebuffersize: u32, propertyvaluebuffer: *mut EVT_VARIANT, propertyvaluebufferused: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtGetEventInfo(::core::mem::transmute(event), ::core::mem::transmute(propertyid), ::core::mem::transmute(propertyvaluebuffersize), ::core::mem::transmute(propertyvaluebuffer), ::core::mem::transmute(propertyvaluebufferused))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtGetEventMetadataProperty(eventmetadata: isize, propertyid: EVT_EVENT_METADATA_PROPERTY_ID, flags: u32, eventmetadatapropertybuffersize: u32, eventmetadatapropertybuffer: *mut EVT_VARIANT, eventmetadatapropertybufferused: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtGetEventMetadataProperty(eventmetadata: isize, propertyid: EVT_EVENT_METADATA_PROPERTY_ID, flags: u32, eventmetadatapropertybuffersize: u32, eventmetadatapropertybuffer: *mut EVT_VARIANT, eventmetadatapropertybufferused: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtGetEventMetadataProperty(::core::mem::transmute(eventmetadata), ::core::mem::transmute(propertyid), ::core::mem::transmute(flags), ::core::mem::transmute(eventmetadatapropertybuffersize), ::core::mem::transmute(eventmetadatapropertybuffer), ::core::mem::transmute(eventmetadatapropertybufferused))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtGetExtendedStatus(buffersize: u32, buffer: super::super::Foundation::PWSTR, bufferused: *mut u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtGetExtendedStatus(buffersize: u32, buffer: super::super::Foundation::PWSTR, bufferused: *mut u32) -> u32; } ::core::mem::transmute(EvtGetExtendedStatus(::core::mem::transmute(buffersize), ::core::mem::transmute(buffer), ::core::mem::transmute(bufferused))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtGetLogInfo(log: isize, propertyid: EVT_LOG_PROPERTY_ID, propertyvaluebuffersize: u32, propertyvaluebuffer: *mut EVT_VARIANT, propertyvaluebufferused: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtGetLogInfo(log: isize, propertyid: EVT_LOG_PROPERTY_ID, propertyvaluebuffersize: u32, propertyvaluebuffer: *mut EVT_VARIANT, propertyvaluebufferused: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtGetLogInfo(::core::mem::transmute(log), ::core::mem::transmute(propertyid), ::core::mem::transmute(propertyvaluebuffersize), ::core::mem::transmute(propertyvaluebuffer), ::core::mem::transmute(propertyvaluebufferused))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtGetObjectArrayProperty(objectarray: isize, propertyid: u32, arrayindex: u32, flags: u32, propertyvaluebuffersize: u32, propertyvaluebuffer: *mut EVT_VARIANT, propertyvaluebufferused: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtGetObjectArrayProperty(objectarray: isize, propertyid: u32, arrayindex: u32, flags: u32, propertyvaluebuffersize: u32, propertyvaluebuffer: *mut EVT_VARIANT, propertyvaluebufferused: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtGetObjectArrayProperty( ::core::mem::transmute(objectarray), ::core::mem::transmute(propertyid), ::core::mem::transmute(arrayindex), ::core::mem::transmute(flags), ::core::mem::transmute(propertyvaluebuffersize), ::core::mem::transmute(propertyvaluebuffer), ::core::mem::transmute(propertyvaluebufferused), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtGetObjectArraySize(objectarray: isize, objectarraysize: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtGetObjectArraySize(objectarray: isize, objectarraysize: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtGetObjectArraySize(::core::mem::transmute(objectarray), ::core::mem::transmute(objectarraysize))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtGetPublisherMetadataProperty(publishermetadata: isize, propertyid: EVT_PUBLISHER_METADATA_PROPERTY_ID, flags: u32, publishermetadatapropertybuffersize: u32, publishermetadatapropertybuffer: *mut EVT_VARIANT, publishermetadatapropertybufferused: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtGetPublisherMetadataProperty(publishermetadata: isize, propertyid: EVT_PUBLISHER_METADATA_PROPERTY_ID, flags: u32, publishermetadatapropertybuffersize: u32, publishermetadatapropertybuffer: *mut EVT_VARIANT, publishermetadatapropertybufferused: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtGetPublisherMetadataProperty( ::core::mem::transmute(publishermetadata), ::core::mem::transmute(propertyid), ::core::mem::transmute(flags), ::core::mem::transmute(publishermetadatapropertybuffersize), ::core::mem::transmute(publishermetadatapropertybuffer), ::core::mem::transmute(publishermetadatapropertybufferused), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtGetQueryInfo(queryorsubscription: isize, propertyid: EVT_QUERY_PROPERTY_ID, propertyvaluebuffersize: u32, propertyvaluebuffer: *mut EVT_VARIANT, propertyvaluebufferused: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtGetQueryInfo(queryorsubscription: isize, propertyid: EVT_QUERY_PROPERTY_ID, propertyvaluebuffersize: u32, propertyvaluebuffer: *mut EVT_VARIANT, propertyvaluebufferused: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtGetQueryInfo(::core::mem::transmute(queryorsubscription), ::core::mem::transmute(propertyid), ::core::mem::transmute(propertyvaluebuffersize), ::core::mem::transmute(propertyvaluebuffer), ::core::mem::transmute(propertyvaluebufferused))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtNext(resultset: isize, eventssize: u32, events: *mut isize, timeout: u32, flags: u32, returned: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtNext(resultset: isize, eventssize: u32, events: *mut isize, timeout: u32, flags: u32, returned: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtNext(::core::mem::transmute(resultset), ::core::mem::transmute(eventssize), ::core::mem::transmute(events), ::core::mem::transmute(timeout), ::core::mem::transmute(flags), ::core::mem::transmute(returned))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtNextChannelPath(channelenum: isize, channelpathbuffersize: u32, channelpathbuffer: super::super::Foundation::PWSTR, channelpathbufferused: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtNextChannelPath(channelenum: isize, channelpathbuffersize: u32, channelpathbuffer: super::super::Foundation::PWSTR, channelpathbufferused: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtNextChannelPath(::core::mem::transmute(channelenum), ::core::mem::transmute(channelpathbuffersize), ::core::mem::transmute(channelpathbuffer), ::core::mem::transmute(channelpathbufferused))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn EvtNextEventMetadata(eventmetadataenum: isize, flags: u32) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtNextEventMetadata(eventmetadataenum: isize, flags: u32) -> isize; } ::core::mem::transmute(EvtNextEventMetadata(::core::mem::transmute(eventmetadataenum), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtNextPublisherId(publisherenum: isize, publisheridbuffersize: u32, publisheridbuffer: super::super::Foundation::PWSTR, publisheridbufferused: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtNextPublisherId(publisherenum: isize, publisheridbuffersize: u32, publisheridbuffer: super::super::Foundation::PWSTR, publisheridbufferused: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtNextPublisherId(::core::mem::transmute(publisherenum), ::core::mem::transmute(publisheridbuffersize), ::core::mem::transmute(publisheridbuffer), ::core::mem::transmute(publisheridbufferused))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtOpenChannelConfig<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(session: isize, channelpath: Param1, flags: u32) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtOpenChannelConfig(session: isize, channelpath: super::super::Foundation::PWSTR, flags: u32) -> isize; } ::core::mem::transmute(EvtOpenChannelConfig(::core::mem::transmute(session), channelpath.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn EvtOpenChannelEnum(session: isize, flags: u32) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtOpenChannelEnum(session: isize, flags: u32) -> isize; } ::core::mem::transmute(EvtOpenChannelEnum(::core::mem::transmute(session), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn EvtOpenEventMetadataEnum(publishermetadata: isize, flags: u32) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtOpenEventMetadataEnum(publishermetadata: isize, flags: u32) -> isize; } ::core::mem::transmute(EvtOpenEventMetadataEnum(::core::mem::transmute(publishermetadata), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtOpenLog<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(session: isize, path: Param1, flags: u32) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtOpenLog(session: isize, path: super::super::Foundation::PWSTR, flags: u32) -> isize; } ::core::mem::transmute(EvtOpenLog(::core::mem::transmute(session), path.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn EvtOpenPublisherEnum(session: isize, flags: u32) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtOpenPublisherEnum(session: isize, flags: u32) -> isize; } ::core::mem::transmute(EvtOpenPublisherEnum(::core::mem::transmute(session), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtOpenPublisherMetadata<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(session: isize, publisherid: Param1, logfilepath: Param2, locale: u32, flags: u32) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtOpenPublisherMetadata(session: isize, publisherid: super::super::Foundation::PWSTR, logfilepath: super::super::Foundation::PWSTR, locale: u32, flags: u32) -> isize; } ::core::mem::transmute(EvtOpenPublisherMetadata(::core::mem::transmute(session), publisherid.into_param().abi(), logfilepath.into_param().abi(), ::core::mem::transmute(locale), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn EvtOpenSession(loginclass: EVT_LOGIN_CLASS, login: *const ::core::ffi::c_void, timeout: u32, flags: u32) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtOpenSession(loginclass: EVT_LOGIN_CLASS, login: *const ::core::ffi::c_void, timeout: u32, flags: u32) -> isize; } ::core::mem::transmute(EvtOpenSession(::core::mem::transmute(loginclass), ::core::mem::transmute(login), ::core::mem::transmute(timeout), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtQuery<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(session: isize, path: Param1, query: Param2, flags: u32) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtQuery(session: isize, path: super::super::Foundation::PWSTR, query: super::super::Foundation::PWSTR, flags: u32) -> isize; } ::core::mem::transmute(EvtQuery(::core::mem::transmute(session), path.into_param().abi(), query.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtRender(context: isize, fragment: isize, flags: u32, buffersize: u32, buffer: *mut ::core::ffi::c_void, bufferused: *mut u32, propertycount: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtRender(context: isize, fragment: isize, flags: u32, buffersize: u32, buffer: *mut ::core::ffi::c_void, bufferused: *mut u32, propertycount: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtRender(::core::mem::transmute(context), ::core::mem::transmute(fragment), ::core::mem::transmute(flags), ::core::mem::transmute(buffersize), ::core::mem::transmute(buffer), ::core::mem::transmute(bufferused), ::core::mem::transmute(propertycount))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtSaveChannelConfig(channelconfig: isize, flags: u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtSaveChannelConfig(channelconfig: isize, flags: u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtSaveChannelConfig(::core::mem::transmute(channelconfig), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtSeek(resultset: isize, position: i64, bookmark: isize, timeout: u32, flags: u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtSeek(resultset: isize, position: i64, bookmark: isize, timeout: u32, flags: u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtSeek(::core::mem::transmute(resultset), ::core::mem::transmute(position), ::core::mem::transmute(bookmark), ::core::mem::transmute(timeout), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtSetChannelConfigProperty(channelconfig: isize, propertyid: EVT_CHANNEL_CONFIG_PROPERTY_ID, flags: u32, propertyvalue: *const EVT_VARIANT) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtSetChannelConfigProperty(channelconfig: isize, propertyid: EVT_CHANNEL_CONFIG_PROPERTY_ID, flags: u32, propertyvalue: *const EVT_VARIANT) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtSetChannelConfigProperty(::core::mem::transmute(channelconfig), ::core::mem::transmute(propertyid), ::core::mem::transmute(flags), ::core::mem::transmute(propertyvalue))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtSubscribe<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(session: isize, signalevent: Param1, channelpath: Param2, query: Param3, bookmark: isize, context: *const ::core::ffi::c_void, callback: ::core::option::Option<EVT_SUBSCRIBE_CALLBACK>, flags: u32) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtSubscribe(session: isize, signalevent: super::super::Foundation::HANDLE, channelpath: super::super::Foundation::PWSTR, query: super::super::Foundation::PWSTR, bookmark: isize, context: *const ::core::ffi::c_void, callback: ::windows::core::RawPtr, flags: u32) -> isize; } ::core::mem::transmute(EvtSubscribe(::core::mem::transmute(session), signalevent.into_param().abi(), channelpath.into_param().abi(), query.into_param().abi(), ::core::mem::transmute(bookmark), ::core::mem::transmute(context), ::core::mem::transmute(callback), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EvtUpdateBookmark(bookmark: isize, event: isize) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EvtUpdateBookmark(bookmark: isize, event: isize) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EvtUpdateBookmark(::core::mem::transmute(bookmark), ::core::mem::transmute(event))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetEventLogInformation<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(heventlog: Param0, dwinfolevel: u32, lpbuffer: *mut ::core::ffi::c_void, cbbufsize: u32, pcbbytesneeded: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetEventLogInformation(heventlog: super::super::Foundation::HANDLE, dwinfolevel: u32, lpbuffer: *mut ::core::ffi::c_void, cbbufsize: u32, pcbbytesneeded: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(GetEventLogInformation(heventlog.into_param().abi(), ::core::mem::transmute(dwinfolevel), ::core::mem::transmute(lpbuffer), ::core::mem::transmute(cbbufsize), ::core::mem::transmute(pcbbytesneeded))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetNumberOfEventLogRecords<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(heventlog: Param0, numberofrecords: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetNumberOfEventLogRecords(heventlog: super::super::Foundation::HANDLE, numberofrecords: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(GetNumberOfEventLogRecords(heventlog.into_param().abi(), ::core::mem::transmute(numberofrecords))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetOldestEventLogRecord<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(heventlog: Param0, oldestrecord: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetOldestEventLogRecord(heventlog: super::super::Foundation::HANDLE, oldestrecord: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(GetOldestEventLogRecord(heventlog.into_param().abi(), ::core::mem::transmute(oldestrecord))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NotifyChangeEventLog<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(heventlog: Param0, hevent: Param1) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NotifyChangeEventLog(heventlog: super::super::Foundation::HANDLE, hevent: super::super::Foundation::HANDLE) -> super::super::Foundation::BOOL; } ::core::mem::transmute(NotifyChangeEventLog(heventlog.into_param().abi(), hevent.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn OpenBackupEventLogA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(lpuncservername: Param0, lpfilename: Param1) -> EventLogHandle { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn OpenBackupEventLogA(lpuncservername: super::super::Foundation::PSTR, lpfilename: super::super::Foundation::PSTR) -> EventLogHandle; } ::core::mem::transmute(OpenBackupEventLogA(lpuncservername.into_param().abi(), lpfilename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn OpenBackupEventLogW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(lpuncservername: Param0, lpfilename: Param1) -> EventLogHandle { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn OpenBackupEventLogW(lpuncservername: super::super::Foundation::PWSTR, lpfilename: super::super::Foundation::PWSTR) -> EventLogHandle; } ::core::mem::transmute(OpenBackupEventLogW(lpuncservername.into_param().abi(), lpfilename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn OpenEventLogA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(lpuncservername: Param0, lpsourcename: Param1) -> EventLogHandle { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn OpenEventLogA(lpuncservername: super::super::Foundation::PSTR, lpsourcename: super::super::Foundation::PSTR) -> EventLogHandle; } ::core::mem::transmute(OpenEventLogA(lpuncservername.into_param().abi(), lpsourcename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn OpenEventLogW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(lpuncservername: Param0, lpsourcename: Param1) -> EventLogHandle { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn OpenEventLogW(lpuncservername: super::super::Foundation::PWSTR, lpsourcename: super::super::Foundation::PWSTR) -> EventLogHandle; } ::core::mem::transmute(OpenEventLogW(lpuncservername.into_param().abi(), lpsourcename.into_param().abi())) } #[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 READ_EVENT_LOG_READ_FLAGS(pub u32); pub const EVENTLOG_SEEK_READ: READ_EVENT_LOG_READ_FLAGS = READ_EVENT_LOG_READ_FLAGS(2u32); pub const EVENTLOG_SEQUENTIAL_READ: READ_EVENT_LOG_READ_FLAGS = READ_EVENT_LOG_READ_FLAGS(1u32); impl ::core::convert::From<u32> for READ_EVENT_LOG_READ_FLAGS { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for READ_EVENT_LOG_READ_FLAGS { type Abi = Self; } impl ::core::ops::BitOr for READ_EVENT_LOG_READ_FLAGS { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for READ_EVENT_LOG_READ_FLAGS { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for READ_EVENT_LOG_READ_FLAGS { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for READ_EVENT_LOG_READ_FLAGS { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for READ_EVENT_LOG_READ_FLAGS { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct REPORT_EVENT_TYPE(pub u16); pub const EVENTLOG_SUCCESS: REPORT_EVENT_TYPE = REPORT_EVENT_TYPE(0u16); pub const EVENTLOG_AUDIT_FAILURE: REPORT_EVENT_TYPE = REPORT_EVENT_TYPE(16u16); pub const EVENTLOG_AUDIT_SUCCESS: REPORT_EVENT_TYPE = REPORT_EVENT_TYPE(8u16); pub const EVENTLOG_ERROR_TYPE: REPORT_EVENT_TYPE = REPORT_EVENT_TYPE(1u16); pub const EVENTLOG_INFORMATION_TYPE: REPORT_EVENT_TYPE = REPORT_EVENT_TYPE(4u16); pub const EVENTLOG_WARNING_TYPE: REPORT_EVENT_TYPE = REPORT_EVENT_TYPE(2u16); impl ::core::convert::From<u16> for REPORT_EVENT_TYPE { fn from(value: u16) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for REPORT_EVENT_TYPE { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReadEventLogA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(heventlog: Param0, dwreadflags: READ_EVENT_LOG_READ_FLAGS, dwrecordoffset: u32, lpbuffer: *mut ::core::ffi::c_void, nnumberofbytestoread: u32, pnbytesread: *mut u32, pnminnumberofbytesneeded: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReadEventLogA(heventlog: super::super::Foundation::HANDLE, dwreadflags: READ_EVENT_LOG_READ_FLAGS, dwrecordoffset: u32, lpbuffer: *mut ::core::ffi::c_void, nnumberofbytestoread: u32, pnbytesread: *mut u32, pnminnumberofbytesneeded: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(ReadEventLogA(heventlog.into_param().abi(), ::core::mem::transmute(dwreadflags), ::core::mem::transmute(dwrecordoffset), ::core::mem::transmute(lpbuffer), ::core::mem::transmute(nnumberofbytestoread), ::core::mem::transmute(pnbytesread), ::core::mem::transmute(pnminnumberofbytesneeded))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReadEventLogW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(heventlog: Param0, dwreadflags: READ_EVENT_LOG_READ_FLAGS, dwrecordoffset: u32, lpbuffer: *mut ::core::ffi::c_void, nnumberofbytestoread: u32, pnbytesread: *mut u32, pnminnumberofbytesneeded: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReadEventLogW(heventlog: super::super::Foundation::HANDLE, dwreadflags: READ_EVENT_LOG_READ_FLAGS, dwrecordoffset: u32, lpbuffer: *mut ::core::ffi::c_void, nnumberofbytestoread: u32, pnbytesread: *mut u32, pnminnumberofbytesneeded: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(ReadEventLogW(heventlog.into_param().abi(), ::core::mem::transmute(dwreadflags), ::core::mem::transmute(dwrecordoffset), ::core::mem::transmute(lpbuffer), ::core::mem::transmute(nnumberofbytestoread), ::core::mem::transmute(pnbytesread), ::core::mem::transmute(pnminnumberofbytesneeded))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RegisterEventSourceA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(lpuncservername: Param0, lpsourcename: Param1) -> EventSourceHandle { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RegisterEventSourceA(lpuncservername: super::super::Foundation::PSTR, lpsourcename: super::super::Foundation::PSTR) -> EventSourceHandle; } ::core::mem::transmute(RegisterEventSourceA(lpuncservername.into_param().abi(), lpsourcename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RegisterEventSourceW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(lpuncservername: Param0, lpsourcename: Param1) -> EventSourceHandle { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RegisterEventSourceW(lpuncservername: super::super::Foundation::PWSTR, lpsourcename: super::super::Foundation::PWSTR) -> EventSourceHandle; } ::core::mem::transmute(RegisterEventSourceW(lpuncservername.into_param().abi(), lpsourcename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportEventA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::PSID>>(heventlog: Param0, wtype: REPORT_EVENT_TYPE, wcategory: u16, dweventid: u32, lpusersid: Param4, wnumstrings: u16, dwdatasize: u32, lpstrings: *const super::super::Foundation::PSTR, lprawdata: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportEventA(heventlog: super::super::Foundation::HANDLE, wtype: REPORT_EVENT_TYPE, wcategory: u16, dweventid: u32, lpusersid: super::super::Foundation::PSID, wnumstrings: u16, dwdatasize: u32, lpstrings: *const super::super::Foundation::PSTR, lprawdata: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL; } ::core::mem::transmute(ReportEventA( heventlog.into_param().abi(), ::core::mem::transmute(wtype), ::core::mem::transmute(wcategory), ::core::mem::transmute(dweventid), lpusersid.into_param().abi(), ::core::mem::transmute(wnumstrings), ::core::mem::transmute(dwdatasize), ::core::mem::transmute(lpstrings), ::core::mem::transmute(lprawdata), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportEventW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::PSID>>(heventlog: Param0, wtype: REPORT_EVENT_TYPE, wcategory: u16, dweventid: u32, lpusersid: Param4, wnumstrings: u16, dwdatasize: u32, lpstrings: *const super::super::Foundation::PWSTR, lprawdata: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportEventW(heventlog: super::super::Foundation::HANDLE, wtype: REPORT_EVENT_TYPE, wcategory: u16, dweventid: u32, lpusersid: super::super::Foundation::PSID, wnumstrings: u16, dwdatasize: u32, lpstrings: *const super::super::Foundation::PWSTR, lprawdata: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL; } ::core::mem::transmute(ReportEventW( heventlog.into_param().abi(), ::core::mem::transmute(wtype), ::core::mem::transmute(wcategory), ::core::mem::transmute(dweventid), lpusersid.into_param().abi(), ::core::mem::transmute(wnumstrings), ::core::mem::transmute(dwdatasize), ::core::mem::transmute(lpstrings), ::core::mem::transmute(lprawdata), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); }
extern crate fnv; extern crate nx; mod item_provider; mod my_node; use item_provider::*; fn main() { let pro = ItemProvider::new(); println!("{:?}", pro.get_item_data(2190000)); println!("{:?}", pro.get_item_data(2190001)); }
use clippy_utils::{ diagnostics::span_lint_and_sugg, get_async_fn_body, is_async_fn, source::{snippet_with_applicability, snippet_with_context, walk_span_to_context}, visitors::expr_visitor_no_bodies, }; use rustc_errors::Applicability; use rustc_hir::intravisit::{FnKind, Visitor}; use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, FnRetTy, HirId}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::lint::in_external_macro; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{Span, SyntaxContext}; declare_clippy_lint! { /// ### What it does /// Checks for missing return statements at the end of a block. /// /// ### Why is this bad? /// Actually omitting the return keyword is idiomatic Rust code. Programmers /// coming from other languages might prefer the expressiveness of `return`. It's possible to miss /// the last returning statement because the only difference is a missing `;`. Especially in bigger /// code with multiple return paths having a `return` keyword makes it easier to find the /// corresponding statements. /// /// ### Example /// ```rust /// fn foo(x: usize) -> usize { /// x /// } /// ``` /// add return /// ```rust /// fn foo(x: usize) -> usize { /// return x; /// } /// ``` #[clippy::version = "1.33.0"] pub IMPLICIT_RETURN, restriction, "use a return statement like `return expr` instead of an expression" } declare_lint_pass!(ImplicitReturn => [IMPLICIT_RETURN]); fn lint_return(cx: &LateContext<'_>, span: Span) { let mut app = Applicability::MachineApplicable; let snip = snippet_with_applicability(cx, span, "..", &mut app); span_lint_and_sugg( cx, IMPLICIT_RETURN, span, "missing `return` statement", "add `return` as shown", format!("return {}", snip), app, ); } fn lint_break(cx: &LateContext<'_>, break_span: Span, expr_span: Span) { let mut app = Applicability::MachineApplicable; let snip = snippet_with_context(cx, expr_span, break_span.ctxt(), "..", &mut app).0; span_lint_and_sugg( cx, IMPLICIT_RETURN, break_span, "missing `return` statement", "change `break` to `return` as shown", format!("return {}", snip), app, ); } #[derive(Clone, Copy, PartialEq, Eq)] enum LintLocation { /// The lint was applied to a parent expression. Parent, /// The lint was applied to this expression, a child, or not applied. Inner, } impl LintLocation { fn still_parent(self, b: bool) -> Self { if b { self } else { Self::Inner } } fn is_parent(self) -> bool { self == Self::Parent } } // Gets the call site if the span is in a child context. Otherwise returns `None`. fn get_call_site(span: Span, ctxt: SyntaxContext) -> Option<Span> { (span.ctxt() != ctxt).then(|| walk_span_to_context(span, ctxt).unwrap_or(span)) } fn lint_implicit_returns( cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, // The context of the function body. ctxt: SyntaxContext, // Whether the expression is from a macro expansion. call_site_span: Option<Span>, ) -> LintLocation { match expr.kind { ExprKind::Block( Block { expr: Some(block_expr), .. }, _, ) => lint_implicit_returns( cx, block_expr, ctxt, call_site_span.or_else(|| get_call_site(block_expr.span, ctxt)), ) .still_parent(call_site_span.is_some()), ExprKind::If(_, then_expr, Some(else_expr)) => { // Both `then_expr` or `else_expr` are required to be blocks in the same context as the `if`. Don't // bother checking. let res = lint_implicit_returns(cx, then_expr, ctxt, call_site_span).still_parent(call_site_span.is_some()); if res.is_parent() { // The return was added as a parent of this if expression. return res; } lint_implicit_returns(cx, else_expr, ctxt, call_site_span).still_parent(call_site_span.is_some()) }, ExprKind::Match(_, arms, _) => { for arm in arms { let res = lint_implicit_returns( cx, arm.body, ctxt, call_site_span.or_else(|| get_call_site(arm.body.span, ctxt)), ) .still_parent(call_site_span.is_some()); if res.is_parent() { // The return was added as a parent of this match expression. return res; } } LintLocation::Inner }, ExprKind::Loop(block, ..) => { let mut add_return = false; expr_visitor_no_bodies(|e| { if let ExprKind::Break(dest, sub_expr) = e.kind { if dest.target_id.ok() == Some(expr.hir_id) { if call_site_span.is_none() && e.span.ctxt() == ctxt { // At this point sub_expr can be `None` in async functions which either diverge, or return // the unit type. if let Some(sub_expr) = sub_expr { lint_break(cx, e.span, sub_expr.span); } } else { // the break expression is from a macro call, add a return to the loop add_return = true; } } } true }) .visit_block(block); if add_return { #[allow(clippy::option_if_let_else)] if let Some(span) = call_site_span { lint_return(cx, span); LintLocation::Parent } else { lint_return(cx, expr.span); LintLocation::Inner } } else { LintLocation::Inner } }, // If expressions without an else clause, and blocks without a final expression can only be the final expression // if they are divergent, or return the unit type. ExprKind::If(_, _, None) | ExprKind::Block(Block { expr: None, .. }, _) | ExprKind::Ret(_) => { LintLocation::Inner }, // Any divergent expression doesn't need a return statement. ExprKind::MethodCall(..) | ExprKind::Call(..) | ExprKind::Binary(..) | ExprKind::Unary(..) | ExprKind::Index(..) if cx.typeck_results().expr_ty(expr).is_never() => { LintLocation::Inner }, _ => { #[allow(clippy::option_if_let_else)] if let Some(span) = call_site_span { lint_return(cx, span); LintLocation::Parent } else { lint_return(cx, expr.span); LintLocation::Inner } }, } } impl<'tcx> LateLintPass<'tcx> for ImplicitReturn { fn check_fn( &mut self, cx: &LateContext<'tcx>, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body: &'tcx Body<'_>, span: Span, _: HirId, ) { if (!matches!(kind, FnKind::Closure) && matches!(decl.output, FnRetTy::DefaultReturn(_))) || span.ctxt() != body.value.span.ctxt() || in_external_macro(cx.sess(), span) { return; } let res_ty = cx.typeck_results().expr_ty(&body.value); if res_ty.is_unit() || res_ty.is_never() { return; } let expr = if is_async_fn(kind) { match get_async_fn_body(cx.tcx, body) { Some(e) => e, None => return, } } else { &body.value }; lint_implicit_returns(cx, expr, expr.span.ctxt(), None); } }
use crate::config::get_config; use crate::fs::write_telegram_chat_id; use crate::telegram::{Api, ParseMode, SendMessageParams}; use crate::unwrap_err; use nanoid; use std::thread; use std::time::Duration; pub fn gen_secret() { println!("{}", nanoid::simple()); } pub fn telegram_setup() { let token = nanoid::generate(6); let config = unwrap_err!(get_config()); let api = Api::from_config(&config).expect("Telegram bot token must be configured"); let sleep_duration = Duration::from_secs(3); println!("Send the following message to your bot:\n /auth {}", token); println!("Polling for incoming message..."); 'poll: loop { let updates = api.poll_updates().expect("Unable to fetch updates"); for update in updates { if let Some(message) = update.message { if let Some((command, params)) = message.bot_command() { match command { // Ignore /start command, because it's required // to enable chatting with the bot "start" => {} "auth" if params == token => { let chat_id = message.chat.id; println!("Message received. Saving chat id ({})...", chat_id); write_telegram_chat_id(chat_id) .expect("Unable to save telegram chat id"); api.send_message(&SendMessageParams { text: "🎉 Congratulations! Toby is now set up and will send notifications to this chat.", chat_id: &chat_id.to_string(), parse_mode: Some(ParseMode::Markdown), ..Default::default() }).expect("Unable to send message"); break 'poll; } _ => { println!( "Invalid command: /{} {}. Did you mistype the token?", command, params ); } }; } } } thread::sleep(sleep_duration); } }
#![allow(clippy::unreadable_literal)] // Each sub-module represents a C-level struct to respective IOCTL request // and idiomatic Rust struct around it. use winapi::shared::minwindef; mod info; mod query_info; mod status; mod wait_status; pub use self::info::BatteryInformation; pub use self::query_info::BatteryQueryInformation; pub use self::status::BatteryStatus; pub use self::wait_status::BatteryWaitStatus; // Following values are based on the https://www.ioctls.net data pub const IOCTL_BATTERY_QUERY_TAG: minwindef::DWORD = 0x294040; pub const IOCTL_BATTERY_QUERY_INFORMATION: minwindef::DWORD = 0x294044; pub const IOCTL_BATTERY_QUERY_STATUS: minwindef::DWORD = 0x29404c; pub mod info_level { #![allow(non_camel_case_types, non_upper_case_globals)] /// For some reasons, "winapi==0.3.6" `ENUM!` macro fails to compile with /// error: no rules expected the token `@` /// so defining `BATTERY_QUERY_INFORMATION_LEVEL` "enum" manually. pub type BATTERY_QUERY_INFORMATION_LEVEL = u32; // pub const BatteryInformation: BATTERY_QUERY_INFORMATION_LEVEL = 0; // pub const BatteryGranularityInformation: BATTERY_QUERY_INFORMATION_LEVEL = 1; pub const BatteryTemperature: BATTERY_QUERY_INFORMATION_LEVEL = 2; // pub const BatteryEstimatedTime: BATTERY_QUERY_INFORMATION_LEVEL = 3; pub const BatteryDeviceName: BATTERY_QUERY_INFORMATION_LEVEL = 4; // pub const BatteryManufactureDate: BATTERY_QUERY_INFORMATION_LEVEL = 5; pub const BatteryManufactureName: BATTERY_QUERY_INFORMATION_LEVEL = 6; // pub const BatteryUniqueID: BATTERY_QUERY_INFORMATION_LEVEL = 7; pub const BatterySerialNumber: BATTERY_QUERY_INFORMATION_LEVEL = 8; }
use std::fmt::{Debug, Display, Formatter}; use std::ops::Mul; use crate::matrix::Matrix4; use crate::number_traits::Float; use crate::vector::Vector3; #[derive(Debug, Clone)] pub struct Quaternion<T> where T: Debug, { scalar_part: T, vector_part: Vector3<T>, } impl<T> Quaternion<T> where T: Debug + Float, { pub fn new(scalar_part: T, vector_part: Vector3<T>) -> Self { Self { scalar_part, vector_part, } } pub fn from_axis_angle(axis: &Vector3<T>, angle: T) -> Self { let half_angle = angle.half(); let half_angle_sin = half_angle.sin(); let x = axis.x * half_angle_sin; let y = axis.y * half_angle_sin; let z = axis.z * half_angle_sin; let w = half_angle.cos(); Self::new(w, Vector3::new(x, y, z)) } pub fn from_euler(angles: &Vector3<T>) -> Self { let roll = angles.x; let pitch = angles.y; let yaw = angles.z; let half_roll = roll.half(); let half_pitch = pitch.half(); let half_yaw = yaw.half(); let cy = half_yaw.cos(); let sy = half_yaw.sin(); let cp = half_pitch.cos(); let sp = half_pitch.sin(); let cr = half_roll.cos(); let sr = half_roll.sin(); let w = cr * cp * cy + sr * sp * sy; let x = sr * cp * cy - cr * sp * sy; let y = cr * sp * cy + sr * cp * sy; let z = cr * cp * sy - sr * sp * cy; Quaternion::new(w, Vector3::new(x, y, z)) } #[rustfmt::skip] #[allow(clippy::similar_names)] pub fn rotation_matrix(&self) -> Matrix4<T> { let (w, x, y, z) = ( self.scalar_part, self.vector_part.x, self.vector_part.y, self.vector_part.z, ); let x2 = x + x; let y2 = y + y; let z2 = z + z; let w2 = w + w; let xx2 = x2 * x; let xy2 = x2 * y; let xz2 = x2 * z; let yy2 = y2 * y; let yz2 = y2 * z; let zz2 = z2 * z; let wx2 = w2 * x; let wy2 = w2 * y; let wz2 = w2 * z; Matrix4::with_values([ T::one() - yy2 - zz2, xy2 - wz2, xz2 + wy2, T::zero(), xy2 + wz2, T::one() - xx2 - zz2, yz2 - wx2, T::zero(), xz2 - wy2, yz2 + wx2, T::one() - xx2 - yy2, T::zero(), T::zero(), T::zero(), T::zero(), T::one() ]) } pub fn normalize(&mut self) { let norm = self.norm(); self.vector_part /= norm; self.scalar_part /= norm; } #[must_use] pub fn normalized(&self) -> Self { let mut normalized_quaternion = self.clone(); normalized_quaternion.normalize(); normalized_quaternion } pub fn norm(&self) -> T { let x = self.vector_part.x; let y = self.vector_part.y; let z = self.vector_part.z; let w = self.scalar_part; let xx = x * x; let yy = y * y; let zz = z * z; let ww = w * w; (ww + xx + yy + zz).sqrt() } } impl<T> Display for Quaternion<T> where T: Debug + Float, { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { writeln!( f, "({} + {} i + {} j + {} k)", self.scalar_part, self.vector_part.x, self.vector_part.y, self.vector_part.z ) } } impl<T> Mul for Quaternion<T> where T: Debug + Float, { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let x1 = self.vector_part.x; let y1 = self.vector_part.y; let z1 = self.vector_part.z; let w1 = self.scalar_part; let x2 = rhs.vector_part.x; let y2 = rhs.vector_part.y; let z2 = rhs.vector_part.z; let w2 = rhs.scalar_part; let scalar_part = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2; let vector_part = Vector3::new( x1 * w2 + y1 * z2 - z1 * y2 + w1 * x2, y1 * w2 + z1 * x2 + w1 * y2 - x1 * z2, z1 * w2 + w1 * z2 + x1 * y2 - y1 * x2, ); Quaternion::new(scalar_part, vector_part) } } #[cfg(test)] mod tests { use assert_float_eq::assert_float_absolute_eq; use super::*; #[test] fn mul() { let q1 = Quaternion::new(12.4, Vector3::new(1.1, 2.0, 4.4)); let q2 = Quaternion::new(4.0, Vector3::new(0.3, 45.0, 5.0)); let result = q1 * q2; assert_float_absolute_eq!(result.scalar_part, -62.73, 0.01); assert_float_absolute_eq!(result.vector_part.x, -179.88, 0.01); assert_float_absolute_eq!(result.vector_part.y, 561.82, 0.01); assert_float_absolute_eq!(result.vector_part.z, 128.5, 0.01); } #[test] fn rotation_matrix() { let q = Quaternion::new(0.56, Vector3::new(0.77, -0.31, 0.0)); let matrix = q.rotation_matrix(); assert_float_absolute_eq!(matrix[0][0], 0.80, 0.02); assert_float_absolute_eq!(matrix[0][1], -0.47, 0.02); assert_float_absolute_eq!(matrix[0][2], -0.34, 0.02); assert_float_absolute_eq!(matrix[0][3], 0.0, 0.02); assert_float_absolute_eq!(matrix[1][0], -0.47, 0.02); assert_float_absolute_eq!(matrix[1][1], -0.18, 0.02); assert_float_absolute_eq!(matrix[1][2], -0.86, 0.02); assert_float_absolute_eq!(matrix[1][3], 0.0, 0.02); assert_float_absolute_eq!(matrix[2][0], 0.34, 0.02); assert_float_absolute_eq!(matrix[2][1], 0.86, 0.02); assert_float_absolute_eq!(matrix[2][2], -0.37, 0.02); assert_float_absolute_eq!(matrix[2][3], 0.0, 0.02); assert_float_absolute_eq!(matrix[3][0], 0.0, 0.02); assert_float_absolute_eq!(matrix[3][1], 0.0, 0.02); assert_float_absolute_eq!(matrix[3][2], 0.0, 0.02); assert_float_absolute_eq!(matrix[3][3], 1.0, 0.02); } #[test] fn norm() { let quaternion = Quaternion::new(23.0, Vector3::new(12.0, 34.0, 56.0)); let norm = quaternion.norm(); assert_float_absolute_eq!(norm, 70.46, 0.01); } #[test] fn normalize() { let mut quaternion = Quaternion::new(23.0, Vector3::new(12.0, 34.0, 56.0)); quaternion.normalize(); assert_float_absolute_eq!(quaternion.scalar_part, 0.32, 0.01); assert_float_absolute_eq!(quaternion.vector_part.x, 0.17, 0.01); assert_float_absolute_eq!(quaternion.vector_part.y, 0.48, 0.01); assert_float_absolute_eq!(quaternion.vector_part.z, 0.79, 0.01); } #[test] fn normalized() { let quaternion = Quaternion::new(23.0, Vector3::new(12.0, 34.0, 56.0)); let normalized = quaternion.normalized(); assert_float_absolute_eq!(normalized.scalar_part, 0.32, 0.01); assert_float_absolute_eq!(normalized.vector_part.x, 0.17, 0.01); assert_float_absolute_eq!(normalized.vector_part.y, 0.48, 0.01); assert_float_absolute_eq!(normalized.vector_part.z, 0.79, 0.01); } #[test] fn from_axis_angle() { let axis = Vector3::new(1.0, 2.0, 3.0).normalized(); let angle = 0.74; let quaternion = Quaternion::from_axis_angle(&axis, angle); assert_float_absolute_eq!(quaternion.scalar_part, 0.93, 0.01); assert_float_absolute_eq!(quaternion.vector_part.x, 0.09, 0.01); assert_float_absolute_eq!(quaternion.vector_part.y, 0.19, 0.01); assert_float_absolute_eq!(quaternion.vector_part.z, 0.28, 0.01); } #[test] fn from_euler() { let angles = Vector3::new(0.4, 1.3, 5.0); let quaternion = Quaternion::from_euler(&angles); assert_float_absolute_eq!(quaternion.scalar_part, -0.55, 0.01); assert_float_absolute_eq!(quaternion.vector_part.x, -0.48, 0.01); assert_float_absolute_eq!(quaternion.vector_part.y, -0.38, 0.01); assert_float_absolute_eq!(quaternion.vector_part.z, 0.56, 0.01); } }
use hashbrown::HashSet; use regex::Regex; use std::iter::FromIterator; pub fn run() { let input = include_str!("input/day4bigboi.txt").trim(); println!("{}", exercise_1(&input)); println!("{}", exercise_2(&input)); } fn exercise_1(input: &str) -> usize { let mut lines = input.lines(); let mut valid = 0; let mut current = 0; let mut cid_found = false; while let Some(start) = lines.next() { if start.trim().is_empty() { if current == 8 || (current == 7 && !cid_found) { valid += 1; } cid_found = false; current = 0; } else { cid_found |= start.contains("cid:"); current += start.split(' ').count(); } } if current == 8 || (current == 7 && !cid_found) { valid += 1; } valid } fn exercise_2(input: &str) -> usize { let mut lines = input.lines(); let mut valid = 0; let mut current = 0; let mut cid_found = false; let eycs = HashSet::<&str>::from_iter( vec!["amb", "blu", "brn", "gry", "grn", "hzl", "oth"].into_iter(), ); while let Some(start) = lines.next() { if start.trim().is_empty() { if current == 8 || (current == 7 && !cid_found) { valid += 1; } cid_found = false; current = 0; } else { for data in start.split(' ') { let key = &data[0..3]; let value = &data[4..]; if match key { "byr" => check_year(value, 1920, 2002) && value.len() == 4, "iyr" => check_year(value, 2010, 2020) && value.len() == 4, "eyr" => check_year(value, 2020, 2030) && value.len() == 4, "hgt" => check_height(value), "hcl" => check_haircolour(value), "ecl" => eycs.contains(value), "pid" => value.len() == 9 && value.parse::<u32>().is_ok(), "cid" => { cid_found = true; true } _ => unreachable!(key), } { current += 1; } } } } if current == 8 || (current == 7 && !cid_found) { valid += 1; } valid } fn check_year(d: &str, low: u16, up: u16) -> bool { d.parse::<u16>().map(|x| (low..=up).contains(&x)).unwrap_or(false) } fn check_height(d: &str) -> bool { if d.ends_with("cm") { check_year(&d.replace("cm", ""), 150, 193) } else if d.ends_with("in") { check_year(&d.replace("in", ""), 59, 76) } else { false } } fn check_haircolour(d: &str) -> bool { if d.starts_with('#') && d.len() == 7 { for c in d.replace("#", "").chars() { if !('0'..='9').contains(&c) && !('a'..='f').contains(&c) { return false; } } true } else { false } } #[cfg(test)] mod tests { use super::{exercise_1, exercise_2}; use crate::test::Bencher; #[test] fn d4t1() { let input = r"eyr:1972 cid:100 hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926 iyr:2019 hcl:#602927 eyr:1967 hgt:170cm ecl:grn pid:012533040 byr:1946 hcl:dab227 iyr:2012 ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277 hgt:59cm ecl:zzz eyr:2038 hcl:74454a iyr:2023 pid:3556412378 byr:2007"; assert_eq!(0, exercise_2(&input)); } #[test] fn d4t12() { let input = r"pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 hcl:#623a2f eyr:2029 ecl:blu cid:129 byr:1989 iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm hcl:#888785 hgt:164cm byr:2001 iyr:2015 cid:88 pid:545766238 ecl:hzl eyr:2022 iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719"; assert_eq!(4, exercise_2(&input)); } #[test] fn d4p1_test() { let input = include_str!("input/day4.txt"); assert_eq!(254, exercise_1(&input)); } #[test] fn d4p2_test() { let input = include_str!("input/day4.txt"); assert_eq!(184, exercise_2(&input)); } #[bench] fn d4_bench_ex1(b: &mut Bencher) { let input = include_str!("input/day4.txt"); b.iter(|| exercise_1(&input)); } #[bench] fn d4_bench_ex2(b: &mut Bencher) { let input = include_str!("input/day4.txt"); b.iter(|| exercise_2(&input)); } #[bench] fn d4_bench_ex1bigboi(b: &mut Bencher) { let input = include_str!("input/day4bigboi.txt"); b.iter(|| exercise_1(&input)); } #[bench] fn d4_bench_ex2bigboi(b: &mut Bencher) { let input = include_str!("input/day4bigboi.txt"); b.iter(|| exercise_2(&input)); } }
//#![deny(warnings)] extern crate futures; extern crate hyper; extern crate hyper_tls; extern crate tokio_core; extern crate url; //use std::env; use std::io::{self, Write}; use url::form_urlencoded; use url::Url; use futures::Future; use futures::stream::Stream; use hyper::{Method, Body, Client, Request}; use hyper_tls::HttpsConnector; use tokio_core::reactor::Core; fn main() { let url = "https://sso.garmin.com/sso/login"; let query = vec![ ("service", "https://connect.garmin.com/post-auth/login"), ("clientId", "GarminConnect"), ("gauthHost", "https://sso.garmin.com/sso"), ("consumeServiceTicket", "false"), ]; let url = Url::parse_with_params(url, query).unwrap(); // let url = Url::parse_with_params(url, query.into_iter()); // let url = url.as_str().parse::<hyper::Uri>().unwrap(); // if url.scheme() != Some("http") { // println!("This example only works with 'http' URLs."); // return; // } let mut core = Core::new().unwrap(); let handle = core.handle(); // https://hyper.rs/guides/client/configuration/ let client = Client::configure() .connector(HttpsConnector::new(4, &handle).unwrap()) .build(&handle); println!("url: {}", url); let req = Request::<Body>::new(Method::Get, url); // http://siciarz.net/24-days-of-rust-hyper/ let query = vec![ ("service", "https://connect.garmin.com/post-auth/login"), ("clientId", "GarminConnect"), ("gauthHost", "https://sso.garmin.com/sso"), ("consumeServiceTicket", "false"), ]; // let param = form_urlencoded::Serializer::new(String::new()) // .extend_pairs(query.into_iter()) // .finish(); // // url. // println!("param: {}", param); // let work = client .request(req) .and_then(|res| { println!("Response: {}", res.status()); println!("Headers: \n{}", res.headers()); res.body().for_each(|chunk| { io::stdout().write_all(&chunk).map_err(From::from) }) }) .map(|_| { println!("\n\nDone."); }); core.run(work).unwrap(); }
//! Rusty Engine's custom collision detection implementation. use crate::sprite::Sprite; use bevy::prelude::*; use serde::{Deserialize, Serialize}; use std::{ collections::HashSet, f32::consts::{PI, TAU}, hash::Hash, }; pub(crate) struct PhysicsPlugin; impl Plugin for PhysicsPlugin { fn build(&self, app: &mut App) { app.add_event::<CollisionEvent>() .add_system(collision_detection); } } // TODO: Replace the handmade 2D overlap detection with real rapier2d physics // can now be multiline. /// This is the struct that is generated when a collision occurs. Collisions only occur between two /// [Sprite]s which: /// - have colliders (you can use the `collider` example to create your own colliders) /// - have their `collision` flags set to `true`. #[derive(Clone, Debug, PartialEq, Eq)] pub struct CollisionEvent { pub state: CollisionState, pub pair: CollisionPair, } /// Indicates whether a [`CollisionEvent`] is at the beginning or ending of a collision. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CollisionState { Begin, End, } impl CollisionState { /// Returns true if the value is [`CollisionState::Begin`] pub fn is_begin(&self) -> bool { match self { CollisionState::Begin => true, CollisionState::End => false, } } /// Returns true if the value is [`CollisionState::End`] pub fn is_end(&self) -> bool { match self { CollisionState::Begin => false, CollisionState::End => true, } } } /// Contains the labels of the two sprites involved in the collision. As the labels are unordered, /// several convenience methods are provided for searching the values. #[derive(Debug, Default, Eq, Clone)] pub struct CollisionPair(pub String, pub String); impl CollisionPair { /// Whether either of the labels contains the text. pub fn either_contains<T: Into<String>>(&self, text: T) -> bool { let text = text.into(); self.0.contains(&text) || self.1.contains(&text) } /// Whether either of the labels equals to the text. pub fn either_equals_to<T: Into<String>>(&self, text: T) -> bool { let text = text.into(); (self.0 == text) || (self.1 == text) } /// Whether either of the labels starts with the text. pub fn either_starts_with<T: Into<String>>(&self, text: T) -> bool { let text = text.into(); self.0.starts_with(&text) || self.1.starts_with(&text) } /// Whether exactly one of the labels starts with the text. pub fn one_starts_with<T: Into<String>>(&self, text: T) -> bool { let text = text.into(); let a_matches = self.0.starts_with(&text); let b_matches = self.1.starts_with(&text); (a_matches && !b_matches) || (!a_matches && b_matches) } pub fn array(&self) -> [&str; 2] { [self.0.as_str(), self.1.as_str()] } pub fn array_mut(&mut self) -> [&mut String; 2] { [&mut self.0, &mut self.1] } } impl IntoIterator for CollisionPair { type Item = String; type IntoIter = std::array::IntoIter<Self::Item, 2>; fn into_iter(self) -> Self::IntoIter { [self.0, self.1].into_iter() } } impl PartialEq for CollisionPair { fn eq(&self, other: &Self) -> bool { ((self.0 == other.0) && (self.1 == other.1)) || ((self.0 == other.1) && (self.1 == other.0)) } } impl Hash for CollisionPair { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { // Make sure we return the same hash no matter which position the same two strings might be // in (so we match our PartialEq implementation) if self.0 < self.1 { self.0.hash(state); self.1.hash(state); } else { self.1.hash(state); self.0.hash(state); } } } /// system - detect collisions and generate the collision events fn collision_detection( mut existing_collisions: Local<HashSet<CollisionPair>>, mut collision_events: EventWriter<CollisionEvent>, query: Query<&Sprite>, ) { let mut current_collisions = HashSet::<CollisionPair>::new(); 'outer: for sprite1 in query.iter().filter(|a| a.collision) { for sprite2 in query.iter().filter(|a| a.collision) { if sprite1.label == sprite2.label { // We only need to compare one half of the matrix triangle continue 'outer; } if Collider::colliding(sprite1, sprite2) { current_collisions .insert(CollisionPair(sprite1.label.clone(), sprite2.label.clone())); } } } let beginning_collisions: Vec<_> = current_collisions .difference(&existing_collisions) .cloned() .collect(); collision_events.send_batch(beginning_collisions.iter().map(|p| CollisionEvent { state: CollisionState::Begin, pair: p.clone(), })); for beginning_collision in beginning_collisions { existing_collisions.insert(beginning_collision); } let ending_collisions: Vec<_> = existing_collisions .difference(&current_collisions) .cloned() .collect(); collision_events.send_batch(ending_collisions.iter().map(|p| CollisionEvent { state: CollisionState::End, pair: p.clone(), })); for ending_collision in ending_collisions { let _ = existing_collisions.remove(&ending_collision); } } /// Represents the collider (or lack thereof) of a sprite. Two sprites need to have colliders AND /// have their `Sprite.collision` fields set to `true` to generate collision events. See the /// `collider` example to create your own colliders #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] pub enum Collider { NoCollider, Poly(Vec<Vec2>), } impl Default for Collider { fn default() -> Self { Collider::NoCollider } } impl Collider { /// Generate a rectangular collider based on top-left and bottom-right points pub fn rect<T: Into<Vec2>>(topleft: T, bottomright: T) -> Self { let topleft = topleft.into(); let bottomright = bottomright.into(); Self::Poly(vec![ topleft, Vec2::new(bottomright.x, topleft.y), bottomright, Vec2::new(topleft.x, bottomright.y), ]) } /// Convert a slice of Vec2's into a polygon collider. This is helpful if you want to hard-code /// colliders in your code as arrays or vectors of Vec2. pub fn poly<T: Into<Vec2> + Copy>(points: &[T]) -> Self { Self::Poly(points.iter().map(|&x| x.into()).collect()) } /// Generate a polygon circle approximation with the specified radius and amount of vertices pub fn circle_custom(radius: f32, vertices: usize) -> Self { let mut points = vec![]; for x in 0..vertices { let inner = std::f64::consts::TAU / vertices as f64 * x as f64; let mut inner_x = inner.cos() as f32 * radius; let mut inner_y = inner.sin() as f32 * radius; // Clamp near-zero values to zero when producing RON files: (-0.0000000000000044087286) if (inner_x > -0.000001) && (inner_x < 0.000001) { inner_x = 0.0; } if (inner_y > -0.000001) && (inner_y < 0.000001) { inner_y = 0.0; } points.push(Vec2::new(inner_x, inner_y)); } Self::Poly(points) } /// Generate a 16-vertex polygon circle approximation. 16 was chosen as the default as it works /// quite well with the circular sprites in the asset pack. pub fn circle(radius: f32) -> Self { Self::circle_custom(radius, 16) } /// Whether or not the collider is a `Collider::Poly`. pub fn is_poly(&self) -> bool { matches!(self, Self::Poly(_)) } /// Whether the points in the collider represent a convex polygon (not concave or complex). /// This is important, because Rusty Engine's collision detection doesn't work correctly unless /// colliders are convex polygons. /// /// This implementation is based on Rory Daulton's answer on https://stackoverflow.com/questions/471962/how-do-i-efficiently-determine-if-a-polygon-is-convex-non-convex-or-complex?answertab=votes#tab-top pub fn is_convex(&self) -> bool { if let Collider::Poly(points) = self { let length = points.len(); if length < 3 { return false; // empty sets, points and lines are not convex polygons } // the source algorithm deals with individual x's and y's and the combined points in // disjoint ways, so we need to follow the pattern unless we want to modify the // algorithm itself. let mut old_x = points[length - 2].x; let mut old_y = points[length - 2].y; let mut new_x = points[length - 1].x; let mut new_y = points[length - 1].y; let mut new_direction = (new_y - old_y).atan2(new_x - old_x); let mut angle_sum = 0.0; let mut old_direction; let mut orientation = 0.0; for (idx, newpoint) in points.iter().enumerate() { // The fact that new_x and new_y are re-used at the top of the loop with the // expectation that they have the last loop's values is why we can't use the // newpoint loop variable directly. Messy. :-/ old_x = new_x; old_y = new_y; old_direction = new_direction; new_x = newpoint.x; new_y = newpoint.y; new_direction = (new_y - old_y).atan2(new_x - old_x); if (old_x == new_x) && (old_y == new_y) { return false; // repeated consecutive points } // Calculate & check the normalized deriction-change angle let mut angle = new_direction - old_direction; if angle <= -PI { angle += TAU; // make it in half-open interval (-Pi, Pi] } else if angle > PI { angle -= TAU; } if idx == 0 { // if first time through loop, initialize orientation if angle == 0.0 { return false; // the source algorithm doesn't explain this one } if angle > 0.0 { orientation = 1.0; } else { orientation = -1.0; } } else if orientation * angle <= 0.0 { // not both positive or both negative return false; } // Accumulate the direction-change angle angle_sum += angle; } // Check that the total number of full turns is plus-or-minus 1 let full_turns = (angle_sum / TAU).abs(); return (full_turns > 0.9999) && (full_turns < 1.0001); } false } /// Return the points rotated by a number of radians fn rotated(&self, rotation: f32) -> Vec<Vec2> { let mut rotated_points = Vec::new(); if let Self::Poly(points) = self { let sin = rotation.sin(); let cos = rotation.cos(); for point in points.iter() { rotated_points.push(Vec2::new( point.x * cos - point.y * sin, point.x * sin + point.y * cos, )); } } rotated_points } #[doc(hidden)] /// Used internally to scale colliders to match a sprite's current translation, rotation, and scale pub fn relative_to(&self, sprite: &Sprite) -> Vec<Vec2> { self.rotated(sprite.rotation) .iter() .map(|&v| v * sprite.scale + sprite.translation) // scale & translation .collect() } /// Returns a `Vec<Vec2>` containing the points of the collider, or an empty `Vec` if there is /// no collider. pub fn points(&self) -> Vec<Vec2> { if let Self::Poly(points) = self { points.clone() } else { Vec::with_capacity(0) } } /// Whether or not two sprites are currently colliding. This method ignores the `collision` /// field of the sprites. pub fn colliding(sprite1: &Sprite, sprite2: &Sprite) -> bool { use Collider::*; if let NoCollider = sprite1.collider { return false; } if let NoCollider = sprite2.collider { return false; } if sprite1.collider.is_poly() && sprite2.collider.is_poly() { let poly1 = sprite1.collider.relative_to(sprite1); let poly2 = sprite2.collider.relative_to(sprite2); // Polygon intersection algorithm adapted from // https://stackoverflow.com/questions/10962379/how-to-check-intersection-between-2-rotated-rectangles for poly in vec![poly1.clone(), poly2.clone()] { for (idx, &p1) in poly.iter().enumerate() { let p2 = poly[(idx + 1) % poly.len()]; let normal = Vec2::new(p2.y - p1.y, p1.x - p2.x); let mut min_a = None; let mut max_a = None; for &p in poly1.iter() { let projected = normal.x * p.x + normal.y * p.y; if min_a.is_none() || projected < min_a.unwrap() { min_a = Some(projected); } if max_a.is_none() || projected > max_a.unwrap() { max_a = Some(projected); } } let mut min_b = None; let mut max_b = None; for &p in poly2.iter() { let projected = normal.x * p.x + normal.y * p.y; if min_b.is_none() || projected < min_b.unwrap() { min_b = Some(projected); } if max_b.is_none() || projected > max_b.unwrap() { max_b = Some(projected); } } if max_a < min_b || max_b < min_a { return false; } } } return true; } false } }
use core::alloc::Layout; use core::cmp; use core::convert::{TryFrom, TryInto}; use core::fmt::{self, Debug, Display, Write}; use core::iter::FusedIterator; use core::marker::PhantomData; use core::mem; use core::ptr; use anyhow::*; use heapless::Vec; use thiserror::Error; use crate::borrow::CloneToProcess; use crate::erts::exception::AllocResult; use crate::erts::process::alloc::{StackAlloc, TermAlloc}; use crate::erts::term::prelude::*; use crate::erts::to_word_size; pub fn optional_cons_to_term(cons: Option<Boxed<Cons>>) -> Term { match cons { None => Term::NIL, Some(boxed) => boxed.into(), } } pub enum List { Empty, NonEmpty(Boxed<Cons>), } impl TryFrom<Term> for List { type Error = TypeError; fn try_from(term: Term) -> Result<List, TypeError> { term.decode().unwrap().try_into() } } impl TryFrom<TypedTerm> for List { type Error = TypeError; fn try_from(typed_term: TypedTerm) -> Result<List, TypeError> { match typed_term { TypedTerm::Nil => Ok(List::Empty), TypedTerm::List(cons) => Ok(List::NonEmpty(cons)), _ => Err(TypeError), } } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum MaybeImproper<P, I> { Proper(P), Improper(I), } impl<P, I> MaybeImproper<P, I> { #[inline] pub fn is_proper(&self) -> bool { match self { &Self::Proper(_) => true, _ => false, } } #[inline] pub fn is_improper(&self) -> bool { !self.is_proper() } } #[derive(Clone, Copy, Hash)] #[repr(C)] pub struct Cons { pub head: Term, pub tail: Term, } impl Cons { pub fn iter(&self) -> self::Iter<'_> { Iter { head: Some(Ok(self.head)), tail: Some(self.tail), _marker: PhantomData, } } /// The number of bytes for the header and immediate terms or box term pointer to elements /// allocated elsewhere. pub fn need_in_bytes_from_len(len: usize) -> usize { mem::size_of::<Cons>() * len } /// The number of words for the header and immediate terms or box term pointer to elements /// allocated elsewhere. pub fn need_in_words_from_len(len: usize) -> usize { to_word_size(Self::need_in_bytes_from_len(len)) } /// Create a new cons cell from a head and tail pointer pair #[inline] pub fn new(head: Term, tail: Term) -> Self { Self { head, tail } } pub fn contains(&self, term: Term) -> bool { self.iter().any(|result| match result { Ok(ref element) => element == &term, _ => false, }) } /// Returns the count only if the list is proper. pub fn count(&self) -> Option<usize> { let mut count = 0; for result in self { match result { Ok(_) => count += 1, Err(_) => return None, } } Some(count) } /// Returns true if this cons cell is actually a move marker #[inline] pub fn is_move_marker(&self) -> bool { self.head.is_none() } /// Returns true if this cons is the head of ///a proper list. pub fn is_proper(&self) -> bool { self.iter().all(|result| result.is_ok()) } /// Reify a cons cell from a pointer to the head of a cons cell /// /// # Safety /// /// It is expected that `cons` is a pointer to the `head` of a /// previously allocated `Cons`, any other usage may result in /// undefined behavior or a segmentation fault #[inline] pub unsafe fn from_raw(cons: *mut Cons) -> Self { *cons } /// Get the `TypedTerm` pointed to by the head of this cons cell #[inline] pub fn head(&self) -> Term { self.head } /// Get the tail of this cons cell, which depending on the type of /// list it represents, may either be another `Cons`, a `TypedTerm` /// value, or no value at all (when the tail is nil). /// /// If the list is improper, then `Some(TypedTerm)` will be returned. /// If the list is proper, then either `Some(TypedTerm)` or `Nil` will /// be returned, depending on whether this cell is the last in the list. #[inline] pub fn tail(&self) -> Option<MaybeImproper<Cons, Term>> { if self.tail.is_nil() { return None; } if self.tail.is_non_empty_list() { let tail: *mut Cons = self.tail.dyn_cast(); return Some(MaybeImproper::Proper(unsafe { *tail })); } Some(MaybeImproper::Improper(self.tail)) } /// Searches this keyword list for the first element which has a matching key /// at the given index. /// /// If no key is found, returns 'badarg' pub fn keyfind<I>(&self, index: I, key: Term) -> anyhow::Result<Option<Term>> where I: TupleIndex + Copy, { for result in self.iter() { if let Ok(item) = result { let tuple_item: Result<Boxed<Tuple>, _> = item.try_into(); if let Ok(tuple) = tuple_item { if let Ok(candidate) = tuple.get_element(index) { if candidate == key { return Ok(Some(item)); } } } } else { return Err(ImproperListError.into()); } } Ok(None) } // See https://github.com/erlang/otp/blob/b8e11b6abe73b5f6306e8833511fcffdb9d252b5/erts/emulator/beam/erl_printf_term.c#L117-L140 fn is_printable_string(&self) -> bool { self.iter().all(|result| match result { Ok(ref element) => { // See https://github.com/erlang/otp/blob/b8e11b6abe73b5f6306e8833511fcffdb9d252b5/erts/emulator/beam/erl_printf_term.c#L128-L129 let result_char: Result<char, _> = (*element).try_into(); match result_char { Ok(c) => { // https://github.com/erlang/otp/blob/b8e11b6abe73b5f6306e8833511fcffdb9d252b5/erts/emulator/beam/erl_printf_term.c#L132 c.is_ascii_graphic() || c.is_ascii_whitespace() } _ => false, } } _ => false, }) } } impl Debug for Cons { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char('[')?; let mut iter = self.iter(); if let Some(first_result) = iter.next() { write!(f, "{:?}", first_result.unwrap())?; for result in iter { match result { Ok(element) => write!(f, ", {:?}", element)?, Err(ImproperList { tail }) => write!(f, " | {:?}", tail)?, } } } f.write_char(']') } } impl Display for Cons { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // See https://github.com/erlang/otp/blob/b8e11b6abe73b5f6306e8833511fcffdb9d252b5/erts/emulator/beam/erl_printf_term.c#L423-443 if self.is_printable_string() { f.write_char('\"')?; for result in self.iter() { // `is_printable_string` guarantees all Ok let element = result.unwrap(); let c: char = element.try_into().unwrap(); match c { '\n' => f.write_str("\\\n")?, '\"' => f.write_str("\\\"")?, _ => f.write_char(c)?, } } f.write_char('\"') } else { f.write_char('[')?; let mut iter = self.iter(); if let Some(first_result) = iter.next() { write!(f, "{}", first_result.unwrap())?; for result in iter { match result { Ok(element) => write!(f, ", {}", element)?, Err(ImproperList { tail }) => write!(f, " | {}", tail)?, } } } f.write_char(']') } } } impl Eq for Cons {} impl Ord for Cons { fn cmp(&self, other: &Cons) -> cmp::Ordering { self.iter().cmp(other.iter()) } } impl PartialEq for Cons { fn eq(&self, other: &Cons) -> bool { self.head.eq(&other.head) && self.tail.eq(&other.tail) } } impl<T> PartialEq<Boxed<T>> for Cons where T: PartialEq<Cons>, { #[inline] fn eq(&self, other: &Boxed<T>) -> bool { other.as_ref().eq(self) } } impl PartialOrd for Cons { fn partial_cmp(&self, other: &Cons) -> Option<cmp::Ordering> { Some(self.cmp(other)) } } impl<T> PartialOrd<Boxed<T>> for Cons where T: PartialOrd<Cons>, { #[inline] fn partial_cmp(&self, other: &Boxed<T>) -> Option<cmp::Ordering> { other.as_ref().partial_cmp(self).map(|o| o.reverse()) } } impl CloneToProcess for Cons { fn clone_to_heap<A>(&self, heap: &mut A) -> AllocResult<Term> where A: ?Sized + TermAlloc, { let mut vec: std::vec::Vec<Term> = Default::default(); let mut tail = Term::NIL; for result in self.iter() { match result { Ok(element) => vec.push(element.clone_to_heap(heap)?), Err(ImproperList { tail: improper_tail, }) => tail = improper_tail, } } heap.improper_list_from_slice(&vec, tail) .map_err(From::from) .map(From::from) } fn size_in_words(&self) -> usize { let mut elements = 0; let mut words = 0; for result in self.iter() { let element = match result { Ok(element) => element, Err(ImproperList { tail }) => tail, }; elements += 1; words += element.size_in_words(); } words += Self::need_in_words_from_len(elements); words } } impl<'a> IntoIterator for &'a Cons { type Item = Result<Term, ImproperList>; type IntoIter = Iter<'a>; #[inline(always)] fn into_iter(self) -> Self::IntoIter { self.iter() } } #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct ImproperList { pub tail: Term, } pub struct Iter<'a> { head: Option<Result<Term, ImproperList>>, tail: Option<Term>, _marker: PhantomData<&'a Term>, } impl FusedIterator for Iter<'_> {} impl Iterator for Iter<'_> { type Item = Result<Term, ImproperList>; fn next(&mut self) -> Option<Self::Item> { let next = self.head.clone(); match next { None => (), Some(Err(_)) => { self.head = None; self.tail = None; } _ => { let tail = self.tail.unwrap(); match tail.decode().unwrap() { TypedTerm::Nil => { self.head = None; self.tail = None; } TypedTerm::List(cons_ptr) => { let cons = cons_ptr.as_ref(); self.head = Some(Ok(cons.head)); self.tail = Some(cons.tail); } _ => { self.head = Some(Err(ImproperList { tail })); self.tail = None; } } } } next } } #[derive(Debug, Error)] #[error("improper list")] pub struct ImproperListError; impl TryFrom<TypedTerm> for Boxed<Cons> { type Error = TypeError; fn try_from(typed_term: TypedTerm) -> Result<Self, Self::Error> { match typed_term { TypedTerm::List(cons) => Ok(cons), _ => Err(TypeError), } } } impl TryInto<String> for Boxed<Cons> { type Error = anyhow::Error; fn try_into(self) -> Result<String, Self::Error> { self.iter() .map(|result| match result { Ok(element) => { let result_char: Result<char, _> = element .try_into() .context("string (Erlang) or charlist (elixir) element not a char"); result_char } Err(_) => Err(ImproperListError.into()), }) .collect() } } pub struct ListBuilder<'a, A: TermAlloc> { heap: &'a mut A, element: Option<Term>, first: *mut Cons, current: *mut Cons, size: usize, failed: bool, } impl<'a, A: TermAlloc> ListBuilder<'a, A> { /// Creates a new list builder that allocates on the given processes' heap #[inline] pub fn new(heap: &'a mut A) -> Self { Self { heap, element: None, first: ptr::null_mut(), current: ptr::null_mut(), size: 0, failed: false, } } /// Pushes the given `Term` on to the end of the list being built. /// /// NOTE: When using `on_heap` mode, the builder will also clone terms if they are /// not already on the process heap #[inline] pub fn push(mut self, term: Term) -> Self { if self.failed { self } else { match self.push_internal(term) { Err(_) => { self.failed = true; self } Ok(_) => self, } } } #[inline] fn push_internal(&mut self, term: Term) -> AllocResult<()> { if self.element.is_none() { // This is the very first push assert!(self.first.is_null()); // We need to allocate a cell self.first = self.alloc_cell(Term::NIL, Term::NIL)?; self.element = Some(self.clone_term_to_heap(term)?); self.current = self.first; self.size += 1; } else { let new_element = self.clone_term_to_heap(term)?; // Swap the current element with the new element let head = self.element.replace(new_element).unwrap(); // Set the head of the current cell to the element we just took out let mut current = unsafe { &mut *self.current }; if current.head.is_nil() { // Fill the head of the cell, this only happens on the second push current.head = head; self.size += 1; } else if current.tail.is_nil() { // Fill the tail of the cell, this is the typical case current.tail = head; self.size += 1; } else { // This occurs when a cell has been filled and we're pushing a new element. // We need to allocate a new cell and move the previous tail to the head of that // cell let cadr = current.tail; let new_current = self.alloc_cell(cadr, Term::NIL)?; current.tail = new_current.into(); self.current = new_current; self.size += 1; } } Ok(()) } /// Consumes the builder and produces a `Term` which points to the allocated list #[inline] pub fn finish(mut self) -> AllocResult<Boxed<Cons>> { if self.failed { // We can't clean up the heap until GC Err(alloc!()) } else { match self.element { // Empty list None => { assert!(self.first.is_null()); // Allocate an empty cell for the list // Technically this is a bit wasteful, since we could just use NIL // as an immediate, but to return a `Boxed<Cons>` we need a value to // point to let first_ptr = self.alloc_cell(Term::NIL, Term::NIL)?; Ok(unsafe { Boxed::new_unchecked(first_ptr) }) } // Non-empty list Some(last) => { let mut current = unsafe { &mut *self.current }; if current.head.is_nil() { // Occurs with one element lists, as tail cell allocation is deferred current.head = last; } else if current.tail.is_nil() { // Typical case, we need to allocate a new tail to wrap up this list let new_current = self.alloc_cell(last, Term::NIL)?; current.tail = new_current.into(); } else { // This occurs when we've filled a cell, so we need to allocate two cells, // one for the current tail and one for the last element let cadr_cell = self.alloc_cell(last, Term::NIL)?; let cadr = cadr_cell.into(); let cdr = self.alloc_cell(current.tail, cadr)?; current.tail = cdr.into(); } // Return a reference to the first cell of the list Ok(unsafe { Boxed::new_unchecked(self.first) }) } } } } /// Like `finish`, but produces an improper list if there is already at least one element #[inline] pub fn finish_with(mut self, term: Term) -> AllocResult<Boxed<Cons>> { if self.failed { // We can't clean up the heap until GC Err(alloc!()) } else { match self.element { // Empty list None => { // We need to allocate a cell, this will end up a proper list self.push_internal(term)?; self.finish() } // Non-empty list, this will always produce an improper list Some(next) => { let mut current = unsafe { &mut *self.current }; if current.head.is_nil() { current.head = next; current.tail = self.clone_term_to_heap(term)?; } else if current.tail.is_nil() { let tail = self.clone_term_to_heap(term)?; let cdr = self.alloc_cell(next, tail)?; current.tail = cdr.into(); } else { let tail = self.clone_term_to_heap(term)?; let cadr_cell = self.alloc_cell(next, tail)?; let cadr = cadr_cell.into(); let cdr = self.alloc_cell(current.tail, cadr)?; current.tail = cdr.into(); } Ok(unsafe { Boxed::new_unchecked(self.first) }) } } } } #[inline] fn clone_term_to_heap(&mut self, term: Term) -> AllocResult<Term> { if term.is_immediate() { Ok(term) } else if term.is_boxed() { let ptr: *mut Term = term.dyn_cast(); if !term.is_literal() && self.heap.is_owner(ptr) { // No need to clone Ok(term) } else { term.clone_to_heap(self.heap) } } else if term.is_non_empty_list() { let ptr: *mut Cons = term.dyn_cast(); if !term.is_literal() && self.heap.is_owner(ptr) { // No need to clone Ok(term) } else { term.clone_to_heap(self.heap) } } else { unreachable!() } } #[inline] fn alloc_cell(&mut self, head: Term, tail: Term) -> AllocResult<*mut Cons> { let layout = Layout::new::<Cons>(); let ptr = unsafe { self.heap.alloc_layout(layout)?.as_ptr() as *mut Cons }; let mut cell = unsafe { &mut *ptr }; cell.head = head; cell.tail = tail; Ok(ptr) } } #[allow(non_camel_case_types)] #[cfg(target_pointer_width = "32")] const MAX_ELEMENTS: usize = 16; #[allow(non_camel_case_types)] #[cfg(target_pointer_width = "64")] const MAX_ELEMENTS: usize = 8; pub struct HeaplessListBuilder<'a, A: StackAlloc> { stack: &'a mut A, elements: Vec<Term, MAX_ELEMENTS>, failed: bool, } impl<'a, A: StackAlloc> HeaplessListBuilder<'a, A> { /// Creates a new list builder that allocates on the given processes' heap #[inline] pub fn new(stack: &'a mut A) -> Self { Self { stack, elements: Vec::new(), failed: false, } } /// Pushes the given `Term` on to the end of the list being built. /// /// NOTE: It is not permitted to allocate on the stack while constructing /// a stack-allocated list, furthermore, stack-allocated lists may only consist /// of immediates or boxes. If these invariants are violated, this function will panic. #[inline] pub fn push(mut self, term: Term) -> Self { assert!( term.is_valid(), "invalid list element for stack-allocated list" ); if self.failed { self } else { match self.elements.push(term) { Err(_) => { self.failed = true; self } Ok(_) => self, } } } /// Consumes the builder and produces a `Term` which points to the allocated list #[inline] pub fn finish(self) -> AllocResult<Boxed<Cons>> { if self.failed { Err(alloc!()) } else { let size = self.elements.len(); if size == 0 { unsafe { let ptr = self.stack.alloca(1)?.as_ptr(); ptr::write(ptr, Term::NIL); Ok(Boxed::new_unchecked(ptr as *mut Cons)) } } else { // Construct allocation layout for list let (elements_layout, _) = Layout::new::<Cons>().repeat(size).unwrap(); let (layout, _) = Layout::new::<Term>().extend(elements_layout).unwrap(); // Allocate on stack let ptr = unsafe { self.stack.alloca_layout(layout)?.as_ptr() }; // Get pointer to first cell let first_ptr = unsafe { ptr.add(1) as *mut Cons }; // Write header with pointer to first cell unsafe { ptr::write(ptr, first_ptr.into()) }; // For each element in the list, write a cell with a pointer to the next one for (i, element) in self.elements.iter().copied().enumerate() { // Offsets are relative to the first cell, first element has `i` of 0 let cell_ptr = unsafe { first_ptr.add(i) }; // Get mutable reference to cell memory let mut cell = unsafe { &mut *cell_ptr }; if i < size - 1 { // If we have future cells to write, generate a valid tail let tail_ptr = unsafe { cell_ptr.add(1) }; cell.head = element; cell.tail = tail_ptr.into(); } else { // This is the last element cell.head = element; cell.tail = Term::NIL; } } Ok(unsafe { Boxed::new_unchecked(first_ptr) }) } } } /// Like `finish`, but produces an improper list if there is already at least one element #[inline] pub fn finish_with(mut self, term: Term) -> AllocResult<Boxed<Cons>> { if self.failed { Err(alloc!()) } else { let size = self.elements.len() + 1; if size == 1 { // Proper list self.elements.push(term).unwrap(); self.finish() } else { // Construct allocation layout for list let (elements_layout, _) = Layout::new::<Cons>().repeat(size).unwrap(); let (layout, _) = Layout::new::<Term>().extend(elements_layout).unwrap(); // Allocate on stack let ptr = unsafe { self.stack.alloca_layout(layout)?.as_ptr() }; // Get pointer to first cell let first_ptr = unsafe { ptr.add(1) as *mut Cons }; // Write header with pointer to first cell unsafe { ptr::write(ptr, first_ptr.into()) }; // For each element in the list, write a cell with a pointer to the next one for (i, element) in self.elements.iter().copied().enumerate() { // Offsets are relative to the first cell, first element has `i` of 0 let cell_ptr = unsafe { first_ptr.add(i) }; // Get mutable reference to cell memory let mut cell = unsafe { &mut *cell_ptr }; if i < size - 2 { // If we have future cells to write, generate a valid tail let tail_ptr = unsafe { cell_ptr.add(1) }; cell.head = element; cell.tail = tail_ptr.into(); } else { // This is the last cell cell.head = element; cell.tail = term; } } Ok(unsafe { Boxed::new_unchecked(first_ptr) }) } } } } #[cfg(test)] mod tests { use super::*; use crate::erts::testing::RegionHeap; mod clone_to_heap { use super::*; #[test] fn list_single_element() { let mut heap = RegionHeap::default(); let cons = cons!(heap, atom!("head")); let cloned_term = cons.clone_to_heap(&mut heap).unwrap(); let cloned: Boxed<Cons> = cloned_term.try_into().unwrap(); assert_eq!(cons, cloned); } #[test] fn list_two_element_proper() { let mut heap = RegionHeap::default(); let element0 = fixnum!(0); let element1 = fixnum!(1); let cons = cons!(heap, element0, element1); let cloned_term = cons.clone_to_heap(&mut heap).unwrap(); let cloned: Boxed<Cons> = cloned_term.try_into().unwrap(); assert_eq!(cons, cloned); } #[test] fn list_three_element_proper() { let mut heap = RegionHeap::default(); let element0 = fixnum!(0); let element1 = fixnum!(1); let element2 = heap.binary_from_str("hello world!").unwrap(); let cons = cons!(heap, element0, element1, element2); let cloned_term = cons.clone_to_heap(&mut heap).unwrap(); let cloned: Boxed<Cons> = cloned_term.try_into().unwrap(); assert_eq!(cons, cloned); } #[test] fn list_three_element_proper_with_nil_element() { let mut heap = RegionHeap::default(); let element0 = fixnum!(0); let element1 = Term::NIL; let element2 = fixnum!(2); let cons = cons!(heap, element0, element1, element2); let cloned_term = cons.clone_to_heap(&mut heap).unwrap(); let cloned: Boxed<Cons> = cloned_term.try_into().unwrap(); assert_eq!(cons, cloned); } #[test] fn list_two_element_improper() { let mut heap = RegionHeap::default(); let head = atom!("head"); let tail = atom!("tail"); let cons = improper_cons!(heap, head, tail); let cloned_term = cons.clone_to_heap(&mut heap).unwrap(); let cloned: Boxed<Cons> = cloned_term.try_into().unwrap(); assert_eq!(cons, cloned); } } mod into_iter { use super::*; #[test] fn list_proper_list_iter() { let mut heap = RegionHeap::default(); let a = fixnum!(42); let b = fixnum!(24); let c = fixnum!(11); let cons = cons!(heap, a, b, c); let mut list_iter = cons.into_iter(); let l0 = list_iter.next().unwrap(); assert_eq!(l0, Ok(a)); let l1 = list_iter.next().unwrap(); assert_eq!(l1, Ok(b)); let l2 = list_iter.next().unwrap(); assert_eq!(l2, Ok(c)); assert_eq!(list_iter.next(), None); assert_eq!(list_iter.next(), None); } #[test] fn list_improper_list_iter() { let mut heap = RegionHeap::default(); let a = fixnum!(42); let b = fixnum!(24); let c = fixnum!(11); let d = fixnum!(99); let cons = improper_cons!(heap, a, b, c, d); let mut list_iter = cons.into_iter(); let l0 = list_iter.next().unwrap(); assert_eq!(l0, Ok(a)); let l1 = list_iter.next().unwrap(); assert_eq!(l1, Ok(b)); let l2 = list_iter.next().unwrap(); assert_eq!(l2, Ok(c)); let l3 = list_iter.next().unwrap(); assert_eq!(l3, Err(ImproperList { tail: d })); assert_eq!(list_iter.next(), None); assert_eq!(list_iter.next(), None); } } mod builder { use super::*; #[test] fn list_builder_proper_list_iter() { let mut heap = RegionHeap::default(); let a = fixnum!(42); let b = fixnum!(24); let c = fixnum!(11); let cons = ListBuilder::new(&mut heap) .push(a) .push(b) .push(c) .finish() .unwrap(); let mut list_iter = cons.into_iter(); let l0 = list_iter.next().unwrap(); assert_eq!(l0, Ok(a)); let l1 = list_iter.next().unwrap(); assert_eq!(l1, Ok(b)); let l2 = list_iter.next().unwrap(); assert_eq!(l2, Ok(c)); assert_eq!(list_iter.next(), None); assert_eq!(list_iter.next(), None); } #[test] fn list_builder_improper_list_iter() { let mut heap = RegionHeap::default(); let a = fixnum!(42); let b = fixnum!(24); let c = fixnum!(11); let d = fixnum!(99); let cons = ListBuilder::new(&mut heap) .push(a) .push(b) .push(c) .finish_with(d) .unwrap(); let mut list_iter = cons.into_iter(); let l0 = list_iter.next().unwrap(); assert_eq!(l0, Ok(a)); let l1 = list_iter.next().unwrap(); assert_eq!(l1, Ok(b)); let l2 = list_iter.next().unwrap(); assert_eq!(l2, Ok(c)); let l3 = list_iter.next().unwrap(); assert_eq!(l3, Err(ImproperList { tail: d })); assert_eq!(list_iter.next(), None); assert_eq!(list_iter.next(), None); } } }
//! Timer-based management of operator activators. use std::cmp::Ordering; use std::collections::BinaryHeap; use std::rc::Weak; use std::time::{Duration, Instant}; use timely::scheduling::Activator; use crate::scheduling::AsScheduler; /// A scheduler allows polling sources to defer triggering their /// activators, in case they do not have work available. This reduces /// time spent polling infrequently updated sources and allows us to /// (optionally) block for input from within the event loop without /// unnecessarily delaying sources that have run out of fuel during /// the current step. #[derive(Default)] pub struct RealtimeScheduler { activator_queue: BinaryHeap<TimedActivator>, } impl AsScheduler for RealtimeScheduler { fn has_pending(&self) -> bool { if let Some(ref timed_activator) = self.activator_queue.peek() { timed_activator.is_ready() } else { false } } } impl RealtimeScheduler { /// Creates a new, empty scheduler. pub fn new() -> Self { RealtimeScheduler { activator_queue: BinaryHeap::new(), } } /// Returns the duration until the next activation in /// `activator_queue` from `now()`. If no activations are present /// returns None. pub fn until_next(&self) -> Option<Duration> { if let Some(ref timed_activator) = self.activator_queue.peek() { Some(timed_activator.until_ready()) } else { None } } /// Schedule activation at the specified instant. No hard /// guarantees on when the activator will actually be triggered. pub fn schedule_at(&mut self, at: Instant, activator: Weak<Activator>) { self.activator_queue.push(TimedActivator { at, activator, event: None, }); } /// Schedule activation now. No hard guarantees on when the /// activator will actually be triggered. pub fn schedule_now(&mut self, activator: Weak<Activator>) { self.schedule_at(Instant::now(), activator); } /// Schedule activation after the specified duration. No hard /// guarantees on when the activator will actually be triggered. pub fn schedule_after(&mut self, after: Duration, activator: Weak<Activator>) { self.schedule_at(Instant::now() + after, activator); } /// Schedule an event at the specified instant. No hard guarantees /// on when the activator will actually be triggered. pub fn event_at(&mut self, at: Instant, event: Event) { self.activator_queue.push(TimedActivator { at, activator: Weak::new(), event: Some(event), }); } /// Schedule an event after the specified duration. No hard /// guarantees on when the activator will actually be triggered. pub fn event_after(&mut self, after: Duration, event: Event) { self.event_at(Instant::now() + after, event); } } impl Iterator for RealtimeScheduler { type Item = TimedActivator; fn next(&mut self) -> Option<TimedActivator> { if self.has_pending() { Some(self.activator_queue.pop().unwrap()) } else { None } } } /// A set of things that we might want to schedule. #[derive(PartialEq, Eq, Debug)] pub enum Event { /// A domain tick. Tick, } /// A thing that can be scheduled at an instant. Scheduling this /// activator might result in an `Event`. pub struct TimedActivator { at: Instant, activator: Weak<Activator>, event: Option<Event>, } impl TimedActivator { fn is_ready(&self) -> bool { Instant::now() >= self.at } fn until_ready(&self) -> Duration { let now = Instant::now(); if self.at > now { self.at.duration_since(now) } else { Duration::from_millis(0) } } /// Trigger the activation, potentially resulting in an event. pub fn schedule(self) -> Option<Event> { if let Some(activator) = self.activator.upgrade() { activator.activate(); } self.event } } // We want the activator_queue to act like a min-heap. impl Ord for TimedActivator { fn cmp(&self, other: &TimedActivator) -> Ordering { other.at.cmp(&self.at) } } impl PartialOrd for TimedActivator { fn partial_cmp(&self, other: &TimedActivator) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for TimedActivator { fn eq(&self, other: &TimedActivator) -> bool { self.at.eq(&other.at) } } impl Eq for TimedActivator {}
use std::fs::File; use std::io::{Read, Write}; use gtk::prelude::*; // Module for aggregating analysis information mod analysis; // Module for maintaining application state mod app; use crate::app::AppContext; // Module for coordinate systems mod coords; // Errors mod errors; use crate::errors::*; // GUI module mod gui; /// Unique Application identifier. const APP_ID: &str = "weather.profiles.sonde"; pub fn run() -> Result<(), Box<dyn Error>> { // Set up data context let app = AppContext::initialize(); // Load the data configuration from last time, if it exists. load_last_used_config(&app); // Create the GTKApplication let gtk_app = gtk::Application::builder().application_id(APP_ID).build(); { let app = app.clone(); gtk_app.connect_activate(move |gtk_app| { let gui = gtk::Builder::from_string(include_str!("./sonde.ui")); let window: gtk::Window = gui.object("main_window").unwrap(); window.set_application(Some(gtk_app)); app.set_gui(gui); gui::initialize(&app).unwrap(); window.show(); }); } gtk_app.run(); // Save the configuration on closing. save_config(&app)?; Ok(()) } const CONFIG_FILE_NAME: &str = "sonde_config.yml"; pub(crate) fn load_config_from_file( app: &AppContext, config_path: &std::path::Path, ) -> Result<(), Box<dyn Error + 'static>> { // Keep the current "last file opened" info let last_file = app.config.borrow().last_open_file.clone(); let config = File::open(config_path) .and_then(|mut f| { let mut serialized_config = String::new(); f.read_to_string(&mut serialized_config) .map(|_| serialized_config) }) .map_err(Box::new)?; let config = serde_yaml::from_str::<app::config::Config>(&config)?; *app.config.borrow_mut() = config; if last_file.is_some() { app.config.borrow_mut().last_open_file = last_file; } app.mark_background_dirty(); app.mark_data_dirty(); app.mark_data_dirty(); Ok(()) } fn load_last_used_config(app: &AppContext) { let path = match dirs::config_dir().map(|path| path.join(CONFIG_FILE_NAME)) { Some(p) => p, None => return, }; let _ = load_config_from_file(app, &path); } pub(crate) fn save_config(app: &AppContext) -> Result<(), Box<dyn Error>> { if let Some(ref config_path) = dirs::config_dir().map(|path| path.join(CONFIG_FILE_NAME)) { save_config_with_file_name(app, config_path)?; } else { eprintln!("Error creating path to save config."); } Ok(()) } pub(crate) fn save_config_with_file_name( app: &AppContext, config_path: &std::path::Path, ) -> Result<(), Box<dyn Error>> { let serialized_config = serde_yaml::to_string(&app.config)?; match File::create(config_path).and_then(|mut f| f.write_all(serialized_config.as_bytes())) { ok @ Ok(_) => ok, Err(err) => { eprintln!("Error saving configuration: \n{}", &err); Err(err) } }?; Ok(()) } // // Make the below public for benchmarking only. // pub use crate::analysis::Analysis; pub use crate::app::load_file::load_file;
//! ## Build Example //! //! ```text //! . //! ├── build.rs //! ├── Cargo.toml //! ├── clib //! │   ├── meson.build //! │   ├── squid.h //! │   └── squid.c //! └── src //! └── lib.rs //! ``` //! //! build.rs: //! //! ``` //! extern crate meson; //! use std::env; //! use std::path::PathBuf; //! //! fn main() { //! let build_path = PathBuf::from(env::var("OUT_DIR").unwrap()); //! build_path.join("build"); //! let build_path = build_path.to_str().unwrap(); //! //! println!("cargo:rustc-link-lib=squid"); //! println!("cargo:rustc-link-search=native={}", build_path); //! meson::build("clib", build_path); //! } //! ``` //! //! Cargo.toml: //! //! ```toml //! # ... //! //! [build-dependencies] //! meson = "1.0.0" //! ``` //! //! meson.build: //! //! ```text //! project('squid', 'c') //! shared_library('squid', 'squid.c') //! ``` use std::path::PathBuf; use std::process::Command; /// Runs meson and/or ninja to build a project. pub fn build(project_dir: &str, build_dir: &str) { run_meson(project_dir, build_dir); } fn run_meson(lib: &str, dir: &str) { if !is_configured(dir) { run_command(lib, "meson", &[".", dir]); } run_command(dir, "ninja", &[]); } fn run_command(dir: &str, name: &str, args: &[&str]) { let mut cmd = Command::new(name); cmd.current_dir(dir); if args.len() > 0 { cmd.args(args); } let status = cmd.status().expect("cannot run command"); assert!(status.success()); } fn is_configured(dir: &str) -> bool { let mut path = PathBuf::from(dir); path.push("build.ninja"); return path.as_path().exists(); }
use std::{collections::HashMap, fmt::Display}; use async_trait::async_trait; use data_types::{Table, TableId}; use super::TablesSource; #[derive(Debug)] pub struct MockTablesSource { tables: HashMap<TableId, Table>, } impl MockTablesSource { #[allow(dead_code)] // not used anywhere pub fn new(tables: HashMap<TableId, Table>) -> Self { Self { tables } } } impl Display for MockTablesSource { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "mock") } } #[async_trait] impl TablesSource for MockTablesSource { async fn fetch(&self, table: TableId) -> Option<Table> { self.tables.get(&table).cloned() } } #[cfg(test)] mod tests { use iox_tests::TableBuilder; use super::*; #[test] fn test_display() { assert_eq!( MockTablesSource::new(HashMap::default()).to_string(), "mock", ) } #[tokio::test] async fn test_fetch() { let t_1 = TableBuilder::new(1).with_name("table1").build(); let t_2 = TableBuilder::new(2).with_name("table2").build(); let tables = HashMap::from([ (TableId::new(1), t_1.clone()), (TableId::new(2), t_2.clone()), ]); let source = MockTablesSource::new(tables); // different tables assert_eq!(source.fetch(TableId::new(1)).await, Some(t_1.clone()),); assert_eq!(source.fetch(TableId::new(2)).await, Some(t_2),); // fetching does not drain assert_eq!(source.fetch(TableId::new(1)).await, Some(t_1),); // unknown table => None result assert_eq!(source.fetch(TableId::new(3)).await, None,); } }
use amq_protocol::protocol::AMQPClass; use failure::{Backtrace, Context, Fail}; use std::fmt; use crate::api::ChannelState; /// The type of error that can be returned in this crate. /// /// Instead of implementing the `Error` trait provided by the standard library, /// it implemented the `Fail` trait provided by the `failure` crate. Doing so /// means that this type guaranteed to be both sendable and usable across /// threads, and that you'll be able to use the downcasting feature of the /// `failure::Error` type. #[derive(Debug)] pub struct Error { inner: Context<ErrorKind>, } /// The different kinds of errors that can be reported. /// /// Even though we expose the complete enumeration of possible error variants, it is not /// considered stable to exhaustively match on this enumeration: do it at your own risk. #[derive(Debug, PartialEq, Fail)] pub enum ErrorKind { #[fail(display = "output buffer is too small")] SendBufferTooSmall, #[fail(display = "input buffer is too small")] ReceiveBufferTooSmall, #[fail(display = "invalid channel state, expected {:?}, got {:?}", expected, actual)] InvalidState { expected: ChannelState, actual: ChannelState }, #[fail(display = "invalid protocol method: {:?}", _0)] InvalidMethod(AMQPClass), #[fail(display = "invalid channel: {}", _0)] InvalidChannel(u16), #[fail(display = "not connected")] NotConnected, #[fail(display = "unexpected answer")] UnexpectedAnswer, /// A hack to prevent developers from exhaustively match on the enum's variants /// /// The purpose of this variant is to let the `ErrorKind` enumeration grow more variants /// without it being a breaking change for users. It is planned for the language to provide /// this functionnality out of the box, though it has not been [stabilized] yet. /// /// [stabilized]: https://github.com/rust-lang/rust/issues/44109 #[doc(hidden)] #[fail(display = "lapin_async::error::ErrorKind::__Nonexhaustive: this should not be printed")] __Nonexhaustive, } impl Error { /// Return the underlying `ErrorKind` pub fn kind(&self) -> &ErrorKind { self.inner.get_context() } } impl Fail for Error { fn cause(&self) -> Option<&dyn Fail> { self.inner.cause() } fn backtrace(&self) -> Option<&Backtrace> { self.inner.backtrace() } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.inner, f) } } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Error { Error { inner: Context::new(kind) } } } impl From<Context<ErrorKind>> for Error { fn from(inner: Context<ErrorKind>) -> Error { Error { inner: inner } } }
// `without_number_errors_badarg` in unit tests test_stdout!(with_atom, "atom\n"); test_stdout!(with_small_integer, "1\n0\n");
// 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::boxed::Box; use super::super::qlib::common::*; use super::super::qlib::linux_def::*; use super::super::task::*; use super::super::qlib::linux::time::*; use super::super::qlib::linux::futex::*; use super::super::kernel::time::*; use super::super::threadmgr::task_syscall::*; use super::super::syscalls::syscalls::*; // futexWaitRestartBlock encapsulates the state required to restart futex(2) // via restart_syscall(2). pub struct FutexWaitRestartBlock { pub dur: Duration, pub addr: u64, pub private: bool, pub val: u32, pub mask: u32, } impl SyscallRestartBlock for FutexWaitRestartBlock { fn Restart(&self, task: &mut Task) -> Result<i64> { FutexWaitDuration(task, Some(self.dur), self.addr, self.private, self.val, self.mask) } } // futexWaitAbsolute performs a FUTEX_WAIT_BITSET, blocking until the wait is // complete. // // The wait blocks forever if forever is true, otherwise it blocks until ts. // // If blocking is interrupted, the syscall is restarted with the original // arguments. fn FutexWaitAbsolute(task: &mut Task, realtime: bool, ts: Option<Timespec>, addr: u64, private: bool, val: u32, mask: u32) -> Result<i64> { let waitEntry = task.blocker.generalEntry.clone(); task.futexMgr.WaitPrepare(&waitEntry, task, addr, private, val, mask)?; let res = match ts { None => task.blocker.BlockWithRealTimer(true, None), Some(ts) => { let ns = ts.ToDuration()?; if realtime { task.blocker.BlockWithRealTimer(true, Some(Time(ns))) } else { task.blocker.BlockWithMonoTimer(true, Some(Time(ns))) } } }; task.futexMgr.WaitComplete(&waitEntry); match res { Err(Error::ErrInterrupted) => return Err(Error::SysError(SysErr::ERESTARTSYS)), Err(e) => return Err(e), Ok(()) => return Ok(0), } } // futexWaitDuration performs a FUTEX_WAIT, blocking until the wait is // complete. // // The wait blocks forever if forever is true, otherwise is blocks for // duration. // // If blocking is interrupted, forever determines how to restart the // syscall. If forever is true, the syscall is restarted with the original // arguments. If forever is false, duration is a relative timeout and the // syscall is restarted with the remaining timeout. fn FutexWaitDuration(task: &mut Task, dur: Option<Duration>, addr: u64, private: bool, val: u32, mask: u32) -> Result<i64> { let waitEntry = task.blocker.generalEntry.clone(); task.futexMgr.WaitPrepare(&waitEntry, task, addr, private, val, mask)?; let (remain, res) = task.blocker.BlockWithMonoTimeout(true, dur); task.futexMgr.WaitComplete(&waitEntry); match res { Ok(_) => return Ok(0), Err(Error::ErrInterrupted) => (), // The wait was unsuccessful for some reason other than interruption. Simply // forward the error. Err(e) => return Err(e), }; // The wait was interrupted and we need to restart. Decide how. // The wait duration was absolute, restart with the original arguments. if dur.is_none() { //wait forever return Err(Error::SysError(SysErr::ERESTARTSYS)) } let b = Box::new(FutexWaitRestartBlock { dur: remain, addr: addr, private: private, val: val, mask: mask }); task.SetSyscallRestartBlock(b); return Err(Error::SysError(SysErr::ERESTART_RESTARTBLOCK)); } fn FutexLockPI(task: &mut Task, ts: Option<Timespec>, addr: u64, private: bool) -> Result<()> { let waitEntry = task.blocker.generalEntry.clone(); let tid = task.Thread().ThreadID(); let locked = task.futexMgr.LockPI(&waitEntry, task, addr, tid as u32, private, false)?; if locked { return Ok(()) } let res = match ts { None => task.blocker.BlockWithRealTimer(true, None), Some(ts) => { let ns = ts.ToDuration()?; task.blocker.BlockWithRealTimer(true, Some(Time(ns))) } }; task.futexMgr.WaitComplete(&waitEntry); match res { Err(Error::ErrInterrupted) => return Err(Error::SysError(SysErr::ERESTARTSYS)), Err(e) => return Err(e), Ok(()) => return Ok(()), } } fn TryLockPid(task: &mut Task, addr: u64, private: bool) -> Result<()> { let waitEntry = task.blocker.generalEntry.clone(); let tid = task.Thread().ThreadID(); let locked = task.futexMgr.LockPI(&waitEntry, task, addr, tid as u32, private, true)?; if !locked { task.futexMgr.WaitComplete(&waitEntry); return Err(Error::SysError(SysErr::EWOULDBLOCK)); } return Ok(()) } // Futex implements linux syscall futex(2). // It provides a method for a program to wait for a value at a given address to // change, and a method to wake up anyone waiting on a particular address. pub fn SysFutex(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0; let futexOp = args.arg1 as i32; let val = args.arg2 as i32; let nreq = args.arg3 as i32; let timeout = args.arg3; let naddr = args.arg4; let val3 = args.arg5 as i32; let cmd = futexOp & !(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME); let private = (futexOp & FUTEX_PRIVATE_FLAG) != 0; let realtime = (futexOp & FUTEX_CLOCK_REALTIME) != 0; let mut mask = val3 as u32; match cmd { FUTEX_WAIT | FUTEX_WAIT_BITSET => { // WAIT{_BITSET} wait forever if the timeout isn't passed. let forever = timeout == 0; let timespec = if !forever { Some(task.CopyInObj::<Timespec>(timeout)?) } else { None }; match cmd { FUTEX_WAIT => { //info!("FUTEX_WAIT..."); // WAIT uses a relative timeout. let mask = !0; let timeoutDur = if forever { None } else { Some(timespec.unwrap().ToDuration()?) }; return FutexWaitDuration(task, timeoutDur, addr, private, val as u32, mask); } FUTEX_WAIT_BITSET => { //info!("FUTEX_WAIT_BITSET..."); // WAIT_BITSET uses an absolute timeout which is either // CLOCK_MONOTONIC or CLOCK_REALTIME. if mask == 0 { return Err(Error::SysError(SysErr::EINVAL)) } return FutexWaitAbsolute(task, realtime, timespec, addr, private, val as u32, mask); } _ => panic!("not reachable") } } FUTEX_WAKE | FUTEX_WAKE_BITSET => { if cmd == FUTEX_WAKE { //info!("FUTEX_WAKE..."); mask = !0; } else { //info!("FUTEX_WAKE_BITSET..."); if mask == 0 { return Err(Error::SysError(SysErr::EINVAL)) } } // linux awake 1 waiter when val is 0 let n = if val == 0 { 1 } else { val }; let res = task.futexMgr.Wake(task, addr, private, mask, n)?; return Ok(res as i64); } FUTEX_REQUEUE => { //info!("FUTEX_REQUEUE..."); let n = task.futexMgr.Requeue(task, addr, naddr, private, val, nreq)?; return Ok(n as i64); } FUTEX_CMP_REQUEUE => { //info!("FUTEX_CMP_REQUEUE..."); // 'val3' contains the value to be checked at 'addr' and // 'val' is the number of waiters that should be woken up. let nval = val3 as u32; let n = task.futexMgr.RequeueCmp(task, addr, naddr, private, nval, val, nreq)?; return Ok(n as i64); } FUTEX_WAKE_OP => { //info!("FUTEX_WAKE_OP..."); let op = val3 as u32; let n = task.futexMgr.WakeOp(task, addr, naddr, private, val, nreq, op)?; return Ok(n as i64); } FUTEX_LOCK_PI => { //info!("FUTEX_LOCK_PI..."); let forever = timeout == 0; let timespec = if forever { None } else { Some(task.CopyInObj::<Timespec>(timeout)?) }; FutexLockPI(task, timespec, addr, private)?; return Ok(0) } FUTEX_TRYLOCK_PI => { //info!("FUTEX_TRYLOCK_PI..."); TryLockPid(task, addr, private)?; return Ok(0) } FUTEX_UNLOCK_PI => { //info!("FUTEX_UNLOCK_PI..."); let tid = task.Thread().ThreadID(); task.futexMgr.UnlockPI(task, addr, tid as u32, private)?; return Ok(0) } //FUTEX_WAIT_REQUEUE_PI | FUTEX_CMP_REQUEUE_PI _ => { return Err(Error::SysError(SysErr::ENOSYS)) } } }
pub trait Clock: Send + Sync { fn now(&self) -> i64; }
use super::internals::svm_engine_state::SVMEngineState; use super::internals::svm_error::SVMError; use super::internals::opcode::{OpcodeValue, OpCode}; use super::svm_program::SVMProgram; pub struct SVMEngine { engine_state: SVMEngineState } impl SVMEngine { pub fn new(program: SVMProgram) -> SVMEngine { SVMEngine { engine_state: SVMEngineState::new(program.get_bytecode()) } } pub fn run(&mut self) { loop { let opcode_number = self.engine_state.instruction_pointer.get_next_memory_value(&self.engine_state.memory); match opcode_number { Ok(opcode_value) => { /*println!("IP:{}, Opcode Value:{}\n", self.engine_state.instruction_pointer.get_ip(), opcode_value); */match opcode_value.get_opcode() { Ok(opcode) => match opcode.dispatch(&mut self.engine_state) { Err(error) => self.print_error(error), _ => {} }, Err(error) => self.print_error(error) }}, Err(error) => self.print_error(error) }; } } fn print_error(&self, error: SVMError) { let ip = self.engine_state.instruction_pointer.get_ip(); let opcode = match self.engine_state.memory.load_memory(ip) { Ok(x) => x, _ => 0, }; println!("Error at instruction: {}, opcode: {} ", ip, opcode); match error { SVMError::InvalidMemory => println!("Memory Error"), SVMError::InvalidOpCode => println!("Invalid Opcode"), SVMError::InvalidRegister => println!("Invalid Register"), SVMError::ReadError => println!("Read error"), SVMError::StackEmpty => println!("Stack error"), SVMError::WriteError => println!("Write error"), } std::process::exit(1); } }
use nannou::prelude::*; use crate::extensions::f32::*; pub type ContourRing = Vec<Point2>; fn to_nannou_contour_ring( rows: u16, columns: u16, container: &Rect, raw_contour_ring: &Vec<Vec<f64>>, ) -> ContourRing { let contour_ring: ContourRing = raw_contour_ring .iter() .map(move |coordinates| { let x = coordinates[0] as f32; let y = coordinates[1] as f32; let scaled_x = x.rescale(0.0, columns.into(), container.left(), container.right()); let scaled_y = y.rescale(0.0, rows.into(), container.bottom(), container.top()); pt2(scaled_x, scaled_y) }) .collect(); contour_ring } pub fn rings( threshold: f32, rows: u16, columns: u16, heights: &Vec<f64>, container: &Rect, ) -> Vec<ContourRing> { let raw_contour_rings = contour::contour_rings( heights.as_slice(), threshold.into(), columns.into(), rows.into(), ); let contour_rings: Vec<ContourRing> = raw_contour_rings .iter() .map(|raw_contour_ring| to_nannou_contour_ring(rows, columns, container, raw_contour_ring)) .collect(); contour_rings }
#[doc = "Reader of register ADC4R"] pub type R = crate::R<u32, super::ADC4R>; #[doc = "Writer for register ADC4R"] pub type W = crate::W<u32, super::ADC4R>; #[doc = "Register ADC4R `reset()`'s with value 0"] impl crate::ResetValue for super::ADC4R { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `AD2TERST`"] pub type AD2TERST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TERST`"] pub struct AD2TERST_W<'a> { w: &'a mut W, } impl<'a> AD2TERST_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 << 31)) | (((value as u32) & 0x01) << 31); self.w } } #[doc = "Reader of field `AD2TEC4`"] pub type AD2TEC4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TEC4`"] pub struct AD2TEC4_W<'a> { w: &'a mut W, } impl<'a> AD2TEC4_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 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `AD2TEC3`"] pub type AD2TEC3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TEC3`"] pub struct AD2TEC3_W<'a> { w: &'a mut W, } impl<'a> AD2TEC3_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 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `AD2TEC2`"] pub type AD2TEC2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TEC2`"] pub struct AD2TEC2_W<'a> { w: &'a mut W, } impl<'a> AD2TEC2_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 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `AD2TDRST`"] pub type AD2TDRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TDRST`"] pub struct AD2TDRST_W<'a> { w: &'a mut W, } impl<'a> AD2TDRST_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 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `AD2TDPER`"] pub type AD2TDPER_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TDPER`"] pub struct AD2TDPER_W<'a> { w: &'a mut W, } impl<'a> AD2TDPER_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 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `AD2TDC4`"] pub type AD2TDC4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TDC4`"] pub struct AD2TDC4_W<'a> { w: &'a mut W, } impl<'a> AD2TDC4_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 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `AD2TDC3`"] pub type AD2TDC3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TDC3`"] pub struct AD2TDC3_W<'a> { w: &'a mut W, } impl<'a> AD2TDC3_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 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `AD2TDC2`"] pub type AD2TDC2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TDC2`"] pub struct AD2TDC2_W<'a> { w: &'a mut W, } impl<'a> AD2TDC2_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 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `AD2TCRST`"] pub type AD2TCRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TCRST`"] pub struct AD2TCRST_W<'a> { w: &'a mut W, } impl<'a> AD2TCRST_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 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `AD2TCPER`"] pub type AD2TCPER_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TCPER`"] pub struct AD2TCPER_W<'a> { w: &'a mut W, } impl<'a> AD2TCPER_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 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `AD2TCC4`"] pub type AD2TCC4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TCC4`"] pub struct AD2TCC4_W<'a> { w: &'a mut W, } impl<'a> AD2TCC4_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 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `AD2TCC3`"] pub type AD2TCC3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TCC3`"] pub struct AD2TCC3_W<'a> { w: &'a mut W, } impl<'a> AD2TCC3_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 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `AD2TCC2`"] pub type AD2TCC2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TCC2`"] pub struct AD2TCC2_W<'a> { w: &'a mut W, } impl<'a> AD2TCC2_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 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `AD2TBPER`"] pub type AD2TBPER_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TBPER`"] pub struct AD2TBPER_W<'a> { w: &'a mut W, } impl<'a> AD2TBPER_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `AD2TBC4`"] pub type AD2TBC4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TBC4`"] pub struct AD2TBC4_W<'a> { w: &'a mut W, } impl<'a> AD2TBC4_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 = "Reader of field `AD2TBC3`"] pub type AD2TBC3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TBC3`"] pub struct AD2TBC3_W<'a> { w: &'a mut W, } impl<'a> AD2TBC3_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 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `AD2TBC2`"] pub type AD2TBC2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TBC2`"] pub struct AD2TBC2_W<'a> { w: &'a mut W, } impl<'a> AD2TBC2_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 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `AD2TAPER`"] pub type AD2TAPER_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TAPER`"] pub struct AD2TAPER_W<'a> { w: &'a mut W, } impl<'a> AD2TAPER_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 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `AD2TAC4`"] pub type AD2TAC4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TAC4`"] pub struct AD2TAC4_W<'a> { w: &'a mut W, } impl<'a> AD2TAC4_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 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `AD2TAC3`"] pub type AD2TAC3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TAC3`"] pub struct AD2TAC3_W<'a> { w: &'a mut W, } impl<'a> AD2TAC3_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 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `AD2TAC2`"] pub type AD2TAC2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2TAC2`"] pub struct AD2TAC2_W<'a> { w: &'a mut W, } impl<'a> AD2TAC2_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 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `AD2EEV10`"] pub type AD2EEV10_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2EEV10`"] pub struct AD2EEV10_W<'a> { w: &'a mut W, } impl<'a> AD2EEV10_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 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `AD2EEV9`"] pub type AD2EEV9_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2EEV9`"] pub struct AD2EEV9_W<'a> { w: &'a mut W, } impl<'a> AD2EEV9_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 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `AD2EEV8`"] pub type AD2EEV8_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2EEV8`"] pub struct AD2EEV8_W<'a> { w: &'a mut W, } impl<'a> AD2EEV8_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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `AD2EEV7`"] pub type AD2EEV7_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2EEV7`"] pub struct AD2EEV7_W<'a> { w: &'a mut W, } impl<'a> AD2EEV7_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `AD2EEV6`"] pub type AD2EEV6_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2EEV6`"] pub struct AD2EEV6_W<'a> { w: &'a mut W, } impl<'a> AD2EEV6_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `AD2MPER`"] pub type AD2MPER_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2MPER`"] pub struct AD2MPER_W<'a> { w: &'a mut W, } impl<'a> AD2MPER_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 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `AD2MC4`"] pub type AD2MC4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2MC4`"] pub struct AD2MC4_W<'a> { w: &'a mut W, } impl<'a> AD2MC4_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 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `AD2MC3`"] pub type AD2MC3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2MC3`"] pub struct AD2MC3_W<'a> { w: &'a mut W, } impl<'a> AD2MC3_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 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `AD2MC2`"] pub type AD2MC2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2MC2`"] pub struct AD2MC2_W<'a> { w: &'a mut W, } impl<'a> AD2MC2_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 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `AD2MC1`"] pub type AD2MC1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AD2MC1`"] pub struct AD2MC1_W<'a> { w: &'a mut W, } impl<'a> AD2MC1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 31 - AD2TERST"] #[inline(always)] pub fn ad2terst(&self) -> AD2TERST_R { AD2TERST_R::new(((self.bits >> 31) & 0x01) != 0) } #[doc = "Bit 30 - AD2TEC4"] #[inline(always)] pub fn ad2tec4(&self) -> AD2TEC4_R { AD2TEC4_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 29 - AD2TEC3"] #[inline(always)] pub fn ad2tec3(&self) -> AD2TEC3_R { AD2TEC3_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 28 - AD2TEC2"] #[inline(always)] pub fn ad2tec2(&self) -> AD2TEC2_R { AD2TEC2_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 27 - AD2TDRST"] #[inline(always)] pub fn ad2tdrst(&self) -> AD2TDRST_R { AD2TDRST_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 26 - AD2TDPER"] #[inline(always)] pub fn ad2tdper(&self) -> AD2TDPER_R { AD2TDPER_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 25 - AD2TDC4"] #[inline(always)] pub fn ad2tdc4(&self) -> AD2TDC4_R { AD2TDC4_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 24 - AD2TDC3"] #[inline(always)] pub fn ad2tdc3(&self) -> AD2TDC3_R { AD2TDC3_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 23 - AD2TDC2"] #[inline(always)] pub fn ad2tdc2(&self) -> AD2TDC2_R { AD2TDC2_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 22 - AD2TCRST"] #[inline(always)] pub fn ad2tcrst(&self) -> AD2TCRST_R { AD2TCRST_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 21 - AD2TCPER"] #[inline(always)] pub fn ad2tcper(&self) -> AD2TCPER_R { AD2TCPER_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 20 - AD2TCC4"] #[inline(always)] pub fn ad2tcc4(&self) -> AD2TCC4_R { AD2TCC4_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 19 - AD2TCC3"] #[inline(always)] pub fn ad2tcc3(&self) -> AD2TCC3_R { AD2TCC3_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 18 - AD2TCC2"] #[inline(always)] pub fn ad2tcc2(&self) -> AD2TCC2_R { AD2TCC2_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - AD2TBPER"] #[inline(always)] pub fn ad2tbper(&self) -> AD2TBPER_R { AD2TBPER_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - AD2TBC4"] #[inline(always)] pub fn ad2tbc4(&self) -> AD2TBC4_R { AD2TBC4_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 15 - AD2TBC3"] #[inline(always)] pub fn ad2tbc3(&self) -> AD2TBC3_R { AD2TBC3_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 14 - AD2TBC2"] #[inline(always)] pub fn ad2tbc2(&self) -> AD2TBC2_R { AD2TBC2_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 13 - AD2TAPER"] #[inline(always)] pub fn ad2taper(&self) -> AD2TAPER_R { AD2TAPER_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 12 - AD2TAC4"] #[inline(always)] pub fn ad2tac4(&self) -> AD2TAC4_R { AD2TAC4_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 11 - AD2TAC3"] #[inline(always)] pub fn ad2tac3(&self) -> AD2TAC3_R { AD2TAC3_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 10 - AD2TAC2"] #[inline(always)] pub fn ad2tac2(&self) -> AD2TAC2_R { AD2TAC2_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - AD2EEV10"] #[inline(always)] pub fn ad2eev10(&self) -> AD2EEV10_R { AD2EEV10_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - AD2EEV9"] #[inline(always)] pub fn ad2eev9(&self) -> AD2EEV9_R { AD2EEV9_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 7 - AD2EEV8"] #[inline(always)] pub fn ad2eev8(&self) -> AD2EEV8_R { AD2EEV8_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 6 - AD2EEV7"] #[inline(always)] pub fn ad2eev7(&self) -> AD2EEV7_R { AD2EEV7_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 5 - AD2EEV6"] #[inline(always)] pub fn ad2eev6(&self) -> AD2EEV6_R { AD2EEV6_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - AD2MPER"] #[inline(always)] pub fn ad2mper(&self) -> AD2MPER_R { AD2MPER_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - AD2MC4"] #[inline(always)] pub fn ad2mc4(&self) -> AD2MC4_R { AD2MC4_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - AD2MC3"] #[inline(always)] pub fn ad2mc3(&self) -> AD2MC3_R { AD2MC3_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - AD2MC2"] #[inline(always)] pub fn ad2mc2(&self) -> AD2MC2_R { AD2MC2_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - AD2MC1"] #[inline(always)] pub fn ad2mc1(&self) -> AD2MC1_R { AD2MC1_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 31 - AD2TERST"] #[inline(always)] pub fn ad2terst(&mut self) -> AD2TERST_W { AD2TERST_W { w: self } } #[doc = "Bit 30 - AD2TEC4"] #[inline(always)] pub fn ad2tec4(&mut self) -> AD2TEC4_W { AD2TEC4_W { w: self } } #[doc = "Bit 29 - AD2TEC3"] #[inline(always)] pub fn ad2tec3(&mut self) -> AD2TEC3_W { AD2TEC3_W { w: self } } #[doc = "Bit 28 - AD2TEC2"] #[inline(always)] pub fn ad2tec2(&mut self) -> AD2TEC2_W { AD2TEC2_W { w: self } } #[doc = "Bit 27 - AD2TDRST"] #[inline(always)] pub fn ad2tdrst(&mut self) -> AD2TDRST_W { AD2TDRST_W { w: self } } #[doc = "Bit 26 - AD2TDPER"] #[inline(always)] pub fn ad2tdper(&mut self) -> AD2TDPER_W { AD2TDPER_W { w: self } } #[doc = "Bit 25 - AD2TDC4"] #[inline(always)] pub fn ad2tdc4(&mut self) -> AD2TDC4_W { AD2TDC4_W { w: self } } #[doc = "Bit 24 - AD2TDC3"] #[inline(always)] pub fn ad2tdc3(&mut self) -> AD2TDC3_W { AD2TDC3_W { w: self } } #[doc = "Bit 23 - AD2TDC2"] #[inline(always)] pub fn ad2tdc2(&mut self) -> AD2TDC2_W { AD2TDC2_W { w: self } } #[doc = "Bit 22 - AD2TCRST"] #[inline(always)] pub fn ad2tcrst(&mut self) -> AD2TCRST_W { AD2TCRST_W { w: self } } #[doc = "Bit 21 - AD2TCPER"] #[inline(always)] pub fn ad2tcper(&mut self) -> AD2TCPER_W { AD2TCPER_W { w: self } } #[doc = "Bit 20 - AD2TCC4"] #[inline(always)] pub fn ad2tcc4(&mut self) -> AD2TCC4_W { AD2TCC4_W { w: self } } #[doc = "Bit 19 - AD2TCC3"] #[inline(always)] pub fn ad2tcc3(&mut self) -> AD2TCC3_W { AD2TCC3_W { w: self } } #[doc = "Bit 18 - AD2TCC2"] #[inline(always)] pub fn ad2tcc2(&mut self) -> AD2TCC2_W { AD2TCC2_W { w: self } } #[doc = "Bit 17 - AD2TBPER"] #[inline(always)] pub fn ad2tbper(&mut self) -> AD2TBPER_W { AD2TBPER_W { w: self } } #[doc = "Bit 16 - AD2TBC4"] #[inline(always)] pub fn ad2tbc4(&mut self) -> AD2TBC4_W { AD2TBC4_W { w: self } } #[doc = "Bit 15 - AD2TBC3"] #[inline(always)] pub fn ad2tbc3(&mut self) -> AD2TBC3_W { AD2TBC3_W { w: self } } #[doc = "Bit 14 - AD2TBC2"] #[inline(always)] pub fn ad2tbc2(&mut self) -> AD2TBC2_W { AD2TBC2_W { w: self } } #[doc = "Bit 13 - AD2TAPER"] #[inline(always)] pub fn ad2taper(&mut self) -> AD2TAPER_W { AD2TAPER_W { w: self } } #[doc = "Bit 12 - AD2TAC4"] #[inline(always)] pub fn ad2tac4(&mut self) -> AD2TAC4_W { AD2TAC4_W { w: self } } #[doc = "Bit 11 - AD2TAC3"] #[inline(always)] pub fn ad2tac3(&mut self) -> AD2TAC3_W { AD2TAC3_W { w: self } } #[doc = "Bit 10 - AD2TAC2"] #[inline(always)] pub fn ad2tac2(&mut self) -> AD2TAC2_W { AD2TAC2_W { w: self } } #[doc = "Bit 9 - AD2EEV10"] #[inline(always)] pub fn ad2eev10(&mut self) -> AD2EEV10_W { AD2EEV10_W { w: self } } #[doc = "Bit 8 - AD2EEV9"] #[inline(always)] pub fn ad2eev9(&mut self) -> AD2EEV9_W { AD2EEV9_W { w: self } } #[doc = "Bit 7 - AD2EEV8"] #[inline(always)] pub fn ad2eev8(&mut self) -> AD2EEV8_W { AD2EEV8_W { w: self } } #[doc = "Bit 6 - AD2EEV7"] #[inline(always)] pub fn ad2eev7(&mut self) -> AD2EEV7_W { AD2EEV7_W { w: self } } #[doc = "Bit 5 - AD2EEV6"] #[inline(always)] pub fn ad2eev6(&mut self) -> AD2EEV6_W { AD2EEV6_W { w: self } } #[doc = "Bit 4 - AD2MPER"] #[inline(always)] pub fn ad2mper(&mut self) -> AD2MPER_W { AD2MPER_W { w: self } } #[doc = "Bit 3 - AD2MC4"] #[inline(always)] pub fn ad2mc4(&mut self) -> AD2MC4_W { AD2MC4_W { w: self } } #[doc = "Bit 2 - AD2MC3"] #[inline(always)] pub fn ad2mc3(&mut self) -> AD2MC3_W { AD2MC3_W { w: self } } #[doc = "Bit 1 - AD2MC2"] #[inline(always)] pub fn ad2mc2(&mut self) -> AD2MC2_W { AD2MC2_W { w: self } } #[doc = "Bit 0 - AD2MC1"] #[inline(always)] pub fn ad2mc1(&mut self) -> AD2MC1_W { AD2MC1_W { w: self } } }
// The functions replacing the C macros use the same names as in libc. #![allow(non_snake_case, unsafe_code)] use linux_raw_sys::ctypes::c_int; pub(crate) use linux_raw_sys::general::{ siginfo_t, WCONTINUED, WEXITED, WNOHANG, WNOWAIT, WSTOPPED, WUNTRACED, }; #[inline] pub(crate) fn WIFSTOPPED(status: u32) -> bool { (status & 0xff) == 0x7f } #[inline] pub(crate) fn WSTOPSIG(status: u32) -> u32 { (status >> 8) & 0xff } #[inline] pub(crate) fn WIFCONTINUED(status: u32) -> bool { status == 0xffff } #[inline] pub(crate) fn WIFSIGNALED(status: u32) -> bool { ((status & 0x7f) + 1) as i8 >= 2 } #[inline] pub(crate) fn WTERMSIG(status: u32) -> u32 { status & 0x7f } #[inline] pub(crate) fn WIFEXITED(status: u32) -> bool { (status & 0x7f) == 0 } #[inline] pub(crate) fn WEXITSTATUS(status: u32) -> u32 { (status >> 8) & 0xff } pub(crate) trait SiginfoExt { fn si_code(&self) -> c_int; unsafe fn si_status(&self) -> c_int; } impl SiginfoExt for siginfo_t { #[inline] fn si_code(&self) -> c_int { // SAFETY: This is technically a union access, but it's only a union // with padding. unsafe { self.__bindgen_anon_1.__bindgen_anon_1.si_code } } /// Return the exit status or signal number recorded in a `siginfo_t`. /// /// # Safety /// /// `si_signo` must equal `SIGCHLD` (as it is guaranteed to do after a /// `waitid` call). #[inline] #[rustfmt::skip] unsafe fn si_status(&self) -> c_int { self.__bindgen_anon_1.__bindgen_anon_1._sifields._sigchld._status } }
use super::computing_script::*; use super::derived_state; use super::derived_state::{DerivedStateData}; use super::super::script_type_description::*; use super::super::streams::*; use super::super::symbol::*; use super::super::error::*; use desync::Desync; use gluon::*; use gluon::compiler_pipeline::{Compileable}; use gluon::vm::{ExternModule}; use gluon::vm::api::{VmType, Getable}; use futures::*; use futures::future; use futures::sync::oneshot; use std::any::*; use std::sync::*; use std::collections::{HashMap}; use std::result::{Result}; /// /// Possible definitions of a symbol in the namespace /// #[derive(Clone)] enum SymbolDefinition { /// Symbol is an input stream Input(InputStreamSource), /// An instantiated script acting as an input source ActiveScript(InputStreamSource), /// Symbol represents a script that couldn't be compiled ScriptError(String), /// Compiled computing expression Computing(Arc<String>), /// Symbol is a namespace Namespace(Arc<Desync<GluonScriptNamespace>>) } /// /// Represents a script namespace /// #[derive(Clone)] pub struct GluonScriptNamespace { /// The definitions for the symbols in this namespace symbols: HashMap<FloScriptSymbol, SymbolDefinition>, /// The current thread for generating streaming scripts (or none if it hasn't been created yet) streaming: Option<RootedThread>, /// The current thread for generating state updating scripts computing: Option<Arc<RootedThread>>, /// Whether or not we'll run I/O operations in this namespace or not run_io: bool } impl GluonScriptNamespace { /// /// Creates a new script namespace. The scripting VM is initially not started /// pub fn new() -> GluonScriptNamespace { GluonScriptNamespace { symbols: HashMap::new(), streaming: None, computing: None, run_io: false } } /// /// Clears this namespace /// pub fn clear(&mut self) { self.symbols.clear(); self.streaming = None; self.computing = None; } /// /// Defines a particular symbol to be an input stream /// pub fn define_input_symbol(&mut self, symbol: FloScriptSymbol, input_stream_type: ScriptTypeDescription) { let source = InputStreamSource::new(input_stream_type); self.symbols.insert(symbol, SymbolDefinition::Input(source)); } /// /// Loads the 'flo.state.resolve' module for a namespace /// pub fn load_state_resolve_module(namespace: &GluonScriptNamespace, thread: &Thread) -> Result<ExternModule, gluon::vm::Error> { unimplemented!() } /// /// Creates a stream to read from a particular symbol /// pub fn read_stream<Symbol: 'static+ScriptType>(&mut self, symbol: FloScriptSymbol) -> FloScriptResult<Box<dyn Stream<Item=Symbol, Error=()>+Send>> where Symbol: for<'vm, 'value> Getable<'vm, 'value> + VmType + Send + 'static, <Symbol as VmType>::Type: Sized { use self::SymbolDefinition::*; match self.symbols.get_mut(&symbol) { None => Err(FloScriptError::UndefinedSymbol(symbol)), Some(ScriptError(description)) => Err(FloScriptError::ScriptError(description.clone())), Some(Input(input_source)) | Some(ActiveScript(input_source)) => Ok(Box::new(input_source.read_as_stream()?)), Some(Computing(expr)) => { let expr = Arc::clone(expr); Ok(Box::new(self.create_computing_stream(symbol, expr)?)) }, Some(Namespace(_)) => Err(FloScriptError::CannotReadFromANamespace) } } /// /// Creates a stream to read from a particular symbol using the state stream semantics /// pub fn read_state_stream<Symbol: 'static+ScriptType>(&mut self, symbol: FloScriptSymbol) -> FloScriptResult<Box<dyn Stream<Item=Symbol, Error=()>+Send>> where Symbol: for<'vm, 'value> Getable<'vm, 'value> + VmType + Send + 'static, <Symbol as VmType>::Type: Sized { use self::SymbolDefinition::*; match self.symbols.get_mut(&symbol) { None => Err(FloScriptError::UndefinedSymbol(symbol)), Some(ScriptError(description)) => Err(FloScriptError::ScriptError(description.clone())), Some(Input(input_source)) | Some(ActiveScript(input_source)) => Ok(Box::new(input_source.read_as_state_stream()?)), Some(Computing(expr)) => { let expr = Arc::clone(expr); Ok(Box::new(self.create_computing_stream(symbol, expr)?)) }, Some(Namespace(_)) => Err(FloScriptError::CannotReadFromANamespace) } } /// /// Creates a new computing stream from a script, storing the result as a new input stream associated with the specified symbol /// pub fn create_computing_stream<Item: 'static+ScriptType>(&mut self, symbol: FloScriptSymbol, expression: Arc<String>) -> FloScriptResult<impl Stream<Item=Item, Error=()>> where Item: for<'vm, 'value> Getable<'vm, 'value> + VmType + Send + 'static, <Item as VmType>::Type: Sized { let computing_thread = self.get_computing_thread(); let mut compiler = Compiler::default(); let expression = (&*expression).compile(&mut compiler, &computing_thread, &symbol.name().unwrap_or("".to_string()), &*expression, None); // Report on the result match expression { Ok(compiled) => { // Create as an input stream let stream = ComputingScriptStream::<Item>::new(computing_thread, compiled, Compiler::default())?; // This will become the input stream for the specified symbol let mut input_stream_source = InputStreamSource::new(Item::description()); input_stream_source.attach(stream)?; // The output is read as a state stream from this input let result_stream = input_stream_source.read_as_state_stream()?; // Update the symbol to be an active stream self.symbols.insert(symbol, SymbolDefinition::ActiveScript(input_stream_source)); Ok(result_stream) }, Err(fail) => { // Generate a script error let error_string = fail.emit_string(&compiler.code_map()) .unwrap_or("<Error while compiling (could not convert to string)>".to_string()); // Don't try to run this script again self.symbols.insert(symbol, SymbolDefinition::ScriptError(error_string.clone())); // Return as the result Err(FloScriptError::ScriptError(error_string)) } } } /// /// Attaches an input stream to a particular symbol /// pub fn attach_input<InputStream: 'static+Stream<Error=()>+Send>(&mut self, symbol: FloScriptSymbol, input: InputStream) -> FloScriptResult<()> where InputStream::Item: 'static+ScriptType { use self::SymbolDefinition::*; match self.symbols.get_mut(&symbol) { None => Err(FloScriptError::UndefinedSymbol(symbol)), Some(Input(input_source)) => input_source.attach(input), _ => Err(FloScriptError::NotAnInputSymbol) } } /// /// Removes the definition of a symbol from this namespace (if it exists) /// pub fn undefine_symbol(&mut self, symbol: FloScriptSymbol) { self.symbols.remove(&symbol); } /// /// Retrieves a sub-namespace within this namespace. The symbol must already be defined to be a namespace, or must be /// undefined (in which case it will be assigned as a namespace) /// pub fn get_or_create_namespace(&mut self, symbol: FloScriptSymbol) -> FloScriptResult<Arc<Desync<GluonScriptNamespace>>> { // Insert the namespace if it doesn't already exist if self.symbols.get(&symbol).is_none() { self.symbols.insert(symbol, SymbolDefinition::Namespace(Arc::new(Desync::new(GluonScriptNamespace::new())))); } // Retrieve the namespace self.symbols.get(&symbol) .and_then(|symbol| if let SymbolDefinition::Namespace(symbol) = symbol { Some(Arc::clone(symbol)) } else { None }) .ok_or(FloScriptError::NotANamespace) } /// /// Retrieves a sub-namespace, if it is defined /// pub fn get_namespace(&self, symbol: FloScriptSymbol) -> Option<Arc<Desync<GluonScriptNamespace>>> { self.symbols.get(&symbol) .and_then(|symbol| if let SymbolDefinition::Namespace(symbol) = symbol { Some(Arc::clone(symbol)) } else { None }) } /// /// Sets whether or not this namespace will run IO commands /// pub fn set_run_io(&mut self, run_io: bool) { // This affects statements compiled after this is set self.run_io = run_io; } /// /// Loads a streaming script into this namespace /// pub fn set_streaming_script(&mut self, _symbol: FloScriptSymbol, script: String) { } /// /// Creates a new thread for this namespace /// fn create_thread(&self) -> RootedThread { // Create the thread as a new VM let thread = new_vm(); // Import the standard modules derived_state::load_flo_computed(&thread).expect("Load flo.computed module"); // To make user data types available to Rust, we need to invoke the side-effects of the import! macro inside gluon Compiler::default().run_expr::<()>(&thread, "import_flo_computed", "import! flo.computed\n()").unwrap(); thread } /// /// Retrieves the computing thread for this namespace, if available /// fn get_computing_thread(&mut self) -> Arc<RootedThread> { let thread = self.computing.clone(); if let Some(thread) = thread { thread } else { let thread = Arc::new(self.create_thread()); self.computing = Some(Arc::clone(&thread)); thread } } /// /// Loads a computing script into this namespace /// pub fn set_computing_script(&mut self, symbol: FloScriptSymbol, script: String) { self.symbols.insert(symbol, SymbolDefinition::Computing(Arc::new(script))); } }
use self_cell::self_cell; pub type I32Ref<'a> = &'a i32; self_cell!( pub struct I32Cell { owner: i32, #[covariant] dependent: I32Ref, } ); pub type Ast<'a> = Vec<&'a str>; self_cell!( pub struct StringCell { owner: String, #[covariant] dependent: Ast, } );
pub fn run_client() { println!("run dbus from client .... "); } use dbus::blocking::Connection; use std::time::Duration; pub enum Variant {} pub fn run_dbus( service: &str, obj_path: &str, method: &str, ) -> Result<Vec<String>, Box<dyn std::error::Error>> { let conn = Connection::new_session()?; let proxy = conn.with_proxy(service, obj_path, Duration::from_millis(100)); let (name,): (Vec<String>,) = proxy.method_call(service, method, ())?; Ok(name) } pub fn dbus_call( service: &str, obj_path: &str, method: &str, ) -> Result<bool, Box<dyn std::error::Error>> { let conn = Connection::new_session()?; let proxy = conn.with_proxy(service, obj_path, Duration::from_millis(100)); let (status,): (bool,) = proxy.method_call(service, method, ())?; Ok(status) }
// Copyright (c) 2018-2022 Ministerio de Fomento // Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC) // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // Author(s): Rafael Villar Burke <pachi@ietcc.csic.es>, // Daniel Jiménez González <dani@ietcc.csic.es>, // Marta Sorribes Gil <msorribes@ietcc.csic.es> /*! Tipos para la eficiencia energética =================================== Definición de tipos para la evaluación de la eficiencia energética y sus datos, según la EN ISO 52000-1. */ use std::collections::HashMap; use serde::{Deserialize, Serialize}; use crate::{types::Carrier, Components, Factors}; use super::{BalanceCarrier, Balance}; // Overall energy performance // -------------------------- /// Datos y resultados de un cálculo de eficiencia energética #[allow(dead_code)] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EnergyPerformance { /// Energy components (produced and consumed energy data + metadata) pub components: Components, /// Weighting factors (weighting factors + metadata) pub wfactors: Factors, /// Exported energy factor [0, 1] pub k_exp: f32, /// Reference area used for energy performance ratios (>1e-3) pub arearef: f32, /// Energy balance results by carrier pub balance_cr: HashMap<Carrier, BalanceCarrier>, /// Global energy balance results pub balance: Balance, /// Global energy balance results expressed as area ratios pub balance_m2: Balance, /// Renewable Energy Ratio considering the distant perimeter /// RER = we_ren / we_tot pub rer: f32, /// Renewable Energy Ratio considering onsite and nearby perimeter /// RER_nrb = we_ren_nrb+onst / we_tot pub rer_nrb: f32, /// Renewable Energy Ratio considering onsite perimeter /// RER_onst = we_ren_onst / we_tot pub rer_onst: f32, /// Generic miscelaneous user provided data pub misc: Option<MiscMap>, } /// Diccionario de valores adicionales #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct MiscMap(pub HashMap<String, String>); impl MiscMap { /// Get value as a string with 1 digit precision or a dash if value is missing or is not a number pub fn get_str_1d(&self, key: &str) -> String { self.get(key) .and_then(|v| v.parse::<f32>().map(|r| format!("{:.1}", r)).ok()) .unwrap_or_else(|| "-".to_string()) } /// Get value as a string for a value, as a percent with 1 digit precision or a dash if value is missing or is not a number pub fn get_str_pct1d(&self, key: &str) -> String { self.get(key) .and_then(|v| v.parse::<f32>().map(|r| format!("{:.1}", 100.0 * r)).ok()) .unwrap_or_else(|| "-".to_string()) } } impl std::ops::Deref for MiscMap { type Target = HashMap<String, String>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for MiscMap { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
//! Code to decode [`MutableBatch`] from pbdata protobuf use generated_types::influxdata::pbdata::v1::{ column::{SemanticType, Values as PbValues}, Column as PbColumn, DatabaseBatch, PackedStrings, TableBatch, }; use hashbrown::{HashMap, HashSet}; use mutable_batch::{writer::Writer, MutableBatch}; use schema::{InfluxColumnType, InfluxFieldType, TIME_COLUMN_NAME}; use snafu::{ensure, OptionExt, ResultExt, Snafu}; /// Error type for line protocol conversion #[derive(Debug, Snafu)] #[allow(missing_docs)] pub enum Error { #[snafu(display("error writing column {}: {}", column, source))] Write { source: mutable_batch::writer::Error, column: String, }, #[snafu(display("duplicate column name: {}", column))] DuplicateColumnName { column: String }, #[snafu(display("table batch must contain time column"))] MissingTime, #[snafu(display("time column must not contain nulls"))] NullTime, #[snafu(display("column with no values: {}", column))] EmptyColumn { column: String }, #[snafu(display("column missing dictionary: {}", column))] MissingDictionary { column: String }, #[snafu(display( "column \"{}\" contains invalid offset {} at index {}", column, offset, index ))] InvalidOffset { column: String, offset: usize, index: usize, }, #[snafu(display("column \"{}\" contains more than one type of values", column))] MultipleValues { column: String }, #[snafu(display("cannot infer type for column: {}", column))] InvalidType { column: String }, } /// Result type for pbdata conversion pub type Result<T, E = Error> = std::result::Result<T, E>; /// Decodes a [`DatabaseBatch`] to a map of [`MutableBatch`] keyed by table ID pub fn decode_database_batch(database_batch: &DatabaseBatch) -> Result<HashMap<i64, MutableBatch>> { let mut id_to_data = HashMap::with_capacity(database_batch.table_batches.len()); for table_batch in &database_batch.table_batches { let batch = id_to_data.entry(table_batch.table_id).or_default(); write_table_batch(batch, table_batch)?; } Ok(id_to_data) } /// Writes the provided [`TableBatch`] to a [`MutableBatch`] on error any changes made /// to `batch` are reverted pub fn write_table_batch(batch: &mut MutableBatch, table_batch: &TableBatch) -> Result<()> { let to_insert = table_batch.row_count as usize; if to_insert == 0 { return Ok(()); } // Verify columns are unique let mut columns = HashSet::with_capacity(table_batch.columns.len()); for col in &table_batch.columns { ensure!( columns.insert(col.column_name.as_str()), DuplicateColumnNameSnafu { column: &col.column_name } ); } // Batch must contain a time column ensure!(columns.contains(TIME_COLUMN_NAME), MissingTimeSnafu); let mut writer = Writer::new(batch, to_insert); for column in &table_batch.columns { let influx_type = pb_column_type(column)?; let valid_mask = compute_valid_mask(&column.null_mask, to_insert); let valid_mask = valid_mask.as_deref(); // Already verified has values let values = column.values.as_ref().unwrap(); match influx_type { InfluxColumnType::Field(InfluxFieldType::Float) => writer.write_f64( &column.column_name, valid_mask, RepeatLastElement::new(values.f64_values.iter().cloned()), ), InfluxColumnType::Field(InfluxFieldType::Integer) => writer.write_i64( &column.column_name, valid_mask, RepeatLastElement::new(values.i64_values.iter().cloned()), ), InfluxColumnType::Field(InfluxFieldType::UInteger) => writer.write_u64( &column.column_name, valid_mask, RepeatLastElement::new(values.u64_values.iter().cloned()), ), InfluxColumnType::Tag => { if let Some(interned) = values.interned_string_values.as_ref() { let dictionary = interned .dictionary .as_ref() .context(MissingDictionarySnafu { column: &column.column_name, })?; validate_packed_string(&column.column_name, dictionary)?; writer.write_tag_dict( &column.column_name, valid_mask, RepeatLastElement::new(interned.values.iter().map(|x| *x as usize)), packed_strings_iter(dictionary), ) } else if let Some(packed) = values.packed_string_values.as_ref() { validate_packed_string(&column.column_name, packed)?; writer.write_tag( &column.column_name, valid_mask, RepeatLastElement::new(packed_strings_iter(packed)), ) } else { writer.write_tag( &column.column_name, valid_mask, RepeatLastElement::new(values.string_values.iter().map(|x| x.as_str())), ) } } InfluxColumnType::Field(InfluxFieldType::String) => { if let Some(interned) = values.interned_string_values.as_ref() { let dictionary = interned .dictionary .as_ref() .context(MissingDictionarySnafu { column: &column.column_name, })?; validate_packed_string(&column.column_name, dictionary)?; writer.write_string( &column.column_name, valid_mask, RepeatLastElement::new( interned .values .iter() .map(|x| packed_string_idx(dictionary, *x as usize)), ), ) } else if let Some(packed) = values.packed_string_values.as_ref() { validate_packed_string(&column.column_name, packed)?; writer.write_string( &column.column_name, valid_mask, RepeatLastElement::new(packed_strings_iter(packed)), ) } else { writer.write_string( &column.column_name, valid_mask, RepeatLastElement::new(values.string_values.iter().map(|x| x.as_str())), ) } } InfluxColumnType::Field(InfluxFieldType::Boolean) => writer.write_bool( &column.column_name, valid_mask, RepeatLastElement::new(values.bool_values.iter().cloned()), ), InfluxColumnType::Timestamp => { ensure!(valid_mask.is_none(), NullTimeSnafu); writer.write_time( &column.column_name, RepeatLastElement::new(values.i64_values.iter().cloned()), ) } } .context(WriteSnafu { column: &column.column_name, })?; } writer.commit(); Ok(()) } /// Inner state of [`RepeatLastElement`]. enum RepeatLastElementInner<I> where I: Iterator, I::Item: Clone, { /// The iteration is running and the iterator hasn't ended yet. Running { it: I, next: I::Item }, /// The iterator has ended and we're repeating the last element by cloning it. Repeating { element: I::Item }, /// The iterator was empty. Empty, } /// Iterator wrapper that repeats the last element forever. /// /// This will just yield `None` if the wrapped iterator was empty. struct RepeatLastElement<I> where I: Iterator, I::Item: Clone, { /// Inner state, wrapped into an option to make the borrow-checker happy. inner: Option<RepeatLastElementInner<I>>, } impl<I> RepeatLastElement<I> where I: Iterator, I::Item: Clone, { fn new(mut it: I) -> Self { let inner = match it.next() { Some(next) => RepeatLastElementInner::Running { it, next }, None => RepeatLastElementInner::Empty, }; Self { inner: Some(inner) } } } impl<I> Iterator for RepeatLastElement<I> where I: Iterator, I::Item: Clone, { type Item = I::Item; fn next(&mut self) -> Option<Self::Item> { match self.inner.take().expect("should be set") { RepeatLastElementInner::Running { mut it, next } => { match it.next() { Some(next2) => { self.inner = Some(RepeatLastElementInner::Running { it, next: next2 }); } None => { self.inner = Some(RepeatLastElementInner::Repeating { element: next.clone(), }); } } Some(next) } RepeatLastElementInner::Repeating { element } => { let element_cloned = element.clone(); self.inner = Some(RepeatLastElementInner::Repeating { element }); Some(element_cloned) } RepeatLastElementInner::Empty => { self.inner = Some(RepeatLastElementInner::Empty); None } } } } /// Validates that the packed strings array is valid fn validate_packed_string(column: &str, strings: &PackedStrings) -> Result<()> { let mut last_offset = match strings.offsets.first() { Some(first) => *first as usize, None => return Ok(()), }; for (index, offset) in strings.offsets.iter().enumerate().skip(1) { let offset = *offset as usize; if offset < last_offset || !strings.values.is_char_boundary(offset) { return InvalidOffsetSnafu { column, offset, index, } .fail(); } last_offset = offset; } Ok(()) } /// Indexes a [`PackedStrings`] /// /// # Panic /// /// - if the index is beyond the bounds /// - if the index is not at a UTF-8 character boundary fn packed_string_idx(strings: &PackedStrings, idx: usize) -> &str { let start_offset = strings.offsets[idx] as usize; let end_offset = strings.offsets[idx + 1] as usize; &strings.values[start_offset..end_offset] } /// Returns an iterator over the strings in a [`PackedStrings`] /// /// # Panic /// /// If the offsets array is not an increasing sequence of numbers less than /// the length of the strings array fn packed_strings_iter(strings: &PackedStrings) -> impl Iterator<Item = &str> + '_ { let mut last_offset = strings.offsets.first().cloned().unwrap_or_default() as usize; strings.offsets.iter().skip(1).map(move |next_offset| { let next_offset = *next_offset as usize; let string = &strings.values[last_offset..next_offset]; last_offset = next_offset; string }) } /// Converts a potentially truncated null mask to a valid mask fn compute_valid_mask(null_mask: &[u8], to_insert: usize) -> Option<Vec<u8>> { if null_mask.is_empty() || null_mask.iter().all(|x| *x == 0) { return None; } // The expected length of the validity mask let expected_len = (to_insert + 7) >> 3; // The number of bits over the byte boundary let overrun = to_insert & 7; let mut mask: Vec<_> = (0..expected_len) .map(|x| match null_mask.get(x) { Some(v) => !*v, None => 0xFF, }) .collect(); if overrun != 0 { *mask.last_mut().unwrap() &= (1 << overrun) - 1; } Some(mask) } fn pb_column_type(col: &PbColumn) -> Result<InfluxColumnType> { let values = col.values.as_ref().context(EmptyColumnSnafu { column: &col.column_name, })?; let value_type = pb_value_type(&col.column_name, values)?; let semantic_type = SemanticType::from_i32(col.semantic_type); match (semantic_type, value_type) { (Some(SemanticType::Tag), InfluxFieldType::String) => Ok(InfluxColumnType::Tag), (Some(SemanticType::Field), field) => Ok(InfluxColumnType::Field(field)), (Some(SemanticType::Time), InfluxFieldType::Integer) if col.column_name.as_str() == TIME_COLUMN_NAME => { Ok(InfluxColumnType::Timestamp) } _ => InvalidTypeSnafu { column: &col.column_name, } .fail(), } } fn pb_value_type(column: &str, values: &PbValues) -> Result<InfluxFieldType> { let mut ret = None; let mut set_type = |field: InfluxFieldType| -> Result<()> { match ret { Some(_) => MultipleValuesSnafu { column }.fail(), None => { ret = Some(field); Ok(()) } } }; if !values.string_values.is_empty() { set_type(InfluxFieldType::String)?; } if values.packed_string_values.is_some() { set_type(InfluxFieldType::String)?; } if values.interned_string_values.is_some() { set_type(InfluxFieldType::String)?; } if !values.i64_values.is_empty() { set_type(InfluxFieldType::Integer)?; } if !values.u64_values.is_empty() { set_type(InfluxFieldType::UInteger)?; } if !values.f64_values.is_empty() { set_type(InfluxFieldType::Float)?; } if !values.bool_values.is_empty() { set_type(InfluxFieldType::Boolean)?; } ret.context(EmptyColumnSnafu { column }) } #[cfg(test)] mod tests { use arrow_util::assert_batches_eq; use generated_types::influxdata::pbdata::v1::InternedStrings; use schema::Projection; use super::*; fn column(name: &str, semantic_type: SemanticType) -> PbColumn { PbColumn { column_name: name.to_string(), semantic_type: semantic_type as _, values: None, null_mask: vec![], } } fn empty_values() -> PbValues { PbValues { i64_values: vec![], f64_values: vec![], u64_values: vec![], string_values: vec![], bool_values: vec![], bytes_values: vec![], packed_string_values: None, interned_string_values: None, } } fn with_strings(mut column: PbColumn, values: Vec<&str>, nulls: Vec<u8>) -> PbColumn { let mut v = empty_values(); v.string_values = values.iter().map(ToString::to_string).collect(); column.null_mask = nulls; column.values = Some(v); column } fn with_packed_strings( mut column: PbColumn, values: PackedStrings, nulls: Vec<u8>, ) -> PbColumn { let mut v = empty_values(); v.packed_string_values = Some(values); column.null_mask = nulls; column.values = Some(v); column } fn with_interned_strings( mut column: PbColumn, values: InternedStrings, nulls: Vec<u8>, ) -> PbColumn { let mut v = empty_values(); v.interned_string_values = Some(values); column.null_mask = nulls; column.values = Some(v); column } fn with_i64(mut column: PbColumn, values: Vec<i64>, nulls: Vec<u8>) -> PbColumn { let mut v = empty_values(); v.i64_values = values; column.null_mask = nulls; column.values = Some(v); column } fn with_u64(mut column: PbColumn, values: Vec<u64>, nulls: Vec<u8>) -> PbColumn { let mut v = empty_values(); v.u64_values = values; column.null_mask = nulls; column.values = Some(v); column } fn with_f64(mut column: PbColumn, values: Vec<f64>, nulls: Vec<u8>) -> PbColumn { let mut v = empty_values(); v.f64_values = values; column.null_mask = nulls; column.values = Some(v); column } fn with_bool(mut column: PbColumn, values: Vec<bool>, nulls: Vec<u8>) -> PbColumn { let mut v = empty_values(); v.bool_values = values; column.null_mask = nulls; column.values = Some(v); column } #[test] fn test_packed_strings_iter() { let s = PackedStrings { values: "".to_string(), offsets: vec![], }; assert_eq!(packed_strings_iter(&s).count(), 0); let s = PackedStrings { values: "".to_string(), offsets: vec![0], }; assert_eq!(packed_strings_iter(&s).count(), 0); let s = PackedStrings { values: "fooboo".to_string(), offsets: vec![0, 3, 6], }; let r: Vec<_> = packed_strings_iter(&s).collect(); assert_eq!(r, vec!["foo", "boo"]); } #[test] fn test_column_type() { let mut column = column("test", SemanticType::Time); let e = pb_column_type(&column).unwrap_err().to_string(); assert_eq!(e, "column with no values: test"); let mut values = empty_values(); values.i64_values = vec![2]; values.f64_values = vec![32.]; column.values = Some(values); let e = pb_column_type(&column).unwrap_err().to_string(); assert_eq!(e, "column \"test\" contains more than one type of values"); let mut values = empty_values(); values.string_values = vec!["hello".to_string()]; values.packed_string_values = Some(PackedStrings { values: "".to_string(), offsets: vec![], }); column.values = Some(values); let e = pb_column_type(&column).unwrap_err().to_string(); assert_eq!(e, "column \"test\" contains more than one type of values"); let mut values = empty_values(); values.string_values = vec!["hello".to_string()]; values.interned_string_values = Some(InternedStrings { dictionary: None, values: vec![], }); column.values = Some(values); let e = pb_column_type(&column).unwrap_err().to_string(); assert_eq!(e, "column \"test\" contains more than one type of values"); } #[test] fn test_basic() { let mut table_batch = TableBatch { columns: vec![ with_strings( column("tag1", SemanticType::Tag), vec!["v1", "v1", "v2", "v2", "v1"], vec![], ), with_strings( column("tag2", SemanticType::Tag), vec!["v2", "v3"], vec![0b00010101], ), with_f64( column("f64", SemanticType::Field), vec![3., 5.], vec![0b00001101], ), with_i64( column("i64", SemanticType::Field), vec![56, 2], vec![0b00001110], ), with_i64( column("time", SemanticType::Time), vec![1, 2, 3, 4, 5], vec![0b00000000], ), with_u64( column("u64", SemanticType::Field), vec![4, 3, 2, 1], vec![0b00000100], ), ], row_count: 5, table_id: 42, }; let mut batch = MutableBatch::new(); write_table_batch(&mut batch, &table_batch).unwrap(); let expected = &[ "+-----+-----+------+------+--------------------------------+-----+", "| f64 | i64 | tag1 | tag2 | time | u64 |", "+-----+-----+------+------+--------------------------------+-----+", "| | 56 | v1 | | 1970-01-01T00:00:00.000000001Z | 4 |", "| 3.0 | | v1 | v2 | 1970-01-01T00:00:00.000000002Z | 3 |", "| | | v2 | | 1970-01-01T00:00:00.000000003Z | |", "| | | v2 | v3 | 1970-01-01T00:00:00.000000004Z | 2 |", "| 5.0 | 2 | v1 | | 1970-01-01T00:00:00.000000005Z | 1 |", "+-----+-----+------+------+--------------------------------+-----+", ]; assert_batches_eq!(expected, &[batch.to_arrow(Projection::All).unwrap()]); table_batch.columns.push(table_batch.columns[0].clone()); let err = write_table_batch(&mut batch, &table_batch) .unwrap_err() .to_string(); assert_eq!(err, "duplicate column name: tag1"); table_batch.columns.pop(); // Missing time column -> error let mut time = table_batch.columns.remove(4); assert_eq!(time.column_name.as_str(), "time"); let err = write_table_batch(&mut batch, &table_batch) .unwrap_err() .to_string(); assert_eq!(err, "table batch must contain time column"); assert_batches_eq!(expected, &[batch.to_arrow(Projection::All).unwrap()]); // Nulls in time column -> error time.null_mask = vec![1]; table_batch.columns.push(time); let err = write_table_batch(&mut batch, &table_batch) .unwrap_err() .to_string(); assert_eq!(err, "time column must not contain nulls"); assert_batches_eq!(expected, &[batch.to_arrow(Projection::All).unwrap()]); // Missing values -> error table_batch.columns[0].values.take().unwrap(); let err = write_table_batch(&mut batch, &table_batch) .unwrap_err() .to_string(); assert_eq!(err, "column with no values: tag1"); assert_batches_eq!(expected, &[batch.to_arrow(Projection::All).unwrap()]); // No data -> error table_batch.columns[0].values = Some(PbValues { i64_values: vec![], f64_values: vec![], u64_values: vec![], string_values: vec![], bool_values: vec![], bytes_values: vec![], packed_string_values: None, interned_string_values: None, }); let err = write_table_batch(&mut batch, &table_batch) .unwrap_err() .to_string(); assert_eq!(err, "column with no values: tag1"); assert_batches_eq!(expected, &[batch.to_arrow(Projection::All).unwrap()]); } #[test] fn test_strings() { let table_batch = TableBatch { columns: vec![ with_packed_strings( column("tag1", SemanticType::Tag), PackedStrings { values: "helloinfluxdata".to_string(), offsets: vec![0, 5, 11, 11, 15], }, vec![0b000010010], ), with_packed_strings( column("tag2", SemanticType::Tag), PackedStrings { values: "helloworld".to_string(), offsets: vec![0, 5, 10], }, vec![0b000111010], ), with_packed_strings( column("s1", SemanticType::Field), PackedStrings { values: "cupcakesareawesome".to_string(), offsets: vec![0, 8, 11, 18], }, vec![0b000110010], ), with_interned_strings( column("tag3", SemanticType::Tag), InternedStrings { dictionary: Some(PackedStrings { values: "tag1tag2".to_string(), offsets: vec![0, 4, 8, 8], }), values: vec![0, 1, 1, 0, 2, 1], }, vec![0b000000000], ), with_interned_strings( column("s2", SemanticType::Field), InternedStrings { dictionary: Some(PackedStrings { values: "v1v2v3".to_string(), offsets: vec![0, 2, 4, 6], }), values: vec![0, 1, 2], }, vec![0b000011010], ), with_i64( column("time", SemanticType::Time), vec![1, 2, 3, 4, 5, 6], vec![], ), ], row_count: 6, table_id: 42, }; let mut batch = MutableBatch::new(); write_table_batch(&mut batch, &table_batch).unwrap(); let expected = &[ "+----------+----+--------+-------+------+--------------------------------+", "| s1 | s2 | tag1 | tag2 | tag3 | time |", "+----------+----+--------+-------+------+--------------------------------+", "| cupcakes | v1 | hello | hello | tag1 | 1970-01-01T00:00:00.000000001Z |", "| | | | | tag2 | 1970-01-01T00:00:00.000000002Z |", "| are | v2 | influx | world | tag2 | 1970-01-01T00:00:00.000000003Z |", "| awesome | | | | tag1 | 1970-01-01T00:00:00.000000004Z |", "| | | | | | 1970-01-01T00:00:00.000000005Z |", "| | v3 | data | | tag2 | 1970-01-01T00:00:00.000000006Z |", "+----------+----+--------+-------+------+--------------------------------+", ]; assert_batches_eq!(expected, &[batch.to_arrow(Projection::All).unwrap()]); // Try to write 6 rows expecting an error let mut try_write = |other: PbColumn, expected_err: &str| { let table_batch = TableBatch { columns: vec![ with_i64( column("time", SemanticType::Time), vec![1, 2, 3, 4, 5, 6], vec![], ), other, ], row_count: 6, table_id: 42, }; let err = write_table_batch(&mut batch, &table_batch) .unwrap_err() .to_string(); assert_eq!(err, expected_err); assert_batches_eq!(expected, &[batch.to_arrow(Projection::All).unwrap()]); }; try_write( with_packed_strings( column("s1", SemanticType::Tag), PackedStrings { values: "helloworld".to_string(), offsets: vec![0, 5, 11], }, vec![0b000111010], ), "column \"s1\" contains invalid offset 11 at index 2", ); try_write( with_packed_strings( column("s1", SemanticType::Field), PackedStrings { values: "helloworld".to_string(), offsets: vec![0, 5, 4], }, vec![0b000111010], ), "column \"s1\" contains invalid offset 4 at index 2", ); try_write( with_packed_strings( column("tag2", SemanticType::Field), PackedStrings { values: "helloworld".to_string(), offsets: vec![0, 5, 10], }, vec![0b000111010], ), "error writing column tag2: Unable to insert iox::column_type::field::string type into column tag2 with type iox::column_type::tag", ); try_write( with_packed_strings( column("tag2", SemanticType::Tag), PackedStrings { values: "hello😀world".to_string(), offsets: vec![0, 6, 10], }, vec![0b000111010], ), "column \"tag2\" contains invalid offset 6 at index 1", ); try_write( with_interned_strings( column("tag3", SemanticType::Tag), InternedStrings { dictionary: Some(PackedStrings { values: "tag1tag2".to_string(), offsets: vec![0, 4, 8, 8], }), values: vec![0, 1, 3, 0, 2, 1], }, vec![0b000000000], ), "error writing column tag3: Key not found in dictionary: 3", ); try_write( with_interned_strings( column("tag3", SemanticType::Tag), InternedStrings { dictionary: Some(PackedStrings { values: "tag1tag2".to_string(), offsets: vec![0, 4, 3, 8], }), values: vec![0, 1, 1, 0, 2, 1], }, vec![0b000000000], ), "column \"tag3\" contains invalid offset 3 at index 2", ); } #[test] fn test_optimization_trim_null_masks() { // See https://github.com/influxdata/influxdb-pb-data-protocol#optimization-1-trim-null-masks let table_batch = TableBatch { columns: vec![ with_i64( column("i64", SemanticType::Field), vec![1, 2, 3, 4, 5, 6, 7], vec![0b11000001], ), with_i64( column("time", SemanticType::Time), vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10], vec![0b00000000], ), ], row_count: 10, table_id: 42, }; let mut batch = MutableBatch::new(); write_table_batch(&mut batch, &table_batch).unwrap(); let expected = &[ "+-----+--------------------------------+", "| i64 | time |", "+-----+--------------------------------+", "| | 1970-01-01T00:00:00.000000001Z |", "| 1 | 1970-01-01T00:00:00.000000002Z |", "| 2 | 1970-01-01T00:00:00.000000003Z |", "| 3 | 1970-01-01T00:00:00.000000004Z |", "| 4 | 1970-01-01T00:00:00.000000005Z |", "| 5 | 1970-01-01T00:00:00.000000006Z |", "| | 1970-01-01T00:00:00.000000007Z |", "| | 1970-01-01T00:00:00.000000008Z |", "| 6 | 1970-01-01T00:00:00.000000009Z |", "| 7 | 1970-01-01T00:00:00.000000010Z |", "+-----+--------------------------------+", ]; assert_batches_eq!(expected, &[batch.to_arrow(Projection::All).unwrap()]); } #[test] fn test_optimization_omit_null_masks() { // See https://github.com/influxdata/influxdb-pb-data-protocol#optimization-1b-omit-empty-null-masks let table_batch = TableBatch { columns: vec![with_i64( column("time", SemanticType::Time), vec![1, 2, 3, 4, 5, 6, 7, 8, 9], vec![], )], row_count: 9, table_id: 42, }; let mut batch = MutableBatch::new(); write_table_batch(&mut batch, &table_batch).unwrap(); let expected = &[ "+--------------------------------+", "| time |", "+--------------------------------+", "| 1970-01-01T00:00:00.000000001Z |", "| 1970-01-01T00:00:00.000000002Z |", "| 1970-01-01T00:00:00.000000003Z |", "| 1970-01-01T00:00:00.000000004Z |", "| 1970-01-01T00:00:00.000000005Z |", "| 1970-01-01T00:00:00.000000006Z |", "| 1970-01-01T00:00:00.000000007Z |", "| 1970-01-01T00:00:00.000000008Z |", "| 1970-01-01T00:00:00.000000009Z |", "+--------------------------------+", ]; assert_batches_eq!(expected, &[batch.to_arrow(Projection::All).unwrap()]); } #[test] fn test_optimization_trim_repeated_tail_values() { // See https://github.com/influxdata/influxdb-pb-data-protocol#optimization-2-trim-repeated-tail-values let table_batch = TableBatch { columns: vec![ with_strings( column("f_s", SemanticType::Field), vec!["s1", "s2", "s3"], vec![0b11000001], ), with_interned_strings( column("f_i", SemanticType::Field), InternedStrings { dictionary: Some(PackedStrings { values: "s1s2".to_string(), offsets: vec![0, 2, 4], }), values: vec![0, 1, 0], }, vec![0b11000001], ), with_packed_strings( column("f_p", SemanticType::Field), PackedStrings { values: "s1s2s3".to_string(), offsets: vec![0, 2, 4, 6], }, vec![0b11000001], ), with_strings( column("t_s", SemanticType::Tag), vec!["s1", "s2", "s3"], vec![0b11000001], ), with_interned_strings( column("t_i", SemanticType::Tag), InternedStrings { dictionary: Some(PackedStrings { values: "s1s2".to_string(), offsets: vec![0, 2, 4], }), values: vec![0, 1, 0], }, vec![0b11000001], ), with_packed_strings( column("t_p", SemanticType::Tag), PackedStrings { values: "s1s2s3".to_string(), offsets: vec![0, 2, 4, 6], }, vec![0b11000001], ), with_bool( column("bool", SemanticType::Field), vec![false, false, true], vec![0b11000001], ), with_f64( column("f64", SemanticType::Field), vec![1.1, 2.2, 3.3], vec![0b11000001], ), with_i64( column("i64", SemanticType::Field), vec![1, 2, 3], vec![0b11000001], ), with_u64( column("u64", SemanticType::Field), vec![1, 2, 3], vec![0b11000001], ), with_i64(column("time", SemanticType::Time), vec![1, 2, 3], vec![]), ], row_count: 9, table_id: 42, }; let mut batch = MutableBatch::new(); write_table_batch(&mut batch, &table_batch).unwrap(); let expected = &[ "+-------+-----+-----+-----+-----+-----+-----+-----+-----+--------------------------------+-----+", "| bool | f64 | f_i | f_p | f_s | i64 | t_i | t_p | t_s | time | u64 |", "+-------+-----+-----+-----+-----+-----+-----+-----+-----+--------------------------------+-----+", "| | | | | | | | | | 1970-01-01T00:00:00.000000001Z | |", "| false | 1.1 | s1 | s1 | s1 | 1 | s1 | s1 | s1 | 1970-01-01T00:00:00.000000002Z | 1 |", "| false | 2.2 | s2 | s2 | s2 | 2 | s2 | s2 | s2 | 1970-01-01T00:00:00.000000003Z | 2 |", "| true | 3.3 | s1 | s3 | s3 | 3 | s1 | s3 | s3 | 1970-01-01T00:00:00.000000003Z | 3 |", "| true | 3.3 | s1 | s3 | s3 | 3 | s1 | s3 | s3 | 1970-01-01T00:00:00.000000003Z | 3 |", "| true | 3.3 | s1 | s3 | s3 | 3 | s1 | s3 | s3 | 1970-01-01T00:00:00.000000003Z | 3 |", "| | | | | | | | | | 1970-01-01T00:00:00.000000003Z | |", "| | | | | | | | | | 1970-01-01T00:00:00.000000003Z | |", "| true | 3.3 | s1 | s3 | s3 | 3 | s1 | s3 | s3 | 1970-01-01T00:00:00.000000003Z | 3 |", "+-------+-----+-----+-----+-----+-----+-----+-----+-----+--------------------------------+-----+", ]; assert_batches_eq!(expected, &[batch.to_arrow(Projection::All).unwrap()]); // we need at least one value though let table_batch = TableBatch { columns: vec![with_i64(column("time", SemanticType::Time), vec![], vec![])], row_count: 9, table_id: 42, }; let mut batch = MutableBatch::new(); let err = write_table_batch(&mut batch, &table_batch) .unwrap_err() .to_string(); assert_eq!(err, "column with no values: time"); } }
use crate::points::Point2D; use std::collections::HashSet; use std::error::Error; use std::iter::FromIterator; use std::str::FromStr; const INPUT: &str = include_str!("../input/2019/day3.txt"); pub fn part1() -> i32 { let wires: Vec<Path> = parse_input(); let wire_one: &Vec<Point2D> = &wires[0].locations; let wire_two: &Vec<Point2D> = &wires[1].locations; let locations_one: HashSet<&Point2D> = HashSet::from_iter(wire_one.iter()); let locations_two: HashSet<&Point2D> = HashSet::from_iter(wire_two.iter()); let intersections: HashSet<&&Point2D> = locations_one.intersection(&locations_two).collect(); let closest: i32 = intersections .iter() .map(|i| i.manhattan_distance()) .min() .expect("No intersections found"); closest } pub fn part2() -> usize { let wires: Vec<Path> = parse_input(); let wire_one: &Vec<Point2D> = &wires[0].locations; let wire_two: &Vec<Point2D> = &wires[1].locations; let locations_one: HashSet<&Point2D> = HashSet::from_iter(wire_one.iter()); let locations_two: HashSet<&Point2D> = HashSet::from_iter(wire_two.iter()); let intersections: HashSet<&&Point2D> = locations_one.intersection(&locations_two).collect(); intersections .iter() .map(|i| { wire_one.iter().position(|x| x == **i).unwrap() + 1 + wire_two.iter().position(|x| x == **i).unwrap() + 1 }) .min() .expect("No intersections found") } fn parse_input() -> Vec<Path> { INPUT.trim().lines().map(|l| l.parse().unwrap()).collect() } struct Path { locations: Vec<Point2D>, } impl FromStr for Path { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { let moves: Vec<_> = s.split(',').map(|m| m.parse::<Move>().unwrap()).collect(); Ok(Path::new(&moves)) } } impl Path { fn new(moves: &[Move]) -> Path { let mut locations = Vec::new(); let mut current = Point2D::zero(); for m in moves { for _ in 0..m.steps { current += m.direction.delta(); locations.push(current); } } Path { locations } } } struct Move { direction: Direction, steps: u32, } impl FromStr for Move { type Err = Box<dyn Error>; fn from_str(s: &str) -> Result<Self, Self::Err> { let direction = s[0..1].parse()?; let steps = s[1..].parse()?; Ok(Move { direction, steps }) } } enum Direction { Up, Down, Left, Right, } impl Direction { pub fn delta(&self) -> Point2D { match *self { Direction::Up => Point2D::new(0, -1), Direction::Down => Point2D::new(0, 1), Direction::Left => Point2D::new(-1, 0), Direction::Right => Point2D::new(1, 0), } } } impl FromStr for Direction { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "U" => Ok(Direction::Up), "D" => Ok(Direction::Down), "L" => Ok(Direction::Left), "R" => Ok(Direction::Right), _ => Err(format!("Unable to parse direction {}", s)), } } } #[cfg(test)] mod tests { use super::*; #[test] fn day03_part1() { assert_eq!(part1(), 1285); } #[test] fn day03_part2() { assert_eq!(part2(), 14228); } }
use std::{thread, time::Duration}; #[no_mangle] pub extern "C" fn async_call(cb: extern fn(i32)) { println!("RUST: Doing some heavy work..."); thread::sleep(Duration::from_secs(2)); cb(1); } #[no_mangle] pub extern "C" fn async_call2() -> i32 { println!("RUST: Doing some heavy work..."); thread::sleep(Duration::from_secs(2)); 2 } #[cfg(test)] mod tests { use crate::async_call; extern "C" fn _cb_test(val: i32) { assert_eq!(1, val); } #[test] fn test_async_call() { async_call(_cb_test); } }
// Raspberry Pi2 pub const GPIO_BASE: u32 = 0x3F200000; // other // pub const GPIO_BASE: u32 = 0x20000000; // Raspberrp Pi+ or Raspberry Pi2 pub const LED_GPFSEL: isize = GPIO_GPFSEL4; pub const LED_GPFBIT: i32 = 21; pub const LED_GPSET: isize = GPIO_GPSET1; pub const LED_GPCLR: isize = GPIO_GPCLR1; pub const LED_GPIO_BIT: isize = 15; // other // pub const LED_GPFSEL: isize = GPIO_GPFSEL1; // pub const LED_GPFBIT: i32 = 18; // pub const LED_GPCLR: isize = GPIO_GPCLR0; // pub const LED_GPSET: isize = GPIO_GPSET0; // pub const LED_GPIO_BIT: i32 = 16; pub const GPIO_GPFSEL0: isize = 0; pub const GPIO_GPFSEL1: isize = 1; pub const GPIO_GPFSEL2: isize = 2; pub const GPIO_GPFSEL3: isize = 3; pub const GPIO_GPFSEL4: isize = 4; pub const GPIO_GPFSEL5: isize = 5; pub const GPIO_GPSET0: isize = 7; pub const GPIO_GPSET1: isize = 8; pub const GPIO_GPCLR0: isize = 10; pub const GPIO_GPCLR1: isize = 11; pub const GPIO_GPLEV0: isize = 13; pub const GPIO_GPLEV1: isize = 14; pub const GPIO_GPEDS0: isize = 16; pub const GPIO_GPEDS1: isize = 17; pub const GPIO_GPREN0: isize = 19; pub const GPIO_GPREN1: isize = 20; pub const GPIO_GPFEN0: isize = 22; pub const GPIO_GPFEN1: isize = 23; pub const GPIO_GPHEN0: isize = 25; pub const GPIO_GPHEN1: isize = 26; pub const GPIO_GPLEN0: isize = 28; pub const GPIO_GPLEN1: isize = 29; pub const GPIO_GPAREN0: isize = 31; pub const GPIO_GPAREN1: isize = 32; pub const GPIO_GPAFEN0: isize = 34; pub const GPIO_GPAFEN1: isize = 35; pub const GPIO_GPPUD: isize = 37; pub const GPIO_GPPUDCLK0: isize = 38; pub const GPIO_GPPUDCLK1: isize = 39;
use std::io; use std::io::Read; use std::io::Write; use byteorder::{WriteBytesExt,ReadBytesExt,BigEndian}; use utils::*; #[derive(Clone, Debug)] pub struct PlaySoundEffect{ pub x: f64, pub y: f64, pub sound: u32, pub volume: u8 } impl PlaySoundEffect{ pub fn send<W: Write>(self, out_stream: &mut W)->io::Result<()>{ send_as_i16(out_stream, self.x)?; send_as_i16(out_stream, self.y)?; out_stream.write_u32::<BigEndian>(self.sound)?; out_stream.write_u8(self.volume)?; Ok(()) } pub fn read<R: Read>(in_stream: &mut R)->io::Result<Self>{ let x=read_as_i16(in_stream)?; let y=read_as_i16(in_stream)?; let sound=in_stream.read_u32::<BigEndian>()?; let volume=in_stream.read_u8()?; Ok(PlaySoundEffect{ x: x, y: y, sound: sound, volume: volume }) } }
use std; use core::time::Time; use super::iter::*; use ::error::Error; pub type LogError = Error; pub type LogResult<T> = std::result::Result<T,LogError>; #[repr(C)] pub struct FileHeader { magic : u32, version : u8, msg_header_size : u8, file_header_size : u8, } impl FileHeader { pub fn msg_header_size(&self) -> u8 { self.msg_header_size } pub fn file_header_size(&self) -> u8 { self.file_header_size } } #[repr(C)] pub struct MessageHeader { time : Time, seqnum : u64, length : u32, checksum : u32, msg_type : u16 } impl MessageHeader { pub fn new(time: Time, seqnum: u64, length: u32, checksum : u32, msg_type: u16) -> MessageHeader { MessageHeader { time : time, seqnum : seqnum, length: length, checksum : checksum, msg_type : msg_type } } pub fn time(&self) -> Time { self.time.clone() } pub fn seqnum(&self) -> u64 { self.seqnum } pub fn length(&self) -> u32 { self.length } pub fn checksum(&self) -> u32 { self.checksum } pub fn msg_type(&self) -> u16 { self.msg_type } } pub struct LogFile { file : std::fs::File, seqnum : u64 } pub enum Permission { Read, ReadWrite } impl Permission { fn writeable(&self) -> bool { match self { &Permission::ReadWrite => true, _ => false } } } pub const MAGIC : u32 = 0xFEEDFACE; pub const VERSION : u8 = 1; use std::path::Path; impl LogFile { fn create(path : &Path, perm : Permission) -> std::io::Result<LogFile> { let mut file = try! { std::fs::OpenOptions::new() .write(perm.writeable()) .read(true) .create(true) .open(path) }; let msg_header_size = std::mem::size_of::<MessageHeader>() as u8; let file_header_size = std::mem::size_of::<FileHeader>() as u8; let hdr = FileHeader { magic : MAGIC , msg_header_size : msg_header_size , version : VERSION , file_header_size : file_header_size }; try!( Self::write_struct(&mut file, &hdr) ); Ok(LogFile{file: file, seqnum : 0}) } fn validate(file: &mut std::fs::File, path: &Path) -> LogResult<u64> { let mut parser = LogFileParser::new(file, path).unwrap(); let mut iter = parser.parse().unwrap(); let mut seqnum = 0; if iter.header().magic != MAGIC { return Err(LogError::from_str("invalid magic")) } if iter.header().version != VERSION { return Err(LogError::from_str("invalid version")) } for msg in &mut iter { match msg { Err(err) => return Err(err), Ok(_) => seqnum += 1 } } Ok(seqnum) } fn open(path : &Path, perm : Permission) -> std::io::Result<LogFile> { use std::io::{Error,ErrorKind}; let mut file = try!{ std::fs::OpenOptions::new() .write(perm.writeable()) .read(true) .open(path) }; match Self::validate(&mut file, path) { Ok(seqnum) => Ok(LogFile{file: file, seqnum : seqnum} ), Err(err) => Err(Error::new(ErrorKind::InvalidData, err)) } } pub fn new( path : &str, perm : Permission ) -> LogResult<LogFile> { use std::path::Path; let path = Path::new(path); let func = if path.exists() { Self::open } else { Self::create }; let file = func(path, perm); match file { Ok(file) => Ok(file), Err(err) => return Err(LogError::new(err.to_string())) } } pub fn write(&mut self, time: Time, msg_type: u16 , data: &[u8]) -> LogResult<u64> { use std::io::Write; let hdr = MessageHeader::new(time, self.seqnum , data.len() as u32, 0, msg_type); let result = Self::write_struct(&mut self.file, &hdr); if let Err(err) = result { return Err(LogError::new(err.to_string())); }; let result = self.file.write(data); match result { Err(err) => return Err(LogError::new(err.to_string())), _ => { self.seqnum += 1; Ok(self.seqnum - 1) } } } fn write_struct<T>(file: &mut std::fs::File, data: &T) -> std::io::Result<usize> { let ptr : *const u8 = data as *const T as *const u8; let data = unsafe { std::slice::from_raw_parts(ptr, std::mem::size_of::<T>()) }; use std::io::Write; file.write(data) } }
use std::borrow::Cow; use std::convert::AsRef; use std::fmt; use std::hash::{Hash, Hasher}; use std::iter; use std::str; use std::str::FromStr; extern crate blake2; use blake2::{Blake2b, VarBlake2b}; extern crate digest; use digest::{Input, VariableOutput}; extern crate byteorder; use byteorder::{BigEndian, ByteOrder, LittleEndian}; extern crate num_bigint; use num_bigint::BigInt; extern crate num_traits; use num_traits::cast::ToPrimitive; extern crate ed25519_dalek; use ed25519_dalek::PublicKey; pub use ed25519_dalek::Signature; extern crate hex; extern crate serde; use serde::de::Error as SerdeError; use serde::de::Visitor as serdeVisitor; use serde::Deserialize; #[macro_use] extern crate serde_derive; #[cfg(test)] extern crate serde_json; #[cfg(test)] mod tests; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Network { Test, Beta, Live, } #[macro_export] macro_rules! zero_v6_addr { () => { ::std::net::SocketAddrV6::new(::std::net::Ipv6Addr::from([0u8; 16]), 0, 0, 0) }; } fn write_hex(f: &mut fmt::Formatter, bytes: &[u8]) -> fmt::Result { for b in bytes.iter() { write!(f, "{:02X}", b)?; } Ok(()) } struct InternalHexVisitor { byte_len: usize, } impl InternalHexVisitor { fn new(byte_len: usize) -> Self { InternalHexVisitor { byte_len } } } impl<'de> serde::de::Visitor<'de> for InternalHexVisitor { type Value = Vec<u8>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!( formatter, "a hex string representing {} bytes", self.byte_len ) } fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Vec<u8>, E> { if v.len() > self.byte_len * 2 { return Err(E::invalid_length(v.len(), &self)); } let mut hex_string = Cow::Borrowed(v); if v.len() < self.byte_len * 2 { let mut new_string = String::with_capacity(self.byte_len * 2); for _ in 0..(self.byte_len * 2 - v.len()) { new_string.push('0'); } new_string.extend(v.chars()); hex_string = Cow::Owned(new_string); } let bytes = hex::decode((&hex_string).as_bytes()) .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(&v), &self))?; assert_eq!( bytes.len(), self.byte_len, "Hex decoding produced unexpected length" ); Ok(bytes) } } trait InternalFromHex: Sized { fn from_hex<'de, D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>; } impl InternalFromHex for Signature { fn from_hex<'de, D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { deserializer .deserialize_str(InternalHexVisitor::new(64)) .and_then(|bytes| { Signature::from_bytes(&bytes).map_err(|_| { D::Error::invalid_value( serde::de::Unexpected::Bytes(&bytes), &"a valid ed25519 signature", ) }) }) } } impl InternalFromHex for u64 { fn from_hex<'de, D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { deserializer .deserialize_str(InternalHexVisitor::new(8)) .map(|bytes| BigEndian::read_u64(&bytes)) } } impl InternalFromHex for u128 { fn from_hex<'de, D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { deserializer .deserialize_str(InternalHexVisitor::new(16)) .map(|bytes| BigEndian::read_u128(&bytes)) } } impl InternalFromHex for BlockHash { fn from_hex<'de, D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { deserializer .deserialize_str(InternalHexVisitor::new(32)) .map(|bytes| { let mut hash = BlockHash([0u8; 32]); hash.0.clone_from_slice(&bytes); hash }) } } trait InternalToHex { fn to_hex<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>; } impl InternalToHex for Signature { fn to_hex<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_str(&hex::encode_upper(&self.to_bytes() as &[u8])) } } impl InternalToHex for u64 { fn to_hex<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { let mut bytes = [0u8; 8]; BigEndian::write_u64(&mut bytes, *self); serializer.serialize_str(&hex::encode(&bytes)) } } impl InternalToHex for u128 { fn to_hex<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { let mut bytes = [0u8; 16]; BigEndian::write_u128(&mut bytes, *self); serializer.serialize_str(&hex::encode_upper(&bytes)) } } impl InternalToHex for BlockHash { fn to_hex<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_str(&hex::encode_upper(&self.0)) } } impl InternalToHex for [u8; 32] { fn to_hex<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_str(&hex::encode_upper(&self)) } } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct BlockHeader { #[serde(deserialize_with = "InternalFromHex::from_hex")] #[serde(serialize_with = "InternalToHex::to_hex")] pub signature: Signature, #[serde(deserialize_with = "InternalFromHex::from_hex")] #[serde(serialize_with = "InternalToHex::to_hex")] pub work: u64, } #[derive(Default, PartialEq, Eq, Clone)] pub struct BlockHash(pub [u8; 32]); impl fmt::Debug for BlockHash { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write_hex(f, &self.0) } } impl fmt::Display for BlockHash { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write_hex(f, &self.0) } } impl Hash for BlockHash { fn hash<H: Hasher>(&self, state: &mut H) { state.write(&self.0); } } pub const ACCOUNT_LOOKUP: &[u8] = b"13456789abcdefghijkmnopqrstuwxyz"; #[derive(Default, PartialEq, Eq, Clone)] pub struct Account(pub [u8; 32]); impl Account { pub fn as_pubkey(&self) -> PublicKey { PublicKey::from_bytes(&self.0).unwrap() } } impl fmt::Debug for Account { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self, f) } } impl fmt::Display for Account { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "nano_")?; let mut reverse_chars = Vec::<u8>::new(); let mut check_hash = VarBlake2b::new(5).unwrap(); check_hash.input(&self.0 as &[u8]); let mut ext_addr = self.0.to_vec(); check_hash.variable_result(|b| ext_addr.extend(b.iter().rev())); let mut ext_addr = BigInt::from_bytes_be(num_bigint::Sign::Plus, &ext_addr); for _ in 0..60 { let n: BigInt = (&ext_addr) % 32; // lower 5 bits reverse_chars.push(ACCOUNT_LOOKUP[n.to_usize().unwrap()]); ext_addr = ext_addr >> 5; } let s = reverse_chars .iter() .rev() .map(|&c| c as char) .collect::<String>(); write!(f, "{}", s) } } impl Into<PublicKey> for Account { fn into(self) -> PublicKey { self.as_pubkey() } } #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum AccountParseError { IncorrectLength, MissingPrefix, InvalidCharacter(char), InvalidChecksum, } impl fmt::Display for AccountParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { AccountParseError::IncorrectLength => write!(f, "incorrect length"), AccountParseError::MissingPrefix => write!(f, "missing prefix"), AccountParseError::InvalidCharacter(c) => write!(f, "invalid character: {:?}", c), AccountParseError::InvalidChecksum => write!(f, "invalid checksum"), } } } impl FromStr for Account { type Err = AccountParseError; fn from_str(s: &str) -> Result<Account, AccountParseError> { let mut s_chars = s.chars(); let mut ext_pubkey = BigInt::default(); if s.starts_with("xrb_") { (&mut s_chars).take(4).count(); } else if s.starts_with("nano_") { (&mut s_chars).take(5).count(); } else { return Err(AccountParseError::MissingPrefix); } let mut i = 0; for ch in s_chars { if i >= 60 { return Err(AccountParseError::IncorrectLength); } let lookup = ACCOUNT_LOOKUP.iter().position(|&c| (c as char) == ch); let byte = match lookup { Some(p) => p as u8, None => { return Err(AccountParseError::InvalidCharacter(ch)); } }; ext_pubkey = ext_pubkey << 5; ext_pubkey = ext_pubkey + byte; i += 1; } if i != 60 { return Err(AccountParseError::IncorrectLength); } let ext_pubkey = ext_pubkey.to_bytes_le().1; if ext_pubkey.len() > 37 { // First character is not a 1 or a 3, // which causes the pubkey to be too long. return Err(AccountParseError::IncorrectLength); } let ext_pubkey: Vec<u8> = iter::repeat(0) .take(37 - ext_pubkey.len()) .chain(ext_pubkey.into_iter().rev()) .collect(); let mut pubkey_bytes = [0u8; 32]; pubkey_bytes.clone_from_slice(&ext_pubkey[..32]); let mut checksum_given = [0u8; 5]; checksum_given.clone_from_slice(&ext_pubkey[32..]); let mut hasher = VarBlake2b::new(5).unwrap(); hasher.input(&pubkey_bytes as &[u8]); let mut matches = false; hasher.variable_result(|checksum_calc| { matches = checksum_given.iter().rev().eq(checksum_calc.into_iter()); }); if matches { Ok(Account(pubkey_bytes)) } else { Err(AccountParseError::InvalidChecksum) } } } impl Hash for Account { fn hash<H: Hasher>(&self, state: &mut H) { state.write(&self.0); } } fn serde_from_str<'de, T, D>(deserializer: D) -> Result<T, D::Error> where T: FromStr, T::Err: fmt::Display, D: serde::de::Deserializer<'de>, { let s = String::deserialize(deserializer)?; T::from_str(&s).map_err(serde::de::Error::custom) } fn serde_to_str<T: ToString, S: serde::ser::Serializer>( value: &T, serializer: S, ) -> Result<S::Ok, S::Error> { serializer.serialize_str(&value.to_string()) } fn deserialize_link<'de, D: serde::de::Deserializer<'de>>( deserializer: D, ) -> Result<[u8; 32], D::Error> { let s = String::deserialize(deserializer)?; if s.starts_with("xrb_") || s.starts_with("nano_") { Account::from_str(&s) .map_err(serde::de::Error::custom) .map(|a| a.0) } else { let visitor = InternalHexVisitor::new(32); let mut bytes = [0u8; 32]; bytes.clone_from_slice(&visitor.visit_str(&s)?); Ok(bytes) } } #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] #[serde(tag = "type")] #[serde(rename_all = "lowercase")] pub enum BlockInner { Send { #[serde(deserialize_with = "InternalFromHex::from_hex")] #[serde(serialize_with = "InternalToHex::to_hex")] previous: BlockHash, #[serde(deserialize_with = "serde_from_str")] #[serde(serialize_with = "serde_to_str")] destination: Account, /// The balance of the account *after* the send. #[serde(deserialize_with = "InternalFromHex::from_hex")] #[serde(serialize_with = "InternalToHex::to_hex")] balance: u128, }, Receive { #[serde(deserialize_with = "InternalFromHex::from_hex")] #[serde(serialize_with = "InternalToHex::to_hex")] previous: BlockHash, /// The block we're receiving. #[serde(deserialize_with = "InternalFromHex::from_hex")] #[serde(serialize_with = "InternalToHex::to_hex")] source: BlockHash, }, /// The first "receive" in an account chain. /// Creates the account, and sets the representative. Open { /// The block we're receiving. #[serde(deserialize_with = "InternalFromHex::from_hex")] #[serde(serialize_with = "InternalToHex::to_hex")] source: BlockHash, #[serde(deserialize_with = "serde_from_str")] #[serde(serialize_with = "serde_to_str")] representative: Account, #[serde(deserialize_with = "serde_from_str")] #[serde(serialize_with = "serde_to_str")] account: Account, }, /// Changes the representative for an account. Change { #[serde(deserialize_with = "InternalFromHex::from_hex")] #[serde(serialize_with = "InternalToHex::to_hex")] previous: BlockHash, #[serde(deserialize_with = "serde_from_str")] #[serde(serialize_with = "serde_to_str")] representative: Account, }, /// A universal transaction which contains the account state. State { #[serde(deserialize_with = "serde_from_str")] #[serde(serialize_with = "serde_to_str")] account: Account, #[serde(deserialize_with = "InternalFromHex::from_hex")] #[serde(serialize_with = "InternalToHex::to_hex")] previous: BlockHash, #[serde(deserialize_with = "serde_from_str")] #[serde(serialize_with = "serde_to_str")] representative: Account, #[serde(deserialize_with = "serde_from_str")] #[serde(serialize_with = "serde_to_str")] balance: u128, /// Link field contains source block_hash if receiving, destination account if sending #[serde(deserialize_with = "deserialize_link")] #[serde(serialize_with = "InternalToHex::to_hex")] link: [u8; 32], }, } impl Hash for BlockInner { fn hash<H: Hasher>(&self, state: &mut H) { match *self { BlockInner::Send { ref previous, ref destination, ref balance, } => { previous.hash(state); destination.hash(state); let mut buf = [0u8; 16]; BigEndian::write_u128(&mut buf, *balance); state.write(&buf); } BlockInner::Receive { ref previous, ref source, } => { previous.hash(state); source.hash(state); } BlockInner::Open { ref source, ref representative, ref account, } => { source.hash(state); representative.hash(state); account.hash(state); } BlockInner::Change { ref previous, ref representative, } => { previous.hash(state); representative.hash(state); } BlockInner::State { ref account, ref previous, ref representative, ref balance, ref link, } => { state.write(&[0u8; 31]); state.write(&[6u8]); // block type code account.hash(state); previous.hash(state); representative.hash(state); let mut buf = [0u8; 16]; BigEndian::write_u128(&mut buf, *balance); state.write(&buf); state.write(link); } } } } struct DigestHasher<'a, D: 'a>(&'a mut D); impl<'a, D: digest::Input + 'a> Hasher for DigestHasher<'a, D> { fn write(&mut self, input: &[u8]) { self.0.input(input); } fn finish(&self) -> u64 { unimplemented!() } } #[derive(Debug, PartialEq, Eq, Clone, Hash)] pub enum BlockRoot { Block(BlockHash), Account(Account), } impl AsRef<[u8; 32]> for BlockRoot { fn as_ref(&self) -> &[u8; 32] { match *self { BlockRoot::Block(BlockHash(ref bytes)) => bytes, BlockRoot::Account(Account(ref bytes)) => bytes, } } } impl Into<[u8; 32]> for BlockRoot { fn into(self) -> [u8; 32] { match self { BlockRoot::Block(BlockHash(bytes)) => bytes, BlockRoot::Account(Account(bytes)) => bytes, } } } #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum BlockType { Send, Receive, Open, Change, State, } #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum BlockTypeCodeError { Invalid, NotABlock, Unknown, } impl BlockType { pub fn name(self) -> &'static str { match self { BlockType::Send => "send", BlockType::Receive => "receive", BlockType::Open => "open", BlockType::Change => "change", BlockType::State => "state", } } pub fn size(self) -> usize { match self { BlockType::Send => 32 + 32 + 16, BlockType::Receive => 32 + 32, BlockType::Open => 32 + 32 + 32, BlockType::Change => 32 + 32, BlockType::State => 32 + 32 + 32 + 16 + 32, } } pub fn to_type_code(self) -> u8 { self.into() } pub fn from_type_code(code: u8) -> Result<BlockType, BlockTypeCodeError> { match code { 0 => Err(BlockTypeCodeError::Invalid), 1 => Err(BlockTypeCodeError::NotABlock), 2 => Ok(BlockType::Send), 3 => Ok(BlockType::Receive), 4 => Ok(BlockType::Open), 5 => Ok(BlockType::Change), 6 => Ok(BlockType::State), _ => Err(BlockTypeCodeError::Unknown), } } } impl Into<u8> for BlockType { fn into(self) -> u8 { match self { BlockType::Send => 2, BlockType::Receive => 3, BlockType::Open => 4, BlockType::Change => 5, BlockType::State => 6, } } } impl fmt::Display for BlockType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name()) } } impl BlockInner { pub fn get_hash(&self) -> BlockHash { let mut hasher = VarBlake2b::new(32).expect("Unsupported hash length"); self.hash(&mut DigestHasher(&mut hasher)); let mut output = BlockHash::default(); hasher.variable_result(|b| output.0.copy_from_slice(b)); output } pub fn previous(&self) -> Option<&BlockHash> { match *self { BlockInner::Send { ref previous, .. } => Some(previous), BlockInner::Receive { ref previous, .. } => Some(previous), BlockInner::Change { ref previous, .. } => Some(previous), BlockInner::Open { .. } => None, BlockInner::State { ref previous, .. } => { let is_zero = previous.0.iter().all(|&x| x == 0); if is_zero { None } else { Some(previous) } } } } pub fn root_bytes(&self) -> &[u8; 32] { match *self { BlockInner::Send { ref previous, .. } => &previous.0, BlockInner::Receive { ref previous, .. } => &previous.0, BlockInner::Change { ref previous, .. } => &previous.0, BlockInner::Open { ref account, .. } => &account.0, BlockInner::State { ref account, .. } => { self.previous().map(|h| &h.0).unwrap_or(&account.0) } } } pub fn into_root(self) -> BlockRoot { match self { BlockInner::Send { previous, .. } => BlockRoot::Block(previous), BlockInner::Receive { previous, .. } => BlockRoot::Block(previous), BlockInner::Change { previous, .. } => BlockRoot::Block(previous), BlockInner::Open { account, .. } => BlockRoot::Account(account), BlockInner::State { account, previous, .. } => { let prev_is_zero = previous.0.iter().all(|&x| x == 0); if prev_is_zero { BlockRoot::Account(account) } else { BlockRoot::Block(previous) } } } } pub fn ty(&self) -> BlockType { match *self { BlockInner::Send { .. } => BlockType::Send, BlockInner::Receive { .. } => BlockType::Receive, BlockInner::Change { .. } => BlockType::Change, BlockInner::Open { .. } => BlockType::Open, BlockInner::State { .. } => BlockType::State, } } pub fn size(&self) -> usize { self.ty().size() } } pub fn work_threshold(network: Network) -> u64 { match network { Network::Live | Network::Beta => 0xffffffc000000000, Network::Test => 0xff00000000000000, } } pub fn work_value(root: &[u8], work: u64) -> u64 { let mut hasher = VarBlake2b::new(8).expect("Unsupported hash length"); let mut buf = [0u8; 8]; LittleEndian::write_u64(&mut buf, work); hasher.input(&buf); hasher.input(root); let mut val = 0; hasher.variable_result(|b| val = LittleEndian::read_u64(b)); val } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Block { #[serde(flatten)] pub inner: BlockInner, #[serde(flatten)] pub header: BlockHeader, } impl Block { pub fn get_hash(&self) -> BlockHash { self.inner.get_hash() } pub fn previous(&self) -> Option<&BlockHash> { self.inner.previous() } pub fn root_bytes(&self) -> &[u8; 32] { self.inner.root_bytes() } pub fn into_root(self) -> BlockRoot { self.inner.into_root() } #[deprecated] /// Use global work_threshold function instead pub fn work_threshold(&self, network: Network) -> u64 { work_threshold(network) } pub fn work_value(&self) -> u64 { work_value(self.root_bytes() as _, self.header.work) } pub fn work_valid(&self, network: Network) -> bool { self.work_value() > work_threshold(network) } pub fn ty(&self) -> BlockType { self.inner.ty() } pub fn size(&self) -> usize { // inner + sig + work self.inner.size() + 64 + 8 } } impl Hash for Block { fn hash<H: Hasher>(&self, state: &mut H) { self.inner.hash(state); } } impl PartialEq for Block { fn eq(&self, other: &Self) -> bool { self.inner.eq(&other.inner) } } impl Eq for Block {} /// What the vote is for. /// Note: internally, the official node can have mixed types in a vote. /// However, over the wire, this isn't possible. #[derive(Debug, Clone, PartialEq)] pub enum VoteInner { Block(Block), Hashes(Vec<BlockHash>), } #[derive(Debug, Clone, PartialEq)] pub struct Vote { pub account: Account, pub signature: Signature, pub sequence: u64, pub inner: VoteInner, } const VOTE_HASH_PREFIX: &[u8] = b"vote "; impl Hash for Vote { fn hash<H: Hasher>(&self, state: &mut H) { match &self.inner { VoteInner::Block(block) => { state.write(&block.get_hash().0); } VoteInner::Hashes(hashes) => { state.write(&VOTE_HASH_PREFIX); for hash in hashes { state.write(&hash.0); } } } let mut seq_bytes = [0u8; 8]; LittleEndian::write_u64(&mut seq_bytes, self.sequence); state.write(&seq_bytes); } } impl Vote { pub fn get_hash(&self) -> [u8; 32] { let mut hasher = VarBlake2b::new(32).expect("Unsupported hash length"); self.hash(&mut DigestHasher(&mut hasher)); let mut output = [0u8; 32]; hasher.variable_result(|b| output.copy_from_slice(b)); output } pub fn verify(&self) -> bool { self.account .as_pubkey() .verify::<Blake2b>(&self.get_hash(), &self.signature) .is_ok() } }
use std::collections::VecDeque; use input_i_scanner::InputIScanner; use join::Join; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t }; (($($t: ty),+); $n: expr) => { std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>() }; ($t: ty; $n: expr) => { std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>() }; } let n = scan!(usize); let s = scan!(String); let s: Vec<char> = s.chars().collect(); let mut a = VecDeque::new(); a.push_back(n); for i in (0..n).rev() { if s[i] == 'L' { a.push_back(i); } else { a.push_front(i); } } let ans = a.iter().join(" "); println!("{}", ans); }
use crate::{MetricKind, MetricObserver, Observation}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; /// A monotonic counter #[derive(Debug, Clone, Default)] pub struct U64Counter { state: Arc<AtomicU64>, } impl U64Counter { pub fn inc(&self, count: u64) { self.state.fetch_add(count, Ordering::Relaxed); } pub fn fetch(&self) -> u64 { self.state.load(Ordering::Relaxed) } } impl MetricObserver for U64Counter { type Recorder = Self; fn kind() -> MetricKind { MetricKind::U64Counter } fn recorder(&self) -> Self::Recorder { self.clone() } fn observe(&self) -> Observation { Observation::U64Counter(self.fetch()) } } /// A concise helper to assert the value of a metric counter, regardless of underlying type. #[macro_export] macro_rules! assert_counter { ( $metrics:ident, $counter:ty, $name:expr, $(labels = $attr:expr,)* $(value = $value:expr,)* ) => { // Default to an empty set of attributes if not specified. #[allow(unused)] let mut attr = None; $(attr = Some($attr);)* let attr = attr.unwrap_or_else(|| metric::Attributes::from(&[])); let counter = $metrics .get_instrument::<metric::Metric<$counter>>($name) .expect("failed to find metric with provided name") .get_observer(&attr) .expect("failed to find metric with provided attributes") .fetch(); $(assert_eq!(counter, $value, "counter value mismatch");)* }; } #[cfg(test)] mod tests { use super::*; #[test] fn test_counter() { let counter = U64Counter::default(); assert_eq!(counter.fetch(), 0); counter.inc(12); assert_eq!(counter.fetch(), 12); counter.inc(34); assert_eq!(counter.fetch(), 46); assert_eq!(counter.observe(), Observation::U64Counter(46)); // Expect counter to wrap around counter.inc(u64::MAX); assert_eq!(counter.observe(), Observation::U64Counter(45)); } }
use std::convert::Infallible; use crate::env::Environment; use axum::{ body::{Bytes, Full}, extract::Extension, handler::{get, post}, response::{self, IntoResponse}, routing::BoxRoute, AddExtensionLayer, Router, }; use http::{Response, StatusCode}; use serde::Serialize; use serde_json::json; use thiserror::Error; use uuid::Uuid; mod ansible; pub mod drives; pub mod hosts; pub mod kernels; mod models; pub mod rpc; pub mod storage; pub mod vms; pub async fn initialize_env(env: Environment) { tracing::info!("Initializing hosts..."); match hosts::initalize_hosts(env).await { Ok(_) => (), Err(e) => { tracing::error!("Failed to initialize hosts: {}", e); } } tracing::info!("Finished initializing hosts"); } pub async fn app(env: Environment) -> Router<BoxRoute> { initialize_env(env.clone()).await; Router::new() .route("/", get(|| async { "hello" })) .nest("/hosts", hosts()) .nest("/storage", storage()) .nest("/drives", drives()) .nest("/kernels", kernels()) .nest("/vms", vms()) .layer(AddExtensionLayer::new(env.clone())) .layer(tower_http::trace::TraceLayer::new_for_http()) .boxed() } pub fn hosts() -> Router<BoxRoute> { Router::new() .route("/:id", get(hosts::get)) .route("/:id/install", post(hosts::install)) .route("/:id/healthcheck", post(hosts::health_check)) .route("/", get(hosts::list).post(hosts::add)) .boxed() } pub fn storage() -> Router<BoxRoute> { Router::new() .route("/:id", get(storage::get)) .route("/", get(storage::list).post(storage::add)) .boxed() } pub fn drives() -> Router<BoxRoute> { Router::new() .route("/:id", get(drives::get)) .route("/", get(drives::list).post(drives::add)) .boxed() } pub fn kernels() -> Router<BoxRoute> { Router::new() .route("/:id", get(kernels::get)) .route("/", get(kernels::list).post(kernels::add)) .boxed() } pub fn vms() -> Router<BoxRoute> { Router::new() .route("/:id", get(vms::get)) .route("/", get(vms::list).post(vms::add)) .route("/:id/start", post(vms::start)) .boxed() } pub struct ApiResponse<T> { data: T, code: StatusCode, } impl<T> IntoResponse for ApiResponse<T> where T: Send + Sync + Serialize, { type Body = Full<Bytes>; type BodyError = Infallible; fn into_response(self) -> Response<Self::Body> { let mut response = response::Json(json!({ "response": self.data, })) .into_response(); *response.status_mut() = self.code; response } } #[derive(Error, Debug, Serialize)] pub enum ServerError { #[error("Internal error")] #[serde(rename(serialize = "internal error"))] Internal(String), #[error("Validation error")] #[serde(rename(serialize = "validation error"))] Validation(String), #[error("Entity not found")] #[serde(rename(serialize = "entity not found"))] EntityNotFound(String), } impl IntoResponse for ServerError { type Body = Full<Bytes>; type BodyError = Infallible; fn into_response(self) -> Response<Self::Body> { let code = match self { ServerError::Internal(ref s) => { tracing::error!("Internal error: {}", s); StatusCode::INTERNAL_SERVER_ERROR } ServerError::Validation(_) => StatusCode::CONFLICT, Self::EntityNotFound(_) => StatusCode::NOT_FOUND, }; let mut response = response::Json(json!({ "error": self, })) .into_response(); *response.status_mut() = code; response } }
use cogs_gamedev::{ ease::Interpolator, grids::{Direction4, Rotation}, }; use crate::{ assets::Assets, boilerplates::{FrameInfo, GamemodeDrawer, RenderTargetStack}, modes::playing::{ draw_space, simulating::{AdvanceMethod, STEP_TIME_ON_DEMAND}, }, simulator::{ floodfill::FloodFillError, transport::{Cable, CableKind}, }, utils::draw::{self, hexcolor}, HEIGHT, WIDTH, }; use super::ModeSimulating; impl GamemodeDrawer for ModeSimulating { fn draw(&self, assets: &Assets, frame_info: FrameInfo, render_targets: &mut RenderTargetStack) { use macroquad::prelude::*; draw_space(assets); self.board.draw(assets); gl_use_material(assets.shaders.cables); // Deal with crossovers later by putting all horizontals before verticals let mut crossovers = Vec::new(); let dt = frame_info.frames_ran - self.step_start; let step_time = match self.advance_method { AdvanceMethod::ByFrames { interval, .. } => interval, AdvanceMethod::OnDemand => STEP_TIME_ON_DEMAND, // whatever _ => 1, }; let tip_progress = (dt as f32 / step_time as f32).clamp(0.0, 1.0); for tip in self.flooder.tips.iter().flatten() { if let Some(cable) = self.board.cables.get(&tip.pos) { let col = tip.resource.color(); // On straight: progress left->right top->bottom // On bent: ccw->cw let (progress, kind) = match cable { Cable::Straight { kind, horizontal } => { if *horizontal == tip.facing.is_horizontal() { if matches!(tip.facing, Direction4::East | Direction4::South) { (tip_progress, *kind) } else { (-tip_progress, *kind) } } else { // make up a kind (0.0, CableKind::Wire) } } Cable::Bent { kind, ccw_dir } => { if tip.facing.flip() == *ccw_dir { (tip_progress, *kind) } else if tip.facing.flip() == ccw_dir.rotate(Rotation::Clockwise) { (-tip_progress, *kind) } else { (0.0, CableKind::Wire) } } Cable::Crossover { horiz_kind, vert_kind, } => { let kind = if tip.facing.is_horizontal() { *horiz_kind } else { *vert_kind }; let progress = if matches!(tip.facing, Direction4::East | Direction4::South) { tip_progress } else { -tip_progress }; crossovers.push((kind, tip.pos, tip.facing, &tip.resource, progress)); continue; } }; assets .shaders .cables .set_uniform("progress", [col.r, col.g, col.b, progress]); assets .shaders .cables .set_uniform("isPipe", if kind == CableKind::Pipe { 1i32 } else { 0 }); let (cx, cy) = self.board.coord_to_px(tip.pos); let ((sx, sy), _) = cable.get_slices(); draw_texture_ex( assets.textures.cable_atlas, cx, cy, WHITE, DrawTextureParams { source: Some(Rect::new(sx, sy + 32.0, 16.0, 16.0)), ..Default::default() }, ); } } for ((visited, horiz), resource) in self.flooder.visited.iter() { if let Some(cable) = self.board.cables.get(visited) { let (progress, kind) = match cable { Cable::Straight { kind, horizontal } => { if *horizontal == *horiz { (1.0, *kind) } else { // make up a kind (0.0, CableKind::Wire) } } Cable::Bent { kind, ccw_dir } => (1.0, *kind), Cable::Crossover { horiz_kind, vert_kind, } => { let kind = if *horiz { *horiz_kind } else { *vert_kind }; crossovers.push(( kind, *visited, if *horiz { Direction4::East } else { Direction4::North }, resource, 1.0, )); continue; } }; let col = resource.color(); assets .shaders .cables .set_uniform("progress", [col.r, col.g, col.b, progress]); assets .shaders .cables .set_uniform("isPipe", if kind == CableKind::Pipe { 1i32 } else { 0 }); let (cx, cy) = self.board.coord_to_px(*visited); let ((sx, sy), _) = cable.get_slices(); draw_texture_ex( assets.textures.cable_atlas, cx, cy, WHITE, DrawTextureParams { source: Some(Rect::new(sx, sy + 32.0, 16.0, 16.0)), ..Default::default() }, ); } } crossovers.sort_by_key(|(kind, pos, dir, res, progress)| { // sort vertical before horiz so it draws first dir.is_vertical() }); for (kind, pos, dir, res, progress) in crossovers { let col = res.color(); assets .shaders .cables .set_uniform("progress", [col.r, col.g, col.b, progress]); assets .shaders .cables .set_uniform("isPipe", if kind == CableKind::Pipe { 1i32 } else { 0 }); let (cx, cy) = self.board.coord_to_px(pos); let ((sx, sy), _) = Cable::Straight { horizontal: dir.is_horizontal(), kind, } .get_slices(); draw_texture_ex( assets.textures.cable_atlas, cx, cy, WHITE, DrawTextureParams { source: Some(Rect::new(sx, sy + 32.0, 16.0, 16.0)), ..Default::default() }, ); } gl_use_default_material(); if let AdvanceMethod::Errors(errs) = &self.advance_method { for error in errs { let pos = match error { FloodFillError::BadCableKind(pos) | FloodFillError::NoEntrance(pos) | FloodFillError::SpilledIntoSpace(pos) | FloodFillError::Backtrack(pos) | FloodFillError::BadOutput(pos, _) => *pos, }; let (cx, cy) = self.board.coord_to_px(pos); let cx = cx + 8.0; let cy = cy + 8.0; // draw arrow draw_texture_ex( assets.textures.error_atlas, cx, cy, WHITE, DrawTextureParams { source: Some(Rect::new(80.0, 0.0, 16.0, 16.0)), ..Default::default() }, ); let sx = match error { FloodFillError::BadCableKind(_) => 0.0, FloodFillError::NoEntrance(_) => 16.0, FloodFillError::SpilledIntoSpace(_) => 32.0, FloodFillError::Backtrack(_) => 48.0, FloodFillError::BadOutput(_, _) => 64.0, }; draw_texture_ex( assets.textures.error_atlas, cx + 4.0, cy + 4.0, WHITE, DrawTextureParams { source: Some(Rect::new(sx, 0.0, 16.0, 16.0)), ..Default::default() }, ); } } else if let AdvanceMethod::WinScreen { appear_progress, text, } = &self.advance_method { let patch_width = 7; let patch_height = 4; // Get the origin X/Y let ox = WIDTH / 2.0 - (16.0 * patch_width as f32) / 2.0; let oy = appear_progress.clamp(0.0, 1.0).quad_out( patch_height as f32 * -6.0, HEIGHT / 2.0 - (16.0 * patch_height as f32) / 2.0 - 48.0, ) + if *appear_progress >= 1.0 { // sin starts at 0 ((appear_progress - 1.0) * 0.5).sin() * 5.0 } else { 0.0 }; gl_use_material(assets.shaders.hologram); assets .shaders .hologram .set_uniform("time", frame_info.frames_ran as f32 / 30.0); draw::patch9( 16.0, ox, oy, patch_width, patch_height, assets.textures.hologram_9patch, ); draw_texture( assets.textures.you_win, WIDTH / 2.0 - assets.textures.you_win.width() / 2.0, oy + 9.0, WHITE, ); draw::pixel_text( text, ox + 6.0, oy + 18.0, None, draw::hexcolor(0xff5277_dd), assets, ); gl_use_default_material(); } let text_x = WIDTH / 2.0 - self.level_name.len() as f32 * 4.0 / 2.0; draw::pixel_text( &self.level_name, text_x, 12.0, None, hexcolor(0xff5277_ff), assets, ); } }
#[doc = "Reader of register UR12"] pub type R = crate::R<u32, super::UR12>; #[doc = "Reader of field `SECURE`"] pub type SECURE_R = crate::R<bool, bool>; impl R { #[doc = "Bit 16 - Secure mode"] #[inline(always)] pub fn secure(&self) -> SECURE_R { SECURE_R::new(((self.bits >> 16) & 0x01) != 0) } }
#![no_main] #![no_std] use stm32l4xx_hal as hal; use ws2812_spi as ws2812; #[macro_use] extern crate cortex_m_rt as rt; use crate::hal::delay::Delay; use crate::hal::prelude::*; use crate::hal::spi::Spi; use crate::hal::stm32; use crate::rt::entry; use crate::rt::ExceptionFrame; use crate::ws2812::Ws2812; use cortex_m::peripheral::Peripherals; use smart_leds::{brightness, SmartLedsWrite, RGB8}; extern crate cortex_m_semihosting as sh; extern crate panic_semihosting; const matrix_map: [i16; 21 * 19] = [ -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, -1, -1, -1, -1, -1, -1, 8, 9, 10, 11, 12, 13, 14, 15, 16, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, -1, -1, -1, -1, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, -1, -1, -1, -1, -1, -1, -1, -1, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, -1, -1, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, -1, -1, -1, -1, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, -1, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, -1, -1, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, -1, -1, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, -1, -1, -1, -1, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, -1, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, -1, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, -1, -1, -1, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, -1, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, -1, -1, -1, -1, -1, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, -1, -1, -1, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, -1, -1, -1, -1, -1, 275, 276, 277, 278, 279, 280, 281, 282, 283, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 283, 284, 285, 286, 287, 288, 289, 290, 291, -1, -1, -1, ]; #[entry] fn main() -> ! { if let (Some(p), Some(cp)) = (stm32::Peripherals::take(), Peripherals::take()) { // Constrain clocking registers let mut flash = p.FLASH.constrain(); let mut rcc = p.RCC.constrain(); let mut pwr = p.PWR.constrain(&mut rcc.apb1r1); let clocks = rcc // full speed (64 & 80MHz) use the 16MHZ HSI osc + PLL (but slower / intermediate values need MSI) .cfgr .sysclk(80.mhz()) .pclk1(80.mhz()) .pclk2(80.mhz()) .freeze(&mut flash.acr, &mut pwr); let mut gpioa = p.GPIOA.split(&mut rcc.ahb2); // Get delay provider let mut delay = Delay::new(cp.SYST, clocks); // Configure pins for SPI let (sck, miso, mosi) = cortex_m::interrupt::free(move |cs| { ( gpioa.pa5.into_af5(&mut gpioa.moder, &mut gpioa.afrl), gpioa.pa6.into_af5(&mut gpioa.moder, &mut gpioa.afrl), gpioa.pa7.into_af5(&mut gpioa.moder, &mut gpioa.afrl), ) }); // Configure SPI with 3Mhz rate let spi = Spi::spi1( p.SPI1, (sck, miso, mosi), ws2812::MODE, 3_000_000.hz(), clocks, &mut rcc.apb2, ); let mut ws = Ws2812::new(spi); const NUM_LEDS: usize = 154; let mut data = [RGB8::default(); NUM_LEDS]; enum Mode { Rainbow, WhiteInOut, Flash, Kitt, } for mode in [Mode::Rainbow, Mode::WhiteInOut, Mode::Flash, Mode::Kitt] .iter() .cycle() { match mode { Mode::Rainbow => { for _ in 0..1 { for j in 0..(256 * 5) { for i in 0..NUM_LEDS { data[i] = wheel( (((i * 256) as u16 / NUM_LEDS as u16 + j as u16) & 255) as u8, ); } ws.write(brightness(data.iter().cloned(), 32)).unwrap(); // ws.write(data.iter().cloned()).unwrap(); delay.delay_ms(5u8); } } } Mode::WhiteInOut => { for _ in 0..1 { for j in ((0..256).chain((0..256).rev())) { let data = [RGB8::new(j as u8, j as u8, j as u8); NUM_LEDS]; ws.write(brightness(data.iter().cloned(), 32)).unwrap(); // ws.write(data.iter().cloned()).unwrap(); //delay.delay_ms(5u8); } } } Mode::Flash => { for _ in 0..1 { let r = 0..NUM_LEDS; for j in r.clone().chain(r.rev()) { let col1 = RGB8::new(255, 200, 160); let col2 = RGB8::new(0, 0, 0); data.iter_mut().enumerate().for_each(|(i, v)| { if i == j { *v = col1 } else { *v = col2 } }); ws.write(brightness(data.iter().cloned(), 32)).unwrap(); // ws.write(data.iter().cloned()).unwrap(); if j == 0 || j == 255 { delay.delay_ms(255u8); // delay.delay_ms(255u8); } delay.delay_ms(16u8); } } } Mode::Kitt => { for _ in 0..2 { let up = 0..NUM_LEDS; let down = (0..NUM_LEDS).rev(); let pause = core::iter::repeat(8).take(8); let pause_short = core::iter::repeat(8).take(2); // let pause_short = core::iter::once(8); // let mut seq = down.chain(pause_short).chain(up).chain(pause).cycle(); let mut seq = up.chain(pause_short).chain(down).chain(pause); let mut prev = seq.next().unwrap(); let mut c = 0; const RAMPDOWN: u8 = 64; for cur in seq { data.iter_mut().for_each(|v| { if v.r < RAMPDOWN { v.r = 0; } else { v.r -= RAMPDOWN; } }); delay.delay_ms(8u8); if c == 1 { // let s = seq.next().unwrap(); // full brightness lags behind one frame (simulate turn on time of 80s lightbulbs) if prev < NUM_LEDS { data[prev] = RGB8::new(255, 0, 0); } if cur < NUM_LEDS { data[cur] = RGB8::new(128, 0, 0); } prev = cur; c = 0; } c += 1; // ws.write(data.iter().cloned()).unwrap(); ws.write(brightness(data.iter().cloned(), 32)).unwrap(); } } } } } } loop { continue; } } /// Input a value 0 to 255 to get a color value /// The colours are a transition r - g - b - back to r. fn wheel(mut wheel_pos: u8) -> RGB8 { wheel_pos = 255 - wheel_pos; if wheel_pos < 85 { return (255 - wheel_pos * 3, 0, wheel_pos * 3).into(); } if wheel_pos < 170 { wheel_pos -= 85; return (0, wheel_pos * 3, 255 - wheel_pos * 3).into(); } wheel_pos -= 170; (wheel_pos * 3, 255 - wheel_pos * 3, 0).into() } #[exception] fn HardFault(ef: &ExceptionFrame) -> ! { panic!("{:#?}", ef); }
use std::fs; use crate::image::Image; pub fn write(image: &Image, filename: &str) -> std::io::Result<()> { let mut s = format!("P3\n{} {}\n255\n",image.width(),image.height()); for p in &image.pixels { s.push_str(&format!("{} {} {}\n", (p.r()*255.99) as u8, (p.g()*255.99) as u8, (p.b() *255.99) as u8 ) ); }; fs::write(filename, s.as_bytes()) }
use core::{ fmt::Debug, ops::{Add, AddAssign, Div, DivAssign, Sub, SubAssign}, }; use serde::{Deserialize, Serialize}; #[derive(Default, Clone, Copy, Debug, Serialize, Deserialize)] pub struct Vec3f(pub f32, pub f32, pub f32); impl Vec3f { pub fn len2(&self) -> f32 { self.0 * self.0 + self.1 * self.1 + self.2 * self.2 } } impl AddAssign for Vec3f { fn add_assign(&mut self, other: Self) { *self = Vec3f(self.0 + other.0, self.1 + other.1, self.2 + other.2) } } impl Add for Vec3f { type Output = Self; fn add(self, other: Self) -> Vec3f { Vec3f(self.0 + other.0, self.1 + other.1, self.2 + other.2) } } impl Sub for Vec3f { type Output = Self; fn sub(self, other: Vec3f) -> Vec3f { Vec3f(self.0 - other.0, self.1 - other.1, self.2 - other.2) } } impl SubAssign for Vec3f { fn sub_assign(&mut self, other: Self) { *self = Vec3f(self.0 - other.0, self.1 - other.1, self.2 - other.2) } } impl Div<f32> for Vec3f { type Output = Self; fn div(self, rhs: f32) -> Vec3f { Vec3f(self.0 / rhs, self.1 / rhs, self.2 / rhs) } } impl DivAssign<f32> for Vec3f { fn div_assign(&mut self, rhs: f32) { *self = Vec3f(self.0 / rhs, self.1 / rhs, self.2 / rhs) } } impl From<nalgebra::Vector3<f32>> for Vec3f { fn from(d: nalgebra::Vector3<f32>) -> Self { Vec3f(d.x, d.y, d.z) } }
use super::h1; use futures::{future, Future, Poll}; use http; use http::header::{HeaderValue, TRANSFER_ENCODING}; use tracing::{debug, warn}; pub const L5D_ORIG_PROTO: &str = "l5d-orig-proto"; /// Upgrades HTTP requests from their original protocol to HTTP2. #[derive(Clone, Debug)] pub struct Upgrade<S> { inner: S, } /// Downgrades HTTP2 requests that were previousl upgraded to their original /// protocol. #[derive(Clone, Debug)] pub struct Downgrade<S> { inner: S, } // ==== impl Upgrade ===== impl<S> Upgrade<S> { pub fn new<A, B>(inner: S) -> Self where S: tower::Service<http::Request<A>, Response = http::Response<B>>, { Self { inner } } } impl<S, A, B> tower::Service<http::Request<A>> for Upgrade<S> where S: tower::Service<http::Request<A>, Response = http::Response<B>>, { type Response = S::Response; type Error = S::Error; type Future = future::Map<S::Future, fn(S::Response) -> S::Response>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.inner.poll_ready() } fn call(&mut self, mut req: http::Request<A>) -> Self::Future { debug_assert!( req.version() != http::Version::HTTP_2 && !h1::wants_upgrade(&req), "illegal request routed to orig-proto Upgrade", ); debug!("upgrading {:?} to HTTP2 with orig-proto", req.version()); // absolute-form is far less common, origin-form is the usual, // so only encode the extra information if it's different than // the normal. let was_absolute_form = h1::is_absolute_form(req.uri()); if !was_absolute_form { // Since the version is going to set to HTTP_2, the NormalizeUri // middleware won't normalize the URI automatically, so it // needs to be done now. h1::normalize_our_view_of_uri(&mut req); } let val = match (req.version(), was_absolute_form) { (http::Version::HTTP_11, false) => "HTTP/1.1", (http::Version::HTTP_11, true) => "HTTP/1.1; absolute-form", (http::Version::HTTP_10, false) => "HTTP/1.0", (http::Version::HTTP_10, true) => "HTTP/1.0; absolute-form", (v, _) => unreachable!("bad orig-proto version: {:?}", v), }; req.headers_mut() .insert(L5D_ORIG_PROTO, HeaderValue::from_static(val)); // transfer-encoding is illegal in HTTP2 req.headers_mut().remove(TRANSFER_ENCODING); *req.version_mut() = http::Version::HTTP_2; self.inner.call(req).map(|mut res| { debug_assert_eq!(res.version(), http::Version::HTTP_2); let version = if let Some(orig_proto) = res.headers_mut().remove(L5D_ORIG_PROTO) { debug!("downgrading {} response: {:?}", L5D_ORIG_PROTO, orig_proto); if orig_proto == "HTTP/1.1" { http::Version::HTTP_11 } else if orig_proto == "HTTP/1.0" { http::Version::HTTP_10 } else { warn!("unknown {} header value: {:?}", L5D_ORIG_PROTO, orig_proto); res.version() } } else { res.version() }; *res.version_mut() = version; res }) } } // ===== impl Downgrade ===== impl<S> Downgrade<S> { pub fn new<A, B>(inner: S) -> Self where S: tower::Service<http::Request<A>, Response = http::Response<B>>, { Self { inner } } } impl<S, A, B> tower::Service<http::Request<A>> for Downgrade<S> where S: tower::Service<http::Request<A>, Response = http::Response<B>>, { type Response = S::Response; type Error = S::Error; type Future = future::Map<S::Future, fn(S::Response) -> S::Response>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.inner.poll_ready() } fn call(&mut self, mut req: http::Request<A>) -> Self::Future { let mut upgrade_response = false; if req.version() == http::Version::HTTP_2 { if let Some(orig_proto) = req.headers_mut().remove(L5D_ORIG_PROTO) { debug!("translating HTTP2 to orig-proto: {:?}", orig_proto); let val: &[u8] = orig_proto.as_bytes(); if val.starts_with(b"HTTP/1.1") { *req.version_mut() = http::Version::HTTP_11; } else if val.starts_with(b"HTTP/1.0") { *req.version_mut() = http::Version::HTTP_10; } else { warn!("unknown {} header value: {:?}", L5D_ORIG_PROTO, orig_proto,); } if !was_absolute_form(val) { h1::set_origin_form(req.uri_mut()); } upgrade_response = true; } } let fut = self.inner.call(req); if upgrade_response { fut.map(|mut res| { let orig_proto = if res.version() == http::Version::HTTP_11 { "HTTP/1.1" } else if res.version() == http::Version::HTTP_10 { "HTTP/1.0" } else { return res; }; res.headers_mut() .insert(L5D_ORIG_PROTO, HeaderValue::from_static(orig_proto)); // transfer-encoding is illegal in HTTP2 res.headers_mut().remove(TRANSFER_ENCODING); *res.version_mut() = http::Version::HTTP_2; res }) } else { fut.map(|res| res) } } } fn was_absolute_form(val: &[u8]) -> bool { val.len() >= "HTTP/1.1; absolute-form".len() && &val[10..23] == b"absolute-form" }
pub fn find() -> Option<u32> { let sum:u32 = 1000; for a in 1..sum-2 { for b in a+1..sum-1 { for c in b+1..sum { if a*a + b*b == c*c { if a+b+c == sum { println!("{} {} {}",a,b,c); return Some(a*b*c); } } } } } None }
use std::{fmt, ops::Deref}; use tui::style::{Color, Modifier, Style}; #[derive(Clone, Debug, PartialEq)] pub struct ColoredString { input: String, style: Style, } /// The trait that enables something to be given color. /// /// You can use `colored` effectively simply by importing this trait /// and then using its methods on `String` and `&str`. // This `trait` was copied from https://github.com/mackwic/colored/blob/0b4ce98dacdddf1b908c4f6c782a97526d2b4e34/src/lib.rs#L53-L113 // Documentation was preserved. pub trait Colorize { // Font Colors fn black(self) -> ColoredString; fn red(self) -> ColoredString; fn green(self) -> ColoredString; fn yellow(self) -> ColoredString; fn blue(self) -> ColoredString; fn magenta(self) -> ColoredString; fn purple(self) -> ColoredString; fn cyan(self) -> ColoredString; fn white(self) -> ColoredString; fn bright_black(self) -> ColoredString; fn bright_red(self) -> ColoredString; fn bright_green(self) -> ColoredString; fn bright_yellow(self) -> ColoredString; fn bright_blue(self) -> ColoredString; fn bright_magenta(self) -> ColoredString; fn bright_purple(self) -> ColoredString; fn bright_cyan(self) -> ColoredString; fn bright_white(self) -> ColoredString; fn color<S: Into<Color>>(self, color: S) -> ColoredString; // Background Colors fn on_black(self) -> ColoredString; fn on_red(self) -> ColoredString; fn on_green(self) -> ColoredString; fn on_yellow(self) -> ColoredString; fn on_blue(self) -> ColoredString; fn on_magenta(self) -> ColoredString; fn on_purple(self) -> ColoredString; fn on_cyan(self) -> ColoredString; fn on_white(self) -> ColoredString; fn on_bright_black(self) -> ColoredString; fn on_bright_red(self) -> ColoredString; fn on_bright_green(self) -> ColoredString; fn on_bright_yellow(self) -> ColoredString; fn on_bright_blue(self) -> ColoredString; fn on_bright_magenta(self) -> ColoredString; fn on_bright_purple(self) -> ColoredString; fn on_bright_cyan(self) -> ColoredString; fn on_bright_white(self) -> ColoredString; fn on_color<S: Into<Color>>(self, color: S) -> ColoredString; // Styles fn clear(self) -> ColoredString; fn normal(self) -> ColoredString; fn bold(self) -> ColoredString; fn dimmed(self) -> ColoredString; fn italic(self) -> ColoredString; fn underline(self) -> ColoredString; fn blink(self) -> ColoredString; /// Historical name of `Colorize::reversed`. May be removed in a future /// version. Please use `Colorize::reversed` instead fn reverse(self) -> ColoredString; /// This should be preferred to `Colorize::reverse`. fn reversed(self) -> ColoredString; fn hidden(self) -> ColoredString; fn strikethrough(self) -> ColoredString; } impl ColoredString { fn has_colors(&self) -> bool { self.style.fg != Color::Reset || self.style.bg != Color::Reset || self.style.modifier != Modifier::Reset } fn is_plain(&self) -> bool { self.style.fg == Color::White && self.style.bg == Color::Reset && self.style.modifier == Modifier::Reset } fn compute_style(&self) -> String { let mut dirty = false; let mut s = String::new(); if self.style.fg != Color::Reset { s.push_str(&format!("fg={}", color_to_str(self.style.fg))); dirty = true; } if self.style.bg != Color::Reset { if dirty { s.push(';'); } s.push_str(&format!("bg={}", color_to_str(self.style.bg))); } if self.style.modifier != Modifier::Reset { if dirty { s.push(';'); } s.push_str(&format!("mod={}", modifier_to_str(self.style.modifier))); } s } fn escape_input(&self) -> String { self.input .replace("\\", "\\\\") .replace("{", "\\{") .replace("}", "\\}") .replace("[", "\\[") .replace("]", "\\]") .replace("(", "\\(") .replace(")", "\\)") } } impl Default for ColoredString { fn default() -> ColoredString { ColoredString { input: String::default(), style: Style::default(), } } } impl Deref for ColoredString { type Target = str; fn deref(&self) -> &str { &self.input } } impl<'a> From<&'a str> for ColoredString { fn from(s: &'a str) -> Self { ColoredString { input: String::from(s), style: Style::default(), } } } macro_rules! def_color { ($side:ident: $name:ident => $color:path) => { fn $name(self) -> ColoredString { self.style.$side($color); self } } } macro_rules! def_style { ($name:ident, $value:path) => { fn $name(self) -> ColoredString { self.style.modifier($value); self } } } macro_rules! def_unimplemented { ($name:ident) => { fn $name(self) -> ColoredString { unimplemented!(); } }; } #[cfg_attr(rustftm, rustfmt_skip)] impl Colorize for ColoredString { def_unimplemented!(hidden); def_unimplemented!(reversed); def_unimplemented!(reverse); def_style!(strikethrough, Modifier::CrossedOut); def_style!(blink, Modifier::Blink); def_style!(underline, Modifier::Underline); def_style!(italic, Modifier::Italic); def_style!(dimmed, Modifier::Faint); def_style!(bold, Modifier::Bold); def_color!(bg: on_bright_white => Color::White); def_color!(bg: on_bright_cyan => Color::LightCyan); def_color!(bg: on_bright_purple => Color::LightMagenta); def_color!(bg: on_bright_magenta => Color::LightMagenta); def_color!(bg: on_bright_blue => Color::LightBlue); def_color!(bg: on_bright_yellow => Color::LightYellow); def_color!(bg: on_bright_green => Color::LightGreen); def_color!(bg: on_bright_red => Color::LightRed); def_color!(bg: on_bright_black => Color::Gray); def_color!(bg: on_white => Color::White); def_color!(bg: on_cyan => Color::Cyan); def_color!(bg: on_purple => Color::Magenta); def_color!(bg: on_magenta => Color::Magenta); def_color!(bg: on_blue => Color::Blue); def_color!(bg: on_yellow => Color::Yellow); def_color!(bg: on_green => Color::Green); def_color!(bg: on_red => Color::Red); def_color!(bg: on_black => Color::Black); def_color!(fg: bright_white => Color::White); def_color!(fg: bright_cyan => Color::LightCyan); def_color!(fg: bright_purple => Color::LightMagenta); def_color!(fg: bright_magenta => Color::LightMagenta); def_color!(fg: bright_blue => Color::LightBlue); def_color!(fg: bright_yellow => Color::LightYellow); def_color!(fg: bright_green => Color::LightGreen); def_color!(fg: bright_red => Color::LightRed); def_color!(fg: bright_black => Color::DarkGray); def_color!(fg: white => Color::White); def_color!(fg: cyan => Color::Cyan); def_color!(fg: purple => Color::Magenta); def_color!(fg: magenta => Color::Magenta); def_color!(fg: blue => Color::Blue); def_color!(fg: yellow => Color::Yellow); def_color!(fg: green => Color::Green); def_color!(fg: red => Color::Red); def_color!(fg: black => Color::Black); fn color<S: Into<Color>>(self, color: S) -> ColoredString { self.style.fg(color.into()); self } fn on_color<S: Into<Color>>(self, color: S) -> ColoredString { self.style.bg(color.into()); self } fn clear(self) -> ColoredString { ColoredString { input: self.input, style: Style::default(), } } fn normal(self) -> ColoredString { self.clear() } } macro_rules! def_str_color { ($side:ident: $name:ident => $color:path) => { fn $name(self) -> ColoredString { ColoredString { input: String::from(self), style: Style::default().$side($color) } } } } macro_rules! def_str_style { ($name:ident, $value:path) => { fn $name(self) -> ColoredString { ColoredString { input: String::from(self), style: Style::default().modifier($value) } } } } #[cfg_attr(rustftm, rustfmt_skip)] impl<'a> Colorize for &'a str { def_unimplemented!(hidden); def_unimplemented!(reversed); def_unimplemented!(reverse); def_str_style!(strikethrough, Modifier::CrossedOut); def_str_style!(blink, Modifier::Blink); def_str_style!(underline, Modifier::Underline); def_str_style!(italic, Modifier::Italic); def_str_style!(dimmed, Modifier::Faint); def_str_style!(bold, Modifier::Bold); def_str_color!(bg: on_bright_white => Color::White); def_str_color!(bg: on_bright_cyan => Color::LightCyan); def_str_color!(bg: on_bright_purple => Color::LightMagenta); def_str_color!(bg: on_bright_magenta => Color::LightMagenta); def_str_color!(bg: on_bright_blue => Color::LightBlue); def_str_color!(bg: on_bright_yellow => Color::LightYellow); def_str_color!(bg: on_bright_green => Color::LightGreen); def_str_color!(bg: on_bright_red => Color::LightRed); def_str_color!(bg: on_bright_black => Color::Gray); def_str_color!(bg: on_white => Color::White); def_str_color!(bg: on_cyan => Color::Cyan); def_str_color!(bg: on_purple => Color::Magenta); def_str_color!(bg: on_magenta => Color::Magenta); def_str_color!(bg: on_blue => Color::Blue); def_str_color!(bg: on_yellow => Color::Yellow); def_str_color!(bg: on_green => Color::Green); def_str_color!(bg: on_red => Color::Red); def_str_color!(bg: on_black => Color::Black); def_str_color!(fg: bright_white => Color::White); def_str_color!(fg: bright_cyan => Color::LightCyan); def_str_color!(fg: bright_purple => Color::LightMagenta); def_str_color!(fg: bright_magenta => Color::LightMagenta); def_str_color!(fg: bright_blue => Color::LightBlue); def_str_color!(fg: bright_yellow => Color::LightYellow); def_str_color!(fg: bright_green => Color::LightGreen); def_str_color!(fg: bright_red => Color::LightRed); def_str_color!(fg: bright_black => Color::DarkGray); def_str_color!(fg: white => Color::White); def_str_color!(fg: cyan => Color::Cyan); def_str_color!(fg: purple => Color::Magenta); def_str_color!(fg: magenta => Color::Magenta); def_str_color!(fg: blue => Color::Blue); def_str_color!(fg: yellow => Color::Yellow); def_str_color!(fg: green => Color::Green); def_str_color!(fg: red => Color::Red); def_str_color!(fg: black => Color::Black); fn color<S: Into<Color>>(self, color: S) -> ColoredString { ColoredString { input: String::from(self), style: Style::default().fg(color.into()) } } fn on_color<S: Into<Color>>(self, color: S) -> ColoredString { ColoredString { input: String::from(self), style: Style::default().bg(color.into()) } } fn clear(self) -> ColoredString { ColoredString { input: String::from(self), style: Style::default().fg(Color::Reset).bg(Color::Reset).modifier(Modifier::Reset), } } fn normal(self) -> ColoredString { self.clear() } } impl fmt::Display for ColoredString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if !self.has_colors() || self.is_plain() { return f.write_str(&self.input); } let sty = self.compute_style(); if sty.is_empty() { f.write_str(&self.input)?; } else { let inp = self.escape_input(); f.write_str("{")?; f.write_str(&format!("{} {}", sty, inp))?; f.write_str("}")?; } Ok(()) } } fn color_to_str(c: Color) -> &'static str { #[cfg_attr(rustfmt, rustfmt_skip)] match c { Color::Black => "black", Color::Red => "red", Color::Green => "green", Color::Yellow => "yellow", Color::Blue => "blue", Color::Magenta => "magenta", Color::Cyan => "cyan", Color::Gray => "gray", Color::DarkGray => "dark_gray", Color::LightRed => "light_red", Color::LightGreen => "light_green", Color::LightBlue => "light_blue", Color::LightYellow => "light_yellow", Color::LightMagenta => "light_magenta", Color::LightCyan => "light_cyan", _ => "", } } fn modifier_to_str(m: Modifier) -> &'static str { #[cfg_attr(rustfmt, rustfmt_skip)] match m { Modifier::Bold => "bold", Modifier::Italic => "italic", Modifier::Underline => "underline", Modifier::Invert => "invert", Modifier::CrossedOut => "crossed_out", _ => "", } }
use std::collections::HashMap; pub fn get_recursive_cache(seed: &mut Vec<u64>, days: u64) -> u64 { let mut cache: HashMap<i64, u64> = HashMap::new(); seed.iter() .map(|fish| get_fishes((days - fish) as i64, &mut cache)) .sum() } pub fn get_fishes(iteration: i64, cache: &mut HashMap<i64, u64>) -> u64 { let ages = vec![7,9]; if iteration > 0 { ages.iter().map( |age| { if let Some(nr) = cache.get(&(iteration - age)) { *nr } else { let nr = get_fishes(iteration - age, cache); cache.insert(iteration-age, nr); nr }}).sum() } else { 1 } } pub fn run_seed_for_x_generations(seed: &mut Vec<u64>, iterations: i32) -> usize { let mut seed = seed.clone(); for _iteration in 0..iterations { for i in 0..seed.len() { if &seed[i] == &0 { seed.push(8) } if &seed[i] == &0 { seed[i] = 6 } else { seed[i] -= 1 } } } seed.len() } pub fn get_fishes_after_x_days(seed: &mut Vec<u64>, days: usize) -> u64 { // setup vec of zeroes let mut breeders: Vec<u64> = vec![0; 9]; // initialize with seed for fish_age in seed.clone() { breeders[fish_age as usize] += 1 } // run to completion for iteration in 0..days { let current_breeders = breeders[iteration % 9]; // existing fish spawn a new fish at age 8 (loop size, keep existing value) // spawn current fish as new fish in 6 cycles breeders[(iteration + 7) % 9] += current_breeders; } breeders.iter().sum() } pub fn get_population_recursive(seed: &mut Vec<u64>, iterations: u64) -> u64 { let seed = seed.clone(); let current_iteration = 0; let mut total_population = 0 as u64; for fish in seed { total_population += get_children(fish, current_iteration, iterations) } total_population } fn get_children(start_age: u64, current_iteration: u64, iterations: u64) -> u64 { let spawns: Vec<u64> = (current_iteration + start_age..iterations) .step_by(7) .collect(); let mut children = 1; for iteration in spawns { children += get_children(9, iteration, iterations) } children } #[cfg(test)] mod tests { use crate::day6::{ get_fishes_after_x_days, get_population_recursive, get_recursive_cache, run_seed_for_x_generations, }; #[test] fn test_example() { let mut seed = vec![3, 4, 3, 1, 2]; //let mut seed = vec![ 3]; assert_eq!(26, run_seed_for_x_generations(&mut seed, 18)); assert_eq!(26, get_population_recursive(&mut seed, 18)); assert_eq!(26, get_recursive_cache(&mut seed, 18)); assert_eq!(26, get_fishes_after_x_days(&mut seed, 18)); assert_eq!(26984457539, get_recursive_cache(&mut seed, 256)); assert_eq!(26984457539, get_fishes_after_x_days(&mut seed, 256)); } #[test] fn test_input() { let mut seed = vec![ 4, 1, 3, 2, 4, 3, 1, 4, 4, 1, 1, 1, 5, 2, 4, 4, 2, 1, 2, 3, 4, 1, 2, 4, 3, 4, 5, 1, 1, 3, 1, 2, 1, 4, 1, 1, 3, 4, 1, 2, 5, 1, 4, 2, 2, 1, 1, 1, 3, 1, 5, 3, 1, 2, 1, 1, 1, 1, 4, 1, 1, 1, 2, 2, 1, 3, 1, 3, 1, 3, 4, 5, 1, 2, 2, 1, 1, 1, 4, 1, 5, 1, 3, 1, 3, 4, 1, 3, 2, 3, 4, 4, 4, 3, 4, 5, 1, 3, 1, 3, 5, 1, 1, 1, 1, 1, 2, 4, 1, 2, 1, 1, 1, 5, 1, 1, 2, 1, 3, 1, 4, 2, 3, 4, 4, 3, 1, 1, 3, 5, 3, 1, 1, 5, 2, 4, 1, 1, 3, 5, 1, 4, 3, 1, 1, 4, 2, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 4, 5, 1, 2, 5, 3, 1, 1, 3, 1, 1, 1, 1, 5, 1, 2, 5, 1, 1, 1, 1, 1, 1, 3, 5, 1, 3, 2, 1, 1, 1, 1, 1, 1, 1, 4, 5, 1, 1, 3, 1, 5, 1, 1, 1, 1, 3, 3, 1, 1, 1, 4, 4, 1, 1, 4, 1, 2, 1, 4, 4, 1, 1, 3, 4, 3, 5, 4, 1, 1, 4, 1, 3, 1, 1, 5, 5, 1, 2, 1, 2, 1, 2, 3, 1, 1, 3, 1, 1, 2, 1, 1, 3, 4, 3, 1, 1, 3, 3, 5, 1, 2, 1, 4, 1, 1, 2, 1, 3, 1, 1, 1, 1, 1, 1, 1, 4, 5, 5, 1, 1, 1, 4, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 5, ]; assert_eq!(1689540415957, get_fishes_after_x_days(&mut seed, 256)); assert_eq!(1689540415957, get_recursive_cache(&mut seed, 256)) } }
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0. /// Type alias to use this library's [`IpldCborError`] type in a `Result`. pub type Result<T> = std::result::Result<T, IpldCoreError>; /// Errors generated from this library. #[derive(Debug, thiserror::Error)] pub enum IpldCoreError { /// JSON serialization/deserialization error. #[error("json de/serialize error: {0}")] JsonCodecErr(#[from] serde_json::Error), /// CBOR serialization/deserialization error. #[error("core encode error: {0}")] CborEncodeErr(#[from] minicbor::encode::Error<std::io::Error>), /// CBOR deserialization error. #[error("core decode error: {0}")] CborDecodeErr(#[from] minicbor::decode::Error), /// CID error. #[error("cid error: {0}")] CidErr(#[from] cid::Error), /// Block format error. #[error("block format error: {0}")] BlockErr(#[from] block_format::BlockFormatError), /// Multihash encode error. #[error("multi hash error: {0}")] HashErr(#[from] multihash::EncodeError), /// No such link found. #[error("no such link found, path: {0}")] NoSuchLink(String), /// Non-link found at given path. #[error("non-link found at given path")] NonLink, /// Invalid link. #[error("link value should have been bytes or cid")] InvalidLink, /// No links #[error("tried to resolve through object that had no links")] NoLinks, /// Link is not a string. #[error("link should have been a string")] NonStringLink, /// Deserialize CID error. #[error("deserialize cid failed, reason: {0}")] DeserializeCid(String), /// Failure when converting to Obj. #[error("Failure when converting to Obj, reason: {0}")] ObjErr(String), /// Other error. #[error("other error: {0}")] Other(#[from] Box<dyn std::error::Error + Send + Sync>), }
//! Do not use this crate directly. //! //! This is the immplementation crate for `hdbconnect` and `hdbconnect_async`. //! //! If you need a synchronous driver, use `hdbconnect`. //! //! If you need an asynchronous driver, use `hdbconnect_async`. //! // only enables the `doc_cfg` feature when the `docsrs` configuration attribute is defined #![cfg_attr(docsrs, feature(doc_cfg))] #![deny(missing_debug_implementations)] #![deny(clippy::all)] #![deny(clippy::pedantic)] #![allow(clippy::module_name_repetitions)] #![allow(clippy::non_ascii_literal)] #![allow(clippy::must_use_candidate)] #![allow(clippy::missing_errors_doc)] #![cfg_attr(not(any(feature = "sync", feature = "async")), allow(unused_imports))] #![cfg_attr(not(any(feature = "sync", feature = "async")), allow(dead_code))] #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern crate serde; mod conn; mod hdb_error; mod internal_returnvalue; mod protocol; mod row; mod rows; mod serde_db_impl; mod types_impl; pub mod url; #[cfg(feature = "dist_tx")] mod xa_impl; #[cfg(feature = "async")] pub mod a_sync; #[cfg(feature = "sync")] pub mod sync; pub(crate) use internal_returnvalue::InternalReturnValue; pub use crate::{ conn::{ ConnectParams, ConnectParamsBuilder, IntoConnectParams, IntoConnectParamsBuilder, ServerCerts, Tls, }, hdb_error::{HdbError, HdbResult}, protocol::parts::{ ExecutionResult, FieldMetadata, HdbValue, OutputParameters, ParameterBinding, ParameterDescriptor, ParameterDescriptors, ParameterDirection, ResultSetMetadata, ServerError, Severity, TypeId, }, protocol::ServerUsage, row::Row, rows::Rows, serde_db_impl::{time, ToHana}, }; /// Non-standard types that are used to represent database values. /// /// A `ResultSet` contains a sequence of `Row`s, each row is a sequence of `HdbValue`s. /// Some variants of `HdbValue` are implemented using plain rust types, /// others are based on the types in this module. pub mod types { pub use crate::types_impl::{ daydate::DayDate, lob::CharLobSlice, longdate::LongDate, seconddate::SecondDate, secondtime::SecondTime, }; } /// Default value for the number of resultset lines that are fetched with a single FETCH roundtrip. /// /// The value used at runtime can be changed with /// [`Connection::set_fetch_size()`](crate::Connection::set_fetch_size). pub const DEFAULT_FETCH_SIZE: u32 = 100_000; /// Number of bytes (for BLOBS and CLOBS) or 1-2-3-byte sequences (for NCLOBS) /// that are fetched in a single LOB READ roundtrip. /// /// The value used at runtime can be changed with /// [`Connection::set_lob_read_length()`](crate::Connection::set_lob_read_length). pub const DEFAULT_LOB_READ_LENGTH: u32 = 16_000_000; /// Number of bytes that are written in a single LOB WRITE roundtrip. /// /// The value used at runtime can be changed with /// [`Connection::set_lob_write_length()`](crate::Connection::set_lob_write_length). pub const DEFAULT_LOB_WRITE_LENGTH: usize = 16_000_000;
use crate::worker::component::{self, Component, ComponentId, DATABASE}; use crate::worker::internal::schema::SchemaComponentData; use spatialos_sdk_sys::worker::{Schema_DestroyComponentData, Worker_ComponentData, Worker_Entity}; use std::collections::HashMap; use std::ptr; use std::slice; #[derive(Debug)] pub struct Entity { components: HashMap<ComponentId, Worker_ComponentData>, } impl Entity { pub fn new() -> Self { Entity::default() } pub(crate) unsafe fn from_worker_sdk(raw_entity: &Worker_Entity) -> Result<Self, String> { let mut entity = Entity::new(); let component_data = slice::from_raw_parts(raw_entity.components, raw_entity.component_count as usize); for data in component_data { entity.add_raw(data)?; } Ok(entity) } pub(crate) fn add<C: Component>(&mut self, component: C) -> Result<(), String> { self.pre_add_check(C::ID)?; let data_ptr = component::handle_allocate(component); let raw_data = Worker_ComponentData { reserved: ptr::null_mut(), component_id: C::ID, schema_type: ptr::null_mut(), user_handle: data_ptr as *mut _, }; self.components.insert(C::ID, raw_data); Ok(()) } pub(crate) unsafe fn add_raw( &mut self, component: &Worker_ComponentData, ) -> Result<(), String> { let id = component.component_id; self.pre_add_check(id)?; // Call copy on the component data. We don't own this Worker_ComponentData. let vtable = DATABASE.get_vtable(id).unwrap(); let copy_data_func = vtable .component_data_copy .unwrap_or_else(|| panic!("No component_data_free method defined for {}", id)); copy_data_func(id, ptr::null_mut(), component.user_handle); self.components.insert( id, Worker_ComponentData { reserved: ptr::null_mut(), component_id: id, schema_type: ptr::null_mut(), user_handle: component.user_handle, }, ); Ok(()) } pub(crate) unsafe fn add_serialized( &mut self, component_id: ComponentId, component: SchemaComponentData, ) -> Result<(), String> { let vtable = DATABASE.get_vtable(component_id).unwrap(); let deserialize_func = vtable.component_data_deserialize.unwrap_or_else(|| { Schema_DestroyComponentData(component.internal); panic!( "No component_data_deserialize method defined for {}", component_id ) }); // Create the **void that the C API requires. We need to then clean this up later. // The value pointed to by handle_out_ptr is written to during the deserialize method. let placeholder_ptr = Box::into_raw(Box::new(0)) as *mut ::std::os::raw::c_void; let handle_out_ptr = Box::into_raw(Box::new(placeholder_ptr)); let deserialize_result = deserialize_func( component_id, ptr::null_mut(), component.internal, handle_out_ptr, ); Schema_DestroyComponentData(component.internal); match deserialize_result { 1 => {}, 0 => return Err("Error deserializing serialized data. Is the SchemaComponentData malformed?".to_owned()), _ => panic!("Unexpected return value from deserialize function. Expected true or false. Received other.") }; let component_data = Worker_ComponentData { reserved: ptr::null_mut(), component_id, schema_type: ptr::null_mut(), user_handle: *handle_out_ptr, }; // Reconstruct these objects so they can be de-alloc'ed. We have pulled the data required // from them by de-referencing handle_out_ptr above. Box::from_raw(placeholder_ptr); Box::from_raw(handle_out_ptr); self.add_raw(&component_data) } pub fn get<C: Component>(&self) -> Option<&C> { self.components .get(&C::ID) .map(|data| unsafe { &*(data.user_handle as *const _) }) } pub(crate) fn raw_component_data(&self) -> RawEntity { RawEntity::new(self.components.values()) } fn pre_add_check(&self, id: ComponentId) -> Result<(), String> { if self.components.contains_key(&id) { return Err(format!( "Duplicate component with ID {} added to `Entity`.", id )); } if !DATABASE.has_vtable(id) { panic!(format!( "Could not find a vtable implementation for component {}", id )); } Ok(()) } } impl Default for Entity { fn default() -> Self { Entity { components: HashMap::new(), } } } impl Drop for Entity { fn drop(&mut self) { for component_data in self.components.values() { let id = component_data.component_id; let vtable = DATABASE.get_vtable(id).unwrap(); let free_data_func = vtable .component_data_free .unwrap_or_else(|| panic!("No component_data_free method defined for {}", id)); unsafe { free_data_func(id, ptr::null_mut(), component_data.user_handle) }; } } } // Required for when we call Entity::raw_component_data() and want a Vec<Worker_ComponentData> rather // than a Vec<&Worker_ComponentData> which most callers *will* want due to how Worker_Entity is structured. pub(crate) struct RawEntity { pub components: Vec<Worker_ComponentData>, } impl RawEntity { pub fn new<'a, I>(original_data: I) -> Self where I: Iterator<Item = &'a Worker_ComponentData>, { // Go through each Worker_ComponentData object, make a copy and call handle_copy using the vtable. let new_data = original_data .map(|original_component_data| { let new_component_data = *original_component_data; // Is a copy operation. let id = original_component_data.component_id; let vtable = DATABASE.get_vtable(id).unwrap(); let copy_data_func = vtable .component_data_copy .unwrap_or_else(|| panic!("No component_data_copy method defined for {}", id)); unsafe { copy_data_func(id, ptr::null_mut(), original_component_data.user_handle) }; new_component_data }) .collect(); RawEntity { components: new_data, } } } impl Drop for RawEntity { fn drop(&mut self) { for component_data in &self.components { let vtable = DATABASE.get_vtable(component_data.component_id).unwrap(); let free_data_func = vtable.component_data_free.unwrap_or_else(|| { panic!( "No component_data_free method defined for {}", component_data.component_id ) }); unsafe { free_data_func( component_data.component_id, ptr::null_mut(), component_data.user_handle, ) }; } } }