text
stringlengths
8
4.13M
#![deny(warnings)] #![feature(abi_msp430_interrupt)] #![feature(const_fn)] #![feature(proc_macro)] #![no_std] extern crate msp430; extern crate msp430g2553; #[macro_use(task)] extern crate msp430_rtfm as rtfm; use rtfm::app; app! { device: msp430g2553, resources: { static SHARED: u32 = 0; }, idle: { resources: [SHARED], }, tasks: { TIMER0_A1: { resources: [SHARED], }, }, } fn init(_p: init::Peripherals, _r: init::Resources) {} fn idle(mut r: idle::Resources) -> ! { loop { // .. // to access a *shared* resource from `idle` a critical section is // needed rtfm::atomic(|cs| { **r.SHARED.borrow_mut(cs) += 1; }); // .. } } task!(TIMER0_A1, periodic); fn periodic(r: TIMER0_A1::Resources) { // interrupts don't need a critical section to access resources **r.SHARED += 1; }
use core_foundation_sys::base::*; extern { pub fn CFNetServiceGetTypeID() -> CFTypeID; pub fn CFNetServiceMonitorGetTypeID() -> CFTypeID; pub fn CFNetServiceBrowserGetTypeID() -> CFTypeID; }
use crate::{material::Material, ray::Ray, Point3}; use std::sync::Arc; pub struct HitRecord { pub p: Point3, pub normal: Point3, pub t: f64, pub front_face: bool, pub material: Option<Arc<dyn Material + Send + Sync>>, } impl Clone for HitRecord { fn clone(&self) -> Self { HitRecord { material: self.material.as_ref().map(|x| x.clone()), ..*self } } } impl HitRecord { pub fn default() -> Self { HitRecord { p: Point3::default(), normal: Point3::default(), t: Default::default(), front_face: Default::default(), material: None, } } pub fn set_face_normal(&mut self, ray: &Ray, outward_normal: &Point3) { self.front_face = ray.direction().dot(outward_normal) < 0.0; self.normal = if self.front_face { *outward_normal } else { -*outward_normal }; } }
use binary_search_range::BinarySearchRange; use proconio::input; fn main() { input! { t: usize, }; for _ in 0..t { input! { n: usize, a: [u32; n], }; solve(n, a); } } fn solve(n: usize, a: Vec<u32>) { let mut b = a.clone(); b.sort(); if n % 2 == 0 { for i in 0..(n / 2) { let rng1 = b.range(a[i * 2]..(a[i * 2] + 1)); let rng2 = b.range(a[i * 2 + 1]..(a[i * 2 + 1] + 1)); if (rng1.contains(&(i * 2)) && rng2.contains(&(i * 2 + 1))) || (rng1.contains(&(i * 2 + 1)) && rng2.contains(&(i * 2))) { // } else { println!("NO"); return; } } println!("YES"); } else { if a[0] != b[0] { println!("NO"); return; } for i in 0..(n / 2) { let rng1 = b.range(a[i * 2 + 1]..(a[i * 2 + 1] + 1)); let rng2 = b.range(a[i * 2 + 2]..(a[i * 2 + 2] + 1)); if (rng1.contains(&(i * 2 + 1)) && rng2.contains(&(i * 2 + 2))) || (rng1.contains(&(i * 2 + 2)) && rng2.contains(&(i * 2 + 1))) { // } else { println!("NO"); return; } } println!("YES"); } }
use super::interfaces::player::{Angle, PlayerState, Position}; use super::packet::Packet; use uuid::Uuid; pub fn route_packet<P: PlayerState>(p: Packet, conn_id: Uuid, player_state: P) { match p { Packet::PlayerPosition(player_position) => { player_state.move_and_look( conn_id, Some(Position { x: player_position.x, y: player_position.feet_y, z: player_position.z, }), None, ); } Packet::PlayerPositionAndLook(player_position_and_look) => { player_state.move_and_look( conn_id, Some(Position { x: player_position_and_look.x, y: player_position_and_look.feet_y, z: player_position_and_look.z, }), Some(Angle { yaw: player_position_and_look.yaw, pitch: player_position_and_look.pitch, }), ); } Packet::PlayerLook(player_look) => { player_state.move_and_look( conn_id, None, Some(Angle { yaw: player_look.yaw, pitch: player_look.pitch, }), ); } Packet::Unknown => (), _ => { panic!("Gameplay router received unexpected packet {:?}", p); } } }
//! VM Runtime #[cfg(not(feature = "std"))] use alloc::vec::Vec; #[cfg(not(feature = "std"))] use alloc::boxed::Box; #[cfg(not(feature = "std"))] use alloc::rc::Rc; #[cfg(feature = "std")] use std::rc::Rc; #[cfg(not(feature = "std"))] use core::ops::AddAssign; #[cfg(feature = "std")] use std::ops::AddAssign; use super::commit::{AccountState, BlockhashState}; use super::errors::{CommitError, EvalOnChainError, NotSupportedError, OnChainError, RequireError, RuntimeError}; use super::pc::Instruction; use super::{AccountCommitment, Context, HeaderParams, Log, Memory, Opcode, PCMut, Patch, Stack, Valids, PC}; use bigint::{Address, Gas, M256, U256}; use self::check::{check_opcode, check_static, check_support, extra_check_opcode}; use self::cost::{gas_cost, gas_refund, gas_stipend, memory_cost, memory_gas, AddRefund}; use self::run::run_opcode; macro_rules! reset_error_hard { ($self: expr, $err: expr) => { $self.status = MachineStatus::ExitedErr($err); $self.state.used_gas = GasUsage::All; $self.state.refunded_gas = Gas::zero(); $self.state.logs = Vec::new(); $self.state.out = Rc::new(Vec::new()); }; } macro_rules! reset_error_revert { ($self: expr) => { $self.status = MachineStatus::ExitedErr(OnChainError::Revert); }; } macro_rules! reset_error_not_supported { ($self: expr, $err: expr) => { $self.status = MachineStatus::ExitedNotSupported($err); $self.state.used_gas = GasUsage::Some(Gas::zero()); $self.state.refunded_gas = Gas::zero(); $self.state.logs = Vec::new(); $self.state.out = Rc::new(Vec::new()); }; } mod check; mod cost; mod lifecycle; mod run; mod util; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum GasUsage { All, Some(Gas), } impl AddAssign<Gas> for GasUsage { fn add_assign(&mut self, rhs: Gas) { match self { GasUsage::All => (), GasUsage::Some(ref mut gas) => { *gas = *gas + rhs; } } } } /// A VM state without PC. pub struct State<'a, M, P: Patch> { /// Current patch pub patch: &'a P, /// Memory of this runtime. pub memory: M, /// Stack of this runtime. pub stack: Stack, /// Context. pub context: Context, /// The current out value. pub out: Rc<Vec<u8>>, /// Return data buffer. pub ret: Rc<Vec<u8>>, /// The current memory cost. Note that this is different from /// memory gas. pub memory_cost: Gas, /// Used gas excluding memory gas. pub used_gas: GasUsage, /// Refunded gas. pub refunded_gas: Gas, /// The current account commitment states. pub account_state: AccountState<'a, P::Account>, /// Logs appended. pub logs: Vec<Log>, /// All removed accounts using the SUICIDE opcode. pub removed: Vec<Address>, /// Depth of this runtime. pub depth: usize, /// Code valid maps. pub valids: Valids, /// PC position. pub position: usize, } impl<'a, M, P: Patch> State<'a, M, P> { /// Memory gas, part of total used gas. pub fn memory_gas(&self) -> Gas { memory_gas(self.memory_cost) } /// Available gas at this moment. pub fn available_gas(&self) -> Gas { self.context.gas_limit - self.total_used_gas() } /// Total used gas including the memory gas. pub fn total_used_gas(&self) -> Gas { match self.used_gas { GasUsage::All => self.context.gas_limit, GasUsage::Some(gas) => self.memory_gas() + gas, } } } /// A VM runtime. Only available in eval. pub struct Runtime { /// The current blockhash commitment states. pub blockhash_state: BlockhashState, /// Block header. pub block: HeaderParams, /// Hooks for context history. pub context_history_hooks: Vec<Box<Fn(&Context)>>, } impl Runtime { /// Create a new VM runtime. pub fn new(block: HeaderParams) -> Self { Self::with_states(block, BlockhashState::default()) } /// Create the runtime with the given blockhash state. pub fn with_states(block: HeaderParams, blockhash_state: BlockhashState) -> Self { Runtime { block, blockhash_state, context_history_hooks: Vec::new(), } } } /// A VM state with PC. pub struct Machine<'a, M, P: Patch> { state: State<'a, M, P>, status: MachineStatus, } #[derive(Debug, Clone)] /// Represents the current runtime status. // TODO: consider boxing the large fields to reduce the total size of the enum pub enum MachineStatus { /// This runtime is actively running or has just been started. Running, /// This runtime has exited successfully. Calling `step` on this /// runtime again would panic. ExitedOk, /// This runtime has exited with errors. Calling `step` on this /// runtime again would panic. ExitedErr(OnChainError), /// This runtime has exited because it does not support certain /// operations. Unlike `ExitedErr`, this is not on-chain, and if /// it happens, client should either drop the transaction or panic /// (because it rarely happens). ExitedNotSupported(NotSupportedError), /// This runtime requires execution of a sub runtime, which is a /// ContractCreation instruction. InvokeCreate(Context), /// This runtime requires execution of a sub runtime, which is a /// MessageCall instruction. InvokeCall(Context, (U256, U256)), } #[derive(Debug, Clone)] /// Used for `check` for additional checks related to the runtime. pub enum ControlCheck { Jump(M256), } #[derive(Debug, Clone)] /// Used for `step` for additional operations related to the runtime. // TODO: consider boxing the large fields to reduce the total size of the enum pub enum Control { Stop, Revert, Jump(M256), InvokeCreate(Context), InvokeCall(Context, (U256, U256)), } impl<'a, M: Memory, P: Patch> Machine<'a, M, P> { /// Derive this runtime to create a sub runtime. This will not /// modify the current runtime, and it will have a chance to /// review whether it wants to accept the result of this sub /// runtime afterwards. pub fn derive(&self, context: Context) -> Self { Machine { status: MachineStatus::Running, state: State { patch: self.state.patch, memory: M::new(self.state.patch.memory_limit()), stack: Stack::default(), out: Rc::new(Vec::new()), ret: Rc::new(Vec::new()), memory_cost: Gas::zero(), used_gas: GasUsage::Some(Gas::zero()), refunded_gas: Gas::zero(), account_state: self.state.account_state.clone(), logs: Vec::new(), removed: self.state.removed.clone(), depth: self.state.depth + 1, position: 0, valids: Valids::new(context.code.as_slice()), context, }, } } /// Create a new runtime. pub fn new(patch: &'a P, context: Context, depth: usize) -> Self { let account_patch = patch.account_patch(); Self::with_states(patch, context, depth, AccountState::new(account_patch)) } /// Create a new runtime with the given states. pub fn with_states( patch: &'a P, context: Context, depth: usize, account_state: AccountState<'a, P::Account>, ) -> Self { let memory_limit = patch.memory_limit(); Machine { status: MachineStatus::Running, state: State { patch, memory: M::new(memory_limit), stack: Stack::default(), out: Rc::new(Vec::new()), ret: Rc::new(Vec::new()), memory_cost: Gas::zero(), used_gas: GasUsage::Some(Gas::zero()), refunded_gas: Gas::zero(), account_state, logs: Vec::new(), removed: Vec::new(), depth, position: 0, valids: Valids::new(context.code.as_slice()), context, }, } } /// Commit a new account into this runtime. pub fn commit_account(&mut self, commitment: AccountCommitment) -> Result<(), CommitError> { self.state.account_state.commit(commitment) } /// Step a precompiled runtime. This function returns true if the /// runtime is indeed a precompiled address. Otherwise return /// false with state unchanged. pub fn step_precompiled(&mut self) -> bool { for precompiled in self.state.patch.precompileds() { if self.state.context.callee == precompiled.0 && self .state .patch .is_precompiled_contract_enabled(&self.state.context.callee) && (precompiled.1.is_none() || precompiled.1.unwrap() == self.state.context.code.as_slice()) { let data = &self.state.context.data; match precompiled.2.gas_and_step(data, self.state.context.gas_limit) { Err(RuntimeError::OnChain(err)) => { reset_error_hard!(self, err); } Err(RuntimeError::NotSupported(err)) => { reset_error_not_supported!(self, err); } Ok((gas, ret)) => { assert!(gas <= self.state.context.gas_limit); self.state.used_gas = GasUsage::Some(gas); self.state.out = ret; self.status = MachineStatus::ExitedOk; } } return true; } } false } /// Peek the next instruction. pub fn peek(&self) -> Option<Instruction> { let pc = PC::<P>::new( &self.state.patch, &self.state.context.code, &self.state.valids, &self.state.position, ); match pc.peek() { Ok(val) => Some(val), Err(_) => None, } } /// Peek the next opcode. pub fn peek_opcode(&self) -> Option<Opcode> { let pc = PC::<P>::new( &self.state.patch, &self.state.context.code, &self.state.valids, &self.state.position, ); match pc.peek_opcode() { Ok(val) => Some(val), Err(_) => None, } } /// Step an instruction in the PC. The eval result is refected by /// the runtime status, and it will only return an error if /// there're accounts or blockhashes to be committed to this /// runtime for it to run. In that case, the state of the current /// runtime will not be affected. pub fn step(&mut self, runtime: &Runtime) -> Result<(), RequireError> { debug!("VM step started"); debug!("Code: {:x?}", &self.state.context.code[self.state.position..]); debug!("Stack: {:#x?}", self.state.stack); struct Precheck { position: usize, memory_cost: Gas, gas_cost: Gas, gas_stipend: Gas, gas_refund: isize, after_gas: Gas, } match &self.status { MachineStatus::Running => (), _ => panic!(), } if self.step_precompiled() { trace!("precompiled step succeeded"); return Ok(()); } let Precheck { position, memory_cost, gas_cost, gas_stipend, gas_refund, after_gas, } = { let pc = PC::<P>::new( &self.state.patch, &self.state.context.code, &self.state.valids, &self.state.position, ); if pc.is_end() { debug!("reached code EOF"); self.status = MachineStatus::ExitedOk; return Ok(()); } let instruction = match pc.peek() { Ok(val) => val, Err(err) => { reset_error_hard!(self, err); return Ok(()); } }; match check_opcode(instruction, &self.state, runtime).and_then(|v| match v { None => Ok(()), Some(ControlCheck::Jump(dest)) => { if dest <= M256::from(usize::max_value()) && pc.is_valid(dest.as_usize()) { Ok(()) } else { Err(OnChainError::BadJumpDest.into()) } } }) { Ok(()) => (), Err(EvalOnChainError::OnChain(error)) => { reset_error_hard!(self, error); return Ok(()); } Err(EvalOnChainError::Require(error)) => { return Err(error); } } if self.state.context.is_static { match check_static(instruction, &self.state, runtime) { Ok(()) => (), Err(EvalOnChainError::OnChain(error)) => { reset_error_hard!(self, error); return Ok(()); } Err(EvalOnChainError::Require(error)) => { return Err(error); } } } let used_gas = match self.state.used_gas { GasUsage::Some(gas) => gas, GasUsage::All => { reset_error_hard!(self, OnChainError::EmptyGas); return Ok(()); } }; let position = pc.position(); let memory_cost = memory_cost(instruction, &self.state); let memory_gas = memory_gas(memory_cost); let gas_cost = gas_cost::<M, P>(instruction, &self.state); let gas_stipend = gas_stipend(instruction, &self.state); let gas_refund = gas_refund(instruction, &self.state); let all_gas_cost = memory_gas + used_gas + gas_cost; if self.state.context.gas_limit < all_gas_cost { reset_error_hard!(self, OnChainError::EmptyGas); return Ok(()); } match check_support(instruction, &self.state) { Ok(()) => (), Err(err) => { reset_error_not_supported!(self, err); return Ok(()); } }; let after_gas = self.state.context.gas_limit - all_gas_cost; match extra_check_opcode::<M, P>(instruction, &self.state, gas_stipend, after_gas) { Ok(()) => (), Err(err) => { reset_error_hard!(self, err); return Ok(()); } } Precheck { position, memory_cost, gas_cost, gas_stipend, gas_refund, after_gas, } }; trace!("position: {}", position); trace!("memory_cost: {:x?}", memory_cost); trace!("gas_cost: {:x?}", gas_cost); trace!("gas_stipend: {:x?}", gas_stipend); trace!("gas_refund: {:x}", gas_refund); trace!("after_gas: {:x?}", after_gas); let instruction = PCMut::<P>::new( &self.state.patch, &self.state.context.code, &self.state.valids, &mut self.state.position, ) .read() .unwrap(); let result = run_opcode::<M, P>( (instruction, position), &mut self.state, runtime, gas_stipend, after_gas, ); self.state.used_gas += gas_cost - gas_stipend; self.state.memory_cost = memory_cost; self.state.refunded_gas = self.state.refunded_gas.add_refund(gas_refund);; debug!("{:?} => {:?}", instruction, result); debug!("gas used: {:x?}", self.state.total_used_gas()); debug!("gas left: {:x?}", self.state.available_gas()); match result { None => Ok(()), Some(Control::Jump(dest)) => { PCMut::<P>::new( &self.state.patch, &self.state.context.code, &self.state.valids, &mut self.state.position, ) .jump(dest.as_usize()) .unwrap(); Ok(()) } Some(Control::InvokeCall(context, (from, len))) => { self.status = MachineStatus::InvokeCall(context, (from, len)); Ok(()) } Some(Control::InvokeCreate(context)) => { self.status = MachineStatus::InvokeCreate(context); Ok(()) } Some(Control::Stop) => { self.status = MachineStatus::ExitedOk; Ok(()) } Some(Control::Revert) => { reset_error_revert!(self); Ok(()) } } } /// Get the runtime state. pub fn state(&self) -> &State<M, P> { &self.state } /// Take the runtime state pub fn take_state(self) -> State<'a, M, P> { self.state } /// Get the runtime PC. pub fn pc(&self) -> PC<P> { PC::new( &self.state.patch, &self.state.context.code, &self.state.valids, &self.state.position, ) } /// Get the current runtime status. pub fn status(&self) -> MachineStatus { self.status.clone() } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AddContactResult(pub i32); impl AddContactResult { pub const Added: AddContactResult = AddContactResult(0i32); pub const AlreadyAdded: AddContactResult = AddContactResult(1i32); pub const Unavailable: AddContactResult = AddContactResult(2i32); } impl ::core::convert::From<i32> for AddContactResult { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AddContactResult { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AddContactResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Contacts.Provider.AddContactResult;i4)"); } impl ::windows::core::DefaultType for AddContactResult { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ContactPickerUI(pub ::windows::core::IInspectable); impl ContactPickerUI { #[cfg(feature = "deprecated")] pub fn AddContact<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::Contact>>(&self, id: Param0, contact: Param1) -> ::windows::core::Result<AddContactResult> { let this = self; unsafe { let mut result__: AddContactResult = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), id.into_param().abi(), contact.into_param().abi(), &mut result__).from_abi::<AddContactResult>(result__) } } pub fn RemoveContact<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, id: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), id.into_param().abi()).ok() } } pub fn ContainsContact<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, id: Param0) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), id.into_param().abi(), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Collections")] pub fn DesiredFields(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } pub fn SelectionMode(&self) -> ::windows::core::Result<super::ContactSelectionMode> { let this = self; unsafe { let mut result__: super::ContactSelectionMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::ContactSelectionMode>(result__) } } #[cfg(feature = "Foundation")] pub fn ContactRemoved<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<ContactPickerUI, ContactRemovedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveContactRemoved<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } pub fn AddContact2<'a, Param0: ::windows::core::IntoParam<'a, super::Contact>>(&self, contact: Param0) -> ::windows::core::Result<AddContactResult> { let this = &::windows::core::Interface::cast::<IContactPickerUI2>(self)?; unsafe { let mut result__: AddContactResult = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), contact.into_param().abi(), &mut result__).from_abi::<AddContactResult>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn DesiredFieldsWithContactFieldType(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<super::ContactFieldType>> { let this = &::windows::core::Interface::cast::<IContactPickerUI2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<super::ContactFieldType>>(result__) } } } unsafe impl ::windows::core::RuntimeType for ContactPickerUI { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Contacts.Provider.ContactPickerUI;{e2cc1366-cf66-43c4-a96a-a5a112db4746})"); } unsafe impl ::windows::core::Interface for ContactPickerUI { type Vtable = IContactPickerUI_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe2cc1366_cf66_43c4_a96a_a5a112db4746); } impl ::windows::core::RuntimeName for ContactPickerUI { const NAME: &'static str = "Windows.ApplicationModel.Contacts.Provider.ContactPickerUI"; } impl ::core::convert::From<ContactPickerUI> for ::windows::core::IUnknown { fn from(value: ContactPickerUI) -> Self { value.0 .0 } } impl ::core::convert::From<&ContactPickerUI> for ::windows::core::IUnknown { fn from(value: &ContactPickerUI) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ContactPickerUI { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ContactPickerUI { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ContactPickerUI> for ::windows::core::IInspectable { fn from(value: ContactPickerUI) -> Self { value.0 } } impl ::core::convert::From<&ContactPickerUI> for ::windows::core::IInspectable { fn from(value: &ContactPickerUI) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ContactPickerUI { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ContactPickerUI { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ContactRemovedEventArgs(pub ::windows::core::IInspectable); impl ContactRemovedEventArgs { pub fn Id(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for ContactRemovedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Contacts.Provider.ContactRemovedEventArgs;{6f354338-3302-4d13-ad8d-adcc0ff9e47c})"); } unsafe impl ::windows::core::Interface for ContactRemovedEventArgs { type Vtable = IContactRemovedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6f354338_3302_4d13_ad8d_adcc0ff9e47c); } impl ::windows::core::RuntimeName for ContactRemovedEventArgs { const NAME: &'static str = "Windows.ApplicationModel.Contacts.Provider.ContactRemovedEventArgs"; } impl ::core::convert::From<ContactRemovedEventArgs> for ::windows::core::IUnknown { fn from(value: ContactRemovedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&ContactRemovedEventArgs> for ::windows::core::IUnknown { fn from(value: &ContactRemovedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ContactRemovedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ContactRemovedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ContactRemovedEventArgs> for ::windows::core::IInspectable { fn from(value: ContactRemovedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&ContactRemovedEventArgs> for ::windows::core::IInspectable { fn from(value: &ContactRemovedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ContactRemovedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ContactRemovedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(transparent)] #[doc(hidden)] pub struct IContactPickerUI(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IContactPickerUI { type Vtable = IContactPickerUI_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe2cc1366_cf66_43c4_a96a_a5a112db4746); } #[repr(C)] #[doc(hidden)] pub struct IContactPickerUI_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, contact: ::windows::core::RawPtr, result__: *mut AddContactResult) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::ContactSelectionMode) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IContactPickerUI2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IContactPickerUI2 { type Vtable = IContactPickerUI2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6e449e28_7b25_4999_9b0b_875400a1e8c8); } #[repr(C)] #[doc(hidden)] pub struct IContactPickerUI2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, contact: ::windows::core::RawPtr, result__: *mut AddContactResult) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IContactRemovedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IContactRemovedEventArgs { type Vtable = IContactRemovedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6f354338_3302_4d13_ad8d_adcc0ff9e47c); } #[repr(C)] #[doc(hidden)] pub struct IContactRemovedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, );
use h2; use http; use indexmap::IndexMap; use std::time::Instant; use proxy::Source; use transport::connect; // TODO this should be replaced with a string name. #[derive(Copy, Clone, Debug)] pub enum Direction { In, Out } #[derive(Clone, Debug)] pub struct Endpoint { pub direction: Direction, pub target: connect::Target, pub labels: IndexMap<String, String>, } #[derive(Clone, Debug)] pub struct Request { pub id: usize, pub source: Source, pub endpoint: Endpoint, pub method: http::Method, pub scheme: Option<http::uri::Scheme>, pub authority: Option<http::uri::Authority>, pub path: String, } #[derive(Clone, Debug)] pub struct Response { pub request: Request, pub status: http::StatusCode, } #[derive(Clone, Debug)] pub enum Event { StreamRequestOpen(Request), StreamRequestFail(Request, StreamRequestFail), StreamRequestEnd(Request, StreamRequestEnd), StreamResponseOpen(Response, StreamResponseOpen), StreamResponseFail(Response, StreamResponseFail), StreamResponseEnd(Response, StreamResponseEnd), } #[derive(Clone, Debug)] pub struct StreamRequestFail { pub request_open_at: Instant, pub request_fail_at: Instant, pub error: h2::Reason, } #[derive(Clone, Debug)] pub struct StreamRequestEnd { pub request_open_at: Instant, pub request_end_at: Instant, } #[derive(Clone, Debug)] pub struct StreamResponseOpen { pub request_open_at: Instant, pub response_open_at: Instant, } #[derive(Clone, Debug)] pub struct StreamResponseFail { pub request_open_at: Instant, pub response_open_at: Instant, pub response_first_frame_at: Option<Instant>, pub response_fail_at: Instant, pub error: h2::Reason, pub bytes_sent: u64, } #[derive(Clone, Debug)] pub struct StreamResponseEnd { pub request_open_at: Instant, pub response_open_at: Instant, pub response_first_frame_at: Instant, pub response_end_at: Instant, pub grpc_status: Option<u32>, pub bytes_sent: u64, }
use regex::Regex; use std::collections::{HashMap, HashSet}; use std::fs::read_to_string; use std::path::Path; fn count_outer_bags_for( input: HashMap<String, HashMap<String, usize>>, input_color: String, containers: &mut HashSet<String>, ) { let mut additional_color_containers = Vec::new(); for (color, bag_container) in &input { if bag_container.contains_key(&input_color) { containers.insert(color.clone()); additional_color_containers.push(color.to_string()) } } for additional_color in additional_color_containers.clone() { count_outer_bags_for(input.clone(), additional_color, containers); } } fn count_inner_bags_for( input: HashMap<String, HashMap<String, usize>>, input_color: String, ) -> usize { let mut all_count = 1; if let Some(bag_container) = input.clone().get(&input_color) { for (bag, count) in bag_container { all_count = all_count + count * count_inner_bags_for(input.clone(), bag.to_string()); } return all_count; } return all_count; } fn get_matches(input: String) -> HashMap<String, HashMap<String, usize>> { let mut output = HashMap::new(); let regex_all = Regex::new(r"([\w ]+)bags contain(( [0-9]+ [\w ]+ bags?,?)+)\.").unwrap(); let regex = Regex::new(r"([0-9]+) ([\w ]+) bags?,?").unwrap(); for line in input.lines() { for full_capture in regex_all.captures_iter(line) { let container_bag = full_capture[1].trim().to_string(); let what_it_contains = &full_capture[2].to_string(); let mut containing_bags = HashMap::<String, usize>::new(); for capture in regex.captures_iter(what_it_contains) { let count = capture[1].to_string(); let color = capture[2].to_string(); containing_bags.insert(color, count.parse::<usize>().unwrap()); } output.insert(container_bag, containing_bags); } } output } pub fn solve_puzzle(path: &Path) { let input = read_to_string(path).unwrap(); let res = get_matches(input); let mut count = HashSet::new(); count_outer_bags_for(res.clone(), "shiny gold".to_string(), &mut count); println!("container bags={}", count.len()); println!( "how many bags does the shinny bag need: {}", count_inner_bags_for(res, String::from("shiny gold")) - 1 ); }
use std::collections::vec_deque::VecDeque; use std::result as result; pub trait TimeMachineState { type Forward; type Reverse; fn apply_forward(&mut self, delta: &Self::Forward) -> Self::Reverse; fn apply_reverse(&mut self, delta: &Self::Reverse); } #[derive(Debug, PartialEq)] pub enum Error<T> { TimeEvicted(T, T) } pub type Result<D, T> = result::Result<D, Error<T>>; struct Timestamped<T, D> (T, D); pub struct TimeMachine<S, T> where S: TimeMachineState { current: S, reverse: VecDeque<Timestamped<T, (S::Forward, S::Reverse)>>, forward: Vec<Timestamped<T, S::Forward>>, oldest: Option<T> } impl <S, T> TimeMachine<S, T> where S: TimeMachineState, T: PartialOrd + Copy { pub fn new(initial: S) -> TimeMachine<S, T> { TimeMachine { current: initial, reverse: VecDeque::new(), forward: Vec::new(), oldest: None } } pub fn change(&mut self, delta: S::Forward, at: T) -> Result<(), T> { try!(self.check_oldest(at)); self.move_to(at); self.forward.push(Timestamped(at, delta)); Ok(()) } pub fn value_at(&mut self, at: T) -> Result<&S, T> { try!(self.check_oldest(at)); self.move_to(at); Ok(&self.current) } pub fn forget_ancient_history(&mut self, until: T) { self.move_forward_to(until); loop { match self.reverse.pop_front() { Some(Timestamped(time, delta)) => if time >= until { self.reverse.push_front(Timestamped(time, delta)); break; }, None => break } } self.oldest = Some(until); } fn check_oldest(&self, at: T) -> Result<(), T> { match self.oldest { Some(i) => if i > at { Err(Error::TimeEvicted(at, i)) } else { Ok(()) }, None => Ok(()) } } fn move_to(&mut self, at: T) { self.move_forward_to(at); self.move_backward_to(at); } fn move_backward_to(&mut self, at: T) { loop { match self.reverse.pop_back() { Some(Timestamped(time, (delta_f, delta_r))) => if time <= at { self.reverse.push_back(Timestamped(time, (delta_f, delta_r))); break; } else { self.current.apply_reverse(&delta_r); self.forward.push(Timestamped(time, delta_f)); }, None => break } } } fn move_forward_to(&mut self, at: T) { loop { match self.forward.pop() { Some(Timestamped(time, delta)) => if time > at { self.forward.push(Timestamped(time, delta)); break; } else { let new_delta = self.current.apply_forward(&delta); self.reverse.push_back(Timestamped(time, (delta, new_delta))); }, None => break } } } } #[cfg(test)] mod tests { use super::{Error, TimeMachine, TimeMachineState}; #[derive(Debug, PartialEq)] struct TestTimeMachineState(i32); enum TestTimeMachineDelta { Add(i32), Sub(i32), Mul(i32), Div(i32) } impl TestTimeMachineState { fn apply(&mut self, delta: &TestTimeMachineDelta) -> TestTimeMachineDelta { match *delta { TestTimeMachineDelta::Add(i) => { self.0 += i; TestTimeMachineDelta::Sub(i) }, TestTimeMachineDelta::Sub(i) => { self.0 -= i; TestTimeMachineDelta::Add(i) }, TestTimeMachineDelta::Mul(i) => { self.0 *= i; TestTimeMachineDelta::Div(i) }, TestTimeMachineDelta::Div(i) => { self.0 /= i; TestTimeMachineDelta::Mul(i) }, } } } impl TimeMachineState for TestTimeMachineState { type Forward = TestTimeMachineDelta; type Reverse = TestTimeMachineDelta; fn apply_forward(&mut self, delta: &TestTimeMachineDelta) -> TestTimeMachineDelta { self.apply(delta) } fn apply_reverse(&mut self, delta: &TestTimeMachineDelta) { self.apply(delta); } } type TestTimeMachine = TimeMachine<TestTimeMachineState, u32>; fn assert_machine_success(m: &mut TestTimeMachine, at: u32, expected: i32) { let result = m.value_at(at).unwrap(); assert_eq!(&TestTimeMachineState(expected), result); } fn assert_machine_failure(m: &mut TestTimeMachine, at: u32, expected: Error<u32>) { let result = m.value_at(at); assert_eq!(Some(expected), result.err()); } #[test] fn forward_change() { let mut m = TestTimeMachine::new(TestTimeMachineState(5)); m.change(TestTimeMachineDelta::Add(3), 1).unwrap(); assert_machine_success(&mut m, 1, 8); } #[test] fn rewind() { let mut m = TestTimeMachine::new(TestTimeMachineState(5)); m.change(TestTimeMachineDelta::Add(3), 1).unwrap(); assert_machine_success(&mut m, 0, 5); } #[test] fn move_around() { let mut m = TestTimeMachine::new(TestTimeMachineState(5)); m.change(TestTimeMachineDelta::Add(3), 1).unwrap(); m.change(TestTimeMachineDelta::Mul(4), 10).unwrap(); m.change(TestTimeMachineDelta::Sub(2), 11).unwrap(); m.change(TestTimeMachineDelta::Div(5), 20).unwrap(); assert_machine_success(&mut m, 25, 6); assert_machine_success(&mut m, 10, 32); assert_machine_success(&mut m, 0, 5); assert_machine_success(&mut m, 15, 30); assert_machine_success(&mut m, 11, 30); assert_machine_success(&mut m, 8, 8); assert_machine_success(&mut m, 1, 8); } #[test] fn change_in_middle() { let mut m = TestTimeMachine::new(TestTimeMachineState(5)); m.change(TestTimeMachineDelta::Add(3), 1).unwrap(); m.change(TestTimeMachineDelta::Add(5), 10).unwrap(); assert_machine_success(&mut m, 5, 8); assert_machine_success(&mut m, 10, 13); m.change(TestTimeMachineDelta::Mul(2), 5).unwrap(); assert_machine_success(&mut m, 5, 16); assert_machine_success(&mut m, 10, 21); } #[test] fn test_forget_ancient_history() { let mut m = TestTimeMachine::new(TestTimeMachineState(5)); m.change(TestTimeMachineDelta::Add(3), 1).unwrap(); m.change(TestTimeMachineDelta::Mul(2), 2).unwrap(); m.change(TestTimeMachineDelta::Add(2), 3).unwrap(); m.change(TestTimeMachineDelta::Sub(10), 4).unwrap(); m.forget_ancient_history(3); assert_machine_failure(&mut m, 1, Error::TimeEvicted(1, 3)); assert_machine_failure(&mut m, 2, Error::TimeEvicted(2, 3)); assert_machine_success(&mut m, 3, 18); assert_machine_success(&mut m, 4, 8); } }
// Port of https://www.rabbitmq.com/tutorials/tutorial-six-python.html. Start this // example in one shell, then the rpc_client example in another. use amiquip::{ AmqpProperties, Connection, ConsumerMessage, ConsumerOptions, Exchange, Publish, QueueDeclareOptions, Result, }; use serde_json::Value; fn fib(input_string: String) -> String { // Convert input string into JSON let input_JSON: Value = serde_json::from_str(&input_string).unwrap(); // Get arrays of each field as json Value object let ground_JSON = input_JSON["ground"].as_array().unwrap(); let skycolor_JSON = input_JSON["sky_color"].as_array().unwrap(); let lookfrom_JSON = input_JSON["lookfrom"].as_array().unwrap(); let lookat_JSON = input_JSON["lookat"].as_array().unwrap(); let vup_JSON = input_JSON["vup"].as_array().unwrap(); let sphere1_center_JSON = input_JSON["sphere1_center"].as_array().unwrap(); let sphere2_center_JSON = input_JSON["sphere2_center"].as_array().unwrap(); let sphere3_center_JSON = input_JSON["sphere3_center"].as_array().unwrap(); let sphere2_color_JSON = input_JSON["sphere2_color"].as_array().unwrap(); let sphere3_color_JSON = input_JSON["sphere3_color"].as_array().unwrap(); // Create mutable vectors let mut ground: Vec<f32> = Vec::new(); let mut skycolor: Vec<f32> = Vec::new(); let mut lookfrom: Vec<f32> = Vec::new(); let mut lookat: Vec<f32> = Vec::new(); let mut vup: Vec<f32> = Vec::new(); let mut sphere1_center: Vec<f32> = Vec::new(); let mut sphere2_center: Vec<f32> = Vec::new(); let mut sphere3_center: Vec<f32> = Vec::new(); let mut sphere2_color: Vec<f32> = Vec::new(); let mut sphere3_color: Vec<f32> = Vec::new(); let sphere1_radius: f32 = input_JSON["sphere1_radius"].as_f64().unwrap() as f32; let sphere2_radius: f32 = input_JSON["sphere2_radius"].as_f64().unwrap() as f32; let sphere3_radius: f32 = input_JSON["sphere3_radius"].as_f64().unwrap() as f32; // Fill mutable vectors with parsed values for g in ground_JSON { ground.push(g.as_f64().unwrap() as f32); } for s in skycolor_JSON { skycolor.push(s.as_f64().unwrap() as f32); } for l in lookfrom_JSON { lookfrom.push(l.as_f64().unwrap() as f32); } for l in lookat_JSON { lookat.push(l.as_f64().unwrap() as f32); } for v in vup_JSON { vup.push(v.as_f64().unwrap() as f32); } for s in sphere1_center_JSON { sphere1_center.push(s.as_f64().unwrap() as f32); } for s in sphere2_center_JSON { sphere2_center.push(s.as_f64().unwrap() as f32); } for s in sphere3_center_JSON { sphere3_center.push(s.as_f64().unwrap() as f32); } for s in sphere2_color_JSON { sphere2_color.push(s.as_f64().unwrap() as f32); } for s in sphere3_color_JSON { sphere3_color.push(s.as_f64().unwrap() as f32); } let scene = raytracer::Scene { ground, skycolor, sphere1_center, sphere1_radius, sphere2_center, sphere2_radius, sphere2_color, sphere3_center, sphere3_radius, sphere3_color, lookfrom, lookat, vup }; let output = raytracer::render(scene); return output; } fn main() -> Result<()> { //env_logger::init(); // Open connection. let mut connection = Connection::insecure_open("amqp://guest:guest@localhost:5672")?; // Open a channel - None says let the library choose the channel ID. let channel = connection.open_channel(None)?; // Get a handle to the default direct exchange. let exchange = Exchange::direct(&channel); // Declare the queue that will receive RPC requests. let queue = channel.queue_declare("rpc_queue", QueueDeclareOptions::default())?; // Start a consumer. let consumer = queue.consume(ConsumerOptions::default())?; println!("Awaiting RPC requests"); for (i, message) in consumer.receiver().iter().enumerate() { match message { ConsumerMessage::Delivery(delivery) => { let body = String::from_utf8_lossy(&delivery.body); println!("({:>3}) fib({})", i, body); let (reply_to, corr_id) = match ( delivery.properties.reply_to(), delivery.properties.correlation_id(), ) { (Some(r), Some(c)) => (r.clone(), c.clone()), _ => { println!("received delivery without reply_to or correlation_id"); consumer.ack(delivery)?; continue; } }; let response = match body.parse() { Ok(n) => format!("{}", fib(n)), Err(_) => "invalid input".to_string(), }; exchange.publish(Publish::with_properties( response.as_bytes(), reply_to, AmqpProperties::default().with_correlation_id(corr_id), ))?; consumer.ack(delivery)?; } other => { println!("Consumer ended: {:?}", other); break; } } } connection.close() }
use crate::{ commands::{ BasicCommand, BasicRetVal, CommandTrait, CommandUnion, CommandUnion as CU, ReturnValUnion, ReturnValUnion as RVU, WhichVariant, }, error::Unsupported, ApplicationMut, Error, Plugin, PluginType, WhichCommandRet, }; use abi_stable::std_types::{RBoxError, RResult, RStr, RString}; use serde::{Deserialize, Serialize}; /// Sends a json encoded command to a plugin,and returns the response by encoding it to json. /// /// # Errors /// /// These are all error that this function returns /// (this does not include error returned as part of the command): /// /// - Error::Serialize: /// If the command/return value could not be serialized to JSON. /// /// - Error::Deserialize /// If the command/return value could not be deserialized from JSON /// (this comes from the plugin). /// /// - Error::UnsupportedCommand /// If the command is not supported by the plugin. /// pub fn process_command<'de, P, C, R, F>( this: &mut P, command: RStr<'de>, f: F, ) -> RResult<RString, Error> where P: Plugin, F: FnOnce(&mut P, C) -> Result<R, Error>, C: Deserialize<'de>, R: Serialize, { (|| -> Result<RString, Error> { let command = command.as_str(); let which_variant = serde_json::from_str::<WhichVariant>(&command) .map_err(|e| Error::Deserialize(RBoxError::new(e), WhichCommandRet::Command))?; let command = serde_json::from_str::<CommandUnion<C>>(command).map_err(|e| { Error::unsupported_command(Unsupported { plugin_name: this.plugin_id().named.clone().into_owned(), command_name: which_variant.variant, error: RBoxError::new(e), supported_commands: this.list_commands(), }) })?; let ret: ReturnValUnion<R> = match command { CU::Basic(BasicCommand::GetCommands) => { let commands = this.list_commands(); RVU::Basic(BasicRetVal::GetCommands(commands)) } CU::ForPlugin(cmd) => RVU::ForPlugin(f(this, cmd)?), }; match serde_json::to_string(&ret) { Ok(v) => Ok(v.into()), Err(e) => Err(Error::Serialize(RBoxError::new(e), WhichCommandRet::Return)), } })() .into() } /// Sends a typed command to a plugin. /// /// # Errors /// /// These are all error that this function returns /// (this does not include error returned as part of the command): /// /// - Error::Serialize: /// If the command/return value could not be serialized to JSON. /// /// - Error::Deserialize /// If the command/return value could not be deserialized from JSON /// (this comes from the plugin). /// /// - Error::UnsupportedReturnValue: /// If the return value could not be deserialized from JSON /// (after checking that it has the `{"name":"...",description: ... }` format), /// containing the name of the command this is a return value for . /// /// - Error::UnsupportedCommand /// If the command is not supported by the plugin. /// pub fn send_command<C>( this: &mut PluginType, command: &C, app: ApplicationMut<'_>, ) -> Result<C::Returns, Error> where C: CommandTrait, { let cmd = serde_json::to_string(&command) .map_err(|e| Error::Serialize(RBoxError::new(e), WhichCommandRet::Command))?; let ret = this.json_command(RStr::from(&*cmd), app).into_result()?; let which_variant = serde_json::from_str::<WhichVariant>(&*ret) .map_err(|e| Error::Deserialize(RBoxError::new(e), WhichCommandRet::Return))?; serde_json::from_str::<C::Returns>(&ret).map_err(|e| { Error::unsupported_return_value(Unsupported { plugin_name: this.plugin_id().named.clone().into_owned(), command_name: which_variant.variant, error: RBoxError::new(e), supported_commands: this.list_commands(), }) }) }
/// Aborts processing of this action and unwinds all pending changes if the test condition is true #[inline] pub fn check(pred: bool, msg: &str) { if !pred { let msg_ptr = msg.as_ptr(); #[allow(clippy::cast_possible_truncation)] let msg_len = msg.len() as u32; unsafe { eosio_cdt_sys::eosio_assert_message(0, msg_ptr, msg_len) } } } /// Aborts processing of this action and unwinds all pending changes if the test condition is true #[inline] pub fn check_code<C>(pred: bool, code: C) where C: Into<u64>, { if !pred { unsafe { eosio_cdt_sys::eosio_assert_code(0, code.into()) } } } pub trait Check { type Output; fn check(self, msg: &str) -> Self::Output; } impl<T, E> Check for Result<T, E> { type Output = T; #[inline] fn check(self, msg: &str) -> Self::Output { if let Ok(t) = self { t } else { check(false, msg); unreachable!(); } } } impl<T> Check for Option<T> { type Output = T; #[inline] fn check(self, msg: &str) -> Self::Output { if let Some(t) = self { t } else { check(false, msg); unreachable!(); } } } impl Check for bool { type Output = Self; #[inline] fn check(self, msg: &str) -> Self::Output { check(self, msg); self } }
use super::{Array, Index, Length, Slice}; use crate::htab; use std::borrow::Borrow; use std::collections::hash_map::RandomState; use std::hash; use std::marker::PhantomData; struct Field<Q: ?Sized>(PhantomData<fn(&Q) -> &Q>); impl<K: Borrow<Q>, V, Q: ?Sized + Eq + hash::Hash> htab::Field<(K, V)> for Field<Q> { type Type = Q; #[inline] fn eq(c: &(K, V), v: &Q) -> bool { *c.0.borrow() == *v } #[inline] fn hash<S: hash::BuildHasher>(hs: &S, v: &Q) -> u64 { htab::hash(hs, v) } } #[derive(Clone)] pub struct IMap<I: Index, K, V, S = RandomState>(htab::HTab<(K, V), S>, PhantomData<fn() -> I>); pub enum IMapEntry<'a, I: Index, K, V, S> { Vacant(IMapVacant<'a, I, K, V, S>), Occupied(IMapOccupied<'a, I, K, V, S>), } pub struct IMapOccupied<'a, I: Index, K, V, S>( htab::Occupied<'a, (K, V), S>, PhantomData<fn() -> I>, ); pub struct IMapVacant<'a, I: Index, K, V, S>(htab::Vacant<'a, (K, V), S>, PhantomData<fn() -> I>); impl<'a, I: Index, K, V, S> IMapOccupied<'a, I, K, V, S> { #[inline] pub fn key(&self) -> &K { &self.0.get().0 } #[inline] pub fn value(&self) -> &V { &self.0.get().1 } #[inline] pub fn value_mut(&mut self) -> &mut V { &mut self.0.get_mut().1 } #[inline] pub fn index(&self) -> I { unsafe { I::from_usize_unchecked(self.0.index()) } } } impl<'a, I: Index, K: Eq + hash::Hash, V, S: hash::BuildHasher + Default> IMapVacant<'a, I, K, V, S> { #[inline] pub fn insert(self, k: K, v: V) -> IMapOccupied<'a, I, K, V, S> { let _ = I::from_usize(self.0.htab().len()); IMapOccupied(self.0.insert((k, v)), PhantomData) } } impl<I: Index, K, V, S: Default> IMap<I, K, V, S> { #[inline] pub fn new() -> Self { IMap(htab::HTab::new(), PhantomData) } } impl<I: Index, K, V, S: Default> Default for IMap<I, K, V, S> { #[inline(always)] fn default() -> Self { Self::new() } } impl<I: Index, K, V, S> IMap<I, K, V, S> { #[inline(always)] pub fn len(&self) -> Length<I> { Length::new(self.0.len()) } #[inline(always)] pub fn is_empty(&self) -> bool { self.0.is_empty() } #[inline(always)] pub fn pairs(&self) -> &Slice<I, (K, V)> { Slice::at(&*self.0.values()) } #[inline(always)] pub fn at(&self, i: I) -> &(K, V) { &self.pairs()[i] } #[inline(always)] pub fn into_pairs(self) -> Array<I, (K, V)> { Array::new_vec(self.0.into_values()) } } impl<I: Index, K: Eq + hash::Hash, V, S: hash::BuildHasher> IMap<I, K, V, S> { #[inline] pub fn get<'a, Q: ?Sized + Eq + hash::Hash>(&'a self, v: &Q) -> Option<I> where K: Borrow<Q>, { let i = self.0.find::<Field<Q>>(v)?.0; let i = unsafe { I::from_usize_unchecked(i) }; Some(i) } #[inline] pub fn find<Q: ?Sized + Eq + hash::Hash>(&self, k: &Q) -> Option<(I, &K, &V)> where K: Borrow<Q>, { let (i, v) = self.0.find::<Field<Q>>(k)?; let i = unsafe { I::from_usize_unchecked(i) }; Some((i, &v.0, &v.1)) } #[inline] pub fn entry<'a, Q: ?Sized + Eq + hash::Hash>(&'a mut self, k: &Q) -> IMapEntry<'a, I, K, V, S> where K: Borrow<Q>, { match self.0.entry::<Field<Q>>(k) { htab::Entry::Vacant(e) => IMapEntry::Vacant(IMapVacant(e, PhantomData)), htab::Entry::Occupied(e) => IMapEntry::Occupied(IMapOccupied(e, PhantomData)), } } } impl<I: Index, K: Eq + hash::Hash, V, S: hash::BuildHasher + Default> IMap<I, K, V, S> { #[inline] pub fn check_insert(&mut self, k: K, v: V) -> Result<I, I> { match self.entry(&k) { IMapEntry::Vacant(e) => Ok(e.insert(k, v).index()), IMapEntry::Occupied(e) => Err(e.index()), } } #[inline] pub fn check_clone_insert(&mut self, k: &K, v: V) -> Result<I, I> where K: Clone, { match self.entry(k) { IMapEntry::Vacant(e) => Ok(e.insert(k.clone(), v).index()), IMapEntry::Occupied(e) => Err(e.index()), } } #[inline] pub fn insert(&mut self, k: K, v: V) -> I { match self.check_insert(k, v) { Ok(i) => i, Err(i) => i, } } }
#![allow(unused_imports)] #![allow(dead_code)] use std::env; use std::fs; use std::thread; use std::path::Path; use std::str::from_utf8; use common::SOCKET_PATH; use sodiumoxide::crypto::box_; use std::collections::HashMap; use serde::{Serialize, Deserialize}; use std::io::{Read, Write, Error}; use std::sync::{Arc, Mutex, RwLock}; use std::os::unix::net::{UnixStream, UnixListener}; mod common; #[derive(Hash, Eq, PartialEq, Debug, Serialize, Deserialize)] struct SecretData { secret_key: String, public_key: String, } impl SecretData { fn new(secret: &str, public: &str) -> SecretData { SecretData { secret_key: secret.to_string(), public_key: public.to_string() } } } fn handle_client(mut stream: UnixStream, child_arc_keys_map: Arc<RwLock<HashMap<usize, SecretData>>>, id: &usize) -> Result<(), Error> { if let Ok(mut write_guard) = child_arc_keys_map.write() { write_guard.insert(*id, SecretData::new( "child secret stuff", "child public stuff")); println!("Write_guard val is {:?}", *write_guard); }; { // Example code related to sodium oxide thing let (ourpk, oursk) = box_::gen_keypair(); // normally theirpk is sent by the other party let (theirpk, theirsk) = box_::gen_keypair(); let nonce = box_::gen_nonce(); let plaintext = b"some data"; let ciphertext = box_::seal(plaintext, &nonce, &theirpk, &oursk); let their_plaintext = box_::open(&ciphertext, &nonce, &ourpk, &theirsk).unwrap(); assert!(plaintext == &their_plaintext[..]); } let mut buf = [0; 512]; loop { let bytes_read = stream.read(&mut buf)?; if bytes_read == 0 { return Ok(()) } stream.write(&buf[..bytes_read])?; } } fn main() { let socket = Path::new(SOCKET_PATH); let mut children = vec![]; // TODO change the hashmap type later once the protocol is decided. let keys_map: HashMap<usize, SecretData> = HashMap::new(); let arc_keys_map = Arc::new(RwLock::new(keys_map)); // Delete old socket if necessary if socket.exists() { fs::remove_file(&socket).unwrap(); } let mut id_gen: usize = 0; let listener = UnixListener::bind(&socket).unwrap(); for stream in listener.incoming() { // Returns a stream of incoming connections. // Iterating over this stream is equivalent to calling accept in a loop match stream { Ok(stream) => { println!("got connection request"); let child_arc_keys_map = arc_keys_map.clone(); // let child_id_gen = id_gen.clone(); id_gen += 1; // simple code will change this later children.push(thread::spawn(move || handle_client(stream, child_arc_keys_map, &id_gen))); } Err(err) => { println!("Error:{}", err); break; } } } for child in children { let _ = child.join(); } }
mod serde_types { pub mod registration { #[derive(Serialize,Deserialize,Clone,PartialEq,Debug)] pub struct ClientData { pub challenge: String, pub origin: String, pub typ: String, } } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[cfg(feature = "Management_Core")] pub mod Core; #[cfg(feature = "Management_Deployment")] pub mod Deployment; #[cfg(feature = "Management_Policies")] pub mod Policies; #[cfg(feature = "Management_Update")] pub mod Update; #[cfg(feature = "Management_Workplace")] pub mod Workplace; #[link(name = "windows")] extern "system" {} pub type MdmAlert = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct MdmAlertDataType(pub i32); impl MdmAlertDataType { pub const String: Self = Self(0i32); pub const Base64: Self = Self(1i32); pub const Boolean: Self = Self(2i32); pub const Integer: Self = Self(3i32); } impl ::core::marker::Copy for MdmAlertDataType {} impl ::core::clone::Clone for MdmAlertDataType { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct MdmAlertMark(pub i32); impl MdmAlertMark { pub const None: Self = Self(0i32); pub const Fatal: Self = Self(1i32); pub const Critical: Self = Self(2i32); pub const Warning: Self = Self(3i32); pub const Informational: Self = Self(4i32); } impl ::core::marker::Copy for MdmAlertMark {} impl ::core::clone::Clone for MdmAlertMark { fn clone(&self) -> Self { *self } } pub type MdmSession = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct MdmSessionState(pub i32); impl MdmSessionState { pub const NotStarted: Self = Self(0i32); pub const Starting: Self = Self(1i32); pub const Connecting: Self = Self(2i32); pub const Communicating: Self = Self(3i32); pub const AlertStatusAvailable: Self = Self(4i32); pub const Retrying: Self = Self(5i32); pub const Completed: Self = Self(6i32); } impl ::core::marker::Copy for MdmSessionState {} impl ::core::clone::Clone for MdmSessionState { fn clone(&self) -> Self { *self } }
use crate::{Error, Module, Trait}; use frame_support::debug; use num_bigint::BigUint; use num_traits::{One, Zero}; use rand::distributions::{Distribution, Uniform}; use rand_chacha::{ rand_core::{RngCore, SeedableRng}, ChaChaRng, }; use sp_std::{vec, vec::Vec}; /// all functions related to random value generation in the offchain worker impl<T: Trait> Module<T> { fn get_rng() -> ChaChaRng { // 32 byte array as random seed let seed: [u8; 32] = sp_io::offchain::random_seed(); ChaChaRng::from_seed(seed) } // Miller-Rabin Primality Test // https://en.wikipedia.org/wiki/Miller-Rabin_primality_test pub fn is_prime(num: &BigUint, certainty: u32) -> Result<bool, Error<T>> { let zero: BigUint = BigUint::zero(); let one: BigUint = BigUint::one(); let two = one.clone() + one.clone(); if *num == two { return Ok(true); } if num % two.clone() == zero { return Ok(false); } let num_less_one = num - one.clone(); // write n-12**s * d let mut d = num_less_one.clone(); let mut s: BigUint = Zero::zero(); while d.clone() % two.clone() == zero.clone() { d /= two.clone(); s += one.clone(); } let mut k = 0; // test for probable prime while k < certainty { let a = Self::get_random_bigunint_range(&two, num)?; let mut x = a.modpow(&d, num); if x != one.clone() && x != num_less_one { let mut random = zero.clone(); loop { x = x.modpow(&two, num); if x == num_less_one { break; } else if x == one.clone() || random == (s.clone() - one.clone()) { return Ok(false); } random += one.clone(); } } k += 2; } Ok(true) } /// secure random number generation using OS randomness pub fn get_random_bytes(size: usize) -> Result<Vec<u8>, Error<T>> { // use chacha20 to produce random vector [u8] of size: size let mut rng = Self::get_rng(); let mut bytes = vec![0; size]; // try to fill the byte array with random values let random_value_generation = rng.try_fill_bytes(&mut bytes); match random_value_generation { // if successful, returns the random bytes. Ok(_) => Ok(bytes), // else, that the randomness generation failed. Err(error) => { debug::error!("randomness generation error: {:?}", error); Err(Error::RandomnessGenerationError) } } } // generate a random value: 0 < random < number pub fn get_random_biguint_less_than(upper: &BigUint) -> Result<BigUint, Error<T>> { if *upper <= BigUint::zero() { return Err(Error::RandomnessUpperBoundZeroError); } // determine the upper bound for the random value let upper_bound: BigUint = upper.clone() - BigUint::one(); // the upper bound but in terms of bytes let size: usize = upper_bound.to_bytes_be().len(); // fill an array of size: <size> with random bytes let random_bytes: Vec<u8> = Self::get_random_bytes(size)?; // try to transform the byte array into a biguint let mut random = BigUint::from_bytes_be(&random_bytes); // ensure: random < number random %= upper; Ok(random) } // generate a number of random biguints: all 0 < random < number pub fn get_random_biguints_less_than( upper: &BigUint, size: usize, ) -> Result<Vec<BigUint>, Error<T>> { let mut randoms: Vec<BigUint> = Vec::new(); // try to fetch {size} random values < upper for _ in 0..size { let random: BigUint = Self::get_random_biguint_less_than(upper)?; randoms.push(random); } // if randoms is empty -> error occurred during get_random_biguint_less_than // since random cannot be pushed onto randoms, the list remains empty if randoms.is_empty() { Err(Error::RandomnessUpperBoundZeroError) } else { Ok(randoms) } } pub fn get_random_bigunint_range( lower: &BigUint, upper: &BigUint, ) -> Result<BigUint, Error<T>> { let mut rng = Self::get_rng(); Self::random_bigunint_range(&mut rng, lower, upper) } fn random_bigunint_range( rng: &mut ChaChaRng, lower: &BigUint, upper: &BigUint, ) -> Result<BigUint, Error<T>> { if *upper == BigUint::zero() { return Err(Error::RandomRangeError); } if *lower >= *upper { return Err(Error::RandomRangeError); } let uniform = Uniform::new(lower, upper); let value: BigUint = uniform.sample(rng); Ok(value) } pub fn get_random_range(lower: usize, upper: usize) -> Result<usize, Error<T>> { let mut rng = Self::get_rng(); Self::random_range(&mut rng, lower, upper) } fn random_range( rng: &mut ChaChaRng, lower: usize, upper: usize, ) -> Result<usize, Error<T>> { if upper == 0 { return Err(Error::RandomRangeError); } if lower >= upper { return Err(Error::RandomRangeError); } let uniform = Uniform::new(lower, upper); let value: usize = uniform.sample(rng); Ok(value) } pub fn generate_permutation(size: usize) -> Result<Vec<usize>, Error<T>> { if size == 0 { return Err(Error::PermutationSizeZeroError); } // vector containing the range of values from 0 up to the size of the vector - 1 let mut permutation: Vec<usize> = Vec::new(); let mut range: Vec<usize> = (0..size).collect(); let mut rng = Self::get_rng(); for index in 0..size { // get random integer let random: usize = Self::random_range(&mut rng, index, size)?; // get the element in the range at the random position let value = range.get(random).ok_or(Error::RandomRangeError)?; // store the value of the element at the random position permutation.push(*value); // swap positions range[random] = range[index]; } Ok(permutation) } pub fn permute_vector(input: Vec<BigUint>, permutation: &[usize]) -> Vec<BigUint> { let mut temp_ = Vec::new(); // permute the input vector // same order as permutation vector for j_i in permutation.iter() { let u_j_i = input[*j_i].clone(); temp_.push(u_j_i); } // ensure that both arrays have the same length // i.e. nothing went wrong assert_eq!(input.len(), temp_.len()); temp_ } }
use {Bathroom, BathroomLocation}; macro_rules! b_room { ( $num:expr, $loc:ident, [$($served:expr),*] ) => { Bathroom { number: $num, rooms: vec![$($served,)*], location: BathroomLocation::$loc, } } } lazy_static! { /// A list of all the bathrooms in Simmons. Data gracefully provided by Tim Wilczynski, Jesse /// Orlowski, Cosmos Darwin, and Will Oursler. pub static ref BATHROOMS: Vec<Bathroom<'static>> = vec![ b_room!(r!(244, "A"), InSuite, [r!(244, "B"), r!(244, "C")]), b_room!(r!(224, "C"), InSuite, [r!(224, "A"), r!(224, "B")]), b_room!(r!(228, "C"), InSuite, [r!(228, "A"), r!(228, "B")]), b_room!(r!(252, "A"), Interior, [r!(252)]), b_room!(r!(225, "A"), Interior, [r!(225)]), b_room!(r!(321, "A"), Interior, [r!(321)]), b_room!(r!(341, "A"), Interior, [r!(341)]), b_room!(r!(322, "A"), InSuite, [r!(322, "C"), r!(322, "D")]), b_room!(r!(322, "BA"), Interior, [r!(322, "B")]), b_room!(r!(325, "A"), Hallway, [r!(325), r!(324)]), b_room!(r!(345, "A"), Hallway, [r!(345), r!(344)]), b_room!(r!(326, "A"), Interior, [r!(326)]), b_room!(r!(327, "A"), Hallway, [r!(327)]), b_room!(r!(328, "A"), Interior, [r!(328)]), b_room!(r!(329, "A"), Hallway, [r!(329), r!(330)]), b_room!(r!(372, "A"), Hallway, [r!(371), r!(372)]), b_room!(r!(373, "A"), Hallway, [r!(373), r!(374), r!(375)]), b_room!(r!(337, "A"), Interior, [r!(337)]), b_room!(r!(378, "A"), Hallway, [r!(376), r!(377), r!(378)]), b_room!(r!(340, "AA"), Interior, [r!(340, "A")]), b_room!(r!(340, "BA"), Interior, [r!(340, "B")]), b_room!(r!(379, "C"), InSuite, [r!(379, "B"), r!(379, "A")]), b_room!(r!(381, "A"), Hallway, [r!(381), r!(380)]), b_room!(r!(421, "A"), InSuite, [r!(421, "B"), r!(421, "C")]), b_room!(r!(422, "A"), InSuite, [r!(422, "B"), r!(422, "C")]), b_room!(r!(424, "C"), InSuite, [r!(424, "B"), r!(424, "A")]), b_room!(r!(427, "A"), Hallway, [r!(426), r!(427)]), b_room!(r!(446, "A"), Hallway, [r!(446)]), b_room!(r!(447, "A"), Hallway, [r!(447), r!(448)]), b_room!(r!(428, "A"), Hallway, [r!(428), r!(429)]), b_room!(r!(450, "A"), Interior, [r!(450)]), b_room!(r!(451, "A"), Hallway, [r!(451), r!(452)]), b_room!(r!(464, "A"), Interior, [r!(464)]), b_room!(r!(465, "A"), Hallway, [r!(465), r!(466)]), b_room!(r!(433, "A"), Interior, [r!(433)]), b_room!(r!(467, "A"), Interior, [r!(467)]), b_room!(r!(473, "A"), Hallway, [r!(473), r!(474), r!(475)]), b_room!(r!(472, "A"), Interior, [r!(472)]), b_room!(r!(438, "A"), Interior, [r!(438)]), b_room!(r!(440, "A"), Interior, [r!(440)]), b_room!(r!(479, "C"), InSuite, [r!(479, "A"), r!(479, "B")]), b_room!(r!(478, "A"), Hallway, [r!(476), r!(477), r!(478)]), b_room!(r!(522, "A"), InSuite, [r!(522, "B"), r!(522, "C")]), b_room!(r!(521, "A"), InSuite, [r!(521, "B"), r!(521, "C")]), b_room!(r!(545, "A"), Hallway, [r!(543), r!(544), r!(545)]), b_room!(r!(525, "A"), Hallway, [r!(524), r!(525)]), b_room!(r!(548, "A"), Hallway, [r!(548)]), b_room!(r!(527, "A"), Hallway, [r!(526), r!(527)]), b_room!(r!(549, "C"), InSuite, [r!(549, "B"), r!(549, "A")]), b_room!(r!(551, "A"), Hallway, [r!(550), r!(551)]), b_room!(r!(552, "A"), Hallway, [r!(552), r!(553)]), b_room!(r!(564, "A"), Interior, [r!(564)]), b_room!(r!(532, "A"), Interior, [r!(532)]), b_room!(r!(565, "A"), Hallway, [r!(565), r!(566)]), b_room!(r!(535, "B"), Hallway, [r!(534), r!(535)]), b_room!(r!(533, "A"), Hallway, [r!(533)]), b_room!(r!(571, "A"), Hallway, [r!(569), r!(570), r!(571)]), b_room!(r!(572, "C"), InSuite, [r!(572, "A"), r!(572, "B")]), b_room!(r!(574, "A"), Hallway, [r!(573), r!(574)]), b_room!(r!(537, "A"), Hallway, [r!(537), r!(538)]), b_room!(r!(575, "A"), Interior, [r!(575)]), b_room!(r!(540, "A"), Hallway, [r!(539), r!(540)]), b_room!(r!(577, "A"), Hallway, [r!(577)]), b_room!(r!(578, "C"), InSuite, [r!(578, "A"), r!(578, "B")]), b_room!(r!(644, "A"), Hallway, [r!(643), r!(644)]), b_room!(r!(624, "C"), InSuite, [r!(624, "A"), r!(624, "B")]), b_room!(r!(645, "C"), InSuite, [r!(645, "B"), r!(645, "A")]), b_room!(r!(648, "A"), Hallway, [r!(647), r!(648)]), b_room!(r!(649, "A"), Hallway, [r!(649), r!(650)]), b_room!(r!(626, "A"), Hallway, [r!(625), r!(626)]), b_room!(r!(627, "A"), Hallway, [r!(627)]), b_room!(r!(628, "A"), Hallway, [r!(628), r!(629)]), b_room!(r!(652, "A"), Hallway, [r!(652), r!(653)]), b_room!(r!(664, "A"), Interior, [r!(664)]), b_room!(r!(631, "A"), Hallway, [r!(631, "B"), r!(631, "C"), r!(631, "D")]), b_room!(r!(665, "A"), Hallway, [r!(665), r!(667)]), b_room!(r!(633, "A"), Hallway, [r!(632), r!(633)]), b_room!(r!(634, "A"), Interior, [r!(634)]), b_room!(r!(635, "A"), Interior, [r!(635)]), b_room!(r!(670, "A"), Interior, [r!(670)]), b_room!(r!(674, "A"), Hallway, [r!(672), r!(673), r!(674)]), b_room!(r!(636, "A"), Hallway, [r!(636), r!(637), r!(638)]), b_room!(r!(675, "A"), Hallway, [r!(675)]), b_room!(r!(640, "A"), Hallway, [r!(639), r!(640)]), b_room!(r!(678, "A"), Interior, [r!(678)]), b_room!(r!(721, "A"), Interior, [r!(721)]), b_room!(r!(741, "C"), InSuite, [r!(741, "A"), r!(741, "B")]), b_room!(r!(725, "A"), Hallway, [r!(724), r!(725)]), b_room!(r!(743, "A"), Hallway, [r!(743), r!(744)]), b_room!(r!(747, "A"), Hallway, [r!(746), r!(747)]), b_room!(r!(748, "D"), InSuite, [r!(748, "B"), r!(748, "C")]), b_room!(r!(727, "A"), Hallway, [r!(727)]), b_room!(r!(728, "A"), Hallway, [r!(728), r!(729)]), b_room!(r!(730, "A"), Hallway, [r!(730), r!(731)]), b_room!(r!(732, "A"), Interior, [r!(732)]), b_room!(r!(733, "A"), Hallway, [r!(733)]), b_room!(r!(738, "A"), InSuite, [r!(738, "B"), r!(738, "C")]), b_room!(r!(775, "A"), Hallway, [r!(775), r!(776)]), b_room!(r!(740, "A"), Hallway, [r!(739), r!(740)]), b_room!(r!(778, "A"), Hallway, [r!(778), r!(779)]), b_room!(r!(780, "A"), Interior, [r!(780)]), b_room!(r!(821, "A"), Interior, [r!(821)]), b_room!(r!(824, "A"), Hallway, [r!(824), r!(825)]), b_room!(r!(846, "A"), Hallway, [r!(846)]), b_room!(r!(832, "A"), Interior, [r!(832)]), b_room!(r!(833, "A"), Hallway, [r!(833)]), b_room!(r!(865, "A"), Hallway, [r!(865), r!(866)]), b_room!(r!(872, "A"), Hallway, [r!(871), r!(872)]), b_room!(r!(873, "A"), Hallway, [r!(873), r!(874), r!(875)]), b_room!(r!(840, "A"), Hallway, [r!(839), r!(840)]), b_room!(r!(878, "A"), Interior, [r!(878)]), b_room!(r!(921, "BA"), Interior, [r!(921, "B")]), b_room!(r!(921, "A"), InSuite, [r!(921, "C")]), b_room!(r!(922, "A"), InSuite, [r!(922, "C"), r!(922, "D")]), b_room!(r!(924, "A"), Hallway, [r!(924), r!(925)]), b_room!(r!(945, "A"), Hallway, [r!(945), r!(946)]), b_room!(r!(931, "A"), Interior, [r!(931)]), b_room!(r!(932, "A"), Interior, [r!(932)]), b_room!(r!(933, "A"), Hallway, [r!(933)]), b_room!(r!(936, "A"), Hallway, [r!(936)]), b_room!(r!(965), Hallway, [r!(966)]), b_room!(r!(971, "A"), Hallway, [r!(971), r!(972)]), b_room!(r!(938, "A"), Interior, [r!(938)]), b_room!(r!(939, "A"), Interior, [r!(939)]), b_room!(r!(940, "AA"), Interior, [r!(940)]), b_room!(r!(941, "A"), Interior, [r!(941)]), b_room!(r!(973, "A"), Hallway, [r!(973), r!(974), r!(975)]), b_room!(r!(977, "A"), Hallway, [r!(976), r!(977)]), b_room!(r!(978, "A"), Hallway, [r!(978), r!(979)]), b_room!(r!(1021, "B"), InSuite, [r!(1021, "A"), r!(1021, "D")]), b_room!(r!(1021, "B"), InSuite, [r!(1021, "A"), r!(1021, "D")]), b_room!(r!(1021, "CA"), Interior, [r!(1021, "C")]), b_room!(r!(1022, "A"), InSuite, [r!(1022, "B"), r!(1022, "C")]), b_room!(r!(1024, "A"), Hallway, [r!(1024), r!(1025)]), b_room!(r!(1044, "A"), Hallway, [r!(1043), r!(1044)]), b_room!(r!(1045, "A"), Hallway, [r!(1045), r!(1046)]), b_room!(r!(1031, "A"), InSuite, [r!(1031, "B"), r!(1031, "C")]), b_room!(r!(1032, "A"), Interior, [r!(1032)]), b_room!(r!(1033, "A"), Hallway, [r!(1033), r!(1034)]), b_room!(r!(1036, "A"), Hallway, [r!(1036)]), b_room!(r!(1052, "C"), InSuite, [r!(1052, "A"), r!(1052, "B")]), b_room!(r!(1064, "A"), Hallway, [r!(1064), r!(1065)]), b_room!(r!(1066, "A"), Interior, [r!(1066)]), b_room!(r!(1072, "A"), Interior, [r!(1072)]), b_room!(r!(1038, "A"), Interior, [r!(1038)]), b_room!(r!(1039, "A"), Interior, [r!(1039)]), b_room!(r!(1040, "AA"), Interior, [r!(1040)]), b_room!(r!(1073, "A"), Hallway, [r!(1073), r!(1074)]), b_room!(r!(1077, "A"), Hallway, [r!(1075), r!(1076), r!(1077)]), b_room!(r!(1078, "C"), InSuite, [r!(1078, "A"), r!(1078, "B")]), ]; }
use std::io::{self, BufRead, BufReader, Read}; use bytes::buf::ext::BufExt; use bytes::Bytes; use flate2::bufread::ZlibDecoder; use crate::object::parse::ParseObjectError; use crate::object::{ObjectData, ObjectHeader}; use crate::parse; pub struct ObjectReader { header: Option<ObjectHeader>, reader: ZlibDecoder<ReaderKind>, } enum ReaderKind { File(BufReader<fs_err::File>), Bytes(bytes::buf::ext::Reader<Bytes>), } impl ObjectReader { pub(in crate::object) fn from_file( header: impl Into<Option<ObjectHeader>>, file: fs_err::File, ) -> Self { ObjectReader { header: header.into(), reader: ZlibDecoder::new(ReaderKind::File(BufReader::new(file))), } } pub(in crate::object) fn from_bytes( header: impl Into<Option<ObjectHeader>>, bytes: Bytes, ) -> Self { ObjectReader { header: header.into(), reader: ZlibDecoder::new(ReaderKind::Bytes(bytes.reader())), } } pub fn reader(&mut self) -> &mut impl Read { &mut self.reader } pub(in crate::object) fn parse(self) -> Result<ObjectData, ParseObjectError> { let mut buffer = parse::Buffer::new(self.reader); let header = match self.header { Some(header) => header, None => buffer.read_object_header()?, }; buffer.read_object_body(header) } } impl Read for ReaderKind { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match self { ReaderKind::File(file) => file.read(buf), ReaderKind::Bytes(bytes) => bytes.read(buf), } } } impl BufRead for ReaderKind { fn fill_buf(&mut self) -> io::Result<&[u8]> { match self { ReaderKind::File(file) => file.fill_buf(), ReaderKind::Bytes(bytes) => bytes.fill_buf(), } } fn consume(&mut self, amt: usize) { match self { ReaderKind::File(file) => file.consume(amt), ReaderKind::Bytes(bytes) => bytes.consume(amt), } } }
//! The module containing the connection pool task and related code. //! //! The connection pool task maintains the current pool of active client //! connections, allowing responses to be broadcast to all active connections. #![experimental] use std::collections::hash_map::{ HashMap, IterMut }; use std::io::stderr; use std::io::net::tcp::{ TcpAcceptor, TcpStream }; use std::io::net::ip::SocketAddr; use std::sync::mpsc::{ Receiver, Sender }; use proto::message::Message; use server::ctl::{ Request, Response }; /// A request for the connection pool to do something with its connections. pub enum Action { /// Requests that a connection be registered with the connection pool. Add(SocketAddr, TcpStream), /// Requests that a connection be removed from the connection pool. Remove(SocketAddr) } /// The connection pool task. /// /// ## Parameters /// /// * `request_tx` - A channel on which requests (Hi and Bye) can be sent. /// * `response_rx` - A channel on which responses from the outside world /// arrive. /// * `paction_rx` - A channel on which connection adds/removes are announced. /// * `acceptor` - A clone of the server's TCP acceptor, used to shut down /// the acceptor if a Quit response is given. pub fn task(request_tx: Sender<Request>, response_rx: Receiver<Response>, paction_rx: Receiver<Action>, acceptor: &mut TcpAcceptor) { let mut pool = HashMap::new(); 'l: loop { select! { action = paction_rx.recv() => match action { Ok(Action::Add(peer, sock)) => { // First, pool the connection. pool.insert(peer.clone(), sock); // Then, let the outside world know, so it can do things // like greeting the new connection. let _ = request_tx.send(Request::Hi(peer)); }, Ok(Action::Remove(peer)) => { // First, let the outside world know the connection is // going away. let _ = request_tx.send(Request::Bye(peer.clone())); // Then, actually depool it. pool.remove(&peer); }, Err(e) => { werr!("Error on action recv: {:?}\n", e); break 'l; } }, response = response_rx.recv() => match response { Ok(Response::Broadcast(msg)) => broadc(&mut pool.iter_mut(), msg), Ok(Response::Unicast(id, msg)) => unic(id, pool.get_mut(&id), msg), Ok(Response::Quit) => break 'l, Err(e) => { werr!("Error on response recv: {:?}\n", e); break 'l; } } } } werr!("server: pool closing...\n"); // If we get here, the server has been told to quit, or should quit anyway. // We now need to bring about the downfall of the entire server. // First, tell the acceptor to stop accepting new connections: let _ = acceptor.close_accept(); // Next, kill the action channel, so the acceptor cannot try to pool any // connections it may still be thinking of sending: drop(paction_rx); // Last, end all remaining connections: for ( _, connection ) in pool.iter_mut() { let _ = connection.close_read(); let _ = connection.close_write(); } // That should do it. werr!("server: pool closed\n"); } // Sends a message to all pooled connections. fn broadc(pool: &mut IterMut<SocketAddr, TcpStream>, msg: Message) { for (peer, connection) in *pool { werr!("server: broadcast =>{}: {}\n", peer, &*msg.pack()); let ml : &str = &*msg.pack(); if let Err(e) = connection.write_line(ml){ werr!("server: couldn't broadcast to {}: {}", peer, e); }; } } // Sends a message to precisely one, named, connection. fn unic(peer: SocketAddr, connection: Option<&mut TcpStream>, msg: Message) { match connection { Some(w) => if let Err(e) = w.write_line(&*msg.pack()) { werr!("server: couldn't send to {}: {}\n", peer, e); }, None => { werr!("server: no such connection: {}\n", peer); } } }
use glutin_window::GlutinWindow; use opengl_graphics::{GlGraphics, OpenGL}; use piston::event_loop::{EventSettings, Events}; use piston::RenderEvent; use crate::scene::Scene; pub struct Program { window: GlutinWindow, scene: Scene, events: Events // gl: GlGraphics } impl Program { pub fn new(w : GlutinWindow) -> Program { Program { window: w, scene: Scene::new(), events: Events::new(EventSettings::new()), // gl: GlGraphics::new(opengl) } } pub fn run(&mut self, mut gl : GlGraphics) -> bool { while let Some(e) = self.events.next(&mut self.window) { if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, g| { use graphics::clear; clear([1.0; 4], g); self.scene.draw(&c, g); }); } } true } }
/* A struct containing syntax errors */ pub struct errors{ missingCaret: "error: expected '^' at the end of the line", misplacedCaret: "error: move '^' to the end of the line", missingVariable: "error: expected variable name after identifier (Ashari,Harf,Sahih)", missingValue: "error: expected a value after '='", missingCommaOrEqual: "error: expected ',' or '=' between variable names", missingComma: "error: expected ',' between variable names", missingOperator: "error: expected one of these 7 tokens: {Jam , Kam, Zarb, Tagsim, Bagimonde, YekiBala, YekiPain , =}", noArgBenevis: "error: missing an argument for Benevis \n Insert the argument to be printed between ()", noArgBegir: "error: missing arguments for Begir \n Use '%d' , '%c' or '%f' and a variable name to store input", wrongArBegir: "error: wrong arguments for Begir \n Use '%d' , '%c' or '%f' and a variable name to store input", noConditionAndBlockAgar: "error: agar has no condition and no blocks", noConditionAgar: "error: agar has no condition", noBlockAgar: "error: agar has no blocks", wrongConditionParanthesisAgar: "error: expected {condition} after agar", noConditionAndBlockTa: "error: ta has no condition and no blocks", noConditionTa: "error: ta has no condition", noBlockTa: "error: ta has no blocks", wrongConditionParanthesisTa: "error: expected {condition} after ta", wrongBlockParanthesis: "error: expected [statement] after condition", wrongComparison: "error: expected two values to compare", noVariableYekiBala: "error: expected a variable name after YekiBala", noVariableYekiPain: "error: expected a variable name after YekiPain" }
use coffee::{graphics::*, load::Task, Game, Result, Timer}; fn main() -> Result<()> { MainGame::run(WindowSettings { title: String::from("coffee_issue"), size: (1280, 1024), resizable: true, fullscreen: false, }) } struct MainGame; impl Game for MainGame { type Input = (); type LoadingScreen = (); fn load(_window: &Window) -> Task<MainGame> { Task::succeed(|| MainGame) } fn draw(&mut self, frame: &mut Frame, _timer: &Timer) { frame.clear(Color::BLACK); } }
// 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. #![allow(clippy::uninlined_format_args)] #![feature(no_sanitize)] /// Config mods provide config support. /// /// We are providing two config types: /// /// - [`config::Config`] represents the options from command line , configuration files or environment vars. /// - [`inner::InnerConfig`] "internal representation" of application settings, built from Config. /// - [`global::GlobalConfig`] A global singleton of [`crate::InnerConfig`]. /// /// It's safe to refactor [`inner::InnerConfig`] in anyway, as long as it satisfied the following traits /// /// - `TryInto<inner::InnerConfig> for config::Config` /// - `From<inner::InnerConfig> for config::Config` mod config; mod global; mod inner; mod mask; mod obsolete; mod version; pub use config::CacheStorageTypeConfig; pub use config::Config; pub use config::QueryConfig; pub use config::StorageConfig; pub use global::GlobalConfig; pub use inner::CacheConfig; pub use inner::CacheStorageTypeConfig as CacheStorageTypeInnerConfig; pub use inner::CatalogConfig; pub use inner::CatalogHiveConfig; pub use inner::InnerConfig; pub use inner::ThriftProtocol; pub use version::DATABEND_COMMIT_VERSION; pub use version::QUERY_SEMVER;
use gl::types::*; pub enum Primitive { Byte, Short, UShort, Int, UInt, Float, Double, Nothing } impl Primitive { pub fn value(&self) -> GLenum { match self { Primitive::Byte => gl::BYTE, Primitive::Short => gl::SHORT, Primitive::UShort => gl::UNSIGNED_SHORT, Primitive::Int => gl::INT, Primitive::UInt => gl::UNSIGNED_INT, Primitive::Float => gl::FLOAT, Primitive::Double => gl::DOUBLE, Primitive::Nothing => unimplemented!() } } pub fn size(&self) -> GLuint { let size = match self { Primitive::Byte => std::mem::size_of::<u8>(), Primitive::Short => std::mem::size_of::<i16>(), Primitive::UShort => std::mem::size_of::<u16>(), Primitive::Int => std::mem::size_of::<i32>(), Primitive::UInt => std::mem::size_of::<u32>(), Primitive::Float => std::mem::size_of::<f32>(), Primitive::Double => std::mem::size_of::<f64>(), Primitive::Nothing => 1 }; size as GLuint } }
/// Contains constants that the user might want to modify. /// The prompt that appears at the beginning of the insert box when in insert mode. pub const ADD_PROMPT: &str = "Add: >"; /// Keep ADD_PROMPT_LEN up to date to ensure proper cursor positioning in insert mode. pub const ADD_PROMPT_LEN: u16 = 6; /// Column width for the "Time" columns of relevant panes. You may want to adjust this according /// to the format used for printing times in the interface. pub const COL_TIME_WIDTH: u16 = 12; /// File into which to backup events during every session. Point the constant to an empty &str to /// disable backups. pub const FILEPATH_BACKUP: &str = "/home/ty/code/clamendar/events.json.bak"; /// File to use for de/serialization. Must be an absolute path, I think. pub const FILEPATH: &str = "/home/ty/code/clamendar/events.json"; /// Preferred output Year, Month, Day format for printing only the date. pub const YMD: &str = "%m-%d"; /// Preferred output Year, Month, Day, Hour, Minute format for printing the date and time. pub const YMDHM: &str = "%m-%d %R";
use lazy_static::lazy_static; lazy_static! { static ref PAGE_SIZE: usize = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }; } lazy_static! { static ref NUM_CPUS: usize = get_num_cpus(); } #[inline] pub fn page_size() -> usize { *PAGE_SIZE } #[inline] pub fn num_cpus() -> usize { *NUM_CPUS } #[cfg(any( target_os = "freebsd", target_os = "dragonfly", target_os = "bitrig", target_os = "netbsd" ))] fn get_num_cpus() -> usize { use core::mem; let mut cpus: libc::c_uint = 0; let mut cpus_size = mem::size_of_val(&cpus); unsafe { cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint; } if cpus < 1 { let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0]; unsafe { libc::sysctl( mib.as_mut_ptr(), 2, &mut cpus as *mut _ as *mut _, &mut cpus_size as *mut _ as *mut _, 0 as *mut _, 0, ); } if cpus < 1 { cpus = 1; } } cpus as usize } #[cfg(target_os = "openbsd")] fn get_num_cpus() -> usize { use core::mem; let mut cpus: libc::c_uint = 0; let mut cpus_size = mem::size_of_val(&cpus); let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0]; unsafe { libc::sysctl( mib.as_mut_ptr(), 2, &mut cpus as *mut _ as *mut _, &mut cpus_size as *mut _ as *mut _, 0 as *mut _, 0, ); } if cpus < 1 { cpus = 1; } cpus as usize } #[cfg(target_os = "linux")] fn get_num_cpus() -> usize { use core::mem; let mut set: libc::cpu_set_t = unsafe { mem::zeroed() }; if unsafe { libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) } == 0 { let mut count: u32 = 0; for i in 0..libc::CPU_SETSIZE as usize { if unsafe { libc::CPU_ISSET(i, &set) } { count += 1 } } count as usize } else { let cpus = unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) }; if cpus < 1 { 1 } else { cpus as usize } } } #[cfg(any( target_os = "nacl", target_os = "macos", target_os = "ios", target_os = "android", target_os = "solaris", target_os = "illumos", target_os = "fuchsia" ))] fn get_num_cpus() -> usize { // On ARM targets, processors could be turned off to save power. // Use `_SC_NPROCESSORS_CONF` to get the real number. #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] const CONF_NAME: libc::c_int = libc::_SC_NPROCESSORS_CONF; #[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))] const CONF_NAME: libc::c_int = libc::_SC_NPROCESSORS_ONLN; let cpus = unsafe { libc::sysconf(CONF_NAME) }; if cpus < 1 { 1 } else { cpus as usize } } #[cfg(not(any( target_os = "nacl", target_os = "macos", target_os = "ios", target_os = "android", target_os = "solaris", target_os = "illumos", target_os = "fuchsia", target_os = "linux", target_os = "openbsd", target_os = "freebsd", target_os = "dragonfly", target_os = "bitrig", target_os = "netbsd", )))] const fn get_num_cpus() -> usize { 1 }
use table; mod lib; use std::io; fn main() { println!("Enter number"); let mut input=String::new(); io::stdin().read_line(&mut input).expect("Fail to read"); let data:u32=input.trim().parse().expect("Fail to read"); print_table::sub_mod::table(data); lib::lib_table::lib_sub_mod::table(data); table::lib_package_table::lib_package_sub_mod::table(data); } mod print_table{ pub mod sub_mod{ pub fn table(data:u32) { for value in 1..=10 { println!{"{} x {} = {}",data,value,data*value}; } } } }
//! How to load new cache entries. use async_trait::async_trait; use std::{fmt::Debug, future::Future, hash::Hash, marker::PhantomData, sync::Arc}; pub mod batch; pub mod metrics; #[cfg(test)] pub(crate) mod test_util; /// Loader for missing [`Cache`](crate::cache::Cache) entries. #[async_trait] pub trait Loader: std::fmt::Debug + Send + Sync + 'static { /// Cache key. type K: Debug + Hash + Send + 'static; /// Extra data needed when loading a missing entry. Specify `()` if not needed. type Extra: Debug + Send + 'static; /// Cache value. type V: Debug + Send + 'static; /// Load value for given key, using the extra data if needed. async fn load(&self, k: Self::K, extra: Self::Extra) -> Self::V; } #[async_trait] impl<K, V, Extra> Loader for Box<dyn Loader<K = K, V = V, Extra = Extra>> where K: Debug + Hash + Send + 'static, V: Debug + Send + 'static, Extra: Debug + Send + 'static, { type K = K; type V = V; type Extra = Extra; async fn load(&self, k: Self::K, extra: Self::Extra) -> Self::V { self.as_ref().load(k, extra).await } } #[async_trait] impl<K, V, Extra, L> Loader for Arc<L> where K: Debug + Hash + Send + 'static, V: Debug + Send + 'static, Extra: Debug + Send + 'static, L: Loader<K = K, V = V, Extra = Extra>, { type K = K; type V = V; type Extra = Extra; async fn load(&self, k: Self::K, extra: Self::Extra) -> Self::V { self.as_ref().load(k, extra).await } } /// Simple-to-use wrapper for async functions to act as a [`Loader`]. /// /// # Typing /// Semantically this wrapper has only one degree of freedom: `T`, which is the async loader function. However until /// [`fn_traits`] are stable, there is no way to extract the parameters and return value from a function via associated /// types. So we need to add additional type parametes for the special `Fn(...) -> ...` handling. /// /// It is likely that `T` will be a closure, e.g.: /// /// ``` /// use cache_system::loader::FunctionLoader; /// /// let my_loader = FunctionLoader::new(|k: u8, _extra: ()| async move { /// format!("{k}") /// }); /// ``` /// /// There is no way to spell out the exact type of `my_loader` in the above example, because the closure has an /// anonymous type. If you need the type signature of [`FunctionLoader`], you have to /// [erase the type](https://en.wikipedia.org/wiki/Type_erasure) by putting the [`FunctionLoader`] it into a [`Box`], /// e.g.: /// /// ``` /// use cache_system::loader::{Loader, FunctionLoader}; /// /// let my_loader = FunctionLoader::new(|k: u8, _extra: ()| async move { /// format!("{k}") /// }); /// let m_loader: Box<dyn Loader<K = u8, V = String, Extra = ()>> = Box::new(my_loader); /// ``` /// /// /// [`fn_traits`]: https://doc.rust-lang.org/beta/unstable-book/library-features/fn-traits.html pub struct FunctionLoader<T, F, K, Extra> where T: Fn(K, Extra) -> F + Send + Sync + 'static, F: Future + Send + 'static, K: Debug + Send + 'static, F::Output: Debug + Send + 'static, Extra: Debug + Send + 'static, { loader: T, _phantom: PhantomData<dyn Fn() -> (F, K, Extra) + Send + Sync + 'static>, } impl<T, F, K, Extra> FunctionLoader<T, F, K, Extra> where T: Fn(K, Extra) -> F + Send + Sync + 'static, F: Future + Send + 'static, K: Debug + Send + 'static, F::Output: Debug + Send + 'static, Extra: Debug + Send + 'static, { /// Create loader from function. pub fn new(loader: T) -> Self { Self { loader, _phantom: PhantomData, } } } impl<T, F, K, Extra> std::fmt::Debug for FunctionLoader<T, F, K, Extra> where T: Fn(K, Extra) -> F + Send + Sync + 'static, F: Future + Send + 'static, K: Debug + Send + 'static, F::Output: Debug + Send + 'static, Extra: Debug + Send + 'static, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("FunctionLoader").finish_non_exhaustive() } } #[async_trait] impl<T, F, K, Extra> Loader for FunctionLoader<T, F, K, Extra> where T: Fn(K, Extra) -> F + Send + Sync + 'static, F: Future + Send + 'static, K: Debug + Hash + Send + 'static, F::Output: Debug + Send + 'static, Extra: Debug + Send + 'static, { type K = K; type V = F::Output; type Extra = Extra; async fn load(&self, k: Self::K, extra: Self::Extra) -> Self::V { (self.loader)(k, extra).await } }
use super::*; use crate::mock::*; use ark_ff::prelude::*; use arkworks_gadgets::{ poseidon::PoseidonParameters, utils::{get_mds_poseidon_circom_bn254_x5_3, get_rounds_poseidon_circom_bn254_x5_3}, }; use frame_support::{assert_err, assert_ok, instances::Instance1}; use sp_core::bytes; #[test] fn should_fail_with_params_not_initialized() { new_test_ext().execute_with(|| { assert_err!( <BN254Poseidon3x5Hasher as HasherModule>::hash(&[1u8; 32]), Error::<Test, Instance1>::ParametersNotInitialized ); }); } #[test] fn should_initialize_parameters() { new_test_ext().execute_with(|| { let rounds = get_rounds_poseidon_circom_bn254_x5_3::<ark_bn254::Fr>(); let mds = get_mds_poseidon_circom_bn254_x5_3::<ark_bn254::Fr>(); let params = PoseidonParameters::new(rounds, mds); let res = BN254CircomPoseidon3x5Hasher::force_set_parameters(Origin::root(), params.to_bytes()); assert_ok!(res); }); } #[test] fn should_output_correct_hash() { type Fr = ark_bn254::Fr; new_test_ext().execute_with(|| { let rounds = get_rounds_poseidon_circom_bn254_x5_3::<Fr>(); let mds = get_mds_poseidon_circom_bn254_x5_3::<Fr>(); let params = PoseidonParameters::new(rounds, mds); let res = BN254CircomPoseidon3x5Hasher::force_set_parameters(Origin::root(), params.to_bytes()); assert_ok!(res); let left = Fr::one().into_repr().to_bytes_le(); // one let right = Fr::one().double().into_repr().to_bytes_le(); // two let hash = BN254CircomPoseidon3x5Hasher::hash_two(&left, &right).unwrap(); let f = Fr::from_le_bytes_mod_order(&hash).into_repr().to_bytes_be(); assert_eq!( f, bytes::from_hex("0x115cc0f5e7d690413df64c6b9662e9cf2a3617f2743245519e19607a4417189a").unwrap() ); }); }
// The device which renders the objects and draws them to the screen. They are all contained in // this one device struct which is why I'm giving it its own file. use crate::render_objects::*; use crate::structures::*; use std::cmp; pub struct Device { // The width and height of the screen. This will of course be the dimensions of the terminal. pub dimensions: (usize, usize), pub camera: Camera, pub meshes: Vec<Mesh>, pub pixels: Vec<Colour>, } impl Device { pub fn new(camera: Camera, meshes: Vec<Mesh>, colour_space: Colour) -> Device { let colour = match colour_space { Colour::Rgba(r,g,b,a) => Colour::Rgba(0.0, 0.0, 0.0, 0.0), Colour::Grey(a) => Colour::Grey(0.0), }; let dimensions = term_size::dimensions().unwrap(); Device { dimensions: term_size::dimensions().unwrap(), camera: camera, meshes: meshes, pixels: vec![colour; dimensions.0 * dimensions.1], } } // Make an array of pixels, probably one dimensional array. Then make a function that takes in // an x and y and sets that pixel to that colour. Then make functions for lines and triangles. pub fn clear_screen(&self) { print!("{}[2J", 27 as char); } pub fn show_cursor(&self, show: bool) { if show { print!("{}[?25h", 27 as char); } else { print!("{}[?25l", 27 as char); } } fn move_cursor_to(&self, x: usize, y: usize) { print!("{}[{};{}H", 27 as char, (x+1).to_string(), (y+1).to_string()); } pub fn draw_point(&self, x: usize, y: usize, colour: Colour) { self.move_cursor_to(x, y); print!("{}", Device::colour_to_char(colour)); } pub fn draw_line_fast(&self, p1: (usize, usize), p2: (usize, usize), colour: Colour) { // Implementing Bresenham's Line Algorithm: // This is fast but provides no antialiasing. let pp1 = (p1.1, p1.0); let pp2 = (p2.1, p2.0); if (pp2.1 as i32 - pp1.1 as i32).abs() < (pp2.0 as i32 - pp1.0 as i32).abs() { if pp1.0 > pp2.0 { self.draw_line_low(pp2, pp1, colour.clone()); } else { self.draw_line_low(pp1, pp2, colour.clone()); } } else { if pp1.1 > pp2.1 { self.draw_line_high(pp2, pp1, colour.clone()); } else { self.draw_line_high(pp1, pp2, colour.clone()); } } } fn draw_line_low(&self, p1: (usize, usize), p2: (usize, usize), colour: Colour) { let mut dx = p2.0 as f64 - p1.0 as f64; let mut dy = p2.1 as f64 - p1.1 as f64; let mut yi = 1; if dy < 0.0 { yi = -1; dy *= -1.0; } let mut D = 2.0*dy - dx; let mut y = p1.1 as i32; for x in p1.0..p2.0 { self.draw_point(x, y as usize, colour.clone()); if D > 0.0 { y += yi; D -= 2.0*dx; } D += 2.0*dy; } } fn draw_line_high(&self, p1: (usize, usize), p2: (usize, usize), colour: Colour) { let mut dx = p2.0 as f64 - p1.0 as f64; let mut dy = p2.1 as f64 - p1.1 as f64; let mut xi: i32 = 1; if dx < 0.0 { xi = -1; dx *= -1.0; } let mut D = 2.0*dx - dy; let mut x = p1.1 as i32; for y in p1.1..p2.1 { self.draw_point(x as usize, y, colour.clone()); if D > 0.0 { x += xi; D -= 2.0*dy; } D += 2.0*dx; } } pub fn draw_line_antialiased(&self, p1: (f64, f64), p2: (f64, f64), colour: Colour) { // Implementing Wu's Line Algorithm: // This is slow but antialiased // The reason this takes f64 input and not usize like draw_line_fast is because this can // give you a line that is not necessarily drawn *from* one pixel to another. Instead since // it is antialiased it can give you something that better approximates a line from a float // value instead of just integers. // Funny story, I tried this normally once and for some reason it would swap the x and y // values for each point around. There's a problem in my code somewhere but my reasoning is // that if I simply swap them around beforehand it will all work out in the end. // Modern problems require modern solutions. let mut y0 = p1.0; let mut y1 = p2.0; let mut x0 = p1.1; let mut x1 = p2.1; let steep = (y1 - y0).abs() > (x1 - x0).abs(); if steep { // Swap x0 and y0 let mut temp = x0; x0 = y0; y0 = temp; // Swap x1 and y1 temp = x1; x1 = y1; y1 = temp; } if x0 > x1 { // Swap x0 and x1 let mut temp = x0; x0 = x1; x1 = temp; // Swap y0 and y1 temp = y0; y0 = y1; y1 = temp; } let dx = x1 - x0; let dy = y1 - y0; let mut gradient = 1f64; if dx != 0.0 { gradient = dy/dx; } // First endpoint. If you haven't realised by now I'm pretty much just reading this off // Wikipedia. Donate $3! let mut xend = x0.round(); let mut yend = y0 + gradient * (xend-x0); let xgap = 1.0-((x0+0.5).fract()); let mut xpxl1 = xend; let mut ypxl1 = yend.trunc(); if steep { self.draw_point(ypxl1 as usize, xpxl1 as usize, Colour::Grey((1.0-(yend.fract())) * xgap)); self.draw_point((ypxl1+1.0) as usize, xpxl1 as usize, Colour::Grey((yend.fract()) * xgap)); } else { self.draw_point(xpxl1 as usize, ypxl1 as usize, Colour::Grey((1.0-(yend.fract())) * xgap)); self.draw_point(xpxl1 as usize, (ypxl1+1.0) as usize, Colour::Grey((yend.fract()) * xgap)); } let mut intery = yend + gradient; // Second endpoint. Same thing. let mut xend = x1.round(); let mut yend = y1 + gradient * (xend-x1); let xgap = 1.0-((x1+0.5).fract()); let mut xpxl2 = xend; let mut ypxl2 = yend.trunc(); if steep { self.draw_point(ypxl2 as usize, xpxl2 as usize, Colour::Grey((1.0-(yend.fract())) * xgap)); self.draw_point((ypxl2+1.0) as usize, xpxl2 as usize, Colour::Grey((yend.fract()) * xgap)); } else { self.draw_point(xpxl2 as usize, ypxl2 as usize, Colour::Grey((1.0-(yend.fract())) * xgap)); self.draw_point(xpxl2 as usize, (ypxl2+1.0) as usize, Colour::Grey((yend.fract()) * xgap)); } if steep { for x in (xpxl1 as usize + 1)..(xpxl2 as usize) { self.draw_point(intery.trunc() as usize, x, Colour::Grey(1.0-intery.fract())); self.draw_point(intery.trunc() as usize + 1, x, Colour::Grey(intery.fract())); intery += gradient; } } else { for x in (xpxl1 as usize + 1)..(xpxl2 as usize) { self.draw_point(x, intery.trunc() as usize, Colour::Grey(1.0-intery.fract())); self.draw_point(x, intery.trunc() as usize + 1, Colour::Grey(intery.fract())); intery += gradient; } } } fn colour_to_char(colour: Colour) -> char { let alpha = match colour { Colour::Rgba(r,g,b,a) => a, Colour::Grey(a) => a, }; // █#&+- if alpha <= 0.2 { return '-'; } else if alpha <= 0.4 { return '+'; } else if alpha <= 0.6 { return '&'; } else if alpha <= 0.8 { return '#'; } else { return '█'; } } pub fn draw_triangle(&self, p1: (f64, f64), p2: (f64, f64), p3: (f64, f64), colour: Colour, antialiased: bool) { // First, draw the lines between each vertex. if antialiased { self.draw_line_antialiased(p1, p2, colour.clone()); self.draw_line_antialiased(p2, p3, colour.clone()); self.draw_line_antialiased(p3, p1, colour.clone()); self.fill_triangle((p1.1, p1.0), (p2.1, p2.0), (p3.1, p3.0), colour.clone()); } else { // This doesn't quite work yet... Just don't use it? self.draw_line_fast((p1.0 as usize, p1.1 as usize), (p2.0 as usize, p2.1 as usize), colour.clone()); self.draw_line_fast((p2.0 as usize, p2.1 as usize), (p3.0 as usize, p3.1 as usize), colour.clone()); self.draw_line_fast((p3.0 as usize, p3.1 as usize), (p1.0 as usize, p1.1 as usize), colour.clone()); self.fill_triangle((p1.1, p1.0), (p2.1, p2.0), (p3.1, p3.0), colour.clone()); } } pub fn fill_triangle(&self, p1: (f64, f64), p2: (f64, f64), p3: (f64, f64), colour: Colour) { let min = (f64::min(f64::min(p1.0, p2.0), p3.0), f64::min(f64::min(p1.1, p2.1), p3.1)); let max = (f64::max(f64::max(p1.0, p2.0), p3.0), f64::max(f64::max(p1.1, p2.1), p3.1)); let vs1 = (p2.0 - p1.0, p2.1 - p1.1); let vs2 = (p3.0 - p1.0, p3.1 - p1.1); for x in (min.0 as usize)..(max.0 as usize+1) { for y in (min.1 as usize)..(max.1 as usize+1) { let q = (x as f64 - p1.0, y as f64 - p1.1); let s = Device::cross_point(q, vs2) / Device::cross_point(vs1, vs2); let t = Device::cross_point(vs1, q) / Device::cross_point(vs1, vs2); if (s >= 0.0 && t >= 0.0) && (s+t <= 1.0) { self.draw_point(x as usize, y as usize, colour.clone()); } } } } fn cross_point(p1: (f64, f64), p2: (f64, f64)) -> f64 { return (p1.0*p2.1)-(p1.1*p2.0); } pub fn render(&self) { // Wow, the main render function! Snazzy. // First, generate the MVP matricies: Model, View, Projection. // Model matrix: the matrix that describes the basic position, rotation and scaling of each // mesh. let mvp_matrices: Vec<Matrix> = Vec::new(); for m in &self.meshes { let position = Matrix::translation(m.pos.clone()); } } pub fn test_render(&self) { // Gives an orthographic projection from the top. I use this only as a sanity check - it // doesn't do any real perspective or anything that requires complex linear transformations for m in &self.meshes { for f in &m.faces { let v = ( m.vertices[f.vertices[0]].clone(), m.vertices[f.vertices[1]].clone(), m.vertices[f.vertices[2]].clone() ); let scale_factor = 1.0; let scale = (scale_factor * (self.dimensions.0 as f64 / 7.5), -scale_factor * (self.dimensions.1 as f64 / 4.0)); let offset = (self.dimensions.0 as f64 / 3.0, self.dimensions.1 as f64 / 3.0); let points = [ ( ((v.0.x * scale.0) + offset.0), ((v.0.z * scale.1) + offset.1), ), ( ((v.1.x * scale.0) + offset.0), ((v.1.z * scale.1) + offset.1), ), ( ((v.2.x * scale.0) + offset.0), ((v.2.z * scale.1) + offset.1), ) ]; self.draw_triangle(points[0], points[1], points[2], Colour::Grey(0.8), true); } } } }
// Copyright 2021 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 common_meta_kvapi::kvapi; use crate::schema_api_keys::ID_GEN_DATABASE; use crate::schema_api_keys::ID_GEN_TABLE; use crate::share_api_keys::ID_GEN_SHARE; pub(crate) const PREFIX_ID_GEN: &str = "__fd_id_gen"; /// Key for resource id generator /// /// This is a special key for an application to generate unique id with kvapi::KVApi. /// Generating an id by updating a record in kvapi::KVApi and retrieve the seq number. /// A seq number is monotonically incremental in kvapi::KVApi. #[derive(Debug, Clone, PartialEq, Eq)] pub struct IdGenerator { pub resource: String, } impl IdGenerator { /// Create a key for generating table id with kvapi::KVApi pub fn table_id() -> Self { Self { resource: ID_GEN_TABLE.to_string(), } } /// Create a key for generating database id with kvapi::KVApi pub fn database_id() -> Self { Self { resource: ID_GEN_DATABASE.to_string(), } } /// Create a key for generating share id with kvapi::KVApi pub fn share_id() -> Self { Self { resource: ID_GEN_SHARE.to_string(), } } } impl kvapi::Key for IdGenerator { const PREFIX: &'static str = PREFIX_ID_GEN; fn to_string_key(&self) -> String { kvapi::KeyBuilder::new_prefixed(Self::PREFIX) .push_raw(&self.resource) .done() } fn from_str_key(s: &str) -> Result<Self, kvapi::KeyError> { let mut p = kvapi::KeyParser::new_prefixed(s, Self::PREFIX)?; let resource = p.next_raw()?; p.done()?; Ok(IdGenerator { resource: resource.to_string(), }) } } #[cfg(test)] mod t { use common_meta_kvapi::kvapi::Key; use crate::id_generator::IdGenerator; #[test] fn test_id_generator() -> anyhow::Result<()> { // Table id generator { let g = IdGenerator::table_id(); let k = g.to_string_key(); assert_eq!("__fd_id_gen/table_id", k); let t2 = IdGenerator::from_str_key(&k)?; assert_eq!(g, t2); } // Database id generator { let g = IdGenerator::database_id(); let k = g.to_string_key(); assert_eq!("__fd_id_gen/database_id", k); let t2 = IdGenerator::from_str_key(&k)?; assert_eq!(g, t2); } // Share id generator { let g = IdGenerator::share_id(); let k = g.to_string_key(); assert_eq!("__fd_id_gen/share_id", k); let t2 = IdGenerator::from_str_key(&k)?; assert_eq!(g, t2); } Ok(()) } #[test] fn test_id_generator_from_key_error() -> anyhow::Result<()> { assert!(IdGenerator::from_str_key("__fd_id_gen").is_err()); assert!(IdGenerator::from_str_key("__fd_id_gen/foo/bar").is_err()); assert!(IdGenerator::from_str_key("__foo/table_id").is_err()); Ok(()) } }
/* http://rosalind.info/problems/ba1b/ Find all the most frequent k-mers Sample: ACGTTGCATGTCGCATGATGCATGAGAGCT 4 CATG GCAT */ extern crate rosalind_rust; use rosalind_rust::Cli; use std::collections::HashMap; use std::io::{prelude::*, BufReader}; use structopt::StructOpt; // https://github.com/dib-lab/bioinf_algorithms/ pub fn most_frequent(text: &[u8], k: usize) -> Vec<String> { let mut kmers = HashMap::new(); let mut maxval = 0; for kmer in text.windows(k as usize) { let counter = kmers.entry(kmer).or_insert(0); *counter += 1; maxval = std::cmp::max(maxval, *counter); } kmers .iter() .filter_map(|(&kmer, &count)| { if count == maxval { Some(String::from_utf8(kmer.to_vec()).unwrap()) } else { None } }) .collect() } #[test] fn test_ba1b() { let seq = b"ACGTTGCATGTCGCATGATGCATGAGAGCT"; let k = 4; let mut res = most_frequent(seq, k); res.sort(); assert_eq!(res, vec!["CATG", "GCAT"]); } fn main() -> std::io::Result<()> { let args = Cli::from_args(); let f = std::fs::File::open(&args.path)?; let reader = BufReader::new(f); let mut iter = reader.lines(); let text = iter.next().unwrap().unwrap(); let k = iter.next().unwrap().unwrap(); let res = most_frequent(&text.as_bytes(), k.parse::<usize>().unwrap()); println!("{}", res.join(" ")); Ok(()) }
extern crate failure; extern crate luster; use std::env; use std::fs::File; use std::io::Read; use failure::{err_msg, Error}; use luster::state::Lua; fn main() -> Result<(), Error> { let mut args = env::args(); args.next(); let mut file = File::open(args.next() .ok_or_else(|| err_msg("no file argument given"))?)?; let mut contents = Vec::new(); file.read_to_end(&mut contents)?; let mut lua = Lua::load(&contents)?; while !lua.run(Some(1024)) {} lua.visit_results(|results| { println!("results: {:?}", results.unwrap()); }); Ok(()) }
#[doc = "Reader of register CTR"] pub type R = crate::R<u32, super::CTR>; #[doc = "Reader of field `_IminLine`"] pub type _IMINLINE_R = crate::R<u8, u8>; #[doc = "Reader of field `DMinLine`"] pub type DMINLINE_R = crate::R<u8, u8>; #[doc = "Reader of field `ERG`"] pub type ERG_R = crate::R<u8, u8>; #[doc = "Reader of field `CWG`"] pub type CWG_R = crate::R<u8, u8>; #[doc = "Reader of field `Format`"] pub type FORMAT_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:3 - IminLine"] #[inline(always)] pub fn _imin_line(&self) -> _IMINLINE_R { _IMINLINE_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 16:19 - DMinLine"] #[inline(always)] pub fn dmin_line(&self) -> DMINLINE_R { DMINLINE_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 20:23 - ERG"] #[inline(always)] pub fn erg(&self) -> ERG_R { ERG_R::new(((self.bits >> 20) & 0x0f) as u8) } #[doc = "Bits 24:27 - CWG"] #[inline(always)] pub fn cwg(&self) -> CWG_R { CWG_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 29:31 - Format"] #[inline(always)] pub fn format(&self) -> FORMAT_R { FORMAT_R::new(((self.bits >> 29) & 0x07) as u8) } }
use input::Input; use input::evaluator::InputEvaluatorRef; use parser::{ Evaluator, Node }; use util; // Smoother pub struct Smooth { input : Box<Input>, values : Vec<f64>, samples : usize, index : usize, curr_val : f64, curr_sum : f64, } impl Smooth { pub fn create(samples_v: usize, input_v: Box<Input>) -> Box<Input> { let mut values_v : Vec<f64> = Vec::new(); values_v.resize(samples_v, 0.0); Box::new(Smooth { input : input_v, values : values_v, samples : samples_v, index : 0, curr_val : 0.0, curr_sum : 0.0, }) } } impl Input for Smooth { fn compute(&mut self) -> f64 { let input = self.input.compute(); // Compute sums without having to traverse the entire // buffer every time. For accuracy reasons, we compute // another sum from zero which will be swapped in after // each full round through the ring buffer. self.curr_val -= self.values[self.index]; self.values[self.index] = input; self.curr_val += input; self.curr_sum += input; // Advance index and perform the magic explained // above to keep the numbers accurate enough. self.index += 1; if self.index == self.samples { self.curr_val = self.curr_sum; self.curr_sum = 0.0; self.index = 0; } // Compute unweighed average self.curr_val / (self.samples as f64) } } /////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////// pub struct EvalSmooth { input : InputEvaluatorRef, } impl EvalSmooth { pub fn new(input_v : InputEvaluatorRef) -> EvalSmooth { EvalSmooth { input : input_v } } } impl Evaluator<Box<Input>> for EvalSmooth { fn parse_nodes(&self, nodes: &[Node]) -> Result<Box<Input>, String> { Ok(Smooth::create( try!(util::get_num_node::<usize>("smooth", nodes, 0)), try!(self.input.borrow().parse_node( try!(util::get_node("smooth", nodes, 1)))))) } }
use crate::topology::{config::DataType, Config}; use std::collections::HashMap; pub fn typecheck(config: &Config) -> Result<(), Vec<String>> { Graph::from(config).typecheck() } #[derive(Debug, Clone)] enum Node { Source { ty: DataType, }, Transform { in_ty: DataType, out_ty: DataType, inputs: Vec<String>, }, Sink { ty: DataType, inputs: Vec<String>, }, } #[derive(Default)] struct Graph { nodes: HashMap<String, Node>, } impl Graph { fn add_source(&mut self, name: &str, ty: DataType) { self.nodes.insert(name.to_string(), Node::Source { ty }); } fn add_transform( &mut self, name: &str, in_ty: DataType, out_ty: DataType, inputs: Vec<impl Into<String>>, ) { let inputs = self.clean_inputs(inputs); self.nodes.insert( name.to_string(), Node::Transform { in_ty, out_ty, inputs, }, ); } fn add_sink(&mut self, name: &str, ty: DataType, inputs: Vec<impl Into<String>>) { let inputs = self.clean_inputs(inputs); self.nodes .insert(name.to_string(), Node::Sink { ty, inputs }); } fn paths(&self) -> Result<Vec<Vec<String>>, Vec<String>> { let mut errors = Vec::new(); let nodes = self .nodes .iter() .filter_map(|(name, node)| match node { Node::Sink { .. } => Some(name), _ => None, }) .flat_map(|node| { paths_rec(&self.nodes, node, Vec::new()).unwrap_or_else(|err| { errors.push(err); Vec::new() }) }) .collect(); if !errors.is_empty() { errors.sort(); errors.dedup(); Err(errors) } else { Ok(nodes) } } fn clean_inputs(&self, inputs: Vec<impl Into<String>>) -> Vec<String> { inputs.into_iter().map(Into::into).collect() } fn typecheck(&self) -> Result<(), Vec<String>> { let mut errors = Vec::new(); for path in self.paths()? { for pair in path.windows(2) { let (x, y) = (&pair[0], &pair[1]); if self.nodes.get(x).is_none() || self.nodes.get(y).is_none() { continue; } match (self.nodes[x].clone(), self.nodes[y].clone()) { (Node::Source { ty: ty1 }, Node::Sink { ty: ty2, .. }) | (Node::Source { ty: ty1 }, Node::Transform { in_ty: ty2, .. }) | (Node::Transform { out_ty: ty1, .. }, Node::Transform { in_ty: ty2, .. }) | (Node::Transform { out_ty: ty1, .. }, Node::Sink { ty: ty2, .. }) => { if ty1 != ty2 && ty1 != DataType::Any && ty2 != DataType::Any { errors.push(format!( "Data type mismatch between {} ({:?}) and {} ({:?})", x, ty1, y, ty2 )); } } (Node::Sink { .. }, _) | (_, Node::Source { .. }) => unreachable!(), } } } if errors.is_empty() { Ok(()) } else { errors.sort(); errors.dedup(); Err(errors) } } } impl From<&Config> for Graph { fn from(config: &Config) -> Self { let mut graph = Graph::default(); // TODO: validate that node names are unique across sources/transforms/sinks? for (name, config) in config.sources.iter() { graph.add_source(name, config.output_type()); } for (name, config) in config.transforms.iter() { graph.add_transform( name, config.inner.input_type(), config.inner.output_type(), config.inputs.clone(), ); } for (name, config) in config.sinks.iter() { graph.add_sink(name, config.inner.input_type(), config.inputs.clone()); } graph } } fn paths_rec( nodes: &HashMap<String, Node>, node: &str, mut path: Vec<String>, ) -> Result<Vec<Vec<String>>, String> { if let Some(i) = path.iter().position(|p| p == node) { let mut segment = path.split_off(i); segment.push(node.into()); // I think this is maybe easier to grok from source -> sink, but I'm not // married to either. segment.reverse(); return Err(format!( "Cyclic dependency detected in the chain [ {} ]", segment.join(" -> ") )); } path.push(node.to_string()); match nodes.get(node) { Some(Node::Source { .. }) | None => { path.reverse(); Ok(vec![path]) } Some(Node::Transform { inputs, .. }) | Some(Node::Sink { inputs, .. }) => { let mut paths = Vec::new(); for input in inputs { match paths_rec(nodes, input, path.clone()) { Ok(mut p) => paths.append(&mut p), Err(err) => { return Err(err); } } } Ok(paths) } } } #[cfg(test)] mod test { use super::Graph; use crate::topology::config::DataType; use pretty_assertions::assert_eq; #[test] fn paths_detects_cycles() { let mut graph = Graph::default(); graph.add_source("in", DataType::Log); graph.add_transform("one", DataType::Log, DataType::Log, vec!["in", "three"]); graph.add_transform("two", DataType::Log, DataType::Log, vec!["one"]); graph.add_transform("three", DataType::Log, DataType::Log, vec!["two"]); graph.add_sink("out", DataType::Log, vec!["three"]); assert_eq!( Err(vec![ "Cyclic dependency detected in the chain [ three -> one -> two -> three ]".into() ]), graph.paths() ); let mut graph = Graph::default(); graph.add_source("in", DataType::Log); graph.add_transform("one", DataType::Log, DataType::Log, vec!["in", "three"]); graph.add_transform("two", DataType::Log, DataType::Log, vec!["one"]); graph.add_transform("three", DataType::Log, DataType::Log, vec!["two"]); graph.add_sink("out", DataType::Log, vec!["two"]); assert_eq!( Err(vec![ "Cyclic dependency detected in the chain [ two -> three -> one -> two ]".into() ]), graph.paths() ); assert_eq!( Err(vec![ "Cyclic dependency detected in the chain [ two -> three -> one -> two ]".into() ]), graph.typecheck() ); let mut graph = Graph::default(); graph.add_source("in", DataType::Log); graph.add_transform("in", DataType::Log, DataType::Log, vec!["in"]); graph.add_sink("out", DataType::Log, vec!["in"]); // This isn't really a cyclic dependency but let me have this one. assert_eq!( Err(vec![ "Cyclic dependency detected in the chain [ in -> in ]".into() ]), graph.paths() ); } #[test] fn paths_doesnt_detect_noncycles() { let mut graph = Graph::default(); graph.add_source("in", DataType::Log); graph.add_transform("one", DataType::Log, DataType::Log, vec!["in"]); graph.add_transform("two", DataType::Log, DataType::Log, vec!["in"]); graph.add_transform("three", DataType::Log, DataType::Log, vec!["one", "two"]); graph.add_sink("out", DataType::Log, vec!["three"]); graph.paths().unwrap(); } #[test] fn detects_type_mismatches() { let mut graph = Graph::default(); graph.add_source("in", DataType::Log); graph.add_sink("out", DataType::Metric, vec!["in"]); assert_eq!( Err(vec![ "Data type mismatch between in (Log) and out (Metric)".into() ]), graph.typecheck() ); } #[test] fn allows_log_or_metric_into_any() { let mut graph = Graph::default(); graph.add_source("log_source", DataType::Log); graph.add_source("metric_source", DataType::Metric); graph.add_sink( "any_sink", DataType::Any, vec!["log_source", "metric_source"], ); assert_eq!(Ok(()), graph.typecheck()); } #[test] fn allows_any_into_log_or_metric() { let mut graph = Graph::default(); graph.add_source("any_source", DataType::Any); graph.add_transform( "log_to_any", DataType::Log, DataType::Any, vec!["any_source"], ); graph.add_transform( "any_to_log", DataType::Any, DataType::Log, vec!["any_source"], ); graph.add_sink( "log_sink", DataType::Log, vec!["any_source", "log_to_any", "any_to_log"], ); graph.add_sink( "metric_sink", DataType::Metric, vec!["any_source", "log_to_any"], ); assert_eq!(graph.typecheck(), Ok(())); } #[test] fn allows_both_directions_for_metrics() { let mut graph = Graph::default(); graph.add_source("log_source", DataType::Log); graph.add_source("metric_source", DataType::Metric); graph.add_transform( "log_to_log", DataType::Log, DataType::Log, vec!["log_source"], ); graph.add_transform( "metric_to_metric", DataType::Metric, DataType::Metric, vec!["metric_source"], ); graph.add_transform( "any_to_any", DataType::Any, DataType::Any, vec!["log_to_log", "metric_to_metric"], ); graph.add_transform( "any_to_log", DataType::Any, DataType::Log, vec!["any_to_any"], ); graph.add_transform( "any_to_metric", DataType::Any, DataType::Metric, vec!["any_to_any"], ); graph.add_sink("log_sink", DataType::Log, vec!["any_to_log"]); graph.add_sink("metric_sink", DataType::Metric, vec!["any_to_metric"]); assert_eq!(Ok(()), graph.typecheck()); } }
extern crate specs; use rltk::Point; use specs::prelude::*; use crate::{GlobalTurnTimeScore, MEDIUM_LIFETIME, ParticleBuilder, Position, TakesTurn, WaitCause, WantsToWait}; pub struct WaitSystem; impl<'a> System<'a> for WaitSystem { type SystemData = ( Entities<'a>, WriteStorage<'a, WantsToWait>, WriteStorage<'a, TakesTurn>, ReadExpect<'a, GlobalTurnTimeScore>, WriteExpect<'a, ParticleBuilder>, ReadStorage<'a, Position>, ); fn run(&mut self, data: Self::SystemData) { let ( entities, mut wants_to_wait, mut takes_turn, global_turn_time_score, mut particle_builder, positions, ) = data; let target_time_score = global_turn_time_score.time_score + 1; for (entity, wants_to_wait, mut takes_turn) in (&entities, &wants_to_wait, &mut takes_turn).join() { takes_turn.time_score = target_time_score; if let Some(position) = positions.get(entity) { match wants_to_wait.cause { WaitCause::Confusion => { particle_builder.request_aura( Point::new(position.x, position.y), MEDIUM_LIFETIME, rltk::RGB::named(rltk::MAGENTA), rltk::to_cp437('?'), ); } WaitCause::Choice => { particle_builder.request_aura( Point::new(position.x, position.y), MEDIUM_LIFETIME, rltk::RGB::named(rltk::LIGHT_SKY), rltk::to_cp437('♪'), ); } WaitCause::Stun => {} } } } wants_to_wait.clear(); } }
use super::vec2; pub struct Ray2d { range: f32, dir: vec2::Vec2 } // todo
use ndarray::{Array, Array2}; pub fn fusion<T, U>(mu1: T, mu2: T, var1: U, var2: U) -> (T, U) where T: num::Float + From<U>, U: num::Float { let v: U = var1 + var2; let mu = (mu1 * From::from(var2) + mu2 * From::from(var1)) / From::from(v); let var = (var1 * var2) / v; (mu, var) } pub fn fusion_arrays<T, U>( mu1: &Array2<T>, mu2: &Array2<T>, var1: &Array2<U>, var2: &Array2<U>, ) -> (Array2<T>, Array2<U>) where T: num::Float + From<U>, U: num::Float { let shape = mu1.shape(); let (height, width) = (shape[0], shape[1]); assert_eq!(mu2.shape(), shape); assert_eq!(var1.shape(), shape); assert_eq!(var2.shape(), shape); let mut mu = Array::zeros((height, width)); let mut var = Array::zeros((height, width)); for y in 0..height { for x in 0..width { let m1: T = mu1[[y, x]]; let m2: T = mu2[[y, x]]; let v1: U = var1[[y, x]]; let v2: U = var2[[y, x]]; let (m, v): (T, U) = fusion(m1, m2, v1, v2); mu[[y, x]] = m; var[[y, x]] = v; } } (mu, var) } #[cfg(test)] mod tests { use super::*; use ndarray::arr2; #[test] fn test_fusion() { let mu1 = arr2( &[[1.9, -2.2], [-3.8, 4.1], [-1.5, 4.5]] ); let mu2 = arr2( &[[-4.1, -2.5], [1.2, 5.0], [6.4, 4.1]] ); let var1 = arr2( &[[4.8, 2.2], [3.1, 6.8], [4.0, 2.1]] ); let var2 = arr2( &[[4.2, 3.1], [0.01, 2.0], [6.0, 3.9]] ); let (mu0, var0) = fusion_arrays(&mu1, &mu2, &var1, &var2); for y in 0..3 { for x in 0..2 { let m0 = mu0[[y, x]]; let m1 = mu1[[y, x]]; let m2 = mu2[[y, x]]; let v0 = var0[[y, x]]; let v1 = var1[[y, x]]; let v2 = var2[[y, x]]; assert_eq!(m0, (v2 * m1 + v1 * m2) / (v1 + v2)); assert_eq!(v0, (v1 * v2) / (v1 + v2)); } } } }
use crate::BLOCK_384_512_LEN as BLOCK_LEN; use crate::PAD_AND_LENGTH_384_512_LEN as PAD_AND_LENGTH_LEN; use crate::STATE_384_512_LEN as STATE_LEN; use crate::WORD_384_512_LEN as WORD_LEN; use crate::{inner_full_pad, inner_pad, process_block_384_512, zero_block}; use crate::{Error, Hash, Sha2}; /// Digest length in bytes (512-bits) pub const DIGEST_LEN: usize = 64; // Initial state words: FIPS-180-2 sections 5.3.4 const INITIAL_STATE: [u64; STATE_LEN] = [ 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179, ]; /// Implementation of the SHA-256 transform pub struct Sha384 { state: [u64; STATE_LEN], block: [u8; BLOCK_LEN], index: usize, bit_index: usize, total_len: u128, hash: Hash, } impl Sha2 for Sha384 { type Block = [u8; BLOCK_LEN]; type Digest = [u8; DIGEST_LEN]; type State = [u64; STATE_LEN]; /// Create a newly initialized SHA-256 transform fn new() -> Self { Self { state: INITIAL_STATE, block: [0_u8; BLOCK_LEN], index: 0, bit_index: 0, total_len: 0, hash: Hash::Sha384, } } fn encode_state(&self) -> Self::Digest { let mut res = [0_u8; DIGEST_LEN]; for (i, word) in self.state.iter().enumerate() { res[i * WORD_LEN..(i + 1) * WORD_LEN].copy_from_slice(word.to_be_bytes().as_ref()); } res } fn process_block(&mut self) { process_block_384_512(&mut self.state, &mut self.block, &mut self.index); } fn pad(&mut self) -> Result<(), Error> { inner_pad( &mut self.block, self.index, self.bit_index, self.total_len as u128, &self.hash, ) } fn full_pad(&mut self) { inner_full_pad(&mut self.block, self.total_len, &self.hash); } fn index(&self) -> usize { self.index } fn increment_index(&mut self) { self.index += 1; } fn bit_index(&self) -> usize { self.bit_index } fn set_bit_index(&mut self, index: usize) { self.bit_index = index; } fn total_len(&self) -> u128 { self.total_len as u128 } fn increment_total_len(&mut self, len: usize) -> Result<(), Error> { let len = len as u128; if len + self.total_len > u128::MAX { return Err(Error::InvalidLength); } // increase the total length of the message self.total_len += len; Ok(()) } fn hash(&self) -> &Hash { &self.hash } fn initial_state(&mut self) { self.state.copy_from_slice(INITIAL_STATE.as_ref()); } fn block_mut(&mut self) -> &mut [u8] { &mut self.block } fn zero_block(&mut self) { zero_block(&mut self.block); } fn reset_counters(&mut self) { self.index = 0; self.bit_index = 0; self.total_len = 0; } } #[cfg(test)] mod tests { use super::*; #[test] fn rfc_vector1() { let input = b"abc"; let expected = [ 0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba, 0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31, 0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2, 0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a, 0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8, 0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd, 0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e, 0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f, ]; let mut sha = Sha384::new(); sha.input(input.as_ref()).unwrap(); let digest = sha.finalize().unwrap(); assert_eq!(digest, expected); } #[test] fn rfc_vector2() { let input = b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"; let expected = [ 0x8e, 0x95, 0x9b, 0x75, 0xda, 0xe3, 0x13, 0xda, 0x8c, 0xf4, 0xf7, 0x28, 0x14, 0xfc, 0x14, 0x3f, 0x8f, 0x77, 0x79, 0xc6, 0xeb, 0x9f, 0x7f, 0xa1, 0x72, 0x99, 0xae, 0xad, 0xb6, 0x88, 0x90, 0x18, 0x50, 0x1d, 0x28, 0x9e, 0x49, 0x00, 0xf7, 0xe4, 0x33, 0x1b, 0x99, 0xde, 0xc4, 0xb5, 0x43, 0x3a, 0xc7, 0xd3, 0x29, 0xee, 0xb6, 0xdd, 0x26, 0x54, 0x5e, 0x96, 0xe5, 0x5b, 0x87, 0x4b, 0xe9, 0x09, ]; let mut sha = Sha384::new(); sha.input(input.as_ref()).unwrap(); let digest = sha.finalize().unwrap(); assert_eq!(digest, expected); } #[test] fn rfc_vector3() { let input = b"a"; let expected = [ 0xe7, 0x18, 0x48, 0x3d, 0x0c, 0xe7, 0x69, 0x64, 0x4e, 0x2e, 0x42, 0xc7, 0xbc, 0x15, 0xb4, 0x63, 0x8e, 0x1f, 0x98, 0xb1, 0x3b, 0x20, 0x44, 0x28, 0x56, 0x32, 0xa8, 0x03, 0xaf, 0xa9, 0x73, 0xeb, 0xde, 0x0f, 0xf2, 0x44, 0x87, 0x7e, 0xa6, 0x0a, 0x4c, 0xb0, 0x43, 0x2c, 0xe5, 0x77, 0xc3, 0x1b, 0xeb, 0x00, 0x9c, 0x5c, 0x2c, 0x49, 0xaa, 0x2e, 0x4e, 0xad, 0xb2, 0x17, 0xad, 0x8c, 0xc0, 0x9b, ]; let mut sha = Sha384::new(); for _i in 0..1_000_000 { sha.input(input.as_ref()).unwrap(); } let digest = sha.finalize().unwrap(); assert_eq!(digest, expected); } #[test] fn rfc_vector4() { let input = b"0123456701234567012345670123456701234567012345670123456701234567"; let expected = [ 0x89, 0xd0, 0x5b, 0xa6, 0x32, 0xc6, 0x99, 0xc3, 0x12, 0x31, 0xde, 0xd4, 0xff, 0xc1, 0x27, 0xd5, 0xa8, 0x94, 0xda, 0xd4, 0x12, 0xc0, 0xe0, 0x24, 0xdb, 0x87, 0x2d, 0x1a, 0xbd, 0x2b, 0xa8, 0x14, 0x1a, 0x0f, 0x85, 0x07, 0x2a, 0x9b, 0xe1, 0xe2, 0xaa, 0x04, 0xcf, 0x33, 0xc7, 0x65, 0xcb, 0x51, 0x08, 0x13, 0xa3, 0x9c, 0xd5, 0xa8, 0x4c, 0x4a, 0xca, 0xa6, 0x4d, 0x3f, 0x3f, 0xb7, 0xba, 0xe9, ]; let mut sha = Sha384::new(); for _i in 0..10 { sha.input(input.as_ref()).unwrap(); } let digest = sha.finalize().unwrap(); assert_eq!(digest, expected); } // FIXME: skip vector 5, 7, and 9 since the `final_bits` API is unimplemented #[test] fn rfc_vector5() { let input = []; let expected = [ 0xd4, 0xee, 0x29, 0xa9, 0xe9, 0x09, 0x85, 0x44, 0x6b, 0x91, 0x3c, 0xf1, 0xd1, 0x37, 0x6c, 0x83, 0x6f, 0x4b, 0xe2, 0xc1, 0xcf, 0x3c, 0xad, 0xa0, 0x72, 0x0a, 0x6b, 0xf4, 0x85, 0x7d, 0x88, 0x6a, 0x7e, 0xcb, 0x3c, 0x4e, 0x4c, 0x0f, 0xa8, 0xc7, 0xf9, 0x52, 0x14, 0xe4, 0x1d, 0xc1, 0xb0, 0xd2, 0x1b, 0x22, 0xa8, 0x4c, 0xc0, 0x3b, 0xf8, 0xce, 0x48, 0x45, 0xf3, 0x4d, 0xd5, 0xbd, 0xba, 0xd4, ]; let mut sha = Sha384::new(); sha.input(input.as_ref()).unwrap(); let digest = sha.final_bits(0xb0, 5).unwrap(); assert_eq!(digest, expected); } #[test] fn rfc_vector6() { let input = b"\xd0"; let expected = [ 0x99, 0x92, 0x20, 0x29, 0x38, 0xe8, 0x82, 0xe7, 0x3e, 0x20, 0xf6, 0xb6, 0x9e, 0x68, 0xa0, 0xa7, 0x14, 0x90, 0x90, 0x42, 0x3d, 0x93, 0xc8, 0x1b, 0xab, 0x3f, 0x21, 0x67, 0x8d, 0x4a, 0xce, 0xee, 0xe5, 0x0e, 0x4e, 0x8c, 0xaf, 0xad, 0xa4, 0xc8, 0x5a, 0x54, 0xea, 0x83, 0x06, 0x82, 0x6c, 0x4a, 0xd6, 0xe7, 0x4c, 0xec, 0xe9, 0x63, 0x1b, 0xfa, 0x8a, 0x54, 0x9b, 0x4a, 0xb3, 0xfb, 0xba, 0x15, ]; let mut sha = Sha384::new(); sha.input(input.as_ref()).unwrap(); let digest = sha.finalize().unwrap(); assert_eq!(digest, expected); } #[test] fn rfc_vector7() { let input = b"\x08\xec\xb5\x2e\xba\xe1\xf7\x42\x2d\xb6\x2b\xcd\x54\x26\x70"; let expected = [ 0xed, 0x8d, 0xc7, 0x8e, 0x8b, 0x01, 0xb6, 0x97, 0x50, 0x05, 0x3d, 0xbb, 0x7a, 0x0a, 0x9e, 0xda, 0x0f, 0xb9, 0xe9, 0xd2, 0x92, 0xb1, 0xed, 0x71, 0x5e, 0x80, 0xa7, 0xfe, 0x29, 0x0a, 0x4e, 0x16, 0x66, 0x4f, 0xd9, 0x13, 0xe8, 0x58, 0x54, 0x40, 0x0c, 0x5a, 0xf0, 0x5e, 0x6d, 0xad, 0x31, 0x6b, 0x73, 0x59, 0xb4, 0x3e, 0x64, 0xf8, 0xbe, 0xc3, 0xc1, 0xf2, 0x37, 0x11, 0x99, 0x86, 0xbb, 0xb6, ]; let mut sha = Sha384::new(); sha.input(input.as_ref()).unwrap(); let digest = sha.final_bits(0x80, 3).unwrap(); assert_eq!(digest, expected); } #[test] fn rfc_vector8() { let input = b"\x8d\x4e\x3c\x0e\x38\x89\x19\x14\x91\x81\x6e\x9d\x98\xbf\xf0\xa0"; let expected = [ 0xcb, 0x0b, 0x67, 0xa4, 0xb8, 0x71, 0x2c, 0xd7, 0x3c, 0x9a, 0xab, 0xc0, 0xb1, 0x99, 0xe9, 0x26, 0x9b, 0x20, 0x84, 0x4a, 0xfb, 0x75, 0xac, 0xbd, 0xd1, 0xc1, 0x53, 0xc9, 0x82, 0x89, 0x24, 0xc3, 0xdd, 0xed, 0xaa, 0xfe, 0x66, 0x9c, 0x5f, 0xdd, 0x0b, 0xc6, 0x6f, 0x63, 0x0f, 0x67, 0x73, 0x98, 0x82, 0x13, 0xeb, 0x1b, 0x16, 0xf5, 0x17, 0xad, 0x0d, 0xe4, 0xb2, 0xf0, 0xc9, 0x5c, 0x90, 0xf8, ]; let mut sha = Sha384::new(); sha.input(input.as_ref()).unwrap(); let digest = sha.finalize().unwrap(); assert_eq!(digest, expected); } #[test] fn rfc_vector9() { let input = [ 0x3a, 0xdd, 0xec, 0x85, 0x59, 0x32, 0x16, 0xd1, 0x61, 0x9a, 0xa0, 0x2d, 0x97, 0x56, 0x97, 0x0b, 0xfc, 0x70, 0xac, 0xe2, 0x74, 0x4f, 0x7c, 0x6b, 0x27, 0x88, 0x15, 0x10, 0x28, 0xf7, 0xb6, 0xa2, 0x55, 0x0f, 0xd7, 0x4a, 0x7e, 0x6e, 0x69, 0xc2, 0xc9, 0xb4, 0x5f, 0xc4, 0x54, 0x96, 0x6d, 0xc3, 0x1d, 0x2e, 0x10, 0xda, 0x1f, 0x95, 0xce, 0x02, 0xbe, 0xb4, 0xbf, 0x87, 0x65, 0x57, 0x4c, 0xbd, 0x6e, 0x83, 0x37, 0xef, 0x42, 0x0a, 0xdc, 0x98, 0xc1, 0x5c, 0xb6, 0xd5, 0xe4, 0xa0, 0x24, 0x1b, 0xa0, 0x04, 0x6d, 0x25, 0x0e, 0x51, 0x02, 0x31, 0xca, 0xc2, 0x04, 0x6c, 0x99, 0x16, 0x06, 0xab, 0x4e, 0xe4, 0x14, 0x5b, 0xee, 0x2f, 0xf4, 0xbb, 0x12, 0x3a, 0xab, 0x49, 0x8d, 0x9d, 0x44, 0x79, 0x4f, 0x99, 0xcc, 0xad, 0x89, 0xa9, 0xa1, 0x62, 0x12, 0x59, 0xed, 0xa7, 0x0a, 0x5b, 0x6d, 0xd4, 0xbd, 0xd8, 0x77, 0x78, 0xc9, 0x04, 0x3b, 0x93, 0x84, 0xf5, 0x49, 0x06, ]; let expected = [ 0x32, 0xba, 0x76, 0xfc, 0x30, 0xea, 0xa0, 0x20, 0x8a, 0xeb, 0x50, 0xff, 0xb5, 0xaf, 0x18, 0x64, 0xfd, 0xbf, 0x17, 0x90, 0x2a, 0x4d, 0xc0, 0xa6, 0x82, 0xc6, 0x1f, 0xce, 0xa6, 0xd9, 0x2b, 0x78, 0x32, 0x67, 0xb2, 0x10, 0x80, 0x30, 0x18, 0x37, 0xf5, 0x9d, 0xe7, 0x9c, 0x6b, 0x33, 0x7d, 0xb2, 0x52, 0x6f, 0x8a, 0x0a, 0x51, 0x0e, 0x5e, 0x53, 0xca, 0xfe, 0xd4, 0x35, 0x5f, 0xe7, 0xc2, 0xf1, ]; let mut sha = Sha384::new(); sha.input(input.as_ref()).unwrap(); let digest = sha.final_bits(0x80, 3).unwrap(); assert_eq!(digest, expected); } #[test] fn rfc_vector10() { let input = [ 0xa5, 0x5f, 0x20, 0xc4, 0x11, 0xaa, 0xd1, 0x32, 0x80, 0x7a, 0x50, 0x2d, 0x65, 0x82, 0x4e, 0x31, 0xa2, 0x30, 0x54, 0x32, 0xaa, 0x3d, 0x06, 0xd3, 0xe2, 0x82, 0xa8, 0xd8, 0x4e, 0x0d, 0xe1, 0xde, 0x69, 0x74, 0xbf, 0x49, 0x54, 0x69, 0xfc, 0x7f, 0x33, 0x8f, 0x80, 0x54, 0xd5, 0x8c, 0x26, 0xc4, 0x93, 0x60, 0xc3, 0xe8, 0x7a, 0xf5, 0x65, 0x23, 0xac, 0xf6, 0xd8, 0x9d, 0x03, 0xe5, 0x6f, 0xf2, 0xf8, 0x68, 0x00, 0x2b, 0xc3, 0xe4, 0x31, 0xed, 0xc4, 0x4d, 0xf2, 0xf0, 0x22, 0x3d, 0x4b, 0xb3, 0xb2, 0x43, 0x58, 0x6e, 0x1a, 0x7d, 0x92, 0x49, 0x36, 0x69, 0x4f, 0xcb, 0xba, 0xf8, 0x8d, 0x95, 0x19, 0xe4, 0xeb, 0x50, 0xa6, 0x44, 0xf8, 0xe4, 0xf9, 0x5e, 0xb0, 0xea, 0x95, 0xbc, 0x44, 0x65, 0xc8, 0x82, 0x1a, 0xac, 0xd2, 0xfe, 0x15, 0xab, 0x49, 0x81, 0x16, 0x4b, 0xbb, 0x6d, 0xc3, 0x2f, 0x96, 0x90, 0x87, 0xa1, 0x45, 0xb0, 0xd9, 0xcc, 0x9c, 0x67, 0xc2, 0x2b, 0x76, 0x32, 0x99, 0x41, 0x9c, 0xc4, 0x12, 0x8b, 0xe9, 0xa0, 0x77, 0xb3, 0xac, 0xe6, 0x34, 0x06, 0x4e, 0x6d, 0x99, 0x28, 0x35, 0x13, 0xdc, 0x06, 0xe7, 0x51, 0x5d, 0x0d, 0x73, 0x13, 0x2e, 0x9a, 0x0d, 0xc6, 0xd3, 0xb1, 0xf8, 0xb2, 0x46, 0xf1, 0xa9, 0x8a, 0x3f, 0xc7, 0x29, 0x41, 0xb1, 0xe3, 0xbb, 0x20, 0x98, 0xe8, 0xbf, 0x16, 0xf2, 0x68, 0xd6, 0x4f, 0x0b, 0x0f, 0x47, 0x07, 0xfe, 0x1e, 0xa1, 0xa1, 0x79, 0x1b, 0xa2, 0xf3, 0xc0, 0xc7, 0x58, 0xe5, 0xf5, 0x51, 0x86, 0x3a, 0x96, 0xc9, 0x49, 0xad, 0x47, 0xd7, 0xfb, 0x40, 0xd2, ]; let expected = [ 0xc6, 0x65, 0xbe, 0xfb, 0x36, 0xda, 0x18, 0x9d, 0x78, 0x82, 0x2d, 0x10, 0x52, 0x8c, 0xbf, 0x3b, 0x12, 0xb3, 0xee, 0xf7, 0x26, 0x03, 0x99, 0x09, 0xc1, 0xa1, 0x6a, 0x27, 0x0d, 0x48, 0x71, 0x93, 0x77, 0x96, 0x6b, 0x95, 0x7a, 0x87, 0x8e, 0x72, 0x05, 0x84, 0x77, 0x9a, 0x62, 0x82, 0x5c, 0x18, 0xda, 0x26, 0x41, 0x5e, 0x49, 0xa7, 0x17, 0x6a, 0x89, 0x4e, 0x75, 0x10, 0xfd, 0x14, 0x51, 0xf5, ]; let mut sha = Sha384::new(); sha.input(input.as_ref()).unwrap(); let digest = sha.finalize().unwrap(); assert_eq!(digest, expected); } }
pub mod account; pub mod account_utils; pub mod bpf_loader; pub mod client; pub mod fee_calculator; pub mod genesis_block; pub mod hash; pub mod instruction; pub mod instruction_processor_utils; pub mod loader_instruction; pub mod message; pub mod native_loader; pub mod packet; pub mod poh_config; pub mod pubkey; pub mod rpc_port; pub mod short_vec; pub mod signature; pub mod syscall; pub mod system_instruction; pub mod system_program; pub mod system_transaction; pub mod timing; pub mod transaction; pub mod transport; #[macro_use] extern crate serde_derive;
//! Thread-safe, asynchronous counting semaphore. //! //! A `Semaphore` instance holds a set of permits. Permits are used to //! synchronize access to a shared resource. //! //! Before accessing the shared resource, callers acquire a permit from the //! semaphore. Once the permit is acquired, the caller then enters the critical //! section. If no permits are available, then acquiring the semaphore returns //! `NotReady`. The task is notified once a permit becomes available. use loom::{ futures::AtomicTask, sync::{ atomic::{AtomicPtr, AtomicUsize}, CausalCell, }, yield_now, }; use futures::Poll; use std::fmt; use std::ptr::{self, NonNull}; use std::sync::atomic::Ordering::{self, AcqRel, Acquire, Relaxed, Release}; use std::sync::Arc; use std::usize; /// Futures-aware semaphore. pub struct Semaphore { /// Tracks both the waiter queue tail pointer and the number of remaining /// permits. state: AtomicUsize, /// waiter queue head pointer. head: CausalCell<NonNull<WaiterNode>>, /// Coordinates access to the queue head. rx_lock: AtomicUsize, /// Stub waiter node used as part of the MPSC channel algorithm. stub: Box<WaiterNode>, } /// A semaphore permit /// /// Tracks the lifecycle of a semaphore permit. /// /// An instance of `Permit` is intended to be used with a **single** instance of /// `Semaphore`. Using a single instance of `Permit` with multiple semaphore /// instances will result in unexpected behavior. /// /// `Permit` does **not** release the permit back to the semaphore on drop. It /// is the user's responsibility to ensure that `Permit::release` is called /// before dropping the permit. #[derive(Debug)] pub struct Permit { waiter: Option<Arc<WaiterNode>>, state: PermitState, } /// Error returned by `Permit::poll_acquire`. #[derive(Debug)] pub struct AcquireError(()); /// Error returned by `Permit::try_acquire`. #[derive(Debug)] pub struct TryAcquireError { kind: ErrorKind, } #[derive(Debug)] enum ErrorKind { Closed, NoPermits, } /// Node used to notify the semaphore waiter when permit is available. #[derive(Debug)] struct WaiterNode { /// Stores waiter state. /// /// See `NodeState` for more details. state: AtomicUsize, /// Task to notify when a permit is made available. task: AtomicTask, /// Next pointer in the queue of waiting senders. next: AtomicPtr<WaiterNode>, } /// Semaphore state /// /// The 2 low bits track the modes. /// /// - Closed /// - Full /// /// When not full, the rest of the `usize` tracks the total number of messages /// in the channel. When full, the rest of the `usize` is a pointer to the tail /// of the "waiting senders" queue. #[derive(Copy, Clone)] struct SemState(usize); /// Permit state #[derive(Debug, Copy, Clone, Eq, PartialEq)] enum PermitState { /// The permit has not been requested. Idle, /// Currently waiting for a permit to be made available and assigned to the /// waiter. Waiting, /// The permit has been acquired. Acquired, } /// Waiter node state #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(usize)] enum NodeState { /// Not waiting for a permit and the node is not in the wait queue. /// /// This is the initial state. Idle = 0, /// Not waiting for a permit but the node is in the wait queue. /// /// This happens when the waiter has previously requested a permit, but has /// since canceled the request. The node cannot be removed by the waiter, so /// this state informs the receiver to skip the node when it pops it from /// the wait queue. Queued = 1, /// Waiting for a permit and the node is in the wait queue. QueuedWaiting = 2, /// The waiter has been assigned a permit and the node has been removed from /// the queue. Assigned = 3, /// The semaphore has been closed. No more permits will be issued. Closed = 4, } // ===== impl Semaphore ===== impl Semaphore { /// Creates a new semaphore with the initial number of permits /// /// # Panics /// /// Panics if `permits` is zero. pub fn new(permits: usize) -> Semaphore { let stub = Box::new(WaiterNode::new()); let ptr = NonNull::new(&*stub as *const _ as *mut _).unwrap(); // Allocations are aligned debug_assert!(ptr.as_ptr() as usize & NUM_FLAG == 0); let state = SemState::new(permits, &stub); Semaphore { state: AtomicUsize::new(state.to_usize()), head: CausalCell::new(ptr), rx_lock: AtomicUsize::new(0), stub, } } /// Returns the current number of available permits pub fn available_permits(&self) -> usize { let curr = SemState::load(&self.state, Acquire); curr.available_permits() } /// Poll for a permit fn poll_permit(&self, mut permit: Option<&mut Permit>) -> Poll<(), AcquireError> { use futures::Async::*; // Load the current state let mut curr = SemState::load(&self.state, Acquire); debug!(" + poll_permit; sem-state = {:?}", curr); // Tracks a *mut WaiterNode representing an Arc clone. // // This avoids having to bump the ref count unless required. let mut maybe_strong: Option<NonNull<WaiterNode>> = None; macro_rules! undo_strong { () => { if let Some(waiter) = maybe_strong { // The waiter was cloned, but never got queued. // Before entering `poll_permit`, the waiter was in the // `Idle` state. We must transition the node back to the // idle state. let waiter = unsafe { Arc::from_raw(waiter.as_ptr()) }; waiter.revert_to_idle(); } }; } loop { let mut next = curr; if curr.is_closed() { undo_strong!(); return Err(AcquireError::closed()); } if !next.acquire_permit(&self.stub) { debug!(" + poll_permit -- no permits"); debug_assert!(curr.waiter().is_some()); if maybe_strong.is_none() { if let Some(ref mut permit) = permit { // Get the Sender's waiter node, or initialize one let waiter = permit .waiter .get_or_insert_with(|| Arc::new(WaiterNode::new())); waiter.register(); debug!(" + poll_permit -- to_queued_waiting"); if !waiter.to_queued_waiting() { debug!(" + poll_permit; waiter already queued"); // The node is alrady queued, there is no further work // to do. return Ok(NotReady); } maybe_strong = Some(WaiterNode::into_non_null(waiter.clone())); } else { // If no `waiter`, then the task is not registered and there // is no further work to do. return Ok(NotReady); } } next.set_waiter(maybe_strong.unwrap()); } debug!(" + poll_permit -- pre-CAS; next = {:?}", next); debug_assert_ne!(curr.0, 0); debug_assert_ne!(next.0, 0); match next.compare_exchange(&self.state, curr, AcqRel, Acquire) { Ok(_) => { debug!(" + poll_permit -- CAS ok"); match curr.waiter() { Some(prev_waiter) => { let waiter = maybe_strong.unwrap(); // Finish pushing unsafe { prev_waiter.as_ref().next.store(waiter.as_ptr(), Release); } debug!(" + poll_permit -- waiter pushed"); return Ok(NotReady); } None => { debug!(" + poll_permit -- permit acquired"); undo_strong!(); return Ok(Ready(())); } } } Err(actual) => { curr = actual; } } } } /// Close the semaphore. This prevents the semaphore from issuing new /// permits and notifies all pending waiters. pub fn close(&self) { debug!("+ Semaphore::close"); // Acquire the `rx_lock`, setting the "closed" flag on the lock. let prev = self.rx_lock.fetch_or(1, AcqRel); debug!(" + close -- rx_lock.fetch_add(1)"); if prev != 0 { debug!("+ close -- locked; prev = {}", prev); // Another thread has the lock and will be responsible for notifying // pending waiters. return; } self.add_permits_locked(0, true); } /// Add `n` new permits to the semaphore. pub fn add_permits(&self, n: usize) { debug!(" + add_permits; n = {}", n); if n == 0 { return; } // TODO: Handle overflow. A panic is not sufficient, the process must // abort. let prev = self.rx_lock.fetch_add(n << 1, AcqRel); debug!(" + add_permits; rx_lock.fetch_add(n << 1); n = {}", n); if prev != 0 { debug!(" + add_permits -- locked; prev = {}", prev); // Another thread has the lock and will be responsible for notifying // pending waiters. return; } self.add_permits_locked(n, false); } fn add_permits_locked(&self, mut rem: usize, mut closed: bool) { while rem > 0 || closed { debug!( " + add_permits_locked -- iter; rem = {}; closed = {:?}", rem, closed ); if closed { SemState::fetch_set_closed(&self.state, AcqRel); } // Release the permits and notify self.add_permits_locked2(rem, closed); let n = rem << 1; let actual = if closed { let actual = self.rx_lock.fetch_sub(n | 1, AcqRel); debug!( " + add_permits_locked; rx_lock.fetch_sub(n | 1); n = {}; actual={}", n, actual ); closed = false; actual } else { let actual = self.rx_lock.fetch_sub(n, AcqRel); debug!( " + add_permits_locked; rx_lock.fetch_sub(n); n = {}; actual={}", n, actual ); closed = actual & 1 == 1; actual }; rem = (actual >> 1) - rem; } debug!(" + add_permits; done"); } /// Release a specific amount of permits to the semaphore /// /// This function is called by `add_permits` after the add lock has been /// acquired. fn add_permits_locked2(&self, mut n: usize, closed: bool) { while n > 0 || closed { let waiter = match self.pop(n, closed) { Some(waiter) => waiter, None => { return; } }; debug!(" + release_n -- notify"); if waiter.notify(closed) { n = n.saturating_sub(1); debug!(" + release_n -- dec"); } } } /// Pop a waiter /// /// `rem` represents the remaining number of times the caller will pop. If /// there are no more waiters to pop, `rem` is used to set the available /// permits. fn pop(&self, rem: usize, closed: bool) -> Option<Arc<WaiterNode>> { debug!(" + pop; rem = {}", rem); 'outer: loop { unsafe { let mut head = self.head.with(|head| *head); let mut next_ptr = head.as_ref().next.load(Acquire); let stub = self.stub(); if head == stub { debug!(" + pop; head == stub"); let next = match NonNull::new(next_ptr) { Some(next) => next, None => { // This loop is not part of the standard intrusive mpsc // channel algorithm. This is where we atomically pop // the last task and add `rem` to the remaining capacity. // // This modification to the pop algorithm works because, // at this point, we have not done any work (only done // reading). We have a *pretty* good idea that there is // no concurrent pusher. // // The capacity is then atomically added by doing an // AcqRel CAS on `state`. The `state` cell is the // linchpin of the algorithm. // // By successfully CASing `head` w/ AcqRel, we ensure // that, if any thread was racing and entered a push, we // see that and abort pop, retrying as it is // "inconsistent". let mut curr = SemState::load(&self.state, Acquire); loop { if curr.has_waiter(&self.stub) { // Inconsistent debug!(" + pop; inconsistent 1"); yield_now(); continue 'outer; } // When closing the semaphore, nodes are popped // with `rem == 0`. In this case, we are not // adding permits, but notifying waiters of the // semaphore's closed state. if rem == 0 { debug_assert!(curr.is_closed(), "state = {:?}", curr); return None; } let mut next = curr; next.release_permits(rem, &self.stub); match next.compare_exchange(&self.state, curr, AcqRel, Acquire) { Ok(_) => return None, Err(actual) => { curr = actual; } } } } }; debug!(" + pop; got next waiter"); self.head.with_mut(|head| *head = next); head = next; next_ptr = next.as_ref().next.load(Acquire); } if let Some(next) = NonNull::new(next_ptr) { self.head.with_mut(|head| *head = next); return Some(Arc::from_raw(head.as_ptr())); } let state = SemState::load(&self.state, Acquire); // This must always be a pointer as the wait list is not empty. let tail = state.waiter().unwrap(); if tail != head { // Inconsistent debug!(" + pop; inconsistent 2"); yield_now(); continue 'outer; } self.push_stub(closed); next_ptr = head.as_ref().next.load(Acquire); if let Some(next) = NonNull::new(next_ptr) { self.head.with_mut(|head| *head = next); return Some(Arc::from_raw(head.as_ptr())); } // Inconsistent state, loop debug!(" + pop; inconsistent 3"); yield_now(); } } } unsafe fn push_stub(&self, closed: bool) { let stub = self.stub(); // Set the next pointer. This does not require an atomic operation as // this node is not accessible. The write will be flushed with the next // operation stub.as_ref().next.store(ptr::null_mut(), Relaxed); // Update the tail to point to the new node. We need to see the previous // node in order to update the next pointer as well as release `task` // to any other threads calling `push`. let prev = SemState::new_ptr(stub, closed).swap(&self.state, AcqRel); debug_assert_eq!(closed, prev.is_closed()); // The stub is only pushed when there are pending tasks. Because of // this, the state must *always* be in pointer mode. let prev = prev.waiter().unwrap(); // We don't want the *existing* pointer to be a stub. debug_assert_ne!(prev, stub); // Release `task` to the consume end. prev.as_ref().next.store(stub.as_ptr(), Release); } fn stub(&self) -> NonNull<WaiterNode> { unsafe { NonNull::new_unchecked(&*self.stub as *const _ as *mut _) } } } impl fmt::Debug for Semaphore { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Semaphore") .field("state", &SemState::load(&self.state, Relaxed)) .field("head", &self.head.with(|ptr| ptr)) .field("rx_lock", &self.rx_lock.load(Relaxed)) .field("stub", &self.stub) .finish() } } unsafe impl Send for Semaphore {} unsafe impl Sync for Semaphore {} // ===== impl Permit ===== impl Permit { /// Create a new `Permit`. /// /// The permit begins in the "unacquired" state. /// /// # Examples /// /// ``` /// use tokio_sync::semaphore::Permit; /// /// let permit = Permit::new(); /// assert!(!permit.is_acquired()); /// ``` pub fn new() -> Permit { Permit { waiter: None, state: PermitState::Idle, } } /// Returns true if the permit has been acquired pub fn is_acquired(&self) -> bool { self.state == PermitState::Acquired } /// Try to acquire the permit. If no permits are available, the current task /// is notified once a new permit becomes available. pub fn poll_acquire(&mut self, semaphore: &Semaphore) -> Poll<(), AcquireError> { use futures::Async::*; match self.state { PermitState::Idle => {} PermitState::Waiting => { let waiter = self.waiter.as_ref().unwrap(); if waiter.acquire()? { self.state = PermitState::Acquired; return Ok(Ready(())); } else { return Ok(NotReady); } } PermitState::Acquired => { return Ok(Ready(())); } } match semaphore.poll_permit(Some(self))? { Ready(v) => { self.state = PermitState::Acquired; Ok(Ready(v)) } NotReady => { self.state = PermitState::Waiting; Ok(NotReady) } } } /// Try to acquire the permit. pub fn try_acquire(&mut self, semaphore: &Semaphore) -> Result<(), TryAcquireError> { use futures::Async::*; match self.state { PermitState::Idle => {} PermitState::Waiting => { let waiter = self.waiter.as_ref().unwrap(); if waiter.acquire2().map_err(to_try_acquire)? { self.state = PermitState::Acquired; return Ok(()); } else { return Err(TryAcquireError::no_permits()); } } PermitState::Acquired => { return Ok(()); } } match semaphore.poll_permit(None).map_err(to_try_acquire)? { Ready(()) => { self.state = PermitState::Acquired; Ok(()) } NotReady => Err(TryAcquireError::no_permits()), } } /// Release a permit back to the semaphore pub fn release(&mut self, semaphore: &Semaphore) { if self.forget2() { semaphore.add_permits(1); } } /// Forget the permit **without** releasing it back to the semaphore. /// /// After calling `forget`, `poll_acquire` is able to acquire new permit /// from the sempahore. /// /// Repeatedly calling `forget` without associated calls to `add_permit` /// will result in the semaphore losing all permits. pub fn forget(&mut self) { self.forget2(); } /// Returns `true` if the permit was acquired fn forget2(&mut self) -> bool { match self.state { PermitState::Idle => false, PermitState::Waiting => { let ret = self.waiter.as_ref().unwrap().cancel_interest(); self.state = PermitState::Idle; ret } PermitState::Acquired => { self.state = PermitState::Idle; true } } } } // ===== impl AcquireError ==== impl AcquireError { fn closed() -> AcquireError { AcquireError(()) } } fn to_try_acquire(_: AcquireError) -> TryAcquireError { TryAcquireError::closed() } impl fmt::Display for AcquireError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } } impl ::std::error::Error for AcquireError { fn description(&self) -> &str { "semaphore closed" } } // ===== impl TryAcquireError ===== impl TryAcquireError { fn closed() -> TryAcquireError { TryAcquireError { kind: ErrorKind::Closed, } } fn no_permits() -> TryAcquireError { TryAcquireError { kind: ErrorKind::NoPermits, } } /// Returns true if the error was caused by a closed semaphore. pub fn is_closed(&self) -> bool { match self.kind { ErrorKind::Closed => true, _ => false, } } /// Returns true if the error was caused by calling `try_acquire` on a /// semaphore with no available permits. pub fn is_no_permits(&self) -> bool { match self.kind { ErrorKind::NoPermits => true, _ => false, } } } impl fmt::Display for TryAcquireError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } } impl ::std::error::Error for TryAcquireError { fn description(&self) -> &str { match self.kind { ErrorKind::Closed => "semaphore closed", ErrorKind::NoPermits => "no permits available", } } } // ===== impl WaiterNode ===== impl WaiterNode { fn new() -> WaiterNode { WaiterNode { state: AtomicUsize::new(NodeState::new().to_usize()), task: AtomicTask::new(), next: AtomicPtr::new(ptr::null_mut()), } } fn acquire(&self) -> Result<bool, AcquireError> { if self.acquire2()? { return Ok(true); } self.task.register(); self.acquire2() } fn acquire2(&self) -> Result<bool, AcquireError> { use self::NodeState::*; match Idle.compare_exchange(&self.state, Assigned, AcqRel, Acquire) { Ok(_) => Ok(true), Err(Closed) => Err(AcquireError::closed()), Err(_) => Ok(false), } } fn register(&self) { self.task.register() } /// Returns `true` if the permit has been acquired fn cancel_interest(&self) -> bool { use self::NodeState::*; match Queued.compare_exchange(&self.state, QueuedWaiting, AcqRel, Acquire) { // Successfully removed interest from the queued node. The permit // has not been assigned to the node. Ok(_) => false, // The semaphore has been closed, there is no further action to // take. Err(Closed) => false, // The permit has been assigned. It must be acquired in order to // be released back to the semaphore. Err(Assigned) => { match self.acquire2() { Ok(true) => true, // Not a reachable state Ok(false) => panic!(), // The semaphore has been closed, no further action to take. Err(_) => false, } } Err(state) => panic!("unexpected state = {:?}", state), } } /// Transition the state to `QueuedWaiting`. /// /// This step can only happen from `Queued` or from `Idle`. /// /// Returns `true` if transitioning into a queued state. fn to_queued_waiting(&self) -> bool { use self::NodeState::*; let mut curr = NodeState::load(&self.state, Acquire); loop { debug_assert!(curr == Idle || curr == Queued, "actual = {:?}", curr); let next = QueuedWaiting; match next.compare_exchange(&self.state, curr, AcqRel, Acquire) { Ok(_) => { if curr.is_queued() { return false; } else { // Transitioned to queued, reset next pointer self.next.store(ptr::null_mut(), Relaxed); return true; } } Err(actual) => { curr = actual; } } } } /// Notify the waiter /// /// Returns `true` if the waiter accepts the notification fn notify(&self, closed: bool) -> bool { use self::NodeState::*; // Assume QueuedWaiting state let mut curr = QueuedWaiting; loop { let next = match curr { Queued => Idle, QueuedWaiting => { if closed { Closed } else { Assigned } } actual => panic!("actual = {:?}", actual), }; match next.compare_exchange(&self.state, curr, AcqRel, Acquire) { Ok(_) => match curr { QueuedWaiting => { debug!(" + notify -- task notified"); self.task.notify(); return true; } other => { debug!(" + notify -- not notified; state = {:?}", other); return false; } }, Err(actual) => curr = actual, } } } fn revert_to_idle(&self) { use self::NodeState::Idle; // There are no other handles to the node NodeState::store(&self.state, Idle, Relaxed); } fn into_non_null(arc: Arc<WaiterNode>) -> NonNull<WaiterNode> { let ptr = Arc::into_raw(arc); unsafe { NonNull::new_unchecked(ptr as *mut _) } } } // ===== impl State ===== /// Flag differentiating between available permits and waiter pointers. /// /// If we assume pointers are properly aligned, then the least significant bit /// will always be zero. So, we use that bit to track if the value represents a /// number. const NUM_FLAG: usize = 0b01; const CLOSED_FLAG: usize = 0b10; const MAX_PERMITS: usize = usize::MAX >> NUM_SHIFT; /// When representing "numbers", the state has to be shifted this much (to get /// rid of the flag bit). const NUM_SHIFT: usize = 2; impl SemState { /// Returns a new default `State` value. fn new(permits: usize, stub: &WaiterNode) -> SemState { assert!(permits <= MAX_PERMITS); if permits > 0 { SemState((permits << NUM_SHIFT) | NUM_FLAG) } else { SemState(stub as *const _ as usize) } } /// Returns a `State` tracking `ptr` as the tail of the queue. fn new_ptr(tail: NonNull<WaiterNode>, closed: bool) -> SemState { let mut val = tail.as_ptr() as usize; if closed { val |= CLOSED_FLAG; } SemState(val) } /// Returns the amount of remaining capacity fn available_permits(&self) -> usize { if !self.has_available_permits() { return 0; } self.0 >> NUM_SHIFT } /// Returns true if the state has permits that can be claimed by a waiter. fn has_available_permits(&self) -> bool { self.0 & NUM_FLAG == NUM_FLAG } fn has_waiter(&self, stub: &WaiterNode) -> bool { !self.has_available_permits() && !self.is_stub(stub) } /// Try to acquire a permit /// /// # Return /// /// Returns `true` if the permit was acquired, `false` otherwise. If `false` /// is returned, it can be assumed that `State` represents the head pointer /// in the mpsc channel. fn acquire_permit(&mut self, stub: &WaiterNode) -> bool { if !self.has_available_permits() { return false; } debug_assert!(self.waiter().is_none()); self.0 -= 1 << NUM_SHIFT; if self.0 == NUM_FLAG { // Set the state to the stub pointer. self.0 = stub as *const _ as usize; } true } /// Release permits /// /// Returns `true` if the permits were accepted. fn release_permits(&mut self, permits: usize, stub: &WaiterNode) { debug_assert!(permits > 0); if self.is_stub(stub) { self.0 = (permits << NUM_SHIFT) | NUM_FLAG | (self.0 & CLOSED_FLAG); return; } debug_assert!(self.has_available_permits()); self.0 += permits << NUM_SHIFT; } fn is_waiter(&self) -> bool { self.0 & NUM_FLAG == 0 } /// Returns the waiter, if one is set. fn waiter(&self) -> Option<NonNull<WaiterNode>> { if self.is_waiter() { let waiter = NonNull::new(self.as_ptr()).expect("null pointer stored"); Some(waiter) } else { None } } /// Assumes `self` represents a pointer fn as_ptr(&self) -> *mut WaiterNode { (self.0 & !CLOSED_FLAG) as *mut WaiterNode } /// Set to a pointer to a waiter. /// /// This can only be done from the full state. fn set_waiter(&mut self, waiter: NonNull<WaiterNode>) { let waiter = waiter.as_ptr() as usize; debug_assert!(waiter & NUM_FLAG == 0); debug_assert!(!self.is_closed()); self.0 = waiter; } fn is_stub(&self, stub: &WaiterNode) -> bool { self.as_ptr() as usize == stub as *const _ as usize } /// Load the state from an AtomicUsize. fn load(cell: &AtomicUsize, ordering: Ordering) -> SemState { let value = cell.load(ordering); debug!(" + SemState::load; value = {}", value); SemState(value) } /// Swap the values fn swap(&self, cell: &AtomicUsize, ordering: Ordering) -> SemState { let prev = SemState(cell.swap(self.to_usize(), ordering)); debug_assert_eq!(prev.is_closed(), self.is_closed()); prev } /// Compare and exchange the current value into the provided cell fn compare_exchange( &self, cell: &AtomicUsize, prev: SemState, success: Ordering, failure: Ordering, ) -> Result<SemState, SemState> { debug_assert_eq!(prev.is_closed(), self.is_closed()); let res = cell.compare_exchange(prev.to_usize(), self.to_usize(), success, failure); debug!( " + SemState::compare_exchange; prev = {}; next = {}; result = {:?}", prev.to_usize(), self.to_usize(), res ); res.map(SemState).map_err(SemState) } fn fetch_set_closed(cell: &AtomicUsize, ordering: Ordering) -> SemState { let value = cell.fetch_or(CLOSED_FLAG, ordering); SemState(value) } fn is_closed(&self) -> bool { self.0 & CLOSED_FLAG == CLOSED_FLAG } /// Converts the state into a `usize` representation. fn to_usize(&self) -> usize { self.0 } } impl fmt::Debug for SemState { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut fmt = fmt.debug_struct("SemState"); if self.is_waiter() { fmt.field("state", &"<waiter>"); } else { fmt.field("permits", &self.available_permits()); } fmt.finish() } } // ===== impl NodeState ===== impl NodeState { fn new() -> NodeState { NodeState::Idle } fn from_usize(value: usize) -> NodeState { use self::NodeState::*; match value { 0 => Idle, 1 => Queued, 2 => QueuedWaiting, 3 => Assigned, 4 => Closed, _ => panic!(), } } fn load(cell: &AtomicUsize, ordering: Ordering) -> NodeState { NodeState::from_usize(cell.load(ordering)) } /// Store a value fn store(cell: &AtomicUsize, value: NodeState, ordering: Ordering) { cell.store(value.to_usize(), ordering); } fn compare_exchange( &self, cell: &AtomicUsize, prev: NodeState, success: Ordering, failure: Ordering, ) -> Result<NodeState, NodeState> { cell.compare_exchange(prev.to_usize(), self.to_usize(), success, failure) .map(NodeState::from_usize) .map_err(NodeState::from_usize) } /// Returns `true` if `self` represents a queued state. fn is_queued(&self) -> bool { use self::NodeState::*; match *self { Queued | QueuedWaiting => true, _ => false, } } fn to_usize(&self) -> usize { *self as usize } }
use std::collections::HashMap; use std::io; use std::io::Read; use regex::Regex; fn main() { let mut input = String::new(); io::stdin().read_to_string(&mut input).unwrap(); let re = Regex::new(r"(?m)(?:^mask = ([01X]+)$)|(?:^mem\[(\d+)\] = (\d+)$)").unwrap(); let mut mem = HashMap::new(); let mut mask_en = 0; let mut mask_dis = 0xFFFFFFFFF; for i in re.captures_iter(&input) { if let Some(mask) = i.get(1) { mask_en = mask.as_str().chars().fold(0, |acc, x| { (acc << 1) | match x { '1' => 1, _ => 0 } }); mask_dis = mask.as_str().chars().fold(0, |acc, x| { (acc << 1) | match x { '0' => 0, _ => 1 } }); } else if let (Some(addr), Some(val)) = (i.get(2), i.get(3)) { let addr: u64 = addr.as_str().parse().unwrap(); let val: u64 = val.as_str().parse().unwrap(); mem.insert(addr, (val & mask_dis) | mask_en); } } println!("{}", mem.values().sum::<u64>()); }
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_structure_associate_file_system_aliases_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::AssociateFileSystemAliasesInput, ) { if let Some(var_1) = &input.client_request_token { object.key("ClientRequestToken").string(var_1); } if let Some(var_2) = &input.file_system_id { object.key("FileSystemId").string(var_2); } if let Some(var_3) = &input.aliases { let mut array_4 = object.key("Aliases").start_array(); for item_5 in var_3 { { array_4.value().string(item_5); } } array_4.finish(); } } pub fn serialize_structure_cancel_data_repository_task_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::CancelDataRepositoryTaskInput, ) { if let Some(var_6) = &input.task_id { object.key("TaskId").string(var_6); } } pub fn serialize_structure_copy_backup_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::CopyBackupInput, ) { if let Some(var_7) = &input.client_request_token { object.key("ClientRequestToken").string(var_7); } if let Some(var_8) = &input.source_backup_id { object.key("SourceBackupId").string(var_8); } if let Some(var_9) = &input.source_region { object.key("SourceRegion").string(var_9); } if let Some(var_10) = &input.kms_key_id { object.key("KmsKeyId").string(var_10); } if let Some(var_11) = &input.copy_tags { object.key("CopyTags").boolean(*var_11); } if let Some(var_12) = &input.tags { let mut array_13 = object.key("Tags").start_array(); for item_14 in var_12 { { let mut object_15 = array_13.value().start_object(); crate::json_ser::serialize_structure_tag(&mut object_15, item_14); object_15.finish(); } } array_13.finish(); } } pub fn serialize_structure_create_backup_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateBackupInput, ) { if let Some(var_16) = &input.file_system_id { object.key("FileSystemId").string(var_16); } if let Some(var_17) = &input.client_request_token { object.key("ClientRequestToken").string(var_17); } if let Some(var_18) = &input.tags { let mut array_19 = object.key("Tags").start_array(); for item_20 in var_18 { { let mut object_21 = array_19.value().start_object(); crate::json_ser::serialize_structure_tag(&mut object_21, item_20); object_21.finish(); } } array_19.finish(); } } pub fn serialize_structure_create_data_repository_task_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateDataRepositoryTaskInput, ) { if let Some(var_22) = &input.r#type { object.key("Type").string(var_22.as_str()); } if let Some(var_23) = &input.paths { let mut array_24 = object.key("Paths").start_array(); for item_25 in var_23 { { array_24.value().string(item_25); } } array_24.finish(); } if let Some(var_26) = &input.file_system_id { object.key("FileSystemId").string(var_26); } if let Some(var_27) = &input.report { let mut object_28 = object.key("Report").start_object(); crate::json_ser::serialize_structure_completion_report(&mut object_28, var_27); object_28.finish(); } if let Some(var_29) = &input.client_request_token { object.key("ClientRequestToken").string(var_29); } if let Some(var_30) = &input.tags { let mut array_31 = object.key("Tags").start_array(); for item_32 in var_30 { { let mut object_33 = array_31.value().start_object(); crate::json_ser::serialize_structure_tag(&mut object_33, item_32); object_33.finish(); } } array_31.finish(); } } pub fn serialize_structure_create_file_system_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateFileSystemInput, ) { if let Some(var_34) = &input.client_request_token { object.key("ClientRequestToken").string(var_34); } if let Some(var_35) = &input.file_system_type { object.key("FileSystemType").string(var_35.as_str()); } if let Some(var_36) = &input.storage_capacity { object.key("StorageCapacity").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_36).into()), ); } if let Some(var_37) = &input.storage_type { object.key("StorageType").string(var_37.as_str()); } if let Some(var_38) = &input.subnet_ids { let mut array_39 = object.key("SubnetIds").start_array(); for item_40 in var_38 { { array_39.value().string(item_40); } } array_39.finish(); } if let Some(var_41) = &input.security_group_ids { let mut array_42 = object.key("SecurityGroupIds").start_array(); for item_43 in var_41 { { array_42.value().string(item_43); } } array_42.finish(); } if let Some(var_44) = &input.tags { let mut array_45 = object.key("Tags").start_array(); for item_46 in var_44 { { let mut object_47 = array_45.value().start_object(); crate::json_ser::serialize_structure_tag(&mut object_47, item_46); object_47.finish(); } } array_45.finish(); } if let Some(var_48) = &input.kms_key_id { object.key("KmsKeyId").string(var_48); } if let Some(var_49) = &input.windows_configuration { let mut object_50 = object.key("WindowsConfiguration").start_object(); crate::json_ser::serialize_structure_create_file_system_windows_configuration( &mut object_50, var_49, ); object_50.finish(); } if let Some(var_51) = &input.lustre_configuration { let mut object_52 = object.key("LustreConfiguration").start_object(); crate::json_ser::serialize_structure_create_file_system_lustre_configuration( &mut object_52, var_51, ); object_52.finish(); } } pub fn serialize_structure_create_file_system_from_backup_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateFileSystemFromBackupInput, ) { if let Some(var_53) = &input.backup_id { object.key("BackupId").string(var_53); } if let Some(var_54) = &input.client_request_token { object.key("ClientRequestToken").string(var_54); } if let Some(var_55) = &input.subnet_ids { let mut array_56 = object.key("SubnetIds").start_array(); for item_57 in var_55 { { array_56.value().string(item_57); } } array_56.finish(); } if let Some(var_58) = &input.security_group_ids { let mut array_59 = object.key("SecurityGroupIds").start_array(); for item_60 in var_58 { { array_59.value().string(item_60); } } array_59.finish(); } if let Some(var_61) = &input.tags { let mut array_62 = object.key("Tags").start_array(); for item_63 in var_61 { { let mut object_64 = array_62.value().start_object(); crate::json_ser::serialize_structure_tag(&mut object_64, item_63); object_64.finish(); } } array_62.finish(); } if let Some(var_65) = &input.windows_configuration { let mut object_66 = object.key("WindowsConfiguration").start_object(); crate::json_ser::serialize_structure_create_file_system_windows_configuration( &mut object_66, var_65, ); object_66.finish(); } if let Some(var_67) = &input.lustre_configuration { let mut object_68 = object.key("LustreConfiguration").start_object(); crate::json_ser::serialize_structure_create_file_system_lustre_configuration( &mut object_68, var_67, ); object_68.finish(); } if let Some(var_69) = &input.storage_type { object.key("StorageType").string(var_69.as_str()); } if let Some(var_70) = &input.kms_key_id { object.key("KmsKeyId").string(var_70); } } pub fn serialize_structure_delete_backup_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::DeleteBackupInput, ) { if let Some(var_71) = &input.backup_id { object.key("BackupId").string(var_71); } if let Some(var_72) = &input.client_request_token { object.key("ClientRequestToken").string(var_72); } } pub fn serialize_structure_delete_file_system_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::DeleteFileSystemInput, ) { if let Some(var_73) = &input.file_system_id { object.key("FileSystemId").string(var_73); } if let Some(var_74) = &input.client_request_token { object.key("ClientRequestToken").string(var_74); } if let Some(var_75) = &input.windows_configuration { let mut object_76 = object.key("WindowsConfiguration").start_object(); crate::json_ser::serialize_structure_delete_file_system_windows_configuration( &mut object_76, var_75, ); object_76.finish(); } if let Some(var_77) = &input.lustre_configuration { let mut object_78 = object.key("LustreConfiguration").start_object(); crate::json_ser::serialize_structure_delete_file_system_lustre_configuration( &mut object_78, var_77, ); object_78.finish(); } } pub fn serialize_structure_describe_backups_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::DescribeBackupsInput, ) { if let Some(var_79) = &input.backup_ids { let mut array_80 = object.key("BackupIds").start_array(); for item_81 in var_79 { { array_80.value().string(item_81); } } array_80.finish(); } if let Some(var_82) = &input.filters { let mut array_83 = object.key("Filters").start_array(); for item_84 in var_82 { { let mut object_85 = array_83.value().start_object(); crate::json_ser::serialize_structure_filter(&mut object_85, item_84); object_85.finish(); } } array_83.finish(); } if let Some(var_86) = &input.max_results { object.key("MaxResults").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_86).into()), ); } if let Some(var_87) = &input.next_token { object.key("NextToken").string(var_87); } } pub fn serialize_structure_describe_data_repository_tasks_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::DescribeDataRepositoryTasksInput, ) { if let Some(var_88) = &input.task_ids { let mut array_89 = object.key("TaskIds").start_array(); for item_90 in var_88 { { array_89.value().string(item_90); } } array_89.finish(); } if let Some(var_91) = &input.filters { let mut array_92 = object.key("Filters").start_array(); for item_93 in var_91 { { let mut object_94 = array_92.value().start_object(); crate::json_ser::serialize_structure_data_repository_task_filter( &mut object_94, item_93, ); object_94.finish(); } } array_92.finish(); } if let Some(var_95) = &input.max_results { object.key("MaxResults").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_95).into()), ); } if let Some(var_96) = &input.next_token { object.key("NextToken").string(var_96); } } pub fn serialize_structure_describe_file_system_aliases_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::DescribeFileSystemAliasesInput, ) { if let Some(var_97) = &input.client_request_token { object.key("ClientRequestToken").string(var_97); } if let Some(var_98) = &input.file_system_id { object.key("FileSystemId").string(var_98); } if let Some(var_99) = &input.max_results { object.key("MaxResults").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_99).into()), ); } if let Some(var_100) = &input.next_token { object.key("NextToken").string(var_100); } } pub fn serialize_structure_describe_file_systems_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::DescribeFileSystemsInput, ) { if let Some(var_101) = &input.file_system_ids { let mut array_102 = object.key("FileSystemIds").start_array(); for item_103 in var_101 { { array_102.value().string(item_103); } } array_102.finish(); } if let Some(var_104) = &input.max_results { object.key("MaxResults").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_104).into()), ); } if let Some(var_105) = &input.next_token { object.key("NextToken").string(var_105); } } pub fn serialize_structure_disassociate_file_system_aliases_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::DisassociateFileSystemAliasesInput, ) { if let Some(var_106) = &input.client_request_token { object.key("ClientRequestToken").string(var_106); } if let Some(var_107) = &input.file_system_id { object.key("FileSystemId").string(var_107); } if let Some(var_108) = &input.aliases { let mut array_109 = object.key("Aliases").start_array(); for item_110 in var_108 { { array_109.value().string(item_110); } } array_109.finish(); } } pub fn serialize_structure_list_tags_for_resource_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::ListTagsForResourceInput, ) { if let Some(var_111) = &input.resource_arn { object.key("ResourceARN").string(var_111); } if let Some(var_112) = &input.max_results { object.key("MaxResults").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_112).into()), ); } if let Some(var_113) = &input.next_token { object.key("NextToken").string(var_113); } } pub fn serialize_structure_tag_resource_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::TagResourceInput, ) { if let Some(var_114) = &input.resource_arn { object.key("ResourceARN").string(var_114); } if let Some(var_115) = &input.tags { let mut array_116 = object.key("Tags").start_array(); for item_117 in var_115 { { let mut object_118 = array_116.value().start_object(); crate::json_ser::serialize_structure_tag(&mut object_118, item_117); object_118.finish(); } } array_116.finish(); } } pub fn serialize_structure_untag_resource_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::UntagResourceInput, ) { if let Some(var_119) = &input.resource_arn { object.key("ResourceARN").string(var_119); } if let Some(var_120) = &input.tag_keys { let mut array_121 = object.key("TagKeys").start_array(); for item_122 in var_120 { { array_121.value().string(item_122); } } array_121.finish(); } } pub fn serialize_structure_update_file_system_input( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::input::UpdateFileSystemInput, ) { if let Some(var_123) = &input.file_system_id { object.key("FileSystemId").string(var_123); } if let Some(var_124) = &input.client_request_token { object.key("ClientRequestToken").string(var_124); } if let Some(var_125) = &input.storage_capacity { object.key("StorageCapacity").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_125).into()), ); } if let Some(var_126) = &input.windows_configuration { let mut object_127 = object.key("WindowsConfiguration").start_object(); crate::json_ser::serialize_structure_update_file_system_windows_configuration( &mut object_127, var_126, ); object_127.finish(); } if let Some(var_128) = &input.lustre_configuration { let mut object_129 = object.key("LustreConfiguration").start_object(); crate::json_ser::serialize_structure_update_file_system_lustre_configuration( &mut object_129, var_128, ); object_129.finish(); } } pub fn serialize_structure_tag( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::Tag, ) { if let Some(var_130) = &input.key { object.key("Key").string(var_130); } if let Some(var_131) = &input.value { object.key("Value").string(var_131); } } pub fn serialize_structure_completion_report( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::CompletionReport, ) { if let Some(var_132) = &input.enabled { object.key("Enabled").boolean(*var_132); } if let Some(var_133) = &input.path { object.key("Path").string(var_133); } if let Some(var_134) = &input.format { object.key("Format").string(var_134.as_str()); } if let Some(var_135) = &input.scope { object.key("Scope").string(var_135.as_str()); } } pub fn serialize_structure_create_file_system_windows_configuration( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::CreateFileSystemWindowsConfiguration, ) { if let Some(var_136) = &input.active_directory_id { object.key("ActiveDirectoryId").string(var_136); } if let Some(var_137) = &input.self_managed_active_directory_configuration { let mut object_138 = object .key("SelfManagedActiveDirectoryConfiguration") .start_object(); crate::json_ser::serialize_structure_self_managed_active_directory_configuration( &mut object_138, var_137, ); object_138.finish(); } if let Some(var_139) = &input.deployment_type { object.key("DeploymentType").string(var_139.as_str()); } if let Some(var_140) = &input.preferred_subnet_id { object.key("PreferredSubnetId").string(var_140); } if let Some(var_141) = &input.throughput_capacity { object.key("ThroughputCapacity").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_141).into()), ); } if let Some(var_142) = &input.weekly_maintenance_start_time { object.key("WeeklyMaintenanceStartTime").string(var_142); } if let Some(var_143) = &input.daily_automatic_backup_start_time { object.key("DailyAutomaticBackupStartTime").string(var_143); } if let Some(var_144) = &input.automatic_backup_retention_days { object.key("AutomaticBackupRetentionDays").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_144).into()), ); } if let Some(var_145) = &input.copy_tags_to_backups { object.key("CopyTagsToBackups").boolean(*var_145); } if let Some(var_146) = &input.aliases { let mut array_147 = object.key("Aliases").start_array(); for item_148 in var_146 { { array_147.value().string(item_148); } } array_147.finish(); } if let Some(var_149) = &input.audit_log_configuration { let mut object_150 = object.key("AuditLogConfiguration").start_object(); crate::json_ser::serialize_structure_windows_audit_log_create_configuration( &mut object_150, var_149, ); object_150.finish(); } } pub fn serialize_structure_create_file_system_lustre_configuration( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::CreateFileSystemLustreConfiguration, ) { if let Some(var_151) = &input.weekly_maintenance_start_time { object.key("WeeklyMaintenanceStartTime").string(var_151); } if let Some(var_152) = &input.import_path { object.key("ImportPath").string(var_152); } if let Some(var_153) = &input.export_path { object.key("ExportPath").string(var_153); } if let Some(var_154) = &input.imported_file_chunk_size { object.key("ImportedFileChunkSize").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_154).into()), ); } if let Some(var_155) = &input.deployment_type { object.key("DeploymentType").string(var_155.as_str()); } if let Some(var_156) = &input.auto_import_policy { object.key("AutoImportPolicy").string(var_156.as_str()); } if let Some(var_157) = &input.per_unit_storage_throughput { object.key("PerUnitStorageThroughput").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_157).into()), ); } if let Some(var_158) = &input.daily_automatic_backup_start_time { object.key("DailyAutomaticBackupStartTime").string(var_158); } if let Some(var_159) = &input.automatic_backup_retention_days { object.key("AutomaticBackupRetentionDays").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_159).into()), ); } if let Some(var_160) = &input.copy_tags_to_backups { object.key("CopyTagsToBackups").boolean(*var_160); } if let Some(var_161) = &input.drive_cache_type { object.key("DriveCacheType").string(var_161.as_str()); } if let Some(var_162) = &input.data_compression_type { object.key("DataCompressionType").string(var_162.as_str()); } } pub fn serialize_structure_delete_file_system_windows_configuration( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::DeleteFileSystemWindowsConfiguration, ) { if let Some(var_163) = &input.skip_final_backup { object.key("SkipFinalBackup").boolean(*var_163); } if let Some(var_164) = &input.final_backup_tags { let mut array_165 = object.key("FinalBackupTags").start_array(); for item_166 in var_164 { { let mut object_167 = array_165.value().start_object(); crate::json_ser::serialize_structure_tag(&mut object_167, item_166); object_167.finish(); } } array_165.finish(); } } pub fn serialize_structure_delete_file_system_lustre_configuration( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::DeleteFileSystemLustreConfiguration, ) { if let Some(var_168) = &input.skip_final_backup { object.key("SkipFinalBackup").boolean(*var_168); } if let Some(var_169) = &input.final_backup_tags { let mut array_170 = object.key("FinalBackupTags").start_array(); for item_171 in var_169 { { let mut object_172 = array_170.value().start_object(); crate::json_ser::serialize_structure_tag(&mut object_172, item_171); object_172.finish(); } } array_170.finish(); } } pub fn serialize_structure_filter( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::Filter, ) { if let Some(var_173) = &input.name { object.key("Name").string(var_173.as_str()); } if let Some(var_174) = &input.values { let mut array_175 = object.key("Values").start_array(); for item_176 in var_174 { { array_175.value().string(item_176); } } array_175.finish(); } } pub fn serialize_structure_data_repository_task_filter( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::DataRepositoryTaskFilter, ) { if let Some(var_177) = &input.name { object.key("Name").string(var_177.as_str()); } if let Some(var_178) = &input.values { let mut array_179 = object.key("Values").start_array(); for item_180 in var_178 { { array_179.value().string(item_180); } } array_179.finish(); } } pub fn serialize_structure_update_file_system_windows_configuration( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::UpdateFileSystemWindowsConfiguration, ) { if let Some(var_181) = &input.weekly_maintenance_start_time { object.key("WeeklyMaintenanceStartTime").string(var_181); } if let Some(var_182) = &input.daily_automatic_backup_start_time { object.key("DailyAutomaticBackupStartTime").string(var_182); } if let Some(var_183) = &input.automatic_backup_retention_days { object.key("AutomaticBackupRetentionDays").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_183).into()), ); } if let Some(var_184) = &input.throughput_capacity { object.key("ThroughputCapacity").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_184).into()), ); } if let Some(var_185) = &input.self_managed_active_directory_configuration { let mut object_186 = object .key("SelfManagedActiveDirectoryConfiguration") .start_object(); crate::json_ser::serialize_structure_self_managed_active_directory_configuration_updates( &mut object_186, var_185, ); object_186.finish(); } if let Some(var_187) = &input.audit_log_configuration { let mut object_188 = object.key("AuditLogConfiguration").start_object(); crate::json_ser::serialize_structure_windows_audit_log_create_configuration( &mut object_188, var_187, ); object_188.finish(); } } pub fn serialize_structure_update_file_system_lustre_configuration( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::UpdateFileSystemLustreConfiguration, ) { if let Some(var_189) = &input.weekly_maintenance_start_time { object.key("WeeklyMaintenanceStartTime").string(var_189); } if let Some(var_190) = &input.daily_automatic_backup_start_time { object.key("DailyAutomaticBackupStartTime").string(var_190); } if let Some(var_191) = &input.automatic_backup_retention_days { object.key("AutomaticBackupRetentionDays").number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_191).into()), ); } if let Some(var_192) = &input.auto_import_policy { object.key("AutoImportPolicy").string(var_192.as_str()); } if let Some(var_193) = &input.data_compression_type { object.key("DataCompressionType").string(var_193.as_str()); } } pub fn serialize_structure_self_managed_active_directory_configuration( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::SelfManagedActiveDirectoryConfiguration, ) { if let Some(var_194) = &input.domain_name { object.key("DomainName").string(var_194); } if let Some(var_195) = &input.organizational_unit_distinguished_name { object .key("OrganizationalUnitDistinguishedName") .string(var_195); } if let Some(var_196) = &input.file_system_administrators_group { object.key("FileSystemAdministratorsGroup").string(var_196); } if let Some(var_197) = &input.user_name { object.key("UserName").string(var_197); } if let Some(var_198) = &input.password { object.key("Password").string(var_198); } if let Some(var_199) = &input.dns_ips { let mut array_200 = object.key("DnsIps").start_array(); for item_201 in var_199 { { array_200.value().string(item_201); } } array_200.finish(); } } pub fn serialize_structure_windows_audit_log_create_configuration( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::WindowsAuditLogCreateConfiguration, ) { if let Some(var_202) = &input.file_access_audit_log_level { object .key("FileAccessAuditLogLevel") .string(var_202.as_str()); } if let Some(var_203) = &input.file_share_access_audit_log_level { object .key("FileShareAccessAuditLogLevel") .string(var_203.as_str()); } if let Some(var_204) = &input.audit_log_destination { object.key("AuditLogDestination").string(var_204); } } pub fn serialize_structure_self_managed_active_directory_configuration_updates( object: &mut smithy_json::serialize::JsonObjectWriter, input: &crate::model::SelfManagedActiveDirectoryConfigurationUpdates, ) { if let Some(var_205) = &input.user_name { object.key("UserName").string(var_205); } if let Some(var_206) = &input.password { object.key("Password").string(var_206); } if let Some(var_207) = &input.dns_ips { let mut array_208 = object.key("DnsIps").start_array(); for item_209 in var_207 { { array_208.value().string(item_209); } } array_208.finish(); } }
use crate::errors::ServiceError; use crate::models::msg::Msg; use crate::schema::option_group; use crate::utils::validator::{re_test_name, Validate}; use actix::Message; use actix_web::error; use actix_web::Error; use diesel; use uuid::Uuid; #[derive(Deserialize, Serialize, Debug, Message, Insertable)] #[rtype(result = "Result<Msg, ServiceError>")] #[table_name = "option_group"] pub struct New { pub name: String, pub shop_id: Uuid, pub default: i32, pub options: Vec<i32>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct InpNew { pub name: String, pub default: i32, pub options: Vec<i32>, } impl Validate for InpNew { fn validate(&self) -> Result<(), Error> { let name = &self.name; let check_name = re_test_name(name); if check_name { Ok(()) } else { Err(error::ErrorBadRequest("option name")) } } } impl InpNew { pub fn new(&self, shop_id: Uuid) -> New { New { name: self.name.to_string(), shop_id: shop_id, options: self.options.clone(), default: self.default.clone(), } } } #[derive(Deserialize, Serialize, Debug, Message, Identifiable, AsChangeset)] #[rtype(result = "Result<Msg, ServiceError>")] #[table_name = "option_group"] pub struct Update { pub id: i32, pub shop_id: Uuid, pub name: String, pub default: i32, pub options: Vec<i32>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct InpUpdate { pub id: i32, pub name: String, pub default: i32, pub options: Vec<i32>, } impl Validate for InpUpdate { fn validate(&self) -> Result<(), Error> { let name = &self.name; let check_name = re_test_name(name); if check_name { Ok(()) } else { Err(error::ErrorBadRequest("option name")) } } } impl InpUpdate { pub fn new(&self, shop_id: Uuid) -> Update { Update { id: self.id, shop_id: shop_id, name: self.name.to_string(), options: self.options.clone(), default: self.default.clone(), } } } #[derive(Deserialize, Serialize, Debug, Message, Identifiable)] #[rtype(result = "Result<Msg, ServiceError>")] #[table_name = "option_group"] pub struct Get { pub id: i32, pub shop_id: Uuid, } #[derive(Deserialize, Serialize, Debug, Message, Identifiable, AsChangeset)] #[rtype(result = "Result<Msg, ServiceError>")] #[table_name = "option_group"] pub struct Delete { pub id: i32, pub shop_id: Uuid, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct InpDelete { pub id: i32, } impl Validate for InpDelete { fn validate(&self) -> Result<(), Error> { Ok(()) } } impl InpDelete { pub fn new(&self, shop_id: Uuid) -> Delete { Delete { id: self.id, shop_id: shop_id, } } } #[derive(Deserialize, Serialize, Debug, Message)] #[rtype(result = "Result<Msg, ServiceError>")] pub struct GetList { pub shop_id: Uuid, } use diesel::sql_types::{Integer, Json, Text}; #[derive(Clone, Debug, Serialize, Deserialize, QueryableByName)] pub struct SimpleOptionGroup { #[sql_type = "Integer"] pub og_id: i32, #[sql_type = "Text"] pub og_nm: String, #[sql_type = "Integer"] pub og_default: i32, #[sql_type = "Json"] pub o: serde_json::Value, }
mod is_unique; pub use self::is_unique::*;
#[inline] pub unsafe fn outb(port: u16, value: u8) { asm!("outb %al, %dx" :: "{dx}" (port), "{al}" (value) :: "volatile" ); } static VIDEO_MEM: u64 = 0xB8000; static mut cursor_x: u64 = 0; static mut cursor_y: u64 = 0; #[inline] unsafe fn update_cursor() { let offset: u64 = cursor_y * 80 + cursor_x; let off_low = offset & 0xFF; let off_high = (offset >> 8) & 0xFF; outb(0x3D4, 0x0F); outb(0x3D5, off_low as u8); outb(0x3D4, 0x0E); outb(0x3D5, off_high as u8); } #[inline] unsafe fn newline() { cursor_x = 0; cursor_y += 1; update_cursor(); } #[inline] unsafe fn forward_cursor() { cursor_x += 1; if(cursor_x >= 80) { newline(); } // if(cursor_y >= 25) // scroll(); update_cursor(); } #[inline] unsafe fn do_putcar(c: char, color: Color) { /* get video_ptr */ let offset: u64 = cursor_y * 80 + cursor_x; let video_ptr: u64 = VIDEO_MEM + offset * 2; *(video_ptr as *mut char) = c; *((video_ptr + 1) as *mut u8) = color as u8; forward_cursor(); } enum Color { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Pink = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightPink = 13, Yellow = 14, White = 15 } pub fn putcar(c: char) { /* body */ match c { '\n' => unsafe { newline() }, _ => unsafe { do_putcar(c, LightGray); } } }
include_generated!(); impl ::application::Application { pub fn create_and_exit<F: FnOnce(&mut ::application::Application) -> i32>(f: F) -> ! { let exit_code = { let mut args = ::qt_core::core_application::CoreApplicationArgs::from_real(); let mut app = unsafe { ::application::Application::new(args.get()) }; f(app.as_mut()) }; ::std::process::exit(exit_code) } }
use rand::prelude::{RngCore, SeedableRng, StdRng}; use solana_remote_wallet::ledger::LedgerWallet; use solana_remote_wallet::remote_wallet::{ initialize_wallet_manager, DerivationPath, RemoteWallet, }; use solana_sdk::{ instruction::{AccountMeta, Instruction}, message::Message, pubkey::Pubkey, system_instruction, system_program, }; use solana_stake_program::{stake_instruction, stake_state}; use solana_vote_program::{vote_instruction, vote_state}; use std::collections::HashSet; use std::sync::Arc; fn get_ledger() -> (Arc<LedgerWallet>, Pubkey) { let wallet_manager = initialize_wallet_manager().expect("Couldn't start wallet manager"); // Update device list const NO_DEVICE_HELP: &str = "No Ledger found, make sure you have a unlocked Ledger connected with the Ledger Wallet Solana running"; wallet_manager.update_devices().expect(NO_DEVICE_HELP); assert!(!wallet_manager.list_devices().is_empty(), NO_DEVICE_HELP); // Fetch the base pubkey of a connected ledger device let ledger_base_pubkey = wallet_manager .list_devices() .iter() .find(|d| d.manufacturer == "ledger") .map(|d| d.pubkey) .expect("No ledger device detected"); let ledger = wallet_manager .get_ledger(&ledger_base_pubkey) .expect("get device"); (ledger, ledger_base_pubkey) } fn test_ledger_pubkey() { let (ledger, ledger_base_pubkey) = get_ledger(); let mut pubkey_set = HashSet::new(); pubkey_set.insert(ledger_base_pubkey); let pubkey_0_0 = ledger .get_pubkey( &DerivationPath { account: Some(0.into()), change: Some(0.into()), }, false, ) .expect("get pubkey"); pubkey_set.insert(pubkey_0_0); let pubkey_0_1 = ledger .get_pubkey( &DerivationPath { account: Some(0.into()), change: Some(1.into()), }, false, ) .expect("get pubkey"); pubkey_set.insert(pubkey_0_1); let pubkey_1 = ledger .get_pubkey( &DerivationPath { account: Some(1.into()), change: None, }, false, ) .expect("get pubkey"); pubkey_set.insert(pubkey_1); let pubkey_1_0 = ledger .get_pubkey( &DerivationPath { account: Some(1.into()), change: Some(0.into()), }, false, ) .expect("get pubkey"); pubkey_set.insert(pubkey_1_0); assert_eq!(pubkey_set.len(), 5); // Ensure keys at various derivation paths are unique } // This test requires interactive approval of message signing on the ledger. fn test_ledger_sign_transaction() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let from = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let instruction = system_instruction::transfer(&from, &ledger_base_pubkey, 42); let message = Message::new(&[instruction], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&from.as_ref(), &message)); // Test large transaction let recipients: Vec<(Pubkey, u64)> = (0..10).map(|_| (Pubkey::new_rand(), 42)).collect(); let instructions = system_instruction::transfer_many(&from, &recipients); let message = Message::new(&instructions, Some(&ledger_base_pubkey)).serialize(); let hash = solana_sdk::hash::hash(&message); println!("Expected hash: {}", hash); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&from.as_ref(), &message)); } fn test_ledger_sign_transaction_too_big() { // Test too big of a transaction let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let from = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let recipients: Vec<(Pubkey, u64)> = (0..100).map(|_| (Pubkey::new_rand(), 42)).collect(); let instructions = system_instruction::transfer_many(&from, &recipients); let message = Message::new(&instructions, Some(&ledger_base_pubkey)).serialize(); ledger.sign_message(&derivation_path, &message).unwrap_err(); } /// This test requires interactive approval of message signing on the ledger. fn test_ledger_delegate_stake() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let authorized_pubkey = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let stake_pubkey = ledger_base_pubkey; let vote_pubkey = Pubkey::default(); let instruction = stake_instruction::delegate_stake(&stake_pubkey, &authorized_pubkey, &vote_pubkey); let message = Message::new(&[instruction], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&authorized_pubkey.as_ref(), &message)); } /// This test requires interactive approval of message signing on the ledger. fn test_ledger_delegate_stake_with_nonce() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let authorized_pubkey = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let stake_pubkey = ledger_base_pubkey; let vote_pubkey = Pubkey::new(&[1u8; 32]); let instruction = stake_instruction::delegate_stake(&stake_pubkey, &authorized_pubkey, &vote_pubkey); let nonce_account = Pubkey::new(&[2u8; 32]); let message = Message::new_with_nonce(vec![instruction], None, &nonce_account, &authorized_pubkey) .serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&authorized_pubkey.as_ref(), &message)); } /// This test requires interactive approval of message signing on the ledger. fn test_ledger_advance_nonce_account() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let authorized_pubkey = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let nonce_account = Pubkey::new(&[1u8; 32]); let instruction = system_instruction::advance_nonce_account(&nonce_account, &authorized_pubkey); let message = Message::new(&[instruction], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&authorized_pubkey.as_ref(), &message)); } /// This test requires interactive approval of message signing on the ledger. fn test_ledger_advance_nonce_account_separate_fee_payer() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let authorized_pubkey = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let nonce_account = Pubkey::new(&[1u8; 32]); let fee_payer = Pubkey::new(&[2u8; 32]); let instruction = system_instruction::advance_nonce_account(&nonce_account, &authorized_pubkey); let message = Message::new(&[instruction], Some(&fee_payer)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&authorized_pubkey.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_ledger_transfer_with_nonce() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let from = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let nonce_account = Pubkey::new(&[1u8; 32]); let nonce_authority = Pubkey::new(&[2u8; 32]); let instruction = system_instruction::transfer(&from, &ledger_base_pubkey, 42); let message = Message::new_with_nonce(vec![instruction], None, &nonce_account, &nonce_authority) .serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&from.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_create_stake_account_with_seed_and_nonce() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let from = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let nonce_account = Pubkey::new(&[1u8; 32]); let nonce_authority = Pubkey::new(&[2u8; 32]); let base = from; let seed = "seedseedseedseedseedseedseedseed"; let stake_account = Pubkey::create_with_seed(&base, seed, &solana_stake_program::id()).unwrap(); let authorized = stake_state::Authorized { staker: Pubkey::new(&[3u8; 32]), withdrawer: Pubkey::new(&[4u8; 32]), }; let instructions = stake_instruction::create_account_with_seed( &from, &stake_account, &base, seed, &authorized, &stake_state::Lockup::default(), 42, ); let message = Message::new_with_nonce(instructions, None, &nonce_account, &nonce_authority).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&from.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_create_stake_account() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let from = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let stake_account = ledger_base_pubkey; let authorized = stake_state::Authorized { staker: Pubkey::new(&[3u8; 32]), withdrawer: Pubkey::new(&[4u8; 32]), }; let instructions = stake_instruction::create_account( &from, &stake_account, &authorized, &stake_state::Lockup::default(), 42, ); let message = Message::new(&instructions, Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&from.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_create_nonce_account_with_seed() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let from = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let base = from; let seed = "seedseedseedseedseedseedseedseed"; let nonce_account = Pubkey::create_with_seed(&base, seed, &system_program::id()).unwrap(); let instructions = system_instruction::create_nonce_account_with_seed( &from, &nonce_account, &base, seed, &Pubkey::new(&[1u8; 32]), 42, ); let message = Message::new(&instructions, Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&from.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_create_nonce_account() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let from = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let nonce_account = ledger_base_pubkey; let instructions = system_instruction::create_nonce_account( &from, &nonce_account, &Pubkey::new(&[1u8; 32]), 42, ); let message = Message::new(&instructions, Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&from.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_sign_full_shred_of_garbage_tx() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let from = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let program_id = Pubkey::new(&[1u8; 32]); let mut data = [0u8; 1232 - 106].to_vec(); let mut rng = StdRng::seed_from_u64(0); rng.fill_bytes(&mut data); let instruction = Instruction { program_id, accounts: Vec::from([AccountMeta::new_readonly(from, true)]), data, }; let message = Message::new(&[instruction], Some(&ledger_base_pubkey)).serialize(); let hash = solana_sdk::hash::hash(&message); println!("Expected hash: {}", hash); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&from.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_create_vote_account() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let from = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let vote_account = ledger_base_pubkey; let vote_init = vote_state::VoteInit { node_pubkey: Pubkey::new(&[1u8; 32]), authorized_voter: Pubkey::new(&[2u8; 32]), authorized_withdrawer: Pubkey::new(&[3u8; 32]), commission: 50u8, }; let instructions = vote_instruction::create_account(&from, &vote_account, &vote_init, 42); let message = Message::new(&instructions, Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&from.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_create_vote_account_with_seed() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let from = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let base = from; let seed = "seedseedseedseedseedseedseedseed"; let vote_account = Pubkey::create_with_seed(&base, seed, &solana_vote_program::id()).unwrap(); let vote_init = vote_state::VoteInit { node_pubkey: Pubkey::new(&[1u8; 32]), authorized_voter: Pubkey::new(&[2u8; 32]), authorized_withdrawer: Pubkey::new(&[3u8; 32]), commission: 50u8, }; let instructions = vote_instruction::create_account_with_seed( &from, &vote_account, &base, seed, &vote_init, 42, ); let message = Message::new(&instructions, Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&from.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_nonce_withdraw() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let nonce_account = ledger_base_pubkey; let nonce_authority = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let to = Pubkey::new(&[1u8; 32]); let instruction = system_instruction::withdraw_nonce_account(&nonce_account, &nonce_authority, &to, 42); let message = Message::new(&[instruction], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&nonce_authority.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_stake_withdraw() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let stake_account = ledger_base_pubkey; let stake_authority = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let to = Pubkey::new(&[1u8; 32]); let instruction = stake_instruction::withdraw(&stake_account, &stake_authority, &to, 42, None); let message = Message::new(&[instruction], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&stake_authority.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_vote_withdraw() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let vote_account = ledger_base_pubkey; let vote_authority = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let to = Pubkey::new(&[1u8; 32]); let instruction = vote_instruction::withdraw(&vote_account, &vote_authority, 42, &to); let message = Message::new(&[instruction], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&vote_authority.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_nonce_authorize() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let nonce_account = ledger_base_pubkey; let nonce_authority = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let new_authority = Pubkey::new(&[1u8; 32]); let instruction = system_instruction::authorize_nonce_account( &nonce_account, &nonce_authority, &new_authority, ); let message = Message::new(&[instruction], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&nonce_authority.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_stake_authorize() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let stake_account = ledger_base_pubkey; let stake_authority = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let new_authority = Pubkey::new(&[1u8; 32]); let stake_auth = stake_instruction::authorize( &stake_account, &stake_authority, &new_authority, stake_state::StakeAuthorize::Staker, ); // Authorize staker let message = Message::new(&[stake_auth.clone()], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&stake_authority.as_ref(), &message)); let new_authority = Pubkey::new(&[2u8; 32]); let withdraw_auth = stake_instruction::authorize( &stake_account, &stake_authority, &new_authority, stake_state::StakeAuthorize::Withdrawer, ); // Authorize withdrawer let message = Message::new(&[withdraw_auth.clone()], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&stake_authority.as_ref(), &message)); // Authorize both // Note: Instruction order must match CLI; staker first, withdrawer second let message = Message::new(&[stake_auth, withdraw_auth], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&stake_authority.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_vote_authorize() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let vote_account = ledger_base_pubkey; let vote_authority = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let new_authority = Pubkey::new(&[1u8; 32]); let vote_auth = vote_instruction::authorize( &vote_account, &vote_authority, &new_authority, vote_state::VoteAuthorize::Voter, ); // Authorize voter let message = Message::new(&[vote_auth.clone()], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&vote_authority.as_ref(), &message)); let new_authority = Pubkey::new(&[2u8; 32]); let withdraw_auth = vote_instruction::authorize( &vote_account, &vote_authority, &new_authority, vote_state::VoteAuthorize::Withdrawer, ); // Authorize withdrawer let message = Message::new(&[withdraw_auth.clone()], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&vote_authority.as_ref(), &message)); // Authorize both // Note: Instruction order must match CLI; voter first, withdrawer second let message = Message::new(&[vote_auth, withdraw_auth], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&vote_authority.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_vote_update_validator_identity() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let vote_account = ledger_base_pubkey; let vote_authority = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let new_node = Pubkey::new(&[1u8; 32]); let instruction = vote_instruction::update_validator_identity(&vote_account, &vote_authority, &new_node); let message = Message::new(&[instruction], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&vote_authority.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_stake_deactivate() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let stake_account = ledger_base_pubkey; let stake_authority = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let instruction = stake_instruction::deactivate_stake(&stake_account, &stake_authority); let message = Message::new(&[instruction], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&stake_authority.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_stake_set_lockup() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let stake_account = ledger_base_pubkey; let stake_custodian = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let new_custodian = Pubkey::new(&[1u8; 32]); let lockup = stake_instruction::LockupArgs { unix_timestamp: Some(1), epoch: Some(2), custodian: Some(new_custodian), }; let instruction = stake_instruction::set_lockup(&stake_account, &lockup, &stake_custodian); let message = Message::new(&[instruction], Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&stake_custodian.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. // Add a nonce here to exercise worst case instruction usage fn test_stake_split_with_nonce() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let stake_authority = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let stake_account = ledger_base_pubkey; let split_account = Pubkey::new(&[1u8; 32]); let nonce_account = Pubkey::new(&[2u8; 32]); let nonce_authority = Pubkey::new(&[3u8; 32]); let instructions = stake_instruction::split(&stake_account, &stake_authority, 42, &split_account); let message = Message::new_with_nonce(instructions, None, &nonce_account, &nonce_authority).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&stake_authority.as_ref(), &message)); } // This test requires interactive approval of message signing on the ledger. fn test_stake_split_with_seed() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let stake_authority = ledger .get_pubkey(&derivation_path, false) .expect("get pubkey"); let stake_account = ledger_base_pubkey; let base = stake_authority; let seed = "seedseedseedseedseedseedseedseed"; let split_account = Pubkey::create_with_seed(&base, seed, &solana_stake_program::id()).unwrap(); let instructions = stake_instruction::split_with_seed( &stake_account, &stake_authority, 42, &split_account, &base, seed, ); let message = Message::new(&instructions, Some(&ledger_base_pubkey)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&stake_authority.as_ref(), &message)); } fn test_ledger_reject_unexpected_signer() { let (ledger, ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let from = Pubkey::new(&[1u8; 32]); let instruction = system_instruction::transfer(&from, &ledger_base_pubkey, 42); let message = Message::new(&[instruction], Some(&ledger_base_pubkey)).serialize(); assert!(ledger.sign_message(&derivation_path, &message).is_err()); } fn test_spl_token_create_mint() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let mint = Pubkey::new(&[1u8; 32]); let instructions = vec![ system_instruction::create_account( &owner, &mint, 501, std::mem::size_of::<spl_token::state::Mint>() as u64, &spl_token::id(), ), spl_token::instruction::initialize_mint(&spl_token::id(), &mint, &owner, None, 2).unwrap(), ]; let message = Message::new(&instructions, Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_create_account() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let account = Pubkey::new(&[1u8; 32]); let mint = Pubkey::new(&[2u8; 32]); let instructions = vec![ system_instruction::create_account( &owner, &account, 501, std::mem::size_of::<spl_token::state::Mint>() as u64, &spl_token::id(), ), spl_token::instruction::initialize_account(&spl_token::id(), &account, &mint, &owner) .unwrap(), ]; let message = Message::new(&instructions, Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_create_multisig() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let account = Pubkey::new(&[1u8; 32]); let signers = [ Pubkey::new(&[2u8; 32]), Pubkey::new(&[3u8; 32]), Pubkey::new(&[4u8; 32]), ]; let instructions = vec![ system_instruction::create_account( &owner, &account, 501, std::mem::size_of::<spl_token::state::Mint>() as u64, &spl_token::id(), ), spl_token::instruction::initialize_multisig( &spl_token::id(), &account, &signers.iter().collect::<Vec<_>>(), 2, ) .unwrap(), ]; let message = Message::new(&instructions, Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_create_mint_with_seed() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let base = owner; let seed = "seedseedseedseedseedseedseedseed"; let mint = Pubkey::create_with_seed(&base, seed, &spl_token::id()).unwrap(); let instructions = vec![ system_instruction::create_account_with_seed( &owner, &mint, &base, &seed, 501, std::mem::size_of::<spl_token::state::Mint>() as u64, &spl_token::id(), ), spl_token::instruction::initialize_mint(&spl_token::id(), &mint, &owner, None, 2).unwrap(), ]; let message = Message::new(&instructions, Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_create_account_with_seed() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let base = owner; let seed = "seedseedseedseedseedseedseedseed"; let mint = Pubkey::new(&[1u8; 32]); let account = Pubkey::create_with_seed(&base, seed, &spl_token::id()).unwrap(); let instructions = vec![ system_instruction::create_account_with_seed( &owner, &mint, &base, &seed, 501, std::mem::size_of::<spl_token::state::Mint>() as u64, &spl_token::id(), ), spl_token::instruction::initialize_account(&spl_token::id(), &account, &mint, &owner) .unwrap(), ]; let message = Message::new(&instructions, Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_create_multisig_with_seed() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let base = owner; let seed = "seedseedseedseedseedseedseedseed"; let mint = Pubkey::new(&[1u8; 32]); let account = Pubkey::create_with_seed(&base, seed, &spl_token::id()).unwrap(); let signers = [ Pubkey::new(&[2u8; 32]), Pubkey::new(&[3u8; 32]), Pubkey::new(&[4u8; 32]), ]; let instructions = vec![ system_instruction::create_account_with_seed( &owner, &mint, &base, &seed, 501, std::mem::size_of::<spl_token::state::Mint>() as u64, &spl_token::id(), ), spl_token::instruction::initialize_multisig( &spl_token::id(), &account, &signers.iter().collect::<Vec<_>>(), 2, ) .unwrap(), ]; let message = Message::new(&instructions, Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_transfer() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let sender = Pubkey::new(&[1u8; 32]); let recipient = Pubkey::new(&[2u8; 32]); let mint = spl_token::native_mint::id(); let instruction = spl_token::instruction::transfer2( &spl_token::id(), &sender, &mint, &recipient, &owner, &[], 42, 9, ) .unwrap(); let message = Message::new(&[instruction], Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_approve() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let account = Pubkey::new(&[1u8; 32]); let delegate = Pubkey::new(&[2u8; 32]); let mint = spl_token::native_mint::id(); let instruction = spl_token::instruction::approve2( &spl_token::id(), &account, &mint, &delegate, &owner, &[], 42, 9, ) .unwrap(); let message = Message::new(&[instruction], Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_revoke() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let account = Pubkey::new(&[1u8; 32]); let instruction = spl_token::instruction::revoke(&spl_token::id(), &account, &owner, &[]).unwrap(); let message = Message::new(&[instruction], Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_set_authority() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let account = Pubkey::new(&[1u8; 32]); let new_owner = Pubkey::new(&[2u8; 32]); let instruction = spl_token::instruction::set_authority( &spl_token::id(), &account, Some(&new_owner), spl_token::instruction::AuthorityType::AccountOwner, &owner, &[], ) .unwrap(); let message = Message::new(&[instruction], Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_mint_to() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let mint = spl_token::native_mint::id(); let account = Pubkey::new(&[2u8; 32]); let instruction = spl_token::instruction::mint_to2(&spl_token::id(), &mint, &account, &owner, &[], 42, 9) .unwrap(); let message = Message::new(&[instruction], Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_burn() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let account = Pubkey::new(&[1u8; 32]); let mint = spl_token::native_mint::id(); let instruction = spl_token::instruction::burn2(&spl_token::id(), &account, &mint, &owner, &[], 42, 9) .unwrap(); let message = Message::new(&[instruction], Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_close_account() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let owner = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let account = Pubkey::new(&[1u8; 32]); let destination = Pubkey::new(&[2u8; 32]); let instruction = spl_token::instruction::close_account( &spl_token::id(), &account, &destination, &owner, &[], ) .unwrap(); let message = Message::new(&[instruction], Some(&owner)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&owner.as_ref(), &message)); } fn test_spl_token_transfer_multisig() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let signer = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let owner = Pubkey::new(&[1u8; 32]); let sender = Pubkey::new(&[2u8; 32]); let recipient = Pubkey::new(&[3u8; 32]); let mint = Pubkey::new(&[4u8; 32]); // Bad mint show symbol "???" let signers = [Pubkey::new(&[5u8; 32]), signer]; let instruction = spl_token::instruction::transfer2( &spl_token::id(), &sender, &mint, &recipient, &owner, &signers.iter().collect::<Vec<_>>(), 42, 9, ) .unwrap(); let message = Message::new(&[instruction], Some(&signer)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&signer.as_ref(), &message)); } fn test_spl_token_approve_multisig() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let signer = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let owner = Pubkey::new(&[1u8; 32]); let account = Pubkey::new(&[2u8; 32]); let delegate = Pubkey::new(&[3u8; 32]); let mint = Pubkey::new(&[4u8; 32]); let signers = [Pubkey::new(&[5u8; 32]), signer]; let instruction = spl_token::instruction::approve2( &spl_token::id(), &account, &mint, &delegate, &owner, &signers.iter().collect::<Vec<_>>(), 42, 9, ) .unwrap(); let message = Message::new(&[instruction], Some(&signer)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&signer.as_ref(), &message)); } fn test_spl_token_revoke_multisig() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let signer = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let owner = Pubkey::new(&[1u8; 32]); let account = Pubkey::new(&[2u8; 32]); let signers = [Pubkey::new(&[3u8; 32]), signer]; let instruction = spl_token::instruction::revoke( &spl_token::id(), &account, &owner, &signers.iter().collect::<Vec<_>>(), ) .unwrap(); let message = Message::new(&[instruction], Some(&signer)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&signer.as_ref(), &message)); } fn test_spl_token_set_authority_multisig() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let signer = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let owner = Pubkey::new(&[1u8; 32]); let account = Pubkey::new(&[2u8; 32]); let new_owner = Pubkey::new(&[3u8; 32]); let signers = [Pubkey::new(&[4u8; 32]), signer]; let instruction = spl_token::instruction::set_authority( &spl_token::id(), &account, Some(&new_owner), spl_token::instruction::AuthorityType::AccountOwner, &owner, &signers.iter().collect::<Vec<_>>(), ) .unwrap(); let message = Message::new(&[instruction], Some(&signer)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&signer.as_ref(), &message)); } fn test_spl_token_mint_to_multisig() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let signer = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let owner = Pubkey::new(&[1u8; 32]); let mint = Pubkey::new(&[2u8; 32]); let account = Pubkey::new(&[3u8; 32]); let signers = [Pubkey::new(&[4u8; 32]), signer]; let instruction = spl_token::instruction::mint_to2( &spl_token::id(), &mint, &account, &owner, &signers.iter().collect::<Vec<_>>(), 42, 9, ) .unwrap(); let message = Message::new(&[instruction], Some(&signer)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&signer.as_ref(), &message)); } fn test_spl_token_burn_multisig() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let signer = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let owner = Pubkey::new(&[1u8; 32]); let account = Pubkey::new(&[2u8; 32]); let signers = [Pubkey::new(&[3u8; 32]), signer]; let mint = Pubkey::new(&[4u8; 32]); let instruction = spl_token::instruction::burn2( &spl_token::id(), &account, &mint, &owner, &signers.iter().collect::<Vec<_>>(), 42, 9, ) .unwrap(); let message = Message::new(&[instruction], Some(&signer)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&signer.as_ref(), &message)); } fn test_spl_token_close_account_multisig() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let signer = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let owner = Pubkey::new(&[1u8; 32]); let account = Pubkey::new(&[2u8; 32]); let destination = Pubkey::new(&[3u8; 32]); let signers = [Pubkey::new(&[4u8; 32]), signer]; let instruction = spl_token::instruction::close_account( &spl_token::id(), &account, &destination, &owner, &signers.iter().collect::<Vec<_>>(), ) .unwrap(); let message = Message::new(&[instruction], Some(&signer)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&signer.as_ref(), &message)); } fn test_spl_token_freeze_account() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let signer = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let freeze_auth = signer; let account = Pubkey::new(&[1u8; 32]); let mint = Pubkey::new(&[2u8; 32]); let instruction = spl_token::instruction::freeze_account( &spl_token::id(), &account, &mint, &freeze_auth, &[], ) .unwrap(); let message = Message::new(&[instruction], Some(&signer)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&signer.as_ref(), &message)); } fn test_spl_token_freeze_account_multisig() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let signer = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let freeze_auth = signer; let account = Pubkey::new(&[1u8; 32]); let mint = Pubkey::new(&[2u8; 32]); let signers = [Pubkey::new(&[3u8; 32]), signer]; let instruction = spl_token::instruction::freeze_account( &spl_token::id(), &account, &mint, &freeze_auth, &signers.iter().collect::<Vec<_>>(), ) .unwrap(); let message = Message::new(&[instruction], Some(&signer)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&signer.as_ref(), &message)); } fn test_spl_token_thaw_account() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let signer = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let thaw_auth = signer; let account = Pubkey::new(&[1u8; 32]); let mint = Pubkey::new(&[2u8; 32]); let instruction = spl_token::instruction::thaw_account(&spl_token::id(), &account, &mint, &thaw_auth, &[]) .unwrap(); let message = Message::new(&[instruction], Some(&signer)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&signer.as_ref(), &message)); } fn test_spl_token_thaw_account_multisig() { let (ledger, _ledger_base_pubkey) = get_ledger(); let derivation_path = DerivationPath { account: Some(12345.into()), change: None, }; let signer = ledger .get_pubkey(&derivation_path, false) .expect("ledger get pubkey"); let thaw_auth = signer; let account = Pubkey::new(&[1u8; 32]); let mint = Pubkey::new(&[2u8; 32]); let signers = [Pubkey::new(&[3u8; 32]), signer]; let instruction = spl_token::instruction::thaw_account( &spl_token::id(), &account, &mint, &thaw_auth, &signers.iter().collect::<Vec<_>>(), ) .unwrap(); let message = Message::new(&[instruction], Some(&signer)).serialize(); let signature = ledger .sign_message(&derivation_path, &message) .expect("sign transaction"); assert!(signature.verify(&signer.as_ref(), &message)); } macro_rules! run { ($test:ident) => { println!(" >>> Running {} <<<", stringify!($test)); $test(); }; } fn main() { solana_logger::setup(); run!(test_spl_token_freeze_account); run!(test_spl_token_freeze_account_multisig); run!(test_spl_token_thaw_account); run!(test_spl_token_thaw_account_multisig); run!(test_spl_token_burn); run!(test_spl_token_burn_multisig); run!(test_spl_token_mint_to); run!(test_spl_token_mint_to_multisig); run!(test_spl_token_approve); run!(test_spl_token_approve_multisig); run!(test_spl_token_transfer); run!(test_spl_token_transfer_multisig); run!(test_spl_token_set_authority); run!(test_spl_token_set_authority_multisig); run!(test_spl_token_create_mint); run!(test_spl_token_create_mint_with_seed); run!(test_spl_token_revoke_multisig); run!(test_spl_token_close_account_multisig); run!(test_spl_token_create_account_with_seed); run!(test_spl_token_create_multisig_with_seed); run!(test_spl_token_create_account); run!(test_spl_token_create_multisig); run!(test_spl_token_revoke); run!(test_spl_token_close_account); run!(test_ledger_reject_unexpected_signer); run!(test_stake_split_with_nonce); run!(test_stake_split_with_seed); run!(test_stake_set_lockup); run!(test_stake_deactivate); run!(test_vote_update_validator_identity); run!(test_vote_authorize); run!(test_stake_authorize); run!(test_nonce_authorize); run!(test_vote_withdraw); run!(test_stake_withdraw); run!(test_nonce_withdraw); run!(test_create_vote_account); run!(test_create_vote_account_with_seed); run!(test_create_nonce_account); run!(test_create_nonce_account_with_seed); run!(test_create_stake_account); run!(test_ledger_pubkey); run!(test_ledger_sign_transaction); run!(test_ledger_sign_transaction_too_big); run!(test_ledger_delegate_stake); run!(test_ledger_advance_nonce_account); run!(test_ledger_advance_nonce_account_separate_fee_payer); run!(test_ledger_delegate_stake_with_nonce); run!(test_ledger_transfer_with_nonce); run!(test_create_stake_account_with_seed_and_nonce); run!(test_sign_full_shred_of_garbage_tx); }
pub fn invert_result<T, E>(res: Result<Option<T>, E>) -> Option<Result<T, E>> { match res { Ok(Some(batch)) => Some(Ok(batch)), Err(err) => Some(Err(err)), Ok(None) => None, } }
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkPipelineTessellationStateCreateInfo { pub sType: VkStructureType, pub pNext: *const c_void, pub flags: VkPipelineTessellationStateCreateFlagBits, pub patchControlPoints: u32, } impl VkPipelineTessellationStateCreateInfo { pub fn new<T>(flags: T, patch_control_points: u32) -> VkPipelineTessellationStateCreateInfo where T: Into<VkPipelineTessellationStateCreateFlagBits>, { VkPipelineTessellationStateCreateInfo { sType: VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO, pNext: ptr::null(), flags: flags.into(), patchControlPoints: patch_control_points, } } }
// memory access - uses values in mem_map to check what address being passed actually is before // returning value use crate::mem_map::*; const RAM_SIZE: usize = 2 * 1024; const VRAM_SIZE: usize = 2 * 1024; const ROM_BLOCK_SIZE: usize = 16 * 1024; const CHR_BLOCK_SIZE: usize = 8 * 1024; pub struct RAM { ram: [u8; RAM_SIZE], rom: Box<[u8]>, ppu_ram: [u8; VRAM_SIZE], chr_ram: Box<[u8]>, ppu_regs: [u8; 8], ppu_reg_write: [u8; 8], ppu_reg_read: [u8; 8], OAM: [u8; 256], universal_bg_color: u8, pallette_colors: [u8; 32], num_prg_blocks : usize, num_chr_blocks : usize, mapper : u8, mirror: u8, } impl RAM { pub fn new(num_prg_blocks : usize, num_chr_blocks : usize, mapper : u8, mirror : u8) -> RAM { RAM { ram: [0; RAM_SIZE], rom: vec![0; ROM_BLOCK_SIZE * num_prg_blocks].into_boxed_slice(), ppu_ram: [0; VRAM_SIZE], chr_ram: vec![0; CHR_BLOCK_SIZE * num_chr_blocks].into_boxed_slice(), ppu_regs: [0; 8], ppu_reg_write: [0; 8], ppu_reg_read: [0; 8], OAM: [0; 256], universal_bg_color: 0, pallette_colors: [0; 32], num_prg_blocks : num_prg_blocks, num_chr_blocks : num_chr_blocks, mapper : mapper, mirror : mirror, } } pub fn clear_read_write_regs(&mut self) { self.ppu_reg_write = [0, 0, 0, 0, 0, 0, 0, 0]; self.ppu_reg_read = [0, 0, 0, 0, 0, 0, 0, 0]; } fn chr_debug(&self, byte1 : u8, byte2 : u8){ for i in 0..8 { print!("{}", ((byte1 >> (7 - i)) & 1) + ((byte2 >> (7 - i)) & 1)); } println!(""); } fn block(&self){ let mut idx = 0x1000; for i in 0..8 { self.chr_debug(self.chr_ram[idx], self.chr_ram[idx + 8]); self.chr_debug(self.chr_ram[idx + 1], self.chr_ram[idx + 9]); self.chr_debug(self.chr_ram[idx + 2], self.chr_ram[idx + 10]); self.chr_debug(self.chr_ram[idx + 3], self.chr_ram[idx + 11]); self.chr_debug(self.chr_ram[idx + 4], self.chr_ram[idx + 12]); self.chr_debug(self.chr_ram[idx + 5], self.chr_ram[idx + 13]); self.chr_debug(self.chr_ram[idx + 6], self.chr_ram[idx + 14]); self.chr_debug(self.chr_ram[idx + 7], self.chr_ram[idx + 15]); idx += 16; println!(""); } } pub fn load_rom(&mut self, rom_data: Box<[u8]>) { let prg_len = self.num_prg_blocks * ROM_BLOCK_SIZE; for i in 0..prg_len { self.rom[i] = rom_data[i + 16]; } let chr_len = self.num_chr_blocks * CHR_BLOCK_SIZE; for i in 0..chr_len { self.chr_ram[i] = rom_data[prg_len + i + 16]; } // self.block(); // panic!(); } pub fn read_mem_value(&mut self, addr: u16) -> u8 { self.check_address_read(addr as usize) } pub fn read_mem_address(&mut self, addr: u16) -> u16 { let byte_one = self.check_address_read(addr as usize); let byte_two = self.check_address_read((addr + 1) as usize); ((byte_two as u16) << 8) | (byte_one as u16) } pub fn write_mem_value(&mut self, addr: u16, value: u8) { self.check_address_write(addr as usize, value); } pub fn write_mem_address(&mut self, addr: u16, new_addr: u16) { let byte_one = (new_addr) as u8; let byte_two = (new_addr >> 8) as u8; self.check_address_write(addr as usize, byte_one); self.check_address_write((addr + 1) as usize, byte_two); } pub fn push_address_on_stack(&mut self, stack_ptr: &mut u8, push_address: u16) { if *stack_ptr == 254 { panic!("stack overflow") } let addr = STACK_START + *stack_ptr as usize; self.ram[addr - 1] = push_address as u8; self.ram[addr] = (push_address >> 8) as u8; //println!("push addr on stack {:#x}, {:#x}, {:#x}", push_address, self.ram[addr], self.ram[addr - 1] ); *stack_ptr -= 2; } pub fn push_value_on_stack(&mut self, stack_ptr: &mut u8, push_value: u8) { if *stack_ptr == 255 { panic!("stack overflow") } let addr = STACK_START + *stack_ptr as usize; self.ram[addr] = push_value; *stack_ptr -= 1; } pub fn pop_address_off_stack(&mut self, stack_ptr: &mut u8) -> u16 { if *stack_ptr == 0 { panic!("stack underflow") } *stack_ptr += 2; let addr = STACK_START + *stack_ptr as usize; let pop_addr = (self.ram[addr] as u16) << 8 | self.ram[addr - 1] as u16; pop_addr } pub fn pop_value_off_stack(&mut self, stack_ptr: &mut u8) -> u8 { *stack_ptr += 1; let value = self.ram[STACK_START + *stack_ptr as usize]; value } // maps addresses to other addresses fn check_address_write(&mut self, address: usize, value: u8) { match address { INTERNAL_RAM_START..=INTERNAL_RAM_MIRROR_THREE_END => { let lookup = address & 0x7FF; self.ram[lookup] = value; } MIRROR_ONE_ROM_START..=MIRROR_ONE_ROM_END => { let base = address - 0x8000; self.rom[base] = value; } MIRROR_TWO_ROM_START..=MIRROR_TWO_ROM_END => { let base = match self.mapper { 0x0 => { address - 0xC000 }, _ => { address }, }; self.rom[base] = value; } PPU_REGISTERS_START..=PPU_REGISTERS_MIRRORS_END => { let base = address - 0x2000; let indx = base % 8; self.ppu_reg_write[indx] = 1; self.ppu_regs[indx] = value; } OAM_DMA => { // writing a byte to this causes a 256 byte page to be copied to the OAM mem // TODO cycles on cpu? let page_addr = ((value as u16) << 8) as usize; for i in 0..256 { self.OAM[i] = self.ram[page_addr + i]; } } _ => { panic!("{:#x}", address); } } } fn check_address_read(&mut self, address: usize) -> u8 { match address { INTERNAL_RAM_START..=INTERNAL_RAM_MIRROR_THREE_END => { let lookup = address & 0x7FF; self.ram[lookup] } MIRROR_ONE_ROM_START..=MIRROR_ONE_ROM_END => { let base = address - 0x8000; self.rom[base] } MIRROR_TWO_ROM_START..=MIRROR_TWO_ROM_END => { let base = match self.mapper { 0x0 => { address - 0xC000 }, _ => { address }, }; self.rom[base] } PPU_REGISTERS_START..=PPU_REGISTERS_MIRRORS_END => { let base = address - 0x2000; let indx = base % 8; self.ppu_reg_read[indx] = 1; self.ppu_regs[indx] } _ => { panic!("{:#x}", address); } } } pub fn write_ppu_data_no_incr(&mut self, value: u8) { self.ppu_regs[PPUDATA - 0x2000] = value } pub fn read_ppu_data_no_incr(&mut self) -> u8 { self.ppu_regs[PPUDATA - 0x2000] } pub fn write_vram_value(&mut self, address: usize, value: u8) { self.check_vram_write(address, value) } pub fn read_vram_value(&mut self, address: usize) -> u8 { let val = self.check_vram_address_read(address); val } // maps vram addresses to other addresses fn check_vram_address_read(&self, address: usize) -> u8 { //println!("read addr {:#x}", address); match address { PATTERN_TABLE_ZERO_START..=PATTERN_TABLE_ZERO_END => self.chr_ram[address], PATTERN_TABLE_ONE_START..=PATTERN_TABLE_ONE_END => self.chr_ram[address], NAME_TABLE_ZERO_START..=NAME_TABLE_ZERO_END => self.ppu_ram[address - NAME_TABLE_ZERO_START], NAME_TABLE_ONE_START..=NAME_TABLE_ONE_END => { if self.mirror == 0 { self.ppu_ram[address - NAME_TABLE_ONE_START] } else { self.ppu_ram[address - NAME_TABLE_ZERO_START] } }, NAME_TABLE_TWO_START..=NAME_TABLE_TWO_END => { if self.mirror == 0 { self.ppu_ram[address - NAME_TABLE_ONE_START] } else { self.ppu_ram[address - NAME_TABLE_TWO_START] } }, NAME_TABLE_THREE_START..=NAME_TABLE_THREE_END => { self.ppu_ram[address - NAME_TABLE_TWO_START] }, NAME_TABLE_ZERO_MIRROR_START..=NAME_TABLE_ZERO_MIRROR_END => self.ppu_ram[address - NAME_TABLE_ZERO_MIRROR_START], NAME_TABLE_ONE_MIRROR_START..=NAME_TABLE_ONE_MIRROR_END => { if self.mirror == 0 { self.ppu_ram[address - NAME_TABLE_ONE_MIRROR_START] } else { self.ppu_ram[address - NAME_TABLE_ZERO_MIRROR_START] } }, NAME_TABLE_TWO_MIRROR_START..=NAME_TABLE_TWO_MIRROR_END => { if self.mirror == 0 { self.ppu_ram[address - NAME_TABLE_ONE_MIRROR_START] } else { self.ppu_ram[address - NAME_TABLE_TWO_MIRROR_START] } }, NAME_TABLE_THREE_MIRROR_START..=NAME_TABLE_THREE_MIRROR_END => { self.ppu_ram[address - NAME_TABLE_TWO_MIRROR_START] } PALLETE_RAM_INDICES_START..=PALLETE_RAM_INDICES_END => { let base = address - PALLETE_RAM_INDICES_START; self.pallette_colors[base] }, PALLETE_RAM_MIRRORS_START..=PALLETE_RAM_MIRRORS_END => { let base = (address - PALLETE_RAM_MIRRORS_START) % 0x20; self.pallette_colors[base] }, _ => { panic!("{:#x}", address); } } } fn check_vram_write(&mut self, address: usize, value: u8) { println!("write addr {:#x} val {:#x}", address, value); match address { NAME_TABLE_ZERO_START..=NAME_TABLE_ZERO_END => self.ppu_ram[address - NAME_TABLE_ZERO_START] = value, NAME_TABLE_ONE_START..=NAME_TABLE_ONE_END => self.ppu_ram[address - NAME_TABLE_ZERO_START] = value, NAME_TABLE_TWO_START..=NAME_TABLE_TWO_END => self.ppu_ram[address - NAME_TABLE_ZERO_START] = value, NAME_TABLE_THREE_START..=NAME_TABLE_THREE_END => self.ppu_ram[address - NAME_TABLE_ZERO_START] = value, PALLETE_RAM_INDICES_START..=PALLETE_RAM_INDICES_END => { let base = address - PALLETE_RAM_INDICES_START; self.pallette_colors[base] = value; }, PALLETE_RAM_MIRRORS_START..=PALLETE_RAM_MIRRORS_END => { let base = (address - PALLETE_RAM_MIRRORS_START) % 0x20; self.pallette_colors[base] = value; }, _ => { panic!("{:#x}", address); } } } pub fn was_read(&self, idx: usize) -> bool { self.ppu_reg_read[idx] == 1 } pub fn was_written(&self, idx: usize) -> bool { self.ppu_reg_write[idx] == 1 } } pub fn swap_bytes(in_val: u16) -> u16 { let out_val = (in_val << 8) | (in_val >> 8); out_val } #[cfg(test)] mod tests { #[test] fn mem_tests() { use super::*; // let mut test_memory : RAM = RAM::new(); // let mut stack_ptr = 0; // // init mem // for i in 0..2048 { // test_memory.write_mem_value(i, i as u8); // } // let byteVal = 0x1FF1; // let newBytes = swap_bytes(byteVal); // assert_eq!(newBytes, 0xF11F); // let value = test_memory.read_mem_value(18); // assert_eq!(value, 18); // test_memory.write_mem_value(0x10, 128); // let value = test_memory.read_mem_value(0x10); // assert_eq!(value, 128); // let address = test_memory.read_mem_address(0x4); // assert_eq!(address, 0x504); // test_memory.write_mem_address(0x20, 0x3FFF); // let new_address = test_memory.read_mem_address(0x20); // assert_eq!(new_address, 0x3FFF); // test_memory.push_address_on_stack(&mut stack_ptr, 0x286); // assert_eq!(stack_ptr, 2); // let stack_addr = test_memory.pop_address_off_stack(&mut stack_ptr); // println!("{:#x}", stack_addr); // assert_eq!(stack_ptr, 0); // assert_eq!(stack_addr, 0x286); // test_memory.push_value_on_stack(&mut stack_ptr, 0x86); // assert_eq!(stack_ptr, 1); // let stack_val = test_memory.pop_value_off_stack(&mut stack_ptr); // assert_eq!(stack_val, 0x86); } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Services_Maps_Guidance")] pub mod Guidance; #[cfg(feature = "Services_Maps_LocalSearch")] pub mod LocalSearch; #[cfg(feature = "Services_Maps_OfflineMaps")] pub mod OfflineMaps; #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct EnhancedWaypoint(pub ::windows::core::IInspectable); impl EnhancedWaypoint { #[cfg(feature = "Devices_Geolocation")] pub fn Point(&self) -> ::windows::core::Result<super::super::Devices::Geolocation::Geopoint> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Devices::Geolocation::Geopoint>(result__) } } pub fn Kind(&self) -> ::windows::core::Result<WaypointKind> { let this = self; unsafe { let mut result__: WaypointKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<WaypointKind>(result__) } } #[cfg(feature = "Devices_Geolocation")] pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>>(point: Param0, kind: WaypointKind) -> ::windows::core::Result<EnhancedWaypoint> { Self::IEnhancedWaypointFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), point.into_param().abi(), kind, &mut result__).from_abi::<EnhancedWaypoint>(result__) }) } pub fn IEnhancedWaypointFactory<R, F: FnOnce(&IEnhancedWaypointFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<EnhancedWaypoint, IEnhancedWaypointFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for EnhancedWaypoint { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.EnhancedWaypoint;{ed268c74-5913-11e6-8b77-86f30ca893d3})"); } unsafe impl ::windows::core::Interface for EnhancedWaypoint { type Vtable = IEnhancedWaypoint_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xed268c74_5913_11e6_8b77_86f30ca893d3); } impl ::windows::core::RuntimeName for EnhancedWaypoint { const NAME: &'static str = "Windows.Services.Maps.EnhancedWaypoint"; } impl ::core::convert::From<EnhancedWaypoint> for ::windows::core::IUnknown { fn from(value: EnhancedWaypoint) -> Self { value.0 .0 } } impl ::core::convert::From<&EnhancedWaypoint> for ::windows::core::IUnknown { fn from(value: &EnhancedWaypoint) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for EnhancedWaypoint { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a EnhancedWaypoint { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<EnhancedWaypoint> for ::windows::core::IInspectable { fn from(value: EnhancedWaypoint) -> Self { value.0 } } impl ::core::convert::From<&EnhancedWaypoint> for ::windows::core::IInspectable { fn from(value: &EnhancedWaypoint) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for EnhancedWaypoint { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a EnhancedWaypoint { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for EnhancedWaypoint {} unsafe impl ::core::marker::Sync for EnhancedWaypoint {} #[repr(transparent)] #[doc(hidden)] pub struct IEnhancedWaypoint(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IEnhancedWaypoint { type Vtable = IEnhancedWaypoint_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xed268c74_5913_11e6_8b77_86f30ca893d3); } #[repr(C)] #[doc(hidden)] pub struct IEnhancedWaypoint_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut WaypointKind) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IEnhancedWaypointFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IEnhancedWaypointFactory { type Vtable = IEnhancedWaypointFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaf868477_a2aa_46dd_b645_23b31b8aa6c7); } #[repr(C)] #[doc(hidden)] pub struct IEnhancedWaypointFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, point: ::windows::core::RawPtr, kind: WaypointKind, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IManeuverWarning(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IManeuverWarning { type Vtable = IManeuverWarning_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc1a36d8a_2630_4378_9e4a_6e44253dceba); } #[repr(C)] #[doc(hidden)] pub struct IManeuverWarning_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ManeuverWarningKind) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ManeuverWarningSeverity) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapAddress(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapAddress { type Vtable = IMapAddress_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcfa7a973_a3b4_4494_b3ff_cba94db69699); } #[repr(C)] #[doc(hidden)] pub struct IMapAddress_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapAddress2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapAddress2 { type Vtable = IMapAddress2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x75cd6df1_e5ad_45a9_bf40_6cf256c1dd13); } #[repr(C)] #[doc(hidden)] pub struct IMapAddress2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapLocation(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapLocation { type Vtable = IMapLocation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c073f57_0da4_42e8_9ee2_a96fcf2371dc); } #[repr(C)] #[doc(hidden)] pub struct IMapLocation_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapLocationFinderResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapLocationFinderResult { type Vtable = IMapLocationFinderResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x43f1f179_e8cc_45f6_bed2_54ccbf965d9a); } #[repr(C)] #[doc(hidden)] pub struct IMapLocationFinderResult_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MapLocationFinderStatus) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapLocationFinderStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapLocationFinderStatics { type Vtable = IMapLocationFinderStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x318adb5d_1c5d_4f35_a2df_aaca94959517); } #[repr(C)] #[doc(hidden)] pub struct IMapLocationFinderStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, querypoint: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation")))] usize, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, searchtext: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, referencepoint: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation")))] usize, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, searchtext: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, referencepoint: ::windows::core::RawPtr, maxcount: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapLocationFinderStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapLocationFinderStatics2 { type Vtable = IMapLocationFinderStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x959a8b96_6485_4dfd_851a_33ac317e3af6); } #[repr(C)] #[doc(hidden)] pub struct IMapLocationFinderStatics2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, querypoint: ::windows::core::RawPtr, accuracy: MapLocationDesiredAccuracy, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapManagerStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapManagerStatics { type Vtable = IMapManagerStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x37e3e515_82b4_4d54_8fd9_af2624b3011c); } #[repr(C)] #[doc(hidden)] pub struct IMapManagerStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRoute(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRoute { type Vtable = IMapRoute_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb07b732_584d_4583_9c60_641fea274349); } #[repr(C)] #[doc(hidden)] pub struct IMapRoute_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRoute2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRoute2 { type Vtable = IMapRoute2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd1c5d40c_2213_4ab0_a260_46b38169beac); } #[repr(C)] #[doc(hidden)] pub struct IMapRoute2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MapRouteRestrictions) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRoute3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRoute3 { type Vtable = IMapRoute3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x858d1eae_f2ad_429f_bb37_cd21094ffc92); } #[repr(C)] #[doc(hidden)] pub struct IMapRoute3_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut TrafficCongestion) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRoute4(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRoute4 { type Vtable = IMapRoute4_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x366c8ca5_3053_4fa1_80ff_d475f3ed1e6e); } #[repr(C)] #[doc(hidden)] pub struct IMapRoute4_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRouteDrivingOptions(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRouteDrivingOptions { type Vtable = IMapRouteDrivingOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6815364d_c6dc_4697_a452_b18f8f0b67a1); } #[repr(C)] #[doc(hidden)] pub struct IMapRouteDrivingOptions_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MapRouteOptimization) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: MapRouteOptimization) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MapRouteRestrictions) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: MapRouteRestrictions) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRouteDrivingOptions2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRouteDrivingOptions2 { type Vtable = IMapRouteDrivingOptions2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x35dc8670_c298_48d0_b5ad_825460645603); } #[repr(C)] #[doc(hidden)] pub struct IMapRouteDrivingOptions2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRouteFinderResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRouteFinderResult { type Vtable = IMapRouteFinderResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa868a31a_9422_46ac_8ca1_b1614d4bfbe2); } #[repr(C)] #[doc(hidden)] pub struct IMapRouteFinderResult_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MapRouteFinderStatus) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRouteFinderResult2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRouteFinderResult2 { type Vtable = IMapRouteFinderResult2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x20709c6d_d90c_46c8_91c6_7d4be4efb215); } #[repr(C)] #[doc(hidden)] pub struct IMapRouteFinderResult2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRouteFinderStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRouteFinderStatics { type Vtable = IMapRouteFinderStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb8a5c50f_1c64_4c3a_81eb_1f7c152afbbb); } #[repr(C)] #[doc(hidden)] pub struct IMapRouteFinderStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, startpoint: ::windows::core::RawPtr, endpoint: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation")))] usize, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, startpoint: ::windows::core::RawPtr, endpoint: ::windows::core::RawPtr, optimization: MapRouteOptimization, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation")))] usize, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, startpoint: ::windows::core::RawPtr, endpoint: ::windows::core::RawPtr, optimization: MapRouteOptimization, restrictions: MapRouteRestrictions, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation")))] usize, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, startpoint: ::windows::core::RawPtr, endpoint: ::windows::core::RawPtr, optimization: MapRouteOptimization, restrictions: MapRouteRestrictions, headingindegrees: f64, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation")))] usize, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, waypoints: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, waypoints: ::windows::core::RawPtr, optimization: MapRouteOptimization, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, waypoints: ::windows::core::RawPtr, optimization: MapRouteOptimization, restrictions: MapRouteRestrictions, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, waypoints: ::windows::core::RawPtr, optimization: MapRouteOptimization, restrictions: MapRouteRestrictions, headingindegrees: f64, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, startpoint: ::windows::core::RawPtr, endpoint: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation")))] usize, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, waypoints: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRouteFinderStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRouteFinderStatics2 { type Vtable = IMapRouteFinderStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xafcc2c73_7760_49af_b3bd_baf135b703e1); } #[repr(C)] #[doc(hidden)] pub struct IMapRouteFinderStatics2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, startpoint: ::windows::core::RawPtr, endpoint: ::windows::core::RawPtr, options: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Geolocation", feature = "Foundation")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRouteFinderStatics3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRouteFinderStatics3 { type Vtable = IMapRouteFinderStatics3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf6098134_5913_11e6_8b77_86f30ca893d3); } #[repr(C)] #[doc(hidden)] pub struct IMapRouteFinderStatics3_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, waypoints: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, waypoints: ::windows::core::RawPtr, options: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRouteLeg(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRouteLeg { type Vtable = IMapRouteLeg_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96f8b2f6_5bba_4d17_9db6_1a263fec7471); } #[repr(C)] #[doc(hidden)] pub struct IMapRouteLeg_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRouteLeg2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRouteLeg2 { type Vtable = IMapRouteLeg2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x02e2062d_c9c6_45b8_8e54_1a10b57a17e8); } #[repr(C)] #[doc(hidden)] pub struct IMapRouteLeg2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut TrafficCongestion) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRouteManeuver(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRouteManeuver { type Vtable = IMapRouteManeuver_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xed5c17f0_a6ab_4d65_a086_fa8a7e340df2); } #[repr(C)] #[doc(hidden)] pub struct IMapRouteManeuver_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MapRouteManeuverKind) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MapManeuverNotices) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRouteManeuver2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRouteManeuver2 { type Vtable = IMapRouteManeuver2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5d7bcd9c_7c9b_41df_838b_eae21e4b05a9); } #[repr(C)] #[doc(hidden)] pub struct IMapRouteManeuver2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapRouteManeuver3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapRouteManeuver3 { type Vtable = IMapRouteManeuver3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa6a138df_0483_4166_85be_b99336c11875); } #[repr(C)] #[doc(hidden)] pub struct IMapRouteManeuver3_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapServiceStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapServiceStatics { type Vtable = IMapServiceStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0144ad85_c04c_4cdd_871a_a0726d097cd4); } #[repr(C)] #[doc(hidden)] pub struct IMapServiceStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapServiceStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapServiceStatics2 { type Vtable = IMapServiceStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf8193eed_9c85_40a9_8896_0fc3fd2b7c2a); } #[repr(C)] #[doc(hidden)] pub struct IMapServiceStatics2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapServiceStatics3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapServiceStatics3 { type Vtable = IMapServiceStatics3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0a11ce20_63a7_4854_b355_d6dcda223d1b); } #[repr(C)] #[doc(hidden)] pub struct IMapServiceStatics3_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMapServiceStatics4(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMapServiceStatics4 { type Vtable = IMapServiceStatics4_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x088a2862_6abc_420e_945f_4cfd89c67356); } #[repr(C)] #[doc(hidden)] pub struct IMapServiceStatics4_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: MapServiceDataUsagePreference) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MapServiceDataUsagePreference) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlaceInfo(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlaceInfo { type Vtable = IPlaceInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9a0810b6_31c8_4f6a_9f18_950b4c38951a); } #[repr(C)] #[doc(hidden)] pub struct IPlaceInfo_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, selection: super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlaceInfoCreateOptions(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlaceInfoCreateOptions { type Vtable = IPlaceInfoCreateOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcd33c125_67f1_4bb3_9907_ecce939b0399); } #[repr(C)] #[doc(hidden)] pub struct IPlaceInfoCreateOptions_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlaceInfoStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlaceInfoStatics { type Vtable = IPlaceInfoStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x82b9ff71_6cd0_48a4_afd9_5ed82097936b); } #[repr(C)] #[doc(hidden)] pub struct IPlaceInfoStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, referencepoint: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, referencepoint: ::windows::core::RawPtr, options: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, identifier: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Geolocation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, identifier: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, defaultpoint: ::windows::core::RawPtr, options: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Geolocation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, location: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlaceInfoStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlaceInfoStatics2 { type Vtable = IPlaceInfoStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x730f0249_4047_44a3_8f81_2550a5216370); } #[repr(C)] #[doc(hidden)] pub struct IPlaceInfoStatics2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, displayaddress: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, displayaddress: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, displayname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ManeuverWarning(pub ::windows::core::IInspectable); impl ManeuverWarning { pub fn Kind(&self) -> ::windows::core::Result<ManeuverWarningKind> { let this = self; unsafe { let mut result__: ManeuverWarningKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ManeuverWarningKind>(result__) } } pub fn Severity(&self) -> ::windows::core::Result<ManeuverWarningSeverity> { let this = self; unsafe { let mut result__: ManeuverWarningSeverity = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ManeuverWarningSeverity>(result__) } } } unsafe impl ::windows::core::RuntimeType for ManeuverWarning { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.ManeuverWarning;{c1a36d8a-2630-4378-9e4a-6e44253dceba})"); } unsafe impl ::windows::core::Interface for ManeuverWarning { type Vtable = IManeuverWarning_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc1a36d8a_2630_4378_9e4a_6e44253dceba); } impl ::windows::core::RuntimeName for ManeuverWarning { const NAME: &'static str = "Windows.Services.Maps.ManeuverWarning"; } impl ::core::convert::From<ManeuverWarning> for ::windows::core::IUnknown { fn from(value: ManeuverWarning) -> Self { value.0 .0 } } impl ::core::convert::From<&ManeuverWarning> for ::windows::core::IUnknown { fn from(value: &ManeuverWarning) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ManeuverWarning { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ManeuverWarning { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ManeuverWarning> for ::windows::core::IInspectable { fn from(value: ManeuverWarning) -> Self { value.0 } } impl ::core::convert::From<&ManeuverWarning> for ::windows::core::IInspectable { fn from(value: &ManeuverWarning) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ManeuverWarning { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ManeuverWarning { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ManeuverWarning {} unsafe impl ::core::marker::Sync for ManeuverWarning {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ManeuverWarningKind(pub i32); impl ManeuverWarningKind { pub const None: ManeuverWarningKind = ManeuverWarningKind(0i32); pub const Accident: ManeuverWarningKind = ManeuverWarningKind(1i32); pub const AdministrativeDivisionChange: ManeuverWarningKind = ManeuverWarningKind(2i32); pub const Alert: ManeuverWarningKind = ManeuverWarningKind(3i32); pub const BlockedRoad: ManeuverWarningKind = ManeuverWarningKind(4i32); pub const CheckTimetable: ManeuverWarningKind = ManeuverWarningKind(5i32); pub const Congestion: ManeuverWarningKind = ManeuverWarningKind(6i32); pub const Construction: ManeuverWarningKind = ManeuverWarningKind(7i32); pub const CountryChange: ManeuverWarningKind = ManeuverWarningKind(8i32); pub const DisabledVehicle: ManeuverWarningKind = ManeuverWarningKind(9i32); pub const GateAccess: ManeuverWarningKind = ManeuverWarningKind(10i32); pub const GetOffTransit: ManeuverWarningKind = ManeuverWarningKind(11i32); pub const GetOnTransit: ManeuverWarningKind = ManeuverWarningKind(12i32); pub const IllegalUTurn: ManeuverWarningKind = ManeuverWarningKind(13i32); pub const MassTransit: ManeuverWarningKind = ManeuverWarningKind(14i32); pub const Miscellaneous: ManeuverWarningKind = ManeuverWarningKind(15i32); pub const NoIncident: ManeuverWarningKind = ManeuverWarningKind(16i32); pub const Other: ManeuverWarningKind = ManeuverWarningKind(17i32); pub const OtherNews: ManeuverWarningKind = ManeuverWarningKind(18i32); pub const OtherTrafficIncidents: ManeuverWarningKind = ManeuverWarningKind(19i32); pub const PlannedEvent: ManeuverWarningKind = ManeuverWarningKind(20i32); pub const PrivateRoad: ManeuverWarningKind = ManeuverWarningKind(21i32); pub const RestrictedTurn: ManeuverWarningKind = ManeuverWarningKind(22i32); pub const RoadClosures: ManeuverWarningKind = ManeuverWarningKind(23i32); pub const RoadHazard: ManeuverWarningKind = ManeuverWarningKind(24i32); pub const ScheduledConstruction: ManeuverWarningKind = ManeuverWarningKind(25i32); pub const SeasonalClosures: ManeuverWarningKind = ManeuverWarningKind(26i32); pub const Tollbooth: ManeuverWarningKind = ManeuverWarningKind(27i32); pub const TollRoad: ManeuverWarningKind = ManeuverWarningKind(28i32); pub const TollZoneEnter: ManeuverWarningKind = ManeuverWarningKind(29i32); pub const TollZoneExit: ManeuverWarningKind = ManeuverWarningKind(30i32); pub const TrafficFlow: ManeuverWarningKind = ManeuverWarningKind(31i32); pub const TransitLineChange: ManeuverWarningKind = ManeuverWarningKind(32i32); pub const UnpavedRoad: ManeuverWarningKind = ManeuverWarningKind(33i32); pub const UnscheduledConstruction: ManeuverWarningKind = ManeuverWarningKind(34i32); pub const Weather: ManeuverWarningKind = ManeuverWarningKind(35i32); } impl ::core::convert::From<i32> for ManeuverWarningKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ManeuverWarningKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ManeuverWarningKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.ManeuverWarningKind;i4)"); } impl ::windows::core::DefaultType for ManeuverWarningKind { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ManeuverWarningSeverity(pub i32); impl ManeuverWarningSeverity { pub const None: ManeuverWarningSeverity = ManeuverWarningSeverity(0i32); pub const LowImpact: ManeuverWarningSeverity = ManeuverWarningSeverity(1i32); pub const Minor: ManeuverWarningSeverity = ManeuverWarningSeverity(2i32); pub const Moderate: ManeuverWarningSeverity = ManeuverWarningSeverity(3i32); pub const Serious: ManeuverWarningSeverity = ManeuverWarningSeverity(4i32); } impl ::core::convert::From<i32> for ManeuverWarningSeverity { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ManeuverWarningSeverity { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ManeuverWarningSeverity { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.ManeuverWarningSeverity;i4)"); } impl ::windows::core::DefaultType for ManeuverWarningSeverity { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MapAddress(pub ::windows::core::IInspectable); impl MapAddress { pub fn BuildingName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn BuildingFloor(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn BuildingRoom(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn BuildingWing(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn StreetNumber(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Street(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Neighborhood(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn District(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Town(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Region(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn RegionCode(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Country(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn CountryCode(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn PostCode(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Continent(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn FormattedAddress(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IMapAddress2>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for MapAddress { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.MapAddress;{cfa7a973-a3b4-4494-b3ff-cba94db69699})"); } unsafe impl ::windows::core::Interface for MapAddress { type Vtable = IMapAddress_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcfa7a973_a3b4_4494_b3ff_cba94db69699); } impl ::windows::core::RuntimeName for MapAddress { const NAME: &'static str = "Windows.Services.Maps.MapAddress"; } impl ::core::convert::From<MapAddress> for ::windows::core::IUnknown { fn from(value: MapAddress) -> Self { value.0 .0 } } impl ::core::convert::From<&MapAddress> for ::windows::core::IUnknown { fn from(value: &MapAddress) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MapAddress { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MapAddress { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MapAddress> for ::windows::core::IInspectable { fn from(value: MapAddress) -> Self { value.0 } } impl ::core::convert::From<&MapAddress> for ::windows::core::IInspectable { fn from(value: &MapAddress) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MapAddress { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MapAddress { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MapAddress {} unsafe impl ::core::marker::Sync for MapAddress {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MapLocation(pub ::windows::core::IInspectable); impl MapLocation { #[cfg(feature = "Devices_Geolocation")] pub fn Point(&self) -> ::windows::core::Result<super::super::Devices::Geolocation::Geopoint> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Devices::Geolocation::Geopoint>(result__) } } pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Description(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Address(&self) -> ::windows::core::Result<MapAddress> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MapAddress>(result__) } } } unsafe impl ::windows::core::RuntimeType for MapLocation { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.MapLocation;{3c073f57-0da4-42e8-9ee2-a96fcf2371dc})"); } unsafe impl ::windows::core::Interface for MapLocation { type Vtable = IMapLocation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c073f57_0da4_42e8_9ee2_a96fcf2371dc); } impl ::windows::core::RuntimeName for MapLocation { const NAME: &'static str = "Windows.Services.Maps.MapLocation"; } impl ::core::convert::From<MapLocation> for ::windows::core::IUnknown { fn from(value: MapLocation) -> Self { value.0 .0 } } impl ::core::convert::From<&MapLocation> for ::windows::core::IUnknown { fn from(value: &MapLocation) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MapLocation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MapLocation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MapLocation> for ::windows::core::IInspectable { fn from(value: MapLocation) -> Self { value.0 } } impl ::core::convert::From<&MapLocation> for ::windows::core::IInspectable { fn from(value: &MapLocation) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MapLocation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MapLocation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MapLocation {} unsafe impl ::core::marker::Sync for MapLocation {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MapLocationDesiredAccuracy(pub i32); impl MapLocationDesiredAccuracy { pub const High: MapLocationDesiredAccuracy = MapLocationDesiredAccuracy(0i32); pub const Low: MapLocationDesiredAccuracy = MapLocationDesiredAccuracy(1i32); } impl ::core::convert::From<i32> for MapLocationDesiredAccuracy { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MapLocationDesiredAccuracy { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MapLocationDesiredAccuracy { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.MapLocationDesiredAccuracy;i4)"); } impl ::windows::core::DefaultType for MapLocationDesiredAccuracy { type DefaultType = Self; } pub struct MapLocationFinder {} impl MapLocationFinder { #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub fn FindLocationsAtAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>>(querypoint: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapLocationFinderResult>> { Self::IMapLocationFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), querypoint.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapLocationFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub fn FindLocationsAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>>(searchtext: Param0, referencepoint: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapLocationFinderResult>> { Self::IMapLocationFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), searchtext.into_param().abi(), referencepoint.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapLocationFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub fn FindLocationsWithMaxCountAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>>(searchtext: Param0, referencepoint: Param1, maxcount: u32) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapLocationFinderResult>> { Self::IMapLocationFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), searchtext.into_param().abi(), referencepoint.into_param().abi(), maxcount, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapLocationFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub fn FindLocationsAtWithAccuracyAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>>(querypoint: Param0, accuracy: MapLocationDesiredAccuracy) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapLocationFinderResult>> { Self::IMapLocationFinderStatics2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), querypoint.into_param().abi(), accuracy, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapLocationFinderResult>>(result__) }) } pub fn IMapLocationFinderStatics<R, F: FnOnce(&IMapLocationFinderStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MapLocationFinder, IMapLocationFinderStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IMapLocationFinderStatics2<R, F: FnOnce(&IMapLocationFinderStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MapLocationFinder, IMapLocationFinderStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for MapLocationFinder { const NAME: &'static str = "Windows.Services.Maps.MapLocationFinder"; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MapLocationFinderResult(pub ::windows::core::IInspectable); impl MapLocationFinderResult { #[cfg(feature = "Foundation_Collections")] pub fn Locations(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<MapLocation>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<MapLocation>>(result__) } } pub fn Status(&self) -> ::windows::core::Result<MapLocationFinderStatus> { let this = self; unsafe { let mut result__: MapLocationFinderStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MapLocationFinderStatus>(result__) } } } unsafe impl ::windows::core::RuntimeType for MapLocationFinderResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.MapLocationFinderResult;{43f1f179-e8cc-45f6-bed2-54ccbf965d9a})"); } unsafe impl ::windows::core::Interface for MapLocationFinderResult { type Vtable = IMapLocationFinderResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x43f1f179_e8cc_45f6_bed2_54ccbf965d9a); } impl ::windows::core::RuntimeName for MapLocationFinderResult { const NAME: &'static str = "Windows.Services.Maps.MapLocationFinderResult"; } impl ::core::convert::From<MapLocationFinderResult> for ::windows::core::IUnknown { fn from(value: MapLocationFinderResult) -> Self { value.0 .0 } } impl ::core::convert::From<&MapLocationFinderResult> for ::windows::core::IUnknown { fn from(value: &MapLocationFinderResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MapLocationFinderResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MapLocationFinderResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MapLocationFinderResult> for ::windows::core::IInspectable { fn from(value: MapLocationFinderResult) -> Self { value.0 } } impl ::core::convert::From<&MapLocationFinderResult> for ::windows::core::IInspectable { fn from(value: &MapLocationFinderResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MapLocationFinderResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MapLocationFinderResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MapLocationFinderResult {} unsafe impl ::core::marker::Sync for MapLocationFinderResult {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MapLocationFinderStatus(pub i32); impl MapLocationFinderStatus { pub const Success: MapLocationFinderStatus = MapLocationFinderStatus(0i32); pub const UnknownError: MapLocationFinderStatus = MapLocationFinderStatus(1i32); pub const InvalidCredentials: MapLocationFinderStatus = MapLocationFinderStatus(2i32); pub const BadLocation: MapLocationFinderStatus = MapLocationFinderStatus(3i32); pub const IndexFailure: MapLocationFinderStatus = MapLocationFinderStatus(4i32); pub const NetworkFailure: MapLocationFinderStatus = MapLocationFinderStatus(5i32); pub const NotSupported: MapLocationFinderStatus = MapLocationFinderStatus(6i32); } impl ::core::convert::From<i32> for MapLocationFinderStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MapLocationFinderStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MapLocationFinderStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.MapLocationFinderStatus;i4)"); } impl ::windows::core::DefaultType for MapLocationFinderStatus { type DefaultType = Self; } pub struct MapManager {} impl MapManager { pub fn ShowDownloadedMapsUI() -> ::windows::core::Result<()> { Self::IMapManagerStatics(|this| unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }) } pub fn ShowMapsUpdateUI() -> ::windows::core::Result<()> { Self::IMapManagerStatics(|this| unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() }) } pub fn IMapManagerStatics<R, F: FnOnce(&IMapManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MapManager, IMapManagerStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for MapManager { const NAME: &'static str = "Windows.Services.Maps.MapManager"; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MapManeuverNotices(pub u32); impl MapManeuverNotices { pub const None: MapManeuverNotices = MapManeuverNotices(0u32); pub const Toll: MapManeuverNotices = MapManeuverNotices(1u32); pub const Unpaved: MapManeuverNotices = MapManeuverNotices(2u32); } impl ::core::convert::From<u32> for MapManeuverNotices { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MapManeuverNotices { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MapManeuverNotices { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.MapManeuverNotices;u4)"); } impl ::windows::core::DefaultType for MapManeuverNotices { type DefaultType = Self; } impl ::core::ops::BitOr for MapManeuverNotices { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for MapManeuverNotices { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for MapManeuverNotices { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for MapManeuverNotices { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for MapManeuverNotices { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MapRoute(pub ::windows::core::IInspectable); impl MapRoute { #[cfg(feature = "Devices_Geolocation")] pub fn BoundingBox(&self) -> ::windows::core::Result<super::super::Devices::Geolocation::GeoboundingBox> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Devices::Geolocation::GeoboundingBox>(result__) } } pub fn LengthInMeters(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } #[cfg(feature = "Foundation")] pub fn EstimatedDuration(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Devices_Geolocation")] pub fn Path(&self) -> ::windows::core::Result<super::super::Devices::Geolocation::Geopath> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Devices::Geolocation::Geopath>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Legs(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<MapRouteLeg>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<MapRouteLeg>>(result__) } } pub fn IsTrafficBased(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn ViolatedRestrictions(&self) -> ::windows::core::Result<MapRouteRestrictions> { let this = &::windows::core::Interface::cast::<IMapRoute2>(self)?; unsafe { let mut result__: MapRouteRestrictions = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MapRouteRestrictions>(result__) } } pub fn HasBlockedRoads(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IMapRoute2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation")] pub fn DurationWithoutTraffic(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = &::windows::core::Interface::cast::<IMapRoute3>(self)?; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } pub fn TrafficCongestion(&self) -> ::windows::core::Result<TrafficCongestion> { let this = &::windows::core::Interface::cast::<IMapRoute3>(self)?; unsafe { let mut result__: TrafficCongestion = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TrafficCongestion>(result__) } } pub fn IsScenic(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IMapRoute4>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for MapRoute { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.MapRoute;{fb07b732-584d-4583-9c60-641fea274349})"); } unsafe impl ::windows::core::Interface for MapRoute { type Vtable = IMapRoute_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb07b732_584d_4583_9c60_641fea274349); } impl ::windows::core::RuntimeName for MapRoute { const NAME: &'static str = "Windows.Services.Maps.MapRoute"; } impl ::core::convert::From<MapRoute> for ::windows::core::IUnknown { fn from(value: MapRoute) -> Self { value.0 .0 } } impl ::core::convert::From<&MapRoute> for ::windows::core::IUnknown { fn from(value: &MapRoute) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MapRoute { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MapRoute { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MapRoute> for ::windows::core::IInspectable { fn from(value: MapRoute) -> Self { value.0 } } impl ::core::convert::From<&MapRoute> for ::windows::core::IInspectable { fn from(value: &MapRoute) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MapRoute { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MapRoute { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MapRoute {} unsafe impl ::core::marker::Sync for MapRoute {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MapRouteDrivingOptions(pub ::windows::core::IInspectable); impl MapRouteDrivingOptions { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MapRouteDrivingOptions, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn MaxAlternateRouteCount(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetMaxAlternateRouteCount(&self, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation")] pub fn InitialHeading(&self) -> ::windows::core::Result<super::super::Foundation::IReference<f64>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<f64>>(result__) } } #[cfg(feature = "Foundation")] pub fn SetInitialHeading<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::IReference<f64>>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn RouteOptimization(&self) -> ::windows::core::Result<MapRouteOptimization> { let this = self; unsafe { let mut result__: MapRouteOptimization = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MapRouteOptimization>(result__) } } pub fn SetRouteOptimization(&self, value: MapRouteOptimization) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } pub fn RouteRestrictions(&self) -> ::windows::core::Result<MapRouteRestrictions> { let this = self; unsafe { let mut result__: MapRouteRestrictions = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MapRouteRestrictions>(result__) } } pub fn SetRouteRestrictions(&self, value: MapRouteRestrictions) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation")] pub fn DepartureTime(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Foundation::DateTime>> { let this = &::windows::core::Interface::cast::<IMapRouteDrivingOptions2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::super::Foundation::DateTime>>(result__) } } #[cfg(feature = "Foundation")] pub fn SetDepartureTime<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::IReference<super::super::Foundation::DateTime>>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IMapRouteDrivingOptions2>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for MapRouteDrivingOptions { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.MapRouteDrivingOptions;{6815364d-c6dc-4697-a452-b18f8f0b67a1})"); } unsafe impl ::windows::core::Interface for MapRouteDrivingOptions { type Vtable = IMapRouteDrivingOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6815364d_c6dc_4697_a452_b18f8f0b67a1); } impl ::windows::core::RuntimeName for MapRouteDrivingOptions { const NAME: &'static str = "Windows.Services.Maps.MapRouteDrivingOptions"; } impl ::core::convert::From<MapRouteDrivingOptions> for ::windows::core::IUnknown { fn from(value: MapRouteDrivingOptions) -> Self { value.0 .0 } } impl ::core::convert::From<&MapRouteDrivingOptions> for ::windows::core::IUnknown { fn from(value: &MapRouteDrivingOptions) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MapRouteDrivingOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MapRouteDrivingOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MapRouteDrivingOptions> for ::windows::core::IInspectable { fn from(value: MapRouteDrivingOptions) -> Self { value.0 } } impl ::core::convert::From<&MapRouteDrivingOptions> for ::windows::core::IInspectable { fn from(value: &MapRouteDrivingOptions) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MapRouteDrivingOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MapRouteDrivingOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MapRouteDrivingOptions {} unsafe impl ::core::marker::Sync for MapRouteDrivingOptions {} pub struct MapRouteFinder {} impl MapRouteFinder { #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub fn GetDrivingRouteAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>, Param1: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>>(startpoint: Param0, endpoint: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), startpoint.into_param().abi(), endpoint.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub fn GetDrivingRouteWithOptimizationAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>, Param1: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>>(startpoint: Param0, endpoint: Param1, optimization: MapRouteOptimization) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), startpoint.into_param().abi(), endpoint.into_param().abi(), optimization, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub fn GetDrivingRouteWithOptimizationAndRestrictionsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>, Param1: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>>(startpoint: Param0, endpoint: Param1, optimization: MapRouteOptimization, restrictions: MapRouteRestrictions) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), startpoint.into_param().abi(), endpoint.into_param().abi(), optimization, restrictions, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub fn GetDrivingRouteWithOptimizationRestrictionsAndHeadingAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>, Param1: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>>(startpoint: Param0, endpoint: Param1, optimization: MapRouteOptimization, restrictions: MapRouteRestrictions, headingindegrees: f64) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), startpoint.into_param().abi(), endpoint.into_param().abi(), optimization, restrictions, headingindegrees, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetDrivingRouteFromWaypointsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<super::super::Devices::Geolocation::Geopoint>>>(waypoints: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), waypoints.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetDrivingRouteFromWaypointsAndOptimizationAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<super::super::Devices::Geolocation::Geopoint>>>(waypoints: Param0, optimization: MapRouteOptimization) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), waypoints.into_param().abi(), optimization, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetDrivingRouteFromWaypointsOptimizationAndRestrictionsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<super::super::Devices::Geolocation::Geopoint>>>(waypoints: Param0, optimization: MapRouteOptimization, restrictions: MapRouteRestrictions) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), waypoints.into_param().abi(), optimization, restrictions, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetDrivingRouteFromWaypointsOptimizationRestrictionsAndHeadingAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<super::super::Devices::Geolocation::Geopoint>>>(waypoints: Param0, optimization: MapRouteOptimization, restrictions: MapRouteRestrictions, headingindegrees: f64) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), waypoints.into_param().abi(), optimization, restrictions, headingindegrees, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub fn GetWalkingRouteAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>, Param1: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>>(startpoint: Param0, endpoint: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), startpoint.into_param().abi(), endpoint.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetWalkingRouteFromWaypointsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<super::super::Devices::Geolocation::Geopoint>>>(waypoints: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), waypoints.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } #[cfg(all(feature = "Devices_Geolocation", feature = "Foundation"))] pub fn GetDrivingRouteWithOptionsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>, Param1: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>, Param2: ::windows::core::IntoParam<'a, MapRouteDrivingOptions>>(startpoint: Param0, endpoint: Param1, options: Param2) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), startpoint.into_param().abi(), endpoint.into_param().abi(), options.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetDrivingRouteFromEnhancedWaypointsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<EnhancedWaypoint>>>(waypoints: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics3(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), waypoints.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetDrivingRouteFromEnhancedWaypointsWithOptionsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<EnhancedWaypoint>>, Param1: ::windows::core::IntoParam<'a, MapRouteDrivingOptions>>(waypoints: Param0, options: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>> { Self::IMapRouteFinderStatics3(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), waypoints.into_param().abi(), options.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MapRouteFinderResult>>(result__) }) } pub fn IMapRouteFinderStatics<R, F: FnOnce(&IMapRouteFinderStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MapRouteFinder, IMapRouteFinderStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IMapRouteFinderStatics2<R, F: FnOnce(&IMapRouteFinderStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MapRouteFinder, IMapRouteFinderStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IMapRouteFinderStatics3<R, F: FnOnce(&IMapRouteFinderStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MapRouteFinder, IMapRouteFinderStatics3> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for MapRouteFinder { const NAME: &'static str = "Windows.Services.Maps.MapRouteFinder"; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MapRouteFinderResult(pub ::windows::core::IInspectable); impl MapRouteFinderResult { pub fn Route(&self) -> ::windows::core::Result<MapRoute> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MapRoute>(result__) } } pub fn Status(&self) -> ::windows::core::Result<MapRouteFinderStatus> { let this = self; unsafe { let mut result__: MapRouteFinderStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MapRouteFinderStatus>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn AlternateRoutes(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<MapRoute>> { let this = &::windows::core::Interface::cast::<IMapRouteFinderResult2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<MapRoute>>(result__) } } } unsafe impl ::windows::core::RuntimeType for MapRouteFinderResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.MapRouteFinderResult;{a868a31a-9422-46ac-8ca1-b1614d4bfbe2})"); } unsafe impl ::windows::core::Interface for MapRouteFinderResult { type Vtable = IMapRouteFinderResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa868a31a_9422_46ac_8ca1_b1614d4bfbe2); } impl ::windows::core::RuntimeName for MapRouteFinderResult { const NAME: &'static str = "Windows.Services.Maps.MapRouteFinderResult"; } impl ::core::convert::From<MapRouteFinderResult> for ::windows::core::IUnknown { fn from(value: MapRouteFinderResult) -> Self { value.0 .0 } } impl ::core::convert::From<&MapRouteFinderResult> for ::windows::core::IUnknown { fn from(value: &MapRouteFinderResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MapRouteFinderResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MapRouteFinderResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MapRouteFinderResult> for ::windows::core::IInspectable { fn from(value: MapRouteFinderResult) -> Self { value.0 } } impl ::core::convert::From<&MapRouteFinderResult> for ::windows::core::IInspectable { fn from(value: &MapRouteFinderResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MapRouteFinderResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MapRouteFinderResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MapRouteFinderResult {} unsafe impl ::core::marker::Sync for MapRouteFinderResult {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MapRouteFinderStatus(pub i32); impl MapRouteFinderStatus { pub const Success: MapRouteFinderStatus = MapRouteFinderStatus(0i32); pub const UnknownError: MapRouteFinderStatus = MapRouteFinderStatus(1i32); pub const InvalidCredentials: MapRouteFinderStatus = MapRouteFinderStatus(2i32); pub const NoRouteFound: MapRouteFinderStatus = MapRouteFinderStatus(3i32); pub const NoRouteFoundWithGivenOptions: MapRouteFinderStatus = MapRouteFinderStatus(4i32); pub const StartPointNotFound: MapRouteFinderStatus = MapRouteFinderStatus(5i32); pub const EndPointNotFound: MapRouteFinderStatus = MapRouteFinderStatus(6i32); pub const NoPedestrianRouteFound: MapRouteFinderStatus = MapRouteFinderStatus(7i32); pub const NetworkFailure: MapRouteFinderStatus = MapRouteFinderStatus(8i32); pub const NotSupported: MapRouteFinderStatus = MapRouteFinderStatus(9i32); } impl ::core::convert::From<i32> for MapRouteFinderStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MapRouteFinderStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MapRouteFinderStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.MapRouteFinderStatus;i4)"); } impl ::windows::core::DefaultType for MapRouteFinderStatus { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MapRouteLeg(pub ::windows::core::IInspectable); impl MapRouteLeg { #[cfg(feature = "Devices_Geolocation")] pub fn BoundingBox(&self) -> ::windows::core::Result<super::super::Devices::Geolocation::GeoboundingBox> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Devices::Geolocation::GeoboundingBox>(result__) } } #[cfg(feature = "Devices_Geolocation")] pub fn Path(&self) -> ::windows::core::Result<super::super::Devices::Geolocation::Geopath> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Devices::Geolocation::Geopath>(result__) } } pub fn LengthInMeters(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } #[cfg(feature = "Foundation")] pub fn EstimatedDuration(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Maneuvers(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<MapRouteManeuver>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<MapRouteManeuver>>(result__) } } #[cfg(feature = "Foundation")] pub fn DurationWithoutTraffic(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = &::windows::core::Interface::cast::<IMapRouteLeg2>(self)?; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } pub fn TrafficCongestion(&self) -> ::windows::core::Result<TrafficCongestion> { let this = &::windows::core::Interface::cast::<IMapRouteLeg2>(self)?; unsafe { let mut result__: TrafficCongestion = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TrafficCongestion>(result__) } } } unsafe impl ::windows::core::RuntimeType for MapRouteLeg { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.MapRouteLeg;{96f8b2f6-5bba-4d17-9db6-1a263fec7471})"); } unsafe impl ::windows::core::Interface for MapRouteLeg { type Vtable = IMapRouteLeg_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96f8b2f6_5bba_4d17_9db6_1a263fec7471); } impl ::windows::core::RuntimeName for MapRouteLeg { const NAME: &'static str = "Windows.Services.Maps.MapRouteLeg"; } impl ::core::convert::From<MapRouteLeg> for ::windows::core::IUnknown { fn from(value: MapRouteLeg) -> Self { value.0 .0 } } impl ::core::convert::From<&MapRouteLeg> for ::windows::core::IUnknown { fn from(value: &MapRouteLeg) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MapRouteLeg { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MapRouteLeg { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MapRouteLeg> for ::windows::core::IInspectable { fn from(value: MapRouteLeg) -> Self { value.0 } } impl ::core::convert::From<&MapRouteLeg> for ::windows::core::IInspectable { fn from(value: &MapRouteLeg) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MapRouteLeg { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MapRouteLeg { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MapRouteLeg {} unsafe impl ::core::marker::Sync for MapRouteLeg {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MapRouteManeuver(pub ::windows::core::IInspectable); impl MapRouteManeuver { #[cfg(feature = "Devices_Geolocation")] pub fn StartingPoint(&self) -> ::windows::core::Result<super::super::Devices::Geolocation::Geopoint> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Devices::Geolocation::Geopoint>(result__) } } pub fn LengthInMeters(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } pub fn InstructionText(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Kind(&self) -> ::windows::core::Result<MapRouteManeuverKind> { let this = self; unsafe { let mut result__: MapRouteManeuverKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MapRouteManeuverKind>(result__) } } pub fn ExitNumber(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn ManeuverNotices(&self) -> ::windows::core::Result<MapManeuverNotices> { let this = self; unsafe { let mut result__: MapManeuverNotices = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MapManeuverNotices>(result__) } } pub fn StartHeading(&self) -> ::windows::core::Result<f64> { let this = &::windows::core::Interface::cast::<IMapRouteManeuver2>(self)?; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } pub fn EndHeading(&self) -> ::windows::core::Result<f64> { let this = &::windows::core::Interface::cast::<IMapRouteManeuver2>(self)?; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } pub fn StreetName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IMapRouteManeuver2>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Warnings(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<ManeuverWarning>> { let this = &::windows::core::Interface::cast::<IMapRouteManeuver3>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<ManeuverWarning>>(result__) } } } unsafe impl ::windows::core::RuntimeType for MapRouteManeuver { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.MapRouteManeuver;{ed5c17f0-a6ab-4d65-a086-fa8a7e340df2})"); } unsafe impl ::windows::core::Interface for MapRouteManeuver { type Vtable = IMapRouteManeuver_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xed5c17f0_a6ab_4d65_a086_fa8a7e340df2); } impl ::windows::core::RuntimeName for MapRouteManeuver { const NAME: &'static str = "Windows.Services.Maps.MapRouteManeuver"; } impl ::core::convert::From<MapRouteManeuver> for ::windows::core::IUnknown { fn from(value: MapRouteManeuver) -> Self { value.0 .0 } } impl ::core::convert::From<&MapRouteManeuver> for ::windows::core::IUnknown { fn from(value: &MapRouteManeuver) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MapRouteManeuver { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MapRouteManeuver { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MapRouteManeuver> for ::windows::core::IInspectable { fn from(value: MapRouteManeuver) -> Self { value.0 } } impl ::core::convert::From<&MapRouteManeuver> for ::windows::core::IInspectable { fn from(value: &MapRouteManeuver) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MapRouteManeuver { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MapRouteManeuver { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MapRouteManeuver {} unsafe impl ::core::marker::Sync for MapRouteManeuver {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MapRouteManeuverKind(pub i32); impl MapRouteManeuverKind { pub const None: MapRouteManeuverKind = MapRouteManeuverKind(0i32); pub const Start: MapRouteManeuverKind = MapRouteManeuverKind(1i32); pub const Stopover: MapRouteManeuverKind = MapRouteManeuverKind(2i32); pub const StopoverResume: MapRouteManeuverKind = MapRouteManeuverKind(3i32); pub const End: MapRouteManeuverKind = MapRouteManeuverKind(4i32); pub const GoStraight: MapRouteManeuverKind = MapRouteManeuverKind(5i32); pub const UTurnLeft: MapRouteManeuverKind = MapRouteManeuverKind(6i32); pub const UTurnRight: MapRouteManeuverKind = MapRouteManeuverKind(7i32); pub const TurnKeepLeft: MapRouteManeuverKind = MapRouteManeuverKind(8i32); pub const TurnKeepRight: MapRouteManeuverKind = MapRouteManeuverKind(9i32); pub const TurnLightLeft: MapRouteManeuverKind = MapRouteManeuverKind(10i32); pub const TurnLightRight: MapRouteManeuverKind = MapRouteManeuverKind(11i32); pub const TurnLeft: MapRouteManeuverKind = MapRouteManeuverKind(12i32); pub const TurnRight: MapRouteManeuverKind = MapRouteManeuverKind(13i32); pub const TurnHardLeft: MapRouteManeuverKind = MapRouteManeuverKind(14i32); pub const TurnHardRight: MapRouteManeuverKind = MapRouteManeuverKind(15i32); pub const FreewayEnterLeft: MapRouteManeuverKind = MapRouteManeuverKind(16i32); pub const FreewayEnterRight: MapRouteManeuverKind = MapRouteManeuverKind(17i32); pub const FreewayLeaveLeft: MapRouteManeuverKind = MapRouteManeuverKind(18i32); pub const FreewayLeaveRight: MapRouteManeuverKind = MapRouteManeuverKind(19i32); pub const FreewayContinueLeft: MapRouteManeuverKind = MapRouteManeuverKind(20i32); pub const FreewayContinueRight: MapRouteManeuverKind = MapRouteManeuverKind(21i32); pub const TrafficCircleLeft: MapRouteManeuverKind = MapRouteManeuverKind(22i32); pub const TrafficCircleRight: MapRouteManeuverKind = MapRouteManeuverKind(23i32); pub const TakeFerry: MapRouteManeuverKind = MapRouteManeuverKind(24i32); } impl ::core::convert::From<i32> for MapRouteManeuverKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MapRouteManeuverKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MapRouteManeuverKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.MapRouteManeuverKind;i4)"); } impl ::windows::core::DefaultType for MapRouteManeuverKind { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MapRouteOptimization(pub i32); impl MapRouteOptimization { pub const Time: MapRouteOptimization = MapRouteOptimization(0i32); pub const Distance: MapRouteOptimization = MapRouteOptimization(1i32); pub const TimeWithTraffic: MapRouteOptimization = MapRouteOptimization(2i32); pub const Scenic: MapRouteOptimization = MapRouteOptimization(3i32); } impl ::core::convert::From<i32> for MapRouteOptimization { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MapRouteOptimization { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MapRouteOptimization { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.MapRouteOptimization;i4)"); } impl ::windows::core::DefaultType for MapRouteOptimization { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MapRouteRestrictions(pub u32); impl MapRouteRestrictions { pub const None: MapRouteRestrictions = MapRouteRestrictions(0u32); pub const Highways: MapRouteRestrictions = MapRouteRestrictions(1u32); pub const TollRoads: MapRouteRestrictions = MapRouteRestrictions(2u32); pub const Ferries: MapRouteRestrictions = MapRouteRestrictions(4u32); pub const Tunnels: MapRouteRestrictions = MapRouteRestrictions(8u32); pub const DirtRoads: MapRouteRestrictions = MapRouteRestrictions(16u32); pub const Motorail: MapRouteRestrictions = MapRouteRestrictions(32u32); } impl ::core::convert::From<u32> for MapRouteRestrictions { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MapRouteRestrictions { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MapRouteRestrictions { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.MapRouteRestrictions;u4)"); } impl ::windows::core::DefaultType for MapRouteRestrictions { type DefaultType = Self; } impl ::core::ops::BitOr for MapRouteRestrictions { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for MapRouteRestrictions { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for MapRouteRestrictions { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for MapRouteRestrictions { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for MapRouteRestrictions { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } pub struct MapService {} impl MapService { pub fn SetServiceToken<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(value: Param0) -> ::windows::core::Result<()> { Self::IMapServiceStatics(|this| unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }) } pub fn ServiceToken() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IMapServiceStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn WorldViewRegionCode() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IMapServiceStatics2(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn DataAttributions() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IMapServiceStatics3(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn SetDataUsagePreference(value: MapServiceDataUsagePreference) -> ::windows::core::Result<()> { Self::IMapServiceStatics4(|this| unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value).ok() }) } pub fn DataUsagePreference() -> ::windows::core::Result<MapServiceDataUsagePreference> { Self::IMapServiceStatics4(|this| unsafe { let mut result__: MapServiceDataUsagePreference = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MapServiceDataUsagePreference>(result__) }) } pub fn IMapServiceStatics<R, F: FnOnce(&IMapServiceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MapService, IMapServiceStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IMapServiceStatics2<R, F: FnOnce(&IMapServiceStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MapService, IMapServiceStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IMapServiceStatics3<R, F: FnOnce(&IMapServiceStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MapService, IMapServiceStatics3> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IMapServiceStatics4<R, F: FnOnce(&IMapServiceStatics4) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MapService, IMapServiceStatics4> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for MapService { const NAME: &'static str = "Windows.Services.Maps.MapService"; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MapServiceDataUsagePreference(pub i32); impl MapServiceDataUsagePreference { pub const Default: MapServiceDataUsagePreference = MapServiceDataUsagePreference(0i32); pub const OfflineMapDataOnly: MapServiceDataUsagePreference = MapServiceDataUsagePreference(1i32); } impl ::core::convert::From<i32> for MapServiceDataUsagePreference { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MapServiceDataUsagePreference { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MapServiceDataUsagePreference { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.MapServiceDataUsagePreference;i4)"); } impl ::windows::core::DefaultType for MapServiceDataUsagePreference { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlaceInfo(pub ::windows::core::IInspectable); impl PlaceInfo { #[cfg(feature = "Foundation")] pub fn Show<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, selection: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), selection.into_param().abi()).ok() } } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowWithPreferredPlacement<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, selection: Param0, preferredplacement: super::super::UI::Popups::Placement) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), selection.into_param().abi(), preferredplacement).ok() } } pub fn Identifier(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn DisplayAddress(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Devices_Geolocation")] pub fn Geoshape(&self) -> ::windows::core::Result<super::super::Devices::Geolocation::IGeoshape> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Devices::Geolocation::IGeoshape>(result__) } } #[cfg(feature = "Devices_Geolocation")] pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>>(referencepoint: Param0) -> ::windows::core::Result<PlaceInfo> { Self::IPlaceInfoStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), referencepoint.into_param().abi(), &mut result__).from_abi::<PlaceInfo>(result__) }) } #[cfg(feature = "Devices_Geolocation")] pub fn CreateWithGeopointAndOptions<'a, Param0: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>, Param1: ::windows::core::IntoParam<'a, PlaceInfoCreateOptions>>(referencepoint: Param0, options: Param1) -> ::windows::core::Result<PlaceInfo> { Self::IPlaceInfoStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), referencepoint.into_param().abi(), options.into_param().abi(), &mut result__).from_abi::<PlaceInfo>(result__) }) } pub fn CreateFromIdentifier<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(identifier: Param0) -> ::windows::core::Result<PlaceInfo> { Self::IPlaceInfoStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), identifier.into_param().abi(), &mut result__).from_abi::<PlaceInfo>(result__) }) } #[cfg(feature = "Devices_Geolocation")] pub fn CreateFromIdentifierWithOptions<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Devices::Geolocation::Geopoint>, Param2: ::windows::core::IntoParam<'a, PlaceInfoCreateOptions>>(identifier: Param0, defaultpoint: Param1, options: Param2) -> ::windows::core::Result<PlaceInfo> { Self::IPlaceInfoStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), identifier.into_param().abi(), defaultpoint.into_param().abi(), options.into_param().abi(), &mut result__).from_abi::<PlaceInfo>(result__) }) } pub fn CreateFromMapLocation<'a, Param0: ::windows::core::IntoParam<'a, MapLocation>>(location: Param0) -> ::windows::core::Result<PlaceInfo> { Self::IPlaceInfoStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), location.into_param().abi(), &mut result__).from_abi::<PlaceInfo>(result__) }) } pub fn IsShowSupported() -> ::windows::core::Result<bool> { Self::IPlaceInfoStatics(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) }) } pub fn CreateFromAddress<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(displayaddress: Param0) -> ::windows::core::Result<PlaceInfo> { Self::IPlaceInfoStatics2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), displayaddress.into_param().abi(), &mut result__).from_abi::<PlaceInfo>(result__) }) } pub fn CreateFromAddressWithName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(displayaddress: Param0, displayname: Param1) -> ::windows::core::Result<PlaceInfo> { Self::IPlaceInfoStatics2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), displayaddress.into_param().abi(), displayname.into_param().abi(), &mut result__).from_abi::<PlaceInfo>(result__) }) } pub fn IPlaceInfoStatics<R, F: FnOnce(&IPlaceInfoStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlaceInfo, IPlaceInfoStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IPlaceInfoStatics2<R, F: FnOnce(&IPlaceInfoStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlaceInfo, IPlaceInfoStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PlaceInfo { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.PlaceInfo;{9a0810b6-31c8-4f6a-9f18-950b4c38951a})"); } unsafe impl ::windows::core::Interface for PlaceInfo { type Vtable = IPlaceInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9a0810b6_31c8_4f6a_9f18_950b4c38951a); } impl ::windows::core::RuntimeName for PlaceInfo { const NAME: &'static str = "Windows.Services.Maps.PlaceInfo"; } impl ::core::convert::From<PlaceInfo> for ::windows::core::IUnknown { fn from(value: PlaceInfo) -> Self { value.0 .0 } } impl ::core::convert::From<&PlaceInfo> for ::windows::core::IUnknown { fn from(value: &PlaceInfo) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlaceInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PlaceInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlaceInfo> for ::windows::core::IInspectable { fn from(value: PlaceInfo) -> Self { value.0 } } impl ::core::convert::From<&PlaceInfo> for ::windows::core::IInspectable { fn from(value: &PlaceInfo) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlaceInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PlaceInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PlaceInfo {} unsafe impl ::core::marker::Sync for PlaceInfo {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlaceInfoCreateOptions(pub ::windows::core::IInspectable); impl PlaceInfoCreateOptions { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlaceInfoCreateOptions, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn SetDisplayName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetDisplayAddress<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn DisplayAddress(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for PlaceInfoCreateOptions { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.Maps.PlaceInfoCreateOptions;{cd33c125-67f1-4bb3-9907-ecce939b0399})"); } unsafe impl ::windows::core::Interface for PlaceInfoCreateOptions { type Vtable = IPlaceInfoCreateOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcd33c125_67f1_4bb3_9907_ecce939b0399); } impl ::windows::core::RuntimeName for PlaceInfoCreateOptions { const NAME: &'static str = "Windows.Services.Maps.PlaceInfoCreateOptions"; } impl ::core::convert::From<PlaceInfoCreateOptions> for ::windows::core::IUnknown { fn from(value: PlaceInfoCreateOptions) -> Self { value.0 .0 } } impl ::core::convert::From<&PlaceInfoCreateOptions> for ::windows::core::IUnknown { fn from(value: &PlaceInfoCreateOptions) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlaceInfoCreateOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PlaceInfoCreateOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlaceInfoCreateOptions> for ::windows::core::IInspectable { fn from(value: PlaceInfoCreateOptions) -> Self { value.0 } } impl ::core::convert::From<&PlaceInfoCreateOptions> for ::windows::core::IInspectable { fn from(value: &PlaceInfoCreateOptions) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlaceInfoCreateOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PlaceInfoCreateOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PlaceInfoCreateOptions {} unsafe impl ::core::marker::Sync for PlaceInfoCreateOptions {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct TrafficCongestion(pub i32); impl TrafficCongestion { pub const Unknown: TrafficCongestion = TrafficCongestion(0i32); pub const Light: TrafficCongestion = TrafficCongestion(1i32); pub const Mild: TrafficCongestion = TrafficCongestion(2i32); pub const Medium: TrafficCongestion = TrafficCongestion(3i32); pub const Heavy: TrafficCongestion = TrafficCongestion(4i32); } impl ::core::convert::From<i32> for TrafficCongestion { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for TrafficCongestion { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for TrafficCongestion { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.TrafficCongestion;i4)"); } impl ::windows::core::DefaultType for TrafficCongestion { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct WaypointKind(pub i32); impl WaypointKind { pub const Stop: WaypointKind = WaypointKind(0i32); pub const Via: WaypointKind = WaypointKind(1i32); } impl ::core::convert::From<i32> for WaypointKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for WaypointKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for WaypointKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.Maps.WaypointKind;i4)"); } impl ::windows::core::DefaultType for WaypointKind { type DefaultType = Self; }
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::PINASSIGN7 { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct CTOUT_1_OR { bits: u8, } impl CTOUT_1_OR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct CTOUT_2_OR { bits: u8, } impl CTOUT_2_OR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct CTOUT_3_OR { bits: u8, } impl CTOUT_3_OR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct I2C_SDA_IOR { bits: u8, } impl I2C_SDA_IOR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Proxy"] pub struct _CTOUT_1_OW<'a> { w: &'a mut W, } impl<'a> _CTOUT_1_OW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 255; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CTOUT_2_OW<'a> { w: &'a mut W, } impl<'a> _CTOUT_2_OW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 255; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CTOUT_3_OW<'a> { w: &'a mut W, } impl<'a> _CTOUT_3_OW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 255; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _I2C_SDA_IOW<'a> { w: &'a mut W, } impl<'a> _I2C_SDA_IOW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 255; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:7 - CTOUT_1 function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn ctout_1_o(&self) -> CTOUT_1_OR { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; CTOUT_1_OR { bits } } #[doc = "Bits 8:15 - CTOUT_2 function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn ctout_2_o(&self) -> CTOUT_2_OR { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 }; CTOUT_2_OR { bits } } #[doc = "Bits 16:23 - CTOUT_3 function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn ctout_3_o(&self) -> CTOUT_3_OR { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 }; CTOUT_3_OR { bits } } #[doc = "Bits 24:31 - I2C_SDA function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn i2c_sda_io(&self) -> I2C_SDA_IOR { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 }; I2C_SDA_IOR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 4294967295 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:7 - CTOUT_1 function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn ctout_1_o(&mut self) -> _CTOUT_1_OW { _CTOUT_1_OW { w: self } } #[doc = "Bits 8:15 - CTOUT_2 function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn ctout_2_o(&mut self) -> _CTOUT_2_OW { _CTOUT_2_OW { w: self } } #[doc = "Bits 16:23 - CTOUT_3 function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn ctout_3_o(&mut self) -> _CTOUT_3_OW { _CTOUT_3_OW { w: self } } #[doc = "Bits 24:31 - I2C_SDA function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn i2c_sda_io(&mut self) -> _I2C_SDA_IOW { _I2C_SDA_IOW { w: self } } }
//! Linux LibOS //! - run process and manage trap/interrupt/syscall #![no_std] #![feature(asm)] #![deny(warnings, unused_must_use, missing_docs)] extern crate alloc; #[macro_use] extern crate log; use { alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}, core::{future::Future, pin::Pin}, kernel_hal::MMUFlags, linux_object::{ fs::{vfs::FileSystem, INodeExt}, loader::LinuxElfLoader, process::ProcessExt, thread::ThreadExt, }, linux_syscall::Syscall, zircon_object::task::*, }; #[cfg(target_arch = "riscv64")] use {kernel_hal::UserContext, zircon_object::object::KernelObject}; #[cfg(target_arch = "x86_64")] use kernel_hal::GeneralRegs; /// Create and run main Linux process pub fn run(args: Vec<String>, envs: Vec<String>, rootfs: Arc<dyn FileSystem>) -> Arc<Process> { let job = Job::root(); let proc = Process::create_linux(&job, rootfs.clone()).unwrap(); let thread = Thread::create_linux(&proc).unwrap(); let loader = LinuxElfLoader { #[cfg(feature = "std")] syscall_entry: kernel_hal_unix::syscall_entry as usize, #[cfg(not(feature = "std"))] syscall_entry: 0, stack_pages: 8, root_inode: rootfs.root_inode(), }; { let mut id = 0; let rust_dir = rootfs.root_inode().lookup("/").unwrap(); trace!("run(), Rootfs: / "); while let Ok(name) = rust_dir.get_entry(id) { id += 1; trace!(" {}", name); } } info!("args {:?}", args); let inode = rootfs.root_inode().lookup(&args[0]).unwrap(); let data = inode.read_as_vec().unwrap(); let path = args[0].clone(); debug!("Linux process: {:?}", path); let pg_token = kernel_hal::current_page_table(); debug!("current pgt = {:#x}", pg_token); //调用zircon-object/src/task/thread.start设置好要执行的thread let (entry, sp) = loader.load(&proc.vmar(), &data, args, envs, path).unwrap(); thread .start(entry, sp, 0, 0, thread_fn) .expect("failed to start main thread"); proc } /// The function of a new thread. /// /// loop: /// - wait for the thread to be ready /// - get user thread context /// - enter user mode /// - handle trap/interrupt/syscall according to the return value /// - return the context to the user thread async fn new_thread(thread: CurrentThread) { loop { // wait let mut cx = thread.wait_for_run().await; if thread.state() == ThreadState::Dying { break; } // run trace!("go to user: {:#x?}", cx); kernel_hal::context_run(&mut cx); trace!("back from user: {:#x?}", cx); // handle trap/interrupt/syscall #[cfg(target_arch = "x86_64")] match cx.trap_num { 0x100 => handle_syscall(&thread, &mut cx.general).await, 0x20..=0x3f => { kernel_hal::InterruptManager::handle(cx.trap_num as u8); if cx.trap_num == 0x20 { kernel_hal::yield_now().await; } } 0xe => { let vaddr = kernel_hal::fetch_fault_vaddr(); let flags = if cx.error_code & 0x2 == 0 { MMUFlags::READ } else { MMUFlags::WRITE }; error!("page fualt from user mode {:#x} {:#x?}", vaddr, flags); let vmar = thread.proc().vmar(); match vmar.handle_page_fault(vaddr, flags) { Ok(()) => {} Err(_) => { panic!("Page Fault from user mode {:#x?}", cx); } } } _ => panic!("not supported interrupt from user mode. {:#x?}", cx), } // UserContext #[cfg(target_arch = "riscv64")] { let trap_num = kernel_hal::fetch_trap_num(&cx); let is_interrupt = ((trap_num >> 63) & 1) == 1; let trap_num = trap_num & 0xfff; let pid = thread.proc().id(); if is_interrupt { match trap_num { //Irq 0 | 4 | 5 | 8 | 9 => { kernel_hal::InterruptManager::handle(trap_num as u8); //Timer if trap_num == 4 || trap_num == 5 { debug!("Timer interrupt: {}", trap_num); /* * 已在irq_handle里加入了timer处理函数 kernel_hal::timer_set_next(); kernel_hal::timer_tick(); */ kernel_hal::yield_now().await; } //kernel_hal::InterruptManager::handle(trap_num as u8); } _ => panic!( "not supported pid: {} interrupt {} from user mode. {:#x?}", pid, trap_num, cx ), } } else { match trap_num { // syscall 8 => handle_syscall(&thread, &mut cx).await, // PageFault 12 | 13 | 15 => { let vaddr = kernel_hal::fetch_fault_vaddr(); //注意这里flags没有包含WRITE权限,后面handle会移除写权限 let flags = if trap_num == 15 { MMUFlags::WRITE } else if trap_num == 12 { MMUFlags::EXECUTE } else { MMUFlags::READ }; info!( "page fualt from pid: {} user mode, vaddr:{:#x}, trap:{}", pid, vaddr, trap_num ); let vmar = thread.proc().vmar(); match vmar.handle_page_fault(vaddr, flags) { Ok(()) => {} Err(error) => { panic!("{:?} Page Fault from user mode {:#x?}", error, cx); } } } _ => panic!( "not supported pid: {} exception {} from user mode. {:#x?}", pid, trap_num, cx ), } } } thread.end_running(cx); } } fn thread_fn(thread: CurrentThread) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> { Box::pin(new_thread(thread)) } /// syscall handler entry #[cfg(target_arch = "x86_64")] async fn handle_syscall(thread: &CurrentThread, regs: &mut GeneralRegs) { trace!("syscall: {:#x?}", regs); let num = regs.rax as u32; let args = [regs.rdi, regs.rsi, regs.rdx, regs.r10, regs.r8, regs.r9]; let mut syscall = Syscall { thread, #[cfg(feature = "std")] syscall_entry: kernel_hal_unix::syscall_entry as usize, #[cfg(not(feature = "std"))] syscall_entry: 0, thread_fn, regs, }; regs.rax = syscall.syscall(num, args).await as usize; } #[cfg(target_arch = "riscv64")] async fn handle_syscall(thread: &CurrentThread, cx: &mut UserContext) { trace!("syscall: {:#x?}", cx.general); let num = cx.general.a7 as u32; let args = [ cx.general.a0, cx.general.a1, cx.general.a2, cx.general.a3, cx.general.a4, cx.general.a5, ]; // add before fork cx.sepc += 4; //注意, 此时的regs没有原context所有权,故无法通过此regs修改寄存器 //let regs = &mut (cx.general as GeneralRegs); let mut syscall = Syscall { thread, #[cfg(feature = "std")] syscall_entry: kernel_hal_unix::syscall_entry as usize, #[cfg(not(feature = "std"))] syscall_entry: 0, context: cx, thread_fn, }; cx.general.a0 = syscall.syscall(num, args).await as usize; }
use bevy::{ input::mouse::{MouseButtonInput, MouseMotion, MouseWheel}, prelude::*, window::CursorMoved, sprite::collide_aabb::{collide, Collision} }; use bevy::{core::FixedTimestep, prelude::*}; use std::convert::TryInto; use std::collections::HashMap; use bevy_ggrs::{GGRSApp, GGRSPlugin, RollbackIdProvider}; use ggrs::{GameInput, P2PSession, P2PSpectatorSession, PlayerHandle, SyncTestSession, PlayerType}; use std::net::SocketAddr; use structopt::StructOpt; const INPUT_SIZE: usize = std::mem::size_of::<u32>(); const FPS: u32 = 60; mod systems; use crate::systems::*; struct Player { handle: u32 } pub struct AudioLib { audio_files: HashMap<String, Handle<AudioSource>> } impl Default for AudioLib { fn default() -> AudioLib { AudioLib { audio_files: HashMap::new() } } } #[derive(Default)] pub struct InputTracking { pub last_mouse_pos: Vec2 } #[derive(StructOpt)] struct Opt { #[structopt(short, long)] local_port: u16, #[structopt(short, long)] players: Vec<String>, #[structopt(short, long)] spectators: Vec<SocketAddr>, } fn main() -> Result<(), Box<dyn std::error::Error>> { // read cmd line arguments let opt = Opt::from_args(); let mut local_handle = 0; let num_players = opt.players.len(); assert!(num_players > 0); //setup p2p sessions let mut p2p_sess = ggrs::start_p2p_session(num_players as u32, INPUT_SIZE, opt.local_port)?; p2p_sess.set_sparse_saving(true)?; for (i, player_addr) in opt.players.iter().enumerate() { // local player if player_addr == "localhost" { p2p_sess.add_player(PlayerType::Local, i)?; local_handle = i; } else { // remote players let remote_addr: SocketAddr = player_addr.parse()?; p2p_sess.add_player(PlayerType::Remote(remote_addr), i)?; } } // optionally, add spectators for (i, spec_addr) in opt.spectators.iter().enumerate() { p2p_sess.add_player(PlayerType::Spectator(*spec_addr), num_players + i)?; } p2p_sess.set_frame_delay(2, local_handle)?; p2p_sess.set_fps(FPS)?; p2p_sess.start_session()?; App::new() .insert_resource(ClearColor(Color::rgb(0.5, 0.5, 0.9))) .insert_resource(WindowDescriptor{ title: "Go".to_string(), width: 320., height: 320., vsync: true, ..Default::default() }) .add_plugins(DefaultPlugins) .add_plugin(GGRSPlugin) .add_startup_system(network_setup.system()) .with_p2p_session(p2p_sess) .insert_resource(InputTracking::default()) .insert_resource(GameState::default()) .insert_resource(AudioLib::default()) .with_rollback_run_criteria(FixedTimestep::steps_per_second(FPS as f64)) .with_input_system(input.system()) .add_system(animate_sprite_system.system()) .add_rollback_system(make_move_system.system()) .register_rollback_type::<GameState>() .run(); Ok(()) } pub fn input( _handle: In<PlayerHandle>, mut mouse_button_input_events: EventReader<MouseButtonInput>, mut cursor_moved_events: EventReader<CursorMoved>, mut input_tracking: ResMut<InputTracking>, mut game_state: ResMut<GameState>, mut tile_query: Query<(&Transform, &mut TileSpriteData)> ) -> Vec<u8> { for event in cursor_moved_events.iter() { input_tracking.last_mouse_pos = event.position; } let mut index = 0; for event in mouse_button_input_events.iter() { match event.button { MouseButton::Left => { let mut input_encoding : u32 = 0; input_encoding |= (input_tracking.last_mouse_pos.x as u32); input_encoding = input_encoding << 16; input_encoding |= (input_tracking.last_mouse_pos.y as u32); println!("Sending:"); println!("{:?} {:?}", input_tracking.last_mouse_pos.x, input_tracking.last_mouse_pos.y); return input_encoding.to_be_bytes().to_vec(); },_ => {} } } vec![0, 0, 0, 0] } fn animate_sprite_system( time: Res<Time>, texture_atlases: Res<Assets<TextureAtlas>>, game_state: Res<GameState>, mut query: Query<(&mut TextureAtlasSprite, &Handle<TextureAtlas>, &TileSpriteData)>, ) { for (mut sprite, texture_atlas_handle, tile) in query.iter_mut() { let texture_atlas = texture_atlases.get(texture_atlas_handle).unwrap(); match game_state.game_board[tile.index].tile_state { Tile::Empty => { sprite.index = 2; }, Tile::Black => { sprite.index = 0; }, Tile::White => { sprite.index = 1; } } } } fn make_move_system( mut game_state: ResMut<GameState>, mut tile_query: Query<(&Transform, &mut TileSpriteData)>, inputs: Res<Vec<GameInput>> ) { for i in inputs.iter() { let mut sum : u32 = 0; for x in 0..4 { sum = sum << 8; sum |= i.buffer[x] as u32; } if sum > 0 { //WE HAVE A MESSAGE FROM THE OTHER SIDE let x = sum >> 16; sum = sum << 16; let y = sum >> 16; println!("I GOt"); println!("{} {}", x, y); for (transform, mut tile) in tile_query.iter_mut() { match game_state.game_board[tile.index].tile_state { Tile::Empty => { let dif = (transform.translation - Vec3::new(x as f32, y as f32, 0.0)).length(); if dif < 16.0 { game_state.game_board[tile.index].tile_state = game_state.current_player; if game_state.current_player_id == 0 { game_state.current_player_id = 1; game_state.current_player = Tile::Black; } else { game_state.current_player_id = 0; game_state.current_player = Tile::White; } } },_ => {} } } } } } fn network_setup( mut commands: Commands, mut texture_atlases: ResMut<Assets<TextureAtlas>>, rip: ResMut<RollbackIdProvider>, mut audio_lib: ResMut<AudioLib>, asset_server: Res<AssetServer>, p2p_session: Option<Res<P2PSession>>, audio: Res<Audio>, session: Option<Res<SyncTestSession>> ) { let texture_handle = asset_server.load("textures/go/go_spritesheet.png"); let texture_atlas = TextureAtlas::from_grid(texture_handle, Vec2::new(32.0, 32.0), 1, 3); let texture_atlas_handle = texture_atlases.add(texture_atlas); let mut ocb = OrthographicCameraBundle::new_2d(); ocb.transform.translation = Vec3::new(160.0, 160., 0.); commands.spawn_bundle(ocb); for i in 0..81 { let x = i % 9; let y = i / 9; let transform = Transform::from_translation(Vec3::new(x as f32 * 32.0 + 32., y as f32 * 32.0 + 32., 0.0)); commands .spawn_bundle(SpriteSheetBundle { texture_atlas: texture_atlas_handle.clone(), transform, ..Default::default() }) .insert(TileSpriteData::new(i)); } /* let num_players = p2p_session.map(|s|s.num_players()).expect("No session"); let transform = Transform::from_scale(Vec3::new(0.0, 0.0, 0.0)); for i in 0..num_players { commands .spawn_bundle(SpriteSheetBundle { texture_atlas: texture_atlas_handle.clone(), transform, ..Default::default() }) .insert(Player{handle: i}); } */ let music = asset_server.load("sounds/clack.mp3"); audio_lib.audio_files.insert("clack".to_string(), music); }
use crate::{AsObject, PyObject, VirtualMachine}; pub struct ReprGuard<'vm> { vm: &'vm VirtualMachine, id: usize, } /// A guard to protect repr methods from recursion into itself, impl<'vm> ReprGuard<'vm> { /// Returns None if the guard against 'obj' is still held otherwise returns the guard. The guard /// which is released if dropped. pub fn enter(vm: &'vm VirtualMachine, obj: &PyObject) -> Option<Self> { let mut guards = vm.repr_guards.borrow_mut(); // Should this be a flag on the obj itself? putting it in a global variable for now until it // decided the form of PyObject. https://github.com/RustPython/RustPython/issues/371 let id = obj.get_id(); if guards.contains(&id) { return None; } guards.insert(id); Some(ReprGuard { vm, id }) } } impl<'vm> Drop for ReprGuard<'vm> { fn drop(&mut self) { self.vm.repr_guards.borrow_mut().remove(&self.id); } }
use std::{collections::{HashMap, HashSet}, ops::{Deref, Mul, DerefMut}}; use itertools::Itertools; use ndarray::{arr1, arr2, Array1, Array2}; // FrameIndependentDisplacement is a tuple of 3 values, indcating the difference in positions of 2 coordinates, // the order is not by axes and there are no nergatives to make them frame independent // sorted by size for convention // This map maps the FrameIndependentDisplacement to the surrounding coordinates (not frame independent) type FrameIndependentDisplacementMap = HashMap<(usize, usize, usize), Vec<Array1<i128>>>; fn main() { let input = include_str!("input").split("\r\n\r\n"); let beacons_by_sensor: Vec<_> = input.map(|sensor_block_str| { let mut lines = sensor_block_str.lines(); lines.next(); lines.map(|line| { let mut split = line.split(","); arr1(&[split.next().unwrap().parse().unwrap(), split.next().unwrap().parse().unwrap(), split.next().unwrap().parse().unwrap()]) }).collect() }).collect(); let fids: Vec<_> = beacons_by_sensor.iter().map(|sesnor_set| get_frame_independent_displacements(sesnor_set)).collect(); let mut possible_transformations = HashMap::new(); let mut transformatons = HashMap::new(); fids.into_iter().enumerate().combinations(2).for_each(|mut q| { let (sensor_a_num, sensor_a_fid) = q.pop().unwrap(); let (sensor_b_num, sensor_b_fid) = q.pop().unwrap(); let transformation = get_transform(&sensor_a_fid, &sensor_b_fid); if transformation.is_none() { return; } let transformation = transformation.unwrap(); transformatons.insert((sensor_b_num, sensor_a_num), transformation.get_inverted()); transformatons.insert((sensor_a_num, sensor_b_num), transformation); possible_transformations.entry(sensor_a_num).or_insert(vec![]).push(sensor_b_num); possible_transformations.entry(sensor_b_num).or_insert(vec![]).push(sensor_a_num); }); let mut from_zero_transformation_map = HashMap::new(); from_zero_transformation_map.insert(0, Transformation::get_identity()); let mut current_sensor_list = vec![0]; while from_zero_transformation_map.len() < beacons_by_sensor.len() { let mut new_set = vec![]; for current_sensor in current_sensor_list.into_iter() { let connected = possible_transformations.get(&current_sensor).unwrap(); for next_sensor in connected { if !from_zero_transformation_map.contains_key(next_sensor) { let from_current_to_next = transformatons.get(&(current_sensor, *next_sensor)).unwrap().clone(); let from_zero_to_current = from_zero_transformation_map.get(&current_sensor).unwrap().clone(); let from_zero_to_next = Transformation::combine(from_zero_to_current, from_current_to_next); from_zero_transformation_map.insert(*next_sensor, from_zero_to_next); new_set.push(*next_sensor) } } } current_sensor_list = new_set; } let largest_distance = (0..beacons_by_sensor.len()).combinations(2).map(|a| { let translation_diff = &from_zero_transformation_map.get(&a[0]).unwrap().get_origin_position() - &from_zero_transformation_map.get(&a[1]).unwrap().get_origin_position(); translation_diff.into_iter().map(|x| x.abs()).sum::<i128>() }).max().unwrap(); let beacons_count = beacons_by_sensor.into_iter().enumerate().flat_map(|(i, sensors)| { let transformation = from_zero_transformation_map.get(&i).unwrap().get_inverted(); sensors.into_iter().map(move |s| { transformation.apply_to(s) }) }).collect::<HashSet<_>>().len(); println!("Part one: {}", beacons_count); println!("Part two: {}", largest_distance); } fn get_transform(from_set: &FrameIndependentDisplacementMap, to_set: &FrameIndependentDisplacementMap) -> Option<Transformation> { let overlap: Vec<_> = from_set.keys().filter(|x| to_set.contains_key(x)).collect(); if overlap.len() < 66 { return None; }; let mut shared_sensor_mapping: HashMap<Array1<i128>, Vec<Array1<i128>>> = HashMap::new(); for fid in overlap { let possible_coors_in_from = from_set.get(fid).unwrap(); let possible_coors_in_to = to_set.get(fid).unwrap(); for coor in possible_coors_in_from { let entry = shared_sensor_mapping.entry(coor.clone()).or_insert(possible_coors_in_to.clone()); *entry = entry.iter().filter(|x| possible_coors_in_to.contains(x)).map(|x| x.clone()).collect(); } }; shared_sensor_mapping.iter().for_each(|(_, val)| { if val.len() != 1 { panic!("Invalid mapping found") } }); let shared_sensor_mapping: HashMap<_,_> = shared_sensor_mapping.into_iter().map(|(a,mut b_vec)| (a, b_vec.pop().unwrap())).collect(); let mut rotate = None; for pair in shared_sensor_mapping.keys().combinations(2) { let diff: Array1<i128> = pair[0] - pair[1]; let diff_abs = get_abs_each_axis(&diff); if diff_abs[0] == diff_abs[1] || diff_abs[1] == diff_abs[2] || diff_abs[0] == diff_abs[2] || diff_abs[0] == 0 || diff_abs[1] == 0 || diff_abs[0] == 0 { continue; } rotate = Some(determine_rotate(&diff, &(shared_sensor_mapping.get(pair[0]).unwrap() - shared_sensor_mapping.get(pair[1]).unwrap()) )); break; } let rotate = rotate.unwrap(); let coor = shared_sensor_mapping.keys().next().unwrap(); let rotated_coor = rotate.apply_to(coor); let translation = shared_sensor_mapping.get(coor).unwrap() - rotated_coor; Some(Transformation { rotate, translation }) } fn determine_rotate(inital: &Array1<i128>, target: &Array1<i128>) -> Rotate { Rotate(arr2( &[ determine_rotation_matrix_row(target[0], inital), determine_rotation_matrix_row(target[1], inital), determine_rotation_matrix_row(target[2], inital) ] )) } fn determine_rotation_matrix_row(val: i128, coor: &Array1<i128>) -> [i128; 3] { let mut element = coor.iter().map(|&x| { if val == x { 1 } else if val == -1 * x { -1 } else { 0 } }); [element.next().unwrap(), element.next().unwrap(), element.next().unwrap()] } #[derive(Clone)] struct Transformation { rotate: Rotate, translation: Array1<i128> } impl Transformation { fn apply_to(&self, vec: Array1<i128>) -> Array1<i128> { let rotated = self.rotate.apply_to(&vec); rotated + &self.translation } fn get_inverted(&self) -> Self { let inverted_rotation = self.rotate.get_inverted(); let rotated_shift = inverted_rotation.apply_to(&self.translation); let new_shift = [- rotated_shift[0], - rotated_shift[1], - rotated_shift[2]]; Self { rotate: inverted_rotation, translation: arr1(&new_shift) } } fn get_identity() -> Self { Self { rotate: Rotate(arr2(&[ [1, 0, 0], [0, 1, 0], [0, 0, 1] ])), translation: arr1(&[0, 0, 0]) } } fn combine(first: Transformation, second: Transformation) -> Self { let rotate = second.rotate.clone() * first.rotate; let translation = second.rotate.apply_to(&first.translation) + second.translation; Self { rotate, translation } } fn get_origin_position(&self) -> Array1<i128> { self.rotate.get_inverted().apply_to(&self.translation) } } impl Mul for Transformation { type Output = Self; fn mul(self, rhs: Self) -> Self { let rotate = self.rotate * rhs.rotate.clone(); let translation = rhs.rotate.apply_to(&self.translation) + rhs.translation; Self { rotate, translation } } } #[derive(Clone, Hash, Debug)] struct Rotate(Array2<i128>); impl Rotate { fn apply_to(&self, vec: &Array1<i128>) -> Array1<i128> { self.dot(vec) } fn get_inverted(&self) -> Self { let mut cl = self.clone(); cl.swap_axes(0, 1); cl } } impl Deref for Rotate { type Target = Array2<i128>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Rotate { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl Mul for Rotate { type Output = Self; fn mul(self, rhs: Self) -> Self { Self(self.dot(&rhs.0)) } } fn get_frame_independent_displacements (set: &Vec<Array1<i128>>) -> FrameIndependentDisplacementMap { set.iter().combinations(2).map(|coors| { let mut a = vec![(coors[0][0] - coors[1][0]).abs() as usize, (coors[0][1] - coors[1][1]).abs() as usize, (coors[0][2] - coors[1][2]).abs() as usize]; a.sort(); ((a[0], a[1], a[2]), vec![coors[0].clone(), coors[1].clone()]) }).collect() } fn get_abs_each_axis(arr: &Array1<i128>) -> Array1<usize> { arr1(&[arr[0].abs() as usize, arr[1].abs() as usize, arr[2].abs() as usize]) }
use std::collections::HashMap; use shader::{Shader, ShaderSource}; use asset_mgr::AssetMgr; use gl; pub struct ShaderMgr { shaders: HashMap<&'static str, Shader> } impl ShaderMgr { pub fn new() -> ShaderMgr { ShaderMgr { shaders: HashMap::new() } } pub fn load_default_shaders(&mut self, asset_mgr: &mut AssetMgr) { self.add("sprite", &*asset_mgr.get(&Path::new("data/shaders/sprite.vs")).unwrap(), &*asset_mgr.get(&Path::new("data/shaders/sprite.fs")).unwrap()) } pub fn add(&mut self, name: &'static str, vertex_source: &ShaderSource, fragment_source: &ShaderSource) { match self.shaders.find(&name) { None => (), Some(_) => return } self.shaders.insert(name, Shader::new(vertex_source, fragment_source)); } pub fn use_shader(&self, name: &'static str) { if name == "" { gl::UseProgram(0); } match self.shaders.find(&name) { None => fail!("Could not find shader \"{}\"", name), Some(shader) => shader.use_program() } } }
use std::fs; use std::sync::Arc; use urlencoding::decode; use crate::path_utils::{get_path, is_filepath}; use crate::request::{Request, RequestHandler, ResponseResult}; use crate::{multipart, Opts, Response}; use std::path::PathBuf; pub struct Patch; impl RequestHandler for Patch { fn get_response<'a>(req: &'a Request<'a>, opts: Arc<Opts>) -> ResponseResult { if req.body.is_none() { return Ok(Response::error(400, Some("Missing request body"))); } let save_path = get_path( opts.directory.as_str(), decode(req.status_line.uri).unwrap().as_str(), ); let is_filepath = is_filepath(&save_path); let content_type = Request::parse_complex_header(req.headers.get("Content-Type").unwrap_or(&"")); let mut file_paths = Vec::new(); if content_type.value == "multipart/form-data" { let files = multipart::parse(req, &content_type)?; if is_filepath && files.len() > 1 { return Ok(Response::error( 400, Some( format!( "Path <code>{}</code> cannot be a filename", save_path.to_str().unwrap() ) .as_str(), ), )); } if !save_path.exists() { let requested_path = req.status_line.uri.parse::<PathBuf>()?; let rel_path = requested_path.parent().unwrap(); return Ok(Response::error( 404, Some( format!( "Directory <code>{}</code> does not exist", rel_path.to_str().unwrap() ) .as_str(), ), )); } for file in files { let rel_path = get_path( req.status_line .uri .strip_prefix("/") .unwrap_or(req.status_line.uri), file.name.as_str(), ); let file_path = save_path.join(file.name); if file_path.exists() { fs::write(file_path, file.body)?; } else { return Ok(Response::error( 404, Some( format!( "File <code>{}</code> does not exist", rel_path.to_str().unwrap() ) .as_str(), ), )); } file_paths.push(rel_path); } } else { let req_path = req .status_line .uri .strip_prefix("/") .unwrap_or(req.status_line.uri); if !is_filepath { return Ok(Response::error( 400, Some( format!( "Path <code>{}</code> is not a filename", save_path.to_str().unwrap() ) .as_str(), ), )); } let rel_path = req_path.parse().unwrap(); fs::write(save_path, req.body.unwrap())?; file_paths.push(rel_path); } let host = get_host(req, opts); let links: Vec<String> = file_paths .into_iter() .map(|name| format!("http://{}/{}", host, name.to_str().unwrap())) .collect(); Ok(Response::ok( 201, req.status_line.uri.parse()?, (links.join("\n") + "\n").as_bytes().to_vec(), )) } } fn get_host(req: &Request, opts: Arc<Opts>) -> String { req.headers.get("Host").map_or_else( || format!("{}:{}", opts.host, opts.port), |&host| host.to_string(), ) }
use crate::types::{HitRecord, Hitable, Ray}; pub struct HitableList { pub list: Vec<Box<dyn Hitable>>, } impl Hitable for HitableList { fn hit(&self, ray: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> { let mut closest_so_far = t_max; let mut hit_rec: Option<HitRecord> = None; for obj in &self.list { if let Some(l_hit_rec) = obj.hit(ray, t_min, closest_so_far) { closest_so_far = l_hit_rec.t; hit_rec = Some(l_hit_rec); } } hit_rec } } impl HitableList { pub fn push(&mut self, obj: Box<dyn Hitable>) { self.list.push(obj); } }
extern crate pest; #[macro_use] extern crate pest_derive; extern crate serde; pub use parser::parse; pub mod ast; pub mod validator; pub mod parser; pub mod errors; pub mod support;
use hitable::HitRecord; use rand::random; use ray::Ray; use sphere; use vec3::{dot, unit_vector, Vec3}; pub trait Material: MaterialClone { fn scatter( &self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool; } // this is coming from the examples provided here: // https://stackoverflow.com/questions/30353462/how-to-clone-a-struct-storing-a-boxed-trait-object // -- without this I had no way to of properly assigning the hitrecord's material to the ray object // -- as it was always already in a borrowed state and couldn't be moved again. So I needed a way // -- to copy/clone the material. pub trait MaterialClone { fn clone_box(&self) -> Box<dyn Material>; } impl<T> MaterialClone for T where T: 'static + Material + Clone, { fn clone_box(&self) -> Box<dyn Material> { Box::new(self.clone()) } } impl Clone for Box<dyn Material> { fn clone(&self) -> Box<dyn Material> { self.clone_box() } } #[derive(Copy, Clone, Debug)] pub struct Lambertian { pub albedo: Vec3, } impl Lambertian { pub fn new(r: f32, g: f32, b: f32) -> Box<Lambertian> { Box::new(Lambertian { albedo: Vec3 { e: [r, g, b] }, }) } } impl Material for Lambertian { fn scatter( &self, _r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool { let target = rec.p + rec.normal + sphere::random_in_unit_sphere(); *scattered = Ray::new(rec.p, target - rec.p); *attenuation = self.albedo; true } } #[derive(Copy, Clone, Debug)] pub struct Metal { pub albedo: Vec3, pub fuzz: f32, } impl Metal { pub fn new(r: f32, g: f32, b: f32, fuzz: f32) -> Box<Metal> { let fuzziness = if fuzz > 1.0 { 1.0 } else { fuzz }; Box::new(Metal { albedo: Vec3 { e: [r, g, b] }, fuzz: fuzziness, }) } fn reflect(v: &Vec3, n: &Vec3) -> Vec3 { *v - *n * (2.0 * dot(v, n)) } } impl Material for Metal { fn scatter( &self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool { let reflected = Metal::reflect(&unit_vector(*r_in.direction()), &rec.normal); *scattered = Ray::new( rec.p, reflected + sphere::random_in_unit_sphere() * self.fuzz, ); *attenuation = self.albedo; dot(scattered.direction(), &rec.normal) > 0.0 } } #[derive(Copy, Clone, Debug)] pub struct Dielectric { pub refraction_index: f32, } impl Dielectric { pub fn new(refraction_index: f32) -> Box<Dielectric> { Box::new(Dielectric { refraction_index }) } fn reflect(v: &Vec3, n: &Vec3) -> Vec3 { *v - *n * (2.0 * dot(v, n)) } fn refract(v: &Vec3, n: &Vec3, ni_over_nt: f32, refracted: &mut Vec3) -> bool { let uv = unit_vector(*v); let dt = dot(&uv, n); let discriminant = 1.0 - ni_over_nt * ni_over_nt * (1.0 - dt * dt); if discriminant > 0.0 { *refracted = (uv - *n * dt) * ni_over_nt - *n * discriminant.sqrt(); true } else { false } } fn schlick(cosine: f32, refraction_index: f32) -> f32 { let mut r0 = (1.0 - refraction_index) / (1.0 + refraction_index); r0 = r0 * r0; r0 + (1.0 - r0) * (1.0 - cosine).powf(5.0) } } impl Material for Dielectric { fn scatter( &self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Vec3, scattered: &mut Ray, ) -> bool { // setup some temp vars let outward_normal; let reflected = Dielectric::reflect(r_in.direction(), &rec.normal); let ni_over_nt; *attenuation = Vec3 { e: [1.0, 1.0, 1.0] }; let refracted = &mut Vec3::new(); let reflect_probability; let cosine = if dot(r_in.direction(), &rec.normal) > 0.0 { outward_normal = rec.normal * -1.0; ni_over_nt = self.refraction_index; self.refraction_index * dot(r_in.direction(), &rec.normal) / (r_in.direction().length()) } else { outward_normal = rec.normal; ni_over_nt = 1.0 / self.refraction_index; dot(r_in.direction(), &rec.normal) * -1.0 / (r_in.direction().length()) }; if Dielectric::refract(r_in.direction(), &outward_normal, ni_over_nt, refracted) { reflect_probability = Dielectric::schlick(cosine, self.refraction_index); //println!("Yes."); } else { reflect_probability = 1.0; } if random::<f32>() < reflect_probability { *scattered = Ray::new(rec.p, reflected.clone()); } else { *scattered = Ray::new(rec.p, refracted.clone()); } true } }
use anyhow::{bail, Result}; use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation}; use serde::Deserialize; use tracing::info; use crate::authoriser::jwk; #[derive(Debug, Deserialize)] pub struct Claims { #[serde(rename = "cognito:username")] pub username: String, } pub async fn verify_claims(token: &str) -> Result<Claims> { let keys = jwk::keys().await?; let header = decode_header(token)?; let kid = match header.kid { Some(k) => k, None => bail!("token header has no kid"), }; let key = match keys.iter().find(|&k| k.kid == kid) { Some(key) => key, None => bail!("none of the keys match token kid"), }; info!("found appropriate key: {:?}", key); let token_data = decode::<Claims>( token, &DecodingKey::from_rsa_components(&key.n, &key.e), &Validation::new(Algorithm::RS256), )?; Ok(token_data.claims) }
#[cfg(target_os = "linux")] static DRIVERFILELOCATION: &str = "/dev/input/by-path/platform-i8042-serio-0-event-kbd"; use std::fs::File; use std::io::{Read}; use libc::time_t; use libc::suseconds_t; // Representation of the kbd event struct in C on linux #[derive(Debug)] #[repr(C)] struct InputEvent { tv_sec: time_t, tv_usec: suseconds_t, pub type_: u16, pub code: u16, pub value: i32 } // Contains a callback set // by the user and the character code the input system will trigger on struct Listener<'a>{ cb_function: &'a dyn Fn(), seeked_char: u8 } // This is pub struct InputSystem<'a> { driver_file: std::fs::File, listeners: Vec<Listener<'a>>, } impl InputSystem<'_> { pub fn new() -> Result<Self, &'static str> { root_check(); let ret = File::open(DRIVERFILELOCATION); let file = match ret { Ok(opened_file) => opened_file, Err(_err_code) => return Err("could not open specified driver file"), }; let default: InputSystem = InputSystem{ driver_file: file, listeners: Vec::new() }; Ok(default) } fn read_event(&mut self) -> Result<InputEvent, ()> { let mut buf = [0u8; std::mem::size_of::<InputEvent>()]; let ret: usize = self.driver_file.read(&mut buf).unwrap(); if ret != std::mem::size_of::<InputEvent>() { panic!("Error while reading from device file"); } let return_packet: InputEvent = unsafe {std::mem::transmute(buf)}; Ok(return_packet) } pub fn read_key(&mut self) -> Option<u8> { let ev = self.read_event().unwrap(); if ev.value == 1 || ev.value == 2 { for i in &self.listeners { if i.seeked_char == ev.code as u8 { (i.cb_function)(); } } return Some(ev.code as u8); } else { return None; } } pub fn attach_listener(&mut self, key_code: u8, callback: &'static dyn Fn()) { let ret = Listener{cb_function: callback, seeked_char: key_code}; self.listeners.push(ret); } } fn root_check() { unsafe { if libc::geteuid() != 0 { panic!("Must run as root user"); } } }
use std::time::Duration; use crate::{ RotatorEvent, RotatorResult, }; use crate::value::get_secret_value; pub fn set_secret(e: RotatorEvent) -> RotatorResult<()> { let timeout = Duration::from_secs(2); let _value = match get_secret_value(&e.secret_id, Some("AWSPENDING"), Some(&e.client_request_token), timeout) { Ok(value) => { info!("setSecret: Successfully retrieved secret for {}.", e.secret_id); Ok(value) }, Err(err) => { error!("setSecret: Error retrieving secret for ARN {} and version {}: {:?}.", e.secret_id, e.client_request_token, err); Err(err) } }?; // todo: set secret on resource Ok(()) }
use decisionengine::datasource::DecisionDataset; use decisionengine::modules::PassAllModule; use decisionengine::results::ModuleResult; use decisionengine::results::RuleResult; use decisionengine::results::SubmoduleResult; use decisionengine::rules::Condition; use decisionengine::rules::Rule; use decisionengine::EvalResult; use decisionengine::Evaluatable; use std; pub trait DecisionTreeVisitor { fn visit_pass_all_module(&mut self, module: &mut PassAllModule); fn visit_rule(&mut self, rule: &mut Rule); fn leave_pass_all_module(&mut self, module: &mut PassAllModule); fn leave_rule(&mut self, rule: &mut Rule); fn visit_condition(&mut self, condition: &Condition); } pub struct ResultAggregatingVisitor { pub stack: ResultStack, pub input: DecisionDataset, } pub struct ResultStack { curr: Option<Box<ResultStackElement>>, } struct ResultStackElement { value: SubmoduleResult, prev: Option<Box<ResultStackElement>>, } impl ResultStackElement { pub fn value(&mut self) -> &mut SubmoduleResult { &mut self.value } } impl ResultStack { pub fn get_result(&self) -> &SubmoduleResult { &self.curr.as_ref().unwrap().value } pub fn new(init: SubmoduleResult) -> Self { ResultStack { curr: Some(Box::from(ResultStackElement { value: init, prev: None, })), } } pub fn new_module(&mut self, module_id: String, result: EvalResult) { let mut top = ResultStackElement { value: SubmoduleResult::ModuleResult(ModuleResult { module_id: module_id, result: result, submodule_results: Vec::new(), }), prev: None, }; std::mem::swap(&mut top.prev, &mut self.curr); self.curr = Some(Box::from(top)); } pub fn end_module(&mut self) { if self.curr.is_none() { panic!("End module"); } let curr = std::mem::replace(&mut self.curr, None); let ResultStackElement { mut prev, value } = *curr.unwrap(); match prev.as_mut().unwrap().value() { SubmoduleResult::ModuleResult(ref mut res) => { res.add_submodule_result(value); } _ => {} } std::mem::replace(&mut self.curr, prev); } pub fn last_mut(&mut self) -> &mut SubmoduleResult { &mut self.curr.as_mut().unwrap().value } } impl DecisionTreeVisitor for ResultAggregatingVisitor { fn visit_pass_all_module(&mut self, module: &mut PassAllModule) { self.stack .new_module(module.module_name.clone(), module.eval(&mut self.input)); } fn leave_pass_all_module(&mut self, _module: &mut PassAllModule) { self.stack.end_module(); } fn visit_rule(&mut self, rule: &mut Rule) { match self.stack.last_mut() { SubmoduleResult::ModuleResult(ref mut res) => { res.add_submodule_result(SubmoduleResult::RuleResult(RuleResult { rule_id: rule.rule_id, result: rule.eval(&mut self.input), })); } _ => panic!("Something went wrong during visiting rule"), } } fn leave_rule(&mut self, _rule: &mut Rule) {} fn visit_condition(&mut self, _condition: &Condition) { unimplemented!(); } }
mod de; mod ser; pub use self::de::Deserializer; pub use self::ser::Serializer; use serde_base::de::{Deserialize, DeserializeOwned}; use serde_base::ser::Serialize; use std::io::{Read, Seek, Write}; use Result; use EventReader; use xml; pub fn deserialize<R: Read + Seek, T: DeserializeOwned>(reader: R) -> Result<T> { let reader = EventReader::new(reader); let mut de = Deserializer::new(reader); Deserialize::deserialize(&mut de) } pub fn serialize_to_xml<W: Write, T: Serialize>(writer: W, value: &T) -> Result<()> { let writer = xml::EventWriter::new(writer); let mut ser = Serializer::new(writer); value.serialize(&mut ser) }
// 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::alloc::Layout; use std::fmt; use std::sync::Arc; use common_arrow::arrow::bitmap::Bitmap; use common_exception::Result; use common_expression::types::DataType; use common_expression::utils::column_merge_validity; use common_expression::Column; use common_expression::ColumnBuilder; use common_io::prelude::BinaryWrite; use crate::aggregates::AggregateFunction; use crate::aggregates::AggregateFunctionRef; use crate::aggregates::StateAddr; #[derive(Clone)] pub struct AggregateNullVariadicAdaptor<const NULLABLE_RESULT: bool> { nested: AggregateFunctionRef, size_of_data: usize, } impl<const NULLABLE_RESULT: bool> AggregateNullVariadicAdaptor<NULLABLE_RESULT> { pub fn create(nested: AggregateFunctionRef) -> AggregateFunctionRef { let size_of_data = if NULLABLE_RESULT { let layout = nested.state_layout(); layout.size() } else { 0 }; Arc::new(Self { nested, size_of_data, }) } #[inline] pub fn set_flag(&self, place: StateAddr, flag: u8) { if NULLABLE_RESULT { let c = place.next(self.size_of_data).get::<u8>(); *c = flag; } } #[inline] pub fn init_flag(&self, place: StateAddr) { if NULLABLE_RESULT { let c = place.next(self.size_of_data).get::<u8>(); *c = 0; } } #[inline] pub fn get_flag(&self, place: StateAddr) -> u8 { if NULLABLE_RESULT { let c = place.next(self.size_of_data).get::<u8>(); *c } else { 1 } } } impl<const NULLABLE_RESULT: bool> AggregateFunction for AggregateNullVariadicAdaptor<NULLABLE_RESULT> { fn name(&self) -> &str { "AggregateNullVariadicAdaptor" } fn return_type(&self) -> Result<DataType> { let nested = self.nested.return_type()?; match NULLABLE_RESULT { true => Ok(nested.wrap_nullable()), false => Ok(nested), } } fn init_state(&self, place: StateAddr) { self.init_flag(place); self.nested.init_state(place); } #[inline] fn state_layout(&self) -> Layout { let layout = self.nested.state_layout(); let add = if NULLABLE_RESULT { layout.align() } else { 0 }; Layout::from_size_align(layout.size() + add, layout.align()).unwrap() } #[inline] fn accumulate( &self, place: StateAddr, columns: &[Column], validity: Option<&Bitmap>, input_rows: usize, ) -> Result<()> { let mut not_null_columns = Vec::with_capacity(columns.len()); let mut validity = validity.cloned(); for col in columns.iter() { validity = column_merge_validity(col, validity); not_null_columns.push(col.remove_nullable()); } self.nested .accumulate(place, &not_null_columns, validity.as_ref(), input_rows)?; if validity .as_ref() .map(|c| c.unset_bits() != input_rows) .unwrap_or(true) { self.set_flag(place, 1); } Ok(()) } fn accumulate_keys( &self, places: &[StateAddr], offset: usize, columns: &[Column], input_rows: usize, ) -> Result<()> { let mut not_null_columns = Vec::with_capacity(columns.len()); let mut validity = None; for col in columns.iter() { validity = column_merge_validity(col, validity); not_null_columns.push(col.remove_nullable()); } match validity { Some(v) if v.unset_bits() > 0 => { // all nulls if v.unset_bits() == v.len() { return Ok(()); } for (valid, (row, place)) in v.iter().zip(places.iter().enumerate()) { if valid { self.set_flag(place.next(offset), 1); self.nested .accumulate_row(place.next(offset), &not_null_columns, row)?; } } } _ => { self.nested .accumulate_keys(places, offset, &not_null_columns, input_rows)?; places .iter() .for_each(|place| self.set_flag(place.next(offset), 1)); } } Ok(()) } fn accumulate_row(&self, _place: StateAddr, _columns: &[Column], _row: usize) -> Result<()> { unreachable!() } fn serialize(&self, place: StateAddr, writer: &mut Vec<u8>) -> Result<()> { self.nested.serialize(place, writer)?; if NULLABLE_RESULT { let flag: u8 = self.get_flag(place); writer.write_scalar(&flag)?; } Ok(()) } fn deserialize(&self, place: StateAddr, reader: &mut &[u8]) -> Result<()> { if NULLABLE_RESULT { let flag = reader[reader.len() - 1]; self.nested .deserialize(place, &mut &reader[..reader.len() - 1])?; self.set_flag(place, flag); } else { self.nested.deserialize(place, reader)?; } Ok(()) } fn merge(&self, place: StateAddr, rhs: StateAddr) -> Result<()> { if self.get_flag(place) == 0 { // initial the state to remove the dirty stats self.init_state(place); } if self.get_flag(rhs) == 1 { self.set_flag(place, 1); self.nested.merge(place, rhs)?; } Ok(()) } fn merge_result(&self, place: StateAddr, builder: &mut ColumnBuilder) -> Result<()> { if NULLABLE_RESULT { if self.get_flag(place) == 1 { match builder { ColumnBuilder::Nullable(ref mut inner) => { self.nested.merge_result(place, &mut inner.builder)?; inner.validity.push(true); } _ => unreachable!(), } } else { builder.push_default(); } Ok(()) } else { self.nested.merge_result(place, builder) } } fn need_manual_drop_state(&self) -> bool { self.nested.need_manual_drop_state() } unsafe fn drop_state(&self, place: StateAddr) { self.nested.drop_state(place) } fn convert_const_to_full(&self) -> bool { self.nested.convert_const_to_full() } fn get_if_condition(&self, columns: &[Column]) -> Option<Bitmap> { self.nested.get_if_condition(columns) } } impl<const NULLABLE_RESULT: bool> fmt::Display for AggregateNullVariadicAdaptor<NULLABLE_RESULT> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "AggregateNullVariadicAdaptor") } }
#[macro_use] extern crate mysql; extern crate time; // ... use museus::mysql::MyDatabase; use museus::LladreDAO; use museus::Visitant; use std::collections::HashSet; use std::iter::FromIterator; mod museus; fn main() { let db = MyDatabase::connecta( String::from("172.99.0.2"), "lladres".to_string(), "root".to_string(), "ies2010".to_string(), ).unwrap(); let denuncies = db.obtenir_denuncies(); let mut repetits: HashSet<Visitant> = HashSet::new(); let mut comptador = 0; for denuncia in denuncies { let noves = db.obtenir_visites(denuncia.museu_id, denuncia.hora); // println!("------------------"); // println!("{} - {}", denuncia.museu_id, denuncia.museu_nom); // println!("------------------"); // println!("{:?}", noves); let nous_visitants = genera_hashset(&noves); if comptador == 0 { repetits = nous_visitants; } else { repetits = interseccio(&repetits, &nous_visitants); } comptador += 1; } println!("Sospitosos"); println!("----------------"); for repetit in repetits.iter() { println!("{}", repetit.visitant_nom); } } fn interseccio(repes: &HashSet<Visitant>, nous: &HashSet<Visitant>) -> HashSet<Visitant> { let resultat = repes.intersection(nous).collect::<HashSet<&Visitant>>(); referencies_to_value(&resultat) } fn referencies_to_value(nous: &HashSet<&Visitant>) -> HashSet<Visitant> { let mut resultat: HashSet<Visitant> = HashSet::new(); for nou in nous.iter() { resultat.insert(Visitant { visitant_id: nou.visitant_id.clone(), visitant_nom: nou.visitant_nom.clone(), }); } resultat } fn genera_hashset(data: &[Visitant]) -> HashSet<Visitant> { HashSet::from_iter(data.iter().cloned()) }
use crate::context::UpstreamContext; use crate::fifo::{AsyncConsumer, AsyncFifo, AsyncProducer}; use crate::handler::{Handler, Sink}; use crate::interrupt::Interruptable; use core::cell::{RefCell, UnsafeCell}; use heapless::consts::*; pub use drogue_async::task::spawn; /// A non-root, but possibly leaf (or middle) portion of the component tree. /// /// Each `Component` may have `::InboundMessage` and `::OutboundMessage` types /// for communication with whichever `Component` or `Kernel` is _upstream_ from /// itself. Typically these types will be `enum`s, and may be `()` if no applicable /// message exists. All messages are considered in relation to it's parent, regardless /// of its children (if any), which are separately dealt with using `Handler<M>` /// trait implementations. pub trait Component: Sized { /// The type of message expected from its parent. type InboundMessage; /// The type of message sent to its parent. type OutboundMessage; /// Start this component and any children. /// /// Each child should be started in an application-appropriate order /// passing the `ctx` down the tree. /// /// `spawn(...)` may be used to initiate asynchronous tasks (generally loops) /// and `ctx.receive().await` may be used to asynchronously receive /// messages of `::InboundMessage` type using futures. fn start(&'static mut self, ctx: &'static ComponentContext<Self>); } /// Context provided to the component upon `start(...)`. pub struct ComponentContext<C: Component> where C: 'static, { component: &'static ConnectedComponent<C>, consumer: UnsafeCell<AsyncConsumer<'static, C::InboundMessage, U32>>, upstream: &'static dyn UpstreamContext<C::OutboundMessage>, } impl<C: Component> ComponentContext<C> { fn new( component: &'static ConnectedComponent<C>, consumer: AsyncConsumer<'static, C::InboundMessage, U32>, upstream: &'static dyn UpstreamContext<C::OutboundMessage>, ) -> Self { Self { component, consumer: UnsafeCell::new(consumer), upstream, } } /// Send a message, *synchronously*, upstream to the containing /// parent `Component` or `Kernel`, which *must* implement /// `Handler<C::OutboundMessage>` to be able to accomodate /// messages from this child. /// /// This method is immediate and synchronous, avoiding any /// FIFOs. By the time it returns, the parent's associated /// `Handler<M>` will have been called and fulled executed. /// /// The component is *not* directly linked to the outbound /// messages, so if differentiation between components that /// can produce similar messages is required, a discriminant /// (possibly using a `PhantomData` field) may be required. pub fn send(&self, message: C::OutboundMessage) { self.upstream.send(message) } /// Receive a message, *asynchronously*, from the upstream /// `Component` or `Kernel` of type `C::InboundMessage`. pub async fn receive(&'static self) -> C::InboundMessage { unsafe { (&mut *self.consumer.get()).dequeue().await } } } impl<C: Component> Sink<C::OutboundMessage> for ComponentContext<C> { fn send(&self, message: C::OutboundMessage) { self.upstream.send(message); } } /// Wrapper for a `Component` to be held by the `Kernel` /// or `Component` parent of this component. Components /// shall not be held directly, but only through a `ConnectedComponent<C>` /// which handles message routing and asynchronous FIFO configuration. pub struct ConnectedComponent<C: Component> where C: 'static, { component: UnsafeCell<C>, context: UnsafeCell<Option<ComponentContext<C>>>, fifo: UnsafeCell<AsyncFifo<C, U32>>, producer: RefCell<Option<AsyncProducer<'static, C::InboundMessage, U32>>>, } impl<C: Component> ConnectedComponent<C> { /// Create a new wrapped `ConnectedComponent<C>` from a `Component`. pub fn new(component: C) -> Self { Self { component: UnsafeCell::new(component), context: UnsafeCell::new(None), fifo: UnsafeCell::new(AsyncFifo::new()), producer: RefCell::new(None), } } /// Start this component and it's associated asynchronous FIFO. /// /// This method should be invoked with the `ctx` passed to it's /// parent's own `start(...)` method. pub fn start(&'static self, upstream: &'static dyn UpstreamContext<C::OutboundMessage>) { let (producer, consumer) = unsafe { &mut *self.fifo.get() }.split(); self.producer.borrow_mut().replace(producer); let context = ComponentContext::new(&self, consumer, upstream); unsafe { (&mut *self.context.get()).replace(context); (&mut *self.component.get()).start((&*self.context.get()).as_ref().unwrap()); } } /// Send a message of type `::InboundMessag` to the contained component. /// /// This method should be used only by the directly-owneding parent of /// the wrapped component. /// /// TODO: There is currently no policy regarding full FIFOs and messages will simply be dropped. pub fn send(&self, message: C::InboundMessage) { // TODO: critical section/lock self.producer .borrow_mut() .as_mut() .unwrap() .enqueue(message) } } impl<C: Component> Sink<C::InboundMessage> for ConnectedComponent<C> { fn send(&self, message: <C as Component>::InboundMessage) { self.producer .borrow_mut() .as_mut() .unwrap() .enqueue(message) } } impl<M, C: Component> UpstreamContext<M> for ComponentContext<C> where C: Handler<M>, { fn send(&self, message: M) { unsafe { &mut *self.component.component.get() }.on_message(message) } fn register_irq(&self, irq: u8, interrupt: &'static dyn Interruptable) { self.upstream.register_irq(irq, interrupt) } }
extern crate reactive_net; mod __authentic_execution; pub mod __run; #[allow(unused_imports)] use __authentic_execution::authentic_execution; #[allow(unused_imports)] use __authentic_execution::authentic_execution::{MODULE_NAME, success, failure, handle_output, handle_request, Error}; #[allow(unused_imports)] use reactive_net::{ResultCode, ResultMessage};
// Copyright 2021 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. #![deny(unused_crate_dependencies)] #![allow(clippy::uninlined_format_args)] mod git; use std::env; use std::path::Path; use gix::Repository; use tracing::error; use vergen::EmitBuilder; /// Setup building environment: /// - Watch git HEAD to trigger a rebuild; /// - Generate vergen instruction to setup environment variables for building databend components. See: https://docs.rs/vergen/5.1.8/vergen/ ; /// - Generate databend environment variables, e.g., authors. pub fn setup() { if Path::new(".git/HEAD").exists() { println!("cargo:rerun-if-changed=.git/HEAD"); } add_building_env_vars(); } pub fn setup_commit_authors() { match gix::discover(".") { Ok(repo) => { add_env_commit_authors(&repo); } Err(e) => { eprintln!("{}", e); println!("cargo:rustc-env=DATABEND_COMMIT_AUTHORS=unknown"); } }; } pub fn add_building_env_vars() { set_env_config(); add_env_credits_info(); add_target_features(); match gix::discover(".") { Ok(repo) => { add_env_git_tag(&repo); } Err(e) => { panic!( "{}; The MetaClient is unable to proceed as it relies on the git-tag version for handshaking, which is not found.", e ); } }; } pub fn set_env_config() { EmitBuilder::builder() .all_build() .all_cargo() .all_git() .all_rustc() .emit() .expect("Unable to generate build envs"); } pub fn add_env_git_tag(repo: &Repository) { match git::get_latest_tag(repo) { Ok(tag) => println!("cargo:rustc-env=DATABEND_GIT_SEMVER={}", tag), Err(e) => println!("cargo:rustc-env=DATABEND_GIT_SEMVER={}", e), } } pub fn add_env_commit_authors(repo: &Repository) { match git::get_commit_authors(repo) { Ok(authors) => println!("cargo:rustc-env=DATABEND_COMMIT_AUTHORS={}", authors), Err(e) => println!("cargo:rustc-env=DATABEND_COMMIT_AUTHORS={}", e), } } pub fn add_env_credits_info() { let metadata_command = cargo_metadata::MetadataCommand::new(); let opt = cargo_license::GetDependenciesOpt { avoid_dev_deps: false, avoid_build_deps: false, direct_deps_only: false, root_only: false, }; let deps = match cargo_license::get_dependencies_from_cargo_lock(metadata_command, opt) { Ok(v) => v, Err(err) => { error!("{:?}", err); vec![] } }; let names: Vec<String> = deps.iter().map(|x| (x.name).to_string()).collect(); let versions: Vec<String> = deps.iter().map(|x| x.version.to_string()).collect(); let licenses: Vec<String> = deps .iter() .map(|x| match &x.license { None => "UNKNOWN".to_string(), Some(license) => license.to_string(), }) .collect(); println!( "cargo:rustc-env=DATABEND_CREDITS_NAMES={}", names.join(", ") ); println!( "cargo:rustc-env=DATABEND_CREDITS_VERSIONS={}", versions.join(", ") ); println!( "cargo:rustc-env=DATABEND_CREDITS_LICENSES={}", licenses.join(", ") ); } pub fn add_target_features() { match env::var_os("CARGO_CFG_TARGET_FEATURE") { Some(var) => match var.into_string() { Ok(s) => println!("cargo:rustc-env=DATABEND_CARGO_CFG_TARGET_FEATURE={}", s), Err(_) => { println!("cargo:warning=CARGO_CFG_TARGET_FEATURE was not valid utf-8"); } }, None => { println!("cargo:warning=CARGO_CFG_TARGET_FEATURE was not set"); } }; }
use reqwest; use std::env; async fn get(symbols: &str) -> Result<String, reqwest::Error> { let mut url = String::from("http://sqt.gtimg.cn/utf8/q="); url.push_str(symbols); url.push_str("&offset=3,2,4,33,39,60,40,46,1"); Ok(reqwest::get(url.as_str()).await?.text().await?) } #[tokio::main] async fn main() { let args: Vec<String> = env::args().collect(); if let Ok(resp) = get(args[1].as_str()).await { let mut wants = Vec::new(); let fld_name: Vec<&str> = vec![ "ticker", "name", "price", "chg%", "tn%", "tn2%", "pe", "mv", "x", ]; wants.push(fld_name); let rows: Vec<&str> = resp.split(';').collect(); for v in rows.iter() { let r: Vec<&str> = v.split('"').collect(); if r[0].len() > 4 { println!("{}", r[1]); let mut row: Vec<&str> = r[1].split('~').collect(); match row[8] { "100" => row[4] = row[5], "1" | "51" | "200" => (), _ => (), } wants.push(row); } } for w in wants.iter() { let s = format!( "{:<12}{:<12}{:<12}{:<12}{:<-12}{:<12}{:<12}", w[0], w[2], w[3], w[4], w[6], w[7], w[1] ); println!("\n{}", s); } } }
use openexr_sys as sys; pub use crate::core::{ error::Error, frame_buffer::{Frame, Slice, SliceRef}, refptr::{OpaquePtr, Ref, RefMut}, PixelType, }; pub use imath_traits::{Bound2, Vec2}; use std::marker::PhantomData; use std::ffi::{CStr, CString}; type Result<T, E = Error> = std::result::Result<T, E>; pub struct DeepFrameBuffer { pub(crate) ptr: *mut sys::Imf_DeepFrameBuffer_t, pub(crate) sample_count_frame: Option<Frame>, } unsafe impl OpaquePtr for DeepFrameBuffer { type SysPointee = sys::Imf_DeepFrameBuffer_t; type Pointee = DeepFrameBuffer; } pub type DeepFrameBufferRef<'a> = Ref<'a, DeepFrameBuffer>; impl DeepFrameBuffer { /// Create a new `DeepFrameBuffer`. pub fn new() -> DeepFrameBuffer { let mut ptr = std::ptr::null_mut(); unsafe { sys::Imf_DeepFrameBuffer_ctor(&mut ptr); } DeepFrameBuffer { ptr, sample_count_frame: None, } } /// Insert a [`DeepSlice`] into the `DeepFrameBuffer`. /// /// # Errors /// * [`Error::InvalidArgument`] - if name is the empty string /// pub fn insert(&mut self, name: &str, slice: &DeepSlice) -> Result<()> { let c_name = CString::new(name).expect("Internal null bytes in filename"); unsafe { sys::Imf_DeepFrameBuffer_insert( self.ptr, c_name.as_ptr(), &slice.0, ) .into_result()?; } Ok(()) } /// Find the [`DeepSlice`] with the given `name` in the `DeepFrameBuffer` /// /// # Returns /// * `Some([`DeepSliceRef`])` - if the [`DeepSlice`] is found /// * `None` - otherwise /// pub fn get_slice<'a>(&'a self, name: &str) -> Option<DeepSliceRef<'a>> { let c_name = CString::new(name).expect("Internal null bytes in filename"); let mut ptr = std::ptr::null(); unsafe { sys::Imf_DeepFrameBuffer_findSlice_const( self.ptr, &mut ptr, c_name.as_ptr(), ); } if ptr.is_null() { None } else { Some(DeepSliceRef::new(ptr)) } } /// Find the [`DeepSlice`] with the given `name` in the `DeepFrameBuffer` and get a /// mutable Ref to it /// /// # Returns /// * `Some([`DeepSliceRefMut`])` - if the [`DeepSlice`] is found /// * `None` - otherwise /// pub fn get_slice_mut<'a>( &'a mut self, name: &str, ) -> Option<DeepSliceRefMut<'a>> { let c_name = CString::new(name).expect("Internal null bytes in filename"); let mut ptr = std::ptr::null_mut(); unsafe { sys::Imf_DeepFrameBuffer_findSlice( self.ptr, &mut ptr, c_name.as_ptr(), ); } if ptr.is_null() { None } else { Some(DeepSliceRefMut::new(ptr)) } } /// Get an iterator over the [`DeepSlice`]s in this `DeepFrameBuffer` /// pub fn iter(&self) -> DeepFrameBufferIter { unsafe { let mut ptr = sys::Imf_DeepFrameBuffer_ConstIterator_t::default(); sys::Imf_DeepFrameBuffer_begin_const(self.ptr, &mut ptr) .into_result() .unwrap(); let ptr = DeepFrameBufferConstIterator(ptr); let mut end = sys::Imf_DeepFrameBuffer_ConstIterator_t::default(); sys::Imf_DeepFrameBuffer_end_const(self.ptr, &mut end) .into_result() .unwrap(); let end = DeepFrameBufferConstIterator(end); DeepFrameBufferIter { ptr, end, _p: PhantomData, } } } /// Insert a [`Slice`] to hold the sample count for each deep pixel. /// /// The slice must be of type [`PixelType::Uint`] /// /// # Errors /// * [`Error::InvalidArgument`] - if the type of the slice is not [`PixelType::Uint`] /// pub fn set_sample_count_slice( &mut self, sample_count_slice: &Slice, ) -> Result<()> { unsafe { sys::Imf_DeepFrameBuffer_insertSampleCountSlice( self.ptr, &sample_count_slice.0, ) .into_result()?; } Ok(()) } /// Set a [`Frame`](crate::core::frame_buffer::Frame) to hold the per-pixel sample /// counts /// pub fn set_sample_count_frame(&mut self, frame: Frame) -> Result<()> { let w = frame.data_window[2] - frame.data_window[0] + 1; let ystride = w as usize * frame.stride; self.set_sample_count_slice( &Slice::with_data_window( frame.channel_type, frame.ptr, frame.data_window, ) .x_stride(frame.stride) .y_stride(ystride) .build()?, )?; self.sample_count_frame = Some(frame); Ok(()) } pub fn sample_count_frame(&self) -> Option<&Frame> { self.sample_count_frame.as_ref() } /// Get the sample count slice /// pub fn sample_count_slice(&self) -> SliceRef { let mut ptr = std::ptr::null(); unsafe { sys::Imf_DeepFrameBuffer_getSampleCountSlice(self.ptr, &mut ptr); } SliceRef::new(ptr) } } impl Drop for DeepFrameBuffer { fn drop(&mut self) { unsafe { sys::Imf_DeepFrameBuffer_dtor(self.ptr); } } } impl Default for DeepFrameBuffer { fn default() -> Self { DeepFrameBuffer::new() } } #[repr(transparent)] #[derive(Clone)] pub(crate) struct DeepFrameBufferConstIterator( pub(crate) sys::Imf_DeepFrameBuffer_ConstIterator_t, ); // #[repr(transparent)] // pub(crate) struct DeepFrameBufferIterator( // pub(crate) sys::Imf_DeepFrameBuffer_Iterator_t, // ); pub struct DeepFrameBufferIter<'a> { ptr: DeepFrameBufferConstIterator, end: DeepFrameBufferConstIterator, _p: PhantomData<&'a DeepFrameBuffer>, } impl<'a> Iterator for DeepFrameBufferIter<'a> { type Item = (&'a str, DeepSliceRef<'a>); fn next(&mut self) -> Option<(&'a str, DeepSliceRef<'a>)> { let ptr_curr = self.ptr.clone(); let mut ptr_next = self.ptr.clone(); unsafe { let mut dummy = std::ptr::null_mut(); sys::Imf_DeepFrameBuffer_ConstIterator__op_inc( &mut ptr_next.0, &mut dummy, ) .into_result() .unwrap(); } if ptr_curr == self.end { None } else { self.ptr = ptr_next; unsafe { let mut nameptr = std::ptr::null(); sys::Imf_DeepFrameBuffer_ConstIterator_name( &ptr_curr.0, &mut nameptr, ) .into_result() .unwrap(); if nameptr.is_null() { panic!( "DeepFrameBuffer::ConstIterator::name() returned NULL" ); } let mut sliceptr = std::ptr::null(); sys::Imf_DeepFrameBuffer_ConstIterator_slice( &ptr_curr.0, &mut sliceptr, ) .into_result() .unwrap(); Some(( CStr::from_ptr(nameptr) .to_str() .expect("NUL bytes in channel name"), DeepSliceRef::new(sliceptr), )) } } } } impl PartialEq for DeepFrameBufferConstIterator { fn eq(&self, rhs: &DeepFrameBufferConstIterator) -> bool { unsafe { let mut result = false; sys::Imf_deep_frame_buffer_const_iter_eq( &mut result, &self.0, &rhs.0, ) .into_result() .unwrap(); result } } } #[repr(transparent)] pub struct DeepSlice(pub(crate) sys::Imf_DeepSlice_t); pub type DeepSliceRef<'a, P = DeepSlice> = Ref<'a, P>; pub type DeepSliceRefMut<'a, P = DeepSlice> = RefMut<'a, P>; unsafe impl OpaquePtr for DeepSlice { type SysPointee = sys::Imf_DeepSlice_t; type Pointee = DeepSlice; } pub struct DeepSliceBuilder { pixel_type: PixelType, data: *mut i8, x_stride: usize, y_stride: usize, sample_stride: usize, x_sampling: i32, y_sampling: i32, fill_value: f64, x_tile_coords: bool, y_tile_coords: bool, } impl DeepSliceBuilder { pub fn build(self) -> Result<DeepSlice> { let mut slice = sys::Imf_DeepSlice_t::default(); unsafe { sys::Imf_DeepSlice_ctor( &mut slice, self.pixel_type.into(), self.data, self.x_stride as u64, self.y_stride as u64, self.sample_stride as u64, self.x_sampling, self.y_sampling, self.fill_value, self.x_tile_coords, self.y_tile_coords, ) .into_result()?; } Ok(DeepSlice(slice)) } pub fn sample_stride(mut self, v: usize) -> Self { self.sample_stride = v; self } pub fn fill_value(mut self, v: f64) -> Self { self.fill_value = v; self } pub fn x_stride(mut self, x: usize) -> Self { self.x_stride = x; self } pub fn y_stride(mut self, y: usize) -> Self { self.y_stride = y; self } pub fn x_sampling(mut self, x: i32) -> Self { self.x_sampling = x; self } pub fn y_sampling(mut self, y: i32) -> Self { self.y_sampling = y; self } pub fn x_tile_coords(mut self, x: bool) -> Self { self.x_tile_coords = x; self } pub fn y_tile_coords(mut self, y: bool) -> Self { self.y_tile_coords = y; self } } impl DeepSlice { pub fn builder(pixel_type: PixelType, data: *mut i8) -> DeepSliceBuilder { DeepSliceBuilder { pixel_type, data, x_stride: std::mem::size_of::<*mut i8>(), y_stride: 0, sample_stride: 0, x_sampling: 1, y_sampling: 1, fill_value: 0.0, x_tile_coords: false, y_tile_coords: false, } } pub fn from_sample_ptr<S: DeepSample>( data: *mut *mut S, width: i32, ) -> DeepSliceBuilder { DeepSliceBuilder { pixel_type: S::CHANNEL_TYPE, data: data as *mut i8, x_stride: std::mem::size_of::<*mut i8>(), y_stride: std::mem::size_of::<*mut i8>() * width as usize, sample_stride: std::mem::size_of::<S>(), x_sampling: 1, y_sampling: 1, fill_value: 0.0, x_tile_coords: false, y_tile_coords: false, } } } impl Drop for DeepSlice { fn drop(&mut self) { unsafe { sys::Imf_DeepSlice_dtor(&mut self.0); } } } pub trait DeepSample { type Type; const CHANNEL_TYPE: PixelType; const STRIDE: usize = std::mem::size_of::<Self::Type>(); } impl DeepSample for half::f16 { type Type = Self; const CHANNEL_TYPE: PixelType = PixelType::Half; } impl DeepSample for f32 { type Type = Self; const CHANNEL_TYPE: PixelType = PixelType::Float; } impl DeepSample for u32 { type Type = Self; const CHANNEL_TYPE: PixelType = PixelType::Uint; }
use std::iter::Peekable; use std::str::Chars; use super::keyword::Keyword; use super::Token; pub fn consume_while<F>(it: &mut Peekable<Chars>, pred: F) -> Vec<char> where F: Fn(char) -> bool { let mut chars: Vec<char> = vec![]; while let Some(&ch) = it.peek() { if pred(ch) { it.next().unwrap(); chars.push(ch); } else { break; } } chars } pub fn consume_token(it: &mut Peekable<Chars>, token_vec: &mut Vec<Token>, token: Token) { it.next(); token_vec.push(token); } pub fn consume_number(it: &mut Peekable<Chars>, token_vec: &mut Vec<Token>, errors: &mut Vec<String>, line: i32) { let num: String = consume_while(it, |a| a.is_numeric()) .into_iter() .collect(); if it.peek().unwrap() == &'.' { it.next(); let decimal: String = consume_while(it, |a| a.is_numeric()) .into_iter() .collect(); let float = [num.as_ref(), ".", decimal.as_ref()].join(""); if it.peek().unwrap().is_alphabetic() { errors.push(format!("Unexpected character in number on Line {}", line)); } else { token_vec.push(Token::Float(float.parse::<f32>().unwrap())); } } else { if it.peek().unwrap().is_alphabetic() { errors.push(format!("Unexpected character in number on Line {}", line)); } else { token_vec.push(Token::Integer(num.parse::<i32>().unwrap())); } } } pub fn consume_constant(it: &mut Peekable<Chars>, token_vec: &mut Vec<Token>) { let chars: String = consume_while(it, |a| a.is_alphanumeric()) .into_iter() .collect(); match chars.as_ref() { "def" => token_vec.push(Token::Keyword(Keyword::Def)), "true" => token_vec.push(Token::Keyword(Keyword::True)), "false" => token_vec.push(Token::Keyword(Keyword::False)), "match" => token_vec.push(Token::Keyword(Keyword::Match)), _ => token_vec.push(Token::Constant(chars)) } } pub fn consume_operator(it: &mut Peekable<Chars>, token_vec: &mut Vec<Token>) { let chars: String = consume_while(it, |a| a == '-' || a == '+' || a == '*' || a == '/' || a == '>' || a == '<' || a == '=' || a == '&' || a == '|' || a == '!' || a == '%') .into_iter() .collect(); token_vec.push(Token::Constant(chars)) } pub fn consume_string(it: &mut Peekable<Chars>, token_vec: &mut Vec<Token>) { it.next(); let chars: String = consume_while(it, |a| a != '\'') .into_iter() .collect(); it.next(); token_vec.push(Token::String(chars)); } pub fn consume_comment(it: &mut Peekable<Chars>, token_vec: &mut Vec<Token>) { it.next(); let comment: String = consume_while(it, |a| a != '\n') .into_iter() .collect(); token_vec.push(Token::Comment(comment)); }
pub use macroquad::prelude::KeyCode as Key; use crate::Context; #[allow(unused_variables)] pub fn pressed(ctx: &Context, key: Key) -> bool { macroquad::prelude::is_key_pressed(key) } #[allow(unused_variables)] pub fn down(ctx: &Context, key: Key) -> bool { macroquad::prelude::is_key_down(key) } #[allow(unused_variables)] pub fn get_char_queue(ctx: &Context) -> Option<char> { macroquad::prelude::get_char_pressed() }
use super::check; #[test] fn t01_inline() { check( ".result {\n output: \"dquoted\";\n output: #{\"dquoted\"};\n \ output: \"[#{\"dquoted\"}]\";\n output: \"#{\"dquoted\"}\";\n \ output: '#{\"dquoted\"}';\n output: \"['#{\"dquoted\"}']\";\n}\n", ".result {\n output: \"dquoted\";\n output: dquoted;\n \ output: \"[dquoted]\";\n output: \"dquoted\";\n \ output: \"dquoted\";\n output: \"['dquoted']\";\n}\n", ) } #[test] fn t06_escape_interpolation() { check( "$input: \"dquoted\";\n.result {\n \ output: \"[\\#{\"dquoted\"}]\";\n \ output: \"\\#{\"dquoted\"}\";\n \ output: '\\#{\"dquoted\"}';\n \ output: \"['\\#{\"dquoted\"}']\";\n}\n", ".result {\n output: \"[#{\" dquoted \"}]\";\n \ output: \"#{\" dquoted \"}\";\n output: '\\#{\"dquoted\"}';\n \ output: \"['#{\" dquoted \"}']\";\n}\n", ) }
use crate::mmu::MMU; use std::time::Instant; pub const VRAM_SIZE: usize = 0x2000; pub const IO_REG: usize = 0xFF7F - 0xFF00 + 1; pub const VOAM_SIZE: usize = 0xFE9F - 0xFE00 + 1; pub const SCREEN_W: usize = 160; pub const SCREEN_H: usize = 144; pub const BACK_W: usize = 256; pub const BACK_H: usize = 256; pub const DARKEST: u32 = 0xFF0F380F; pub const DARK: u32 = 0xFF306230; pub const LIGHT: u32 = 0xFF8BAC0F; pub const LIGHTEST: u32 = 0xFF9BBC0F; pub struct GPU { pub data: Vec<u32>, tile_set: [[u32; 64]; 384], tile_map0: [u8; 0x400], pub vram: [u8; VRAM_SIZE], voam: [u8; VOAM_SIZE], io_r: [u8; IO_REG], mode: u8, mode_clock: usize, pub update_screen: bool, } impl GPU { pub fn new() -> Self { GPU { data: vec![LIGHTEST; SCREEN_H * SCREEN_W], tile_set: [[0; 64]; 384], tile_map0: [0; 0x400], vram: [0; VRAM_SIZE], voam: [0; VOAM_SIZE], io_r: [0; IO_REG], mode: 0, mode_clock: 0, update_screen: false, } } pub fn step(&mut self, cpu_clocks: usize) { let lcdc = self.read_ior(0xFF40); let lcdc_off = (self.read_ior(0xFF40) & 0x80) == 0; if lcdc_off { return } self.mode_clock += cpu_clocks; let mut ly = self.read_ior(0xFF44); let lyc = self.read_ior(0xFF45); if self.mode_clock > 456 && self.mode != 1 { ly = ly.wrapping_add(1); self.write_ior(0xFF44, ly); if ly <= 144 { self.mode_clock = 0 } } match self.mode_clock { 0..=80 => self.mode = 2, 81..=252 => self.mode = 3, 253..=456 => self.mode = 0, // H BLANK 457..=4560 => self.mode = 1, // V BLANK _ => { self.mode = 2; self.mode_clock = 0; if ly >= 154 { self.write_ior(0xFF44, 0) } } } let clean_stat = self.read_ior(0xFF41) & 0xF8; let new_stat = clean_stat | (self.mode | if ly == lyc { 0b100 } else { 0 }); self.write_ior(0xFF41, new_stat); if self.mode == 2 && self.update_screen { self.draw_bg(); self.update_screen = false; } } pub fn get_screen(&self) -> &Vec<u32> { &self.data } pub fn lcd_on(&self) -> bool { (self.read_ior(0xFF40) & 0b1000_0000) != 0 } pub fn draw_bg(&mut self) { // let now = Instant::now(); let scx = self.read_ior(0xFF43) as usize; let scy = self.read_ior(0xFF42) as usize; for (t, tile_index) in self.tile_map0.iter().enumerate() { let tile_map_column = t % 32; let tile_map_row = t / 32; for (p, pixel) in self.tile_set[*tile_index as usize].iter().enumerate() { let pixel_column = p % 8; let pixel_row = p / 8; let col = pixel_column + (tile_map_column * 8); let row = (pixel_row + tile_map_row * 8) * 256; let idx = col + row; let fitted_col = idx % 256; let fitted_row = idx / 256; let clear_scx = fitted_col >= scx && fitted_col < scx + SCREEN_W; let clear_scy = fitted_row >= scy && fitted_row < scy + SCREEN_H; if clear_scx && clear_scy { let fitted_idx = (fitted_col - scx) + ((fitted_row - scy) * SCREEN_W); self.data[fitted_idx] = *pixel; } } } // println!("{:?}", Instant::now().duration_since(now)); } pub fn get_color_from(&self, pair: u8) -> u32 { match self.read_ior(0xFF47) >> (2 * pair) & 0b11 { 0b00 => LIGHTEST, 0b01 => LIGHT, 0b10 => DARK, _ => DARKEST, } } pub fn read_oam(&self, address: usize) -> u8 { self.voam[address - 0xFE00] } pub fn write_oam(&mut self, address: usize, value: u8) { self.voam[address - 0xFE00] = value; } pub fn read_ior(&self, address: usize) -> u8 { self.io_r[address - 0xFF00] } pub fn write_ior(&mut self, address: usize, value: u8) { self.io_r[address - 0xFF00] = value; if address == 0xFF42 || address == 0xFF43 { self.update_screen = true } } pub fn read_vram(&self, address: usize) -> u8 { self.vram[address - 0x8000] } pub fn write_vram(&mut self, address: usize, value: u8) { let index = address - 0x8000; self.vram[index] = value; self.update_screen = true; match address { 0x9800..=0x9BFF => self.tile_map0[index - 0x1800] = value, 0x8000..=0x97FF => { let normalized_index = index & 0xFFFE; let byte1 = self.vram[normalized_index]; let byte2 = self.vram[normalized_index + 1]; let tile_index = index / 16; let row_index = ((index % 16) / 2) * 8; for px_index in 0..8 { let mask = 1 << (7 - px_index); let bit1 = byte1 & mask != 0; let bit2 = byte2 & mask != 0; let pair = ((bit1 as u8) << 1) | bit2 as u8; let color = self.get_color_from(pair); self.tile_set[tile_index][row_index + px_index as usize] = color; } }, _ => {} } } }
fn main() { let equation = |x: f64| -> f64 { 3.0 * x.powi(2) + 2.0 }; let value = quadrature(0.01, equation); println!("{:?}", value); } fn quadrature(x_delta: f64, equation: fn(f64) -> f64) -> f64 { let mut x: f64 = 0.0; let mut s: f64 = 0.0; while x <= 1.0 { s += equation(x) * x_delta; x += x_delta; } s } #[cfg(test)] mod tests { #[test] fn test() { assert_eq!(true, true); } }
#![no_main] #![no_std] #![deny(unsafe_code)] extern crate stm32f4xx_hal as hal; #[allow(unused_imports)] use panic_semihosting; use crate::hal::{prelude::*, spi::Spi, stm32}; use cortex_m_rt::ExceptionFrame; use cortex_m_rt::{entry, exception}; use embedded_hal::digital::v1_compat::OldOutputPin; use mcp49xx::{Command, Mcp49xx, MODE0}; #[entry] fn main() -> ! { let dp = stm32::Peripherals::take().expect("Failed to take stm32::Peripherals"); let _cp = cortex_m::peripheral::Peripherals::take().expect("Failed to take cortex_m::Peripherals"); // Set up the system clock. We want to run at 48MHz for this one. let rcc = dp.RCC.constrain(); let clocks = rcc.cfgr.sysclk(48.mhz()).freeze(); // Set up SPI let gpioa = dp.GPIOA.split(); let gpiod = dp.GPIOD.split(); let sck = gpioa.pa5.into_alternate_af5(); let miso = gpioa.pa6.into_alternate_af5(); let mosi = gpioa.pa7.into_alternate_af5(); let mut cs = gpiod.pd14.into_push_pull_output(); // Deselect cs.set_high().unwrap(); let gpioc = dp.GPIOC.split(); let btn = gpioc.pc13.into_pull_down_input(); let spi = Spi::spi1(dp.SPI1, (sck, miso, mosi), MODE0, 1.mhz().into(), clocks); let mut mcp4922 = Mcp49xx::new_mcp4922(spi, OldOutputPin::from(cs)); // Set up state for the loop let mut was_pressed = btn.is_low().unwrap(); let cmd = Command::default(); let cmd = cmd.double_gain().value(50); // This runs continuously, as fast as possible loop { // Check if the button has just been pressed. // Remember, active low. let is_pressed = btn.is_low().unwrap(); if !was_pressed && is_pressed { // Enable double gain and set value mcp4922.send(cmd).unwrap(); // Keeps double gain enabled but changes value mcp4922.send(cmd.value(100)).unwrap(); was_pressed = true; } else if !is_pressed { was_pressed = false; } } } #[exception] fn HardFault(ef: &ExceptionFrame) -> ! { panic!("HardFault at {:#?}", ef); } #[exception] fn DefaultHandler(irqn: i16) { panic!("Unhandled exception (IRQn = {})", irqn); }
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(raw_identifiers)] fn r#fn(r#match: u32) -> u32 { r#match } pub fn main() { let r#struct = 1; assert_eq!(1, r#struct); let foo = 2; assert_eq!(2, r#foo); let r#bar = 3; assert_eq!(3, bar); assert_eq!(4, r#fn(4)); let r#true = false; assert_eq!(r#true, false); }
use std::cmp::{max, min, Reverse}; use crate::parse::boolean_matrix::BooleanMatrix; use crate::parse::image::{Image, Color}; use crate::parse::target::Target; use ordered_float::OrderedFloat; #[derive(Debug)] pub struct TargetMesh { pub targets: Vec<Target>, // coordinates stored are between 0 and 1 as height percentage } impl TargetMesh { pub fn add_to_image(&self, image: &mut Image) { let target_center_square_size = image.height / 200; for target in self.targets.iter() { let color = target.get_color(); let top = (target.top * image.height as f64) as usize; let bottom = (target.bottom * image.height as f64) as usize; let left = (target.left * image.base as f64) as usize; let right = (target.right * image.base as f64) as usize; let mean_x = (target.mean_x * image.base as f64) as usize; let mean_y = (target.mean_y * image.height as f64) as usize; for y in top..=bottom { for x in left..=right { // we need to scale this up to the size of the image image.set_color(x, y, color); } } for y in mean_y-target_center_square_size..=mean_y+target_center_square_size { for x in mean_x-target_center_square_size..=mean_x+target_center_square_size { if x < image.base && y < image.height { image.set_color(x, y, Color::yellow()); } } } } } pub fn get_bar_centers(&self) -> Vec<(f64, f64)> { self.targets.iter() .filter(|t| t.is_bar()) .map(|t| t.center_position()) .collect() } pub fn get_aligner_centers(&self) -> Vec<(f64, f64)> { let mut aligners: Vec<Target> = self.targets.iter() .filter(|t| t.is_aligner()) .cloned() .collect(); aligners.sort_by_key(|t| Reverse(OrderedFloat(t.fraction_of_image_filled))); aligners.truncate(4); assert_eq!(aligners.len(), 4, "Fewer than four aligners were found"); let mut centers: Vec<(f64, f64)> = aligners.into_iter() .map(|t| (t.mean_x as f64, t.mean_y as f64)) .collect(); // we want to let mut sorted_centers = Vec::with_capacity(4); sorted_centers.push(remove_max_by(&mut centers, |&(x0, y0), &(x1, y1)| x0+y0 < x1+y1)); // top left sorted_centers.push(remove_max_by(&mut centers, |&(x0, y0), &(x1, y1)| x0-y0 > x1-y1)); // top right sorted_centers.push(remove_max_by(&mut centers, |&(x0, y0), &(x1, y1)| x0+y0 > x1+y1)); // bottom right sorted_centers.push(remove_max_by(&mut centers, |&(x0, y0), &(x1, y1)| x0-y0 < x1-y1)); // bottom left sorted_centers } pub fn from_matrix(target_candidates: &BooleanMatrix) -> TargetMesh { // lets iterate through all of the `dark` pixels let (base, height) = target_candidates.base_height(); let mut has_seen = BooleanMatrix::all_false(height, height); let mut targets = Vec::new(); // we add coordinates of the targets here for y in 0..height { for x in 0..base { if !target_candidates.is_set(x, y) || has_seen.is_set(x, y) { continue } // this pixel isn't a target, or we've already seen it if let Some(target) = flood_fill(x, y, target_candidates, &mut has_seen) { targets.push(target); } } } TargetMesh { targets } } } fn flood_fill(x: usize, y: usize, target_candidates: &BooleanMatrix, has_seen: &mut BooleanMatrix) -> Option<Target> { // returns the topmost, rightmost, bottommost, leftmost point, and the total pixels filled let (image_base, image_height) = target_candidates.base_height(); assert!(!has_seen.is_set(x, y)); assert!(target_candidates.is_set(x, y)); // let mut top = y as f64 / image_height as f64; // let mut bottom = y as f64 / image_height as f64; // let mut left = x as f64 / image_base as f64; // let mut right = x as f64 / image_base as f64; let mut top = y; let mut bottom = y; let mut left = x; let mut right = x; // let mut x_sum = 0.0; // let mut y_sum = 0.0; let mut x_sum = 0; let mut y_sum = 0; let mut pixels_filled = 0; let mut stack = Vec::new(); stack.push((x, y)); while let Some((x, y)) = stack.pop() { if has_seen.is_set(x, y) { continue } // after this was pushed on, this pixel was colored has_seen.set(x, y); // let x_frac = x as f64 / image_base as f64; // let y_frac = y as f64 / image_height as f64; pixels_filled += 1; // // x_sum += x_frac; // y_sum += y_frac; // // left = min(left, x_frac); // top = min(top, y_frac); // right = max(right, x_frac); // bottom = max(bottom, y_frac); x_sum += x; y_sum += y; left = min(left, x); top = min(top, y); right = max(right, x); bottom = max(bottom, y); // process the neighbors for (new_x, new_y) in neighbors(x, y, image_base, image_height) { if target_candidates.is_set(new_x, new_y) { stack.push((new_x, new_y)); } } } // let mean_x = x_sum / pixels_filled as f64; // let mean_y = y_sum / pixels_filled as f64; // Target::new shouldn't care about the image_base or image_height of our image. That's why we want to convert all of our numbers // to fractions between 0 and 1 // let (b, h) = (image_base as f64, image_height as f64); // just to be clear, these are the image_base and image_height of the image // // // this is the 'center of mass' of our target // let mean_x = x_sum / pixels_filled; // let mean_y = y_sum / pixels_filled; // // let mut fraction_of_image_filled = pixels_filled as f64 / (b*h); // // // why add one: because otherwise if there is a target only one pixel, then right-left == 0, and so image_base would be reported as 0 // let target_base_unmapped = right-left+1; // we add one, because // let target_height_unmapped = bottom-left+1; // let squareness = squareness(target_base_unmapped, target_height_unmapped); // let fullness = pixels_filled as f64 / (target_base_unmapped*target_height_unmapped) as f64; // // Target::new( // top as f64 / h, // bottom as f64 / h, // right as f64 / b, // left as f64 / b, // mean_x as f64 / b, // mean_y as f64 / h, // fraction_of_image_filled, // squareness, // fullness, // ) let mean_x = x_sum / pixels_filled; let mean_y = y_sum / pixels_filled; Target::new(left, right, top, bottom, pixels_filled, mean_x, mean_y, image_base, image_height) } fn neighbors(x: usize, y: usize, width: usize, height: usize) -> impl Iterator<Item=(usize, usize)> { // returns an iterator over the 4 pixels surrounding (x,y) respecting the edges let mut ret = Vec::with_capacity(4); if x > 0 { ret.push((x-1, y)); } if y > 0 { ret.push((x, y-1)); } if x < width-1 { ret.push((x+1, y)); } if y < height-1 { ret.push((x, y+1)); } ret.into_iter() } fn remove_max_by<T>(vec: &mut Vec<T>, greater_than: impl Fn(&T, &T) -> bool) -> T { let mut max_index = 0; let mut max = &vec[0]; for (i, k) in vec.iter().enumerate().skip(1) { if greater_than(k, max) { max = k; max_index = i; } } return vec.remove(max_index); }
//! The following is derived from Rust's //! library/std/src/os/windows/io/raw.rs //! at revision //! 4f9b394c8a24803e57ba892fa00e539742ebafc0. //! //! All code in this file is licensed MIT or Apache 2.0 at your option. use super::super::raw; /// Raw SOCKETs. #[cfg_attr(staged_api, stable(feature = "rust1", since = "1.0.0"))] pub type RawSocket = raw::SOCKET; /// Extracts raw sockets. #[cfg_attr(staged_api, stable(feature = "rust1", since = "1.0.0"))] pub trait AsRawSocket { /// Extracts the raw socket. /// /// This function is typically used to **borrow** an owned socket. /// When used in this way, this method does **not** pass ownership of the /// raw socket to the caller, and the socket is only guaranteed /// to be valid while the original object has not yet been destroyed. /// /// However, borrowing is not strictly required. See [`AsSocket::as_socket`] /// for an API which strictly borrows a socket. #[cfg_attr(staged_api, stable(feature = "rust1", since = "1.0.0"))] fn as_raw_socket(&self) -> RawSocket; } /// Creates I/O objects from raw sockets. #[cfg_attr(staged_api, stable(feature = "from_raw_os", since = "1.1.0"))] pub trait FromRawSocket { /// Constructs a new I/O object from the specified raw socket. /// /// This function is typically used to **consume ownership** of the socket /// given, passing responsibility for closing the socket to the returned /// object. When used in this way, the returned object /// will take responsibility for closing it when the object goes out of /// scope. /// /// However, consuming ownership is not strictly required. Use a /// `From<OwnedSocket>::from` implementation for an API which strictly /// consumes ownership. /// /// # Safety /// /// The `socket` passed in must: /// - be a valid an open socket, /// - be a socket that may be freed via [`closesocket`]. /// /// [`closesocket`]: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-closesocket #[cfg_attr(staged_api, stable(feature = "from_raw_os", since = "1.1.0"))] unsafe fn from_raw_socket(sock: RawSocket) -> Self; } /// A trait to express the ability to consume an object and acquire ownership of /// its raw `SOCKET`. #[cfg_attr(staged_api, stable(feature = "into_raw_os", since = "1.4.0"))] pub trait IntoRawSocket { /// Consumes this object, returning the raw underlying socket. /// /// This function is typically used to **transfer ownership** of the underlying /// socket to the caller. When used in this way, callers are then the unique /// owners of the socket and must close it once it's no longer needed. /// /// However, transferring ownership is not strictly required. Use a /// `Into<OwnedSocket>::into` implementation for an API which strictly /// transfers ownership. #[cfg_attr(staged_api, stable(feature = "into_raw_os", since = "1.4.0"))] fn into_raw_socket(self) -> RawSocket; }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use failure::Error; use serde_derive::{Deserialize, Serialize}; use serde_json::Value; use std::sync::Arc; use crate::test::facade::TestFacade; use crate::test::types::TestPlan; #[derive(Serialize, Deserialize)] struct RunTestArgs { test: String, } pub async fn test_method_to_fidl( method_name: String, args_value: Value, facade: Arc<TestFacade>, ) -> Result<Value, Error> { match method_name.as_str() { "RunTest" => { let args: RunTestArgs = serde_json::from_value(args_value)?; facade.run_test(args.test).await } "RunPlan" => { let plan: TestPlan = serde_json::from_value(args_value)?; facade.run_plan(plan).await } _ => Err(format_err!("Unsupported method {}", method_name)), } }
mod client; mod config; mod server; use config::Config; use server::Server; fn main() { let config = Config::init(); Server::new(&config.get_address()) .max_clients(config.get_max_clients()) .max_acceptable_buffer(config.get_acceptable_buffer()) .run(); }
#![allow(dead_code)] use crate::{regex, utils}; use lazy_static::lazy_static; use regex::Regex; use std::collections::{HashMap, HashSet}; use utils::AOCResult; lazy_static! { static ref BAG_REGEX: Regex = regex!(r"([0-9])* ?([a-z]+ [a-z]+) bags?"); } pub type BagID = usize; #[derive(Debug)] pub struct BagRules { registry: HashMap<String, BagID>, contained_by: HashMap<BagID, HashMap<BagID, usize>>, contains: HashMap<BagID, HashMap<BagID, usize>>, } pub fn day7() { let input = utils::get_input("day7"); let mut rules = BagRules::new(); println!( "handy_haversacks part 1: {}", rules .process(input) .unwrap() .container_count("shiny gold") .unwrap() ); println!( "handy_haversacks part 2: {}", rules.contained_count("shiny gold").unwrap() ); } impl BagRules { pub fn new() -> BagRules { BagRules { registry: HashMap::new(), contained_by: HashMap::new(), contains: HashMap::new(), } } fn register(&mut self, bag_type: &str) -> BagID { let count = self.registry.len(); *self.registry.entry(bag_type.to_string()).or_insert(count) } pub fn process(&mut self, input: impl Iterator<Item = String>) -> AOCResult<&mut Self> { for line in input { self.process_line(&line)?; } Ok(self) } pub fn process_line(&mut self, line: &str) -> AOCResult<&mut Self> { let mut captures = BAG_REGEX.captures_iter(line); let container_bag_type = self.register(&captures.next()?[2]); for capture in captures { let count = capture .get(1) .map_or(Ok(0), |m| m.as_str().parse::<usize>())?; let contained_bag_type = self.register(&capture[2]); self.contained_by .entry(contained_bag_type) .or_insert(HashMap::new()) .insert(container_bag_type, count); self.contains .entry(container_bag_type) .or_insert(HashMap::new()) .insert(contained_bag_type, count); } Ok(self) } fn gather_containers(&self, bag_id: &BagID, seen_types: &mut HashSet<BagID>) { if !self.contained_by.contains_key(bag_id) { return; } for containing_bag in self.contained_by[bag_id].iter() { let id = containing_bag.0; if seen_types.insert(*id) { self.gather_containers(id, seen_types); } } } fn gather_contained(&self, bag_id: &BagID, cached_count: &mut HashMap<BagID, usize>) -> usize { if !self.contains.contains_key(bag_id) { return 0; } if cached_count.contains_key(bag_id) { return cached_count[bag_id]; } let contained_count = self.contains[bag_id].iter().fold(0, |a, bag| { a + bag.1 * (1 + self.gather_contained(bag.0, cached_count)) }); cached_count.insert(*bag_id, contained_count); contained_count } pub fn container_count(&self, bag_type: &str) -> AOCResult<usize> { let bag_id = self.registry.get(bag_type)?; let mut containers: HashSet<BagID> = HashSet::new(); self.gather_containers(&bag_id, &mut containers); Ok(containers.len()) } pub fn contained_count(&self, bag_type: &str) -> AOCResult<usize> { let bag_id = self.registry.get(bag_type)?; let mut cached_count: HashMap<BagID, usize> = HashMap::new(); Ok(self.gather_contained(bag_id, &mut cached_count)) } } #[test] pub fn basic_handy_haversacks() { let input = utils::get_input("test_day7"); let mut rules = BagRules::new(); assert_eq!( rules .process(input) .unwrap() .container_count("shiny gold") .unwrap(), 4 ); assert_eq!(rules.contained_count("shiny gold").unwrap(), 32); }
extern crate criterion; use criterion::{black_box, criterion_group, criterion_main, Criterion}; #[path = "../src/ecoz2_lib/lpca_c.rs"] mod lpca_c; #[path = "../src/lpc/lpca_rs.rs"] mod lpca_rs; fn criterion_benchmark(c: &mut Criterion) { let input = lpca_rs::lpca_load_input("signal_frame.inputs").unwrap(); let frame = black_box(input.x); let prediction_order = black_box(input.p); //println!("input length={}, prediction_order={}", frame.len(), prediction_order); let mut vector = vec![0f64; prediction_order + 1]; let mut reflex = vec![0f64; prediction_order + 1]; let mut pred = vec![0f64; prediction_order + 1]; c.bench_function("lpca1_rs", |b| { b.iter(|| { lpca_rs::lpca1( &frame, prediction_order, &mut vector, &mut reflex, &mut pred, ) }) }); c.bench_function("lpca2_rs", |b| { b.iter(|| { lpca_rs::lpca2( &frame, prediction_order, &mut vector, &mut reflex, &mut pred, ) }) }); c.bench_function("lpca_c", |b| { b.iter(|| { lpca_c::lpca( &frame, prediction_order, &mut vector, &mut reflex, &mut pred, ) }) }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
pub struct Solution; impl Solution { pub fn find_words(board: Vec<Vec<char>>, words: Vec<String>) -> Vec<String> { let solver = Solver::from_board(board); solver.find_words(words) } } struct Solver { m: usize, n: usize, board: Vec<Vec<char>>, visited: Vec<Vec<bool>>, result: Vec<String>, } impl Solver { fn from_board(board: Vec<Vec<char>>) -> Self { let m = board.len(); let n = board.first().map_or(0, |x| x.len()); let visited = vec![vec![false; n]; m]; let result = Vec::new(); Solver { m, n, board, visited, result, } } fn find_words(mut self, words: Vec<String>) -> Vec<String> { let mut trie = Trie::from_words(words); for i in 0..self.m { for j in 0..self.n { self.find_words_rec(i, j, &mut trie); } } self.result } fn find_words_rec(&mut self, i: usize, j: usize, trie: &mut Trie) { if self.visited[i][j] { return; } if let Some(next) = trie.get_next(self.board[i][j]) { self.visited[i][j] = true; if let Some(word) = next.end.take() { self.result.push(word); } if i > 0 { self.find_words_rec(i - 1, j, next); } if j > 0 { self.find_words_rec(i, j - 1, next); } if i + 1 < self.m { self.find_words_rec(i + 1, j, next); } if j + 1 < self.n { self.find_words_rec(i, j + 1, next); } self.visited[i][j] = false; } } } #[derive(Default)] struct Trie { end: Option<String>, next: [Option<Box<Trie>>; 26], } impl Trie { fn new() -> Self { Self::default() } fn from_words(words: Vec<String>) -> Self { let mut trie = Self::new(); for word in words { let mut cur = &mut trie; for c in word.chars() { cur = cur.get_next_or_new(c); } cur.end = Some(word); } trie } fn get_next(&mut self, c: char) -> Option<&mut Self> { self.next[c as usize - 'a' as usize] .as_mut() .map(|x| x.as_mut()) } fn get_next_or_new(&mut self, c: char) -> &mut Self { self.next[c as usize - 'a' as usize].get_or_insert_with(|| Box::new(Trie::new())) } } #[test] fn test0212() { fn case(board: &[&str], words: &[&str], want: &[&str]) { let board = board.iter().map(|s| s.chars().collect()).collect(); let words = words.iter().map(|s| s.to_string()).collect(); let want = want.iter().map(|s| s.to_string()).collect::<Vec<String>>(); let got = Solution::find_words(board, words); assert_eq!(got, want); } case( &["oaan", "etae", "ihkr", "iflv"], &["oath", "pea", "eat", "rain"], &["oath", "eat"], ); case(&["a"], &["a"], &["a"]); case(&["aa"], &["aaa"], &[]); }
#[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::AES_DMAIC { #[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 AES_DMAIC_CINR { bits: bool, } impl AES_DMAIC_CINR { #[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 _AES_DMAIC_CINW<'a> { w: &'a mut W, } impl<'a> _AES_DMAIC_CINW<'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 AES_DMAIC_COUTR { bits: bool, } impl AES_DMAIC_COUTR { #[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 _AES_DMAIC_COUTW<'a> { w: &'a mut W, } impl<'a> _AES_DMAIC_COUTW<'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 AES_DMAIC_DINR { bits: bool, } impl AES_DMAIC_DINR { #[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 _AES_DMAIC_DINW<'a> { w: &'a mut W, } impl<'a> _AES_DMAIC_DINW<'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 AES_DMAIC_DOUTR { bits: bool, } impl AES_DMAIC_DOUTR { #[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 _AES_DMAIC_DOUTW<'a> { w: &'a mut W, } impl<'a> _AES_DMAIC_DOUTW<'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 } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Context In DMA Done Interrupt Clear"] #[inline(always)] pub fn aes_dmaic_cin(&self) -> AES_DMAIC_CINR { let bits = ((self.bits >> 0) & 1) != 0; AES_DMAIC_CINR { bits } } #[doc = "Bit 1 - Context Out DMA Done Interrupt Clear"] #[inline(always)] pub fn aes_dmaic_cout(&self) -> AES_DMAIC_COUTR { let bits = ((self.bits >> 1) & 1) != 0; AES_DMAIC_COUTR { bits } } #[doc = "Bit 2 - Data In DMA Done Interrupt Clear"] #[inline(always)] pub fn aes_dmaic_din(&self) -> AES_DMAIC_DINR { let bits = ((self.bits >> 2) & 1) != 0; AES_DMAIC_DINR { bits } } #[doc = "Bit 3 - Data Out DMA Done Interrupt Clear"] #[inline(always)] pub fn aes_dmaic_dout(&self) -> AES_DMAIC_DOUTR { let bits = ((self.bits >> 3) & 1) != 0; AES_DMAIC_DOUTR { 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 - Context In DMA Done Interrupt Clear"] #[inline(always)] pub fn aes_dmaic_cin(&mut self) -> _AES_DMAIC_CINW { _AES_DMAIC_CINW { w: self } } #[doc = "Bit 1 - Context Out DMA Done Interrupt Clear"] #[inline(always)] pub fn aes_dmaic_cout(&mut self) -> _AES_DMAIC_COUTW { _AES_DMAIC_COUTW { w: self } } #[doc = "Bit 2 - Data In DMA Done Interrupt Clear"] #[inline(always)] pub fn aes_dmaic_din(&mut self) -> _AES_DMAIC_DINW { _AES_DMAIC_DINW { w: self } } #[doc = "Bit 3 - Data Out DMA Done Interrupt Clear"] #[inline(always)] pub fn aes_dmaic_dout(&mut self) -> _AES_DMAIC_DOUTW { _AES_DMAIC_DOUTW { w: self } } }
mod common; use std::str::FromStr; use common::run_test_in_repo; use rusty_git::object::Id; use rusty_git::repository::Repository; #[test] fn test_pack_file() { run_test_in_repo("tests/resources/repo.git", |path| { let repo = Repository::open(path).unwrap(); repo.object_database() .parse_object(Id::from_str("90012941912143fcf042590f8e152c41b13d5520").unwrap()) .unwrap(); }); }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qundoview.h // dst-file: /src/widgets/qundoview.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::qlistview::*; // 773 use std::ops::Deref; use super::qundogroup::*; // 773 use super::qwidget::*; // 773 use super::qundostack::*; // 773 use super::super::core::qstring::*; // 771 use super::super::gui::qicon::*; // 771 use super::super::core::qobjectdefs::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QUndoView_Class_Size() -> c_int; // proto: void QUndoView::QUndoView(QUndoGroup * group, QWidget * parent); fn C_ZN9QUndoViewC2EP10QUndoGroupP7QWidget(arg0: *mut c_void, arg1: *mut c_void) -> u64; // proto: void QUndoView::setStack(QUndoStack * stack); fn C_ZN9QUndoView8setStackEP10QUndoStack(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QUndoView::setEmptyLabel(const QString & label); fn C_ZN9QUndoView13setEmptyLabelERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QUndoView::setCleanIcon(const QIcon & icon); fn C_ZN9QUndoView12setCleanIconERK5QIcon(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QUndoView::setGroup(QUndoGroup * group); fn C_ZN9QUndoView8setGroupEP10QUndoGroup(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QUndoGroup * QUndoView::group(); fn C_ZNK9QUndoView5groupEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: const QMetaObject * QUndoView::metaObject(); fn C_ZNK9QUndoView10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QUndoStack * QUndoView::stack(); fn C_ZNK9QUndoView5stackEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QIcon QUndoView::cleanIcon(); fn C_ZNK9QUndoView9cleanIconEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QString QUndoView::emptyLabel(); fn C_ZNK9QUndoView10emptyLabelEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QUndoView::QUndoView(QWidget * parent); fn C_ZN9QUndoViewC2EP7QWidget(arg0: *mut c_void) -> u64; // proto: void QUndoView::~QUndoView(); fn C_ZN9QUndoViewD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QUndoView::QUndoView(QUndoStack * stack, QWidget * parent); fn C_ZN9QUndoViewC2EP10QUndoStackP7QWidget(arg0: *mut c_void, arg1: *mut c_void) -> u64; } // <= ext block end // body block begin => // class sizeof(QUndoView)=1 #[derive(Default)] pub struct QUndoView { qbase: QListView, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QUndoView { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QUndoView { return QUndoView{qbase: QListView::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QUndoView { type Target = QListView; fn deref(&self) -> &QListView { return & self.qbase; } } impl AsRef<QListView> for QUndoView { fn as_ref(& self) -> & QListView { return & self.qbase; } } // proto: void QUndoView::QUndoView(QUndoGroup * group, QWidget * parent); impl /*struct*/ QUndoView { pub fn new<T: QUndoView_new>(value: T) -> QUndoView { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QUndoView_new { fn new(self) -> QUndoView; } // proto: void QUndoView::QUndoView(QUndoGroup * group, QWidget * parent); impl<'a> /*trait*/ QUndoView_new for (&'a QUndoGroup, Option<&'a QWidget>) { fn new(self) -> QUndoView { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUndoViewC2EP10QUndoGroupP7QWidget()}; let ctysz: c_int = unsafe{QUndoView_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_ZN9QUndoViewC2EP10QUndoGroupP7QWidget(arg0, arg1)}; let rsthis = QUndoView{qbase: QListView::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QUndoView::setStack(QUndoStack * stack); impl /*struct*/ QUndoView { pub fn setStack<RetType, T: QUndoView_setStack<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setStack(self); // return 1; } } pub trait QUndoView_setStack<RetType> { fn setStack(self , rsthis: & QUndoView) -> RetType; } // proto: void QUndoView::setStack(QUndoStack * stack); impl<'a> /*trait*/ QUndoView_setStack<()> for (&'a QUndoStack) { fn setStack(self , rsthis: & QUndoView) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUndoView8setStackEP10QUndoStack()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QUndoView8setStackEP10QUndoStack(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QUndoView::setEmptyLabel(const QString & label); impl /*struct*/ QUndoView { pub fn setEmptyLabel<RetType, T: QUndoView_setEmptyLabel<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setEmptyLabel(self); // return 1; } } pub trait QUndoView_setEmptyLabel<RetType> { fn setEmptyLabel(self , rsthis: & QUndoView) -> RetType; } // proto: void QUndoView::setEmptyLabel(const QString & label); impl<'a> /*trait*/ QUndoView_setEmptyLabel<()> for (&'a QString) { fn setEmptyLabel(self , rsthis: & QUndoView) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUndoView13setEmptyLabelERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QUndoView13setEmptyLabelERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QUndoView::setCleanIcon(const QIcon & icon); impl /*struct*/ QUndoView { pub fn setCleanIcon<RetType, T: QUndoView_setCleanIcon<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setCleanIcon(self); // return 1; } } pub trait QUndoView_setCleanIcon<RetType> { fn setCleanIcon(self , rsthis: & QUndoView) -> RetType; } // proto: void QUndoView::setCleanIcon(const QIcon & icon); impl<'a> /*trait*/ QUndoView_setCleanIcon<()> for (&'a QIcon) { fn setCleanIcon(self , rsthis: & QUndoView) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUndoView12setCleanIconERK5QIcon()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QUndoView12setCleanIconERK5QIcon(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QUndoView::setGroup(QUndoGroup * group); impl /*struct*/ QUndoView { pub fn setGroup<RetType, T: QUndoView_setGroup<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setGroup(self); // return 1; } } pub trait QUndoView_setGroup<RetType> { fn setGroup(self , rsthis: & QUndoView) -> RetType; } // proto: void QUndoView::setGroup(QUndoGroup * group); impl<'a> /*trait*/ QUndoView_setGroup<()> for (&'a QUndoGroup) { fn setGroup(self , rsthis: & QUndoView) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUndoView8setGroupEP10QUndoGroup()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QUndoView8setGroupEP10QUndoGroup(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QUndoGroup * QUndoView::group(); impl /*struct*/ QUndoView { pub fn group<RetType, T: QUndoView_group<RetType>>(& self, overload_args: T) -> RetType { return overload_args.group(self); // return 1; } } pub trait QUndoView_group<RetType> { fn group(self , rsthis: & QUndoView) -> RetType; } // proto: QUndoGroup * QUndoView::group(); impl<'a> /*trait*/ QUndoView_group<QUndoGroup> for () { fn group(self , rsthis: & QUndoView) -> QUndoGroup { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QUndoView5groupEv()}; let mut ret = unsafe {C_ZNK9QUndoView5groupEv(rsthis.qclsinst)}; let mut ret1 = QUndoGroup::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: const QMetaObject * QUndoView::metaObject(); impl /*struct*/ QUndoView { pub fn metaObject<RetType, T: QUndoView_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QUndoView_metaObject<RetType> { fn metaObject(self , rsthis: & QUndoView) -> RetType; } // proto: const QMetaObject * QUndoView::metaObject(); impl<'a> /*trait*/ QUndoView_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QUndoView) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QUndoView10metaObjectEv()}; let mut ret = unsafe {C_ZNK9QUndoView10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QUndoStack * QUndoView::stack(); impl /*struct*/ QUndoView { pub fn stack<RetType, T: QUndoView_stack<RetType>>(& self, overload_args: T) -> RetType { return overload_args.stack(self); // return 1; } } pub trait QUndoView_stack<RetType> { fn stack(self , rsthis: & QUndoView) -> RetType; } // proto: QUndoStack * QUndoView::stack(); impl<'a> /*trait*/ QUndoView_stack<QUndoStack> for () { fn stack(self , rsthis: & QUndoView) -> QUndoStack { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QUndoView5stackEv()}; let mut ret = unsafe {C_ZNK9QUndoView5stackEv(rsthis.qclsinst)}; let mut ret1 = QUndoStack::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QIcon QUndoView::cleanIcon(); impl /*struct*/ QUndoView { pub fn cleanIcon<RetType, T: QUndoView_cleanIcon<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cleanIcon(self); // return 1; } } pub trait QUndoView_cleanIcon<RetType> { fn cleanIcon(self , rsthis: & QUndoView) -> RetType; } // proto: QIcon QUndoView::cleanIcon(); impl<'a> /*trait*/ QUndoView_cleanIcon<QIcon> for () { fn cleanIcon(self , rsthis: & QUndoView) -> QIcon { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QUndoView9cleanIconEv()}; let mut ret = unsafe {C_ZNK9QUndoView9cleanIconEv(rsthis.qclsinst)}; let mut ret1 = QIcon::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QString QUndoView::emptyLabel(); impl /*struct*/ QUndoView { pub fn emptyLabel<RetType, T: QUndoView_emptyLabel<RetType>>(& self, overload_args: T) -> RetType { return overload_args.emptyLabel(self); // return 1; } } pub trait QUndoView_emptyLabel<RetType> { fn emptyLabel(self , rsthis: & QUndoView) -> RetType; } // proto: QString QUndoView::emptyLabel(); impl<'a> /*trait*/ QUndoView_emptyLabel<QString> for () { fn emptyLabel(self , rsthis: & QUndoView) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QUndoView10emptyLabelEv()}; let mut ret = unsafe {C_ZNK9QUndoView10emptyLabelEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QUndoView::QUndoView(QWidget * parent); impl<'a> /*trait*/ QUndoView_new for (Option<&'a QWidget>) { fn new(self) -> QUndoView { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUndoViewC2EP7QWidget()}; let ctysz: c_int = unsafe{QUndoView_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_ZN9QUndoViewC2EP7QWidget(arg0)}; let rsthis = QUndoView{qbase: QListView::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QUndoView::~QUndoView(); impl /*struct*/ QUndoView { pub fn free<RetType, T: QUndoView_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QUndoView_free<RetType> { fn free(self , rsthis: & QUndoView) -> RetType; } // proto: void QUndoView::~QUndoView(); impl<'a> /*trait*/ QUndoView_free<()> for () { fn free(self , rsthis: & QUndoView) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUndoViewD2Ev()}; unsafe {C_ZN9QUndoViewD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QUndoView::QUndoView(QUndoStack * stack, QWidget * parent); impl<'a> /*trait*/ QUndoView_new for (&'a QUndoStack, Option<&'a QWidget>) { fn new(self) -> QUndoView { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUndoViewC2EP10QUndoStackP7QWidget()}; let ctysz: c_int = unsafe{QUndoView_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_ZN9QUndoViewC2EP10QUndoStackP7QWidget(arg0, arg1)}; let rsthis = QUndoView{qbase: QListView::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // <= body block end
use super::*; #[test] fn with_atom_right_returns_true() { with_right_returns_true(|mut _process| Atom::str_to_term("right")); } #[test] fn with_false_right_returns_true() { with_right_returns_true(|_| false.into()); } #[test] fn with_true_right_returns_true() { with_right_returns_true(|_| true.into()); } #[test] fn with_local_reference_right_returns_true() { with_right_returns_true(|process| process.next_reference()); } #[test] fn with_empty_list_right_returns_true() { with_right_returns_true(|_| Term::NIL); } #[test] fn with_list_right_returns_true() { with_right_returns_true(|process| process.cons(process.integer(0), process.integer(1))); } #[test] fn with_small_integer_right_returns_true() { with_right_returns_true(|process| process.integer(1)) } #[test] fn with_big_integer_right_returns_true() { with_right_returns_true(|process| process.integer(SmallInteger::MAX_VALUE + 1)) } #[test] fn with_float_right_returns_true() { with_right_returns_true(|process| process.float(1.0)); } #[test] fn with_local_pid_right_returns_true() { with_right_returns_true(|_| Pid::make_term(0, 1).unwrap()); } #[test] fn with_external_pid_right_returns_true() { with_right_returns_true(|process| process.external_pid(external_arc_node(), 2, 3).unwrap()); } #[test] fn with_tuple_right_returns_true() { with_right_returns_true(|process| process.tuple_from_slice(&[])); } #[test] fn with_map_is_right_returns_true() { with_right_returns_true(|process| process.map_from_slice(&[])); } #[test] fn with_heap_binary_right_returns_true() { with_right_returns_true(|process| process.binary_from_bytes(&[])); } #[test] fn with_subbinary_right_returns_true() { with_right_returns_true(|process| bitstring!(1 :: 1, &process)); } fn with_right_returns_true<R>(right: R) where R: FnOnce(&Process) -> Term, { with_process(|process| { let left = true.into(); let right = right(&process); assert_eq!(result(left, right), Ok(left)); }); }
macro_rules! force_trailing_comma { [$($x:expr,)*] => (vec![$($x),*]) } macro_rules! forbid_trailing_comma { [$($x:expr),*] => (vec![$($x),*]) } macro_rules! allow_both { [$($x:expr,)*] => { force_trailing_comma![$($x,)*] }; [$($x:expr),*] => { forbid_trailing_comma![$($x),*] }; } fn main() { force_trailing_comma![1,]; // force_trailing_comma![1]; // compile error // forbid_trailing_comma![1,]; // compile error forbid_trailing_comma![1]; allow_both![1,]; allow_both![1]; }
pub mod api; pub mod tls_mitm; pub mod tls_check; pub mod plaintext; pub mod tcp_hijack; pub mod dns_hijack; pub mod packet_logger;
use std::{num::ParseIntError, ops::RangeInclusive}; pub const INPUT: &str = include_str!("../input.txt"); type ParseResult = Result<Vec<(RangeInclusive<u8>, RangeInclusive<u8>)>, ParseIntError>; pub fn parse_input(input: &str) -> ParseResult { let parts = input.trim().split(['\n', ',', '-']); let numbers = parts.map(str::parse::<u8>).collect::<Result<Vec<_>, _>>()?; let ranges = numbers .chunks_exact(4) .map(|chunk| (chunk[0]..=chunk[1], chunk[2]..=chunk[3])) .collect(); Ok(ranges) } pub fn part_one(pairs: &[(RangeInclusive<u8>, RangeInclusive<u8>)]) -> usize { pairs .iter() .filter(|(a, b)| { b.contains(a.start()) && b.contains(a.end()) || a.contains(b.start()) && a.contains(b.end()) }) .count() } pub fn part_two(pairs: &[(RangeInclusive<u8>, RangeInclusive<u8>)]) -> usize { pairs .iter() .filter(|(a, b)| { b.contains(a.start()) || b.contains(a.end()) || a.contains(b.start()) || a.contains(b.end()) }) .count() } #[cfg(test)] mod test { use super::*; #[test] fn test_part_one() { let pairs = parse_input(INPUT).unwrap(); assert_eq!(part_one(&pairs), 441); } #[test] fn test_part_two() { let pairs = parse_input(INPUT).unwrap(); assert_eq!(part_two(&pairs), 861); } }
// xfail-stage1 // xfail-stage2 // xfail-stage3 // Create a task that is supervised by another task, // join the supervised task from the supervising task, // then fail the supervised task. The supervised task // will kill the supervising task, waking it up. The // supervising task no longer needs to be wakened when // the supervised task exits. fn supervised() { // Yield to make sure the supervisor joins before we // fail. This is currently not needed because the supervisor // runs first, but I can imagine that changing. yield; fail; } fn supervisor() { let task t = spawn "supervised" supervised(); join t; } fn main() { // Start the test in another domain so that // the process doesn't return a failure status as a result // of the main task being killed. let task dom2 = spawn thread "supervisor" supervisor(); join dom2; } // Local Variables: // mode: rust; // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'"; // End:
/* * @lc app=leetcode id=3 lang=rust * * [3] Longest Substring Without Repeating Characters */ impl Solution { pub fn length_of_longest_substring(s: String) -> i32 { let mut counts = [0; 256]; let mut bad = 0; let mut i = 0; let mut j = 0; let s = s.as_bytes(); while j < s.len() { counts[s[j] as usize] += 1; if counts[s[j] as usize] > 1 { bad += 1; } j += 1; if bad > 0 { if counts[s[i] as usize] > 1 { bad -= 1; } counts[s[i] as usize] -= 1; i += 1; } } return (j - i) as i32; } }