text
stringlengths
8
4.13M
use ggez::{GameResult, Context}; use ggez::graphics::{Font, Point2, Text, Vector2}; use globals::*; use hex::{DirectionIndex, HexPoint}; use text::*; #[derive(Debug)] pub struct Assets { lap1_a: Text, lap1_b: Text, lap2: Text, lap3: Text, win_a: Text, win_b: Text, lose_a: Text, lose_b: Text, } pub fn load_assets(ctx: &mut Context, font: &Font) -> GameResult<Assets> { Ok( Assets { lap1_a: Text::new(ctx, "First to complete", &font)?, lap1_b: Text::new(ctx, "3 laps wins!", &font)?, lap2: Text::new(ctx, "Second lap!", &font)?, lap3: Text::new(ctx, "Final lap!", &font)?, win_a: Text::new(ctx, "You win!", &font)?, win_b: Text::new(ctx, "Press ESC to quit.", &font)?, lose_a: Text::new(ctx, "You lose :(", &font)?, lose_b: Text::new(ctx, "Press R to try again.", &font)?, } ) } pub fn draw_lap_message(ctx: &mut Context, assets: &Assets, lap: Lap) -> GameResult<()> { let center = Point2::new( WINDOW_WIDTH as f32 / 2.0, WINDOW_HEIGHT as f32 / 2.0 - 13.0, ); match lap { 0 => { draw_centered_text(ctx, &assets.lap1_a, center, 0.0)?; draw_centered_text(ctx, &assets.lap1_b, center + Vector2::new(0.0, 20.0), 0.0)?; Ok(()) }, 1 => draw_centered_text(ctx, &assets.lap2, center, 0.0), 2 => draw_centered_text(ctx, &assets.lap3, center, 0.0), _ => { draw_centered_text(ctx, &assets.win_a, center - Vector2::new(0.0, 20.0), 0.0)?; draw_centered_text(ctx, &assets.win_b, center, 0.0)?; Ok(()) }, } } pub fn draw_loss_message(ctx: &mut Context, assets: &Assets) -> GameResult<()> { let center = Point2::new( WINDOW_WIDTH as f32 / 2.0, WINDOW_HEIGHT as f32 / 2.0 - 13.0, ); draw_centered_text(ctx, &assets.lose_a, center - Vector2::new(0.0, 20.0), 0.0)?; draw_centered_text(ctx, &assets.lose_b, center, 0.0)?; Ok(()) } // 0 is from right up to but not including the first checkpoint, // 1 is from the first checkpoint up to but not including the second, etc. // always in the range 0..6 pub type Section = i32; pub fn point_to_section(hex_point: HexPoint) -> Section { if hex_point.q == 0 { if hex_point.r < 0 { 2 } else { 5 } } else if hex_point.q > 0 { if hex_point.r > 0 { 5 } else if -hex_point.r < hex_point.q { 0 } else { 1 } } else { if hex_point.r < 0 { 2 } else if -hex_point.q > hex_point.r { 3 } else { 4 } } } pub fn at_checkpoint(hex_point: HexPoint) -> bool { hex_point.q == 0 || hex_point.r == 0 || hex_point.q == -hex_point.r } pub fn forward(hex_point: HexPoint) -> DirectionIndex { let section = point_to_section(hex_point); (section + 2) % 6 } #[allow(dead_code)] pub fn backward(hex_point: HexPoint) -> DirectionIndex { let mut section = point_to_section(hex_point); if at_checkpoint(hex_point) { section = (section + 5) % 6; } (section + 5) % 6 } // same as Section, but increases beyond 5 when completing laps. pub type Checkpoint = i32; pub fn checkpoint_to_section(checkpoint: Checkpoint) -> Section { if checkpoint >= 0 { checkpoint % 6 } else { 5 + (checkpoint + 1) % 6 } } pub fn update_checkpoint(old_checkpoint: Checkpoint, new_hex_point: HexPoint) -> Checkpoint { let old_section = checkpoint_to_section(old_checkpoint); let new_section = point_to_section(new_hex_point); if new_section == (old_section + 1) % 6 { old_checkpoint + 1 } else if new_section == (old_section + 2) % 6 { old_checkpoint + 2 } else if new_section == (old_section + 5) % 6 { old_checkpoint - 1 } else if new_section == (old_section + 4) % 6 { old_checkpoint - 2 } else { old_checkpoint } } // number of _completed_ laps, so 0 during the first lap, 1 during the second, etc. // negative if the racer drives the wrong way. pub type Lap = i32; #[allow(dead_code)] pub fn checkpoint_to_lap(checkpoint: Checkpoint) -> Lap { if checkpoint >= 0 { checkpoint / 6 } else { (checkpoint + 1) / 6 - 1 } }
use wasm_bindgen::prelude::*; /// Arrow Schema representing a Parquet file. #[derive(Debug, Clone)] #[wasm_bindgen] pub struct ArrowSchema(arrow2::datatypes::Schema); #[wasm_bindgen] impl ArrowSchema { /// Clone this struct in wasm memory. #[wasm_bindgen] pub fn copy(&self) -> Self { ArrowSchema(self.0.clone()) } } impl From<arrow2::datatypes::Schema> for ArrowSchema { fn from(schema: arrow2::datatypes::Schema) -> Self { ArrowSchema(schema) } } impl From<ArrowSchema> for arrow2::datatypes::Schema { fn from(meta: ArrowSchema) -> arrow2::datatypes::Schema { meta.0 } }
// 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 std::cmp::max; use std::sync::Arc; use common_catalog::table::Table; use common_catalog::table_context::TableContext; use common_exception::Result; use common_expression::types::StringType; use common_expression::utils::FromData; use common_expression::DataBlock; use common_expression::TableDataType; use common_expression::TableField; use common_expression::TableSchemaRefExt; use common_meta_app::schema::TableIdent; use common_meta_app::schema::TableInfo; use common_meta_app::schema::TableMeta; use crate::SyncOneBlockSystemTable; use crate::SyncSystemTable; pub struct BuildOptionsTable { table_info: TableInfo, } impl SyncSystemTable for BuildOptionsTable { const NAME: &'static str = "system.build_options"; fn get_table_info(&self) -> &TableInfo { &self.table_info } fn get_full_data(&self, _: Arc<dyn TableContext>) -> Result<DataBlock> { let mut cargo_features: Vec<Vec<u8>>; if let Some(features) = option_env!("VERGEN_CARGO_FEATURES") { cargo_features = features .split_terminator(',') .map(|x| x.trim().as_bytes().to_vec()) .collect(); } else { cargo_features = vec!["not available".as_bytes().to_vec()]; } let mut target_features: Vec<Vec<u8>> = env!("DATABEND_CARGO_CFG_TARGET_FEATURE") .split_terminator(',') .map(|x| x.trim().as_bytes().to_vec()) .collect(); let length = max(cargo_features.len(), target_features.len()); cargo_features.resize(length, "".as_bytes().to_vec()); target_features.resize(length, "".as_bytes().to_vec()); Ok(DataBlock::new_from_columns(vec![ StringType::from_data(cargo_features), StringType::from_data(target_features), ])) } } impl BuildOptionsTable { pub fn create(table_id: u64) -> Arc<dyn Table> { let schema = TableSchemaRefExt::create(vec![ TableField::new("cargo_features", TableDataType::String), TableField::new("target_features", TableDataType::String), ]); let table_info = TableInfo { desc: "'system'.'build_options'".to_string(), name: "build_options".to_string(), ident: TableIdent::new(table_id, 0), meta: TableMeta { schema, engine: "SystemBuildOptions".to_string(), ..Default::default() }, ..Default::default() }; SyncOneBlockSystemTable::create(BuildOptionsTable { table_info }) } }
// Copyright 2018 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 carnelian::{ make_message, set_node_color, AnimationMode, App, AppAssistant, Color, ViewAssistant, ViewAssistantContext, ViewAssistantPtr, ViewKey, ViewMessages, }; use failure::{Error, ResultExt}; use fidl::endpoints::{RequestStream, ServiceMarker}; use fidl_fidl_examples_echo::{EchoMarker, EchoRequest, EchoRequestStream}; use fidl_fuchsia_ui_input::{KeyboardEvent, KeyboardEventPhase}; use fuchsia_async as fasync; use fuchsia_scenic::{Rectangle, RoundedRectangle, SessionPtr, ShapeNode}; use fuchsia_zircon::{ClockId, Time}; use futures::prelude::*; use std::f32::consts::PI; const BACKGROUND_Z: f32 = 0.0; const SQUARE_Z: f32 = BACKGROUND_Z - 8.0; struct SpinningSquareAppAssistant; impl AppAssistant for SpinningSquareAppAssistant { fn setup(&mut self) -> Result<(), Error> { Ok(()) } fn create_view_assistant( &mut self, _: ViewKey, session: &SessionPtr, ) -> Result<ViewAssistantPtr, Error> { Ok(Box::new(SpinningSquareViewAssistant { background_node: ShapeNode::new(session.clone()), spinning_square_node: ShapeNode::new(session.clone()), rounded: false, start: Time::get(ClockId::Monotonic), })) } /// Return the list of names of services this app wants to provide fn outgoing_services_names(&self) -> Vec<&'static str> { [EchoMarker::NAME].to_vec() } /// Handle a request to connect to a service provided by this app fn handle_service_connection_request( &mut self, _service_name: &str, channel: fasync::Channel, ) -> Result<(), Error> { Self::create_echo_server(channel, false); Ok(()) } } impl SpinningSquareAppAssistant { fn create_echo_server(channel: fasync::Channel, quiet: bool) { fasync::spawn_local( async move { let mut stream = EchoRequestStream::from_channel(channel); while let Some(EchoRequest::EchoString { value, responder }) = stream.try_next().await.context("error running echo server")? { if !quiet { println!("Spinning Square received echo request for string {:?}", value); } responder .send(value.as_ref().map(|s| &**s)) .context("error sending response")?; if !quiet { println!("echo response sent successfully"); } } Ok(()) } .unwrap_or_else(|e: failure::Error| eprintln!("{:?}", e)), ); } } struct SpinningSquareViewAssistant { background_node: ShapeNode, spinning_square_node: ShapeNode, rounded: bool, start: Time, } impl ViewAssistant for SpinningSquareViewAssistant { fn setup(&mut self, context: &ViewAssistantContext) -> Result<(), Error> { set_node_color( context.session(), &self.background_node, &Color { r: 0xb7, g: 0x41, b: 0x0e, a: 0xff }, ); set_node_color( context.session(), &self.spinning_square_node, &Color { r: 0xff, g: 0x00, b: 0xff, a: 0xff }, ); context.root_node().add_child(&self.background_node); context.root_node().add_child(&self.spinning_square_node); Ok(()) } fn update(&mut self, context: &ViewAssistantContext) -> Result<(), Error> { const SPEED: f32 = 0.25; const SECONDS_PER_NANOSECOND: f32 = 1e-9; let center_x = context.size.width * 0.5; let center_y = context.size.height * 0.5; self.background_node.set_shape(&Rectangle::new( context.session().clone(), context.size.width, context.size.height, )); self.background_node.set_translation(center_x, center_y, BACKGROUND_Z); let square_size = context.size.width.min(context.size.height) * 0.6; let t = ((context.presentation_time.into_nanos() - self.start.into_nanos()) as f32 * SECONDS_PER_NANOSECOND * SPEED) % 1.0; let angle = t * PI * 2.0; if self.rounded { let corner_radius = (square_size / 4.0).ceil(); self.spinning_square_node.set_shape(&RoundedRectangle::new( context.session().clone(), square_size, square_size, corner_radius, corner_radius, corner_radius, corner_radius, )); } else { self.spinning_square_node.set_shape(&Rectangle::new( context.session().clone(), square_size, square_size, )); } self.spinning_square_node.set_translation(center_x, center_y, SQUARE_Z); self.spinning_square_node.set_rotation(0.0, 0.0, (angle * 0.5).sin(), (angle * 0.5).cos()); Ok(()) } fn initial_animation_mode(&mut self) -> AnimationMode { return AnimationMode::EveryFrame; } fn handle_keyboard_event( &mut self, context: &mut ViewAssistantContext, keyboard_event: &KeyboardEvent, ) -> Result<(), Error> { if keyboard_event.code_point == ' ' as u32 && keyboard_event.phase == KeyboardEventPhase::Pressed { self.rounded = !self.rounded; } context.queue_message(make_message(ViewMessages::Update)); Ok(()) } } fn main() -> Result<(), Error> { let assistant = SpinningSquareAppAssistant {}; App::run(Box::new(assistant)) }
fn fib(n: u32) -> u32 { let mut a = 1; let mut b = 1; for _ in 1..n { let t = a; a += b; b = t; } return a; } #[test] fn fib_values() { let expected = vec![1, 1, 2, 3, 5, 8, 13]; let actual = (0..7).map(fib).collect::<Vec<_>>(); assert_eq!(actual, expected); } fn main() { println!("Hello, world!"); }
//required in order for near_bindgen macro to work outside of lib.rs use crate::interface::ContractFinancials; use crate::*; use crate::{ domain::RedeemLock, interface::{contract_state::ContractState, AccountManagement}, interface::{Operator, StakingService}, }; use near_sdk::near_bindgen; #[near_bindgen] impl Operator for Contract { fn operator_id(&self) -> AccountId { self.operator_id.clone() } fn contract_state(&self) -> ContractState { ContractState { block: domain::BlockTimeHeight::from_env().into(), config_change_block_height: self.config_change_block_height.into(), staking_pool_id: self.staking_pool_id.clone(), registered_accounts_count: self.total_registered_accounts().clone(), total_unstaked_near: self.total_near.into(), total_stake_supply: self.total_stake.into(), stake_token_value: self.stake_token_value.into(), batch_id_sequence: self.batch_id_sequence.into(), stake_batch: self.stake_batch.map(interface::StakeBatch::from), next_stake_batch: self.next_stake_batch.map(interface::StakeBatch::from), redeem_stake_batch: self.redeem_stake_batch.map(|batch| { interface::RedeemStakeBatch::from( batch, self.redeem_stake_batch_receipt(batch.id().into()), ) }), next_redeem_stake_batch: self.next_redeem_stake_batch.map(|batch| { interface::RedeemStakeBatch::from( batch, self.redeem_stake_batch_receipt(batch.id().into()), ) }), stake_batch_lock: self.stake_batch_lock.map(Into::into), redeem_stake_batch_lock: self.redeem_stake_batch_lock, balances: self.balances(), initial_storage_usage: self.contract_initial_storage_usage.into(), storage_usage_growth: (env::storage_usage() - self.contract_initial_storage_usage.value()) .into(), } } fn config(&self) -> interface::Config { self.config.into() } fn reset_config_default(&mut self) -> interface::Config { self.assert_predecessor_is_operator(); self.config = Config::default(); self.config.into() } fn update_config(&mut self, config: interface::Config) -> interface::Config { self.assert_predecessor_is_operator(); self.config.merge(config); self.config_change_block_height = env::block_index().into(); self.config.into() } fn force_update_config(&mut self, config: interface::Config) -> interface::Config { self.assert_predecessor_is_operator(); self.config.force_merge(config); self.config_change_block_height = env::block_index().into(); self.config.into() } fn clear_stake_lock(&mut self) { self.assert_predecessor_is_self_or_operator(); // we only want to release the stake batch lock if the batch funds have not transferred over // to the staking pool let unlock = match self.stake_batch_lock { Some(StakeLock::Staking) => true, Some(StakeLock::RefreshingStakeTokenValue) => true, _ => false, }; if unlock { self.stake_batch_lock = None; } } fn clear_redeem_lock(&mut self) { self.assert_predecessor_is_self_or_operator(); if let Some(RedeemLock::Unstaking) = self.redeem_stake_batch_lock { self.redeem_stake_batch_lock = None } } } #[cfg(test)] mod test { use super::*; use crate::test_utils::*; use near_sdk::{serde_json, testing_env, MockedBlockchain}; #[test] fn release_run_redeem_stake_batch_unstaking_lock_with_unstaking_lock() { let mut context = TestContext::new(); let contract = &mut context.contract; let mut context = context.context.clone(); contract.redeem_stake_batch_lock = Some(RedeemLock::Unstaking); context.predecessor_account_id = context.current_account_id.clone(); testing_env!(context); contract.clear_redeem_lock(); assert!(contract.redeem_stake_batch_lock.is_none()); } #[test] fn release_run_redeem_stake_batch_unstaking_lock_invoked_by_operator() { let mut context = TestContext::new(); let contract = &mut context.contract; let mut context = context.context.clone(); contract.redeem_stake_batch_lock = Some(RedeemLock::Unstaking); context.predecessor_account_id = contract.operator_id.clone(); testing_env!(context); contract.clear_redeem_lock(); assert!(contract.redeem_stake_batch_lock.is_none()); } #[test] fn release_run_redeem_stake_batch_unstaking_lock_with_pending_withdrawal_lock() { // Arrange let mut context = TestContext::new(); let contract = &mut context.contract; let mut context = context.context.clone(); contract.redeem_stake_batch_lock = Some(RedeemLock::PendingWithdrawal); context.predecessor_account_id = context.current_account_id.clone(); testing_env!(context.clone()); // Act contract.clear_redeem_lock(); // Assert assert_eq!( contract.redeem_stake_batch_lock, Some(RedeemLock::PendingWithdrawal) ); } #[test] #[should_panic(expected = "contract call is only allowed internally or by an operator account")] fn release_run_redeem_stake_batch_unstaking_lock_access_denied() { // Arrange let mut context = TestContext::new(); let contract = &mut context.contract; // Act contract.clear_redeem_lock(); } #[test] fn contract_state_invoked_by_operator() { // Arrange let mut context = TestContext::new(); let contract = &mut context.contract; let mut context = context.context.clone(); const CONTRACT_STATE_STORAGE_OVERHEAD: u64 = 45; context.storage_usage += contract.try_to_vec().unwrap().len() as u64 + CONTRACT_STATE_STORAGE_OVERHEAD; context.predecessor_account_id = contract.operator_id.clone(); testing_env!(context.clone()); let state = contract.contract_state(); println!("{}", serde_json::to_string_pretty(&state).unwrap()); } }
use crate::static_kv::mod_test; pub mod static_kv { pub fn mod_test() { println!("test") } } fn main() { mod_test(); println!("Hello, world!"); }
use std::collections::HashMap; use crate::types::{Expression, ExpressionType, ProgramError, SourceCodeLocation, Statement, StatementType, Pass}; pub struct Resolver<'a> { check_used: bool, scopes: Vec<HashMap<&'a str, bool>>, uses: Vec<HashMap<&'a str, usize>>, locations: Vec<HashMap<&'a str, &'a SourceCodeLocation<'a>>>, locals: HashMap<usize, usize>, } impl<'a> Resolver<'a> { pub fn new() -> Resolver<'a> { Resolver { check_used: true, locals: HashMap::default(), locations: vec![HashMap::default()], scopes: vec![HashMap::default()], uses: vec![HashMap::default()], } } pub fn new_without_check_used() -> Resolver<'a> { Resolver { check_used: false, locals: HashMap::default(), locations: vec![HashMap::default()], scopes: vec![HashMap::default()], uses: vec![HashMap::default()], } } fn push_scope(&mut self, scope: HashMap<&'a str, bool>) { self.scopes.push(scope); self.uses.push(HashMap::default()); self.locations.push(HashMap::default()); } fn dry_pop_scope(&mut self) { self.scopes.pop(); self.uses.pop(); self.locations.pop(); } fn pop_scope(&mut self) -> Result<(), Vec<ProgramError<'a>>> { self.scopes.pop(); if let (Some(mut variables), Some(locations)) = (self.uses.pop(), self.locations.pop()) { variables.insert("this", 1); let errors: Vec<ProgramError<'a>> = variables .iter() .filter(|(_, uses)| self.check_used && **uses == 0) .map(|p| ProgramError { message: format!("Variable `{}` never used.", *p.0), location: locations[*p.0].clone(), }) .collect(); if !errors.is_empty() { return Err(errors); } } Ok(()) } fn declare( &mut self, name: &'a str, location: &'a SourceCodeLocation<'a>, ) -> Result<(), ProgramError<'a>> { if let Some(s) = self.scopes.last_mut() { if s.contains_key(name) { return Err(ProgramError { message: format!("Variable `{}` already declared in this scope!", name), location: location.clone(), }); } s.insert(name, false); if let Some(locations) = self.locations.last_mut() { locations.insert(name, location); } if let Some(uses) = self.uses.last_mut() { uses.insert(name, 0); } } Ok(()) } fn define(&mut self, name: &'a str) { if let Some(s) = self.scopes .iter_mut() .rev() .find(|s| s.contains_key(name)) { s.insert(name, true); } } fn resolve_local(&mut self, expression: &Expression<'a>, name: &'a str) -> Result<(), ProgramError<'a>> { if let Some((i, scope)) = self .scopes .iter() .enumerate() .rev() .find(|(_, s)| s.contains_key(name)) { if !scope[name] { return Err(ProgramError { message: format!("`{}` used without being initialized.", name), location: expression.location.clone(), }) } let new_uses = self.uses[i][name] + 1; self.uses[i].insert(name, new_uses); self.locals.insert(expression.id(), i); } Ok(()) } fn resolve_functions( &mut self, methods: &'a [Box<Statement<'a>>], check_defined: bool, ) -> Result<(), Vec<ProgramError<'a>>> { methods .iter() .map(|s| { if let StatementType::FunctionDeclaration { name, .. } = &s.statement_type { if !check_defined { self.scopes.last_mut().map(|h| h.remove(*name)); } } let r = self.pass(s); if let StatementType::FunctionDeclaration { name, .. } = &s.statement_type { self.uses.last_mut().unwrap().insert(name, 1); } r }) .collect::<Result<_, Vec<ProgramError<'a>>>>()?; Ok(()) } fn resolve_function<'b>( &mut self, arguments: &'a [&'a str], context_variables: Option<&'a [&'a str]>, body: &'b [&'a Statement<'a>], location: &'a SourceCodeLocation<'a>, ) -> Result<(), Vec<ProgramError<'a>>> { self.push_scope(HashMap::default()); for arg in arguments { self.declare(arg, location).map_err(|e| vec![e])?; self.define(arg); } if let Some(context_variables) = context_variables { for arg in context_variables { self.declare(arg, location).map_err(|e| vec![e])?; self.define(arg); } } body.iter() .map(|s| self.pass(s)) .collect::<Result<Vec<()>, Vec<ProgramError>>>()?; self.pop_scope()?; Ok(()) } } impl<'a> Pass<'a, HashMap<usize, usize>> for Resolver<'a> { fn run(&mut self, ss: &'a [Statement<'a>]) -> Result<HashMap<usize, usize>, Vec<ProgramError<'a>>> { ss.iter() .filter(|s| s.is_variable_declaration()) .map(|s| { if let StatementType::VariableDeclaration { name, expression } = &s.statement_type { self.declare(name, &s.location) .map_err(|e| vec![e])?; if expression.is_some() { self.define(name); } } Ok(()) }) .collect::<Result<Vec<()>, Vec<ProgramError<'a>>>>()?; ss.iter() .map(|s| self.pass(&s)) .collect::<Result<Vec<()>, Vec<ProgramError<'a>>>>()?; Ok(self.locals.clone()) } fn pass_module( &mut self, name: &'a str, statements: &'a [Box<Statement<'a>>], statement: &'a Statement<'a>, ) -> Result<(), Vec<ProgramError<'a>>> { self.declare(name, &statement.location) .map_err(|e| vec![e])?; self.define(name); self.push_scope(HashMap::default()); statements.iter() .map(|s| self.pass(&s)) .collect::<Result<Vec<()>, Vec<ProgramError>>>()?; self.dry_pop_scope(); Ok(()) } fn pass_import( &mut self, name: &'a str, statement: &'a Statement<'a>, ) -> Result<(), Vec<ProgramError<'a>>> { self.declare(name, &statement.location) .map_err(|e| vec![e])?; self.define(name); Ok(()) } fn pass_block(&mut self, body: &'a [Box<Statement<'a>>], _statement_id: usize) -> Result<(), Vec<ProgramError<'a>>> { self.push_scope(HashMap::default()); body.iter() .map(|s| self.pass(&s)) .collect::<Result<Vec<()>, Vec<ProgramError>>>()?; self.pop_scope() } fn pass_variable_declaration( &mut self, name: &'a str, expression: &'a Option<Expression<'a>>, statement: &'a Statement<'a>, ) -> Result<(), Vec<ProgramError<'a>>> { if self.scopes.len() != 1 { self.declare(name, &statement.location) .map_err(|e| vec![e])?; } if let Some(e) = expression { self.pass_expression(e)?; if self.scopes.len() != 1 { self.define(name); } } Ok(()) } fn pass_class_declaration( &mut self, name: &'a str, properties: &'a [Box<Statement<'a>>], methods: &'a [Box<Statement<'a>>], static_methods: &'a [Box<Statement<'a>>], setters: &'a [Box<Statement<'a>>], getters: &'a [Box<Statement<'a>>], superclass: &'a Option<Expression<'a>>, statement: &'a Statement<'a>, ) -> Result<(), Vec<ProgramError<'a>>> { self.declare(name, &statement.location) .map_err(|e| vec![e])?; if let Some(e) = superclass { if let ExpressionType::VariableLiteral { identifier } = &e.expression_type { if *identifier == name { return Err(vec![ProgramError { message: "A class cannot inherit from itself.".to_owned(), location: statement.location.clone(), }]); } self.resolve_local(e, identifier) .map_err(|e| vec![e])?; } else { self.pass_expression(e)?; } } self.push_scope(HashMap::default()); for property in properties { if let StatementType::VariableDeclaration { name, expression } = &property.statement_type { self.pass_variable_declaration(name, expression, property)?; } } self.resolve_functions(methods, true)?; self.resolve_functions(getters, false)?; self.resolve_functions(setters, false)?; self.resolve_functions(static_methods, true)?; self.pop_scope()?; self.define(&name); Ok(()) } fn pass_trait_declaration( &mut self, name: &'a str, statement: &'a Statement<'a>, ) -> Result<(), Vec<ProgramError<'a>>> { self.declare(name, &statement.location) .map_err(|e| vec![e])?; self.define(name); Ok(()) } fn pass_trait_implementation( &mut self, class_name: &'a Expression<'a>, trait_name: &'a Expression<'a>, methods: &'a [Box<Statement<'a>>], static_methods: &'a [Box<Statement<'a>>], setters: &'a [Box<Statement<'a>>], getters: &'a [Box<Statement<'a>>], _statement: &'a Statement<'a>, ) -> Result<(), Vec<ProgramError<'a>>> { self.pass_expression(class_name)?; self.pass_expression(trait_name)?; self.push_scope(HashMap::default()); self.resolve_functions(methods, true)?; self.resolve_functions(getters, false)?; self.resolve_functions(setters, false)?; self.resolve_functions(static_methods, true)?; self.pop_scope() } fn pass_function_declaration( &mut self, name: &'a str, arguments: &'a [&'a str], body: &'a [Box<Statement<'a>>], statement: &'a Statement<'a>, context_variables: &'a [&'a str], ) -> Result<(), Vec<ProgramError<'a>>> { self.declare(name, &statement.location) .map_err(|e| vec![e])?; self.define(name); let body = body.iter().map(|s| &(**s)).collect::<Vec<&Statement>>(); self.resolve_function( arguments, Some(context_variables), &body, &statement.location ) } fn pass_module_literal( &mut self, module: &'a str, field: &'a Expression<'a>, expression: &'a Expression<'a>, ) -> Result<(), Vec<ProgramError<'a>>> { self.pass_expression(field)?; self.resolve_local(expression, module).map_err(|e| vec![e]) } fn pass_variable_literal( &mut self, identifier: &'a str, expression: &'a Expression<'a>, ) -> Result<(), Vec<ProgramError<'a>>> { self.resolve_local(expression, identifier).map_err(|e| vec![e]) } fn pass_variable_assignment( &mut self, identifier: &'a str, expression_value: &'a Expression<'a>, expression: &'a Expression<'a>, ) -> Result<(), Vec<ProgramError<'a>>> { self.define(identifier); self.pass_expression(expression_value)?; self.resolve_local(expression, identifier).map_err(|e| vec![e]) } fn pass_anonymous_function( &mut self, arguments: &'a [&'a str], body: &'a [Statement<'a>], expression: &'a Expression<'a>, ) -> Result<(), Vec<ProgramError<'a>>> { let body = body.iter().collect::<Vec<&'a Statement>>(); self.resolve_function(arguments, None, &body, &expression.location) } }
fn main(){ //ベクトルを用意する let mut vec = vec![1,2,3]; // ベクトルの要素への参照を取り出す → i // ベクトルをイミュータブルに参照する for i in vec.iter(){ //すでにベクトルはイミュータブルに参照されているので、 //ここでベクトルを変更しようとするとエラーが発生(だってイミュータブルなものを書き換えようとしている) //実際、これを許すと無限ループになってしまう。 vec.push(i*2); } }
//! REST API of the node mod server; pub mod v0; pub use self::server::{Error, Server}; use std::sync::{Arc, Mutex, RwLock}; use crate::blockchain::{Blockchain, Branch}; use crate::fragment::Logs; use crate::secure::enclave::Enclave; use crate::settings::start::{Error as ConfigError, Rest}; use crate::stats_counter::StatsCounter; use crate::intercom::TransactionMsg; use crate::utils::async_msg::MessageBox; #[derive(Clone)] pub struct Context { pub stats_counter: StatsCounter, pub blockchain: Blockchain, pub blockchain_tip: Branch, pub transaction_task: Arc<Mutex<MessageBox<TransactionMsg>>>, pub logs: Arc<Mutex<Logs>>, pub server: Arc<RwLock<Option<Server>>>, pub enclave: Enclave, } pub fn start_rest_server(config: &Rest, context: Context) -> Result<Server, ConfigError> { let app_context = context.clone(); let server = Server::start(config.pkcs12.clone(), config.listen.clone(), move || { vec![v0::app(app_context.clone()).boxed()] })?; context .server .write() .unwrap_or_else(|e| e.into_inner()) .replace(server.clone()); Ok(server) }
use crate::headers::{Error, Header, HeaderName, HeaderValue}; use cookie::Cookie as HTTPCookie; use hyper::http::header; use itertools::Either; use std::iter; use std::ops::Deref; static COOKIE: &HeaderName = &header::COOKIE; static SET_COOKIE: &HeaderName = &header::SET_COOKIE; #[derive(Clone, Debug, PartialEq)] pub struct Cookie<'a>(pub Vec<HTTPCookie<'a>>); impl Header for Cookie<'_> { fn name() -> &'static HeaderName { COOKIE } fn decode<'i, I>(values: &mut I) -> Result<Self, Error> where I: Iterator<Item = &'i HeaderValue>, { values .map(|h| h.to_str().map_err(|_| Error::invalid())) .flat_map(|h| match h { Ok(v) => Either::Left(v.split(';').map(|s| Ok(s.trim()))), Err(e) => Either::Right(iter::once(Err(e))), }) .map(|item| { item.and_then(|s| { HTTPCookie::parse(s) .map_err(|_| Error::invalid()) .map(|c| c.into_owned()) }) }) .collect::<Result<Vec<_>, _>>() .map(Cookie) } fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) { let cookies = self.iter().map(|c| c.to_string()).collect::<Vec<_>>(); values.extend(iter::once(cookies.join("; ").parse().unwrap())) } } impl<'a> Deref for Cookie<'a> { type Target = Vec<HTTPCookie<'a>>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Clone, Debug, PartialEq)] pub struct SetCookie<'a>(pub HTTPCookie<'a>); impl Header for SetCookie<'_> { fn name() -> &'static HeaderName { SET_COOKIE } fn decode<'i, I>(values: &mut I) -> Result<Self, Error> where Self: Sized, I: Iterator<Item = &'i HeaderValue>, { values .next() .and_then(|v| HTTPCookie::parse(v.to_str().ok()?.to_string()).ok()) .map(SetCookie) .ok_or_else(Error::invalid) } fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) { values.extend(iter::once(self.0.to_string().parse().unwrap())) } } #[cfg(test)] mod test { use super::{Cookie, HTTPCookie, SetCookie}; use crate::headers::{Header, HeaderMapExt, HeaderValue}; use crate::test::headers::encode; use hyper::http::HeaderMap; #[test] fn test_encode_single_cookie() { let cookie = HTTPCookie::new("name", "value"); assert_eq!(encode(Cookie(vec![cookie])).to_str().unwrap(), "name=value") } #[test] fn test_encode_multiple_cookies() { assert_eq!( encode(Cookie(vec![ HTTPCookie::new("first", "value"), HTTPCookie::new("second", "another") ])) .to_str() .unwrap(), "first=value; second=another" ) } #[test] fn test_decode_single_cookie() { let mut headers = HeaderMap::new(); headers.insert(Cookie::name(), "name=value".parse().unwrap()); let header = headers.typed_get::<Cookie>().unwrap(); assert_eq!(header, Cookie(vec![HTTPCookie::new("name", "value")])) } #[test] fn test_decode_multiple_cookies() { let mut headers = HeaderMap::new(); headers.insert( Cookie::name(), "first=value; second=another".parse().unwrap(), ); let header = headers.typed_get::<Cookie>().unwrap(); assert_eq!( header, Cookie(vec![ HTTPCookie::new("first", "value"), HTTPCookie::new("second", "another") ]) ) } #[test] fn test_decode_cookie_invalid() { let mut headers = HeaderMap::new(); headers.insert(Cookie::name(), "abc".parse().unwrap()); let header = headers.typed_try_get::<Cookie>(); assert!(header.is_err()) } #[test] fn test_decode_cookie_invalid_not_str() { let mut headers = HeaderMap::new(); headers .insert(Cookie::name(), HeaderValue::from_bytes(b"\xfa").unwrap()); let header = headers.typed_try_get::<Cookie>(); assert!(header.is_err()) } #[test] fn test_encode_set_cookie() { let cookie = HTTPCookie::new("name", "value"); assert_eq!(encode(SetCookie(cookie)).to_str().unwrap(), "name=value") } #[test] fn test_decode_set_cookie() { let mut headers = HeaderMap::new(); headers.insert(SetCookie::name(), "name=value".parse().unwrap()); let header = headers.typed_get::<SetCookie>().unwrap(); assert_eq!(header, SetCookie(HTTPCookie::new("name", "value"))) } #[test] fn test_decode_set_cookie_invalid() { let mut headers = HeaderMap::new(); headers.insert(SetCookie::name(), "abc".parse().unwrap()); let header = headers.typed_try_get::<SetCookie>(); assert!(header.is_err()) } }
use crate::error::ArweaveError as Error; use async_trait::async_trait; use base64::{self, encode_config}; use ring::rand::{SecureRandom, SystemRandom}; use std::{fs as fsstd, path::PathBuf}; use tokio::fs; pub struct TempDir(pub PathBuf); #[async_trait] pub trait TempFrom<T> { async fn from_str(path_str: &str) -> Result<T, Error>; } #[async_trait] impl TempFrom<TempDir> for TempDir { async fn from_str(path_str: &str) -> Result<Self, Error> { if path_str.chars().last().unwrap() != '/' { return Err(Error::MissingTrailingSlash); } let rng = SystemRandom::new(); let mut rand_bytes: [u8; 8] = [0; 8]; let _ = rng.fill(&mut rand_bytes)?; let temp_stem = encode_config(rand_bytes, base64::URL_SAFE_NO_PAD); let path = PathBuf::from(path_str).join(temp_stem); fs::create_dir(&path).await?; Ok(Self(path)) } } impl Drop for TempDir { fn drop(&mut self) { match fsstd::remove_dir_all(&self.0) { Ok(_) => {} Err(e) => { eprintln!("{}", e); } } } }
use bindings::emscripten::*; use common::Vec2i; use console; use std::mem::transmute; use std::ptr::null; pub enum Event { Resize(Vec2i), Down(Vec2i), Up(Vec2i), Move(Vec2i), } pub fn init_event_queue(queue: *mut Vec<Event>) { unsafe { let evt_ptr = transmute(queue); on_resize(0, null(), evt_ptr); emscripten_set_resize_callback(null(), evt_ptr, 0, Some(on_resize)); emscripten_set_mousemove_callback(null(), evt_ptr, 0, Some(on_mouse_move)); emscripten_set_mousedown_callback(null(), evt_ptr, 0, Some(on_mouse_down)); emscripten_set_mouseup_callback(null(), evt_ptr, 0, Some(on_mouse_up)); emscripten_set_touchstart_callback(null(), evt_ptr, 0, Some(on_touch_start)); emscripten_set_touchmove_callback(null(), evt_ptr, 0, Some(on_touch_move)); emscripten_set_touchend_callback(null(), evt_ptr, 0, Some(on_touch_end)); emscripten_set_touchcancel_callback(null(), evt_ptr, 0, Some(on_touch_end)); } } unsafe extern "C" fn on_resize(_: i32, _e: *const EmscriptenUiEvent, ud: *mut CVoid) -> i32 { let event_queue: &mut Vec<Event> = transmute(ud); js! { b"Module.canvas = document.getElementById('canvas')\0" }; let mut screen_size = Vec2i::zero(); screen_size.x = js! { b"return (Module.canvas.width = Module.canvas.style.width = window.innerWidth)\0" }; screen_size.y = js! { b"return (Module.canvas.height = Module.canvas.style.height = window.innerHeight)\0" }; event_queue.push(Event::Resize(screen_size)); 0 } unsafe extern "C" fn on_mouse_move(_: i32, e: *const EmscriptenMouseEvent, ud: *mut CVoid) -> i32 { let event_queue: &mut Vec<Event> = transmute(ud); let e: &EmscriptenMouseEvent = transmute(e); event_queue.push(Event::Move(Vec2i::new(e.clientX as _, e.clientY as _))); 1 } unsafe extern "C" fn on_mouse_down(_: i32, e: *const EmscriptenMouseEvent, ud: *mut CVoid) -> i32 { let event_queue: &mut Vec<Event> = transmute(ud); let e: &EmscriptenMouseEvent = transmute(e); event_queue.push(Event::Down(Vec2i::new(e.clientX as _, e.clientY as _))); 1 } unsafe extern "C" fn on_mouse_up(_: i32, e: *const EmscriptenMouseEvent, ud: *mut CVoid) -> i32 { let event_queue: &mut Vec<Event> = transmute(ud); let e: &EmscriptenMouseEvent = transmute(e); event_queue.push(Event::Up(Vec2i::new(e.clientX as _, e.clientY as _))); 1 } unsafe extern "C" fn on_touch_move(_: i32, e: *const EmscriptenTouchEvent, ud: *mut CVoid) -> i32 { let event_queue: &mut Vec<Event> = transmute(ud); let e: &EmscriptenTouchEvent = transmute(e); if e.touches[0].identifier != 0 { return 0 } let pos = Vec2i::new(e.touches[0].clientX as _, e.touches[0].clientY as _); event_queue.push(Event::Move(pos)); 1 } unsafe extern "C" fn on_touch_start(_: i32, e: *const EmscriptenTouchEvent, ud: *mut CVoid) -> i32 { let event_queue: &mut Vec<Event> = transmute(ud); let e: &EmscriptenTouchEvent = transmute(e); if e.touches[0].identifier != 0 { return 0 } let pos = Vec2i::new(e.touches[0].clientX as _, e.touches[0].clientY as _); event_queue.push(Event::Down(pos)); 1 } unsafe extern "C" fn on_touch_end(_: i32, e: *const EmscriptenTouchEvent, ud: *mut CVoid) -> i32 { let event_queue: &mut Vec<Event> = transmute(ud); let e: &EmscriptenTouchEvent = transmute(e); if e.numTouches > 2 { use std::mem::uninitialized; let mut fs_state: EmscriptenFullscreenChangeEvent = uninitialized(); emscripten_get_fullscreen_status(&mut fs_state); if fs_state.isFullscreen == 0 { js! {{ b"Module.requestFullscreen(1, 1)\0" }}; console::set_section("Fullscreen requested", ""); } } if e.touches[0].identifier != 0 { return 0 } let pos = Vec2i::new(e.touches[0].clientX as _, e.touches[0].clientY as _); event_queue.push(Event::Up(pos)); 1 }
use super::address::*; use super::func::{DefinedFunctionInstance, InstIndex}; use super::module::ModuleIndex; use super::value::Value; #[derive(Debug)] pub enum StackValueType { Label, Value, Activation, } const DEFAULT_CALL_STACK_LIMIT: usize = 1024; #[derive(Debug)] pub enum Error { PopEmptyStack, MismatchStackValueType( /* expected: */ StackValueType, /* actual: */ StackValueType, ), NoCallFrame, Overflow, } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Overflow => write!(f, "call stack exhausted"), _ => write!(f, "{:?}", self), } } } type Result<T> = std::result::Result<T, Error>; #[derive(Clone, Copy, Debug)] pub enum Label { If(usize), Block(usize), Loop(LoopLabel), Return(usize), } #[derive(Clone, Copy, Debug)] pub struct LoopLabel { inst_index: InstIndex, } impl Label { pub fn new_loop(inst_index: InstIndex) -> Self { Self::Loop(LoopLabel { inst_index }) } pub fn arity(&self) -> usize { match self { Label::If(arity) => *arity, Label::Block(arity) => *arity, Label::Loop(_) => 0, Label::Return(arity) => *arity, } } } #[derive(Clone, Copy)] pub struct ProgramCounter { module_index: ModuleIndex, exec_addr: ExecutableFuncAddr, inst_index: InstIndex, } impl ProgramCounter { pub fn new( module_index: ModuleIndex, exec_addr: ExecutableFuncAddr, inst_index: InstIndex, ) -> Self { Self { module_index, exec_addr, inst_index, } } pub fn module_index(&self) -> ModuleIndex { self.module_index } pub fn exec_addr(&self) -> ExecutableFuncAddr { self.exec_addr } pub fn inst_index(&self) -> InstIndex { self.inst_index } pub fn inc_inst_index(&mut self) { self.inst_index.0 += 1; } pub fn loop_jump(&mut self, loop_label: &LoopLabel) { self.inst_index = loop_label.inst_index; } } #[derive(Clone)] pub struct CallFrame { pub module_index: ModuleIndex, pub locals: Vec<Value>, pub ret_pc: Option<ProgramCounter>, // Only for debug use pub exec_addr: ExecutableFuncAddr, } impl CallFrame { fn new( module_index: ModuleIndex, exec_addr: ExecutableFuncAddr, local_inits: &Vec<Value>, args: Vec<Value>, pc: Option<ProgramCounter>, ) -> Self { let mut locals = local_inits.clone(); for (i, arg) in args.into_iter().enumerate() { locals[i] = arg; } Self { module_index, exec_addr, locals, ret_pc: pc, } } pub fn new_from_func( exec_addr: ExecutableFuncAddr, func: &DefinedFunctionInstance, args: Vec<Value>, pc: Option<ProgramCounter>, ) -> Self { Self::new( func.module_index(), exec_addr, &func.cached_local_inits, args, pc, ) } pub fn set_local(&mut self, index: usize, value: Value) { self.locals[index] = value; } pub fn local(&self, index: usize) -> Value { self.locals[index] } pub fn module_index(&self) -> ModuleIndex { self.module_index } } pub enum StackValue { Value(Value), Label(Label), Activation(CallFrame), } impl StackValue { pub fn value_type(&self) -> StackValueType { match self { Self::Value(_) => StackValueType::Value, Self::Label(_) => StackValueType::Label, Self::Activation(_) => StackValueType::Activation, } } pub fn as_value(self) -> Result<Value> { match self { Self::Value(val) => Ok(val), _ => Err(Error::MismatchStackValueType( StackValueType::Value, self.value_type(), )), } } fn as_label(self) -> Result<Label> { match self { Self::Label(val) => Ok(val), _ => Err(Error::MismatchStackValueType( StackValueType::Label, self.value_type(), )), } } fn as_activation(self) -> Result<CallFrame> { match self { Self::Activation(val) => Ok(val), _ => Err(Error::MismatchStackValueType( StackValueType::Activation, self.value_type(), )), } } fn as_activation_ref(&self) -> Result<&CallFrame> { match self { Self::Activation(val) => Ok(val), _ => Err(Error::MismatchStackValueType( StackValueType::Activation, self.value_type(), )), } } fn as_activation_mut(&mut self) -> Result<&mut CallFrame> { match self { Self::Activation(val) => Ok(val), _ => Err(Error::MismatchStackValueType( StackValueType::Activation, self.value_type(), )), } } } impl std::fmt::Display for StackValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Value(_) => writeln!(f, "StackValue::Value"), Self::Label(_) => writeln!(f, "StackValue::Label"), Self::Activation(_) => writeln!(f, "StackValue::Activation"), } } } #[derive(Default)] pub struct Stack { stack: Vec<StackValue>, frame_index: Vec<usize>, } // Debugger impl Stack { pub fn peek_frames(&self) -> Vec<&CallFrame> { self.stack .iter() .filter_map(|v| match v { StackValue::Activation(f) => Some(f), _ => None, }) .collect() } pub fn peek_values(&self) -> Vec<&Value> { self.stack .iter() .filter_map(|v| match v { StackValue::Value(v) => Some(v), _ => None, }) .collect() } } impl Stack { pub fn pop_while<F: Fn(&StackValue) -> bool>(&mut self, f: F) -> Vec<StackValue> { let mut result = vec![]; while f(self.latest()) { result.push(self.stack.pop().unwrap()); } result } pub fn current_frame_index(&self) -> Result<usize> { self.frame_index .last() .map(|v| *v) .ok_or(Error::NoCallFrame) } pub fn is_func_top_level(&self) -> Result<bool> { match self.stack[self.current_frame_index()?..] .iter() .filter(|v| match v { StackValue::Label(Label::Return(_)) => false, StackValue::Label(_) => true, _ => false, }) .next() { Some(_) => Ok(false), None => Ok(true), } } pub fn current_frame_labels(&self) -> Result<Vec<&Label>> { Ok(self.stack[self.current_frame_index()?..] .iter() .filter_map(|v| match v { StackValue::Label(label) => Some(label), _ => None, }) .collect()) } fn latest(&self) -> &StackValue { self.stack.last().unwrap() } pub fn push_value(&mut self, val: Value) { self.stack.push(StackValue::Value(val)) } pub fn pop_value(&mut self) -> Result<Value> { match self.stack.pop() { Some(val) => val.as_value(), None => Err(Error::PopEmptyStack), } } pub fn push_label(&mut self, val: Label) { self.stack.push(StackValue::Label(val)) } pub fn pop_label(&mut self) -> Result<Label> { match self.stack.pop() { Some(val) => val.as_label(), None => Err(Error::PopEmptyStack), } } pub fn set_frame(&mut self, frame: CallFrame) -> Result<()> { if self.frame_index.len() > DEFAULT_CALL_STACK_LIMIT { return Err(Error::Overflow); } self.frame_index.push(self.stack.len()); self.stack.push(StackValue::Activation(frame)); Ok(()) } pub fn current_frame(&self) -> Result<&CallFrame> { self.stack[self.current_frame_index()?].as_activation_ref() } pub fn pop_frame(&mut self) -> Result<CallFrame> { match self.stack.pop() { Some(val) => { self.frame_index.pop(); val.as_activation() } None => Err(Error::PopEmptyStack), } } pub fn is_over_top_level(&self) -> bool { self.frame_index.is_empty() } pub fn set_local(&mut self, index: usize, value: Value) -> Result<()> { let size = self.current_frame_index()?; if let Some(stack) = self.stack.get_mut(size) { let frame = stack.as_activation_mut()?; frame.set_local(index, value); Ok(()) } else { Err(Error::NoCallFrame) } } } impl std::fmt::Debug for Stack { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!(f, "┌-------------------------┐")?; writeln!(f, "|--------- Stack ---------|")?; writeln!(f, "| ty | val |")?; for v in &self.stack { match v { StackValue::Value(value) => { writeln!(f, "| Value({:?})|{:?}|", value.value_type(), value)?; } StackValue::Label(label) => { writeln!(f, "| Label |{:?}|", label)?; } StackValue::Activation(_) => { writeln!(f, "| Frame | - |")?; } } } writeln!(f, "└-------------------------┘")?; Ok(()) } }
/// Struktur program sederhana pada rust /// fn main() { println!("Hello world"); }
use std::io; use std::time::Duration; use nats::connect; fn main() -> io::Result<()> { let nc = connect("localhost")?; let sub = nc.subscribe("sample")?; let res = nc.publish("sample", "test-message-1")?; println!("*** published: {:?}", res); if let Some(msg) = sub.next() { println!("*** received message: {:?}", msg); if let Ok(s) = String::from_utf8(msg.data) { println!("*** message body: {}", s); } } if let Ok(msg) = sub.next_timeout(Duration::from_secs(1)) { println!("*** received message2: {:?}", msg); } else { println!("*** timeout"); } sub.unsubscribe() }
use {flush, Body, RecvBody}; use futures::{Future, Poll, Stream}; use futures::future::{Executor, Either, Join, MapErr}; use h2::{self, Reason}; use h2::server::{Server as Accept, Handshake, Respond}; use http::{self, Request, Response}; use tokio_io::{AsyncRead, AsyncWrite}; use tower::{NewService, Service}; use std::marker::PhantomData; /// Attaches service implementations to h2 connections. #[derive(Clone)] pub struct Server<S, E, B> where S: NewService, B: Body, { new_service: S, builder: h2::server::Builder, executor: E, _p: PhantomData<B>, } /// Drives connection-level I/O . pub struct Connection<T, S, E, B, F> where T: AsyncRead + AsyncWrite, S: NewService, B: Body, { state: State<T, S, B>, executor: E, modify: F, } /// Modify a received request pub trait Modify { /// Modify a request before calling the service. fn modify(&mut self, request: &mut Request<()>); } enum State<T, S, B> where T: AsyncRead + AsyncWrite, S: NewService, B: Body, { /// Establish the HTTP/2.0 connection and get a service to process inbound /// requests. Init(Init<T, B::Data, S::Future, S::InitError>), /// Both the HTTP/2.0 connection and the service are ready. Ready { connection: Accept<T, B::Data>, service: S::Service, }, } type Init<T, B, S, E> = Join< MapErr<Handshake<T, B>, MapErrA<E>>, MapErr<S, MapErrB<E>>>; type MapErrA<E> = fn(h2::Error) -> Either<h2::Error, E>; type MapErrB<E> = fn(E) -> Either<h2::Error, E>; /// Task used to process requests pub struct Background<T, B> where B: Body, { state: BackgroundState<T, B>, } enum BackgroundState<T, B> where B: Body, { Respond { respond: Respond<B::Data>, response: T, }, Flush(flush::Flush<B>), } /// Error produced by a `Connection`. #[derive(Debug)] pub enum Error<S> where S: NewService, { /// Error produced during the HTTP/2.0 handshake. Handshake(h2::Error), /// Error produced by the HTTP/2.0 stream Protocol(h2::Error), /// Error produced when obtaining the service NewService(S::InitError), /// Error produced by the service Service(S::Error), /// Error produced when attempting to spawn a task Execute, } // ===== impl Server ===== impl<S, E, B> Server<S, E, B> where S: NewService<Request = Request<RecvBody>, Response = Response<B>>, B: Body, { pub fn new(new_service: S, builder: h2::server::Builder, executor: E) -> Self { Server { new_service, executor, builder, _p: PhantomData, } } } impl<S, E, B> Server<S, E, B> where S: NewService<Request = http::Request<RecvBody>, Response = Response<B>>, B: Body, E: Clone, { /// Produces a future that is satisfied once the h2 connection has been initialized. pub fn serve<T>(&self, io: T) -> Connection<T, S, E, B, ()> where T: AsyncRead + AsyncWrite, { self.serve_modified(io, ()) } pub fn serve_modified<T, F>(&self, io: T, modify: F) -> Connection<T, S, E, B, F> where T: AsyncRead + AsyncWrite, F: Modify, { // Clone a handle to the executor so that it can be moved into the // connection handle let executor = self.executor.clone(); let service = self.new_service.new_service() .map_err(Either::B as MapErrB<S::InitError>); // TODO we should specify initial settings here! let handshake = self.builder.handshake(io) .map_err(Either::A as MapErrA<S::InitError>); Connection { state: State::Init(handshake.join(service)), executor, modify, } } } // ===== impl Connection ===== impl<T, S, E, B, F> Connection<T, S, E, B, F> where T: AsyncRead + AsyncWrite, S: NewService<Request = http::Request<RecvBody>, Response = Response<B>>, B: Body, { fn is_ready(&self) -> bool { use self::State::*; match self.state { Ready { .. } => true, _ => false, } } fn try_ready(&mut self) -> Poll<(), Error<S>> { use self::State::*; let (connection, service) = match self.state { Init(ref mut join) => try_ready!(join.poll().map_err(Error::from_init)), _ => unreachable!(), }; self.state = Ready { connection, service }; Ok(().into()) } } impl<T, S, E, B, F> Future for Connection<T, S, E, B, F> where T: AsyncRead + AsyncWrite, S: NewService<Request = http::Request<RecvBody>, Response = Response<B>>, E: Executor<Background<<S::Service as Service>::Future, B>>, B: Body + 'static, F: Modify, { type Item = (); type Error = Error<S>; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if !self.is_ready() { // Advance the initialization of the service and HTTP/2.0 connection try_ready!(self.try_ready()); } let (connection, service) = match self.state { State::Ready { ref mut connection, ref mut service } => { (connection, service) } _ => unreachable!(), }; loop { // Make sure the service is ready let ready = service.poll_ready() // TODO: Don't dump the error .map_err(Error::Service); try_ready!(ready); let next = connection.poll() .map_err(Error::Protocol); let (request, respond) = match try_ready!(next) { Some(next) => next, None => return Ok(().into()), }; let (parts, body) = request.into_parts(); // This is really unfortunate, but the `http` currently lacks the // APIs to do this better :( let mut request = Request::from_parts(parts, ()); self.modify.modify(&mut request); let (parts, _) = request.into_parts(); let request = Request::from_parts(parts, RecvBody::new(body)); // Dispatch the request to the service let response = service.call(request); // Spawn a new task to process the response future if let Err(_) = self.executor.execute(Background::new(respond, response)) { return Err(Error::Execute) } } } } // ===== impl Modify ===== impl<T> Modify for T where T: FnMut(&mut Request<()>) { fn modify(&mut self, request: &mut Request<()>) { (*self)(request); } } impl Modify for () { fn modify(&mut self, _: &mut Request<()>) { } } // ===== impl Background ===== impl<T, B> Background<T, B> where T: Future, B: Body, { fn new(respond: Respond<B::Data>, response: T) -> Self { Background { state: BackgroundState::Respond { respond, response, }, } } } impl<T, B> Future for Background<T, B> where T: Future<Item = Response<B>>, B: Body, { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { use self::BackgroundState::*; loop { let flush = match self.state { Respond { ref mut respond, ref mut response } => { use flush::Flush; let response = try_ready!(response.poll().map_err(|_| { // TODO: do something better the error? let reason = Reason::INTERNAL_ERROR; respond.send_reset(reason); })); let (parts, body) = response.into_parts(); // Check if the response is immediately an end-of-stream. let end_stream = body.is_end_stream(); trace!("send_response eos={} {:?}", end_stream, parts); // Try sending the response. let response = Response::from_parts(parts, ()); match respond.send_response(response, end_stream) { Ok(stream) => { if end_stream { // Nothing more to do return Ok(().into()); } // Transition to flushing the body Flush::new(body, stream) } Err(_) => { // TODO: Do something with the error? return Ok(().into()); } } } Flush(ref mut flush) => return flush.poll(), }; self.state = Flush(flush); } } } // ===== impl Error ===== impl<S> Error<S> where S: NewService, { fn from_init(err: Either<h2::Error, S::InitError>) -> Self { match err { Either::A(err) => Error::Handshake(err), Either::B(err) => Error::NewService(err), } } }
use std::convert::TryInto; use std::num::NonZeroU8; use std::ops::{Div, Mul, Sub}; use nalgebra::{distance_squared, Point2, RealField, Scalar, distance}; use num_traits::{CheckedSub, Zero}; use num_traits::{FromPrimitive, ToPrimitive}; use wasm_bindgen::UnwrapThrowExt; use super::node::Node; #[derive(Clone, Debug, Hash)] pub struct Line<Coord: Scalar> { start: Point2<Coord>, end: Point2<Coord>, strength: NonZeroU8, } impl<Coord: Scalar> Line<Coord> { pub fn start(&self) -> &Point2<Coord> { &self.start } pub fn end(&self) -> &Point2<Coord> { &self.end } pub fn endpoints(&self) -> (&Point2<Coord>, &Point2<Coord>) { (&self.start(), &self.end()) } pub fn get_strength(&self) -> NonZeroU8 { self.strength } } impl<Coord: Scalar> Line<Coord> where Coord: Mul<Coord, Output = Coord> + Div<Coord, Output = Coord> + PartialOrd + ToPrimitive + From<u8> + Zero + Sub<Coord, Output = Coord> + RealField, { /// `max` is the maximum strength of the line. Lower this to lower the rate of change of the alpha(?) /// /// `threshold` is the distance at which the line no longer exists. Lower this to make connections happen at shorter distances and vise versa. /// /// `strength_alpha` returns either a `Some(u8)` value which represents the alpha (from 0..256). /// (it is actually a `NonZeroU8` for optimization purposes, since an alpha of zero would return `None`) pub fn strength_alpha(strength: Coord, max: Coord, threshold: Coord) -> Option<NonZeroU8> { // Balance in between max and threshold (and cutoff below threshold) Some(max - (max * strength / threshold)) // Return None if below threshold (nodes are too far apart) .and_then(|c| if c >= Coord::zero() { Some(c) } else { None }) .map(|adjusted| { // Clamp below max if adjusted <= max { adjusted } else { max } }) .map(|adjusted| { // FIXME: should this be 255 or 256 // Apply to scale of 0..255 adjusted * Coord::from(255u8) / max }) .as_ref() .map(Coord::to_u8) .map(|r| r.expect_throw("Error casting Coord to u8")) .and_then(NonZeroU8::new) } pub fn try_new( start: &Node<Coord>, end: &Node<Coord>, max_strength: Coord, distance_threshold: Coord, ) -> Option<Self> { if start.position() == end.position() { return None; } let alpha = Line::strength_alpha(distance(start.position(), end.position()), max_strength, distance_threshold)?; Some(Line { start: start.get_position(), end: end.get_position(), strength: alpha, }) } } #[cfg(test)] mod tests { use super::Line; use std::num::NonZeroU8; #[test] fn test_strength_alpha_halfway() { let strength = 50.0; let max = 100.0; let threshold = 100.0; let expected = NonZeroU8::new((255 / 2) as u8); let actual = Line::strength_alpha(strength, max, threshold); assert_eq!(actual, expected) } #[test] fn test_strength_alpha_upper_quarter() { let strength = 75.0; let max = 100.0; let threshold = 100.0; let expected = NonZeroU8::new((255 / 4) as u8); let actual = Line::strength_alpha(strength, max, threshold); assert_eq!(actual, expected) } #[test] fn test_strength_alpha_lower_quarter() { let strength = 25.0; let max = 100.0; let threshold = 100.0; let expected = NonZeroU8::new((255 * 3 / 4) as u8); let actual = Line::strength_alpha(strength, max, threshold); assert_eq!(actual, expected) } #[test] fn test_strength_alpha_upper_edge() { let strength = 100.0; let max = 100.0; let threshold = 100.0; let expected = None; let actual = Line::strength_alpha(strength, max, threshold); assert_eq!(actual, expected) } #[test] fn test_strength_alpha_lower_edge() { let strength = 0.0; let max = 100.0; let threshold = 100.0; let expected = NonZeroU8::new(255u8); let actual = Line::strength_alpha(strength, max, threshold); assert_eq!(actual, expected) } #[test] fn test_strength_alpha_above_threshold() { let strength = 150.0; let max = 100.0; let threshold = 100.0; let expected = None; // Should be above threshold let actual = Line::strength_alpha(strength, max, threshold); assert_eq!(actual, expected) } }
pub mod is_unique; pub mod is_permutation; pub mod urlify; pub mod palindrome_permutation; pub mod one_away; pub mod string_compression; pub mod rotation; pub mod zero_matrix; pub mod is_rotation;
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct ISpatialSurfaceInfo(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpatialSurfaceInfo { type Vtable = ISpatialSurfaceInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf8e9ebe7_39b7_3962_bb03_57f56e1fb0a1); } #[repr(C)] #[doc(hidden)] pub struct ISpatialSurfaceInfo_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::GUID) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Numerics"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, coordinatesystem: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Numerics")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, maxtrianglespercubicmeter: f64, 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, maxtrianglespercubicmeter: f64, options: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ISpatialSurfaceMesh(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpatialSurfaceMesh { type Vtable = ISpatialSurfaceMesh_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x108f57d9_df0d_3950_a0fd_f972c77c27b4); } #[repr(C)] #[doc(hidden)] pub struct ISpatialSurfaceMesh_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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::Numerics::Vector3) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Numerics"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ISpatialSurfaceMeshBuffer(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpatialSurfaceMeshBuffer { type Vtable = ISpatialSurfaceMeshBuffer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x93cf59e0_871f_33f8_98b2_03d101458f6f); } #[repr(C)] #[doc(hidden)] pub struct ISpatialSurfaceMeshBuffer_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 = "Graphics_DirectX")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Graphics::DirectX::DirectXPixelFormat) -> ::windows::core::HRESULT, #[cfg(not(feature = "Graphics_DirectX"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ISpatialSurfaceMeshOptions(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpatialSurfaceMeshOptions { type Vtable = ISpatialSurfaceMeshOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd2759f89_3572_3d2d_a10d_5fee9394aa37); } #[repr(C)] #[doc(hidden)] pub struct ISpatialSurfaceMeshOptions_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 = "Graphics_DirectX")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Graphics::DirectX::DirectXPixelFormat) -> ::windows::core::HRESULT, #[cfg(not(feature = "Graphics_DirectX"))] usize, #[cfg(feature = "Graphics_DirectX")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::super::Graphics::DirectX::DirectXPixelFormat) -> ::windows::core::HRESULT, #[cfg(not(feature = "Graphics_DirectX"))] usize, #[cfg(feature = "Graphics_DirectX")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Graphics::DirectX::DirectXPixelFormat) -> ::windows::core::HRESULT, #[cfg(not(feature = "Graphics_DirectX"))] usize, #[cfg(feature = "Graphics_DirectX")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::super::Graphics::DirectX::DirectXPixelFormat) -> ::windows::core::HRESULT, #[cfg(not(feature = "Graphics_DirectX"))] usize, #[cfg(feature = "Graphics_DirectX")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Graphics::DirectX::DirectXPixelFormat) -> ::windows::core::HRESULT, #[cfg(not(feature = "Graphics_DirectX"))] usize, #[cfg(feature = "Graphics_DirectX")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::super::Graphics::DirectX::DirectXPixelFormat) -> ::windows::core::HRESULT, #[cfg(not(feature = "Graphics_DirectX"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ISpatialSurfaceMeshOptionsStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpatialSurfaceMeshOptionsStatics { type Vtable = ISpatialSurfaceMeshOptionsStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9b340abf_9781_4505_8935_013575caae5e); } #[repr(C)] #[doc(hidden)] pub struct ISpatialSurfaceMeshOptionsStatics_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_Collections", feature = "Graphics_DirectX"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation_Collections", feature = "Graphics_DirectX")))] usize, #[cfg(all(feature = "Foundation_Collections", feature = "Graphics_DirectX"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation_Collections", feature = "Graphics_DirectX")))] usize, #[cfg(all(feature = "Foundation_Collections", feature = "Graphics_DirectX"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation_Collections", feature = "Graphics_DirectX")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ISpatialSurfaceObserver(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpatialSurfaceObserver { type Vtable = ISpatialSurfaceObserver_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x10b69819_ddca_3483_ac3a_748fe8c86df5); } #[repr(C)] #[doc(hidden)] pub struct ISpatialSurfaceObserver_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, bounds: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bounds: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[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 ISpatialSurfaceObserverStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpatialSurfaceObserverStatics { type Vtable = ISpatialSurfaceObserverStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x165951ed_2108_4168_9175_87e027bc9285); } #[repr(C)] #[doc(hidden)] pub struct ISpatialSurfaceObserverStatics_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, ); #[repr(transparent)] #[doc(hidden)] pub struct ISpatialSurfaceObserverStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpatialSurfaceObserverStatics2 { type Vtable = ISpatialSurfaceObserverStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0f534261_c55d_4e6b_a895_a19de69a42e3); } #[repr(C)] #[doc(hidden)] pub struct ISpatialSurfaceObserverStatics2_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)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SpatialSurfaceInfo(pub ::windows::core::IInspectable); impl SpatialSurfaceInfo { pub fn Id(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } #[cfg(feature = "Foundation")] pub fn UpdateTime(&self) -> ::windows::core::Result<super::super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::DateTime>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Numerics"))] pub fn TryGetBounds<'a, Param0: ::windows::core::IntoParam<'a, super::SpatialCoordinateSystem>>(&self, coordinatesystem: Param0) -> ::windows::core::Result<super::super::super::Foundation::IReference<super::SpatialBoundingOrientedBox>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), coordinatesystem.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IReference<super::SpatialBoundingOrientedBox>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryComputeLatestMeshAsync(&self, maxtrianglespercubicmeter: f64) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<SpatialSurfaceMesh>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), maxtrianglespercubicmeter, &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<SpatialSurfaceMesh>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryComputeLatestMeshWithOptionsAsync<'a, Param1: ::windows::core::IntoParam<'a, SpatialSurfaceMeshOptions>>(&self, maxtrianglespercubicmeter: f64, options: Param1) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<SpatialSurfaceMesh>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), maxtrianglespercubicmeter, options.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<SpatialSurfaceMesh>>(result__) } } } unsafe impl ::windows::core::RuntimeType for SpatialSurfaceInfo { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.Surfaces.SpatialSurfaceInfo;{f8e9ebe7-39b7-3962-bb03-57f56e1fb0a1})"); } unsafe impl ::windows::core::Interface for SpatialSurfaceInfo { type Vtable = ISpatialSurfaceInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf8e9ebe7_39b7_3962_bb03_57f56e1fb0a1); } impl ::windows::core::RuntimeName for SpatialSurfaceInfo { const NAME: &'static str = "Windows.Perception.Spatial.Surfaces.SpatialSurfaceInfo"; } impl ::core::convert::From<SpatialSurfaceInfo> for ::windows::core::IUnknown { fn from(value: SpatialSurfaceInfo) -> Self { value.0 .0 } } impl ::core::convert::From<&SpatialSurfaceInfo> for ::windows::core::IUnknown { fn from(value: &SpatialSurfaceInfo) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialSurfaceInfo { 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 SpatialSurfaceInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SpatialSurfaceInfo> for ::windows::core::IInspectable { fn from(value: SpatialSurfaceInfo) -> Self { value.0 } } impl ::core::convert::From<&SpatialSurfaceInfo> for ::windows::core::IInspectable { fn from(value: &SpatialSurfaceInfo) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialSurfaceInfo { 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 SpatialSurfaceInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SpatialSurfaceInfo {} unsafe impl ::core::marker::Sync for SpatialSurfaceInfo {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SpatialSurfaceMesh(pub ::windows::core::IInspectable); impl SpatialSurfaceMesh { pub fn SurfaceInfo(&self) -> ::windows::core::Result<SpatialSurfaceInfo> { 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::<SpatialSurfaceInfo>(result__) } } pub fn CoordinateSystem(&self) -> ::windows::core::Result<super::SpatialCoordinateSystem> { 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::SpatialCoordinateSystem>(result__) } } pub fn TriangleIndices(&self) -> ::windows::core::Result<SpatialSurfaceMeshBuffer> { 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::<SpatialSurfaceMeshBuffer>(result__) } } pub fn VertexPositions(&self) -> ::windows::core::Result<SpatialSurfaceMeshBuffer> { 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::<SpatialSurfaceMeshBuffer>(result__) } } #[cfg(feature = "Foundation_Numerics")] pub fn VertexPositionScale(&self) -> ::windows::core::Result<super::super::super::Foundation::Numerics::Vector3> { let this = self; unsafe { let mut result__: super::super::super::Foundation::Numerics::Vector3 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Numerics::Vector3>(result__) } } pub fn VertexNormals(&self) -> ::windows::core::Result<SpatialSurfaceMeshBuffer> { 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::<SpatialSurfaceMeshBuffer>(result__) } } } unsafe impl ::windows::core::RuntimeType for SpatialSurfaceMesh { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.Surfaces.SpatialSurfaceMesh;{108f57d9-df0d-3950-a0fd-f972c77c27b4})"); } unsafe impl ::windows::core::Interface for SpatialSurfaceMesh { type Vtable = ISpatialSurfaceMesh_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x108f57d9_df0d_3950_a0fd_f972c77c27b4); } impl ::windows::core::RuntimeName for SpatialSurfaceMesh { const NAME: &'static str = "Windows.Perception.Spatial.Surfaces.SpatialSurfaceMesh"; } impl ::core::convert::From<SpatialSurfaceMesh> for ::windows::core::IUnknown { fn from(value: SpatialSurfaceMesh) -> Self { value.0 .0 } } impl ::core::convert::From<&SpatialSurfaceMesh> for ::windows::core::IUnknown { fn from(value: &SpatialSurfaceMesh) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialSurfaceMesh { 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 SpatialSurfaceMesh { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SpatialSurfaceMesh> for ::windows::core::IInspectable { fn from(value: SpatialSurfaceMesh) -> Self { value.0 } } impl ::core::convert::From<&SpatialSurfaceMesh> for ::windows::core::IInspectable { fn from(value: &SpatialSurfaceMesh) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialSurfaceMesh { 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 SpatialSurfaceMesh { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SpatialSurfaceMesh {} unsafe impl ::core::marker::Sync for SpatialSurfaceMesh {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SpatialSurfaceMeshBuffer(pub ::windows::core::IInspectable); impl SpatialSurfaceMeshBuffer { #[cfg(feature = "Graphics_DirectX")] pub fn Format(&self) -> ::windows::core::Result<super::super::super::Graphics::DirectX::DirectXPixelFormat> { let this = self; unsafe { let mut result__: super::super::super::Graphics::DirectX::DirectXPixelFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Graphics::DirectX::DirectXPixelFormat>(result__) } } pub fn Stride(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn ElementCount(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn Data(&self) -> ::windows::core::Result<super::super::super::Storage::Streams::IBuffer> { 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::Storage::Streams::IBuffer>(result__) } } } unsafe impl ::windows::core::RuntimeType for SpatialSurfaceMeshBuffer { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.Surfaces.SpatialSurfaceMeshBuffer;{93cf59e0-871f-33f8-98b2-03d101458f6f})"); } unsafe impl ::windows::core::Interface for SpatialSurfaceMeshBuffer { type Vtable = ISpatialSurfaceMeshBuffer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x93cf59e0_871f_33f8_98b2_03d101458f6f); } impl ::windows::core::RuntimeName for SpatialSurfaceMeshBuffer { const NAME: &'static str = "Windows.Perception.Spatial.Surfaces.SpatialSurfaceMeshBuffer"; } impl ::core::convert::From<SpatialSurfaceMeshBuffer> for ::windows::core::IUnknown { fn from(value: SpatialSurfaceMeshBuffer) -> Self { value.0 .0 } } impl ::core::convert::From<&SpatialSurfaceMeshBuffer> for ::windows::core::IUnknown { fn from(value: &SpatialSurfaceMeshBuffer) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialSurfaceMeshBuffer { 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 SpatialSurfaceMeshBuffer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SpatialSurfaceMeshBuffer> for ::windows::core::IInspectable { fn from(value: SpatialSurfaceMeshBuffer) -> Self { value.0 } } impl ::core::convert::From<&SpatialSurfaceMeshBuffer> for ::windows::core::IInspectable { fn from(value: &SpatialSurfaceMeshBuffer) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialSurfaceMeshBuffer { 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 SpatialSurfaceMeshBuffer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SpatialSurfaceMeshBuffer {} unsafe impl ::core::marker::Sync for SpatialSurfaceMeshBuffer {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SpatialSurfaceMeshOptions(pub ::windows::core::IInspectable); impl SpatialSurfaceMeshOptions { 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<SpatialSurfaceMeshOptions, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Graphics_DirectX")] pub fn VertexPositionFormat(&self) -> ::windows::core::Result<super::super::super::Graphics::DirectX::DirectXPixelFormat> { let this = self; unsafe { let mut result__: super::super::super::Graphics::DirectX::DirectXPixelFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Graphics::DirectX::DirectXPixelFormat>(result__) } } #[cfg(feature = "Graphics_DirectX")] pub fn SetVertexPositionFormat(&self, value: super::super::super::Graphics::DirectX::DirectXPixelFormat) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Graphics_DirectX")] pub fn TriangleIndexFormat(&self) -> ::windows::core::Result<super::super::super::Graphics::DirectX::DirectXPixelFormat> { let this = self; unsafe { let mut result__: super::super::super::Graphics::DirectX::DirectXPixelFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Graphics::DirectX::DirectXPixelFormat>(result__) } } #[cfg(feature = "Graphics_DirectX")] pub fn SetTriangleIndexFormat(&self, value: super::super::super::Graphics::DirectX::DirectXPixelFormat) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Graphics_DirectX")] pub fn VertexNormalFormat(&self) -> ::windows::core::Result<super::super::super::Graphics::DirectX::DirectXPixelFormat> { let this = self; unsafe { let mut result__: super::super::super::Graphics::DirectX::DirectXPixelFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Graphics::DirectX::DirectXPixelFormat>(result__) } } #[cfg(feature = "Graphics_DirectX")] pub fn SetVertexNormalFormat(&self, value: super::super::super::Graphics::DirectX::DirectXPixelFormat) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } pub fn IncludeVertexNormals(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetIncludeVertexNormals(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(all(feature = "Foundation_Collections", feature = "Graphics_DirectX"))] pub fn SupportedVertexPositionFormats() -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<super::super::super::Graphics::DirectX::DirectXPixelFormat>> { Self::ISpatialSurfaceMeshOptionsStatics(|this| 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::super::Foundation::Collections::IVectorView<super::super::super::Graphics::DirectX::DirectXPixelFormat>>(result__) }) } #[cfg(all(feature = "Foundation_Collections", feature = "Graphics_DirectX"))] pub fn SupportedTriangleIndexFormats() -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<super::super::super::Graphics::DirectX::DirectXPixelFormat>> { Self::ISpatialSurfaceMeshOptionsStatics(|this| 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::IVectorView<super::super::super::Graphics::DirectX::DirectXPixelFormat>>(result__) }) } #[cfg(all(feature = "Foundation_Collections", feature = "Graphics_DirectX"))] pub fn SupportedVertexNormalFormats() -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<super::super::super::Graphics::DirectX::DirectXPixelFormat>> { Self::ISpatialSurfaceMeshOptionsStatics(|this| 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::super::Foundation::Collections::IVectorView<super::super::super::Graphics::DirectX::DirectXPixelFormat>>(result__) }) } pub fn ISpatialSurfaceMeshOptionsStatics<R, F: FnOnce(&ISpatialSurfaceMeshOptionsStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<SpatialSurfaceMeshOptions, ISpatialSurfaceMeshOptionsStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for SpatialSurfaceMeshOptions { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.Surfaces.SpatialSurfaceMeshOptions;{d2759f89-3572-3d2d-a10d-5fee9394aa37})"); } unsafe impl ::windows::core::Interface for SpatialSurfaceMeshOptions { type Vtable = ISpatialSurfaceMeshOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd2759f89_3572_3d2d_a10d_5fee9394aa37); } impl ::windows::core::RuntimeName for SpatialSurfaceMeshOptions { const NAME: &'static str = "Windows.Perception.Spatial.Surfaces.SpatialSurfaceMeshOptions"; } impl ::core::convert::From<SpatialSurfaceMeshOptions> for ::windows::core::IUnknown { fn from(value: SpatialSurfaceMeshOptions) -> Self { value.0 .0 } } impl ::core::convert::From<&SpatialSurfaceMeshOptions> for ::windows::core::IUnknown { fn from(value: &SpatialSurfaceMeshOptions) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialSurfaceMeshOptions { 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 SpatialSurfaceMeshOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SpatialSurfaceMeshOptions> for ::windows::core::IInspectable { fn from(value: SpatialSurfaceMeshOptions) -> Self { value.0 } } impl ::core::convert::From<&SpatialSurfaceMeshOptions> for ::windows::core::IInspectable { fn from(value: &SpatialSurfaceMeshOptions) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialSurfaceMeshOptions { 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 SpatialSurfaceMeshOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SpatialSurfaceMeshOptions {} unsafe impl ::core::marker::Sync for SpatialSurfaceMeshOptions {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SpatialSurfaceObserver(pub ::windows::core::IInspectable); impl SpatialSurfaceObserver { 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<SpatialSurfaceObserver, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation_Collections")] pub fn GetObservedSurfaces(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IMapView<::windows::core::GUID, SpatialSurfaceInfo>> { 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::super::Foundation::Collections::IMapView<::windows::core::GUID, SpatialSurfaceInfo>>(result__) } } pub fn SetBoundingVolume<'a, Param0: ::windows::core::IntoParam<'a, super::SpatialBoundingVolume>>(&self, bounds: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), bounds.into_param().abi()).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn SetBoundingVolumes<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<super::SpatialBoundingVolume>>>(&self, bounds: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), bounds.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn ObservedSurfacesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<SpatialSurfaceObserver, ::windows::core::IInspectable>>>(&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).9)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveObservedSurfacesChanged<'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).10)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn RequestAccessAsync() -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<super::SpatialPerceptionAccessStatus>> { Self::ISpatialSurfaceObserverStatics(|this| 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::super::Foundation::IAsyncOperation<super::SpatialPerceptionAccessStatus>>(result__) }) } pub fn IsSupported() -> ::windows::core::Result<bool> { Self::ISpatialSurfaceObserverStatics2(|this| 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__) }) } pub fn ISpatialSurfaceObserverStatics<R, F: FnOnce(&ISpatialSurfaceObserverStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<SpatialSurfaceObserver, ISpatialSurfaceObserverStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ISpatialSurfaceObserverStatics2<R, F: FnOnce(&ISpatialSurfaceObserverStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<SpatialSurfaceObserver, ISpatialSurfaceObserverStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for SpatialSurfaceObserver { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.Surfaces.SpatialSurfaceObserver;{10b69819-ddca-3483-ac3a-748fe8c86df5})"); } unsafe impl ::windows::core::Interface for SpatialSurfaceObserver { type Vtable = ISpatialSurfaceObserver_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x10b69819_ddca_3483_ac3a_748fe8c86df5); } impl ::windows::core::RuntimeName for SpatialSurfaceObserver { const NAME: &'static str = "Windows.Perception.Spatial.Surfaces.SpatialSurfaceObserver"; } impl ::core::convert::From<SpatialSurfaceObserver> for ::windows::core::IUnknown { fn from(value: SpatialSurfaceObserver) -> Self { value.0 .0 } } impl ::core::convert::From<&SpatialSurfaceObserver> for ::windows::core::IUnknown { fn from(value: &SpatialSurfaceObserver) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialSurfaceObserver { 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 SpatialSurfaceObserver { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SpatialSurfaceObserver> for ::windows::core::IInspectable { fn from(value: SpatialSurfaceObserver) -> Self { value.0 } } impl ::core::convert::From<&SpatialSurfaceObserver> for ::windows::core::IInspectable { fn from(value: &SpatialSurfaceObserver) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialSurfaceObserver { 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 SpatialSurfaceObserver { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SpatialSurfaceObserver {} unsafe impl ::core::marker::Sync for SpatialSurfaceObserver {}
use projecteuler::helper; use projecteuler::square_roots; fn main() { //gets optimized into a nop I think helper::check_bench(|| { solve(); }); assert_eq!(solve(), 5482660); dbg!(solve()); } //what is the distance from P_n to P_{n+1}? /* P_{n+1}-P_n = (n+1)(3n+3-1)/2 - n(3n-1)/2 P_{n+1}-P_n = ((n+1)(3n+3-1) - n(3n-1))/2 (n+1)(3n+3-1) - n(3n-1) (n+1)(3n+2) - n(3n-1) 3n²+2n+3n+2 - 3n²+n 2n+3n+2+n 6n+2 P_{n+1}-P_n = (6n+2)/2 P_{n+1}-P_n = 3n+1 */ //how to go back from number to index /* P_n = n(3n-1)/2 n = 1/6 * (1 +- \sqrt{ 24*P_n + 1 }) */ fn solve() -> usize { let mut min = usize::MAX; for i in 1.. { let p_i = get_pentagonal(i); for j in (1..i).rev() { let p_j = get_pentagonal(j); let diff = p_i - p_j; let sum = p_i + p_j; if diff > min { if j == i - 1 { dbg!(i); return min; } break; } if is_pentagonal(diff) && is_pentagonal(sum) { dbg!(i, diff); min = diff; } } } 0 } fn get_pentagonal(n: usize) -> usize { (n * (3 * n - 1)) / 2 } fn is_pentagonal(n: usize) -> bool { let (floor, ceil) = square_roots::sqrt(24 * n + 1); if floor != ceil { return false; } let temp = floor + 1; temp % 6 == 0 }
/* http://rosalind.info/problems/ba1c/ Find the reverse complement of a string Sample: AAAACCCGGT ACCGGGTTTT */ extern crate rosalind_rust; use rosalind_rust::Cli; use std::io::{prelude::*, BufReader}; use structopt::StructOpt; fn revcomp(s: &str) -> String { s.chars() .map(|c| match c { 'A' => 'T', 'T' => 'A', 'G' => 'C', 'C' => 'G', _ => 'N', }) .rev() .collect::<String>() } #[test] fn test_ba1c() { let seq = String::from("AAAACCCGGT"); assert_eq!(revcomp(&seq), String::from("ACCGGGTTTT")); } 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 res = revcomp(&text); println!("{}", res); Ok(()) }
use std::{cell::RefCell, iter::Peekable, rc::Rc}; use crate::{ algorithm::{Components, ComponentsIter, Sorted, SortedIntersect, SortedIntersectIter}, properties::{WithRegion, WithRegionCore}, records::Bed3, ChromName, }; pub struct InvertedIter<C, A> where A: Iterator + Sorted, C: ChromName + Clone, A::Item: WithRegion<C> + Clone, { iter: Peekable<ComponentsIter<C, A>>, last_chrom: Option<C>, } pub trait InvertExt<C> where Self: Iterator + Sorted + Sized, C: ChromName + Clone, Self::Item: WithRegion<C> + Clone, { fn invert(self) -> InvertedIter<C, Self> { InvertedIter { iter: self.components().peekable(), last_chrom: None, } } } impl<T, C> InvertExt<C> for T where T: Iterator + Sorted + Sized, C: ChromName, T::Item: WithRegion<C> + Clone, { } impl<C, A> Iterator for InvertedIter<C, A> where A: Iterator + Sorted, C: ChromName, A::Item: WithRegion<C> + Clone, { type Item = Bed3<C>; fn next(&mut self) -> Option<Self::Item> { let next_comp = self.iter.peek()?; let is_fresh_chrom = self .last_chrom .as_ref() .map_or(true, |chrom| chrom != next_comp.value.chrom()); if is_fresh_chrom { self.last_chrom = Some(next_comp.value.chrom().clone()); if next_comp.value.begin() > 0 { return Some(Bed3 { chrom: next_comp.value.chrom().clone(), begin: 0u32, end: next_comp.value.begin(), }); } } let begin = loop { let next = self.iter.next()?; if next.depth == 0 { break next.value.end(); } }; if let Some(next) = self.iter.peek() { let end = if next.value.chrom() == self.last_chrom.as_ref().unwrap() { next.value.begin() } else { u32::MAX }; if end - begin > 0 { return Some(Bed3 { chrom: self.last_chrom.clone().unwrap(), begin, end, }); } self.next() } else { Some(Bed3 { chrom: self.last_chrom.clone().unwrap(), begin, end: u32::MAX, }) } } } struct SubstractData<C, A, B> where A: Iterator + Sorted, B: Iterator + Sorted, C: ChromName, A::Item: WithRegion<C> + Clone, B::Item: WithRegion<C> + Clone, { iter_a: Peekable<A>, iter_b: Peekable<InvertedIter<C, B>>, known_chrom: Vec<C>, } pub struct SubstractIterA<C, A, B> where A: Iterator + Sorted, B: Iterator + Sorted, C: ChromName, A::Item: WithRegion<C> + Clone, B::Item: WithRegion<C> + Clone, { core: Rc<RefCell<SubstractData<C, A, B>>>, } impl<C, A, B> Sorted for SubstractIterA<C, A, B> where A: Iterator + Sorted, B: Iterator + Sorted, C: ChromName, A::Item: WithRegion<C> + Clone, B::Item: WithRegion<C> + Clone, { } impl<C, A, B> Iterator for SubstractIterA<C, A, B> where A: Iterator + Sorted, B: Iterator + Sorted, C: ChromName, A::Item: WithRegion<C> + Clone, B::Item: WithRegion<C> + Clone, { type Item = A::Item; fn next(&mut self) -> Option<Self::Item> { let core = &mut self.core.borrow_mut(); let ret = core.iter_a.next()?; if core .known_chrom .last() .map_or(true, |last| last < ret.chrom()) { core.known_chrom.push(ret.chrom().clone()); } if let Some(next) = core.iter_a.peek() { let chrom = next.chrom().clone(); if core.known_chrom.last().map_or(true, |last| last < &chrom) { core.known_chrom.push(chrom); } } Some(ret) } } pub struct SubstractIterB<C, A, B> where A: Iterator + Sorted, B: Iterator + Sorted, C: ChromName, A::Item: WithRegion<C> + Clone, B::Item: WithRegion<C> + Clone, { core: Rc<RefCell<SubstractData<C, A, B>>>, last_chrom: Option<usize>, } impl<C, A, B> Sorted for SubstractIterB<C, A, B> where A: Iterator + Sorted, B: Iterator + Sorted, C: ChromName, A::Item: WithRegion<C> + Clone, B::Item: WithRegion<C> + Clone, { } impl<C, A, B> Iterator for SubstractIterB<C, A, B> where A: Iterator + Sorted, B: Iterator + Sorted, C: ChromName, A::Item: WithRegion<C> + Clone, B::Item: WithRegion<C> + Clone, { type Item = Bed3<C>; fn next(&mut self) -> Option<Self::Item> { let core = &mut self.core.borrow_mut(); let current_chrom = self .last_chrom .map_or(core.known_chrom.get(0), |id| core.known_chrom.get(id))? .clone(); while let Some(next_chrom) = core.iter_b.peek().map(|x| x.chrom().clone()) { if next_chrom < current_chrom { core.iter_b.next(); } else if next_chrom == current_chrom { let next = core.iter_b.next()?; return Some(next); } else { break; } } if self.last_chrom.map_or(core.known_chrom.len() > 0, |cid| { cid < core.known_chrom.len() - 1 }) { let idx = self.last_chrom.map_or(0, |x| x + 1); self.last_chrom = Some(idx); return Some(Bed3 { chrom: core.known_chrom[idx].clone(), begin: 0, end: u32::MAX, }); } None } } pub trait SubtractExt<C: ChromName> where Self: Iterator + Sorted + Sized, Self::Item: WithRegion<C> + Clone, { fn subtract<T>( self, other: T, ) -> SortedIntersectIter<C, SubstractIterA<C, Self, T>, SubstractIterB<C, Self, T>> where T: Iterator + Sorted, T::Item: WithRegion<C> + Clone, { let core_data = Rc::new(RefCell::new(SubstractData { iter_a: self.peekable(), iter_b: other.invert().peekable(), known_chrom: vec![], })); let iter_a = SubstractIterA { core: core_data.clone(), }; let iter_b = SubstractIterB { core: core_data, last_chrom: None, }; iter_a.sorted_intersect(iter_b) } } impl<C: ChromName, T> SubtractExt<C> for T where Self: Iterator + Sorted, Self::Item: WithRegion<C> + Clone, { }
#![warn(clippy::all)] mod vtable; mod driver; mod va_backend; use va_backend as va; mod vdpau; mod vdpau_loader; mod vdpau_x11; mod xlib; const VDPAU_MAX_PROFILES: usize = 12; const VDPAU_MAX_ENTRYPOINTS: usize = 5; const VDPAU_MAX_CONFIG_ATTRIBUTES: usize = 10; const VDPAU_MAX_IMAGE_FORMATS: usize = 10; const VDPAU_MAX_SUBPICTURE_FORMATS: usize = 6; const VDPAU_MAX_DISPLAY_ATTRIBUTES: usize = 6; pub(crate) fn va_driver_init(ctx: va::VADriverContextP) -> Result<(), va::VAStatus> { let mut ctx = unsafe { &mut *ctx }; let mut driver_data = driver::Driver::new(ctx)?; ctx.pDriverData = &mut driver_data as *mut _ as _; std::mem::forget(driver_data); ctx.version_major = 1; ctx.version_minor = 8; ctx.max_profiles = VDPAU_MAX_PROFILES as _; ctx.max_entrypoints = VDPAU_MAX_ENTRYPOINTS as _; ctx.max_attributes = VDPAU_MAX_CONFIG_ATTRIBUTES as _; ctx.max_image_formats = VDPAU_MAX_IMAGE_FORMATS as _; ctx.max_subpic_formats = VDPAU_MAX_SUBPICTURE_FORMATS as _; ctx.max_display_attributes = VDPAU_MAX_DISPLAY_ATTRIBUTES as _; ctx.str_vendor = b"nvidia-va-driver\0".as_ptr() as _; let vtable = unsafe { &mut *ctx.vtable }; vtable.vaTerminate = Some(terminate); vtable.vaQueryConfigProfiles = Some(vtable::vaQueryConfigProfiles); vtable.vaQueryConfigEntrypoints = Some(vtable::vaQueryConfigEntrypoints); vtable.vaGetConfigAttributes = Some(vtable::vaGetConfigAttributes); vtable.vaCreateConfig = Some(vtable::vaCreateConfig); vtable.vaDestroyConfig = Some(vtable::vaDestroyConfig); vtable.vaQueryConfigAttributes = Some(vtable::vaQueryConfigAttributes); vtable.vaCreateSurfaces = Some(vtable::vaCreateSurfaces); vtable.vaDestroySurfaces = Some(vtable::vaDestroySurfaces); vtable.vaCreateContext = Some(vtable::vaCreateContext); vtable.vaDestroyContext = Some(vtable::vaDestroyContext); vtable.vaCreateBuffer = Some(vtable::vaCreateBuffer); vtable.vaBufferSetNumElements = Some(vtable::vaBufferSetNumElements); vtable.vaMapBuffer = Some(vtable::vaMapBuffer); vtable.vaUnmapBuffer = Some(vtable::vaUnmapBuffer); vtable.vaDestroyBuffer = Some(vtable::vaDestroyBuffer); vtable.vaBeginPicture = Some(vtable::vaBeginPicture); vtable.vaRenderPicture = Some(vtable::vaRenderPicture); vtable.vaEndPicture = Some(vtable::vaEndPicture); vtable.vaSyncSurface = Some(vtable::vaSyncSurface); vtable.vaQuerySurfaceStatus = Some(vtable::vaQuerySurfaceStatus); vtable.vaQuerySurfaceError = Some(vtable::vaQuerySurfaceError); vtable.vaPutSurface = Some(vtable::vaPutSurface); vtable.vaQueryImageFormats = Some(vtable::vaQueryImageFormats); vtable.vaCreateImage = Some(vtable::vaCreateImage); vtable.vaDeriveImage = Some(vtable::vaDeriveImage); vtable.vaDestroyImage = Some(vtable::vaDestroyImage); vtable.vaSetImagePalette = Some(vtable::vaSetImagePalette); vtable.vaGetImage = Some(vtable::vaGetImage); vtable.vaPutImage = Some(vtable::vaPutImage); vtable.vaQuerySubpictureFormats = Some(vtable::vaQuerySubpictureFormats); vtable.vaCreateSubpicture = Some(vtable::vaCreateSubpicture); vtable.vaDestroySubpicture = Some(vtable::vaDestroySubpicture); vtable.vaSetSubpictureImage = Some(vtable::vaSetSubpictureImage); vtable.vaSetSubpictureChromakey = Some(vtable::vaSetSubpictureChromakey); vtable.vaSetSubpictureGlobalAlpha = Some(vtable::vaSetSubpictureGlobalAlpha); vtable.vaAssociateSubpicture = Some(vtable::vaAssociateSubpicture); vtable.vaDeassociateSubpicture = Some(vtable::vaDeassociateSubpicture); vtable.vaQueryDisplayAttributes = Some(vtable::vaQueryDisplayAttributes); vtable.vaGetDisplayAttributes = Some(vtable::vaGetDisplayAttributes); vtable.vaSetDisplayAttributes = Some(vtable::vaSetDisplayAttributes); vtable.vaBufferInfo = Some(vtable::vaBufferInfo); vtable.vaLockSurface = Some(vtable::vaLockSurface); vtable.vaUnlockSurface = Some(vtable::vaUnlockSurface); vtable.vaGetSurfaceAttributes = Some(vtable::vaGetSurfaceAttributes); vtable.vaCreateSurfaces2 = Some(vtable::vaCreateSurfaces2); vtable.vaQuerySurfaceAttributes = Some(vtable::vaQuerySurfaceAttributes); vtable.vaAcquireBufferHandle = Some(vtable::vaAcquireBufferHandle); vtable.vaReleaseBufferHandle = Some(vtable::vaReleaseBufferHandle); vtable.vaCreateMFContext = Some(vtable::vaCreateMFContext); vtable.vaMFAddContext = Some(vtable::vaMFAddContext); vtable.vaMFReleaseContext = Some(vtable::vaMFReleaseContext); vtable.vaMFSubmit = Some(vtable::vaMFSubmit); vtable.vaCreateBuffer2 = Some(vtable::vaCreateBuffer2); vtable.vaQueryProcessingRate = Some(vtable::vaQueryProcessingRate); vtable.vaExportSurfaceHandle = Some(vtable::vaExportSurfaceHandle); Ok(()) } #[no_mangle] pub extern "C" fn __vaDriverInit_1_8(ctx: va::VADriverContextP) -> va::VAStatus { match va_driver_init(ctx) { Ok(_) => va::VA_STATUS_SUCCESS as _, Err(e) => e, } } pub(crate) extern "C" fn terminate(ctx: va::VADriverContextP) -> va::VAStatus { unsafe { ((*ctx).pDriverData as *mut driver::Driver).drop_in_place() }; va::VA_STATUS_SUCCESS as _ }
use std::collections::HashMap; use std::thread; use std::time::Duration; use std::io; extern crate iris; use iris::portfire; use iris::script::{self, Cue}; extern crate clap; use clap::App; #[cfg(feature="tts")] use iris::tts::TTS; fn main() { let args = App::new("IRIS") .args_from_usage(" --dry-run 'Don't really fire, just print the fire actions' --skip-checks 'Skip all board related checks' --skip-sleep 'Skip all sleep commands' <script> 'Path to script file' ") .get_matches(); let scriptpath = args.value_of("script").unwrap(); let dryrun = args.is_present("dry-run"); let skipchecks = args.is_present("skip-checks"); let skipsleep = args.is_present("skip-sleep"); // Read script let script = script::Script::from_file(&scriptpath).unwrap(); // Find Portfires and map to script let mut discovered_portfires = portfire::autodiscover().unwrap(); let mut portfires: HashMap<String, portfire::Board> = HashMap::new(); for (board_id, mac) in script.boards.iter() { let mut board_found = false; for portfire in &mut discovered_portfires { if portfire.mac == *mac { portfires.insert(board_id.clone(), portfire.clone()); board_found = true; } } if !board_found && !skipchecks { println!("Didn't find board {} {:2X}:{:2X}:{:2X}:{:2X}:{:2X}:{:2X}", board_id, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); return; } } // Check all portfires are behaving and have correct continuities let mut got_error = false; for (board_id, board) in portfires.iter() { // Check ping board.ping().unwrap(); // Bus voltage while disarmed should be 0 let v = board.bus_voltage().unwrap(); if v > 1.0 { println!("Board {} bus voltage {}v ERROR", board_id, v); got_error = true; } // Check all continuities are correct let conts = board.continuities().unwrap(); for (ch, &(ref ch_bid, ref ch_num)) in script.channels.iter() { if ch_bid == board_id { let ch_cont = conts[*ch_num as usize - 1]; if ch_cont == 255 { println!("Board {} ch#{} '{}' not connected, ERROR", board_id, ch_num, ch); got_error = true; } } } // Check all unassigned channels are not connected for num in 1..31 { let mut channel_used = false; for &(ref ch_bid, ref ch_num) in script.channels.values() { if ch_bid == board_id && *ch_num == num { channel_used = true; } } if !channel_used && conts[num as usize - 1] != 255 { println!("Board {} unused channel #{:02} connected, ERROR", board_id, num); got_error = true; } } // Check the continuity test voltage is not pulled down if conts[30] < 30 { println!("Board {} continuity voltage {}, ERROR", board_id, conts[30]); got_error = true; } // Check the boards arm and the bus voltage comes up board.arm().unwrap(); let v = board.bus_voltage().unwrap(); if v < 2.5 { println!("Board {} arm voltage {}, ERROR", board_id, v); got_error = true; } } // Quit early if anything went wrong in setup if got_error && !skipchecks { println!("An error occurred, disarming and quitting."); for board in portfires.values() { board.disarm().unwrap(); } return; } // Start up the TTS engine #[cfg(feature="tts")] let tts = TTS::new(); // Run the show! for cue in script.cues { match cue { Cue::Sleep { time } => { if !skipsleep { thread::sleep(Duration::from_secs(time)); } }, Cue::Pause => { let mut l = String::new(); let _ = io::stdin().read_line(&mut l); }, Cue::Print { message } => { println!("{}", message); }, Cue::Say { message } => { #[cfg(feature="tts")] tts.say(&message); #[cfg(not(feature="tts"))] println!("SAYING: {}", message); }, Cue::Fire { channels } => { // Accumulate numerical channels to fire on each board let mut board_channels: HashMap<String, Vec<u8>> = HashMap::new(); for channel in channels { let (ref board_id, ref ch_num) = script.channels[&channel]; let chs = board_channels.entry(board_id.clone()) .or_insert(Vec::new()); (*chs).push(*ch_num); } // Send the fire commands for (ref board_id, ref chans) in board_channels.iter() { let mut firing_chans = [0u8; 3]; for (idx, chan) in chans.iter().enumerate() { firing_chans[idx] = *chan; } if !dryrun { let portfire = &portfires[&board_id.to_string()]; portfire.fire_retry(firing_chans); } else { println!("FIRING Board {} Channels {:?}", board_id, firing_chans); } } }, _ => {}, } } // Wait for final user input before quitting, in case of pending TTS let mut l = String::new(); let _ = io::stdin().read_line(&mut l); // Show over, disarm for board in portfires.values() { let _ = board.disarm(); } }
#[doc = "Reader of register CR"] pub type R = crate::R<u32, super::CR>; #[doc = "Writer for register CR"] pub type W = crate::W<u32, super::CR>; #[doc = "Register CR `reset()`'s with value 0"] impl crate::ResetValue for super::CR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `EN`"] pub type EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EN`"] pub struct EN_W<'a> { w: &'a mut W, } impl<'a> EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `WRIE`"] pub type WRIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WRIE`"] pub struct WRIE_W<'a> { w: &'a mut W, } impl<'a> WRIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `RDIE`"] pub type RDIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RDIE`"] pub struct RDIE_W<'a> { w: &'a mut W, } impl<'a> RDIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `EIE`"] pub type EIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EIE`"] pub struct EIE_W<'a> { w: &'a mut W, } impl<'a> EIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `DPC`"] pub type DPC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DPC`"] pub struct DPC_W<'a> { w: &'a mut W, } impl<'a> DPC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `PORT_ADDRESS`"] pub type PORT_ADDRESS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PORT_ADDRESS`"] pub struct PORT_ADDRESS_W<'a> { w: &'a mut W, } impl<'a> PORT_ADDRESS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1f << 8)) | (((value as u32) & 0x1f) << 8); self.w } } impl R { #[doc = "Bit 0 - Peripheral enable"] #[inline(always)] pub fn en(&self) -> EN_R { EN_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Register write interrupt enable"] #[inline(always)] pub fn wrie(&self) -> WRIE_R { WRIE_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Register Read Interrupt Enable"] #[inline(always)] pub fn rdie(&self) -> RDIE_R { RDIE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Error interrupt enable"] #[inline(always)] pub fn eie(&self) -> EIE_R { EIE_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 7 - Disable Preamble Check"] #[inline(always)] pub fn dpc(&self) -> DPC_R { DPC_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bits 8:12 - Slaves's address"] #[inline(always)] pub fn port_address(&self) -> PORT_ADDRESS_R { PORT_ADDRESS_R::new(((self.bits >> 8) & 0x1f) as u8) } } impl W { #[doc = "Bit 0 - Peripheral enable"] #[inline(always)] pub fn en(&mut self) -> EN_W { EN_W { w: self } } #[doc = "Bit 1 - Register write interrupt enable"] #[inline(always)] pub fn wrie(&mut self) -> WRIE_W { WRIE_W { w: self } } #[doc = "Bit 2 - Register Read Interrupt Enable"] #[inline(always)] pub fn rdie(&mut self) -> RDIE_W { RDIE_W { w: self } } #[doc = "Bit 3 - Error interrupt enable"] #[inline(always)] pub fn eie(&mut self) -> EIE_W { EIE_W { w: self } } #[doc = "Bit 7 - Disable Preamble Check"] #[inline(always)] pub fn dpc(&mut self) -> DPC_W { DPC_W { w: self } } #[doc = "Bits 8:12 - Slaves's address"] #[inline(always)] pub fn port_address(&mut self) -> PORT_ADDRESS_W { PORT_ADDRESS_W { w: self } } }
#[doc = "Reader of register SECWM2R2"] pub type R = crate::R<u32, super::SECWM2R2>; #[doc = "Writer for register SECWM2R2"] pub type W = crate::W<u32, super::SECWM2R2>; #[doc = "Register SECWM2R2 `reset()`'s with value 0x0f00_0f00"] impl crate::ResetValue for super::SECWM2R2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0f00_0f00 } } #[doc = "Reader of field `PCROP2_PSTRT`"] pub type PCROP2_PSTRT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PCROP2_PSTRT`"] pub struct PCROP2_PSTRT_W<'a> { w: &'a mut W, } impl<'a> PCROP2_PSTRT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x7f) | ((value as u32) & 0x7f); self.w } } #[doc = "Reader of field `PCROP2EN`"] pub type PCROP2EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PCROP2EN`"] pub struct PCROP2EN_W<'a> { w: &'a mut W, } impl<'a> PCROP2EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `HDP2_PEND`"] pub type HDP2_PEND_R = crate::R<u8, u8>; #[doc = "Write proxy for field `HDP2_PEND`"] pub struct HDP2_PEND_W<'a> { w: &'a mut W, } impl<'a> HDP2_PEND_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x7f << 16)) | (((value as u32) & 0x7f) << 16); self.w } } #[doc = "Reader of field `HDP2EN`"] pub type HDP2EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HDP2EN`"] pub struct HDP2EN_W<'a> { w: &'a mut W, } impl<'a> HDP2EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bits 0:6 - PCROP2_PSTRT"] #[inline(always)] pub fn pcrop2_pstrt(&self) -> PCROP2_PSTRT_R { PCROP2_PSTRT_R::new((self.bits & 0x7f) as u8) } #[doc = "Bit 15 - PCROP2EN"] #[inline(always)] pub fn pcrop2en(&self) -> PCROP2EN_R { PCROP2EN_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bits 16:22 - HDP2_PEND"] #[inline(always)] pub fn hdp2_pend(&self) -> HDP2_PEND_R { HDP2_PEND_R::new(((self.bits >> 16) & 0x7f) as u8) } #[doc = "Bit 31 - HDP2EN"] #[inline(always)] pub fn hdp2en(&self) -> HDP2EN_R { HDP2EN_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:6 - PCROP2_PSTRT"] #[inline(always)] pub fn pcrop2_pstrt(&mut self) -> PCROP2_PSTRT_W { PCROP2_PSTRT_W { w: self } } #[doc = "Bit 15 - PCROP2EN"] #[inline(always)] pub fn pcrop2en(&mut self) -> PCROP2EN_W { PCROP2EN_W { w: self } } #[doc = "Bits 16:22 - HDP2_PEND"] #[inline(always)] pub fn hdp2_pend(&mut self) -> HDP2_PEND_W { HDP2_PEND_W { w: self } } #[doc = "Bit 31 - HDP2EN"] #[inline(always)] pub fn hdp2en(&mut self) -> HDP2EN_W { HDP2EN_W { w: self } } }
#[allow(unused_imports)] use proconio::{marker::*, *}; #[fastout] fn main() { input! { n: i32, k: i32, } let mut count = 0; for red in 1..=n { for blue in 1..=n { let white = k - red - blue; if 1 <= white && white <= n { count += 1; } } } println!("{}", count); }
use os; use game; use gl::types::GLfloat; use std::num::Float; pub fn render(window: &os::Window, world: &game::World) -> Vec<GLfloat> { let mut vertices: Vec<GLfloat> = vec![]; vertices.push_all(&render_player(&world.player)[..]); vertices.push_all(&render_player(&world.opponent)[..]); vertices.push_all(&render_ball(&world.ball)[..]); vertices.push_all(&render_net()[..]); let proportions = window.get_canvas_proportions(); let mut parity = false; vertices.map_in_place(|v| { parity = !parity; if parity { v } else { (v * proportions) + proportions - 1.0 } }) } fn render_net() -> Vec<GLfloat> { vec![ -0.01, -1.0, -0.01, -0.25, 0.01, -0.25, 0.01, -0.25, 0.01, -1.0, -0.01, -1.0, ] } fn render_player(player: &game::Player) -> Vec<GLfloat> { let mut vertices: Vec<GLfloat> = vec![]; vertices.push_all(&render_circle(player.x, player.y, 0.13)[..]); vertices.push_all(&render_circle(player.x, player.y + 0.13, 0.1)[..]); vertices } fn render_ball(ball: &game::Ball) -> Vec<GLfloat> { render_circle(ball.circle.center.x, ball.circle.center.y, ball.circle.radius) } fn render_circle(x: f32, y: f32, r: f32) -> Vec<GLfloat> { let mut vertex: Vec<GLfloat> = vec![]; let precision = 400is; let tau: f32 = 2.0 * 3.14; let startx: f32 = x + (r * (tau / precision as f32).cos()); let starty: f32 = y + (r * (tau / precision as f32).sin()); for i in 1..(precision + 1) { vertex.push(x); vertex.push(y); vertex.push(x + (r * (i as f32 * tau / precision as f32).cos())); vertex.push(y + (r * (i as f32 * tau / precision as f32).sin())); vertex.push(x + (r * ((i + 1) as f32 * tau / precision as f32).cos())); vertex.push(y + (r * ((i + 1) as f32 * tau / precision as f32).sin())); } vertex.pop(); vertex.pop(); vertex.push(startx); vertex.push(starty); vertex }
use std::{ alloc::{self, Layout}, sync::RwLock, mem }; use owning_ref::*; /// An error that may be due to insertion of duplicate key. #[derive(Debug)] pub struct DupErr { pub key: i32 } #[derive(Clone, Debug)] struct Item<V> { key: i32, value: V, state: CellState } /// Thread-safe HashMap. /// A wrapper over the `HashMap<V>` pub struct TsHashMap<V> { hm: RwLock<HashMap<V>> } impl<V: Eq + Clone> TsHashMap<V> { /// Creates an empty `TsHashMap`. /// /// # Examples /// /// ``` /// use mk_collections::TsHashMap; /// /// let map = TsHashMap::<i32>::new(); /// assert_eq!(map.capacity(), 0); /// ``` pub fn new() -> TsHashMap<V> { TsHashMap{ hm: RwLock::new(HashMap::new()) } } /// Creates an empty `TsHashMap` with the specified capacity. /// /// # Examples /// /// ``` /// use mk_collections::TsHashMap; /// /// let map = TsHashMap::<i32>::with_capacity(10); /// assert_eq!(map.capacity(), 10); /// ``` pub fn with_capacity(capacity: usize) -> TsHashMap<V> { TsHashMap { hm: RwLock::new(HashMap::with_capacity(capacity)) } } /// Gets capacity pub fn capacity(&self) -> usize { let lock = self.hm.read().unwrap(); lock.capacity() } /// Inserts the new key-value pair if it's not or updates the value if key is aloredy present in the map. /// If it updates the old value will be returned, otherwise - [`None`]. /// /// # Examples /// /// ``` /// use mk_collections::TsHashMap; /// /// let mut map = TsHashMap::new(); /// assert!(map.insert(3, "a").is_none()); /// assert_eq!(map.insert(3, "b").unwrap(), "a"); /// ``` pub fn insert(&self, key: i32, value: V) -> Option<V> { let mut map = self.hm.write().unwrap(); map.insert(key, value) } /// Returns a reference to the value corresponding to the key, or [`None`] if it didn't found in the map. /// /// # Examples /// /// ``` /// use mk_collections::TsHashMap; /// /// let mut map = TsHashMap::new(); /// assert!(map.insert(3, "a").is_none()); /// assert_eq!(*map.find(3).unwrap(), "a"); /// assert!(map.find(4).is_none()); /// ``` pub fn find<'ret, 'me: 'ret>(&'me self, key: i32) -> Option<RwLockReadGuardRef<'ret, HashMap<V>, V>> { let lock = self.hm.read().unwrap(); if lock.contains_key(key) { let guard_ref = RwLockReadGuardRef::new(lock); return Some(guard_ref.map(|hm| hm.find(key).unwrap())); } else { return None; } } /// Removes a key from the map, returning the value at the key if the key /// was previously in the map. /// /// # Examples /// /// ``` /// use mk_collections::TsHashMap; /// /// let mut map = TsHashMap::new(); /// assert!(map.insert(3, "a").is_none()); /// /// map.remove(3); /// assert!(map.find(3).is_none()); /// ``` pub fn remove<'ret, 'me: 'ret>(&'me self, key: i32) -> Option<RwLockWriteGuardRef<'ret, HashMap<V>, V>> { let write_lock = self.hm.write().unwrap(); if write_lock.contains_key(key) { let guard_ref = RwLockWriteGuardRefMut::new(write_lock); return Some(guard_ref.map(|hm| hm.remove(key).unwrap())); } None } } /// A hash map implemented with linear probing. pub struct HashMap<V> { ht: Vec<Item<V>>, count: usize } #[derive(Clone, PartialEq, Debug)] enum CellState { Empty, Filled, Deleted } impl<V> HashMap<V> { /// Creates an empty `HashMap`. /// /// # Examples /// /// ``` /// use mk_collections::HashMap; /// /// let mut map = HashMap::<i32>::new(); /// assert_eq!(map.capacity(), 0); /// ``` pub fn new() -> HashMap<V> { HashMap::with_capacity(0) } /// Creates an empty `HashMap` with the specified capacity. /// /// # Examples /// /// ``` /// use mk_collections::HashMap; /// /// let mut map = HashMap::<i32>::with_capacity(10); /// assert_eq!(map.capacity(), 10); /// ``` pub fn with_capacity(capacity: usize) -> HashMap<V> { HashMap { ht: init_table(capacity), count: 0 } } /// Gets capacity pub fn capacity(&self) -> usize { self.ht.capacity() } /// Returns a reference to the value corresponding to the key, or [`None`] if it didn't found in the map. /// /// # Examples /// /// ``` /// use mk_collections::HashMap; /// /// let mut map = HashMap::new(); /// assert!(map.insert_new(3, "a").is_ok()); /// assert_eq!(*map.find(3).unwrap(), "a"); /// assert!(map.find(4).is_none()); /// ``` pub fn find(&self, key: i32) -> Option<&V> { if let Some(found) = self.find_index(key) { return Some(&self.ht[found].value); } else { return None; } } /// Inserts a new key-value pair into the map. /// /// If the map already have the key present, it returns error result `DupErr`. /// To modify the value of already present key use the put method. /// /// # Examples /// /// ``` /// use mk_collections::HashMap; /// /// let mut map = HashMap::new(); /// assert!(map.insert_new(3, "a").is_ok()); /// assert_eq!(*map.find(3).unwrap(), "a"); /// ``` pub fn insert_new(&mut self, key: i32, value: V) -> Result<(), DupErr> { if self.count == self.ht.capacity() { self.resize(); } let res = self.insert_inner(key, value); self.count += 1; res } /// Returns `true` if the map have this key present, and `false` - otherwise. /// /// # Examples /// /// ``` /// use mk_collections::HashMap; /// /// let mut map = HashMap::new(); /// assert!(map.insert(3, "a").is_none()); /// assert!(map.insert(5, "a").is_none()); /// /// assert!(map.contains_key(3)); /// assert!(map.contains_key(5)); /// ``` pub fn contains_key(&self, key: i32) -> bool { self.find_index(key).is_some() } /// Inserts the new key-value pair if it's not or updates the value if key is aloredy present in the map. /// If it updates the old value will be returned, otherwise - [`None`]. /// /// # Examples /// /// ``` /// use mk_collections::HashMap; /// /// let mut map = HashMap::new(); /// assert!(map.insert(3, "a").is_none()); /// assert_eq!(map.insert(3, "b").unwrap(), "a"); /// ``` pub fn insert(&mut self, key: i32, value: V) -> Option<V> { if let Some(index) = self.find_index(key) { Some(mem::replace(&mut self.ht[index].value, value)) } else { self.insert_new(key, value).expect("cannot insert key-value pair"); None } } /// Removes a key from the map, returning the value at the key if the key /// was previously in the map. /// /// # Examples /// /// ``` /// use mk_collections::HashMap; /// /// let mut map = HashMap::new(); /// assert!(map.insert(3, "a").is_none()); /// /// assert_eq!(*map.remove(3).unwrap(), "a"); /// assert!(map.remove(3).is_none()); /// ``` pub fn remove(&mut self, key: i32) -> Option<&V> { if let Some(index) = self.find_index(key) { self.ht[index].state = CellState::Deleted; self.count -= 1; return Some(&self.ht[index].value); } else { return None; } } fn find_index(&self, key: i32) -> Option<usize> { if self.capacity() == 0 { return None; } let i = self.index(key); let item = &self.ht[i]; if item.key == key && item.state == CellState::Filled { return Some(i); } else { let mut index = self.next_index(i); while index != i && { let item = &self.ht[index]; ((item.state == CellState::Filled && item.key != key) || item.state == CellState::Deleted) } { index = self.next_index(index); } if index == i || self.ht[index].state == CellState::Empty { return Option::None; } else { return Option::Some(index) } } } fn insert_inner(&mut self, key: i32, value: V) -> Result<(), DupErr> { let index = self.index(key); if self.ht[index].state == CellState::Filled { let item = &self.ht[index]; if item.key == key { return Err(DupErr { key }); } else { let mut index = self.next_index(index); while self.ht[index].state == CellState::Filled { if self.ht[index].key == key { return Err(DupErr { key }); } index = self.next_index(index); } self.put_to_index(index, key, value); } } else { self.put_to_index(index, key, value); } Ok(()) } fn put_to_index(&mut self, index: usize, key: i32, value: V) { self.ht[index] = Item { key, value, state: CellState::Filled }; } fn resize(&mut self) { let capacity = if self.ht.is_empty() { 1 } else { self.capacity() * 2 }; let ht = init_table(capacity); let mut old_ht = mem::replace(&mut self.ht, ht); for item in old_ht.drain(..) .enumerate() .filter(|(_, item)| item.state == CellState::Filled) .map(|(_, item)| item) { self.insert_inner(item.key, item.value).unwrap(); } } fn index(&self, key: i32) -> usize { key as usize % self.ht.capacity() } fn next_index(&self, index: usize) -> usize { (index + 1) % self.ht.capacity() } } fn init_table<V>(capacity: usize) -> Vec<Item<V>> { let align = mem::align_of::<Item<V>>(); let elem_size = mem::size_of::<Item<V>>(); let num_bytes = capacity * elem_size; let ptr = unsafe { alloc::alloc( Layout::from_size_align(num_bytes, align) .expect("Bad layout")) }; let mut res = unsafe { Vec::from_raw_parts(ptr as *mut Item<V>, capacity, capacity) }; for i in 0..capacity { res[i].state = CellState::Empty; } res }
#![allow(clippy::type_complexity)] use crate::components::{ keyboard_movement::{Direction, KeyboardMovement}, speed::Speed, }; use oxygengine::prelude::*; // system that moves tagged entities. pub struct KeyboardMovementSystem; impl<'s> System<'s> for KeyboardMovementSystem { type SystemData = ( Read<'s, InputController>, ReadExpect<'s, AppLifeCycle>, Read<'s, UserInterfaceRes>, ReadStorage<'s, Speed>, WriteStorage<'s, KeyboardMovement>, WriteStorage<'s, CompositeTransform>, WriteStorage<'s, CompositeSpriteAnimation>, ); fn run( &mut self, ( input, lifecycle, user_interface, speed, mut keyboard_movement, mut transform, mut animation, ): Self::SystemData, ) { if user_interface.last_frame_captured() { return; } let dt = lifecycle.delta_time_seconds(); let hor = -input.axis_or_default("move-left") + input.axis_or_default("move-right"); let ver = -input.axis_or_default("move-up") + input.axis_or_default("move-down"); let diff = Vec2::new(hor, ver) * dt; let is_moving = hor.abs() + ver.abs() > 0.01; let iter = ( &mut keyboard_movement, &speed, &mut transform, &mut animation, ) .join(); for (keyboard_movement, speed, transform, animation) in iter { transform.set_translation(transform.get_translation() + diff * speed.0); let direction = if !is_moving { keyboard_movement.direction } else if hor.abs() > 0.5 { if hor < 0.5 { Direction::West } else { Direction::East } } else if ver < 0.5 { Direction::North } else { Direction::South }; let was_moving = keyboard_movement.is_moving; let old_direction = keyboard_movement.direction; if direction != old_direction || is_moving != was_moving { if is_moving { let name = match direction { Direction::East => "walk-east", Direction::West => "walk-west", Direction::North => "walk-north", Direction::South => "walk-south", }; animation.play(name, 4.0, true); } else { let name = match direction { Direction::East => "idle-east", Direction::West => "idle-west", Direction::North => "idle-north", Direction::South => "idle-south", }; animation.play(name, 4.0, true); } keyboard_movement.is_moving = is_moving; keyboard_movement.direction = direction; } } } }
// Copyright 2019 Liebi Technologies. // This file is part of Bifrost. // Bifrost is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Bifrost is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Bifrost. If not, see <http://www.gnu.org/licenses/>. //! Offers macros that build extrinsics for custom runtime modules based on the metadata. //! Additionally, some predefined extrinsics for common runtime modules are implemented. /// Generates the extrinsic's call field for a given module and call passed as &str /// # Arguments /// /// * 'node_metadata' - This crate's parsed node metadata as field of the API. /// * 'module' - Module name as &str for which the call is composed. /// * 'call' - Call name as &str /// * 'args' - Optional sequence of arguments of the call. They are not checked against the metadata. /// As of now the user needs to check himself that the correct arguments are supplied. #[macro_export] macro_rules! compose_call { ($node_metadata: expr, $module: expr, $call_name: expr $(, $args: expr) *) => { { let mut meta = $node_metadata; meta.retain(|m| !m.calls.is_empty()); let module_index = meta .iter().position(|m| m.name == $module).expect("Module not found in Metadata"); let call_index = meta[module_index].calls .iter().position(|c| c.name == $call_name).expect("Call not found in Module"); ([module_index as u8, call_index as u8] $(, ($args)) *) } }; } /// Generates an Unchecked extrinsic for a given call /// # Arguments /// /// * 'signer' - AccountKey that is used to sign the extrinsic. /// * 'call' - call as returned by the compose_call! macro or via substrate's call enums. /// * 'nonce' - signer's account nonce: u32 /// * 'genesis_hash' - sr-primitives::Hash256/[u8; 32]. /// * 'runtime_spec_version' - RuntimeVersion.spec_version/u32 #[macro_export] macro_rules! compose_extrinsic_offline { ($signer: expr, $call: expr, $nonce: expr, $genesis_hash: expr, $runtime_spec_version: expr) => {{ use $crate::extrinsic::xt_primitives::*; use $crate::extrinsic::node_primitives::AccountId; let extra = GenericExtra::new($nonce); let raw_payload = SignedPayload::from_raw( $call.clone(), extra.clone(), ( $runtime_spec_version, $genesis_hash, $genesis_hash, (), (), (), (), ), ); let signature = raw_payload.using_encoded(|payload| $signer.sign(payload)); let mut arr: [u8; 32] = Default::default(); arr.clone_from_slice($signer.public().as_ref()); UncheckedExtrinsicV4::new_signed( $call, GenericAddress::from(AccountId::from(arr)), signature.into(), extra ) }}; } /// Generates an Unchecked extrinsic for a given module and call passed as a &str. /// # Arguments /// /// * 'api' - This instance of API. If the *signer* field is not set, an unsigned extrinsic will be generated. /// * 'module' - Module name as &str for which the call is composed. /// * 'call' - Call name as &str /// * 'args' - Optional sequence of arguments of the call. They are not checked against the metadata. /// As of now the user needs to check himself that the correct arguments are supplied. #[macro_export] #[cfg(feature = "std")] macro_rules! compose_extrinsic { ($api: expr, $module: expr, $call: expr $(, $args: expr) *) => { { use $crate::extrinsic::codec::Compact; use $crate::extrinsic::xt_primitives::*; info!("Composing generic extrinsic for module {:?} and call {:?}", $module, $call); let call = $crate::compose_call!($api.metadata.clone(), $module, $call $(, ($args)) *); if let Some(signer) = $api.signer.clone() { $crate::compose_extrinsic_offline!( signer, call.clone(), $api.get_nonce().unwrap(), $api.genesis_hash, $api.runtime_version.spec_version ) } else { UncheckedExtrinsicV4 { signature: None, function: call.clone(), } } } }; } #[cfg(test)] mod tests { use codec::{Compact, Encode}; use keyring::AccountKeyring; use primitives::{sr25519, crypto::Pair}; use node_primitives::{AccountIndex, AccountId}; use crate::extrinsic::xt_primitives::*; use crate::utils::*; use crate::Api; use eos_chain::{ Action, ActionReceipt, Checksum256, get_proof, IncrementalMerkle, ProducerSchedule, SignedBlockHeader }; use std::{ error::Error, fs::File, io::Read, path::Path, str::FromStr, }; // use substrate_primitives::crypto::UncheckedInto; #[test] fn test_init_schedule() { env_logger::init(); let url = "127.0.0.1:9944"; let from = AccountKeyring::Alice.pair(); let api = Api::new(format!("ws://{}", url)).set_signer(from.clone()); let schedule = r#" { "version": 1, "producers": [ { "producer_name": "batinthedark", "block_signing_key": "EOS6dwoM8XGMQn49LokUcLiony7JDkbHrsFDvh5svLvPDkXtvM7oR" }, { "producer_name": "bighornsheep", "block_signing_key": "EOS5xfwWr4UumKm4PqUGnyCrFWYo6j5cLioNGg5yf4GgcTp2WcYxf" }, { "producer_name": "bigpolarbear", "block_signing_key": "EOS6oZi9WjXUcLionUtSiKRa4iwCW5cT6oTzoWZdENXq1p2pq53Nv" }, { "producer_name": "clevermonkey", "block_signing_key": "EOS5mp5wmRyL5RH2JUeEh3eoZxkJ2ZZJ9PVd1BcLioNuq4PRCZYxQ" }, { "producer_name": "funnyhamster", "block_signing_key": "EOS7A9BoRetjpKtE3sqA6HRykRJ955MjQ5XdRmCLionVte2uERL8h" }, { "producer_name": "gorillapower", "block_signing_key": "EOS8X5NCx1Xqa1xgQgBa9s6EK7M1SjGaDreAcLion4kDVLsjhQr9n" }, { "producer_name": "hippopotamus", "block_signing_key": "EOS7qDcxm8YtAZUA3t9kxNGuzpCLioNnzpTRigi5Dwsfnszckobwc" }, { "producer_name": "hungryolddog", "block_signing_key": "EOS6tw3AqqVUsCbchYRmxkPLqGct3vC63cEzKgVzLFcLionoY8YLQ" }, { "producer_name": "iliketurtles", "block_signing_key": "EOS6itYvNZwhqS7cLion3xp3rLJNJAvKKegxeS7guvbBxG1XX5uwz" }, { "producer_name": "jumpingfrogs", "block_signing_key": "EOS7oVWG413cLioNG7RU5Kv7NrPZovAdRSP6GZEG4LFUDWkgwNXHW" }, { "producer_name": "lioninjungle", "block_signing_key": "EOS5BcLionmbgEtcmu7qY6XKWaE1q31qCQSsd89zXij7FDXQnKjwk" }, { "producer_name": "littlerabbit", "block_signing_key": "EOS65orCLioNFkVT5uDF7J63bNUk97oF8T83iWfuvbSKWYUUq9EWd" }, { "producer_name": "proudrooster", "block_signing_key": "EOS5qBd3T6nmLRsuACLion346Ue8UkCwvsoS5f3EDC1jwbrEiBDMX" }, { "producer_name": "pythoncolors", "block_signing_key": "EOS8R7GB5CLionUEy8FgGksGAGtc2cbcQWgty3MTAgzJvGTmtqPLz" }, { "producer_name": "soaringeagle", "block_signing_key": "EOS6iuBqJKqSK82QYCGuM96gduQpQG8xJsPDU1CLionPMGn2bT4Yn" }, { "producer_name": "spideronaweb", "block_signing_key": "EOS6M4CYEDt3JDKS6nsxMnUcdCLioNcbyEzeAwZsQmDcoJCgaNHT8" }, { "producer_name": "ssssssssnake", "block_signing_key": "EOS8SDhZ5CLioNLie9mb7kDu1gHfDXLwTvYBSxR1ccYSJERvutLqG" }, { "producer_name": "thebluewhale", "block_signing_key": "EOS6Wfo1wwTPzzBVT8fe3jpz8vxCnf77YscLionBnw39iGzFWokZm" }, { "producer_name": "thesilentowl", "block_signing_key": "EOS7y4hU89NJ658H1KmAdZ6A585bEVmSV8xBGJ3SbQM4Pt3pcLion" }, { "producer_name": "wealthyhorse", "block_signing_key": "EOS5i1HrfxfHLRJqbExgRodhrZwp4dcLioNn4xZWCyhoBK6DNZgZt" } ] } "#; let v2_producers: Result<eos_chain::ProducerSchedule, _> = serde_json::from_str(schedule); assert!(v2_producers.is_ok()); let v2_producers = v2_producers.unwrap(); // let s = hex::encode(schedule).into_bytes(); let json = "change_schedule_9313.json"; let signed_blocks_str = read_json_from_file(json); let signed_blocks_headers: Vec<SignedBlockHeader> = serde_json::from_str(&signed_blocks_str.unwrap()).unwrap(); let ids_json = "block_ids_list.json"; let ids_str = read_json_from_file(ids_json).unwrap(); let block_ids_list: Vec<Vec<String>> = serde_json::from_str(&ids_str).unwrap(); let block_ids_list: Vec<Vec<Checksum256>> = block_ids_list.iter().map(|ids| { ids.iter().map(|id| Checksum256::from_str(id).unwrap()).collect::<Vec<_>>() }).collect::<Vec<_>>(); let proposal = compose_call!( api.metadata.clone(), "BridgeEOS", "init_schedule", v2_producers, signed_blocks_headers, block_ids_list ); let xt: UncheckedExtrinsicV4<_> = compose_extrinsic!( api.clone(), "Sudo", "sudo", proposal ); println!("[+] Composed extrinsic: {:?}\n", xt); // send and watch extrinsic until finalized let tx_hash = api.send_extrinsic(xt.hex_encode()).unwrap(); println!("[+] Transaction got finalized. Hash: {:?}\n", tx_hash); } #[test] fn prove_action_should_be_ok() { let shedule_json = "schedule_v2.json"; let v2_producers_str = read_json_from_file(shedule_json); assert!(v2_producers_str.is_ok()); let v2_producers: Result<ProducerSchedule, _> = serde_json::from_str(&v2_producers_str.unwrap()); assert!(v2_producers.is_ok()); let v2_producers = v2_producers.unwrap(); let v2_schedule_hash = v2_producers.schedule_hash(); assert!(v2_schedule_hash.is_ok()); // get block headers let block_headers_json = "actions_verification_10776.json"; let signed_blocks_str = read_json_from_file(block_headers_json); let signed_blocks: Result<Vec<SignedBlockHeader>, _> = serde_json::from_str(&signed_blocks_str.unwrap()); assert!(signed_blocks.is_ok()); let signed_blocks_headers = signed_blocks.unwrap(); let node_count = 10774; let active_nodes: Vec<Checksum256> = vec![ "45c2c1cbc4b049d72a627124b05f5c476ae1cc87955fbea70bc8dbe549cf395a".into(), "d96747605aaed959630b23a28e0004f42a87eae93f51d5fe241735644a0c3921".into(), "937a489eea576d74a3d091cc4dcf1cb867f01e314ac7f1334f6cec00dfcee476".into(), "36cbf5d9c35b2538181bf7f8af4ee57c55c17e516eedd992a73bace9ca14a5c3".into(), "40e8bb864481e7bb01674ec3517c84e557869fea8160c4b2762d3e83d71d6034".into(), "afa502d408f5bdf1660fa9fe3a1fcb432462467e7eb403a8499392ee5297d8d1".into(), "f1329d3ee84040279460cbc87b6769b7363e477a832f73d639e0692a4042f093".into() ]; let merkle = IncrementalMerkle::new(node_count, active_nodes); // block ids list let ids_json = "block_ids_list_10776.json"; let ids_str = read_json_from_file(ids_json).unwrap(); let block_ids_list: Result<Vec<Vec<String>>, _> = serde_json::from_str(&ids_str); assert!(block_ids_list.is_ok()); let block_ids_list: Vec<Vec<Checksum256>> = block_ids_list.as_ref().unwrap().iter().map(|ids| { ids.iter().map(|id| Checksum256::from_str(id).unwrap()).collect::<Vec<_>>() }).collect::<Vec<_>>(); // read action merkle paths let action_merkle_paths_json = "action_merkle_paths.json"; let action_merkle_paths_str = read_json_from_file(action_merkle_paths_json); assert!(action_merkle_paths_str.is_ok()); let action_merkle_paths: Result<Vec<String>, _> = serde_json::from_str(&action_merkle_paths_str.unwrap()); assert!(action_merkle_paths.is_ok()); let action_merkle_paths = action_merkle_paths.unwrap(); let action_merkle_paths = { let mut path: Vec<Checksum256> = Vec::with_capacity(action_merkle_paths.len()); for path_str in action_merkle_paths { path.push(Checksum256::from_str(&path_str).unwrap()); } path }; let proof = get_proof(15, action_merkle_paths); assert!(proof.is_ok()); let actual_merkle_paths = proof.unwrap(); // get action let actions_json = "actions_from_10776.json"; let actions_str = read_json_from_file(actions_json); assert!(actions_str.is_ok()); let actions: Result<Vec<Action>, _> = serde_json::from_str(actions_str.as_ref().unwrap()); assert!(actions.is_ok()); let actions = actions.unwrap(); let action = actions[3].clone(); let action_receipt = r#"{ "receiver": "megasuper333", "act_digest": "eaa3b4bf845a1b41668ab7ca49fb5644fc91a6c0156dfd33911b4ec69d2e41d6", "global_sequence": 3040972, "recv_sequence": 1, "auth_sequence": [ [ "junglefaucet", 21 ] ], "code_sequence": 2, "abi_sequence": 2 }"#; let action_receipt: Result<ActionReceipt, _> = serde_json::from_str(action_receipt); assert!(action_receipt.is_ok()); let action_receipt = action_receipt.unwrap(); env_logger::init(); let url = "127.0.0.1:9944"; let from = AccountKeyring::Alice.pair(); let api = Api::new(format!("ws://{}", url)).set_signer(from.clone()); let proposal = compose_call!( api.metadata.clone(), "BridgeEOS", "prove_action", action, action_receipt, actual_merkle_paths, merkle, signed_blocks_headers, block_ids_list ); let xt: UncheckedExtrinsicV4<_> = compose_extrinsic!( api.clone(), "Sudo", "sudo", proposal ); println!("[+] Composed extrinsic: {:?}\n", xt); // send and watch extrinsic until finalized let tx_hash = api.send_extrinsic(xt.hex_encode()).unwrap(); println!("[+] Transaction got finalized. Hash: {:?}\n", tx_hash); } #[test] fn change_schedule_should_be_ok() { let json = "change_schedule_9313.json"; let signed_blocks_str = read_json_from_file(json); let signed_blocks_headers: Vec<SignedBlockHeader> = serde_json::from_str(&signed_blocks_str.unwrap()).unwrap(); let ids_json = "block_ids_list.json"; let ids_str = read_json_from_file(ids_json).unwrap(); let block_ids_list: Vec<Vec<String>> = serde_json::from_str(&ids_str).unwrap(); let block_ids_list: Vec<Vec<Checksum256>> = block_ids_list.iter().map(|ids| { ids.iter().map(|id| Checksum256::from_str(id).unwrap()).collect::<Vec<_>>() }).collect::<Vec<_>>(); let node_count = 9311; let active_nodes: Vec<Checksum256> = vec![ "0000245f60aa338bd246cb7598a14796ee0210f669f9c9b37f6ddad0b5765649".into(), "9d41d4581cab233fe68c4510cacd05d0cc979c53ae317ce9364040578037de6a".into(), "a397d1a6dc90389dc592ea144b1801c4b323c12b0b2f066aa55faa5892803317".into(), "0cf502411e185ea7e3cc790e0b757807987e767a81c463c3e4ee5970b7fd1c67".into(), "9f774a35e86ddb2d293da1bfe2e25b7b447fd3d9372ee580fce230a87fefa586".into(), "4d018eda9a22334ac0492489fdf79118d696eea52af3871a7e4bf0e2d5ab5945".into(), "acba7c7ee5c1d8ba97ea1a841707fbb2147e883b56544ba821814aebe086383e".into(), "afa502d408f5bdf1660fa9fe3a1fcb432462467e7eb403a8499392ee5297d8d1".into(), "4d723385cad26cf80c2db366f9666a3ef77679c098e07d1af48d523b64b1d460".into() ]; let merkle = IncrementalMerkle::new(node_count, active_nodes); env_logger::init(); let url = "127.0.0.1:9944"; let from = AccountKeyring::Alice.pair(); let api = Api::new(format!("ws://{}", url)).set_signer(from.clone()); let proposal = compose_call!( api.metadata.clone(), "BridgeEOS", "change_schedule", merkle, signed_blocks_headers, block_ids_list ); let xt: UncheckedExtrinsicV4<_> = compose_extrinsic!( api.clone(), "Sudo", "sudo", proposal ); // Unable to decode Vec on index 2 createType(ExtrinsicV4):: Source is too large println!("[+] Composed extrinsic: {:?}\n", xt); // send and watch extrinsic until finalized let tx_hash = api.send_extrinsic(xt.hex_encode()).unwrap(); println!("[+] Transaction got finalized. Hash: {:?}\n", tx_hash); } fn read_json_from_file(json_name: impl AsRef<str>) -> Result<String, Box<dyn Error>> { let path = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src/test_data/")).join(json_name.as_ref()); dbg!(&path); let mut file = File::open(path)?; let mut json_str = String::new(); file.read_to_string(&mut json_str)?; Ok(json_str) } #[test] fn test_balances_transfer() { env_logger::init(); let url = "127.0.0.1:9944"; let from = AccountKeyring::Alice.pair(); let api = Api::new(format!("ws://{}", url)).set_signer(from.clone()); let to = AccountId::from(AccountKeyring::Bob); let result = api.get_free_balance(&to); info!("[+] Bob's Free Balance is is {}\n", result); let acc_id = GenericAddress::from(to.clone()); // generate extrinsic let xt: UncheckedExtrinsicV4<_> = compose_extrinsic!( api.clone(), "Balances", "transfer", acc_id, Compact(1230u128) ); println!( "Sending an extrinsic from Alice (Key = {:?}),\n\nto Bob (Key = {:?})\n", from.public(), to ); println!("[+] Composed extrinsic: {:?}\n", xt); // send and watch extrinsic until finalized let tx_hash = api.send_extrinsic(xt.hex_encode()).unwrap(); println!("[+] Transaction got finalized. Hash: {:?}\n", tx_hash); // verify that Bob's free Balance increased let result = api.get_free_balance(&to); println!("[+] Bob's Free Balance is now {}\n", result); } }
use gl::types::*; use glfw::{Action, Key}; use sepia::app::*; use sepia::buffer::*; use sepia::framebuffer::*; use sepia::shaderprogram::*; use sepia::texture::*; use sepia::vao::*; use std::ptr; #[rustfmt::skip] const VERTICES: &[GLfloat; 15] = &[ -0.5, -0.5, 0.0, 0.0, 0.0, 0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.5, 1.0 ]; #[rustfmt::skip] const QUAD_VERTICES: &[GLfloat; 20] = &[ -1.0, 1.0, 0.0, 0.0, 1.0, // top left 1.0, 1.0, 0.0, 1.0, 1.0, // top right -1.0, -1.0, 0.0, 0.0, 0.0, // bottom left 1.0, -1.0, 0.0, 1.0, 0.0, // bottom right ]; #[rustfmt::skip] const INDICES: &[GLuint; 6] = &[ 1, 2, 0, // first triangle 2, 1, 3, // second triangle ]; #[derive(Default)] struct MainState { vao: VertexArrayObject, vbo: Buffer, shader_program: ShaderProgram, texture: Texture, screen_vao: VertexArrayObject, screen_vbo: Buffer, screen_ebo: Buffer, screen_program: ShaderProgram, fbo: Framebuffer, } impl MainState { fn load_shaders(&mut self) { self.shader_program = ShaderProgram::new(); self.shader_program .vertex_shader_file("assets/shaders/texture/texture.vs.glsl") .fragment_shader_file("assets/shaders/texture/texture.fs.glsl") .link(); self.screen_program = ShaderProgram::new(); self.screen_program .vertex_shader_file("assets/shaders/texture/screen.vs.glsl") .fragment_shader_file("assets/shaders/texture/screen.fs.glsl") .link(); } } impl State for MainState { fn initialize(&mut self) { self.texture = Texture::from_file("assets/textures/blue.jpg"); self.load_shaders(); self.vao = VertexArrayObject::new(); self.vbo = Buffer::new(BufferKind::Array); self.vbo.add_data(VERTICES); self.vbo.upload(&self.vao, DrawingHint::StaticDraw); self.vao.configure_attribute(0, 3, 5, 0); self.vao.configure_attribute(1, 2, 5, 3); self.screen_vao = VertexArrayObject::new(); self.screen_vbo = Buffer::new(BufferKind::Array); self.screen_ebo = Buffer::new(BufferKind::Element); self.screen_vbo.add_data(QUAD_VERTICES); self.screen_vbo .upload(&self.screen_vao, DrawingHint::StaticDraw); self.screen_ebo.add_data(INDICES); self.screen_ebo .upload(&self.screen_vao, DrawingHint::StaticDraw); self.screen_vao.configure_attribute(0, 3, 5, 0); self.screen_vao.configure_attribute(1, 2, 5, 3); self.fbo = Framebuffer::new(); self.fbo.create_with_texture(200, 200); self.fbo.add_depth_buffer(); } fn handle_events(&mut self, state_data: &mut StateData, event: &glfw::WindowEvent) { match *event { glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => { state_data.window.set_should_close(true); } glfw::WindowEvent::Key(Key::R, _, Action::Press, _) => { self.load_shaders(); } _ => (), } } fn render(&mut self, _: &mut StateData) { // Use the framebuffer self.fbo.bind(); unsafe { gl::Enable(gl::DEPTH_TEST); gl::ClearColor(0.1, 0.1, 0.1, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); } // Render the scene to the framebuffer self.shader_program.activate(); self.texture.bind(0); self.vao.bind(); unsafe { gl::DrawArrays(gl::TRIANGLES, 0, 3); } // Use the default framebuffer (render to the screen) Framebuffer::bind_default_framebuffer(); self.fbo.color_texture().bind(0); self.screen_vao.bind(); self.screen_program.activate(); unsafe { gl::Disable(gl::DEPTH_TEST); gl::ClearColor(1.0, 1.0, 1.0, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT); gl::DrawElements( gl::TRIANGLES, INDICES.len() as i32, self.screen_ebo.type_representation(), ptr::null(), ); } } } fn main() { let mut state = MainState::default(); let mut state_machine: Vec<&mut dyn State> = Vec::new(); state_machine.push(&mut state); App::new(state_machine).run(); }
use rustc_serialize::json; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use curl::http; use dependency_container::base_project_dependency::BaseProjectDependencyContainer; #[derive(RustcDecodable, RustcEncodable, Debug)] pub struct ComposerJson { pub require: HashMap<String, String> } pub fn getBaseProjectDependencyContainer() -> BaseProjectDependencyContainer { let mut f = File::open("/Users/tim/proj_/symfony/symfony/composer.json").unwrap(); let mut file_contents = String::new(); f.read_to_string(&mut file_contents); let mut d = BaseProjectDependencyContainer::new(); // Deserialize using `json::decode` let composer_json: ComposerJson = json::decode(&mut file_contents).unwrap(); for (a, b) in composer_json.require { d.addDependency(a.to_string(), b.to_string()); } d }
/// Implementation of the Snake game for an 8x8 LED Dot Screen. use crate::{Components, Direction}; use crate::peripherals::{Dot, DotScreen, InputSignal, JoyStickSignal}; // Constants for the Snake game. // The x-coordinate of the egg starting location. const EGG_START_X: usize = 1; // The y-coordinate of the egg starting location. const EGG_START_Y: usize = DotScreen::WIDTH - 2; // The y-index (row) along which the snake starts. const SNAKE_START_Y: usize = DotScreen::WIDTH / 2; // The stating length of the snake. const START_LENGTH: usize = (DotScreen::WIDTH / 2) - 1; // The initial polling interval for the SnakeGame. const INITIAL_POLL_INTERVAL: usize = 500; // The number of point when the player has won the game (the screen is full). const VICTORY: usize = DotScreen::TOTAL_DOTS - START_LENGTH; /// The Title Screen for the Snake Game ("S"). pub static TITLE_SCREEN: DotScreen = DotScreen::new( [ 0b00000000, 0b00000000, 0b11011111, 0b10011001, 0b10011001, 0b11111011, 0b00000000, 0b00000000, ] ); /// The game loop which runs the Snake game. /// /// # Arguments /// components - Consumes the Components object. pub fn snake_game_loop(mut components: Components) -> ! { let mut game = SnakeGame::new(); loop { game.play(&mut components); game.game_over(&mut components); game.reset(); } } /// A segment represents a segment of the Snake. /// /// This is fully described by a Dot (the position on the screen) /// and a Direction (indicating where the segment will be next). #[derive(Copy, Clone)] struct Segment { direction: Direction, position: Dot, } impl Segment { /// Create a new Segment object, from an x-coordinate, y-coordinate, and direction. fn new(x: usize, y: usize, direction: Direction) -> Self { let position = Dot { x, y }; Segment { direction, position } } /// Create a new Segment, which represents where the Snake will be /// at the next game tick. /// /// The direction of the segment remains constant. /// Additionally, the output Segment is constrained to be within the Dot grid. fn next(&self) -> Self { let position = match self.direction { Direction::Left=> { self.position.left() }, Direction::Right => { self.position.right() }, Direction::Up => { self.position.up() }, Direction::Down => { self.position.down() }, }; Self { direction: self.direction, position } } } /// An enumeration of the results of the Snake::slither function. enum SlitherResult { // The Snake moved successfully, but no egg was eaten. // The inner Segment is the last part of the Tail that was dropped. Moved(Segment), // The Snake moved successfully and the egg was eaten. EggEaten, // The Snake collided with itself or the wall. Collision, } // The Tail is implemented as an ArrayDeque object from the arraydeque crate. type Tail = arraydeque::ArrayDeque<[Segment; DotScreen::TOTAL_DOTS], arraydeque::Wrapping>; /// The Snake object. This is the character that the player controls. /// /// This object is described by the Head, the part that the player controls, /// and the Tail which follows in the tracks of the Head. struct Snake { head: Segment, tail: Tail, } impl Snake { /// Constructs a new Snake object. /// /// This Snake is always in the same place, middle of the screen with tail extended /// to the left and headed in the rightward direction, and the same length length, /// one less than half of the screen width. fn new() -> Self { // Initialize an empty Snake. let head = Segment::new(0, 0, Direction::Up); let tail: Tail = arraydeque::ArrayDeque::new(); let mut snake = Snake { head, tail }; // Initialize and return. snake.init(); return snake } /// Initializes the Snake object. /// /// This method can be used to "reset" the Snake to the original position. fn init(&mut self) { self.tail.clear(); self.head = Segment::new(START_LENGTH, SNAKE_START_Y, Direction::Right); self.tail.push_back(Segment::new(START_LENGTH - 1, SNAKE_START_Y, Direction::Right)); self.tail.push_back(Segment::new(START_LENGTH - 2, SNAKE_START_Y, Direction::Right)); } /// Checks if the Snake has collided with itself or the wall. /// /// If the Snake has collided with the wall, then its Head would not have moved, /// meaning that the first segment of the snake is the same as the Head. /// /// # Returns /// The determination of if a collision has occurred. fn check_collision(&self) -> bool { for segment in self.tail.iter() { if self.head.position == segment.position { return true } } return false } /// Gets the length of the Snake. fn get_length(&self) -> usize { self.tail.len() + 1 } /// Sets the direction of the Snake /// /// This sets the direction of the Head of the Snake. /// The direction is not allowed to be backwards, since if the Snake turned /// around, there would be a collision. This choice improves game play. fn set_direction(&mut self, dir: Direction) { if dir.opposite() != self.head.direction { self.head.direction = dir; } } /// Moves the snake to the next position. /// /// Returns a SlitherResult indicating one of the following: /// * The Snake ate the egg, /// * The Snake collided with either itself or the wall, /// * The Snake moved to the next space, but did not eat the egg. fn slither(&mut self, egg: &Dot) -> SlitherResult { self.tail.push_front(self.head); self.head = self.head.next(); return if self.head.position == *egg { SlitherResult::EggEaten } else { let dropped_segment = self.tail.pop_back().unwrap(); if self.check_collision() { SlitherResult::Collision } else { SlitherResult::Moved(dropped_segment) } } } } /// The SnakeGame object. struct SnakeGame { /// The Egg that the Snake is trying to eat. egg: Dot, /// The character that the player controls. snake: Snake, /// The screen depicting the current state of the game. screen: DotScreen, /// The interval to poll for user input. /// This can be interpreted as the time between game ticks. polling_interval_ms: usize, } impl SnakeGame { /// Construct a new SnakeGame object. fn new() -> Self { let egg = Dot { x: EGG_START_X, y: EGG_START_Y}; let snake = Snake::new(); let screen = DotScreen::new_empty(); let mut game = Self { egg, snake, screen, polling_interval_ms: INITIAL_POLL_INTERVAL }; game.reset(); return game } /// This method is called to begin the game-play. /// /// This constructs its own game loop. Once the game-play ends, this returns. /// /// # Args /// * components - The peripheral components for the game display. fn play(&mut self, components: &mut Components) { loop { // Improves the players comprehension of the game. self.twinkle_egg(&mut components.display); // Gather user input, for the amount of milliseconds stored in the // `self.polling_interval_ms` attribute. // This interval gets shorter and shorter as more eggs are eaten, // increasing the difficulty of the game. let signal = components.analog.poll_joystick(self.polling_interval_ms).back(); if let Some(InputSignal::JoyStick(signal)) = signal { if let Some(direction) = signal.to_single_direction() { self.snake.set_direction(direction); }; }; // Update the game state. If unsuccessful, break out the game loop. let update_successful = self.update(&mut components.analog); if !update_successful { break } // Display the game state to the LED Dot Display. components.display.show(&self.screen); } } /// Update the game state. /// /// This is called for every game tick. This function will move the Snake /// in the direction its Head is pointing, and then resolves the games state. /// /// # Arguments /// * rng - The Random Number Generator. /// /// # Returns /// Whether the game state was successfully updated. fn update(&mut self, rng: &mut dyn rand_core::RngCore) -> bool { match self.snake.slither(&self.egg) { SlitherResult::Moved(dropped_segment) => { self.screen.remove(&dropped_segment.position); self.screen.add(&self.snake.head.position); }, SlitherResult::EggEaten => { if self.get_score() == VICTORY { return false } // Place a new egg in an open dot. let index = { let modulus = DotScreen::TOTAL_DOTS - self.snake.get_length(); (rng.next_u32() as usize) % modulus }; self.egg = self.screen.iter_off().nth(index).unwrap(); self.screen.add(&self.egg); // Decrease the time between game ticks. self.increase_speed(); }, SlitherResult::Collision => { // If a collision occurred, then the game did not successfully update. return false } } return true } /// This method is called when the game is over. /// /// When the game over state is complete, this method returns. /// /// # Args /// * components - The peripheral components for the game display. fn game_over(&self, components: &mut Components) { // Flash between the last game state screen and an empty screen, // to indicate that the player has lost the game. let mut game_over_screen = DotScreen::new_empty(); components.display.show(&game_over_screen); for _ in 0..2 { arduino_uno::delay_ms(400); components.display.show(&self.screen); arduino_uno::delay_ms(400); components.display.show(&game_over_screen); } let score = self.get_score(); if score == 0 { components.display.show(&self.screen); } else { // Display the game score to the user by displaying a dot for each egg eaten, // one at a time, from left to right, top to bottom of the screen. let tally = if score == VICTORY { DotScreen::TOTAL_DOTS } else { score }; let delay = 3000 / (tally as u16); DotScreen::new_empty() .iter() .take(tally) .for_each(|dot| { game_over_screen.add(&dot); components.display.show(&game_over_screen); arduino_uno::delay_ms(delay); } ); } // Loop waiting for a JoyStick button press to end the game over screen. loop { match components.analog.poll_joystick_until_any() { InputSignal::JoyStick(signal) => { if let JoyStickSignal { button: true, .. } = signal { break } } } } } /// This method is called to reset the game to its initial state. /// /// After this method is called, the game should be ready to be played again. fn reset(&mut self) { // Reset the Egg. self.egg = Dot { x: EGG_START_X, y: EGG_START_Y}; // Reset the Snake. self.snake.init(); // Clear and reset the Screen. self.screen.clear(); self.screen.add(&self.egg); self.screen.add(&self.snake.head.position); for segment in self.snake.tail.iter() { self.screen.add(&segment.position) } // Reset the polling interval. self.polling_interval_ms = INITIAL_POLL_INTERVAL; } /// Returns the current score for the game. fn get_score(&self) -> usize { self.snake.get_length() - START_LENGTH } /// Decrease the time between game ticks. fn increase_speed(&mut self) { self.polling_interval_ms -= self.polling_interval_ms / 50; } /// Briefly toggle the Dot representing the egg off and on. /// /// This should help the player understand which Dot is the egg. fn twinkle_egg(&mut self, display: &mut crate::peripherals::DotDisplay) { const INTERVAL_MS: u16 = 24; self.screen.remove(&self.egg); display.show(&self.screen); arduino_uno::delay_ms(INTERVAL_MS); self.screen.add(&self.egg); display.show(&self.screen); } }
// Copyright 2019, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use super::StoreAndForwardRequester; use crate::{ envelope::NodeDestination, inbound::DecryptedDhtMessage, store_forward::{ database::NewStoredMessage, error::StoreAndForwardError, message::StoredMessagePriority, SafResult, }, DhtConfig, }; use futures::{task::Context, Future}; use log::*; use std::{sync::Arc, task::Poll}; use tari_comms::{ peer_manager::{NodeIdentity, PeerFeatures, PeerManager}, pipeline::PipelineError, }; use tower::{layer::Layer, Service, ServiceExt}; const LOG_TARGET: &str = "comms::dht::storeforward::store"; /// This layer is responsible for storing messages which have failed to decrypt pub struct StoreLayer { peer_manager: Arc<PeerManager>, config: DhtConfig, node_identity: Arc<NodeIdentity>, saf_requester: StoreAndForwardRequester, } impl StoreLayer { pub fn new( config: DhtConfig, peer_manager: Arc<PeerManager>, node_identity: Arc<NodeIdentity>, saf_requester: StoreAndForwardRequester, ) -> Self { Self { peer_manager, config, node_identity, saf_requester, } } } impl<S> Layer<S> for StoreLayer { type Service = StoreMiddleware<S>; fn layer(&self, service: S) -> Self::Service { StoreMiddleware::new( service, self.config.clone(), Arc::clone(&self.peer_manager), Arc::clone(&self.node_identity), self.saf_requester.clone(), ) } } #[derive(Clone)] pub struct StoreMiddleware<S> { next_service: S, config: DhtConfig, peer_manager: Arc<PeerManager>, node_identity: Arc<NodeIdentity>, saf_requester: StoreAndForwardRequester, } impl<S> StoreMiddleware<S> { pub fn new( next_service: S, config: DhtConfig, peer_manager: Arc<PeerManager>, node_identity: Arc<NodeIdentity>, saf_requester: StoreAndForwardRequester, ) -> Self { Self { next_service, config, peer_manager, node_identity, saf_requester, } } } impl<S> Service<DecryptedDhtMessage> for StoreMiddleware<S> where S: Service<DecryptedDhtMessage, Response = (), Error = PipelineError> + Clone + 'static { type Error = PipelineError; type Response = (); type Future = impl Future<Output = Result<Self::Response, Self::Error>>; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn call(&mut self, msg: DecryptedDhtMessage) -> Self::Future { StoreTask::new( self.next_service.clone(), self.config.clone(), Arc::clone(&self.peer_manager), Arc::clone(&self.node_identity), self.saf_requester.clone(), ) .handle(msg) } } /// Responsible for processing a single DecryptedDhtMessage, storing if necessary or passing the message /// to the next service. struct StoreTask<S> { next_service: S, peer_manager: Arc<PeerManager>, config: DhtConfig, node_identity: Arc<NodeIdentity>, saf_requester: StoreAndForwardRequester, } impl<S> StoreTask<S> { pub fn new( next_service: S, config: DhtConfig, peer_manager: Arc<PeerManager>, node_identity: Arc<NodeIdentity>, saf_requester: StoreAndForwardRequester, ) -> Self { Self { config, peer_manager, node_identity, saf_requester, next_service, } } } impl<S> StoreTask<S> where S: Service<DecryptedDhtMessage, Response = (), Error = PipelineError> { /// Determine if this is a message we should store for our peers and, if so, store it. /// /// The criteria for storing a message is: /// 1. Messages MUST have a message origin set and be encrypted (Join messages are the exception) /// 1. Unencrypted Join messages - this increases the knowledge the network has of peers (Low priority) /// 1. Encrypted Discovery messages - so that nodes are aware of other nodes that are looking for them (High /// priority) 1. Encrypted messages addressed to the neighbourhood - some node in the neighbourhood may be /// interested in this message (High priority) 1. Encrypted messages addressed to a particular public key or /// node id that this node knows about async fn handle(mut self, message: DecryptedDhtMessage) -> Result<(), PipelineError> { if !self.node_identity.features().contains(PeerFeatures::DHT_STORE_FORWARD) { trace!(target: LOG_TARGET, "Passing message to next service (Not a SAF node)"); self.next_service.oneshot(message).await?; return Ok(()); } if let Some(priority) = self .get_storage_priority(&message) .await .map_err(PipelineError::from_debug)? { self.store(priority, message.clone()) .await .map_err(PipelineError::from_debug)?; } debug!(target: LOG_TARGET, "Passing message {} to next service", message.tag); self.next_service.oneshot(message).await?; Ok(()) } async fn get_storage_priority(&self, message: &DecryptedDhtMessage) -> SafResult<Option<StoredMessagePriority>> { let log_not_eligible = |reason: &str| { debug!( target: LOG_TARGET, "Message from peer '{}' not eligible for SAF storage because {}", message.source_peer.node_id.short_str(), reason ); }; if message.body_len() > self.config.saf_max_message_size { log_not_eligible(&format!( "the message body exceeded the maximum storage size (body size={}, max={})", message.body_len(), self.config.saf_max_message_size )); return Ok(None); } if message.dht_header.message_type.is_saf_message() { log_not_eligible("it is a SAF message"); return Ok(None); } if message.dht_header.message_type.is_dht_join() { log_not_eligible("it is a join message"); return Ok(None); } if message .authenticated_origin() .map(|pk| pk == self.node_identity.public_key()) .unwrap_or(false) { log_not_eligible("this message originates from this node"); return Ok(None); } match message.success() { // The message decryption was successful, or the message was not encrypted Some(_) => { // If the message doesnt have an origin we wont store it if !message.has_origin_mac() { log_not_eligible("it is a cleartext message and does not have an origin MAC"); return Ok(None); } // If this node decrypted the message (message.success() above), no need to store it if message.is_encrypted() { log_not_eligible("the message was encrypted for this node"); return Ok(None); } // If this is a join message, we may want to store it if it's for our neighbourhood // if message.dht_header.message_type.is_dht_join() { // return match self.get_priority_for_dht_join(message).await? { // Some(priority) => Ok(Some(priority)), // None => { // log_not_eligible("the join message was not considered in this node's neighbourhood"); // Ok(None) // }, // }; // } log_not_eligible("it is not an eligible DhtMessageType"); // Otherwise, don't store Ok(None) }, // This node could not decrypt the message None => { if !message.has_origin_mac() { // TODO: #banheuristic - the source peer should not have propagated this message warn!( target: LOG_TARGET, "Store task received an encrypted message with no origin MAC. This message is invalid and \ should not be stored or propagated. Dropping message. Sent by node '{}'", message.source_peer.node_id.short_str() ); return Ok(None); } // The destination of the message will determine if we store it self.get_priority_by_destination(message).await }, } } // async fn get_priority_for_dht_join( // &self, // message: &DecryptedDhtMessage, // ) -> SafResult<Option<StoredMessagePriority>> // { // debug_assert!(message.dht_header.message_type.is_dht_join() && !message.is_encrypted()); // // let body = message // .decryption_result // .as_ref() // .expect("already checked that this message is not encrypted"); // let join_msg = body // .decode_part::<JoinMessage>(0)? // .ok_or_else(|| StoreAndForwardError::InvalidEnvelopeBody)?; // let node_id = NodeId::from_bytes(&join_msg.node_id).map_err(StoreAndForwardError::MalformedNodeId)?; // // // If this join request is for a peer that we'd consider to be a neighbour, store it for other neighbours // if self // .peer_manager // .in_network_region( // &node_id, // self.node_identity.node_id(), // self.config.num_neighbouring_nodes, // ) // .await? // { // if self.saf_requester.query_messages( // DhtMessageType::Join, // ) // return Ok(Some(StoredMessagePriority::Low)); // } // // Ok(None) // } async fn get_priority_by_destination( &self, message: &DecryptedDhtMessage, ) -> SafResult<Option<StoredMessagePriority>> { let log_not_eligible = |reason: &str| { debug!( target: LOG_TARGET, "Message from peer '{}' not eligible for SAF storage because {}", message.source_peer.node_id.short_str(), reason ); }; let peer_manager = &self.peer_manager; let node_identity = &self.node_identity; if message.dht_header.destination == node_identity.public_key() || message.dht_header.destination == node_identity.node_id() { log_not_eligible("the message is destined for this node"); return Ok(None); } use NodeDestination::*; match &message.dht_header.destination { Unknown => { // No destination provided, if message.dht_header.message_type.is_dht_discovery() { log_not_eligible("it is an anonymous discovery message"); Ok(None) } else { Ok(Some(StoredMessagePriority::Low)) } }, PublicKey(dest_public_key) => { // If we know the destination peer, keep the message for them match peer_manager.find_by_public_key(&dest_public_key).await { Ok(peer) => { if peer.is_banned() { log_not_eligible( "origin peer is banned. ** This should not happen because it should have been checked \ earlier in the pipeline **", ); Ok(None) } else { Ok(Some(StoredMessagePriority::High)) } }, Err(err) if err.is_peer_not_found() => Ok(Some(StoredMessagePriority::Low)), Err(err) => Err(err.into()), } }, NodeId(dest_node_id) => { if peer_manager.exists_node_id(&dest_node_id).await || peer_manager .in_network_region( &dest_node_id, node_identity.node_id(), self.config.num_neighbouring_nodes, ) .await? { Ok(Some(StoredMessagePriority::High)) } else { log_not_eligible(&format!( "this node does not know the destination node id '{}' or does not consider it a neighbouring \ node id", dest_node_id )); Ok(None) } }, } } async fn store(&mut self, priority: StoredMessagePriority, message: DecryptedDhtMessage) -> SafResult<()> { debug!( target: LOG_TARGET, "Storing message from peer '{}' ({} bytes)", message.source_peer.node_id.short_str(), message.body_len(), ); let stored_message = NewStoredMessage::try_construct(message, priority) .ok_or_else(|| StoreAndForwardError::InvalidStoreMessage)?; self.saf_requester.insert_message(stored_message).await?; Ok(()) } } #[cfg(test)] mod test { use super::*; use crate::{ envelope::DhtMessageFlags, proto::{dht::JoinMessage, envelope::DhtMessageType}, test_utils::{ create_store_and_forward_mock, make_dht_inbound_message, make_node_identity, make_peer_manager, service_spy, }, }; use chrono::Utc; use std::time::Duration; use tari_comms::{message::MessageExt, wrap_in_envelope_body}; use tari_test_utils::async_assert_eventually; use tari_utilities::{hex::Hex, ByteArray}; #[tokio_macros::test_basic] async fn cleartext_message_no_origin() { let (requester, mock_state) = create_store_and_forward_mock(); let spy = service_spy(); let peer_manager = make_peer_manager(); let node_identity = make_node_identity(); let mut service = StoreLayer::new(Default::default(), peer_manager, node_identity, requester) .layer(spy.to_service::<PipelineError>()); let inbound_msg = make_dht_inbound_message(&make_node_identity(), b"".to_vec(), DhtMessageFlags::empty(), false); let msg = DecryptedDhtMessage::succeeded(wrap_in_envelope_body!(Vec::new()), None, inbound_msg); service.call(msg).await.unwrap(); assert!(spy.is_called()); let messages = mock_state.get_messages().await; assert_eq!(messages.len(), 0); } #[ignore] #[tokio_macros::test_basic] async fn cleartext_join_message() { let (requester, mock_state) = create_store_and_forward_mock(); let spy = service_spy(); let peer_manager = make_peer_manager(); let node_identity = make_node_identity(); let join_msg_bytes = JoinMessage { node_id: node_identity.node_id().to_vec(), addresses: vec![], peer_features: 0, } .to_encoded_bytes(); let mut service = StoreLayer::new(Default::default(), peer_manager, node_identity, requester) .layer(spy.to_service::<PipelineError>()); let sender_identity = make_node_identity(); let inbound_msg = make_dht_inbound_message(&sender_identity, b"".to_vec(), DhtMessageFlags::empty(), true); let mut msg = DecryptedDhtMessage::succeeded( wrap_in_envelope_body!(join_msg_bytes), Some(sender_identity.public_key().clone()), inbound_msg, ); msg.dht_header.message_type = DhtMessageType::Join; service.call(msg).await.unwrap(); assert!(spy.is_called()); // Because we dont wait for the message to reach the mock/service before continuing (for efficiency and it's not // necessary) we need to wait for the call to happen eventually - it should be almost instant async_assert_eventually!( mock_state.call_count(), expect = 1, max_attempts = 10, interval = Duration::from_millis(10), ); let messages = mock_state.get_messages().await; assert_eq!(messages[0].message_type, DhtMessageType::Join as i32); } #[tokio_macros::test_basic] async fn decryption_succeeded_no_store() { let (requester, mock_state) = create_store_and_forward_mock(); let spy = service_spy(); let peer_manager = make_peer_manager(); let node_identity = make_node_identity(); let mut service = StoreLayer::new(Default::default(), peer_manager, node_identity, requester) .layer(spy.to_service::<PipelineError>()); let msg_node_identity = make_node_identity(); let inbound_msg = make_dht_inbound_message( &msg_node_identity, b"This shouldnt be stored".to_vec(), DhtMessageFlags::ENCRYPTED, true, ); let msg = DecryptedDhtMessage::succeeded( wrap_in_envelope_body!(b"secret".to_vec()), Some(msg_node_identity.public_key().clone()), inbound_msg, ); service.call(msg).await.unwrap(); assert!(spy.is_called()); assert_eq!(mock_state.call_count(), 0); } #[tokio_macros::test_basic] async fn decryption_failed_should_store() { let (requester, mock_state) = create_store_and_forward_mock(); let spy = service_spy(); let peer_manager = make_peer_manager(); let origin_node_identity = make_node_identity(); peer_manager.add_peer(origin_node_identity.to_peer()).await.unwrap(); let node_identity = make_node_identity(); let mut service = StoreLayer::new(Default::default(), peer_manager, node_identity, requester) .layer(spy.to_service::<PipelineError>()); let mut inbound_msg = make_dht_inbound_message( &origin_node_identity, b"Will you keep this for me?".to_vec(), DhtMessageFlags::ENCRYPTED, true, ); inbound_msg.dht_header.destination = NodeDestination::PublicKey(Box::new(origin_node_identity.public_key().clone())); let msg = DecryptedDhtMessage::failed(inbound_msg.clone()); service.call(msg).await.unwrap(); assert_eq!(spy.is_called(), true); async_assert_eventually!( mock_state.call_count(), expect = 1, max_attempts = 10, interval = Duration::from_millis(10), ); let message = mock_state.get_messages().await.remove(0); assert_eq!( message.destination_pubkey.unwrap(), origin_node_identity.public_key().to_hex() ); let duration = Utc::now().naive_utc().signed_duration_since(message.stored_at); assert!(duration.num_seconds() <= 5); } }
pub fn my_sqrt(x: i32) -> i32 { let result = x >> 1; println!("{}", result); result } #[cfg(test)] mod my_sqrt_tests { use super::*; #[test] fn my_sqrt_test_one() { assert_eq!(my_sqrt(8), 2); assert_eq!(my_sqrt(36), 6); } }
pub mod directory_entry; pub mod fat32_device_driver; pub mod get_bytes; pub mod mbr_device_driver; pub mod partition;
// revisions: base nll // ignore-compare-mode-nll //[nll] compile-flags: -Z borrowck=mir fn thing(x: impl FnOnce(&u32)) {} fn main() { let f = |_| (); thing(f); //[nll]~^ ERROR mismatched types //~^^ ERROR implementation of `FnOnce` is not general enough }
// Copyright 2018 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 crate::wlan::types::{ ClientStateSummary, ConnectionState, DisconnectStatus, NetworkIdentifier, NetworkState, SecurityType, WlanClientState, }; use connectivity_testing::wlan_service_util; use failure::{Error, ResultExt}; use fidl_fuchsia_wlan_device_service::{DeviceServiceMarker, DeviceServiceProxy}; use fuchsia_component::client::connect_to_service; use fuchsia_syslog::fx_log_err; use parking_lot::RwLock; // WlanFacade: proxies commands from sl4f test to proper fidl APIs // // This object is shared among all threads created by server. The inner object is the facade // itself. Callers interact with a wrapped version of the facade that enforces read/write // protection. // // Use: Create once per server instantiation. #[derive(Debug)] struct InnerWlanFacade { scan_results: bool, } #[derive(Debug)] pub struct WlanFacade { wlan_svc: DeviceServiceProxy, inner: RwLock<InnerWlanFacade>, } impl WlanFacade { pub fn new() -> Result<WlanFacade, Error> { let wlan_svc = connect_to_service::<DeviceServiceMarker>()?; Ok(WlanFacade { wlan_svc, inner: RwLock::new(InnerWlanFacade { scan_results: false }) }) } pub async fn scan(&self) -> Result<Vec<String>, Error> { // get iface info let wlan_iface_ids = wlan_service_util::get_iface_list(&self.wlan_svc) .await .context("Scan: failed to get wlan iface list")?; if wlan_iface_ids.len() == 0 { bail!("no wlan interfaces found"); } // pick the first one let sme_proxy = wlan_service_util::get_iface_sme_proxy(&self.wlan_svc, wlan_iface_ids[0]) .await .context("Scan: failed to get iface sme proxy")?; // start the scan let results = wlan_service_util::perform_scan(&sme_proxy).await.context("Scan failed")?; // send the ssids back to the test let mut ssids = Vec::new(); for entry in &results { let ssid = String::from_utf8_lossy(&entry.ssid).into_owned(); ssids.push(ssid); } Ok(ssids) } pub async fn connect(&self, target_ssid: Vec<u8>, target_pwd: Vec<u8>) -> Result<bool, Error> { // get iface info let wlan_iface_ids = wlan_service_util::get_iface_list(&self.wlan_svc) .await .context("Connect: failed to get wlan iface list")?; if wlan_iface_ids.len() == 0 { bail!("no wlan interfaces found"); } // pick the first one let sme_proxy = wlan_service_util::get_iface_sme_proxy(&self.wlan_svc, wlan_iface_ids[0]) .await .context("Connect: failed to get iface sme proxy")?; wlan_service_util::connect_to_network(&sme_proxy, target_ssid, target_pwd).await } pub async fn disconnect(&self) -> Result<(), Error> { // get iface info let wlan_iface_ids = wlan_service_util::get_iface_list(&self.wlan_svc) .await .context("Disconnect: failed to get wlan iface list")?; if wlan_iface_ids.len() == 0 { bail!("no wlan interfaces found"); } let mut disconnect_error = false; // disconnect all networks for iface_id in wlan_iface_ids { let sme_proxy = wlan_service_util::get_iface_sme_proxy(&self.wlan_svc, iface_id) .await .context("Disconnect: failed to get iface sme proxy")?; match wlan_service_util::disconnect_from_network(&sme_proxy).await { Err(e) => { fx_log_err!("Disconnect call failed on iface {}: {:?}", iface_id, e); disconnect_error = true; } _ => {} } } if disconnect_error { bail!("saw a failure with at least one disconnect call"); } Ok(()) } pub async fn status(&self) -> Result<ClientStateSummary, Error> { // get iface info let wlan_iface_ids = wlan_service_util::get_iface_list(&self.wlan_svc) .await .context("Status: failed to get wlan iface list")?; if wlan_iface_ids.len() == 0 { bail!("no wlan interfaces found"); } // pick the first one let sme_proxy = wlan_service_util::get_iface_sme_proxy(&self.wlan_svc, wlan_iface_ids[0]) .await .context("Status: failed to get iface sme proxy")?; let rsp = sme_proxy.status().await.context("failed to get status from sme_proxy")?; // Create dummy ClientStateSummary let mut connection_state = ConnectionState::Disconnected; let mut network_id = NetworkIdentifier { ssid: vec![], type_: SecurityType::None }; match rsp.connected_to { Some(ref bss) => { network_id.ssid = bss.ssid.as_slice().to_vec(); connection_state = ConnectionState::Connected; } _ => {} } let network_state = NetworkState { id: Some(network_id), state: Some(connection_state), status: Some(DisconnectStatus::ConnectionFailed), }; let mut networks = Vec::new(); networks.push(network_state); let client_state_summary = ClientStateSummary { state: Some(WlanClientState::ConnectionsEnabled), networks: Some(networks), }; Ok(client_state_summary) } }
fn main() { let input = include_str!("day1.txt"); let mut v: Vec<i32> = Vec::new(); let split = input.split("\n"); let mut counter_upper = 0; for s in split { v.push(s.parse().unwrap()); } for mut module in v { while module > 0 { counter_upper += fuel_required(module); module = fuel_required(module); } } println!("{}", counter_upper); } fn fuel_required(x: i32) -> i32 { x/3-2 }
use crate::{ channel::{Channel, ChannelId, Completer, Packet, Performer}, execution_controller::{ExecutionController, RunLimitedNumberOfInstructions}, fiber::{self, EndedReason, Fiber, FiberId, Panic, VmEnded}, heap::{Data, Function, Heap, HirId, InlineObject, SendPort, Struct, SymbolId, Tag}, lir::Lir, tracer::{FiberTracer, TracedFiberEnded, TracedFiberEndedReason, Tracer}, }; use candy_frontend::{ hir::Id, id::{CountableId, IdGenerator}, impl_countable_id, }; use extension_trait::extension_trait; use itertools::Itertools; use rand::{seq::SliceRandom, thread_rng}; use std::{ borrow::Borrow, collections::{HashMap, HashSet}, fmt::{self, Debug, Formatter}, hash::Hash, }; use strum::EnumIs; #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct OperationId(usize); impl_countable_id!(OperationId); impl fmt::Debug for OperationId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "operation_{:x}", self.0) } } /// A VM represents a Candy program that thinks it's currently running. Because /// VMs are first-class Rust structs, they enable other code to store "freezed" /// programs and to remain in control about when and for how long code runs. pub struct Vm<L: Borrow<Lir>, T: Tracer> { lir: L, fibers: HashMap<FiberId, FiberTree<T::ForFiber>>, channels: HashMap<ChannelId, ChannelLike>, pub completed_operations: HashMap<OperationId, CompletedOperation>, pub unreferenced_channels: HashSet<ChannelId>, operation_id_generator: IdGenerator<OperationId>, fiber_id_generator: IdGenerator<FiberId>, channel_id_generator: IdGenerator<ChannelId>, } pub enum FiberTree<T: FiberTracer> { /// This tree is currently focused on running a single fiber. Single(Single<T>), /// The fiber of this tree entered a `core.parallel` scope so that it's now /// paused and waits for the parallel scope to end. Instead of the main /// former single fiber, the tree now runs the function passed to /// `core.parallel` as well as any other spawned children. Parallel(Parallel<T>), Try(Try<T>), } /// Single fibers are the leaves of the fiber tree. pub struct Single<T: FiberTracer> { pub fiber: Fiber<T>, parent: Option<FiberId>, } /// When a parallel section is entered, the fiber that started the section is /// paused. Instead, the children of the parallel section are run. Initially, /// there's only one child – the function given to the parallel builtin /// function. Using the nursery parameter (a nursery can be thought of as a /// pointer to a parallel section), you can also spawn other fibers. In contrast /// to the first child, those children also have an explicit send port where the /// function's result is sent to. pub struct Parallel<T: FiberTracer> { pub paused_fiber: Single<T>, children: HashMap<FiberId, ChildKind>, return_value: Option<InlineObject>, // will later contain the body's return value nursery: ChannelId, } #[derive(Clone)] enum ChildKind { InitialChild, SpawnedChild(ChannelId), } pub struct Try<T: FiberTracer> { pub paused_fiber: Single<T>, child: FiberId, } #[derive(EnumIs)] enum ChannelLike { Channel(Channel), Nursery(FiberId), } pub enum CompletedOperation { Sent, Received { packet: Packet }, } #[derive(Clone, Debug, EnumIs)] pub enum Status { CanRun, WaitingForOperations, Done, Panicked(Panic), } impl FiberId { pub fn root() -> Self { FiberId::from_usize(0) } } impl<L: Borrow<Lir>, T: Tracer> Vm<L, T> { pub fn uninitialized(lir: L) -> Self { Self { lir, fibers: HashMap::new(), channels: HashMap::new(), completed_operations: Default::default(), unreferenced_channels: Default::default(), operation_id_generator: Default::default(), channel_id_generator: Default::default(), fiber_id_generator: IdGenerator::start_at(FiberId::root().to_usize()), } } pub fn initialize_for_function( &mut self, heap: Heap, function: Function, arguments: &[InlineObject], responsible: HirId, tracer: &mut T, ) { assert!(self.fibers.is_empty()); let fiber = Fiber::for_function( heap, function, arguments, responsible, tracer.root_fiber_created(), ); self.fibers.insert( self.fiber_id_generator.generate(), FiberTree::Single(Single { fiber, parent: None, }), ); } pub fn for_function( lir: L, heap: Heap, function: Function, arguments: &[InlineObject], responsible: HirId, tracer: &mut T, ) -> Self { let mut this = Self::uninitialized(lir); this.initialize_for_function(heap, function, arguments, responsible, tracer); this } pub fn for_module(lir: L, tracer: &mut T) -> Self { let actual_lir = lir.borrow(); let function = actual_lir.module_function; let responsible = actual_lir.responsible_module; Self::for_function(lir, Heap::default(), function, &[], responsible, tracer) } pub fn tear_down(mut self, tracer: &mut T) -> VmEnded { let tree = self.fibers.remove(&FiberId::root()).unwrap(); let single = tree.into_single().unwrap(); let mut ended = single.fiber.tear_down(); tracer.root_fiber_ended(TracedFiberEnded { id: FiberId::root(), heap: &mut ended.heap, tracer: ended.tracer, reason: match &ended.reason { EndedReason::Finished(object) => TracedFiberEndedReason::Finished(*object), EndedReason::Panicked(reason) => TracedFiberEndedReason::Panicked(reason.clone()), }, }); VmEnded { heap: ended.heap, reason: ended.reason, } } pub fn lir(&self) -> &L { &self.lir } pub fn status(&self) -> Status { self.status_of(FiberId::root()) } fn status_of(&self, fiber: FiberId) -> Status { match &self.fibers[&fiber] { FiberTree::Single(Single { fiber, .. }) => match &fiber.status { fiber::Status::Running => Status::CanRun, fiber::Status::Sending { .. } | fiber::Status::Receiving { .. } => { Status::WaitingForOperations } fiber::Status::CreatingChannel { .. } | fiber::Status::InParallelScope { .. } | fiber::Status::InTry { .. } => unreachable!(), fiber::Status::Done => Status::Done, fiber::Status::Panicked(panic) => Status::Panicked(panic.clone()), }, FiberTree::Parallel(Parallel { children, .. }) => { for child_fiber in children.keys() { match self.status_of(*child_fiber) { Status::CanRun => return Status::CanRun, Status::WaitingForOperations => {} Status::Done | Status::Panicked { .. } => unreachable!(), }; } // The section is still running, otherwise it would have been // removed. Thus, there was at least one child and all children // were waiting for operations. Status::WaitingForOperations } FiberTree::Try(Try { child, .. }) => self.status_of(*child), } } fn can_run(&self) -> bool { self.status().is_can_run() } pub fn fibers(&self) -> &HashMap<FiberId, FiberTree<T::ForFiber>> { &self.fibers } pub fn fiber(&self, id: FiberId) -> Option<&FiberTree<T::ForFiber>> { self.fibers.get(&id) } /// Can be called at any time from outside the VM to create a channel that /// can be used to communicate with the outside world. pub fn create_channel(&mut self, capacity: usize) -> ChannelId { let id = self.channel_id_generator.generate(); self.channels .insert(id, ChannelLike::Channel(Channel::new(capacity))); id } // This will be used as soon as the outside world tries to send something // into the VM. #[allow(dead_code)] pub fn send(&mut self, channel: ChannelId, packet: Packet) -> OperationId { let operation_id = self.operation_id_generator.generate(); self.send_to_channel(Performer::External(operation_id), channel, packet); operation_id } pub fn receive(&mut self, channel: ChannelId) -> OperationId { let operation_id = self.operation_id_generator.generate(); self.receive_from_channel(Performer::External(operation_id), channel); operation_id } pub fn free_unreferenced_channels(&mut self) { for channel in self.unreferenced_channels.iter().copied().collect_vec() { self.free_channel(channel); } } /// May only be called if the channel is in the `unreferenced_channels`. pub fn free_channel(&mut self, channel: ChannelId) { assert!(self.unreferenced_channels.contains(&channel)); self.channels.remove(&channel); self.unreferenced_channels.remove(&channel); } pub fn run( &mut self, execution_controller: &mut impl ExecutionController<T::ForFiber>, tracer: &mut T, ) { while self.can_run() && execution_controller.should_continue_running() { // Choose a random fiber to run. let mut fiber_id = FiberId::root(); let fiber = loop { match self.fibers.get(&fiber_id).unwrap() { FiberTree::Single(Single { fiber, .. }) => break fiber, FiberTree::Parallel(Parallel { children, .. }) => { let children_as_vec = children.iter().collect_vec(); let random_child = children_as_vec.choose(&mut thread_rng()).unwrap(); fiber_id = *random_child.0 } FiberTree::Try(Try { child, .. }) => fiber_id = *child, } }; if !fiber.status().is_running() { continue; } self.run_fiber( fiber_id, &mut ( &mut *execution_controller, &mut RunLimitedNumberOfInstructions::new(100), ), tracer, ); } } pub fn run_fiber( &mut self, fiber_id: FiberId, execution_controller: &mut impl ExecutionController<T::ForFiber>, tracer: &mut T, ) { assert!( self.can_run(), "Called `Vm::run_fiber(…)` on a VM that is not ready to run.", ); let fiber = self.fibers.get_mut(&fiber_id).unwrap().fiber_mut(); assert!( fiber.status().is_running(), "Called `Vm::run_fiber(…)` with a fiber that is not ready to run.", ); tracer.fiber_execution_started(fiber_id); fiber.run(self.lir.borrow(), execution_controller, fiber_id); let is_finished = match fiber.status() { fiber::Status::Running => false, fiber::Status::CreatingChannel { capacity } => { let channel_id = self.channel_id_generator.generate(); self.channels .insert(channel_id, ChannelLike::Channel(Channel::new(capacity))); fiber.complete_channel_create(channel_id); tracer.channel_created(channel_id); false } fiber::Status::Sending { channel, packet } => { self.send_to_channel(Performer::Fiber(fiber_id), channel, packet); false } fiber::Status::Receiving { channel } => { self.receive_from_channel(Performer::Fiber(fiber_id), channel); false } fiber::Status::InParallelScope { body } => { let nursery_id = self.channel_id_generator.generate(); self.channels .insert(nursery_id, ChannelLike::Nursery(fiber_id)); let first_child_id = { let id = self.fiber_id_generator.generate(); let mut heap = Heap::default(); let body = Data::from(body.clone_to_heap(&mut heap)) .try_into() .unwrap(); let responsible = HirId::create(&mut fiber.heap, true, Id::complicated_responsibility()); let nursery_send_port = SendPort::create(&mut heap, nursery_id); let child_tracer = fiber.tracer.child_fiber_created(id); self.fibers.insert( id, FiberTree::Single(Single { fiber: Fiber::for_function( heap, body, &[nursery_send_port], responsible, child_tracer, ), parent: Some(fiber_id), }), ); id }; self.fibers.replace(fiber_id, |tree| { let single = tree.into_single().unwrap(); FiberTree::Parallel(Parallel { paused_fiber: single, children: HashMap::from([(first_child_id, ChildKind::InitialChild)]), return_value: None, nursery: nursery_id, }) }); false } fiber::Status::InTry { body } => { let child_id = { let id = self.fiber_id_generator.generate(); let mut heap = Heap::default(); let body = Data::from(body.clone_to_heap(&mut heap)) .try_into() .unwrap(); let responsible = HirId::create(&mut fiber.heap, true, Id::complicated_responsibility()); let child_tracer = fiber.tracer.child_fiber_created(id); self.fibers.insert( id, FiberTree::Single(Single { fiber: Fiber::for_function(heap, body, &[], responsible, child_tracer), parent: Some(fiber_id), }), ); id }; self.fibers.replace(fiber_id, |tree| { let single = tree.into_single().unwrap(); FiberTree::Try(Try { paused_fiber: single, child: child_id, }) }); false } fiber::Status::Done | fiber::Status::Panicked { .. } => true, }; if is_finished && fiber_id != FiberId::root() { let single = self .fibers .remove(&fiber_id) .unwrap() .into_single() .unwrap(); let mut ended = single.fiber.tear_down(); let parent = single .parent .expect("We already checked we're not the root fiber."); match self.fibers.get_mut(&parent).unwrap() { FiberTree::Single(_) => unreachable!("Single fibers can't have children."), FiberTree::Parallel(parallel) => { let child = parallel.children.remove(&fiber_id).unwrap(); let parallel_result = match &ended.reason { EndedReason::Finished(return_value) => { let is_finished = parallel.children.is_empty(); match child { ChildKind::InitialChild => { parallel.return_value = Some(*return_value) } ChildKind::SpawnedChild(return_channel) => { self.send_to_channel( Performer::Nursery, return_channel, (*return_value).into(), ); return_value.drop(&mut ended.heap); } } if is_finished { Some(Ok(())) } else { None } } EndedReason::Panicked(panic) => Some(Err(panic.to_owned())), }; self.fibers .get_mut(&parent) .unwrap() .as_parallel_mut() .unwrap() .paused_fiber .fiber .adopt_finished_child(fiber_id, ended); if let Some(parallel_result) = parallel_result { self.finish_parallel(parent, parallel_result) } } FiberTree::Try(Try { child, .. }) => { let child_id = *child; self.fibers.replace(parent, |tree| { let mut paused_fiber = tree.into_try().unwrap().paused_fiber; let reason = ended.reason.clone(); paused_fiber.fiber.adopt_finished_child(child_id, ended); paused_fiber.fiber.complete_try(&reason); FiberTree::Single(paused_fiber) }); } } } let all_channels = self.channels.keys().copied().collect::<HashSet<_>>(); let mut known_channels = HashSet::new(); for fiber in self.fibers.values() { if let Some(single) = fiber.as_single() { known_channels.extend(single.fiber.heap.known_channels()); } } // Because we don't track yet which channels have leaked to the outside // world, any channel may be re-sent into the VM from the outside even // after no fibers remember it. Rather than removing it directly, we // communicate to the outside that no fiber references it anymore. If // the outside doesn't intend to re-use the channel, it should call // `free_channel`. self.unreferenced_channels = all_channels .difference(&known_channels) .filter(|channel| { // Note that nurseries are automatically removed when their // parallel scope is exited. self.channels.get(channel).unwrap().is_channel() }) .copied() .collect(); } fn finish_parallel(&mut self, parallel_id: FiberId, result: Result<(), Panic>) { let parallel = self .fibers .get_mut(&parallel_id) .unwrap() .as_parallel_mut() .unwrap(); for child_id in parallel.children.clone().into_keys() { self.cancel(parallel_id, child_id); } self.fibers.replace(parallel_id, |tree| { let Parallel { mut paused_fiber, nursery, return_value, .. } = tree.into_parallel().unwrap(); self.channels.remove(&nursery).unwrap(); paused_fiber .fiber .complete_parallel_scope(result.map(|_| return_value.unwrap())); FiberTree::Single(paused_fiber) }); } fn cancel(&mut self, parent_id: FiberId, fiber_id: FiberId) { let fiber_tree = self.fibers.remove(&fiber_id).unwrap(); match &fiber_tree { FiberTree::Single(_) => {} FiberTree::Parallel(Parallel { children, nursery, .. }) => { self.channels.remove(nursery).unwrap().to_nursery().unwrap(); for child_fiber in children.keys() { self.cancel(fiber_id, *child_fiber); } } FiberTree::Try(Try { child, .. }) => self.cancel(fiber_id, *child), } let parent = self.fibers.get_mut(&parent_id).unwrap().fiber_mut(); parent.tracer.child_fiber_ended(TracedFiberEnded { id: fiber_id, heap: &mut parent.heap, tracer: fiber_tree.into_fiber().tracer, reason: TracedFiberEndedReason::Canceled, }); } fn send_to_channel(&mut self, performer: Performer, channel_id: ChannelId, packet: Packet) { let channel = match self.channels.get_mut(&channel_id) { Some(channel) => channel, None => { // The channel was a nursery that died. if let Performer::Fiber(fiber) = performer { let tree = self.fibers.get_mut(&fiber).unwrap(); tree.as_single_mut() .unwrap() .fiber .panic(Panic::new_without_responsible( "The nursery is already dead because the parallel section ended." .to_string(), )); } return; } }; match channel { ChannelLike::Channel(channel) => { let mut completer = InternalCompleter { fibers: &mut self.fibers, completed_operations: &mut self.completed_operations, }; channel.send(&mut completer, performer, packet); } ChannelLike::Nursery(parent_id) => { let parent_id = *parent_id; match Self::parse_spawn_packet(packet) { Some((_packet_heap, function_to_spawn, return_channel)) => { let mut heap = Heap::default(); let function_to_spawn: Function = function_to_spawn .clone_to_heap(&mut heap) .try_into() .unwrap(); let responsible = HirId::create(&mut heap, true, Id::complicated_responsibility()); let child_id = self.fiber_id_generator.generate(); let parent = self .fibers .get_mut(&parent_id) .unwrap() .as_parallel_mut() .unwrap(); let child_tracer = parent .paused_fiber .fiber .tracer .child_fiber_created(child_id); self.fibers.insert( child_id, FiberTree::Single(Single { fiber: Fiber::for_function( heap, function_to_spawn, &[], responsible, child_tracer, ), parent: Some(parent_id), }), ); self.fibers .get_mut(&parent_id) .unwrap() .as_parallel_mut() .unwrap() .children .insert(child_id, ChildKind::SpawnedChild(return_channel)); } None => self.finish_parallel( parent_id, Err(Panic::new_without_responsible( "A nursery received an invalid message.".to_string(), )), ), } InternalCompleter { fibers: &mut self.fibers, completed_operations: &mut self.completed_operations, } .complete_send(performer); } } } fn parse_spawn_packet(packet: Packet) -> Option<(Heap, Function, ChannelId)> { let Packet { heap, object } = packet; let arguments: Struct = object.try_into().ok()?; let function_tag = Tag::create(SymbolId::FUNCTION); let function: Function = arguments.get(function_tag)?.try_into().ok()?; if function.argument_count() > 0 { return None; } let return_channel_tag = Tag::create(SymbolId::RETURN_CHANNEL); let return_channel: SendPort = arguments.get(return_channel_tag)?.try_into().ok()?; Some((heap, function, return_channel.channel_id())) } fn receive_from_channel(&mut self, performer: Performer, channel: ChannelId) { let mut completer = InternalCompleter { fibers: &mut self.fibers, completed_operations: &mut self.completed_operations, }; match self.channels.get_mut(&channel).unwrap() { ChannelLike::Channel(channel) => { channel.receive(&mut completer, performer); } ChannelLike::Nursery { .. } => unreachable!("Nurseries are only sent stuff."), } } } struct InternalCompleter<'a, T: FiberTracer> { fibers: &'a mut HashMap<FiberId, FiberTree<T>>, completed_operations: &'a mut HashMap<OperationId, CompletedOperation>, } impl<'a, T: FiberTracer> Completer for InternalCompleter<'a, T> { fn complete_send(&mut self, performer: Performer) { match performer { Performer::Fiber(fiber) => { let tree = self.fibers.get_mut(&fiber).unwrap(); tree.as_single_mut().unwrap().fiber.complete_send(); } Performer::Nursery => {} Performer::External(id) => { self.completed_operations .insert(id, CompletedOperation::Sent); } } } fn complete_receive(&mut self, performer: Performer, packet: Packet) { match performer { Performer::Fiber(fiber) => { let tree = self.fibers.get_mut(&fiber).unwrap(); tree.as_single_mut().unwrap().fiber.complete_receive(packet); } Performer::Nursery => {} Performer::External(id) => { self.completed_operations .insert(id, CompletedOperation::Received { packet }); } } } } impl ChannelLike { fn to_nursery(&self) -> Option<FiberId> { match self { ChannelLike::Nursery(fiber) => Some(*fiber), _ => None, } } } impl<T: FiberTracer> FiberTree<T> { fn into_fiber(self) -> Fiber<T> { match self { FiberTree::Single(single) => single.fiber, FiberTree::Parallel(parallel) => parallel.paused_fiber.fiber, FiberTree::Try(try_) => try_.paused_fiber.fiber, } } pub fn fiber_ref(&self) -> &Fiber<T> { match self { FiberTree::Single(single) => &single.fiber, FiberTree::Parallel(parallel) => &parallel.paused_fiber.fiber, FiberTree::Try(try_) => &try_.paused_fiber.fiber, } } pub fn fiber_mut(&mut self) -> &mut Fiber<T> { match self { FiberTree::Single(single) => &mut single.fiber, FiberTree::Parallel(parallel) => &mut parallel.paused_fiber.fiber, FiberTree::Try(try_) => &mut try_.paused_fiber.fiber, } } // TODO: Use macros to generate these. fn into_single(self) -> Option<Single<T>> { match self { FiberTree::Single(single) => Some(single), _ => None, } } fn as_single(&self) -> Option<&Single<T>> { match self { FiberTree::Single(single) => Some(single), _ => None, } } fn as_single_mut(&mut self) -> Option<&mut Single<T>> { match self { FiberTree::Single(single) => Some(single), _ => None, } } fn into_parallel(self) -> Option<Parallel<T>> { match self { FiberTree::Parallel(parallel) => Some(parallel), _ => None, } } fn as_parallel_mut(&mut self) -> Option<&mut Parallel<T>> { match self { FiberTree::Parallel(parallel) => Some(parallel), _ => None, } } fn into_try(self) -> Option<Try<T>> { match self { FiberTree::Try(try_) => Some(try_), _ => None, } } } impl<L: Borrow<Lir>, T: Tracer> Debug for Vm<L, T> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("Vm") .field("fibers", &self.fibers) .field("channels", &self.channels) .finish() } } impl<T: FiberTracer> Debug for FiberTree<T> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Self::Single(Single { fiber, parent }) => f .debug_struct("SingleFiber") .field("status", &fiber.status()) .field("parent", parent) .finish(), Self::Parallel(Parallel { children, nursery, .. }) => f .debug_struct("ParallelSection") .field("children", children) .field("nursery", nursery) .finish(), Self::Try(Try { child, .. }) => f.debug_struct("Try").field("child", child).finish(), } } } impl Debug for ChildKind { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { ChildKind::InitialChild => write!(f, "is initial child"), ChildKind::SpawnedChild(return_channel) => write!(f, "returns to {:?}", return_channel), } } } impl Debug for ChannelLike { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Self::Channel(channel) => channel.fmt(f), Self::Nursery(fiber) => f.debug_tuple("Nursery").field(fiber).finish(), } } } #[extension_trait] impl<K: Eq + Hash, V> ReplaceHashMapValue<K, V> for HashMap<K, V> { fn replace<F: FnOnce(V) -> V>(&mut self, key: K, replacer: F) { let value = self.remove(&key).unwrap(); let value = replacer(value); self.insert(key, value); } }
use std::collections::HashMap; use serde::Serialize; use crate::types::{RunInTerminalRequestArgumentsKind, StartDebuggingRequestKind}; #[derive(Serialize, Debug, Clone)] #[serde(rename_all(deserialize = "camelCase", serialize = "snake_case"))] pub struct RunInTerminalRequestArguments { /// What kind of terminal to launch. /// Values: 'integrated', 'external' pub kind: Option<RunInTerminalRequestArgumentsKind>, /// Title of the terminal. pub title: Option<String>, /// Working directory for the command. For non-empty, valid paths this /// typically results in execution of a change directory command. pub cwd: String, /// List of arguments. The first argument is the command to run. pub args: Vec<String>, /// Environment key-value pairs that are added to or removed from the default /// environment. pub env: Option<HashMap<String, Option<String>>>, /// This property should only be set if the corresponding capability /// `supportsArgsCanBeInterpretedByShell` is true. If the client uses an /// intermediary shell to launch the application, then the client must not /// attempt to escape characters with special meanings for the shell. The user /// is fully responsible for escaping as needed and that arguments using /// special characters may not be portable across shells. pub args_can_be_interpreted_by_shell: Option<bool>, } #[derive(Serialize, Debug, Clone)] #[serde(rename_all(deserialize = "camelCase", serialize = "snake_case"))] pub struct StartDebuggingRequestArguments { /// Arguments passed to the new debug session. The arguments must only contain /// properties understood by the `launch` or `attach` requests of the debug /// adapter and they must not contain any client-specific properties (e.g. /// `type`) or client-specific features (e.g. substitutable 'variables'). pub configuration: HashMap<String, serde_json::Value>, /// Indicates whether the new debug session should be started with a `launch` /// or `attach` request. /// Values: 'launch', 'attach' pub request: StartDebuggingRequestKind, } #[derive(Serialize, Debug, Clone)] #[serde( tag = "command", content = "arguments", rename_all(deserialize = "camelCase", serialize = "snake_case") )] pub enum ReverseCommand { /// This request is sent from the debug adapter to the client to run a command in a terminal. /// /// This is typically used to launch the debuggee in a terminal provided by the client. /// /// This request should only be called if the corresponding client capability /// `supportsRunInTerminalRequest` is true. /// /// Client implementations of `runInTerminal` are free to run the command however they choose /// including issuing the command to a command line interpreter (aka 'shell'). Argument strings /// passed to the `runInTerminal` request must arrive verbatim in the command to be run. /// As a consequence, clients which use a shell are responsible for escaping any special shell /// characters in the argument strings to prevent them from being interpreted (and modified) by /// the shell. /// /// Some users may wish to take advantage of shell processing in the argument strings. For /// clients which implement `runInTerminal` using an intermediary shell, the /// `argsCanBeInterpretedByShell` property can be set to true. In this case the client is /// requested not to escape any special shell characters in the argument strings. /// /// Specification: [RunInTerminal](https://microsoft.github.io/debug-adapter-protocol/specification#Reverse_Requests_RunInTerminal) RunInTerminal(RunInTerminalRequestArguments), /// This request is sent from the debug adapter to the client to start a new debug session of the /// same type as the caller. /// /// This request should only be sent if the corresponding client capability /// `supportsStartDebuggingRequest` is true. /// /// Specification: [StartDebugging](https://microsoft.github.io/debug-adapter-protocol/specification#Reverse_Requests_StartDebugging) StartDebugging(StartDebuggingRequestArguments), } /// A debug adapter initiated request. /// /// The specification treats reverse requests identically to all other requests /// (even though there is a separate section for them). However, in Rust, it is /// beneficial to separate them because then we don't need to generate a huge /// amount of serialization code for all requests and supporting types (that the /// vast majority of would never be serialized by the adapter, only deserialized). #[derive(Serialize, Debug, Clone)] #[serde(rename_all(deserialize = "camelCase", serialize = "snake_case"))] pub struct ReverseRequest { /// Sequence number for the Request. /// /// From the [specification](https://microsoft.github.io/debug-adapter-protocol/specification#Base_Protocol_ProtocolMessage): /// /// Sequence number of the message (also known as message ID). The `seq` for /// the first message sent by a client or debug adapter is 1, and for each /// subsequent message is 1 greater than the previous message sent by that /// actor. `seq` can be used to order requests, responses, and events, and to /// associate requests with their corresponding responses. For protocol /// messages of type `request` the sequence number can be used to cancel the /// request. pub seq: usize, /// The command to execute. /// /// This is stringly typed in the specification, but represented as an enum for better /// ergonomics in Rust code, along with the arguments when present. #[serde(flatten)] pub command: ReverseCommand, }
use nalgebra::Scalar; use crate::Pose; pub mod basic; pub mod kld; pub trait ParticleResampler<N: Scalar> { fn resample(&self, poses: &[Pose<N>], weights: &[N]) -> Vec<Pose<N>>; }
#[doc = "Reader of register EMR2"] pub type R = crate::R<u32, super::EMR2>; #[doc = "Writer for register EMR2"] pub type W = crate::W<u32, super::EMR2>; #[doc = "Register EMR2 `reset()`'s with value 0"] impl crate::ResetValue for super::EMR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `EM32`"] pub type EM32_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EM32`"] pub struct EM32_W<'a> { w: &'a mut W, } impl<'a> EM32_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `EM33`"] pub type EM33_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EM33`"] pub struct EM33_W<'a> { w: &'a mut W, } impl<'a> EM33_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `EM34`"] pub type EM34_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EM34`"] pub struct EM34_W<'a> { w: &'a mut W, } impl<'a> EM34_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `EM35`"] pub type EM35_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EM35`"] pub struct EM35_W<'a> { w: &'a mut W, } impl<'a> EM35_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `EM36`"] pub type EM36_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EM36`"] pub struct EM36_W<'a> { w: &'a mut W, } impl<'a> EM36_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `EM37`"] pub type EM37_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EM37`"] pub struct EM37_W<'a> { w: &'a mut W, } impl<'a> EM37_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `EM38`"] pub type EM38_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EM38`"] pub struct EM38_W<'a> { w: &'a mut W, } impl<'a> EM38_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `EM40`"] pub type EM40_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EM40`"] pub struct EM40_W<'a> { w: &'a mut W, } impl<'a> EM40_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `EM41`"] pub type EM41_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EM41`"] pub struct EM41_W<'a> { w: &'a mut W, } impl<'a> EM41_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `EM42`"] pub type EM42_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EM42`"] pub struct EM42_W<'a> { w: &'a mut W, } impl<'a> EM42_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } impl R { #[doc = "Bit 0 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em32(&self) -> EM32_R { EM32_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em33(&self) -> EM33_R { EM33_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em34(&self) -> EM34_R { EM34_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em35(&self) -> EM35_R { EM35_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em36(&self) -> EM36_R { EM36_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em37(&self) -> EM37_R { EM37_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em38(&self) -> EM38_R { EM38_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 8 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em40(&self) -> EM40_R { EM40_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em41(&self) -> EM41_R { EM41_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em42(&self) -> EM42_R { EM42_R::new(((self.bits >> 10) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em32(&mut self) -> EM32_W { EM32_W { w: self } } #[doc = "Bit 1 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em33(&mut self) -> EM33_W { EM33_W { w: self } } #[doc = "Bit 2 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em34(&mut self) -> EM34_W { EM34_W { w: self } } #[doc = "Bit 3 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em35(&mut self) -> EM35_W { EM35_W { w: self } } #[doc = "Bit 4 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em36(&mut self) -> EM36_W { EM36_W { w: self } } #[doc = "Bit 5 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em37(&mut self) -> EM37_W { EM37_W { w: self } } #[doc = "Bit 6 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em38(&mut self) -> EM38_W { EM38_W { w: self } } #[doc = "Bit 8 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em40(&mut self) -> EM40_W { EM40_W { w: self } } #[doc = "Bit 9 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em41(&mut self) -> EM41_W { EM41_W { w: self } } #[doc = "Bit 10 - CPU wakeup with interrupt mask on event input"] #[inline(always)] pub fn em42(&mut self) -> EM42_W { EM42_W { w: self } } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::vec::Vec; use alloc::string::String; use super::limits::*; use super::auth::cap_set::*; #[derive(Serialize, Deserialize, Default, Debug, Eq, PartialEq)] pub struct Process { //user pub UID: u32, pub GID: u32, pub AdditionalGids: Vec<u32>, pub Terminal: bool, pub Args: Vec<String>, pub Envs: Vec<String>, pub Cwd: String, //caps pub Caps: TaskCaps, pub NoNewPrivileges: bool, //host pub NumCpu: u32, pub HostName: String, //Container pub limitSet: LimitSetInternal, pub ID: String, pub Root: String, pub Stdiofds: [i32; 3], }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - FDCAN Core Release Register"] pub fdcan_crel: FDCAN_CREL, #[doc = "0x04 - FDCAN Core Release Register"] pub fdcan_endn: FDCAN_ENDN, _reserved2: [u8; 4usize], #[doc = "0x0c - FDCAN Data Bit Timing and Prescaler Register"] pub fdcan_dbtp: FDCAN_DBTP, #[doc = "0x10 - FDCAN Test Register"] pub fdcan_test: FDCAN_TEST, #[doc = "0x14 - FDCAN RAM Watchdog Register"] pub fdcan_rwd: FDCAN_RWD, #[doc = "0x18 - FDCAN CC Control Register"] pub fdcan_cccr: FDCAN_CCCR, #[doc = "0x1c - FDCAN Nominal Bit Timing and Prescaler Register"] pub fdcan_nbtp: FDCAN_NBTP, #[doc = "0x20 - FDCAN Timestamp Counter Configuration Register"] pub fdcan_tscc: FDCAN_TSCC, #[doc = "0x24 - FDCAN Timestamp Counter Value Register"] pub fdcan_tscv: FDCAN_TSCV, #[doc = "0x28 - FDCAN Timeout Counter Configuration Register"] pub fdcan_tocc: FDCAN_TOCC, #[doc = "0x2c - FDCAN Timeout Counter Value Register"] pub fdcan_tocv: FDCAN_TOCV, _reserved11: [u8; 16usize], #[doc = "0x40 - FDCAN Error Counter Register"] pub fdcan_ecr: FDCAN_ECR, #[doc = "0x44 - FDCAN Protocol Status Register"] pub fdcan_psr: FDCAN_PSR, #[doc = "0x48 - FDCAN Transmitter Delay Compensation Register"] pub fdcan_tdcr: FDCAN_TDCR, _reserved14: [u8; 4usize], #[doc = "0x50 - FDCAN Interrupt Register"] pub fdcan_ir: FDCAN_IR, #[doc = "0x54 - FDCAN Interrupt Enable Register"] pub fdcan_ie: FDCAN_IE, #[doc = "0x58 - FDCAN Interrupt Line Select Register"] pub fdcan_ils: FDCAN_ILS, #[doc = "0x5c - FDCAN Interrupt Line Enable Register"] pub fdcan_ile: FDCAN_ILE, _reserved18: [u8; 32usize], #[doc = "0x80 - FDCAN Global Filter Configuration Register"] pub fdcan_gfc: FDCAN_GFC, #[doc = "0x84 - FDCAN Standard ID Filter Configuration Register"] pub fdcan_sidfc: FDCAN_SIDFC, #[doc = "0x88 - FDCAN Extended ID Filter Configuration Register"] pub fdcan_xidfc: FDCAN_XIDFC, _reserved21: [u8; 4usize], #[doc = "0x90 - FDCAN Extended ID and Mask Register"] pub fdcan_xidam: FDCAN_XIDAM, #[doc = "0x94 - FDCAN High Priority Message Status Register"] pub fdcan_hpms: FDCAN_HPMS, #[doc = "0x98 - FDCAN New Data 1 Register"] pub fdcan_ndat1: FDCAN_NDAT1, #[doc = "0x9c - FDCAN New Data 2 Register"] pub fdcan_ndat2: FDCAN_NDAT2, #[doc = "0xa0 - FDCAN Rx FIFO 0 Configuration Register"] pub fdcan_rxf0c: FDCAN_RXF0C, #[doc = "0xa4 - FDCAN Rx FIFO 0 Status Register"] pub fdcan_rxf0s: FDCAN_RXF0S, #[doc = "0xa8 - CAN Rx FIFO 0 Acknowledge Register"] pub fdcan_rxf0a: FDCAN_RXF0A, #[doc = "0xac - FDCAN Rx Buffer Configuration Register"] pub fdcan_rxbc: FDCAN_RXBC, #[doc = "0xb0 - FDCAN Rx FIFO 1 Configuration Register"] pub fdcan_rxf1c: FDCAN_RXF1C, #[doc = "0xb4 - FDCAN Rx FIFO 1 Status Register"] pub fdcan_rxf1s: FDCAN_RXF1S, #[doc = "0xb8 - FDCAN Rx FIFO 1 Acknowledge Register"] pub fdcan_rxf1a: FDCAN_RXF1A, #[doc = "0xbc - FDCAN Rx Buffer Element Size Configuration Register"] pub fdcan_rxesc: FDCAN_RXESC, #[doc = "0xc0 - FDCAN Tx Buffer Configuration Register"] pub fdcan_txbc: FDCAN_TXBC, #[doc = "0xc4 - FDCAN Tx FIFO/Queue Status Register"] pub fdcan_txfqs: FDCAN_TXFQS, #[doc = "0xc8 - FDCAN Tx Buffer Element Size Configuration Register"] pub fdcan_txesc: FDCAN_TXESC, #[doc = "0xcc - FDCAN Tx Buffer Request Pending Register"] pub fdcan_txbrp: FDCAN_TXBRP, #[doc = "0xd0 - FDCAN Tx Buffer Add Request Register"] pub fdcan_txbar: FDCAN_TXBAR, #[doc = "0xd4 - FDCAN Tx Buffer Cancellation Request Register"] pub fdcan_txbcr: FDCAN_TXBCR, #[doc = "0xd8 - FDCAN Tx Buffer Transmission Occurred Register"] pub fdcan_txbto: FDCAN_TXBTO, #[doc = "0xdc - FDCAN Tx Buffer Cancellation Finished Register"] pub fdcan_txbcf: FDCAN_TXBCF, #[doc = "0xe0 - FDCAN Tx Buffer Transmission Interrupt Enable Register"] pub fdcan_txbtie: FDCAN_TXBTIE, #[doc = "0xe4 - FDCAN Tx Buffer Cancellation Finished Interrupt Enable Register"] pub fdcan_txbcie: FDCAN_TXBCIE, _reserved43: [u8; 8usize], #[doc = "0xf0 - FDCAN Tx Event FIFO Configuration Register"] pub fdcan_txefc: FDCAN_TXEFC, #[doc = "0xf4 - FDCAN Tx Event FIFO Status Register"] pub fdcan_txefs: FDCAN_TXEFS, #[doc = "0xf8 - FDCAN Tx Event FIFO Acknowledge Register"] pub fdcan_txefa: FDCAN_TXEFA, _reserved46: [u8; 4usize], _reserved_46_fdcan: [u8; 4usize], #[doc = "0x104 - FDCAN TT Reference Message Configuration Register"] pub fdcan_ttrmc: FDCAN_TTRMC, #[doc = "0x108 - FDCAN TT Operation Configuration Register"] pub fdcan_ttocf: FDCAN_TTOCF, #[doc = "0x10c - FDCAN TT Matrix Limits Register"] pub fdcan_ttmlm: FDCAN_TTMLM, #[doc = "0x110 - FDCAN TUR Configuration Register"] pub fdcan_turcf: FDCAN_TURCF, #[doc = "0x114 - FDCAN TT Operation Control Register"] pub fdcan_ttocn: FDCAN_TTOCN, #[doc = "0x118 - FDCAN TT Global Time Preset Register"] pub can_ttgtp: CAN_TTGTP, #[doc = "0x11c - FDCAN TT Time Mark Register"] pub fdcan_tttmk: FDCAN_TTTMK, #[doc = "0x120 - FDCAN TT Interrupt Register"] pub fdcan_ttir: FDCAN_TTIR, #[doc = "0x124 - FDCAN TT Interrupt Enable Register"] pub fdcan_ttie: FDCAN_TTIE, #[doc = "0x128 - FDCAN TT Interrupt Line Select Register"] pub fdcan_ttils: FDCAN_TTILS, #[doc = "0x12c - FDCAN TT Operation Status Register"] pub fdcan_ttost: FDCAN_TTOST, #[doc = "0x130 - FDCAN TUR Numerator Actual Register"] pub fdcan_turna: FDCAN_TURNA, #[doc = "0x134 - FDCAN TT Local and Global Time Register"] pub fdcan_ttlgt: FDCAN_TTLGT, #[doc = "0x138 - FDCAN TT Cycle Time and Count Register"] pub fdcan_ttctc: FDCAN_TTCTC, #[doc = "0x13c - FDCAN TT Capture Time Register"] pub fdcan_ttcpt: FDCAN_TTCPT, #[doc = "0x140 - FDCAN TT Cycle Sync Mark Register"] pub fdcan_ttcsm: FDCAN_TTCSM, } impl RegisterBlock { #[doc = "0x100 - FDCAN TT Trigger Select Register"] #[inline(always)] pub fn fdcan_ttts(&self) -> &FDCAN_TTTS { unsafe { &*(((self as *const Self) as *const u8).add(256usize) as *const FDCAN_TTTS) } } #[doc = "0x100 - FDCAN TT Trigger Select Register"] #[inline(always)] pub fn fdcan_ttts_mut(&self) -> &mut FDCAN_TTTS { unsafe { &mut *(((self as *const Self) as *mut u8).add(256usize) as *mut FDCAN_TTTS) } } #[doc = "0x100 - FDCAN TT Trigger Memory Configuration Register"] #[inline(always)] pub fn fdcan_tttmc(&self) -> &FDCAN_TTTMC { unsafe { &*(((self as *const Self) as *const u8).add(256usize) as *const FDCAN_TTTMC) } } #[doc = "0x100 - FDCAN TT Trigger Memory Configuration Register"] #[inline(always)] pub fn fdcan_tttmc_mut(&self) -> &mut FDCAN_TTTMC { unsafe { &mut *(((self as *const Self) as *mut u8).add(256usize) as *mut FDCAN_TTTMC) } } } #[doc = "FDCAN Core Release Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_crel](fdcan_crel) module"] pub type FDCAN_CREL = crate::Reg<u32, _FDCAN_CREL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_CREL; #[doc = "`read()` method returns [fdcan_crel::R](fdcan_crel::R) reader structure"] impl crate::Readable for FDCAN_CREL {} #[doc = "FDCAN Core Release Register"] pub mod fdcan_crel; #[doc = "FDCAN Core Release Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_endn](fdcan_endn) module"] pub type FDCAN_ENDN = crate::Reg<u32, _FDCAN_ENDN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_ENDN; #[doc = "`read()` method returns [fdcan_endn::R](fdcan_endn::R) reader structure"] impl crate::Readable for FDCAN_ENDN {} #[doc = "FDCAN Core Release Register"] pub mod fdcan_endn; #[doc = "FDCAN Data Bit Timing and Prescaler Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_dbtp](fdcan_dbtp) module"] pub type FDCAN_DBTP = crate::Reg<u32, _FDCAN_DBTP>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_DBTP; #[doc = "`read()` method returns [fdcan_dbtp::R](fdcan_dbtp::R) reader structure"] impl crate::Readable for FDCAN_DBTP {} #[doc = "FDCAN Data Bit Timing and Prescaler Register"] pub mod fdcan_dbtp; #[doc = "FDCAN Test Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_test](fdcan_test) module"] pub type FDCAN_TEST = crate::Reg<u32, _FDCAN_TEST>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TEST; #[doc = "`read()` method returns [fdcan_test::R](fdcan_test::R) reader structure"] impl crate::Readable for FDCAN_TEST {} #[doc = "FDCAN Test Register"] pub mod fdcan_test; #[doc = "FDCAN RAM Watchdog Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rwd](fdcan_rwd) module"] pub type FDCAN_RWD = crate::Reg<u32, _FDCAN_RWD>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_RWD; #[doc = "`read()` method returns [fdcan_rwd::R](fdcan_rwd::R) reader structure"] impl crate::Readable for FDCAN_RWD {} #[doc = "FDCAN RAM Watchdog Register"] pub mod fdcan_rwd; #[doc = "FDCAN CC Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_cccr](fdcan_cccr) module"] pub type FDCAN_CCCR = crate::Reg<u32, _FDCAN_CCCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_CCCR; #[doc = "`read()` method returns [fdcan_cccr::R](fdcan_cccr::R) reader structure"] impl crate::Readable for FDCAN_CCCR {} #[doc = "`write(|w| ..)` method takes [fdcan_cccr::W](fdcan_cccr::W) writer structure"] impl crate::Writable for FDCAN_CCCR {} #[doc = "FDCAN CC Control Register"] pub mod fdcan_cccr; #[doc = "FDCAN Nominal Bit Timing and Prescaler Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_nbtp](fdcan_nbtp) module"] pub type FDCAN_NBTP = crate::Reg<u32, _FDCAN_NBTP>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_NBTP; #[doc = "`read()` method returns [fdcan_nbtp::R](fdcan_nbtp::R) reader structure"] impl crate::Readable for FDCAN_NBTP {} #[doc = "`write(|w| ..)` method takes [fdcan_nbtp::W](fdcan_nbtp::W) writer structure"] impl crate::Writable for FDCAN_NBTP {} #[doc = "FDCAN Nominal Bit Timing and Prescaler Register"] pub mod fdcan_nbtp; #[doc = "FDCAN Timestamp Counter Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_tscc](fdcan_tscc) module"] pub type FDCAN_TSCC = crate::Reg<u32, _FDCAN_TSCC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TSCC; #[doc = "`read()` method returns [fdcan_tscc::R](fdcan_tscc::R) reader structure"] impl crate::Readable for FDCAN_TSCC {} #[doc = "`write(|w| ..)` method takes [fdcan_tscc::W](fdcan_tscc::W) writer structure"] impl crate::Writable for FDCAN_TSCC {} #[doc = "FDCAN Timestamp Counter Configuration Register"] pub mod fdcan_tscc; #[doc = "FDCAN Timestamp Counter Value Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_tscv](fdcan_tscv) module"] pub type FDCAN_TSCV = crate::Reg<u32, _FDCAN_TSCV>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TSCV; #[doc = "`read()` method returns [fdcan_tscv::R](fdcan_tscv::R) reader structure"] impl crate::Readable for FDCAN_TSCV {} #[doc = "`write(|w| ..)` method takes [fdcan_tscv::W](fdcan_tscv::W) writer structure"] impl crate::Writable for FDCAN_TSCV {} #[doc = "FDCAN Timestamp Counter Value Register"] pub mod fdcan_tscv; #[doc = "FDCAN Timeout Counter Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_tocc](fdcan_tocc) module"] pub type FDCAN_TOCC = crate::Reg<u32, _FDCAN_TOCC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TOCC; #[doc = "`read()` method returns [fdcan_tocc::R](fdcan_tocc::R) reader structure"] impl crate::Readable for FDCAN_TOCC {} #[doc = "`write(|w| ..)` method takes [fdcan_tocc::W](fdcan_tocc::W) writer structure"] impl crate::Writable for FDCAN_TOCC {} #[doc = "FDCAN Timeout Counter Configuration Register"] pub mod fdcan_tocc; #[doc = "FDCAN Timeout Counter Value Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_tocv](fdcan_tocv) module"] pub type FDCAN_TOCV = crate::Reg<u32, _FDCAN_TOCV>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TOCV; #[doc = "`read()` method returns [fdcan_tocv::R](fdcan_tocv::R) reader structure"] impl crate::Readable for FDCAN_TOCV {} #[doc = "`write(|w| ..)` method takes [fdcan_tocv::W](fdcan_tocv::W) writer structure"] impl crate::Writable for FDCAN_TOCV {} #[doc = "FDCAN Timeout Counter Value Register"] pub mod fdcan_tocv; #[doc = "FDCAN Error Counter Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ecr](fdcan_ecr) module"] pub type FDCAN_ECR = crate::Reg<u32, _FDCAN_ECR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_ECR; #[doc = "`read()` method returns [fdcan_ecr::R](fdcan_ecr::R) reader structure"] impl crate::Readable for FDCAN_ECR {} #[doc = "`write(|w| ..)` method takes [fdcan_ecr::W](fdcan_ecr::W) writer structure"] impl crate::Writable for FDCAN_ECR {} #[doc = "FDCAN Error Counter Register"] pub mod fdcan_ecr; #[doc = "FDCAN Protocol Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_psr](fdcan_psr) module"] pub type FDCAN_PSR = crate::Reg<u32, _FDCAN_PSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_PSR; #[doc = "`read()` method returns [fdcan_psr::R](fdcan_psr::R) reader structure"] impl crate::Readable for FDCAN_PSR {} #[doc = "`write(|w| ..)` method takes [fdcan_psr::W](fdcan_psr::W) writer structure"] impl crate::Writable for FDCAN_PSR {} #[doc = "FDCAN Protocol Status Register"] pub mod fdcan_psr; #[doc = "FDCAN Transmitter Delay Compensation Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_tdcr](fdcan_tdcr) module"] pub type FDCAN_TDCR = crate::Reg<u32, _FDCAN_TDCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TDCR; #[doc = "`read()` method returns [fdcan_tdcr::R](fdcan_tdcr::R) reader structure"] impl crate::Readable for FDCAN_TDCR {} #[doc = "FDCAN Transmitter Delay Compensation Register"] pub mod fdcan_tdcr; #[doc = "FDCAN Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ir](fdcan_ir) module"] pub type FDCAN_IR = crate::Reg<u32, _FDCAN_IR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_IR; #[doc = "`read()` method returns [fdcan_ir::R](fdcan_ir::R) reader structure"] impl crate::Readable for FDCAN_IR {} #[doc = "FDCAN Interrupt Register"] pub mod fdcan_ir; #[doc = "FDCAN Interrupt Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ie](fdcan_ie) module"] pub type FDCAN_IE = crate::Reg<u32, _FDCAN_IE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_IE; #[doc = "`read()` method returns [fdcan_ie::R](fdcan_ie::R) reader structure"] impl crate::Readable for FDCAN_IE {} #[doc = "FDCAN Interrupt Enable Register"] pub mod fdcan_ie; #[doc = "FDCAN Interrupt Line Select Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ils](fdcan_ils) module"] pub type FDCAN_ILS = crate::Reg<u32, _FDCAN_ILS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_ILS; #[doc = "`read()` method returns [fdcan_ils::R](fdcan_ils::R) reader structure"] impl crate::Readable for FDCAN_ILS {} #[doc = "FDCAN Interrupt Line Select Register"] pub mod fdcan_ils; #[doc = "FDCAN Interrupt Line Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ile](fdcan_ile) module"] pub type FDCAN_ILE = crate::Reg<u32, _FDCAN_ILE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_ILE; #[doc = "`read()` method returns [fdcan_ile::R](fdcan_ile::R) reader structure"] impl crate::Readable for FDCAN_ILE {} #[doc = "`write(|w| ..)` method takes [fdcan_ile::W](fdcan_ile::W) writer structure"] impl crate::Writable for FDCAN_ILE {} #[doc = "FDCAN Interrupt Line Enable Register"] pub mod fdcan_ile; #[doc = "FDCAN Global Filter Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_gfc](fdcan_gfc) module"] pub type FDCAN_GFC = crate::Reg<u32, _FDCAN_GFC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_GFC; #[doc = "`read()` method returns [fdcan_gfc::R](fdcan_gfc::R) reader structure"] impl crate::Readable for FDCAN_GFC {} #[doc = "`write(|w| ..)` method takes [fdcan_gfc::W](fdcan_gfc::W) writer structure"] impl crate::Writable for FDCAN_GFC {} #[doc = "FDCAN Global Filter Configuration Register"] pub mod fdcan_gfc; #[doc = "FDCAN Standard ID Filter Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_sidfc](fdcan_sidfc) module"] pub type FDCAN_SIDFC = crate::Reg<u32, _FDCAN_SIDFC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_SIDFC; #[doc = "`read()` method returns [fdcan_sidfc::R](fdcan_sidfc::R) reader structure"] impl crate::Readable for FDCAN_SIDFC {} #[doc = "`write(|w| ..)` method takes [fdcan_sidfc::W](fdcan_sidfc::W) writer structure"] impl crate::Writable for FDCAN_SIDFC {} #[doc = "FDCAN Standard ID Filter Configuration Register"] pub mod fdcan_sidfc; #[doc = "FDCAN Extended ID Filter Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_xidfc](fdcan_xidfc) module"] pub type FDCAN_XIDFC = crate::Reg<u32, _FDCAN_XIDFC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_XIDFC; #[doc = "`read()` method returns [fdcan_xidfc::R](fdcan_xidfc::R) reader structure"] impl crate::Readable for FDCAN_XIDFC {} #[doc = "`write(|w| ..)` method takes [fdcan_xidfc::W](fdcan_xidfc::W) writer structure"] impl crate::Writable for FDCAN_XIDFC {} #[doc = "FDCAN Extended ID Filter Configuration Register"] pub mod fdcan_xidfc; #[doc = "FDCAN Extended ID and Mask Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_xidam](fdcan_xidam) module"] pub type FDCAN_XIDAM = crate::Reg<u32, _FDCAN_XIDAM>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_XIDAM; #[doc = "`read()` method returns [fdcan_xidam::R](fdcan_xidam::R) reader structure"] impl crate::Readable for FDCAN_XIDAM {} #[doc = "`write(|w| ..)` method takes [fdcan_xidam::W](fdcan_xidam::W) writer structure"] impl crate::Writable for FDCAN_XIDAM {} #[doc = "FDCAN Extended ID and Mask Register"] pub mod fdcan_xidam; #[doc = "FDCAN High Priority Message Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_hpms](fdcan_hpms) module"] pub type FDCAN_HPMS = crate::Reg<u32, _FDCAN_HPMS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_HPMS; #[doc = "`read()` method returns [fdcan_hpms::R](fdcan_hpms::R) reader structure"] impl crate::Readable for FDCAN_HPMS {} #[doc = "FDCAN High Priority Message Status Register"] pub mod fdcan_hpms; #[doc = "FDCAN New Data 1 Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ndat1](fdcan_ndat1) module"] pub type FDCAN_NDAT1 = crate::Reg<u32, _FDCAN_NDAT1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_NDAT1; #[doc = "`read()` method returns [fdcan_ndat1::R](fdcan_ndat1::R) reader structure"] impl crate::Readable for FDCAN_NDAT1 {} #[doc = "FDCAN New Data 1 Register"] pub mod fdcan_ndat1; #[doc = "FDCAN New Data 2 Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ndat2](fdcan_ndat2) module"] pub type FDCAN_NDAT2 = crate::Reg<u32, _FDCAN_NDAT2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_NDAT2; #[doc = "`read()` method returns [fdcan_ndat2::R](fdcan_ndat2::R) reader structure"] impl crate::Readable for FDCAN_NDAT2 {} #[doc = "FDCAN New Data 2 Register"] pub mod fdcan_ndat2; #[doc = "FDCAN Rx FIFO 0 Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxf0c](fdcan_rxf0c) module"] pub type FDCAN_RXF0C = crate::Reg<u32, _FDCAN_RXF0C>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_RXF0C; #[doc = "`read()` method returns [fdcan_rxf0c::R](fdcan_rxf0c::R) reader structure"] impl crate::Readable for FDCAN_RXF0C {} #[doc = "`write(|w| ..)` method takes [fdcan_rxf0c::W](fdcan_rxf0c::W) writer structure"] impl crate::Writable for FDCAN_RXF0C {} #[doc = "FDCAN Rx FIFO 0 Configuration Register"] pub mod fdcan_rxf0c; #[doc = "FDCAN Rx FIFO 0 Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxf0s](fdcan_rxf0s) module"] pub type FDCAN_RXF0S = crate::Reg<u32, _FDCAN_RXF0S>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_RXF0S; #[doc = "`read()` method returns [fdcan_rxf0s::R](fdcan_rxf0s::R) reader structure"] impl crate::Readable for FDCAN_RXF0S {} #[doc = "`write(|w| ..)` method takes [fdcan_rxf0s::W](fdcan_rxf0s::W) writer structure"] impl crate::Writable for FDCAN_RXF0S {} #[doc = "FDCAN Rx FIFO 0 Status Register"] pub mod fdcan_rxf0s; #[doc = "CAN Rx FIFO 0 Acknowledge Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxf0a](fdcan_rxf0a) module"] pub type FDCAN_RXF0A = crate::Reg<u32, _FDCAN_RXF0A>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_RXF0A; #[doc = "`read()` method returns [fdcan_rxf0a::R](fdcan_rxf0a::R) reader structure"] impl crate::Readable for FDCAN_RXF0A {} #[doc = "`write(|w| ..)` method takes [fdcan_rxf0a::W](fdcan_rxf0a::W) writer structure"] impl crate::Writable for FDCAN_RXF0A {} #[doc = "CAN Rx FIFO 0 Acknowledge Register"] pub mod fdcan_rxf0a; #[doc = "FDCAN Rx Buffer Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxbc](fdcan_rxbc) module"] pub type FDCAN_RXBC = crate::Reg<u32, _FDCAN_RXBC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_RXBC; #[doc = "`read()` method returns [fdcan_rxbc::R](fdcan_rxbc::R) reader structure"] impl crate::Readable for FDCAN_RXBC {} #[doc = "`write(|w| ..)` method takes [fdcan_rxbc::W](fdcan_rxbc::W) writer structure"] impl crate::Writable for FDCAN_RXBC {} #[doc = "FDCAN Rx Buffer Configuration Register"] pub mod fdcan_rxbc; #[doc = "FDCAN Rx FIFO 1 Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxf1c](fdcan_rxf1c) module"] pub type FDCAN_RXF1C = crate::Reg<u32, _FDCAN_RXF1C>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_RXF1C; #[doc = "`read()` method returns [fdcan_rxf1c::R](fdcan_rxf1c::R) reader structure"] impl crate::Readable for FDCAN_RXF1C {} #[doc = "`write(|w| ..)` method takes [fdcan_rxf1c::W](fdcan_rxf1c::W) writer structure"] impl crate::Writable for FDCAN_RXF1C {} #[doc = "FDCAN Rx FIFO 1 Configuration Register"] pub mod fdcan_rxf1c; #[doc = "FDCAN Rx FIFO 1 Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxf1s](fdcan_rxf1s) module"] pub type FDCAN_RXF1S = crate::Reg<u32, _FDCAN_RXF1S>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_RXF1S; #[doc = "`read()` method returns [fdcan_rxf1s::R](fdcan_rxf1s::R) reader structure"] impl crate::Readable for FDCAN_RXF1S {} #[doc = "`write(|w| ..)` method takes [fdcan_rxf1s::W](fdcan_rxf1s::W) writer structure"] impl crate::Writable for FDCAN_RXF1S {} #[doc = "FDCAN Rx FIFO 1 Status Register"] pub mod fdcan_rxf1s; #[doc = "FDCAN Rx FIFO 1 Acknowledge Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxf1a](fdcan_rxf1a) module"] pub type FDCAN_RXF1A = crate::Reg<u32, _FDCAN_RXF1A>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_RXF1A; #[doc = "`read()` method returns [fdcan_rxf1a::R](fdcan_rxf1a::R) reader structure"] impl crate::Readable for FDCAN_RXF1A {} #[doc = "`write(|w| ..)` method takes [fdcan_rxf1a::W](fdcan_rxf1a::W) writer structure"] impl crate::Writable for FDCAN_RXF1A {} #[doc = "FDCAN Rx FIFO 1 Acknowledge Register"] pub mod fdcan_rxf1a; #[doc = "FDCAN Rx Buffer Element Size Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxesc](fdcan_rxesc) module"] pub type FDCAN_RXESC = crate::Reg<u32, _FDCAN_RXESC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_RXESC; #[doc = "`read()` method returns [fdcan_rxesc::R](fdcan_rxesc::R) reader structure"] impl crate::Readable for FDCAN_RXESC {} #[doc = "`write(|w| ..)` method takes [fdcan_rxesc::W](fdcan_rxesc::W) writer structure"] impl crate::Writable for FDCAN_RXESC {} #[doc = "FDCAN Rx Buffer Element Size Configuration Register"] pub mod fdcan_rxesc; #[doc = "FDCAN Tx Buffer Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbc](fdcan_txbc) module"] pub type FDCAN_TXBC = crate::Reg<u32, _FDCAN_TXBC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXBC; #[doc = "`read()` method returns [fdcan_txbc::R](fdcan_txbc::R) reader structure"] impl crate::Readable for FDCAN_TXBC {} #[doc = "`write(|w| ..)` method takes [fdcan_txbc::W](fdcan_txbc::W) writer structure"] impl crate::Writable for FDCAN_TXBC {} #[doc = "FDCAN Tx Buffer Configuration Register"] pub mod fdcan_txbc; #[doc = "FDCAN Tx FIFO/Queue Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txfqs](fdcan_txfqs) module"] pub type FDCAN_TXFQS = crate::Reg<u32, _FDCAN_TXFQS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXFQS; #[doc = "`read()` method returns [fdcan_txfqs::R](fdcan_txfqs::R) reader structure"] impl crate::Readable for FDCAN_TXFQS {} #[doc = "FDCAN Tx FIFO/Queue Status Register"] pub mod fdcan_txfqs; #[doc = "FDCAN Tx Buffer Element Size Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txesc](fdcan_txesc) module"] pub type FDCAN_TXESC = crate::Reg<u32, _FDCAN_TXESC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXESC; #[doc = "`read()` method returns [fdcan_txesc::R](fdcan_txesc::R) reader structure"] impl crate::Readable for FDCAN_TXESC {} #[doc = "`write(|w| ..)` method takes [fdcan_txesc::W](fdcan_txesc::W) writer structure"] impl crate::Writable for FDCAN_TXESC {} #[doc = "FDCAN Tx Buffer Element Size Configuration Register"] pub mod fdcan_txesc; #[doc = "FDCAN Tx Buffer Request Pending Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbrp](fdcan_txbrp) module"] pub type FDCAN_TXBRP = crate::Reg<u32, _FDCAN_TXBRP>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXBRP; #[doc = "`read()` method returns [fdcan_txbrp::R](fdcan_txbrp::R) reader structure"] impl crate::Readable for FDCAN_TXBRP {} #[doc = "FDCAN Tx Buffer Request Pending Register"] pub mod fdcan_txbrp; #[doc = "FDCAN Tx Buffer Add Request Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbar](fdcan_txbar) module"] pub type FDCAN_TXBAR = crate::Reg<u32, _FDCAN_TXBAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXBAR; #[doc = "`read()` method returns [fdcan_txbar::R](fdcan_txbar::R) reader structure"] impl crate::Readable for FDCAN_TXBAR {} #[doc = "`write(|w| ..)` method takes [fdcan_txbar::W](fdcan_txbar::W) writer structure"] impl crate::Writable for FDCAN_TXBAR {} #[doc = "FDCAN Tx Buffer Add Request Register"] pub mod fdcan_txbar; #[doc = "FDCAN Tx Buffer Cancellation Request Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbcr](fdcan_txbcr) module"] pub type FDCAN_TXBCR = crate::Reg<u32, _FDCAN_TXBCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXBCR; #[doc = "`read()` method returns [fdcan_txbcr::R](fdcan_txbcr::R) reader structure"] impl crate::Readable for FDCAN_TXBCR {} #[doc = "`write(|w| ..)` method takes [fdcan_txbcr::W](fdcan_txbcr::W) writer structure"] impl crate::Writable for FDCAN_TXBCR {} #[doc = "FDCAN Tx Buffer Cancellation Request Register"] pub mod fdcan_txbcr; #[doc = "FDCAN Tx Buffer Transmission Occurred Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbto](fdcan_txbto) module"] pub type FDCAN_TXBTO = crate::Reg<u32, _FDCAN_TXBTO>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXBTO; #[doc = "`read()` method returns [fdcan_txbto::R](fdcan_txbto::R) reader structure"] impl crate::Readable for FDCAN_TXBTO {} #[doc = "`write(|w| ..)` method takes [fdcan_txbto::W](fdcan_txbto::W) writer structure"] impl crate::Writable for FDCAN_TXBTO {} #[doc = "FDCAN Tx Buffer Transmission Occurred Register"] pub mod fdcan_txbto; #[doc = "FDCAN Tx Buffer Cancellation Finished Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbcf](fdcan_txbcf) module"] pub type FDCAN_TXBCF = crate::Reg<u32, _FDCAN_TXBCF>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXBCF; #[doc = "`read()` method returns [fdcan_txbcf::R](fdcan_txbcf::R) reader structure"] impl crate::Readable for FDCAN_TXBCF {} #[doc = "FDCAN Tx Buffer Cancellation Finished Register"] pub mod fdcan_txbcf; #[doc = "FDCAN Tx Buffer Transmission Interrupt Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbtie](fdcan_txbtie) module"] pub type FDCAN_TXBTIE = crate::Reg<u32, _FDCAN_TXBTIE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXBTIE; #[doc = "`read()` method returns [fdcan_txbtie::R](fdcan_txbtie::R) reader structure"] impl crate::Readable for FDCAN_TXBTIE {} #[doc = "`write(|w| ..)` method takes [fdcan_txbtie::W](fdcan_txbtie::W) writer structure"] impl crate::Writable for FDCAN_TXBTIE {} #[doc = "FDCAN Tx Buffer Transmission Interrupt Enable Register"] pub mod fdcan_txbtie; #[doc = "FDCAN Tx Buffer Cancellation Finished Interrupt Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbcie](fdcan_txbcie) module"] pub type FDCAN_TXBCIE = crate::Reg<u32, _FDCAN_TXBCIE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXBCIE; #[doc = "`read()` method returns [fdcan_txbcie::R](fdcan_txbcie::R) reader structure"] impl crate::Readable for FDCAN_TXBCIE {} #[doc = "`write(|w| ..)` method takes [fdcan_txbcie::W](fdcan_txbcie::W) writer structure"] impl crate::Writable for FDCAN_TXBCIE {} #[doc = "FDCAN Tx Buffer Cancellation Finished Interrupt Enable Register"] pub mod fdcan_txbcie; #[doc = "FDCAN Tx Event FIFO Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txefc](fdcan_txefc) module"] pub type FDCAN_TXEFC = crate::Reg<u32, _FDCAN_TXEFC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXEFC; #[doc = "`read()` method returns [fdcan_txefc::R](fdcan_txefc::R) reader structure"] impl crate::Readable for FDCAN_TXEFC {} #[doc = "`write(|w| ..)` method takes [fdcan_txefc::W](fdcan_txefc::W) writer structure"] impl crate::Writable for FDCAN_TXEFC {} #[doc = "FDCAN Tx Event FIFO Configuration Register"] pub mod fdcan_txefc; #[doc = "FDCAN Tx Event FIFO Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txefs](fdcan_txefs) module"] pub type FDCAN_TXEFS = crate::Reg<u32, _FDCAN_TXEFS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXEFS; #[doc = "`read()` method returns [fdcan_txefs::R](fdcan_txefs::R) reader structure"] impl crate::Readable for FDCAN_TXEFS {} #[doc = "`write(|w| ..)` method takes [fdcan_txefs::W](fdcan_txefs::W) writer structure"] impl crate::Writable for FDCAN_TXEFS {} #[doc = "FDCAN Tx Event FIFO Status Register"] pub mod fdcan_txefs; #[doc = "FDCAN Tx Event FIFO Acknowledge Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txefa](fdcan_txefa) module"] pub type FDCAN_TXEFA = crate::Reg<u32, _FDCAN_TXEFA>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TXEFA; #[doc = "`read()` method returns [fdcan_txefa::R](fdcan_txefa::R) reader structure"] impl crate::Readable for FDCAN_TXEFA {} #[doc = "`write(|w| ..)` method takes [fdcan_txefa::W](fdcan_txefa::W) writer structure"] impl crate::Writable for FDCAN_TXEFA {} #[doc = "FDCAN Tx Event FIFO Acknowledge Register"] pub mod fdcan_txefa; #[doc = "FDCAN TT Trigger Memory Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_tttmc](fdcan_tttmc) module"] pub type FDCAN_TTTMC = crate::Reg<u32, _FDCAN_TTTMC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTTMC; #[doc = "`read()` method returns [fdcan_tttmc::R](fdcan_tttmc::R) reader structure"] impl crate::Readable for FDCAN_TTTMC {} #[doc = "`write(|w| ..)` method takes [fdcan_tttmc::W](fdcan_tttmc::W) writer structure"] impl crate::Writable for FDCAN_TTTMC {} #[doc = "FDCAN TT Trigger Memory Configuration Register"] pub mod fdcan_tttmc; #[doc = "FDCAN TT Reference Message Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttrmc](fdcan_ttrmc) module"] pub type FDCAN_TTRMC = crate::Reg<u32, _FDCAN_TTRMC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTRMC; #[doc = "`read()` method returns [fdcan_ttrmc::R](fdcan_ttrmc::R) reader structure"] impl crate::Readable for FDCAN_TTRMC {} #[doc = "`write(|w| ..)` method takes [fdcan_ttrmc::W](fdcan_ttrmc::W) writer structure"] impl crate::Writable for FDCAN_TTRMC {} #[doc = "FDCAN TT Reference Message Configuration Register"] pub mod fdcan_ttrmc; #[doc = "FDCAN TT Operation Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttocf](fdcan_ttocf) module"] pub type FDCAN_TTOCF = crate::Reg<u32, _FDCAN_TTOCF>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTOCF; #[doc = "`read()` method returns [fdcan_ttocf::R](fdcan_ttocf::R) reader structure"] impl crate::Readable for FDCAN_TTOCF {} #[doc = "`write(|w| ..)` method takes [fdcan_ttocf::W](fdcan_ttocf::W) writer structure"] impl crate::Writable for FDCAN_TTOCF {} #[doc = "FDCAN TT Operation Configuration Register"] pub mod fdcan_ttocf; #[doc = "FDCAN TT Matrix Limits Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttmlm](fdcan_ttmlm) module"] pub type FDCAN_TTMLM = crate::Reg<u32, _FDCAN_TTMLM>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTMLM; #[doc = "`read()` method returns [fdcan_ttmlm::R](fdcan_ttmlm::R) reader structure"] impl crate::Readable for FDCAN_TTMLM {} #[doc = "`write(|w| ..)` method takes [fdcan_ttmlm::W](fdcan_ttmlm::W) writer structure"] impl crate::Writable for FDCAN_TTMLM {} #[doc = "FDCAN TT Matrix Limits Register"] pub mod fdcan_ttmlm; #[doc = "FDCAN TUR Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_turcf](fdcan_turcf) module"] pub type FDCAN_TURCF = crate::Reg<u32, _FDCAN_TURCF>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TURCF; #[doc = "`read()` method returns [fdcan_turcf::R](fdcan_turcf::R) reader structure"] impl crate::Readable for FDCAN_TURCF {} #[doc = "`write(|w| ..)` method takes [fdcan_turcf::W](fdcan_turcf::W) writer structure"] impl crate::Writable for FDCAN_TURCF {} #[doc = "FDCAN TUR Configuration Register"] pub mod fdcan_turcf; #[doc = "FDCAN TT Operation Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttocn](fdcan_ttocn) module"] pub type FDCAN_TTOCN = crate::Reg<u32, _FDCAN_TTOCN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTOCN; #[doc = "`read()` method returns [fdcan_ttocn::R](fdcan_ttocn::R) reader structure"] impl crate::Readable for FDCAN_TTOCN {} #[doc = "`write(|w| ..)` method takes [fdcan_ttocn::W](fdcan_ttocn::W) writer structure"] impl crate::Writable for FDCAN_TTOCN {} #[doc = "FDCAN TT Operation Control Register"] pub mod fdcan_ttocn; #[doc = "FDCAN TT Global Time Preset Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [can_ttgtp](can_ttgtp) module"] pub type CAN_TTGTP = crate::Reg<u32, _CAN_TTGTP>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CAN_TTGTP; #[doc = "`read()` method returns [can_ttgtp::R](can_ttgtp::R) reader structure"] impl crate::Readable for CAN_TTGTP {} #[doc = "`write(|w| ..)` method takes [can_ttgtp::W](can_ttgtp::W) writer structure"] impl crate::Writable for CAN_TTGTP {} #[doc = "FDCAN TT Global Time Preset Register"] pub mod can_ttgtp; #[doc = "FDCAN TT Time Mark Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_tttmk](fdcan_tttmk) module"] pub type FDCAN_TTTMK = crate::Reg<u32, _FDCAN_TTTMK>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTTMK; #[doc = "`read()` method returns [fdcan_tttmk::R](fdcan_tttmk::R) reader structure"] impl crate::Readable for FDCAN_TTTMK {} #[doc = "`write(|w| ..)` method takes [fdcan_tttmk::W](fdcan_tttmk::W) writer structure"] impl crate::Writable for FDCAN_TTTMK {} #[doc = "FDCAN TT Time Mark Register"] pub mod fdcan_tttmk; #[doc = "FDCAN TT Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttir](fdcan_ttir) module"] pub type FDCAN_TTIR = crate::Reg<u32, _FDCAN_TTIR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTIR; #[doc = "`read()` method returns [fdcan_ttir::R](fdcan_ttir::R) reader structure"] impl crate::Readable for FDCAN_TTIR {} #[doc = "`write(|w| ..)` method takes [fdcan_ttir::W](fdcan_ttir::W) writer structure"] impl crate::Writable for FDCAN_TTIR {} #[doc = "FDCAN TT Interrupt Register"] pub mod fdcan_ttir; #[doc = "FDCAN TT Interrupt Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttie](fdcan_ttie) module"] pub type FDCAN_TTIE = crate::Reg<u32, _FDCAN_TTIE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTIE; #[doc = "`read()` method returns [fdcan_ttie::R](fdcan_ttie::R) reader structure"] impl crate::Readable for FDCAN_TTIE {} #[doc = "`write(|w| ..)` method takes [fdcan_ttie::W](fdcan_ttie::W) writer structure"] impl crate::Writable for FDCAN_TTIE {} #[doc = "FDCAN TT Interrupt Enable Register"] pub mod fdcan_ttie; #[doc = "FDCAN TT Interrupt Line Select Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttils](fdcan_ttils) module"] pub type FDCAN_TTILS = crate::Reg<u32, _FDCAN_TTILS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTILS; #[doc = "`read()` method returns [fdcan_ttils::R](fdcan_ttils::R) reader structure"] impl crate::Readable for FDCAN_TTILS {} #[doc = "`write(|w| ..)` method takes [fdcan_ttils::W](fdcan_ttils::W) writer structure"] impl crate::Writable for FDCAN_TTILS {} #[doc = "FDCAN TT Interrupt Line Select Register"] pub mod fdcan_ttils; #[doc = "FDCAN TT Operation Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttost](fdcan_ttost) module"] pub type FDCAN_TTOST = crate::Reg<u32, _FDCAN_TTOST>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTOST; #[doc = "`read()` method returns [fdcan_ttost::R](fdcan_ttost::R) reader structure"] impl crate::Readable for FDCAN_TTOST {} #[doc = "FDCAN TT Operation Status Register"] pub mod fdcan_ttost; #[doc = "FDCAN TUR Numerator Actual Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_turna](fdcan_turna) module"] pub type FDCAN_TURNA = crate::Reg<u32, _FDCAN_TURNA>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TURNA; #[doc = "`read()` method returns [fdcan_turna::R](fdcan_turna::R) reader structure"] impl crate::Readable for FDCAN_TURNA {} #[doc = "FDCAN TUR Numerator Actual Register"] pub mod fdcan_turna; #[doc = "FDCAN TT Local and Global Time Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttlgt](fdcan_ttlgt) module"] pub type FDCAN_TTLGT = crate::Reg<u32, _FDCAN_TTLGT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTLGT; #[doc = "`read()` method returns [fdcan_ttlgt::R](fdcan_ttlgt::R) reader structure"] impl crate::Readable for FDCAN_TTLGT {} #[doc = "FDCAN TT Local and Global Time Register"] pub mod fdcan_ttlgt; #[doc = "FDCAN TT Cycle Time and Count Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttctc](fdcan_ttctc) module"] pub type FDCAN_TTCTC = crate::Reg<u32, _FDCAN_TTCTC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTCTC; #[doc = "`read()` method returns [fdcan_ttctc::R](fdcan_ttctc::R) reader structure"] impl crate::Readable for FDCAN_TTCTC {} #[doc = "FDCAN TT Cycle Time and Count Register"] pub mod fdcan_ttctc; #[doc = "FDCAN TT Capture Time Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttcpt](fdcan_ttcpt) module"] pub type FDCAN_TTCPT = crate::Reg<u32, _FDCAN_TTCPT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTCPT; #[doc = "`read()` method returns [fdcan_ttcpt::R](fdcan_ttcpt::R) reader structure"] impl crate::Readable for FDCAN_TTCPT {} #[doc = "FDCAN TT Capture Time Register"] pub mod fdcan_ttcpt; #[doc = "FDCAN TT Cycle Sync Mark Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttcsm](fdcan_ttcsm) module"] pub type FDCAN_TTCSM = crate::Reg<u32, _FDCAN_TTCSM>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTCSM; #[doc = "`read()` method returns [fdcan_ttcsm::R](fdcan_ttcsm::R) reader structure"] impl crate::Readable for FDCAN_TTCSM {} #[doc = "FDCAN TT Cycle Sync Mark Register"] pub mod fdcan_ttcsm; #[doc = "FDCAN TT Trigger Select Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ttts](fdcan_ttts) module"] pub type FDCAN_TTTS = crate::Reg<u32, _FDCAN_TTTS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _FDCAN_TTTS; #[doc = "`read()` method returns [fdcan_ttts::R](fdcan_ttts::R) reader structure"] impl crate::Readable for FDCAN_TTTS {} #[doc = "`write(|w| ..)` method takes [fdcan_ttts::W](fdcan_ttts::W) writer structure"] impl crate::Writable for FDCAN_TTTS {} #[doc = "FDCAN TT Trigger Select Register"] pub mod fdcan_ttts;
use { crate::types::{HitRecord, Ray, Vec3}, rand::Rng, }; pub trait Material: Send + Sync { fn scatter(&self, ray: &Ray, hit_rec: &HitRecord) -> (Vec3, Option<Ray>); } pub struct Lambertian { albedo: Vec3, } impl Lambertian { pub fn new(a: Vec3) -> Self { Self { albedo: a } } } impl Material for Lambertian { fn scatter(&self, _ray: &Ray, hit_rec: &HitRecord) -> (Vec3, Option<Ray>) { let mut rng = rand::thread_rng(); let target = hit_rec.p + hit_rec.normal + random_point_in_unit_sphere(&mut rng); let scattered_ray = Ray::new(hit_rec.p, target - hit_rec.p); (self.albedo, Some(scattered_ray)) } } pub struct Metal { albedo: Vec3, fuzz: f64, } impl Metal { pub fn new(albedo: Vec3) -> Self { Self { albedo, fuzz: 0.0 } } pub fn with_fuzz(albedo: Vec3, fuzz: f64) -> Self { Self { albedo, fuzz } } } impl Material for Metal { fn scatter(&self, ray_in: &Ray, hit_rec: &HitRecord) -> (Vec3, Option<Ray>) { let mut rng = rand::thread_rng(); let reflected_ray = reflect(ray_in.direction().unit_vector(), hit_rec.normal); let scattered_ray = Ray::new( hit_rec.p, reflected_ray + random_point_in_unit_sphere(&mut rng) * self.fuzz, ); if scattered_ray.direction().dot(&hit_rec.normal) > 0.0 { (self.albedo, Some(scattered_ray)) } else { (self.albedo, None) } } } pub struct Dielectric { reflection_index: f64, } impl Dielectric { pub fn new(reflection_index: f64) -> Self { Self { reflection_index } } } impl Material for Dielectric { fn scatter(&self, ray_in: &Ray, hit_rec: &HitRecord) -> (Vec3, Option<Ray>) { let reflected_ray = reflect(ray_in.direction(), hit_rec.normal); // Glass absorbs nothing! So, Attenuation is always going to be 1.0 for this let attenuation = Vec3::new(1.0, 1.0, 1.0); let mut rng = rand::thread_rng(); let (outward_normal, ni_over_nt, cosine) = if ray_in.direction().dot(&hit_rec.normal) > 0.0 { ( -hit_rec.normal, self.reflection_index, (ray_in.direction().dot(&hit_rec.normal) * self.reflection_index) / ray_in.direction().length(), ) } else { ( hit_rec.normal, 1.0 / self.reflection_index, (-ray_in.direction().dot(&hit_rec.normal)) / ray_in.direction().length(), ) }; if let Some(refracted_ray) = refract(ray_in.direction(), outward_normal, ni_over_nt) { let reflect_prob = schlick(cosine, self.reflection_index); if rng.gen::<f64>() < reflect_prob { (attenuation, Some(Ray::new(hit_rec.p, reflected_ray))) } else { (attenuation, Some(Ray::new(hit_rec.p, refracted_ray))) } } else { (attenuation, Some(Ray::new(hit_rec.p, reflected_ray))) } } } // Christophe Schlick's Polynomial approximation to figure out reflectivity as the angle changes // See Fresnel Equations, https://en.wikipedia.org/wiki/Fresnel_equations fn schlick(cosine: f64, reflection_index: f64) -> f64 { let mut r0 = (1.0 - reflection_index) / (1.0 + reflection_index); r0 = r0 * r0; r0 + (1.0 - r0) * (1.0 - cosine).powf(5.0) } fn reflect(incident: Vec3, normal: Vec3) -> Vec3 { incident - normal * incident.dot(&normal) * 2.0 } // Snell's Law fn refract(incident: Vec3, normal: Vec3, ni_over_nt: f64) -> Option<Vec3> { let uv = incident.unit_vector(); let dt = uv.dot(&normal); let discriminant = 1.0 - ni_over_nt * ni_over_nt * (1.0 - dt * dt); if discriminant > 0.0 { Some((uv - normal * dt) * ni_over_nt - normal * discriminant.sqrt()) } else { None } } fn random_point_in_unit_sphere(rng: &mut rand::rngs::ThreadRng) -> Vec3 { let mut point = Vec3::new(rng.gen::<f64>(), rng.gen::<f64>(), rng.gen::<f64>()) * 2.0 - Vec3::new(1.0, 1.0, 1.0); while point.sq_len() >= 1.0 { point = Vec3::new(rng.gen::<f64>(), rng.gen::<f64>(), rng.gen::<f64>()) * 2.0 - Vec3::new(1.0, 1.0, 1.0); } point }
mod common; use std::panic; use std::path::Path; use std::str; use std::str::FromStr as _; use rusty_git::object::{ObjectData, TreeEntry}; use rusty_git::repository::Repository; use self::common::*; #[test] fn reading_head_produces_same_result_as_libgit2() { run_test(|path| { git_init(path).expect("failed to initialize git repository"); let test_file = test_write_file(path, b"Hello world!", "hello_world.txt"); git_add_file(path, test_file.as_path()); git_commit(path, "Initial commit."); let lg2_repo = git2::Repository::open(path).expect("failed to open repository with libgit2"); let lg2_head = lg2_repo .head() .expect("failed to get head from libgit2 repo"); let repo = Repository::open(path).expect("failed to open repository with rusty_git"); let head = repo .reference_database() .head() .expect("failed to get head from rusty_git reference database"); assert_eq!( lg2_head.name().ok_or("libgit2 name was empty").unwrap(), head.name().ok_or("rusty_git name was empty").unwrap() ); }); } #[test] fn reading_refs_produces_same_result_as_libgit2() { run_test(|path| { git_init(path).expect("failed to initialize git repository"); let test_file = test_write_file(path, b"Hello world!", "hello_world.txt"); git_add_file(path, test_file.as_path()); git_commit(path, "Initial commit."); git_branch(path, "test_stuff"); test_write_file(path, b"Hello peeps!", "hello_world.txt"); git_add_file(path, test_file.as_path()); git_commit(path, "Initial commit."); git_tag(path, "v1.0", Some("Version 1.0")); let lg2_repo = git2::Repository::open(path).expect("failed to open repository with libgit2"); let lg2_refs: Vec<(Option<String>, Option<git2::Oid>, Option<git2::Oid>)> = lg2_repo .references() .expect("failed to read references with libgit2") .map(|r| r.unwrap()) .map(|r| (r.name().map(|s| s.to_owned()), r.target_peel(), r.target())) .collect(); let repo = Repository::open(path).expect("failed to open repository with rusty_git"); let names = repo.reference_database().reference_names(); println!("{:?}", lg2_refs); println!("{:?}", names); }); } #[test] fn reading_file_produces_same_result_as_libgit2() { run_test(|path| { git_init(path).expect("failed to initialize git repository"); let test_file = test_write_file(path, b"Hello world!", "hello_world.txt"); git_add_file(path, test_file.as_path()); let cli_objects = git_get_objects(path); let target_object_id = cli_objects[0].to_owned(); let lg2_object = test_libgit2_read_object(path, target_object_id.as_str()); assert_eq!(b"Hello world!", lg2_object.as_slice()); let object = test_rusty_git_read_blob(path, target_object_id.as_str()); assert_eq!(b"Hello world!", object.as_slice()); }); } #[test] fn reading_commit_produces_same_result_as_libgit2() { run_test_in_new_repo(|path| { let target_object_id = String::from_utf8(git_log(path, &["-1", "--format=%H"]).stdout) .expect("failed to parse commit hash as utf8") .trim() .to_owned(); let git_author_name = abuse_git_log_to_get_data(path, "%an"); let git_author_email = abuse_git_log_to_get_data(path, "%ae"); let git_committer_name = abuse_git_log_to_get_data(path, "%cn"); let git_committer_email = abuse_git_log_to_get_data(path, "%ce"); let lg2_repo = git2::Repository::init(path).expect("failed to initialize git repository"); let lg2_object_id = git2::Oid::from_str(target_object_id.as_str()) .expect("failed to read real git id using lg2"); let lg2_commit = lg2_repo .find_commit(lg2_object_id) .expect("failed to read commit using lg2"); assert_eq!(git_author_name, lg2_commit.author().name().unwrap()); assert_eq!(git_author_email, lg2_commit.author().email().unwrap()); assert_eq!(git_committer_name, lg2_commit.committer().name().unwrap()); assert_eq!(git_committer_email, lg2_commit.committer().email().unwrap()); let repo = Repository::open(path).expect("failed to open repository with rusty_git"); let object_id = rusty_git::object::Id::from_str(target_object_id.as_str()) .expect("failed to read object ID using rusty_git"); let commit_object = repo .object_database() .parse_object(object_id) .expect("failed to parse tree object with rusty git"); let commit = match commit_object.data() { ObjectData::Commit(commit) => commit, _ => panic!("expected object to be a commit"), }; assert_eq!(git_author_name, commit.author().name()); assert_eq!(git_author_email, commit.author().email()); assert_eq!(git_committer_name, commit.committer().name()); assert_eq!(git_committer_email, commit.committer().email()); }); } #[test] fn reading_tree_produces_same_result_as_libgit2() { run_test_in_new_repo(|path| { let cli_objects = git_get_objects(path); let lg2_repo = git2::Repository::init(path).expect("failed to initialize git repository"); let lg2_head = lg2_repo.head().unwrap(); let lg2_tree = lg2_head.peel_to_tree().unwrap(); let lg2_tree_id = lg2_tree.id().to_string(); let mut lg2_blob_id = String::new(); lg2_tree .walk(git2::TreeWalkMode::PreOrder, |_, entry| { // There is only one thing in this tree, and we know it's a blob. lg2_blob_id = entry.id().to_string(); git2::TreeWalkResult::Ok }) .unwrap(); assert!(cli_objects.contains(&lg2_tree_id)); assert!(cli_objects.contains(&lg2_blob_id)); let repo = Repository::open(path).expect("failed to open repository with rusty_git"); let target_tree_id = rusty_git::object::Id::from_str(lg2_tree_id.as_str()) .expect("failed to read tree ID using rusty_git"); let tree_object = repo .object_database() .parse_object(target_tree_id) .expect("failed to parse tree object with rusty git"); let tree = match tree_object.data() { ObjectData::Tree(tree) => tree, _ => panic!("expected object to be a tree"), }; let tree_id = tree_object.id().to_string(); let blob_id = tree.entries().collect::<Vec<TreeEntry>>()[0] .id() .to_string(); assert_eq!(lg2_tree_id, tree_id); assert_eq!(lg2_blob_id, blob_id); }); } fn test_rusty_git_read_blob(cwd: &Path, id: &str) -> Vec<u8> { let repo = Repository::open(cwd).expect("failed to open repository with rusty_git"); let object_id = rusty_git::object::Id::from_str(id).expect("failed to read object ID using rusty_git"); let object = repo .object_database() .parse_object(object_id) .expect("failed to get object with rusty_git"); let blob = match object.data() { ObjectData::Blob(blob) => blob, _ => panic!("expected object to be a blob"), }; blob.data().to_vec() } fn test_libgit2_read_object(cwd: &Path, id: &str) -> Vec<u8> { let repo = git2::Repository::init(cwd).expect("failed to initialize git repository"); let odb = repo.odb().expect("failed to open object database"); let object_id = git2::Oid::from_str(id).expect("failed to read real git id using lg2"); let object = odb .read(object_id) .expect("failed to read object using lg2"); object.data().to_vec() }
use projecteuler::{helper, square_roots}; fn main() { helper::check_bench(|| { square_roots::get_approximation(2, 1000); }); //dbg!(find_minimum_solution_in_x_4(&7, &61)); assert_eq!(solve(100, 100), 40886); } fn solve(n: usize, precision: u32) -> usize { return (1..) .map(|x| (x * x, (x + 1) * (x + 1))) .flat_map(|(previous_square, next_square)| (previous_square + 1..next_square)) .take_while(|non_square| *non_square <= n) .map(|n| sum_first_precision_digits(n, precision)) .sum(); } fn sum_first_precision_digits(n: usize, precision: u32) -> usize { square_roots::get_approximation(n, precision) .to_radix_be(10) .iter() .take(precision as usize) .map(|n| *n as usize) .sum::<usize>() }
pub struct Solution; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Tree, pub right: Tree, } use std::cell::RefCell; use std::rc::Rc; type Tree = Option<Rc<RefCell<TreeNode>>>; impl Solution { pub fn has_path_sum(root: Tree, sum: i32) -> bool { match root.as_ref() { None => false, Some(node) => rec(node, sum), } } } fn rec(node: &Rc<RefCell<TreeNode>>, sum: i32) -> bool { let new_sum = sum - node.borrow().val; if node.borrow().left.is_none() && node.borrow().right.is_none() { return new_sum == 0; } if node.borrow().left.is_some() { if rec(node.borrow().left.as_ref().unwrap(), new_sum) { return true; } } if node.borrow().right.is_some() { if rec(node.borrow().right.as_ref().unwrap(), new_sum) { return true; } } false } #[test] fn test0112() { let tree = |left, val, right| Some(Rc::new(RefCell::new(TreeNode { val, left, right }))); assert_eq!( Solution::has_path_sum( tree( tree(tree(tree(None, 7, None), 11, tree(None, 2, None)), 4, None), 5, tree(tree(None, 13, None), 8, tree(None, 4, tree(None, 1, None))) ), 22 ), true ); assert_eq!(Solution::has_path_sum(None, 0), false); }
//! Tests CLI commands use std::fs::read_dir; use std::sync::Arc; use std::time::{Duration, Instant}; use arrow_util::assert_batches_sorted_eq; use assert_cmd::Command; use assert_matches::assert_matches; use futures::FutureExt; use lazy_static::lazy_static; use predicates::prelude::*; use tempfile::tempdir; use test_helpers_end_to_end::{ maybe_skip_integration, AddAddrEnv, BindAddresses, MiniCluster, ServerType, Step, StepTest, StepTestState, TestConfig, }; use super::get_object_store_id; #[tokio::test] async fn default_mode_is_run_all_in_one() { let tmpdir = tempdir().unwrap(); let addrs = BindAddresses::default(); Command::cargo_bin("influxdb_iox") .unwrap() .args(["-v"]) // Do not attempt to connect to the real DB (object store, etc) if the // prod DSN is set - all other tests use TEST_INFLUXDB_IOX_CATALOG_DSN // but this one will use the real env if not cleared. .env_clear() // Without this, we have errors about writing read-only root filesystem on macos. .env("HOME", tmpdir.path()) .add_addr_env(ServerType::AllInOne, &addrs) .timeout(Duration::from_secs(5)) .assert() .failure() .stdout(predicate::str::contains("starting all in one server")); } #[tokio::test] async fn default_run_mode_is_all_in_one() { let tmpdir = tempdir().unwrap(); let addrs = BindAddresses::default(); Command::cargo_bin("influxdb_iox") .unwrap() .args(["run", "-v"]) // This test is designed to assert the default running mode is using // in-memory state, so ensure that any outside config does not influence // this. .env_clear() .env("HOME", tmpdir.path()) .add_addr_env(ServerType::AllInOne, &addrs) .timeout(Duration::from_secs(5)) .assert() .failure() .stdout(predicate::str::contains("starting all in one server")); } #[tokio::test] async fn parquet_to_lp() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); // The test below assumes a specific partition id, so use a // non-shared one here so concurrent tests don't interfere with // each other let mut cluster = MiniCluster::create_non_shared(database_url).await; let line_protocol = "my_awesome_table,tag1=A,tag2=B val=42i 123456"; StepTest::new( &mut cluster, vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol(String::from(line_protocol)), // wait for partitions to be persisted Step::WaitForPersisted { expected_increase: 1, }, // Run the 'remote partition' command Step::Custom(Box::new(move |state: &mut StepTestState| { async move { let router_addr = state.cluster().router().router_grpc_base().to_string(); // Validate the output of the remote partition CLI command // // Looks like: // { // "id": "1", // "namespaceId": 1, // "tableId": 1, // "partitionId": "1", // "objectStoreId": "fa6cdcd1-cbc2-4fb7-8b51-4773079124dd", // "minTime": "123456", // "maxTime": "123456", // "fileSizeBytes": "2029", // "rowCount": "1", // "compactionLevel": "1", // "createdAt": "1650019674289347000" // } let out = Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_addr) .arg("remote") .arg("partition") .arg("show") .arg("1") .assert() .success() .get_output() .stdout .clone(); let object_store_id = get_object_store_id(&out); let dir = tempdir().unwrap(); let f = dir.path().join("tmp.parquet"); let filename = f.as_os_str().to_str().unwrap(); Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_addr) .arg("remote") .arg("store") .arg("get") .arg(&object_store_id) .arg(filename) .assert() .success() .stdout( predicate::str::contains("wrote") .and(predicate::str::contains(filename)), ); // convert to line protocol (stdout) let output = Command::cargo_bin("influxdb_iox") .unwrap() .arg("debug") .arg("parquet-to-lp") .arg(filename) .assert() .success() .stdout(predicate::str::contains(line_protocol)) .get_output() .stdout .clone(); println!("Got output {output:?}"); // test writing to output file as well // Ensure files are actually wrote to the filesystem let output_file = tempfile::NamedTempFile::new().expect("Error making temp file"); println!("Writing to {output_file:?}"); // convert to line protocol (to a file) Command::cargo_bin("influxdb_iox") .unwrap() .arg("debug") .arg("parquet-to-lp") .arg(filename) .arg("--output") .arg(output_file.path()) .assert() .success(); let file_contents = std::fs::read(output_file.path()).expect("can not read data from tempfile"); let file_contents = String::from_utf8_lossy(&file_contents); assert!( predicate::str::contains(line_protocol).eval(&file_contents), "Could not file {line_protocol} in {file_contents}" ); } .boxed() })), ], ) .run() .await } /// Test the schema cli command #[tokio::test] async fn schema_cli() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol(String::from( "my_awesome_table2,tag1=A,tag2=B val=42i 123456", )), Step::WaitForPersisted { expected_increase: 1, }, Step::Custom(Box::new(|state: &mut StepTestState| { async { // should be able to query both router and querier for the schema let addrs = vec![ ( "router", state.cluster().router().router_grpc_base().to_string(), ), ( "querier", state.cluster().querier().querier_grpc_base().to_string(), ), ]; for (addr_type, addr) in addrs { println!("Trying address {addr_type}: {addr}"); // Validate the output of the schema CLI command Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("debug") .arg("schema") .arg("get") .arg(state.cluster().namespace()) .assert() .success() .stdout( predicate::str::contains("my_awesome_table2") .and(predicate::str::contains("tag1")) .and(predicate::str::contains("val")), ); } } .boxed() })), ], ) .run() .await } /// Test write CLI command and query CLI command #[tokio::test] async fn write_and_query() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ Step::Custom(Box::new(|state: &mut StepTestState| { async { let router_addr = state.cluster().router().router_http_base().to_string(); let namespace = state.cluster().namespace(); println!("Writing into {namespace}"); // Validate the output of the schema CLI command Command::cargo_bin("influxdb_iox") .unwrap() .arg("-v") .arg("-h") .arg(&router_addr) .arg("write") .arg(namespace) // raw line protocol ('h2o_temperature' measurement) .arg("../test_fixtures/lineproto/air_and_water.lp") // gzipped line protocol ('m0') .arg("../test_fixtures/lineproto/read_filter.lp.gz") // iox formatted parquet ('cpu' measurement) .arg("../test_fixtures/cpu.parquet") .assert() .success() // this number is the total size of // uncompressed line protocol stored in all // three files .stdout(predicate::str::contains("889317 Bytes OK")); } .boxed() })), Step::Custom(Box::new(|state: &mut StepTestState| { async { // data from 'air_and_water.lp' wait_for_query_result( state, "SELECT * from h2o_temperature order by time desc limit 10", None, "| 51.3 | coyote_creek | CA | 55.1 | 1970-01-01T00:00:01.568756160Z |" ).await; // data from 'read_filter.lp.gz', specific query language type wait_for_query_result( state, "SELECT * from m0 order by time desc limit 10;", Some(QueryLanguage::Sql), "| value1 | value9 | value9 | value49 | value0 | 2021-04-26T13:47:39.727574Z | 1.0 |" ).await; // data from 'cpu.parquet' wait_for_query_result( state, "SELECT * from cpu where cpu = 'cpu2' order by time desc limit 10", None, "cpu2 | MacBook-Pro-8.hsd1.ma.comcast.net | 2022-09-30T12:55:00Z" ).await; } .boxed() })), ], ) .run() .await } // Negative tests for create table CLI command #[tokio::test] async fn create_tables_negative() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ Step::Custom(Box::new(|state: &mut StepTestState| { async { // Need router grpc based address to create namespace let router_grpc_addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns_tablenegative"; println!("Create namespace {namespace}"); Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_grpc_addr) .arg("namespace") .arg("create") .arg(namespace) .assert() .success() .stdout(predicate::str::contains(namespace)); } .boxed() })), Step::Custom(Box::new(|state: &mut StepTestState| { async { // Need router grpc based address to create tables let router_grpc_addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns_tablenegative"; // no partition tempplate specified Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("create") .arg(namespace) .arg("h2o_temperature") .arg("--partition-template") .assert() .failure() .stderr(predicate::str::contains( "error: a value is required for '--partition-template <PARTITION_TEMPLATE>' but none was supplied", )); // Wrong spelling `prts` Command::cargo_bin("influxdb_iox") .unwrap() // .arg("-v") .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("create") .arg(namespace) .arg("h2o_temperature") .arg("--partition-template") .arg("{\"prts\": [{\"tagValue\": \"location\"}, {\"tagValue\": \"state\"}, {\"timeFormat\": \"%Y-%m\"}] }") .assert() .failure() .stderr(predicate::str::contains( "Client Error: Invalid partition template format : unknown field `prts`", )); // Time as tag Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("create") .arg(namespace) .arg("h2o_temperature") .arg("--partition-template") .arg("{\"parts\": [{\"tagValue\": \"location\"}, {\"tagValue\": \"time\"}, {\"timeFormat\": \"%Y-%m\"}] }") .assert() .failure() .stderr(predicate::str::contains( "Client error: Client specified an invalid argument: invalid tag value in partition template: time cannot be used", )); // Time format is `%42` which is invalid Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("create") .arg(namespace) .arg("h2o_temperature") .arg("--partition-template") .arg("{\"parts\": [{\"tagValue\": \"location\"}, {\"timeFormat\": \"%42\"}] }") .assert() .failure() .stderr(predicate::str::contains( "Client error: Client specified an invalid argument: invalid strftime format in partition template", )); // Over 8 parts Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("create") .arg(namespace) .arg("h2o_temperature") .arg("--partition-template") .arg("{\"parts\": [{\"tagValue\": \"1\"},{\"tagValue\": \"2\"},{\"timeFormat\": \"%Y-%m\"},{\"tagValue\": \"4\"},{\"tagValue\": \"5\"},{\"tagValue\": \"6\"},{\"tagValue\": \"7\"},{\"tagValue\": \"8\"},{\"tagValue\": \"9\"}]}") .assert() .failure() .stderr(predicate::str::contains( "Partition templates may have a maximum of 8 parts", )); // Update an existing table Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("update") .arg(namespace) .arg("h2o_temperature") .arg("--partition-template") .arg("{\"parts\":[{\"tagValue\":\"col1\"}] }") .assert() .failure() .stderr(predicate::str::contains( "error: unrecognized subcommand 'update'", )); } .boxed() })), ]) .run() .await } // Positive tests for create table CLI command #[tokio::test] async fn create_tables_positive() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ Step::Custom(Box::new(|state: &mut StepTestState| { async { // Need router grpc based addres to create namespace let router_grpc_addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns_tablepositive"; println!("Create namespace {namespace}"); Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_grpc_addr) .arg("namespace") .arg("create") .arg(namespace) .assert() .success() .stdout(predicate::str::contains(namespace)); } .boxed() })), Step::Custom(Box::new(|state: &mut StepTestState| { async { // Need router grpc based addres to create tables let router_grpc_addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns_tablepositive"; println!("Creating tables h2o_temperature, m0, cpu explicitly into {namespace}"); // no partition template specified Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("create") .arg(namespace) .arg("t1") .assert() .success() .stdout(predicate::str::contains("t1")); // Partition template with time format Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("create") .arg(namespace) .arg("t2") .arg("--partition-template") .arg("{\"parts\":[{\"timeFormat\":\"%Y-%m\"}] }") .assert() .success() .stdout(predicate::str::contains("t2")); // Partition template with tag Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("create") .arg(namespace) .arg("t3") .arg("--partition-template") .arg("{\"parts\":[{\"tagValue\":\"col1\"}] }") .assert() .success() .stdout(predicate::str::contains("t3")); // Partition template with time format, tag value, and tag of unsual column name Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("create") .arg(namespace) .arg("t4") .arg("--partition-template") .arg("{\"parts\":[{\"tagValue\":\"col1\"},{\"timeFormat\":\"%Y-%d\"},{\"tagValue\":\"yes,col name\"}] }") .assert() .success() .stdout(predicate::str::contains("t4")); } .boxed() })), ]) .run() .await } // Positive tests: create table, write data and read back #[tokio::test] async fn create_tables_write_and_query() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; let namespace = "ns_createtables"; StepTest::new( &mut cluster, vec![ // Create name space Step::Custom(Box::new(|state: &mut StepTestState| { async { // Need router grpc based addres to create namespace let router_grpc_addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns_createtables"; println!("Create namespace {namespace}"); Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&router_grpc_addr) .arg("namespace") .arg("create") .arg(namespace) .assert() .success() .stdout(predicate::str::contains(namespace)); } .boxed() })), // Create tables Step::Custom(Box::new(|state: &mut StepTestState| { async { // Need router grpc based addres to create tables let router_grpc_addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns_createtables"; println!("Creating tables h2o_temperature, m0, cpu explicitly into {namespace}"); // create tables h2o_temperature, m0, cpu Command::cargo_bin("influxdb_iox") .unwrap() .arg("-v") .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("create") .arg(namespace) .arg("h2o_temperature") .arg("--partition-template") .arg("{\"parts\": [{\"tagValue\": \"location\"}, {\"tagValue\": \"state\"}, {\"timeFormat\": \"%Y-%m\"}] }") .assert() .success() .stdout(predicate::str::contains("h2o_temperature")); Command::cargo_bin("influxdb_iox") .unwrap() .arg("-v") .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("create") .arg(namespace) .arg("m0") .arg("--partition-template") .arg("{\"parts\": [{\"timeFormat\": \"%Y.%j\"}] }") .assert() .success() .stdout(predicate::str::contains("m0")); Command::cargo_bin("influxdb_iox") .unwrap() .arg("-v") .arg("-h") .arg(&router_grpc_addr) .arg("table") .arg("create") .arg(namespace) .arg("cpu") .arg("--partition-template") .arg("{\"parts\": [{\"timeFormat\": \"%Y-%m-%d\"}, {\"tagValue\": \"cpu\"}] }") .assert() .success() .stdout(predicate::str::contains("cpu")); } .boxed() })), // Load data Step::Custom(Box::new(|state: &mut StepTestState| { async { // write must use router http based address let router_http_addr = state.cluster().router().router_http_base().to_string(); let namespace = "ns_createtables"; println!("Writing into {namespace}"); // Validate the output of the schema CLI command Command::cargo_bin("influxdb_iox") .unwrap() .arg("-v") .arg("-h") .arg(&router_http_addr) .arg("write") .arg(namespace) // raw line protocol ('h2o_temperature' measurement) .arg("../test_fixtures/lineproto/air_and_water.lp") // gzipped line protocol ('m0') .arg("../test_fixtures/lineproto/read_filter.lp.gz") // iox formatted parquet ('cpu' measurement) .arg("../test_fixtures/cpu.parquet") .assert() .success() // this number is the total size of // uncompressed line protocol stored in all // three files .stdout(predicate::str::contains("889317 Bytes OK")); } .boxed() })), // Read back data Step::Custom(Box::new(|state: &mut StepTestState| { async { // data from 'air_and_water.lp' wait_for_query_result_with_namespace( namespace, state, "SELECT * from h2o_temperature order by time desc limit 10", None, "| 51.3 | coyote_creek | CA | 55.1 | 1970-01-01T00:00:01.568756160Z |" ).await; // data from 'read_filter.lp.gz', specific query language type wait_for_query_result_with_namespace( namespace, state, "SELECT * from m0 order by time desc limit 10;", Some(QueryLanguage::Sql), "| value1 | value9 | value9 | value49 | value0 | 2021-04-26T13:47:39.727574Z | 1.0 |" ).await; // data from 'cpu.parquet' wait_for_query_result_with_namespace( namespace, state, "SELECT * from cpu where cpu = 'cpu2' order by time desc limit 10", None, "cpu2 | MacBook-Pro-8.hsd1.ma.comcast.net | 2022-09-30T12:55:00Z" ).await; } .boxed() })), // Check partition keys Step::PartitionKeys{table_name: "h2o_temperature".to_string(), namespace_name: Some(namespace.to_string()), expected: vec!["coyote_creek|CA|1970-01", "puget_sound|WA|1970-01", "santa_monica|CA|1970-01"]}, Step::PartitionKeys{table_name: "m0".to_string(), namespace_name: Some(namespace.to_string()), expected: vec!["2021.116"]}, Step::PartitionKeys{table_name: "cpu".to_string(), namespace_name: Some(namespace.to_string()), expected: vec!["2022-09-30|cpu2"]}, ], ) .run() .await } /// Test error handling for the query CLI command #[tokio::test] async fn query_error_handling() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ Step::WriteLineProtocol("this_table_does_exist,tag=A val=\"foo\" 1".into()), Step::Custom(Box::new(|state: &mut StepTestState| { async { let querier_addr = state.cluster().querier().querier_grpc_base().to_string(); let namespace = state.cluster().namespace(); Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&querier_addr) .arg("query") .arg(namespace) .arg("drop table this_table_doesnt_exist") .assert() .failure() .stderr(predicate::str::contains( "Error while planning query: \ This feature is not implemented: \ Unsupported logical plan: DropTable", )); } .boxed() })), ], ) .run() .await } /// Test error handling for the query CLI command for InfluxQL queries #[tokio::test] async fn influxql_error_handling() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ Step::WriteLineProtocol("this_table_does_exist,tag=A val=\"foo\" 1".into()), Step::Custom(Box::new(|state: &mut StepTestState| { async { let querier_addr = state.cluster().querier().querier_grpc_base().to_string(); let namespace = state.cluster().namespace(); Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&querier_addr) .arg("query") .arg("--lang") .arg("influxql") .arg(namespace) .arg("CREATE DATABASE foo") .assert() .failure() .stderr(predicate::str::contains( "Error while planning query: This feature is not implemented: CREATE DATABASE", )); } .boxed() })), ], ) .run() .await } #[allow(dead_code)] #[derive(Clone, Copy)] enum QueryLanguage { Sql, InfluxQL, } impl ToString for QueryLanguage { fn to_string(&self) -> String { match self { Self::Sql => "sql".to_string(), Self::InfluxQL => "influxql".to_string(), } } } trait AddQueryLanguage { /// Add the query language option to the receiver. fn add_query_lang(&mut self, query_lang: Option<QueryLanguage>) -> &mut Self; } impl AddQueryLanguage for assert_cmd::Command { fn add_query_lang(&mut self, query_lang: Option<QueryLanguage>) -> &mut Self { match query_lang { Some(lang) => self.arg("--lang").arg(lang.to_string()), None => self, } } } async fn wait_for_query_result( state: &mut StepTestState<'_>, query_sql: &str, query_lang: Option<QueryLanguage>, expected: &str, ) { let namespace = state.cluster().namespace().to_owned(); wait_for_query_result_with_namespace(namespace.as_str(), state, query_sql, query_lang, expected) .await } /// Runs the specified query in a loop for up to 10 seconds, waiting /// for the specified output to appear async fn wait_for_query_result_with_namespace( namespace: &str, state: &mut StepTestState<'_>, query_sql: &str, query_lang: Option<QueryLanguage>, expected: &str, ) { let querier_addr = state.cluster().querier().querier_grpc_base().to_string(); let max_wait_time = Duration::from_secs(10); println!("Waiting for {expected}"); // Validate the output of running the query CLI command appears after at most max_wait_time let end = Instant::now() + max_wait_time; while Instant::now() < end { let assert = Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&querier_addr) .arg("query") .add_query_lang(query_lang) .arg(namespace) .arg(query_sql) .assert(); let assert = match assert.try_success() { Err(e) => { println!("Got err running command: {e}, retrying"); continue; } Ok(a) => a, }; match assert.try_stdout(predicate::str::contains(expected)) { Err(e) => { println!("No match: {e}, retrying"); } Ok(r) => { println!("Success: {r:?}"); return; } } // sleep and try again tokio::time::sleep(Duration::from_secs(1)).await } panic!("Did not find expected output {expected} within {max_wait_time:?}"); } /// Test the namespace cli command #[tokio::test] async fn namespaces_cli() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ Step::WriteLineProtocol(String::from( "my_awesome_table2,tag1=A,tag2=B val=42i 123456", )), Step::Custom(Box::new(|state: &mut StepTestState| { async { let querier_addr = state.cluster().querier().querier_grpc_base().to_string(); // Validate the output of the schema CLI command Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&querier_addr) .arg("namespace") .arg("list") .assert() .success() .stdout(predicate::str::contains(state.cluster().namespace())); } .boxed() })), ], ) .run() .await } /// Test the namespace retention command #[tokio::test] async fn namespace_retention() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ Step::WriteLineProtocol(String::from( "my_awesome_table2,tag1=A,tag2=B val=42i 123456", )), // Set the retention period to 2 hours Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = state.cluster().namespace(); let retention_period_hours = 2; let retention_period_ns = retention_period_hours as i64 * 60 * 60 * 1_000_000_000; // Validate the output of the namespace retention command // // { // "id": "1", // "name": "0911430016317810_8303971312605107", // "retentionPeriodNs": "7200000000000" // } Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("retention") .arg("--retention-hours") .arg(retention_period_hours.to_string()) .arg(namespace) .assert() .success() .stdout( predicate::str::contains(namespace) .and(predicate::str::contains(retention_period_ns.to_string())), ); } .boxed() })), // set the retention period to null Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = state.cluster().namespace(); let retention_period_hours = 0; // will be updated to null // Validate the output of the namespace retention command // // { // "id": "1", // "name": "6699752880299094_1206270074309156" // } Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("retention") .arg("--retention-hours") .arg(retention_period_hours.to_string()) .arg(namespace) .assert() .success() .stdout( predicate::str::contains(namespace) .and(predicate::str::contains("retentionPeriodNs".to_string())) .not(), ); } .boxed() })), // create a new namespace and set the retention period to 2 hours Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "namespace_2"; let retention_period_hours = 2; let retention_period_ns = retention_period_hours as i64 * 60 * 60 * 1_000_000_000; // Validate the output of the namespace retention command // // { // "id": "1", // "name": "namespace_2", // "retentionPeriodNs": "7200000000000" // } Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg("--retention-hours") .arg(retention_period_hours.to_string()) .arg(namespace) .assert() .success() .stdout( predicate::str::contains(namespace) .and(predicate::str::contains(retention_period_ns.to_string())), ); } .boxed() })), // create a namespace without retention. 0 represeting null/infinite will be used Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "namespace_3"; // Validate the output of the namespace retention command // // { // "id": "1", // "name": "namespace_3", // } Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .assert() .success() .stdout( predicate::str::contains(namespace) .and(predicate::str::contains("retentionPeriodNs".to_string())) .not(), ); } .boxed() })), // create a namespace retention 0 represeting null/infinite will be used Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "namespace_4"; let retention_period_hours = 0; // Validate the output of the namespace retention command // // { // "id": "1", // "name": "namespace_4", // } Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg("--retention-hours") .arg(retention_period_hours.to_string()) .arg(namespace) .assert() .success() .stdout( predicate::str::contains(namespace) .and(predicate::str::contains("retentionPeriodNs".to_string())) .not(), ); } .boxed() })), ], ) .run() .await } /// Test the namespace deletion command #[tokio::test] async fn namespace_deletion() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ // create a new namespace without retention policy Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let retention_period_hours = 0; let namespace = "bananas_namespace"; // Validate the output of the namespace retention command // // { // "id": "1", // "name": "bananas_namespace", // } Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg("--retention-hours") .arg(retention_period_hours.to_string()) .arg(namespace) .assert() .success() .stdout( predicate::str::contains(namespace) .and(predicate::str::contains("retentionPeriodNs".to_string())) .not(), ); } .boxed() })), // delete the newly created namespace Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "bananas_namespace"; Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("delete") .arg(namespace) .assert() .success() .stdout( predicate::str::contains("Deleted namespace") .and(predicate::str::contains(namespace)), ); } .boxed() })), Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "bananas_namespace"; Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("list") .assert() .success() .stdout(predicate::str::contains(namespace).not()); } .boxed() })), ], ) .run() .await } /// Test the query_ingester CLI command #[tokio::test] async fn query_ingester() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared_never_persist(database_url).await; StepTest::new( &mut cluster, vec![ Step::WriteLineProtocol(String::from( "my_awesome_table2,tag1=A,tag2=B val=42i 123456", )), Step::Custom(Box::new(|state: &mut StepTestState| { async { let ingester_addr = state.cluster().ingester().ingester_grpc_base().to_string(); let expected = [ "+------+------+--------------------------------+-----+", "| tag1 | tag2 | time | val |", "+------+------+--------------------------------+-----+", "| A | B | 1970-01-01T00:00:00.000123456Z | 42 |", "+------+------+--------------------------------+-----+", ] .join("\n"); // Validate the output of the query Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&ingester_addr) .arg("query-ingester") .arg(state.cluster().namespace_id().await.get().to_string()) .arg( state .cluster() .table_id("my_awesome_table2") .await .get() .to_string(), ) .assert() .success() .stdout(predicate::str::contains(&expected)); } .boxed() })), Step::Custom(Box::new(|state: &mut StepTestState| { async { // now run the query-ingester command against the querier let querier_addr = state.cluster().querier().querier_grpc_base().to_string(); // this is not a good error: it should be // something like "wrong query protocol" or // "invalid message" as the querier requires a // different message format Ticket in the flight protocol let expected = "Database '' not found"; // Validate that the error message contains a reasonable error Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&querier_addr) .arg("query-ingester") .arg(state.cluster().namespace_id().await.get().to_string()) .arg( state .cluster() .table_id("my_awesome_table2") .await .get() .to_string(), ) .assert() .failure() .stderr(predicate::str::contains(expected)); } .boxed() })), Step::Custom(Box::new(|state: &mut StepTestState| { async { let ingester_addr = state.cluster().ingester().ingester_grpc_base().to_string(); let expected = [ "+------+-----+", "| tag1 | val |", "+------+-----+", "| A | 42 |", "+------+-----+", ] .join("\n"); // Validate the output of the query Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&ingester_addr) .arg("query-ingester") .arg(state.cluster().namespace_id().await.get().to_string()) .arg( state .cluster() .table_id("my_awesome_table2") .await .get() .to_string(), ) .arg("--columns") .arg("tag1,val") .assert() .success() .stdout(predicate::str::contains(&expected)); } .boxed() })), ], ) .run() .await } /// Test setting service limits while creating namespaces #[tokio::test] async fn namespace_create_service_limits() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns1"; // { // "id": <foo>, // "name": "ns1", // "serviceProtectionLimits": { // "maxTables": 123, // "maxColumnsPerTable": 200 // } // } Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .arg("--max-tables") .arg("123") .assert() .success() .stdout( predicate::str::contains(namespace) .and(predicate::str::contains(r#""maxTables": 123"#)) .and(predicate::str::contains(r#""maxColumnsPerTable": 200"#)), ); } .boxed() })), Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns2"; // { // "id": <foo>, // "name": "ns2", // "serviceProtectionLimits": { // "maxTables": 500, // "maxColumnsPerTable": 321 // } // } Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .arg("--max-columns-per-table") .arg("321") .assert() .success() .stdout( predicate::str::contains(namespace) .and(predicate::str::contains(r#""maxTables": 500"#)) .and(predicate::str::contains(r#""maxColumnsPerTable": 321"#)), ); } .boxed() })), Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns3"; // { // "id": <foo>, // "name": "ns3", // "serviceProtectionLimits": { // "maxTables": 123, // "maxColumnsPerTable": 321 // } // } Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .arg("--max-tables") .arg("123") .arg("--max-columns-per-table") .arg("321") .assert() .success() .stdout( predicate::str::contains(namespace) .and(predicate::str::contains(r#""maxTables": 123"#)) .and(predicate::str::contains(r#""maxColumnsPerTable": 321"#)), ); } .boxed() })), ], ) .run() .await } /// Test setting partition template while creating namespaces, negative tests #[tokio::test] async fn namespace_create_partition_template_negative() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns_negative"; // No partition tempplate specified Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .arg("--partition-template") .assert() .failure() .stderr( predicate::str::contains( "error: a value is required for '--partition-template <PARTITION_TEMPLATE>' but none was supplied" ) ); // Wrong spelling `prts` Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .arg("--partition-template") .arg("{\"prts\": [{\"tagValue\": \"location\"}, {\"tagValue\": \"state\"}, {\"timeFormat\": \"%Y-%m\"}] }") .assert() .failure() .stderr(predicate::str::contains( "Client Error: Invalid partition template format : unknown field `prts`", )); // Time as tag Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .arg("--partition-template") .arg("{\"parts\": [{\"tagValue\": \"location\"}, {\"tagValue\": \"time\"}, {\"timeFormat\": \"%Y-%m\"}] }") .assert() .failure() .stderr(predicate::str::contains( "Client error: Client specified an invalid argument: invalid tag value in partition template: time cannot be used", )); // Time format is `%42` which is invalid Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .arg("--partition-template") .arg("{\"parts\": [{\"tagValue\": \"location\"}, {\"timeFormat\": \"%42\"}] }") .assert() .failure() .stderr(predicate::str::contains( "Client error: Client specified an invalid argument: invalid strftime format in partition template", )); // Over 8 parts Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .arg("--partition-template") .arg("{\"parts\": [{\"tagValue\": \"1\"},{\"tagValue\": \"2\"},{\"timeFormat\": \"%Y-%m\"},{\"tagValue\": \"4\"},{\"tagValue\": \"5\"},{\"tagValue\": \"6\"},{\"tagValue\": \"7\"},{\"tagValue\": \"8\"},{\"tagValue\": \"9\"}]}") .assert() .failure() .stderr(predicate::str::contains( "Partition templates may have a maximum of 8 parts", )); } .boxed() })) ], ) .run() .await } /// Test setting partition template while creating namespaces, positive tests #[tokio::test] async fn namespace_create_partition_template_positive() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); // No partition template specified Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg("ns_partition_template_1") .assert() .success() .stdout(predicate::str::contains("ns_partition_template_1")); // Partition template with time format Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg("ns_partition_template_2") .arg("--partition-template") .arg("{\"parts\":[{\"timeFormat\":\"%Y-%m\"}] }") .assert() .success() .stdout(predicate::str::contains("ns_partition_template_2")); // Partition template with tag value Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg("ns_partition_template_3") .arg("--partition-template") .arg("{\"parts\":[{\"tagValue\":\"col1\"}] }") .assert() .success() .stdout(predicate::str::contains("ns_partition_template_3")); // Partition template with time format, tag value, and tag of unsual column name Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg("ns_partition_template_4") .arg("--partition-template") .arg("{\"parts\":[{\"tagValue\":\"col1\"},{\"timeFormat\":\"%Y-%d\"},{\"tagValue\":\"yes,col name\"}] }") .assert() .success() .stdout(predicate::str::contains("ns_partition_template_4")); // Update an existing namespace Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("update") .arg("ns_partition_template_4") .arg("--partition-template") .arg("{\"parts\":[{\"tagValue\":\"col1\"}] }") .assert() .failure() .stderr(predicate::str::contains( "error: unrecognized subcommand 'update'", )); } .boxed() })), ], ) .run() .await } /// Test partition template for namespace and table creation: /// When a namespace is created *with* a custom partition template /// and a table is created implicitly, i.e. *without* a partition template, /// the namespace's partition template will be applied to this table #[tokio::test] async fn namespace_create_partition_template_implicit_table_creation() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; let namespace = "ns_createtableimplicit"; StepTest::new( &mut cluster, vec![ // Explicitly create a namespace with a custom partition template Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns_createtableimplicit"; Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .arg("--partition-template") .arg( "{\"parts\":[{\"timeFormat\":\"%Y-%m\"}, {\"tagValue\":\"location\"}]}", ) .assert() .success() .stdout(predicate::str::contains(namespace)); } .boxed() })), // Write, which implicitly creates the table with the namespace's custom partition template Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_http_base().to_string(); let namespace = "ns_createtableimplicit"; Command::cargo_bin("influxdb_iox") .unwrap() .arg("-v") .arg("-h") .arg(&addr) .arg("write") .arg(namespace) .arg("../test_fixtures/lineproto/temperature.lp") .assert() .success() .stdout(predicate::str::contains("591 Bytes OK")); } .boxed() })), // Read data Step::Custom(Box::new(|state: &mut StepTestState| { async { // data from 'air_and_water.lp' wait_for_query_result_with_namespace( namespace, state, "SELECT * from h2o_temperature order by time desc limit 10", None, "| 51.3 | coyote_creek | CA | 55.1 | 1970-01-01T00:00:01.568756160Z |" ).await; } .boxed() })), // Check partition keys that use the namespace's partition template Step::PartitionKeys { table_name: "h2o_temperature".to_string(), namespace_name: Some(namespace.to_string()), expected: vec![ "1970-01|coyote_creek", "1970-01|puget_sound", "1970-01|santa_monica", ], }, ], ) .run() .await } /// Test partition template for namespace and table creation: /// When a namespace is created *with* a custom partition template /// and a table is created *without* a partition template, /// the namespace's partition template will be applied to this table #[tokio::test] async fn namespace_create_partition_template_explicit_table_creation_without_partition_template() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; let namespace = "ns_createtableexplicitwithout"; StepTest::new( &mut cluster, vec![ // Explicitly create a namespace with a custom partition template Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns_createtableexplicitwithout"; Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .arg("--partition-template") .arg("{\"parts\":[{\"timeFormat\":\"%Y-%m\"}, {\"tagValue\":\"state\"}]}") .assert() .success() .stdout(predicate::str::contains(namespace)); } .boxed() })), // Explicitly create a table *without* a custom partition template Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns_createtableexplicitwithout"; let table_name = "h2o_temperature"; Command::cargo_bin("influxdb_iox") .unwrap() .arg("-v") .arg("-h") .arg(&addr) .arg("table") .arg("create") .arg(namespace) .arg(table_name) .assert() .success() .stdout(predicate::str::contains(table_name)); } .boxed() })), // Write to the just-created table Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_http_base().to_string(); let namespace = "ns_createtableexplicitwithout"; Command::cargo_bin("influxdb_iox") .unwrap() .arg("-v") .arg("-h") .arg(&addr) .arg("write") .arg(namespace) .arg("../test_fixtures/lineproto/temperature.lp") .assert() .success() .stdout(predicate::str::contains("591 Bytes OK")); } .boxed() })), // Read data Step::Custom(Box::new(|state: &mut StepTestState| { async { // data from 'air_and_water.lp' wait_for_query_result_with_namespace( namespace, state, "SELECT * from h2o_temperature order by time desc limit 10", None, "| 51.3 | coyote_creek | CA | 55.1 | 1970-01-01T00:00:01.568756160Z |" ).await; } .boxed() })), // Check partition keys that use the namespace's partition template Step::PartitionKeys{table_name: "h2o_temperature".to_string(), namespace_name: Some(namespace.to_string()), expected: vec!["1970-01|CA", "1970-01|WA"]}, ], ) .run() .await } /// Test partition template for namespace and table creation: /// When a namespace is created *with* a custom partition template /// and a table is created *with* a partition template, /// the table's partition template will be applied to this table #[tokio::test] async fn namespace_create_partition_template_explicit_table_creation_with_partition_template() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; let namespace = "ns_createtableexplicitwith"; StepTest::new( &mut cluster, vec![ // Explicitly create a namespace with a custom partition template Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns_createtableexplicitwith"; Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .arg("--partition-template") .arg("{\"parts\":[{\"timeFormat\":\"%Y-%m\"}, {\"tagValue\":\"state\"}]}") .assert() .success() .stdout(predicate::str::contains(namespace)); } .boxed() })), // Explicitly create a table *with* a custom partition template Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_grpc_base().to_string(); let namespace = "ns_createtableexplicitwith"; let table_name = "h2o_temperature"; Command::cargo_bin("influxdb_iox") .unwrap() .arg("-v") .arg("-h") .arg(&addr) .arg("table") .arg("create") .arg(namespace) .arg(table_name) .arg("--partition-template") .arg("{\"parts\":[{\"tagValue\":\"location\"}, {\"timeFormat\":\"%Y-%m\"}]}") .assert() .success() .stdout(predicate::str::contains(table_name)); } .boxed() })), // Write to the just-created table Step::Custom(Box::new(|state: &mut StepTestState| { async { let addr = state.cluster().router().router_http_base().to_string(); let namespace = "ns_createtableexplicitwith"; Command::cargo_bin("influxdb_iox") .unwrap() .arg("-v") .arg("-h") .arg(&addr) .arg("write") .arg(namespace) .arg("../test_fixtures/lineproto/temperature.lp") .assert() .success() .stdout(predicate::str::contains("591 Bytes OK")); } .boxed() })), // Read data Step::Custom(Box::new(|state: &mut StepTestState| { async { // data from 'air_and_water.lp' wait_for_query_result_with_namespace( namespace, state, "SELECT * from h2o_temperature order by time desc limit 10", None, "| 51.3 | coyote_creek | CA | 55.1 | 1970-01-01T00:00:01.568756160Z |" ).await; } .boxed() })), // Check partition keys that use the table's partition template Step::PartitionKeys{table_name: "h2o_temperature".to_string(), namespace_name: Some(namespace.to_string()), expected: vec!["coyote_creek|1970-01", "puget_sound|1970-01", "santa_monica|1970-01"]}, ], ) .run() .await } /// Test the namespace update service limit command #[tokio::test] async fn namespace_update_service_limit() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let mut cluster = MiniCluster::create_shared(database_url).await; StepTest::new( &mut cluster, vec![ Step::Custom(Box::new(|state: &mut StepTestState| { async { let namespace = "service_limiter_namespace"; let addr = state.cluster().router().router_grpc_base().to_string(); // { // "id": <foo>, // "name": "service_limiter_namespace", // "serviceProtectionLimits": { // "maxTables": 500, // "maxColumnsPerTable": 200 // } // } Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("create") .arg(namespace) .assert() .success() .stdout( predicate::str::contains(namespace) .and(predicate::str::contains(r#""maxTables": 500"#)) .and(predicate::str::contains(r#""maxColumnsPerTable": 200"#)), ); } .boxed() })), Step::Custom(Box::new(|state: &mut StepTestState| { async { let namespace = "service_limiter_namespace"; let addr = state.cluster().router().router_grpc_base().to_string(); // { // "id": <foo>, // "name": "service_limiter_namespace", // "serviceProtectionLimits": { // "maxTables": 1337, // "maxColumnsPerTable": 200 // } // } Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("update-limit") .arg("--max-tables") .arg("1337") .arg(namespace) .assert() .success() .stdout( predicate::str::contains(namespace) .and(predicate::str::contains(r#""maxTables": 1337"#)) .and(predicate::str::contains(r#""maxColumnsPerTable": 200"#)), ); } .boxed() })), Step::Custom(Box::new(|state: &mut StepTestState| { async { let namespace = "service_limiter_namespace"; let addr = state.cluster().router().router_grpc_base().to_string(); // { // "id": <foo>, // "name": "service_limiter_namespace", // "serviceProtectionLimits": { // "maxTables": 1337, // "maxColumnsPerTable": 42 // } // } Command::cargo_bin("influxdb_iox") .unwrap() .arg("-h") .arg(&addr) .arg("namespace") .arg("update-limit") .arg("--max-columns-per-table") .arg("42") .arg(namespace) .assert() .success() .stdout( predicate::str::contains(namespace) .and(predicate::str::contains(r#""maxTables": 1337"#)) .and(predicate::str::contains(r#""maxColumnsPerTable": 42"#)), ); } .boxed() })), ], ) .run() .await } lazy_static! { static ref TEMPERATURE_RESULTS: Vec<&'static str> = vec![ "+----------------+--------------+-------+-----------------+--------------------------------+", "| bottom_degrees | location | state | surface_degrees | time |", "+----------------+--------------+-------+-----------------+--------------------------------+", "| 50.4 | santa_monica | CA | 65.2 | 1970-01-01T00:00:01.568756160Z |", "| 49.2 | santa_monica | CA | 63.6 | 1970-01-01T00:00:01.600756160Z |", "| 51.3 | coyote_creek | CA | 55.1 | 1970-01-01T00:00:01.568756160Z |", "| 50.9 | coyote_creek | CA | 50.2 | 1970-01-01T00:00:01.600756160Z |", "| 40.2 | puget_sound | WA | 55.8 | 1970-01-01T00:00:01.568756160Z |", "| 40.1 | puget_sound | WA | 54.7 | 1970-01-01T00:00:01.600756160Z |", "+----------------+--------------+-------+-----------------+--------------------------------+", ]; } #[tokio::test] async fn write_lp_from_wal() { use std::fs; test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let ingester_config = TestConfig::new_ingester_never_persist(&database_url); let router_config = TestConfig::new_router(&ingester_config); let wal_dir = Arc::new(std::path::PathBuf::from( ingester_config .wal_dir() .as_ref() .expect("missing WAL dir") .path(), )); let mut cluster = MiniCluster::new() .with_ingester(ingester_config) .await .with_router(router_config) .await; // Check that the query returns the same result between the original and // regenerated input. let table_name = "h2o_temperature"; StepTest::new( &mut cluster, vec![ Step::Custom(Box::new(|state: &mut StepTestState| { async { let router_addr = state.cluster().router().router_http_base().to_string(); let namespace = state.cluster().namespace(); Command::cargo_bin("influxdb_iox") .unwrap() .arg("-v") .arg("-h") .arg(&router_addr) .arg("write") .arg(namespace) .arg("../test_fixtures/lineproto/temperature.lp") .assert() .success() .stdout(predicate::str::contains("591 Bytes OK")); } .boxed() })), Step::Custom(Box::new(move |state: &mut StepTestState| { // Ensure the results are queryable in the ingester async { assert_ingester_contains_results( state.cluster(), table_name, &TEMPERATURE_RESULTS, ) .await; } .boxed() })), Step::Custom(Box::new(move |state: &mut StepTestState| { let wal_dir = Arc::clone(&wal_dir); async move { let mut reader = read_dir(wal_dir.as_path()).expect("failed to read WAL directory"); let segment_file_path = reader .next() .expect("no segment file found") .unwrap() .path(); assert_matches!(reader.next(), None); let out_dir = test_helpers::tmp_dir() .expect("failed to create temp directory for line proto output"); // Regenerate the line proto from the segment file Command::cargo_bin("influxdb_iox") .unwrap() .arg("-vv") .arg("-h") .arg(state.cluster().router().router_grpc_base().to_string()) .arg("debug") .arg("wal") .arg("regenerate-lp") .arg("-o") .arg( out_dir .path() .to_str() .expect("should be able to get temp directory as string"), ) .arg( segment_file_path .to_str() .expect("should be able to get segment file path as string"), ) .assert() .success(); let mut reader = read_dir(out_dir.path()).expect("failed to read output directory"); let regenerated_file_path = reader .next() .expect("no regenerated files found") .unwrap() .path(); // Make sure that only one file was regenerated. assert_matches!(reader.next(), None); // Remove the WAL segment file, ensure the WAL dir is empty // and restart the services. fs::remove_file(segment_file_path) .expect("should be able to remove WAL segment file"); assert_matches!( fs::read_dir(wal_dir.as_path()) .expect("failed to read WAL directory") .next(), None ); state.cluster_mut().restart_ingesters().await; state.cluster_mut().restart_router().await; // Feed the regenerated LP back into the ingester and check // that the expected results are returned. Command::cargo_bin("influxdb_iox") .unwrap() .arg("-v") .arg("-h") .arg(state.cluster().router().router_http_base().to_string()) .arg("write") .arg(state.cluster().namespace()) .arg( regenerated_file_path .to_str() .expect("should be able to get valid path to regenerated file"), ) .assert() .success() .stdout(predicate::str::contains("592 Bytes OK")); assert_ingester_contains_results( state.cluster(), table_name, &TEMPERATURE_RESULTS, ) .await; } .boxed() })), ], ) .run() .await } async fn assert_ingester_contains_results( cluster: &MiniCluster, table_name: &str, expected: &[&str], ) { use ingester_query_grpc::{influxdata::iox::ingester::v1 as proto, IngesterQueryRequest}; // query the ingester let query = IngesterQueryRequest::new( cluster.namespace_id().await, cluster.table_id(table_name).await, vec![], Some(::predicate::EMPTY_PREDICATE), ); let query: proto::IngesterQueryRequest = query.try_into().unwrap(); let ingester_response = cluster .query_ingester(query.clone(), cluster.ingester().ingester_grpc_connection()) .await .unwrap(); let ingester_partition = ingester_response .partitions .into_iter() .next() .expect("at least one ingester partition"); let ingester_uuid = ingester_partition.app_metadata.ingester_uuid; assert!(!ingester_uuid.is_empty()); assert_batches_sorted_eq!(expected, &ingester_partition.record_batches); } #[tokio::test] async fn inspect_entries_from_wal() { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let ingester_config = TestConfig::new_ingester_never_persist(&database_url); let router_config = TestConfig::new_router(&ingester_config); let wal_dir = Arc::new(std::path::PathBuf::from( ingester_config .wal_dir() .as_ref() .expect("missing WAL dir") .path(), )); let mut cluster = MiniCluster::new() .with_ingester(ingester_config) .await .with_router(router_config) .await; StepTest::new( &mut cluster, vec![ // Perform 3 separate writes, then inspect the WAL and ensure that // they can all be accounted for in the output by the sequencing. Step::WriteLineProtocol("bananas,quality=fresh,taste=good val=42i 123456".to_string()), Step::WriteLineProtocol("arán,quality=fresh,taste=best val=42i 654321".to_string()), Step::WriteLineProtocol("arán,quality=stale,taste=crunchy val=42i 654456".to_string()), Step::Custom(Box::new(move |_| { let wal_dir = Arc::clone(&wal_dir); async move { let mut reader = read_dir(wal_dir.as_path()).expect("failed to read WAL directory"); let segment_file_path = reader .next() .expect("no segment file found") .unwrap() .path(); assert_matches!(reader.next(), None); Command::cargo_bin("influxdb_iox") .unwrap() .arg("debug") .arg("wal") .arg("inspect") .arg( segment_file_path .to_str() .expect("should be able to get segment file path as string"), ) .assert() .success() .stdout(predicate::str::contains("SequencedWalOp").count(3)); // Re-inspect the log, but filter for WAL operations with // sequence numbers in a range. Command::cargo_bin("influxdb_iox") .unwrap() .arg("debug") .arg("wal") .arg("inspect") .arg("--sequence-number-range") .arg("1-2") .arg( segment_file_path .to_str() .expect("should be able to get segment file path as string"), ) .assert() .success() .stdout(predicate::str::contains("SequencedWalOp").count(2)); } .boxed() })), ], ) .run() .await }
pub mod filter; pub mod utils;
#[cfg(feature = "poll-driver")] use crate::alsa::AsyncWriter; use crate::alsa::{ ChannelArea, Configurator, Error, HardwareParameters, HardwareParametersMut, Result, Sample, SoftwareParameters, SoftwareParametersMut, State, Stream, Writer, }; use crate::libc as c; use crate::unix::poll::PollFlags; use alsa_sys as alsa; use std::ffi::CStr; use std::mem; use std::ptr; /// An opened PCM device. pub struct Pcm { pub(super) tag: ste::Tag, pub(super) handle: ptr::NonNull<alsa::snd_pcm_t>, } impl Pcm { /// Open the given pcm device identified by name. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// use std::ffi::CStr; /// /// # fn main() -> anyhow::Result<()> { /// let name = CStr::from_bytes_with_nul(b"hw:0\0")?; /// /// let pcm = alsa::Pcm::open(name, alsa::Stream::Playback)?; /// # Ok(()) } /// ``` pub fn open(name: &CStr, stream: Stream) -> Result<Self> { Self::open_inner(name, stream, 0) } /// Open the default pcm device. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// use std::ffi::CStr; /// /// # fn main() -> anyhow::Result<()> { /// let pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// # Ok(()) } /// ``` pub fn open_default(stream: Stream) -> Result<Self> { static DEFAULT: &[u8] = b"default\0"; Self::open( unsafe { CStr::from_bytes_with_nul_unchecked(DEFAULT) }, stream, ) } /// Open the given pcm device identified by name in a nonblocking manner. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// use std::ffi::CStr; /// /// # fn main() -> anyhow::Result<()> { /// let name = CStr::from_bytes_with_nul(b"hw:0\0")?; /// /// let pcm = alsa::Pcm::open_nonblocking(name, alsa::Stream::Playback)?; /// # Ok(()) } /// ``` pub fn open_nonblocking(name: &CStr, stream: Stream) -> Result<Self> { Self::open_inner(name, stream, alsa::SND_PCM_NONBLOCK) } /// Open the default pcm device in a nonblocking mode. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// use std::ffi::CStr; /// /// # fn main() -> anyhow::Result<()> { /// let pcm = alsa::Pcm::open_default_nonblocking(alsa::Stream::Playback)?; /// # Ok(()) } /// ``` pub fn open_default_nonblocking(stream: Stream) -> Result<Self> { static DEFAULT: &[u8] = b"default\0"; Self::open_nonblocking( unsafe { CStr::from_bytes_with_nul_unchecked(DEFAULT) }, stream, ) } fn open_inner(name: &CStr, stream: Stream, flags: i32) -> Result<Self> { unsafe { let mut handle = mem::MaybeUninit::uninit(); errno!(alsa::snd_pcm_open( handle.as_mut_ptr(), name.as_ptr(), stream as c::c_uint, flags ))?; Ok(Self { tag: ste::Tag::current_thread(), handle: ptr::NonNull::new_unchecked(handle.assume_init()), }) } } /// Get the state of the PCM. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// dbg!(pcm.state()); /// # Ok(()) } /// ``` pub fn state(&self) -> State { self.tag.ensure_on_thread(); unsafe { let state = alsa::snd_pcm_state(self.handle.as_ptr()); State::from_value(state).unwrap_or(State::Private1) } } /// Construct a simple stream [Configurator]. /// /// It will be initialized with a set of default parameters which are /// usually suitable for simple playback or recording for the given sample /// type `T`. /// /// See [Configurator]. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// let config = pcm.configure::<i16>().install()?; /// # Ok(()) } /// ``` pub fn configure<T>(&mut self) -> Configurator<'_, T> where T: Sample, { self.tag.ensure_on_thread(); Configurator::new(self) } /// Start a PCM. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// pcm.start()?; /// # Ok(()) } /// ``` pub fn start(&mut self) -> Result<()> { self.tag.ensure_on_thread(); unsafe { errno!(alsa::snd_pcm_start(self.handle.as_mut()))?; Ok(()) } } /// Pause a PCM. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// pcm.pause()?; /// # Ok(()) } /// ``` pub fn pause(&mut self) -> Result<()> { self.tag.ensure_on_thread(); unsafe { errno!(alsa::snd_pcm_pause(self.handle.as_mut(), 1))?; Ok(()) } } /// Resume a PCM. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// pcm.resume()?; /// # Ok(()) } /// ``` pub fn resume(&mut self) -> Result<()> { self.tag.ensure_on_thread(); unsafe { errno!(alsa::snd_pcm_pause(self.handle.as_mut(), 0))?; Ok(()) } } /// Open all available hardware parameters for the current handle. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// let mut hw = pcm.hardware_parameters_any()?; /// hw.set_rate_last()?; /// hw.install()?; /// # Ok(()) } /// ``` pub fn hardware_parameters_any(&mut self) -> Result<HardwareParametersMut<'_>> { self.tag.ensure_on_thread(); unsafe { HardwareParametersMut::any(&mut self.handle) } } /// Open current hardware parameters for the current handle for mutable access. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// /// let mut hw = pcm.hardware_parameters_mut()?; /// let actual_rate = hw.set_rate(44100, alsa::Direction::Nearest)?; /// hw.install()?; /// /// dbg!(actual_rate); /// # Ok(()) } /// ``` pub fn hardware_parameters_mut(&mut self) -> Result<HardwareParametersMut<'_>> { self.tag.ensure_on_thread(); unsafe { HardwareParametersMut::current(&mut self.handle) } } /// Open current hardware parameters for the current handle. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// let sw = pcm.hardware_parameters()?; /// dbg!(sw.rate()?); /// # Ok(()) } /// ``` pub fn hardware_parameters(&mut self) -> Result<HardwareParameters> { self.tag.ensure_on_thread(); unsafe { HardwareParameters::current(&mut self.handle) } } /// Open current software parameters for the current handle. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// let sw = pcm.software_parameters()?; /// /// dbg!(sw.boundary()?); /// # Ok(()) } /// ``` pub fn software_parameters(&mut self) -> Result<SoftwareParameters> { self.tag.ensure_on_thread(); unsafe { SoftwareParameters::new(&mut self.handle) } } /// Open current software parameters for the current handle for mutable access. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// let mut sw = pcm.software_parameters_mut()?; /// /// sw.set_timestamp_mode(alsa::Timestamp::Enable)?; /// sw.install()?; /// # Ok(()) } /// ``` pub fn software_parameters_mut(&mut self) -> Result<SoftwareParametersMut<'_>> { self.tag.ensure_on_thread(); unsafe { SoftwareParametersMut::new(&mut self.handle) } } /// Get count of poll descriptors for PCM handle. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// let count = pcm.poll_descriptors_count(); /// dbg!(count); /// # Ok(()) } /// ``` pub fn poll_descriptors_count(&mut self) -> usize { self.tag.ensure_on_thread(); unsafe { alsa::snd_pcm_poll_descriptors_count(self.handle.as_mut()) as usize } } /// Get poll descriptors. /// /// This function fills the given poll descriptor structs for the specified /// PCM handle. The poll desctiptor array should have the size returned by /// [poll_descriptors_count()][Pcm::poll_descriptors_count()] function. /// /// The result is intended for direct use with the `poll()` syscall. /// /// For reading the returned events of poll descriptor after `poll()` system /// call, use ::snd_pcm_poll_descriptors_revents() function. The field /// values in pollfd structs may be bogus regarding the stream direction /// from the application perspective (`POLLIN` might not imply read /// direction and `POLLOUT` might not imply write), but the /// [poll_descriptors_revents()][Pcm::poll_descriptors_revents()] function /// does the right "demangling". /// /// You can use output from this function as arguments for the select() /// syscall, too. Do not forget to translate `POLLIN` and `POLLOUT` events /// to corresponding `FD_SET` arrays and demangle events using /// [poll_descriptors_revents()][Pcm::poll_descriptors_revents()]. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// /// let mut fds = Vec::with_capacity(pcm.poll_descriptors_count()); /// pcm.poll_descriptors_vec(&mut fds)?; /// # Ok(()) } /// ``` pub fn poll_descriptors_vec(&mut self, fds: &mut Vec<c::pollfd>) -> Result<()> { self.tag.ensure_on_thread(); unsafe { let count = self.poll_descriptors_count(); if fds.capacity() < count { fds.reserve(count - fds.capacity()); } let result = errno!(alsa::snd_pcm_poll_descriptors( self.handle.as_mut(), fds.as_mut_ptr() as *mut c::pollfd, fds.capacity() as c::c_uint ))?; let result = result as usize; assert!(result <= fds.capacity()); fds.set_len(result); Ok(()) } } /// Get returned events from poll descriptors. /// /// This function does "demangling" of the revents mask returned from the /// `poll()` syscall to correct semantics ([PollFlags::POLLIN] = read, /// [PollFlags::POLLOUT] = write). /// /// Note: The null event also exists. Even if `poll()` or `select()` syscall /// returned that some events are waiting, this function might return empty /// set of events. In this case, application should do next event waiting /// using `poll()` or `select()`. /// /// Note: Even if multiple poll descriptors are used (i.e. `fds.len() > 1`), /// this function returns only a single event. pub fn poll_descriptors_revents(&mut self, fds: &mut [c::pollfd]) -> Result<PollFlags> { self.tag.ensure_on_thread(); unsafe { let mut revents = mem::MaybeUninit::uninit(); errno!(alsa::snd_pcm_poll_descriptors_revents( self.handle.as_mut(), // NB: PollFd is `#[repr(transparent)]` around pollfd. fds.as_mut_ptr(), fds.len() as c::c_uint, revents.as_mut_ptr(), ))?; let revents = revents.assume_init(); Ok(PollFlags::from_bits_truncate(revents as c::c_short)) } } /// Write unchecked interleaved frames to a PCM. /// /// Note: that the `len` must be the number of frames in the `buf` which /// *does not* account for the number of channels. So if `len` is 100, and /// the number of configured channels is 2, the `buf` must contain **at /// least** 200 bytes. /// /// See [HardwareParameters::channels]. pub unsafe fn write_interleaved_unchecked( &mut self, buf: *const c::c_void, len: c::c_ulong, ) -> Result<c::c_long> { self.tag.ensure_on_thread(); Ok(errno!(alsa::snd_pcm_writei( self.handle.as_mut(), buf, len ))?) } /// Construct a checked safe writer with the given number of channels and /// the specified sample type. /// /// This will error if the type `T` is not appropriate for this device, or /// if the number of channels does not match the number of configured /// channels. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// let config = pcm.configure::<i16>().install()?; /// /// let mut writer = pcm.writer::<i16>()?; /// // use writer with the resulting config. /// # Ok(()) } /// ``` pub fn writer<T>(&mut self) -> Result<Writer<'_, T>> where T: Sample, { self.tag.ensure_on_thread(); let hw = self.hardware_parameters()?; let channels = hw.channels()? as usize; // NB: here we check that `T` is appropriate for the current format. let format = hw.format()?; if !T::test(format) { return Err(Error::FormatMismatch { ty: T::describe(), format, }); } unsafe { Ok(Writer::new(self, channels)) } } cfg_poll_driver! { /// Construct a checked safe writer with the given number of channels and /// the specified sample type. /// /// This will error if the type `T` is not appropriate for this device, or /// if the number of channels does not match the number of configured /// channels. /// /// # Panics /// /// Panics if the audio runtime is not available. /// /// See [Runtime][crate::runtime::Runtime] for more. /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// let config = pcm.configure::<i16>().install()?; /// /// let mut writer = pcm.writer::<i16>()?; /// // use writer with the resulting config. /// # Ok(()) } /// ``` pub fn async_writer<T>(&mut self) -> Result<AsyncWriter<'_, T>> where T: Sample, { self.tag.ensure_on_thread(); let hw = self.hardware_parameters()?; let channels = hw.channels()? as usize; // NB: here we check that `T` is appropriate for the current format. let format = hw.format()?; if !T::test(format) { return Err(Error::FormatMismatch { ty: T::describe(), format, }); } let mut fds = Vec::new(); self.poll_descriptors_vec(&mut fds)?; if fds.len() != 1 { return Err(Error::MissingPollFds); } let fd = fds[0]; Ok(unsafe { AsyncWriter::new(self, fd, channels)? }) } } /// Return number of frames ready to be read (capture) / written (playback). /// /// # Examples /// /// ```rust,no_run /// use audio_device::alsa; /// /// # fn main() -> anyhow::Result<()> { /// let mut pcm = alsa::Pcm::open_default(alsa::Stream::Playback)?; /// /// let avail = pcm.available_update()?; /// dbg!(avail); /// # Ok(()) } /// ``` pub fn available_update(&mut self) -> Result<usize> { self.tag.ensure_on_thread(); unsafe { Ok(errno!(alsa::snd_pcm_avail_update(self.handle.as_mut()))? as usize) } } /// Application request to access a portion of direct (mmap) area. #[doc(hidden)] // incomplete feature pub fn mmap_begin(&mut self, mut frames: c::c_ulong) -> Result<ChannelArea<'_>> { self.tag.ensure_on_thread(); unsafe { let mut area = mem::MaybeUninit::uninit(); let mut offset = mem::MaybeUninit::uninit(); errno!(alsa::snd_pcm_mmap_begin( self.handle.as_mut(), area.as_mut_ptr(), offset.as_mut_ptr(), &mut frames ))?; let area = area.assume_init(); let offset = offset.assume_init(); Ok(ChannelArea { pcm: &mut self.handle, area, offset, frames, }) } } } // Safety: [Pcm] is tagged with the thread its created it and is ensured not to // leave it. unsafe impl Send for Pcm {} impl Drop for Pcm { fn drop(&mut self) { unsafe { alsa::snd_pcm_close(self.handle.as_ptr()) }; } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "UI_Xaml_Automation_Peers")] pub mod Peers; #[cfg(feature = "UI_Xaml_Automation_Provider")] pub mod Provider; #[cfg(feature = "UI_Xaml_Automation_Text")] pub mod Text; #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AnnotationPatternIdentifiers(pub ::windows::core::IInspectable); impl AnnotationPatternIdentifiers { pub fn AnnotationTypeIdProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAnnotationPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn AnnotationTypeNameProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAnnotationPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn AuthorProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAnnotationPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn DateTimeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAnnotationPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn TargetProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAnnotationPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IAnnotationPatternIdentifiersStatics<R, F: FnOnce(&IAnnotationPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AnnotationPatternIdentifiers, IAnnotationPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for AnnotationPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.AnnotationPatternIdentifiers;{d475a0c1-48b2-4e40-a6cf-3dc4b638c0de})"); } unsafe impl ::windows::core::Interface for AnnotationPatternIdentifiers { type Vtable = IAnnotationPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd475a0c1_48b2_4e40_a6cf_3dc4b638c0de); } impl ::windows::core::RuntimeName for AnnotationPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.AnnotationPatternIdentifiers"; } impl ::core::convert::From<AnnotationPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: AnnotationPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&AnnotationPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &AnnotationPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AnnotationPatternIdentifiers { 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 AnnotationPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AnnotationPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: AnnotationPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&AnnotationPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &AnnotationPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AnnotationPatternIdentifiers { 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 AnnotationPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AnnotationPatternIdentifiers {} unsafe impl ::core::marker::Sync for AnnotationPatternIdentifiers {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AnnotationType(pub i32); impl AnnotationType { pub const Unknown: AnnotationType = AnnotationType(60000i32); pub const SpellingError: AnnotationType = AnnotationType(60001i32); pub const GrammarError: AnnotationType = AnnotationType(60002i32); pub const Comment: AnnotationType = AnnotationType(60003i32); pub const FormulaError: AnnotationType = AnnotationType(60004i32); pub const TrackChanges: AnnotationType = AnnotationType(60005i32); pub const Header: AnnotationType = AnnotationType(60006i32); pub const Footer: AnnotationType = AnnotationType(60007i32); pub const Highlighted: AnnotationType = AnnotationType(60008i32); pub const Endnote: AnnotationType = AnnotationType(60009i32); pub const Footnote: AnnotationType = AnnotationType(60010i32); pub const InsertionChange: AnnotationType = AnnotationType(60011i32); pub const DeletionChange: AnnotationType = AnnotationType(60012i32); pub const MoveChange: AnnotationType = AnnotationType(60013i32); pub const FormatChange: AnnotationType = AnnotationType(60014i32); pub const UnsyncedChange: AnnotationType = AnnotationType(60015i32); pub const EditingLockedChange: AnnotationType = AnnotationType(60016i32); pub const ExternalChange: AnnotationType = AnnotationType(60017i32); pub const ConflictingChange: AnnotationType = AnnotationType(60018i32); pub const Author: AnnotationType = AnnotationType(60019i32); pub const AdvancedProofingIssue: AnnotationType = AnnotationType(60020i32); pub const DataValidationError: AnnotationType = AnnotationType(60021i32); pub const CircularReferenceError: AnnotationType = AnnotationType(60022i32); } impl ::core::convert::From<i32> for AnnotationType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AnnotationType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AnnotationType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.AnnotationType;i4)"); } impl ::windows::core::DefaultType for AnnotationType { 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 AutomationActiveEnd(pub i32); impl AutomationActiveEnd { pub const None: AutomationActiveEnd = AutomationActiveEnd(0i32); pub const Start: AutomationActiveEnd = AutomationActiveEnd(1i32); pub const End: AutomationActiveEnd = AutomationActiveEnd(2i32); } impl ::core::convert::From<i32> for AutomationActiveEnd { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AutomationActiveEnd { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AutomationActiveEnd { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.AutomationActiveEnd;i4)"); } impl ::windows::core::DefaultType for AutomationActiveEnd { 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 AutomationAnimationStyle(pub i32); impl AutomationAnimationStyle { pub const None: AutomationAnimationStyle = AutomationAnimationStyle(0i32); pub const LasVegasLights: AutomationAnimationStyle = AutomationAnimationStyle(1i32); pub const BlinkingBackground: AutomationAnimationStyle = AutomationAnimationStyle(2i32); pub const SparkleText: AutomationAnimationStyle = AutomationAnimationStyle(3i32); pub const MarchingBlackAnts: AutomationAnimationStyle = AutomationAnimationStyle(4i32); pub const MarchingRedAnts: AutomationAnimationStyle = AutomationAnimationStyle(5i32); pub const Shimmer: AutomationAnimationStyle = AutomationAnimationStyle(6i32); pub const Other: AutomationAnimationStyle = AutomationAnimationStyle(7i32); } impl ::core::convert::From<i32> for AutomationAnimationStyle { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AutomationAnimationStyle { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AutomationAnimationStyle { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.AutomationAnimationStyle;i4)"); } impl ::windows::core::DefaultType for AutomationAnimationStyle { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AutomationAnnotation(pub ::windows::core::IInspectable); impl AutomationAnnotation { 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<AutomationAnnotation, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn Type(&self) -> ::windows::core::Result<AnnotationType> { let this = self; unsafe { let mut result__: AnnotationType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AnnotationType>(result__) } } pub fn SetType(&self, value: AnnotationType) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn Element(&self) -> ::windows::core::Result<super::UIElement> { 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::UIElement>(result__) } } pub fn SetElement<'a, Param0: ::windows::core::IntoParam<'a, super::UIElement>>(&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 CreateInstance(r#type: AnnotationType) -> ::windows::core::Result<AutomationAnnotation> { Self::IAutomationAnnotationFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), r#type, &mut result__).from_abi::<AutomationAnnotation>(result__) }) } pub fn CreateWithElementParameter<'a, Param1: ::windows::core::IntoParam<'a, super::UIElement>>(r#type: AnnotationType, element: Param1) -> ::windows::core::Result<AutomationAnnotation> { Self::IAutomationAnnotationFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), r#type, element.into_param().abi(), &mut result__).from_abi::<AutomationAnnotation>(result__) }) } pub fn TypeProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationAnnotationStatics(|this| 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::DependencyProperty>(result__) }) } pub fn ElementProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationAnnotationStatics(|this| 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::DependencyProperty>(result__) }) } pub fn IAutomationAnnotationFactory<R, F: FnOnce(&IAutomationAnnotationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationAnnotation, IAutomationAnnotationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationAnnotationStatics<R, F: FnOnce(&IAutomationAnnotationStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationAnnotation, IAutomationAnnotationStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for AutomationAnnotation { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.AutomationAnnotation;{fb3c30ca-03d8-4618-91bf-e4d84f4af318})"); } unsafe impl ::windows::core::Interface for AutomationAnnotation { type Vtable = IAutomationAnnotation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb3c30ca_03d8_4618_91bf_e4d84f4af318); } impl ::windows::core::RuntimeName for AutomationAnnotation { const NAME: &'static str = "Windows.UI.Xaml.Automation.AutomationAnnotation"; } impl ::core::convert::From<AutomationAnnotation> for ::windows::core::IUnknown { fn from(value: AutomationAnnotation) -> Self { value.0 .0 } } impl ::core::convert::From<&AutomationAnnotation> for ::windows::core::IUnknown { fn from(value: &AutomationAnnotation) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AutomationAnnotation { 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 AutomationAnnotation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AutomationAnnotation> for ::windows::core::IInspectable { fn from(value: AutomationAnnotation) -> Self { value.0 } } impl ::core::convert::From<&AutomationAnnotation> for ::windows::core::IInspectable { fn from(value: &AutomationAnnotation) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AutomationAnnotation { 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 AutomationAnnotation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<AutomationAnnotation> for super::DependencyObject { fn from(value: AutomationAnnotation) -> Self { ::core::convert::Into::<super::DependencyObject>::into(&value) } } impl ::core::convert::From<&AutomationAnnotation> for super::DependencyObject { fn from(value: &AutomationAnnotation) -> Self { ::windows::core::Interface::cast(value).unwrap() } } impl<'a> ::windows::core::IntoParam<'a, super::DependencyObject> for AutomationAnnotation { fn into_param(self) -> ::windows::core::Param<'a, super::DependencyObject> { ::windows::core::Param::Owned(::core::convert::Into::<super::DependencyObject>::into(self)) } } impl<'a> ::windows::core::IntoParam<'a, super::DependencyObject> for &AutomationAnnotation { fn into_param(self) -> ::windows::core::Param<'a, super::DependencyObject> { ::windows::core::Param::Owned(::core::convert::Into::<super::DependencyObject>::into(::core::clone::Clone::clone(self))) } } unsafe impl ::core::marker::Send for AutomationAnnotation {} unsafe impl ::core::marker::Sync for AutomationAnnotation {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AutomationBulletStyle(pub i32); impl AutomationBulletStyle { pub const None: AutomationBulletStyle = AutomationBulletStyle(0i32); pub const HollowRoundBullet: AutomationBulletStyle = AutomationBulletStyle(1i32); pub const FilledRoundBullet: AutomationBulletStyle = AutomationBulletStyle(2i32); pub const HollowSquareBullet: AutomationBulletStyle = AutomationBulletStyle(3i32); pub const FilledSquareBullet: AutomationBulletStyle = AutomationBulletStyle(4i32); pub const DashBullet: AutomationBulletStyle = AutomationBulletStyle(5i32); pub const Other: AutomationBulletStyle = AutomationBulletStyle(6i32); } impl ::core::convert::From<i32> for AutomationBulletStyle { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AutomationBulletStyle { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AutomationBulletStyle { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.AutomationBulletStyle;i4)"); } impl ::windows::core::DefaultType for AutomationBulletStyle { 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 AutomationCaretBidiMode(pub i32); impl AutomationCaretBidiMode { pub const LTR: AutomationCaretBidiMode = AutomationCaretBidiMode(0i32); pub const RTL: AutomationCaretBidiMode = AutomationCaretBidiMode(1i32); } impl ::core::convert::From<i32> for AutomationCaretBidiMode { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AutomationCaretBidiMode { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AutomationCaretBidiMode { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.AutomationCaretBidiMode;i4)"); } impl ::windows::core::DefaultType for AutomationCaretBidiMode { 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 AutomationCaretPosition(pub i32); impl AutomationCaretPosition { pub const Unknown: AutomationCaretPosition = AutomationCaretPosition(0i32); pub const EndOfLine: AutomationCaretPosition = AutomationCaretPosition(1i32); pub const BeginningOfLine: AutomationCaretPosition = AutomationCaretPosition(2i32); } impl ::core::convert::From<i32> for AutomationCaretPosition { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AutomationCaretPosition { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AutomationCaretPosition { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.AutomationCaretPosition;i4)"); } impl ::windows::core::DefaultType for AutomationCaretPosition { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AutomationElementIdentifiers(pub ::windows::core::IInspectable); impl AutomationElementIdentifiers { pub fn AcceleratorKeyProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn AccessKeyProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn AutomationIdProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn BoundingRectangleProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ClassNameProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ClickablePointProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ControlTypeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn HasKeyboardFocusProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn HelpTextProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn IsContentElementProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn IsControlElementProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn IsEnabledProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn IsKeyboardFocusableProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn IsOffscreenProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn IsPasswordProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn IsRequiredForFormProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn ItemStatusProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn ItemTypeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn LabeledByProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn LocalizedControlTypeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn NameProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn OrientationProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn LiveSettingProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn ControlledPeersProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics2(|this| 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::<AutomationProperty>(result__) }) } pub fn PositionInSetProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics3(|this| 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::<AutomationProperty>(result__) }) } pub fn SizeOfSetProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics3(|this| 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::<AutomationProperty>(result__) }) } pub fn LevelProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics3(|this| 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::<AutomationProperty>(result__) }) } pub fn AnnotationsProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics3(|this| 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::<AutomationProperty>(result__) }) } pub fn LandmarkTypeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics4(|this| 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::<AutomationProperty>(result__) }) } pub fn LocalizedLandmarkTypeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics4(|this| 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::<AutomationProperty>(result__) }) } pub fn IsPeripheralProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics5(|this| 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::<AutomationProperty>(result__) }) } pub fn IsDataValidForFormProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics5(|this| 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::<AutomationProperty>(result__) }) } pub fn FullDescriptionProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics5(|this| 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::<AutomationProperty>(result__) }) } pub fn DescribedByProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics5(|this| 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::<AutomationProperty>(result__) }) } pub fn FlowsToProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics5(|this| 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::<AutomationProperty>(result__) }) } pub fn FlowsFromProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics5(|this| 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::<AutomationProperty>(result__) }) } pub fn CultureProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics6(|this| 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::<AutomationProperty>(result__) }) } pub fn HeadingLevelProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics7(|this| 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::<AutomationProperty>(result__) }) } pub fn IsDialogProperty() -> ::windows::core::Result<AutomationProperty> { Self::IAutomationElementIdentifiersStatics8(|this| 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::<AutomationProperty>(result__) }) } pub fn IAutomationElementIdentifiersStatics<R, F: FnOnce(&IAutomationElementIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationElementIdentifiers, IAutomationElementIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationElementIdentifiersStatics2<R, F: FnOnce(&IAutomationElementIdentifiersStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationElementIdentifiers, IAutomationElementIdentifiersStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationElementIdentifiersStatics3<R, F: FnOnce(&IAutomationElementIdentifiersStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationElementIdentifiers, IAutomationElementIdentifiersStatics3> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationElementIdentifiersStatics4<R, F: FnOnce(&IAutomationElementIdentifiersStatics4) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationElementIdentifiers, IAutomationElementIdentifiersStatics4> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationElementIdentifiersStatics5<R, F: FnOnce(&IAutomationElementIdentifiersStatics5) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationElementIdentifiers, IAutomationElementIdentifiersStatics5> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationElementIdentifiersStatics6<R, F: FnOnce(&IAutomationElementIdentifiersStatics6) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationElementIdentifiers, IAutomationElementIdentifiersStatics6> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationElementIdentifiersStatics7<R, F: FnOnce(&IAutomationElementIdentifiersStatics7) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationElementIdentifiers, IAutomationElementIdentifiersStatics7> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationElementIdentifiersStatics8<R, F: FnOnce(&IAutomationElementIdentifiersStatics8) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationElementIdentifiers, IAutomationElementIdentifiersStatics8> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for AutomationElementIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.AutomationElementIdentifiers;{e68a63cf-4345-4e2d-8a6a-49cce1fa2dcc})"); } unsafe impl ::windows::core::Interface for AutomationElementIdentifiers { type Vtable = IAutomationElementIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe68a63cf_4345_4e2d_8a6a_49cce1fa2dcc); } impl ::windows::core::RuntimeName for AutomationElementIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.AutomationElementIdentifiers"; } impl ::core::convert::From<AutomationElementIdentifiers> for ::windows::core::IUnknown { fn from(value: AutomationElementIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&AutomationElementIdentifiers> for ::windows::core::IUnknown { fn from(value: &AutomationElementIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AutomationElementIdentifiers { 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 AutomationElementIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AutomationElementIdentifiers> for ::windows::core::IInspectable { fn from(value: AutomationElementIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&AutomationElementIdentifiers> for ::windows::core::IInspectable { fn from(value: &AutomationElementIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AutomationElementIdentifiers { 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 AutomationElementIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AutomationElementIdentifiers {} unsafe impl ::core::marker::Sync for AutomationElementIdentifiers {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AutomationFlowDirections(pub i32); impl AutomationFlowDirections { pub const Default: AutomationFlowDirections = AutomationFlowDirections(0i32); pub const RightToLeft: AutomationFlowDirections = AutomationFlowDirections(1i32); pub const BottomToTop: AutomationFlowDirections = AutomationFlowDirections(2i32); pub const Vertical: AutomationFlowDirections = AutomationFlowDirections(3i32); } impl ::core::convert::From<i32> for AutomationFlowDirections { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AutomationFlowDirections { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AutomationFlowDirections { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.AutomationFlowDirections;i4)"); } impl ::windows::core::DefaultType for AutomationFlowDirections { 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 AutomationOutlineStyles(pub i32); impl AutomationOutlineStyles { pub const None: AutomationOutlineStyles = AutomationOutlineStyles(0i32); pub const Outline: AutomationOutlineStyles = AutomationOutlineStyles(1i32); pub const Shadow: AutomationOutlineStyles = AutomationOutlineStyles(2i32); pub const Engraved: AutomationOutlineStyles = AutomationOutlineStyles(3i32); pub const Embossed: AutomationOutlineStyles = AutomationOutlineStyles(4i32); } impl ::core::convert::From<i32> for AutomationOutlineStyles { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AutomationOutlineStyles { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AutomationOutlineStyles { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.AutomationOutlineStyles;i4)"); } impl ::windows::core::DefaultType for AutomationOutlineStyles { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AutomationProperties(pub ::windows::core::IInspectable); impl AutomationProperties { pub fn AcceleratorKeyProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics(|this| 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::DependencyProperty>(result__) }) } pub fn GetAcceleratorKey<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAutomationPropertiesStatics(|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), element.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn SetAcceleratorKey<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(element: Param0, value: Param1) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), element.into_param().abi(), value.into_param().abi()).ok() }) } pub fn AccessKeyProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics(|this| 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::DependencyProperty>(result__) }) } pub fn GetAccessKey<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn SetAccessKey<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(element: Param0, value: Param1) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics(|this| unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), element.into_param().abi(), value.into_param().abi()).ok() }) } pub fn AutomationIdProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } pub fn GetAutomationId<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn SetAutomationId<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(element: Param0, value: Param1) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics(|this| unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), element.into_param().abi(), value.into_param().abi()).ok() }) } pub fn HelpTextProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } pub fn GetHelpText<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn SetHelpText<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(element: Param0, value: Param1) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics(|this| unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), element.into_param().abi(), value.into_param().abi()).ok() }) } pub fn IsRequiredForFormProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } pub fn GetIsRequiredForForm<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<bool> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<bool>(result__) }) } pub fn SetIsRequiredForForm<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0, value: bool) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics(|this| unsafe { (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn ItemStatusProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } pub fn GetItemStatus<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn SetItemStatus<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(element: Param0, value: Param1) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics(|this| unsafe { (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), element.into_param().abi(), value.into_param().abi()).ok() }) } pub fn ItemTypeProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } pub fn GetItemType<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn SetItemType<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(element: Param0, value: Param1) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics(|this| unsafe { (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), element.into_param().abi(), value.into_param().abi()).ok() }) } pub fn LabeledByProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } pub fn GetLabeledBy<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<super::UIElement> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<super::UIElement>(result__) }) } pub fn SetLabeledBy<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>, Param1: ::windows::core::IntoParam<'a, super::UIElement>>(element: Param0, value: Param1) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics(|this| unsafe { (::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), element.into_param().abi(), value.into_param().abi()).ok() }) } pub fn NameProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } pub fn GetName<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn SetName<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(element: Param0, value: Param1) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics(|this| unsafe { (::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), element.into_param().abi(), value.into_param().abi()).ok() }) } pub fn LiveSettingProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } #[cfg(feature = "UI_Xaml_Automation_Peers")] pub fn GetLiveSetting<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<Peers::AutomationLiveSetting> { Self::IAutomationPropertiesStatics(|this| unsafe { let mut result__: Peers::AutomationLiveSetting = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<Peers::AutomationLiveSetting>(result__) }) } #[cfg(feature = "UI_Xaml_Automation_Peers")] pub fn SetLiveSetting<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0, value: Peers::AutomationLiveSetting) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics(|this| unsafe { (::windows::core::Interface::vtable(this).35)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn AccessibilityViewProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics2(|this| 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::DependencyProperty>(result__) }) } #[cfg(feature = "UI_Xaml_Automation_Peers")] pub fn GetAccessibilityView<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<Peers::AccessibilityView> { Self::IAutomationPropertiesStatics2(|this| unsafe { let mut result__: Peers::AccessibilityView = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<Peers::AccessibilityView>(result__) }) } #[cfg(feature = "UI_Xaml_Automation_Peers")] pub fn SetAccessibilityView<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0, value: Peers::AccessibilityView) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics2(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn ControlledPeersProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics2(|this| 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::DependencyProperty>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn GetControlledPeers<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<super::UIElement>> { Self::IAutomationPropertiesStatics2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<super::UIElement>>(result__) }) } pub fn PositionInSetProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics3(|this| 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::DependencyProperty>(result__) }) } pub fn GetPositionInSet<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<i32> { Self::IAutomationPropertiesStatics3(|this| unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<i32>(result__) }) } pub fn SetPositionInSet<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0, value: i32) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics3(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn SizeOfSetProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics3(|this| 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::DependencyProperty>(result__) }) } pub fn GetSizeOfSet<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<i32> { Self::IAutomationPropertiesStatics3(|this| unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<i32>(result__) }) } pub fn SetSizeOfSet<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0, value: i32) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics3(|this| unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn LevelProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics3(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } pub fn GetLevel<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<i32> { Self::IAutomationPropertiesStatics3(|this| unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<i32>(result__) }) } pub fn SetLevel<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0, value: i32) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics3(|this| unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn AnnotationsProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics3(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn GetAnnotations<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<AutomationAnnotation>> { Self::IAutomationPropertiesStatics3(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<AutomationAnnotation>>(result__) }) } pub fn LandmarkTypeProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics4(|this| 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::DependencyProperty>(result__) }) } #[cfg(feature = "UI_Xaml_Automation_Peers")] pub fn GetLandmarkType<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<Peers::AutomationLandmarkType> { Self::IAutomationPropertiesStatics4(|this| unsafe { let mut result__: Peers::AutomationLandmarkType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<Peers::AutomationLandmarkType>(result__) }) } #[cfg(feature = "UI_Xaml_Automation_Peers")] pub fn SetLandmarkType<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0, value: Peers::AutomationLandmarkType) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics4(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn LocalizedLandmarkTypeProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics4(|this| 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::DependencyProperty>(result__) }) } pub fn GetLocalizedLandmarkType<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAutomationPropertiesStatics4(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn SetLocalizedLandmarkType<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(element: Param0, value: Param1) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics4(|this| unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), element.into_param().abi(), value.into_param().abi()).ok() }) } pub fn IsPeripheralProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics5(|this| 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::DependencyProperty>(result__) }) } pub fn GetIsPeripheral<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<bool> { Self::IAutomationPropertiesStatics5(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<bool>(result__) }) } pub fn SetIsPeripheral<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0, value: bool) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics5(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn IsDataValidForFormProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics5(|this| 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::DependencyProperty>(result__) }) } pub fn GetIsDataValidForForm<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<bool> { Self::IAutomationPropertiesStatics5(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<bool>(result__) }) } pub fn SetIsDataValidForForm<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0, value: bool) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics5(|this| unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn FullDescriptionProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics5(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } pub fn GetFullDescription<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAutomationPropertiesStatics5(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn SetFullDescription<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(element: Param0, value: Param1) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics5(|this| unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), element.into_param().abi(), value.into_param().abi()).ok() }) } pub fn LocalizedControlTypeProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics5(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } pub fn GetLocalizedControlType<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAutomationPropertiesStatics5(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn SetLocalizedControlType<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(element: Param0, value: Param1) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics5(|this| unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), element.into_param().abi(), value.into_param().abi()).ok() }) } pub fn DescribedByProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics5(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn GetDescribedBy<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<super::DependencyObject>> { Self::IAutomationPropertiesStatics5(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<super::DependencyObject>>(result__) }) } pub fn FlowsToProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics5(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn GetFlowsTo<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<super::DependencyObject>> { Self::IAutomationPropertiesStatics5(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<super::DependencyObject>>(result__) }) } pub fn FlowsFromProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics5(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DependencyProperty>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn GetFlowsFrom<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<super::DependencyObject>> { Self::IAutomationPropertiesStatics5(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<super::DependencyObject>>(result__) }) } pub fn CultureProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics6(|this| 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::DependencyProperty>(result__) }) } pub fn GetCulture<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<i32> { Self::IAutomationPropertiesStatics6(|this| unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<i32>(result__) }) } pub fn SetCulture<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0, value: i32) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics6(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn HeadingLevelProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics7(|this| 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::DependencyProperty>(result__) }) } #[cfg(feature = "UI_Xaml_Automation_Peers")] pub fn GetHeadingLevel<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<Peers::AutomationHeadingLevel> { Self::IAutomationPropertiesStatics7(|this| unsafe { let mut result__: Peers::AutomationHeadingLevel = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<Peers::AutomationHeadingLevel>(result__) }) } #[cfg(feature = "UI_Xaml_Automation_Peers")] pub fn SetHeadingLevel<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0, value: Peers::AutomationHeadingLevel) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics7(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn IsDialogProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics8(|this| 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::DependencyProperty>(result__) }) } pub fn GetIsDialog<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0) -> ::windows::core::Result<bool> { Self::IAutomationPropertiesStatics8(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<bool>(result__) }) } pub fn SetIsDialog<'a, Param0: ::windows::core::IntoParam<'a, super::DependencyObject>>(element: Param0, value: bool) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics8(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn AutomationControlTypeProperty() -> ::windows::core::Result<super::DependencyProperty> { Self::IAutomationPropertiesStatics9(|this| 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::DependencyProperty>(result__) }) } #[cfg(feature = "UI_Xaml_Automation_Peers")] pub fn GetAutomationControlType<'a, Param0: ::windows::core::IntoParam<'a, super::UIElement>>(element: Param0) -> ::windows::core::Result<Peers::AutomationControlType> { Self::IAutomationPropertiesStatics9(|this| unsafe { let mut result__: Peers::AutomationControlType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), element.into_param().abi(), &mut result__).from_abi::<Peers::AutomationControlType>(result__) }) } #[cfg(feature = "UI_Xaml_Automation_Peers")] pub fn SetAutomationControlType<'a, Param0: ::windows::core::IntoParam<'a, super::UIElement>>(element: Param0, value: Peers::AutomationControlType) -> ::windows::core::Result<()> { Self::IAutomationPropertiesStatics9(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), element.into_param().abi(), value).ok() }) } pub fn IAutomationPropertiesStatics<R, F: FnOnce(&IAutomationPropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationProperties, IAutomationPropertiesStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationPropertiesStatics2<R, F: FnOnce(&IAutomationPropertiesStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationProperties, IAutomationPropertiesStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationPropertiesStatics3<R, F: FnOnce(&IAutomationPropertiesStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationProperties, IAutomationPropertiesStatics3> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationPropertiesStatics4<R, F: FnOnce(&IAutomationPropertiesStatics4) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationProperties, IAutomationPropertiesStatics4> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationPropertiesStatics5<R, F: FnOnce(&IAutomationPropertiesStatics5) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationProperties, IAutomationPropertiesStatics5> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationPropertiesStatics6<R, F: FnOnce(&IAutomationPropertiesStatics6) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationProperties, IAutomationPropertiesStatics6> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationPropertiesStatics7<R, F: FnOnce(&IAutomationPropertiesStatics7) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationProperties, IAutomationPropertiesStatics7> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationPropertiesStatics8<R, F: FnOnce(&IAutomationPropertiesStatics8) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationProperties, IAutomationPropertiesStatics8> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAutomationPropertiesStatics9<R, F: FnOnce(&IAutomationPropertiesStatics9) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AutomationProperties, IAutomationPropertiesStatics9> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for AutomationProperties { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.AutomationProperties;{68d7232c-e622-48e9-af0b-1ffa33cc5cba})"); } unsafe impl ::windows::core::Interface for AutomationProperties { type Vtable = IAutomationProperties_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x68d7232c_e622_48e9_af0b_1ffa33cc5cba); } impl ::windows::core::RuntimeName for AutomationProperties { const NAME: &'static str = "Windows.UI.Xaml.Automation.AutomationProperties"; } impl ::core::convert::From<AutomationProperties> for ::windows::core::IUnknown { fn from(value: AutomationProperties) -> Self { value.0 .0 } } impl ::core::convert::From<&AutomationProperties> for ::windows::core::IUnknown { fn from(value: &AutomationProperties) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AutomationProperties { 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 AutomationProperties { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AutomationProperties> for ::windows::core::IInspectable { fn from(value: AutomationProperties) -> Self { value.0 } } impl ::core::convert::From<&AutomationProperties> for ::windows::core::IInspectable { fn from(value: &AutomationProperties) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AutomationProperties { 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 AutomationProperties { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AutomationProperties {} unsafe impl ::core::marker::Sync for AutomationProperties {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AutomationProperty(pub ::windows::core::IInspectable); impl AutomationProperty {} unsafe impl ::windows::core::RuntimeType for AutomationProperty { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.AutomationProperty;{b627195b-3227-4e16-9534-ddece30ddb46})"); } unsafe impl ::windows::core::Interface for AutomationProperty { type Vtable = IAutomationProperty_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb627195b_3227_4e16_9534_ddece30ddb46); } impl ::windows::core::RuntimeName for AutomationProperty { const NAME: &'static str = "Windows.UI.Xaml.Automation.AutomationProperty"; } impl ::core::convert::From<AutomationProperty> for ::windows::core::IUnknown { fn from(value: AutomationProperty) -> Self { value.0 .0 } } impl ::core::convert::From<&AutomationProperty> for ::windows::core::IUnknown { fn from(value: &AutomationProperty) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AutomationProperty { 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 AutomationProperty { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AutomationProperty> for ::windows::core::IInspectable { fn from(value: AutomationProperty) -> Self { value.0 } } impl ::core::convert::From<&AutomationProperty> for ::windows::core::IInspectable { fn from(value: &AutomationProperty) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AutomationProperty { 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 AutomationProperty { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AutomationProperty {} unsafe impl ::core::marker::Sync for AutomationProperty {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AutomationStyleId(pub i32); impl AutomationStyleId { pub const Heading1: AutomationStyleId = AutomationStyleId(70001i32); pub const Heading2: AutomationStyleId = AutomationStyleId(70002i32); pub const Heading3: AutomationStyleId = AutomationStyleId(70003i32); pub const Heading4: AutomationStyleId = AutomationStyleId(70004i32); pub const Heading5: AutomationStyleId = AutomationStyleId(70005i32); pub const Heading6: AutomationStyleId = AutomationStyleId(70006i32); pub const Heading7: AutomationStyleId = AutomationStyleId(70007i32); pub const Heading8: AutomationStyleId = AutomationStyleId(70008i32); pub const Heading9: AutomationStyleId = AutomationStyleId(70009i32); pub const Title: AutomationStyleId = AutomationStyleId(70010i32); pub const Subtitle: AutomationStyleId = AutomationStyleId(70011i32); pub const Normal: AutomationStyleId = AutomationStyleId(70012i32); pub const Emphasis: AutomationStyleId = AutomationStyleId(70013i32); pub const Quote: AutomationStyleId = AutomationStyleId(70014i32); pub const BulletedList: AutomationStyleId = AutomationStyleId(70015i32); } impl ::core::convert::From<i32> for AutomationStyleId { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AutomationStyleId { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AutomationStyleId { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.AutomationStyleId;i4)"); } impl ::windows::core::DefaultType for AutomationStyleId { 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 AutomationTextDecorationLineStyle(pub i32); impl AutomationTextDecorationLineStyle { pub const None: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(0i32); pub const Single: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(1i32); pub const WordsOnly: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(2i32); pub const Double: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(3i32); pub const Dot: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(4i32); pub const Dash: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(5i32); pub const DashDot: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(6i32); pub const DashDotDot: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(7i32); pub const Wavy: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(8i32); pub const ThickSingle: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(9i32); pub const DoubleWavy: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(10i32); pub const ThickWavy: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(11i32); pub const LongDash: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(12i32); pub const ThickDash: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(13i32); pub const ThickDashDot: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(14i32); pub const ThickDashDotDot: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(15i32); pub const ThickDot: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(16i32); pub const ThickLongDash: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(17i32); pub const Other: AutomationTextDecorationLineStyle = AutomationTextDecorationLineStyle(18i32); } impl ::core::convert::From<i32> for AutomationTextDecorationLineStyle { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AutomationTextDecorationLineStyle { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AutomationTextDecorationLineStyle { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.AutomationTextDecorationLineStyle;i4)"); } impl ::windows::core::DefaultType for AutomationTextDecorationLineStyle { 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 AutomationTextEditChangeType(pub i32); impl AutomationTextEditChangeType { pub const None: AutomationTextEditChangeType = AutomationTextEditChangeType(0i32); pub const AutoCorrect: AutomationTextEditChangeType = AutomationTextEditChangeType(1i32); pub const Composition: AutomationTextEditChangeType = AutomationTextEditChangeType(2i32); pub const CompositionFinalized: AutomationTextEditChangeType = AutomationTextEditChangeType(3i32); } impl ::core::convert::From<i32> for AutomationTextEditChangeType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AutomationTextEditChangeType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AutomationTextEditChangeType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.AutomationTextEditChangeType;i4)"); } impl ::windows::core::DefaultType for AutomationTextEditChangeType { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct DockPatternIdentifiers(pub ::windows::core::IInspectable); impl DockPatternIdentifiers { pub fn DockPositionProperty() -> ::windows::core::Result<AutomationProperty> { Self::IDockPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IDockPatternIdentifiersStatics<R, F: FnOnce(&IDockPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<DockPatternIdentifiers, IDockPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for DockPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.DockPatternIdentifiers;{ccd7f4e6-e4f9-47ff-bde7-378b11f78e09})"); } unsafe impl ::windows::core::Interface for DockPatternIdentifiers { type Vtable = IDockPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xccd7f4e6_e4f9_47ff_bde7_378b11f78e09); } impl ::windows::core::RuntimeName for DockPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.DockPatternIdentifiers"; } impl ::core::convert::From<DockPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: DockPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&DockPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &DockPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for DockPatternIdentifiers { 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 DockPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<DockPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: DockPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&DockPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &DockPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for DockPatternIdentifiers { 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 DockPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for DockPatternIdentifiers {} unsafe impl ::core::marker::Sync for DockPatternIdentifiers {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DockPosition(pub i32); impl DockPosition { pub const Top: DockPosition = DockPosition(0i32); pub const Left: DockPosition = DockPosition(1i32); pub const Bottom: DockPosition = DockPosition(2i32); pub const Right: DockPosition = DockPosition(3i32); pub const Fill: DockPosition = DockPosition(4i32); pub const None: DockPosition = DockPosition(5i32); } impl ::core::convert::From<i32> for DockPosition { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DockPosition { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for DockPosition { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.DockPosition;i4)"); } impl ::windows::core::DefaultType for DockPosition { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct DragPatternIdentifiers(pub ::windows::core::IInspectable); impl DragPatternIdentifiers { pub fn DropEffectProperty() -> ::windows::core::Result<AutomationProperty> { Self::IDragPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn DropEffectsProperty() -> ::windows::core::Result<AutomationProperty> { Self::IDragPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn GrabbedItemsProperty() -> ::windows::core::Result<AutomationProperty> { Self::IDragPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IsGrabbedProperty() -> ::windows::core::Result<AutomationProperty> { Self::IDragPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IDragPatternIdentifiersStatics<R, F: FnOnce(&IDragPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<DragPatternIdentifiers, IDragPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for DragPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.DragPatternIdentifiers;{6266e985-4d07-4e80-82eb-8f96690a1a0c})"); } unsafe impl ::windows::core::Interface for DragPatternIdentifiers { type Vtable = IDragPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6266e985_4d07_4e80_82eb_8f96690a1a0c); } impl ::windows::core::RuntimeName for DragPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.DragPatternIdentifiers"; } impl ::core::convert::From<DragPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: DragPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&DragPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &DragPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for DragPatternIdentifiers { 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 DragPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<DragPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: DragPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&DragPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &DragPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for DragPatternIdentifiers { 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 DragPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for DragPatternIdentifiers {} unsafe impl ::core::marker::Sync for DragPatternIdentifiers {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct DropTargetPatternIdentifiers(pub ::windows::core::IInspectable); impl DropTargetPatternIdentifiers { pub fn DropTargetEffectProperty() -> ::windows::core::Result<AutomationProperty> { Self::IDropTargetPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn DropTargetEffectsProperty() -> ::windows::core::Result<AutomationProperty> { Self::IDropTargetPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IDropTargetPatternIdentifiersStatics<R, F: FnOnce(&IDropTargetPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<DropTargetPatternIdentifiers, IDropTargetPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for DropTargetPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.DropTargetPatternIdentifiers;{11865133-a6fe-4634-bd18-0ef612b7b208})"); } unsafe impl ::windows::core::Interface for DropTargetPatternIdentifiers { type Vtable = IDropTargetPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x11865133_a6fe_4634_bd18_0ef612b7b208); } impl ::windows::core::RuntimeName for DropTargetPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.DropTargetPatternIdentifiers"; } impl ::core::convert::From<DropTargetPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: DropTargetPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&DropTargetPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &DropTargetPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for DropTargetPatternIdentifiers { 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 DropTargetPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<DropTargetPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: DropTargetPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&DropTargetPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &DropTargetPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for DropTargetPatternIdentifiers { 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 DropTargetPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for DropTargetPatternIdentifiers {} unsafe impl ::core::marker::Sync for DropTargetPatternIdentifiers {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ExpandCollapsePatternIdentifiers(pub ::windows::core::IInspectable); impl ExpandCollapsePatternIdentifiers { pub fn ExpandCollapseStateProperty() -> ::windows::core::Result<AutomationProperty> { Self::IExpandCollapsePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IExpandCollapsePatternIdentifiersStatics<R, F: FnOnce(&IExpandCollapsePatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<ExpandCollapsePatternIdentifiers, IExpandCollapsePatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for ExpandCollapsePatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.ExpandCollapsePatternIdentifiers;{b006bac0-751b-4d55-92cb-613ec1bdf5d0})"); } unsafe impl ::windows::core::Interface for ExpandCollapsePatternIdentifiers { type Vtable = IExpandCollapsePatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb006bac0_751b_4d55_92cb_613ec1bdf5d0); } impl ::windows::core::RuntimeName for ExpandCollapsePatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.ExpandCollapsePatternIdentifiers"; } impl ::core::convert::From<ExpandCollapsePatternIdentifiers> for ::windows::core::IUnknown { fn from(value: ExpandCollapsePatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&ExpandCollapsePatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &ExpandCollapsePatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ExpandCollapsePatternIdentifiers { 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 ExpandCollapsePatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ExpandCollapsePatternIdentifiers> for ::windows::core::IInspectable { fn from(value: ExpandCollapsePatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&ExpandCollapsePatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &ExpandCollapsePatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ExpandCollapsePatternIdentifiers { 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 ExpandCollapsePatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ExpandCollapsePatternIdentifiers {} unsafe impl ::core::marker::Sync for ExpandCollapsePatternIdentifiers {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ExpandCollapseState(pub i32); impl ExpandCollapseState { pub const Collapsed: ExpandCollapseState = ExpandCollapseState(0i32); pub const Expanded: ExpandCollapseState = ExpandCollapseState(1i32); pub const PartiallyExpanded: ExpandCollapseState = ExpandCollapseState(2i32); pub const LeafNode: ExpandCollapseState = ExpandCollapseState(3i32); } impl ::core::convert::From<i32> for ExpandCollapseState { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ExpandCollapseState { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ExpandCollapseState { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.ExpandCollapseState;i4)"); } impl ::windows::core::DefaultType for ExpandCollapseState { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GridItemPatternIdentifiers(pub ::windows::core::IInspectable); impl GridItemPatternIdentifiers { pub fn ColumnProperty() -> ::windows::core::Result<AutomationProperty> { Self::IGridItemPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ColumnSpanProperty() -> ::windows::core::Result<AutomationProperty> { Self::IGridItemPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ContainingGridProperty() -> ::windows::core::Result<AutomationProperty> { Self::IGridItemPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn RowProperty() -> ::windows::core::Result<AutomationProperty> { Self::IGridItemPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn RowSpanProperty() -> ::windows::core::Result<AutomationProperty> { Self::IGridItemPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IGridItemPatternIdentifiersStatics<R, F: FnOnce(&IGridItemPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<GridItemPatternIdentifiers, IGridItemPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for GridItemPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.GridItemPatternIdentifiers;{757744f1-3285-4fb1-803b-2545bd431599})"); } unsafe impl ::windows::core::Interface for GridItemPatternIdentifiers { type Vtable = IGridItemPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x757744f1_3285_4fb1_803b_2545bd431599); } impl ::windows::core::RuntimeName for GridItemPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.GridItemPatternIdentifiers"; } impl ::core::convert::From<GridItemPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: GridItemPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&GridItemPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &GridItemPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GridItemPatternIdentifiers { 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 GridItemPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GridItemPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: GridItemPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&GridItemPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &GridItemPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GridItemPatternIdentifiers { 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 GridItemPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GridItemPatternIdentifiers {} unsafe impl ::core::marker::Sync for GridItemPatternIdentifiers {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GridPatternIdentifiers(pub ::windows::core::IInspectable); impl GridPatternIdentifiers { pub fn ColumnCountProperty() -> ::windows::core::Result<AutomationProperty> { Self::IGridPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn RowCountProperty() -> ::windows::core::Result<AutomationProperty> { Self::IGridPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IGridPatternIdentifiersStatics<R, F: FnOnce(&IGridPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<GridPatternIdentifiers, IGridPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for GridPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.GridPatternIdentifiers;{c902980f-96c5-450c-9044-7e52c24f9e94})"); } unsafe impl ::windows::core::Interface for GridPatternIdentifiers { type Vtable = IGridPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc902980f_96c5_450c_9044_7e52c24f9e94); } impl ::windows::core::RuntimeName for GridPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.GridPatternIdentifiers"; } impl ::core::convert::From<GridPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: GridPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&GridPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &GridPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GridPatternIdentifiers { 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 GridPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GridPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: GridPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&GridPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &GridPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GridPatternIdentifiers { 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 GridPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GridPatternIdentifiers {} unsafe impl ::core::marker::Sync for GridPatternIdentifiers {} #[repr(transparent)] #[doc(hidden)] pub struct IAnnotationPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAnnotationPatternIdentifiers { type Vtable = IAnnotationPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd475a0c1_48b2_4e40_a6cf_3dc4b638c0de); } #[repr(C)] #[doc(hidden)] pub struct IAnnotationPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IAnnotationPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAnnotationPatternIdentifiersStatics { type Vtable = IAnnotationPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe0e3a35d_d167_46dc_95ab_330af61aebb5); } #[repr(C)] #[doc(hidden)] pub struct IAnnotationPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 IAutomationAnnotation(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationAnnotation { type Vtable = IAutomationAnnotation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb3c30ca_03d8_4618_91bf_e4d84f4af318); } #[repr(C)] #[doc(hidden)] pub struct IAutomationAnnotation_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 AnnotationType) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AnnotationType) -> ::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, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationAnnotationFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationAnnotationFactory { type Vtable = IAutomationAnnotationFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4906fa52_ddc0_4e69_b76b_019d928d822f); } #[repr(C)] #[doc(hidden)] pub struct IAutomationAnnotationFactory_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, r#type: AnnotationType, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, r#type: AnnotationType, element: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationAnnotationStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationAnnotationStatics { type Vtable = IAutomationAnnotationStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe503eab7_4ee5_48cb_b5b8_bbcd46c9d1da); } #[repr(C)] #[doc(hidden)] pub struct IAutomationAnnotationStatics_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationElementIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationElementIdentifiers { type Vtable = IAutomationElementIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe68a63cf_4345_4e2d_8a6a_49cce1fa2dcc); } #[repr(C)] #[doc(hidden)] pub struct IAutomationElementIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationElementIdentifiersStatics { type Vtable = IAutomationElementIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4549399f_8340_4d67_b9bf_8c2ac6a0773a); } #[repr(C)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics_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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 IAutomationElementIdentifiersStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationElementIdentifiersStatics2 { type Vtable = IAutomationElementIdentifiersStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb5cbb1e2_d55f_46a9_9eda_1a4742515dc3); } #[repr(C)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics2_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationElementIdentifiersStatics3 { type Vtable = IAutomationElementIdentifiersStatics3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0f5cbebd_b3eb_4083_adc7_0c2f39bb3543); } #[repr(C)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics3_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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics4(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationElementIdentifiersStatics4 { type Vtable = IAutomationElementIdentifiersStatics4_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5af51f75_5913_4d78_b330_a6f50b73ed9b); } #[repr(C)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics4_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics5(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationElementIdentifiersStatics5 { type Vtable = IAutomationElementIdentifiersStatics5_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x986a8206_de59_42f9_a1e7_62b8af9e756d); } #[repr(C)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics5_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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics6(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationElementIdentifiersStatics6 { type Vtable = IAutomationElementIdentifiersStatics6_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xde52b00d_8328_4eae_8035_f8db99c8bac4); } #[repr(C)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics6_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics7(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationElementIdentifiersStatics7 { type Vtable = IAutomationElementIdentifiersStatics7_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x00f1abb2_742c_446a_a8f6_1672b10d2874); } #[repr(C)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics7_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics8(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationElementIdentifiersStatics8 { type Vtable = IAutomationElementIdentifiersStatics8_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8517b060_806c_5dc5_bc41_891bb5a47adf); } #[repr(C)] #[doc(hidden)] pub struct IAutomationElementIdentifiersStatics8_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationProperties(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationProperties { type Vtable = IAutomationProperties_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x68d7232c_e622_48e9_af0b_1ffa33cc5cba); } #[repr(C)] #[doc(hidden)] pub struct IAutomationProperties_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationPropertiesStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationPropertiesStatics { type Vtable = IAutomationPropertiesStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb618fd7b_32d0_4970_9c42_7c039ac7be78); } #[repr(C)] #[doc(hidden)] pub struct IAutomationPropertiesStatics_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, element: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: ::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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: ::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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: ::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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: ::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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: bool) -> ::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, element: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: ::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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: ::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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::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, element: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: ::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, #[cfg(feature = "UI_Xaml_Automation_Peers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut Peers::AutomationLiveSetting) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Automation_Peers"))] usize, #[cfg(feature = "UI_Xaml_Automation_Peers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: Peers::AutomationLiveSetting) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Automation_Peers"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationPropertiesStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationPropertiesStatics2 { type Vtable = IAutomationPropertiesStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3976547f_7089_4801_8f1d_aab78090d1a0); } #[repr(C)] #[doc(hidden)] pub struct IAutomationPropertiesStatics2_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, #[cfg(feature = "UI_Xaml_Automation_Peers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut Peers::AccessibilityView) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Automation_Peers"))] usize, #[cfg(feature = "UI_Xaml_Automation_Peers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: Peers::AccessibilityView) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Automation_Peers"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationPropertiesStatics3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationPropertiesStatics3 { type Vtable = IAutomationPropertiesStatics3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7b75d735_5cb1_42ad_9b57_5faba8c1867f); } #[repr(C)] #[doc(hidden)] pub struct IAutomationPropertiesStatics3_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, element: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: 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, element: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: 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, element: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationPropertiesStatics4(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationPropertiesStatics4 { type Vtable = IAutomationPropertiesStatics4_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf7d62655_311a_4b7c_a131_524e89cd3cf9); } #[repr(C)] #[doc(hidden)] pub struct IAutomationPropertiesStatics4_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, #[cfg(feature = "UI_Xaml_Automation_Peers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut Peers::AutomationLandmarkType) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Automation_Peers"))] usize, #[cfg(feature = "UI_Xaml_Automation_Peers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: Peers::AutomationLandmarkType) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Automation_Peers"))] usize, 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, element: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationPropertiesStatics5(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationPropertiesStatics5 { type Vtable = IAutomationPropertiesStatics5_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0be35b26_c8f9_41a2_b4db_e6a7a32b0c34); } #[repr(C)] #[doc(hidden)] pub struct IAutomationPropertiesStatics5_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, element: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: bool) -> ::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, element: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: bool) -> ::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, element: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: ::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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: ::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, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationPropertiesStatics6(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationPropertiesStatics6 { type Vtable = IAutomationPropertiesStatics6_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc61e030f_eb49_4e5d_b012_4c1c96c3901b); } #[repr(C)] #[doc(hidden)] pub struct IAutomationPropertiesStatics6_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, element: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationPropertiesStatics7(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationPropertiesStatics7 { type Vtable = IAutomationPropertiesStatics7_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf7e98bf3_8f91_4068_a4ad_b7b402d10a2c); } #[repr(C)] #[doc(hidden)] pub struct IAutomationPropertiesStatics7_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, #[cfg(feature = "UI_Xaml_Automation_Peers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut Peers::AutomationHeadingLevel) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Automation_Peers"))] usize, #[cfg(feature = "UI_Xaml_Automation_Peers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: Peers::AutomationHeadingLevel) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Automation_Peers"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationPropertiesStatics8(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationPropertiesStatics8 { type Vtable = IAutomationPropertiesStatics8_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x432eca20_171a_560d_8524_3e651d3ad6ca); } #[repr(C)] #[doc(hidden)] pub struct IAutomationPropertiesStatics8_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, element: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationPropertiesStatics9(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationPropertiesStatics9 { type Vtable = IAutomationPropertiesStatics9_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2f20b1d1_87b2_5562_8077_da593edafd2d); } #[repr(C)] #[doc(hidden)] pub struct IAutomationPropertiesStatics9_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, #[cfg(feature = "UI_Xaml_Automation_Peers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, result__: *mut Peers::AutomationControlType) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Automation_Peers"))] usize, #[cfg(feature = "UI_Xaml_Automation_Peers")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, element: ::windows::core::RawPtr, value: Peers::AutomationControlType) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Automation_Peers"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAutomationProperty(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAutomationProperty { type Vtable = IAutomationProperty_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb627195b_3227_4e16_9534_ddece30ddb46); } #[repr(C)] #[doc(hidden)] pub struct IAutomationProperty_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IDockPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IDockPatternIdentifiers { type Vtable = IDockPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xccd7f4e6_e4f9_47ff_bde7_378b11f78e09); } #[repr(C)] #[doc(hidden)] pub struct IDockPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IDockPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IDockPatternIdentifiersStatics { type Vtable = IDockPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2b87245c_ed80_4fe5_8eb4_708a39c841e5); } #[repr(C)] #[doc(hidden)] pub struct IDockPatternIdentifiersStatics_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IDragPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IDragPatternIdentifiers { type Vtable = IDragPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6266e985_4d07_4e80_82eb_8f96690a1a0c); } #[repr(C)] #[doc(hidden)] pub struct IDragPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IDragPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IDragPatternIdentifiersStatics { type Vtable = IDragPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2a05379d_1755_4082_9d90_46f1411d7986); } #[repr(C)] #[doc(hidden)] pub struct IDragPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IDropTargetPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IDropTargetPatternIdentifiers { type Vtable = IDropTargetPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x11865133_a6fe_4634_bd18_0ef612b7b208); } #[repr(C)] #[doc(hidden)] pub struct IDropTargetPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IDropTargetPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IDropTargetPatternIdentifiersStatics { type Vtable = IDropTargetPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1b693304_89fb_4b0a_9452_ca2c66aaf9f3); } #[repr(C)] #[doc(hidden)] pub struct IDropTargetPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IExpandCollapsePatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IExpandCollapsePatternIdentifiers { type Vtable = IExpandCollapsePatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb006bac0_751b_4d55_92cb_613ec1bdf5d0); } #[repr(C)] #[doc(hidden)] pub struct IExpandCollapsePatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IExpandCollapsePatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IExpandCollapsePatternIdentifiersStatics { type Vtable = IExpandCollapsePatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd7816fd4_6ee0_4f38_8e14_56ef21adacfd); } #[repr(C)] #[doc(hidden)] pub struct IExpandCollapsePatternIdentifiersStatics_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IGridItemPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGridItemPatternIdentifiers { type Vtable = IGridItemPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x757744f1_3285_4fb1_803b_2545bd431599); } #[repr(C)] #[doc(hidden)] pub struct IGridItemPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IGridItemPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGridItemPatternIdentifiersStatics { type Vtable = IGridItemPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x217d2402_5e46_4d61_8794_b8ee8e774714); } #[repr(C)] #[doc(hidden)] pub struct IGridItemPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 IGridPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGridPatternIdentifiers { type Vtable = IGridPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc902980f_96c5_450c_9044_7e52c24f9e94); } #[repr(C)] #[doc(hidden)] pub struct IGridPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IGridPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGridPatternIdentifiersStatics { type Vtable = IGridPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7bc452f3_a181_4137_8de9_1f9b1a8320ed); } #[repr(C)] #[doc(hidden)] pub struct IGridPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMultipleViewPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMultipleViewPatternIdentifiers { type Vtable = IMultipleViewPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5d5cd3b8_1e12_488b_b0ea_5e6cb89816e1); } #[repr(C)] #[doc(hidden)] pub struct IMultipleViewPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IMultipleViewPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMultipleViewPatternIdentifiersStatics { type Vtable = IMultipleViewPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa9cfa66f_6b84_4d71_9e48_d764d3bcda8e); } #[repr(C)] #[doc(hidden)] pub struct IMultipleViewPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IRangeValuePatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRangeValuePatternIdentifiers { type Vtable = IRangeValuePatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf8760f45_33c9_467d_bc9e_d1515263ace1); } #[repr(C)] #[doc(hidden)] pub struct IRangeValuePatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IRangeValuePatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRangeValuePatternIdentifiersStatics { type Vtable = IRangeValuePatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xce23450f_1c27_457f_b815_7a5e46863dbb); } #[repr(C)] #[doc(hidden)] pub struct IRangeValuePatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IScrollPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IScrollPatternIdentifiers { type Vtable = IScrollPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x366b1003_425c_4951_ae83_d521e73bc696); } #[repr(C)] #[doc(hidden)] pub struct IScrollPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IScrollPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IScrollPatternIdentifiersStatics { type Vtable = IScrollPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4bf8e0a1_fb7f_4fa4_83b3_cfaeb103a685); } #[repr(C)] #[doc(hidden)] pub struct IScrollPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::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 f64) -> ::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 ::windows::core::RawPtr) -> ::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 ISelectionItemPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISelectionItemPatternIdentifiers { type Vtable = ISelectionItemPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2dafa41a_3ef8_4bb5_a02b_3ee1b2274740); } #[repr(C)] #[doc(hidden)] pub struct ISelectionItemPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct ISelectionItemPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISelectionItemPatternIdentifiersStatics { type Vtable = ISelectionItemPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa918d163_487e_4e3e_9f86_7b44acbe27ce); } #[repr(C)] #[doc(hidden)] pub struct ISelectionItemPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ISelectionPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISelectionPatternIdentifiers { type Vtable = ISelectionPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4aa66fb0_e3f7_475f_b78d_f8a83bb730c4); } #[repr(C)] #[doc(hidden)] pub struct ISelectionPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct ISelectionPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISelectionPatternIdentifiersStatics { type Vtable = ISelectionPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x93035b4c_6b50_40a1_b23f_5c78ddbd479a); } #[repr(C)] #[doc(hidden)] pub struct ISelectionPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::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 ISpreadsheetItemPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpreadsheetItemPatternIdentifiers { type Vtable = ISpreadsheetItemPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x84347e19_ca4b_46a2_a794_c87928a3b1ab); } #[repr(C)] #[doc(hidden)] pub struct ISpreadsheetItemPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct ISpreadsheetItemPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISpreadsheetItemPatternIdentifiersStatics { type Vtable = ISpreadsheetItemPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x43658779_5380_4f12_b468_b4f368ad4499); } #[repr(C)] #[doc(hidden)] pub struct ISpreadsheetItemPatternIdentifiersStatics_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IStylesPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IStylesPatternIdentifiers { type Vtable = IStylesPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0e4e201_e89d_436b_8287_4f7903466879); } #[repr(C)] #[doc(hidden)] pub struct IStylesPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IStylesPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IStylesPatternIdentifiersStatics { type Vtable = IStylesPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x528a457a_bc3c_4d48_94af_1f68703ca296); } #[repr(C)] #[doc(hidden)] pub struct IStylesPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ITableItemPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITableItemPatternIdentifiers { type Vtable = ITableItemPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc326e5ad_8077_4c64_98e4_e83bcf1b4389); } #[repr(C)] #[doc(hidden)] pub struct ITableItemPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct ITableItemPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITableItemPatternIdentifiersStatics { type Vtable = ITableItemPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x24c4b923_e9a2_4de9_b2a4_a8b22d0be362); } #[repr(C)] #[doc(hidden)] pub struct ITableItemPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ITablePatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITablePatternIdentifiers { type Vtable = ITablePatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x38d104fe_0d0c_412a_bf8d_51ede683baf5); } #[repr(C)] #[doc(hidden)] pub struct ITablePatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct ITablePatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITablePatternIdentifiersStatics { type Vtable = ITablePatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x75073d25_32c9_4903_aecf_dc3504cbd244); } #[repr(C)] #[doc(hidden)] pub struct ITablePatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::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 ITogglePatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITogglePatternIdentifiers { type Vtable = ITogglePatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7e191f6b_34d4_4ae7_83ac_29f88882d985); } #[repr(C)] #[doc(hidden)] pub struct ITogglePatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct ITogglePatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITogglePatternIdentifiersStatics { type Vtable = ITogglePatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc7f75544_14a5_4f2f_92fc_760524de06ea); } #[repr(C)] #[doc(hidden)] pub struct ITogglePatternIdentifiersStatics_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, ); #[repr(transparent)] #[doc(hidden)] pub struct ITransformPattern2Identifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITransformPattern2Identifiers { type Vtable = ITransformPattern2Identifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x08aaa03d_dea7_402f_8097_9a2783d60e5d); } #[repr(C)] #[doc(hidden)] pub struct ITransformPattern2Identifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct ITransformPattern2IdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITransformPattern2IdentifiersStatics { type Vtable = ITransformPattern2IdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x78963644_11f0_467c_a72b_5dac41c1f6fe); } #[repr(C)] #[doc(hidden)] pub struct ITransformPattern2IdentifiersStatics_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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ITransformPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITransformPatternIdentifiers { type Vtable = ITransformPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe4115b8c_c3c8_4a37_b994_2709a7811665); } #[repr(C)] #[doc(hidden)] pub struct ITransformPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct ITransformPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITransformPatternIdentifiersStatics { type Vtable = ITransformPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4570edab_d705_40c4_a1dc_e9acfcef85f6); } #[repr(C)] #[doc(hidden)] pub struct ITransformPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::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 IValuePatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IValuePatternIdentifiers { type Vtable = IValuePatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x425bf64c_5333_4e41_b470_2bad14ecd085); } #[repr(C)] #[doc(hidden)] pub struct IValuePatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IValuePatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IValuePatternIdentifiersStatics { type Vtable = IValuePatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc247e8f7_adcc_440f_b123_33788a40525a); } #[repr(C)] #[doc(hidden)] pub struct IValuePatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IWindowPatternIdentifiers(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IWindowPatternIdentifiers { type Vtable = IWindowPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x39f78bb4_7032_41e2_b79e_27b74a8628de); } #[repr(C)] #[doc(hidden)] pub struct IWindowPatternIdentifiers_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IWindowPatternIdentifiersStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IWindowPatternIdentifiersStatics { type Vtable = IWindowPatternIdentifiersStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x07d0ad06_6302_4d29_878b_19da03fc228d); } #[repr(C)] #[doc(hidden)] pub struct IWindowPatternIdentifiersStatics_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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MultipleViewPatternIdentifiers(pub ::windows::core::IInspectable); impl MultipleViewPatternIdentifiers { pub fn CurrentViewProperty() -> ::windows::core::Result<AutomationProperty> { Self::IMultipleViewPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn SupportedViewsProperty() -> ::windows::core::Result<AutomationProperty> { Self::IMultipleViewPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IMultipleViewPatternIdentifiersStatics<R, F: FnOnce(&IMultipleViewPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MultipleViewPatternIdentifiers, IMultipleViewPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MultipleViewPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.MultipleViewPatternIdentifiers;{5d5cd3b8-1e12-488b-b0ea-5e6cb89816e1})"); } unsafe impl ::windows::core::Interface for MultipleViewPatternIdentifiers { type Vtable = IMultipleViewPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5d5cd3b8_1e12_488b_b0ea_5e6cb89816e1); } impl ::windows::core::RuntimeName for MultipleViewPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.MultipleViewPatternIdentifiers"; } impl ::core::convert::From<MultipleViewPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: MultipleViewPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&MultipleViewPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &MultipleViewPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MultipleViewPatternIdentifiers { 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 MultipleViewPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MultipleViewPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: MultipleViewPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&MultipleViewPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &MultipleViewPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MultipleViewPatternIdentifiers { 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 MultipleViewPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MultipleViewPatternIdentifiers {} unsafe impl ::core::marker::Sync for MultipleViewPatternIdentifiers {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct RangeValuePatternIdentifiers(pub ::windows::core::IInspectable); impl RangeValuePatternIdentifiers { pub fn IsReadOnlyProperty() -> ::windows::core::Result<AutomationProperty> { Self::IRangeValuePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn LargeChangeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IRangeValuePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn MaximumProperty() -> ::windows::core::Result<AutomationProperty> { Self::IRangeValuePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn MinimumProperty() -> ::windows::core::Result<AutomationProperty> { Self::IRangeValuePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn SmallChangeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IRangeValuePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ValueProperty() -> ::windows::core::Result<AutomationProperty> { Self::IRangeValuePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IRangeValuePatternIdentifiersStatics<R, F: FnOnce(&IRangeValuePatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<RangeValuePatternIdentifiers, IRangeValuePatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for RangeValuePatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.RangeValuePatternIdentifiers;{f8760f45-33c9-467d-bc9e-d1515263ace1})"); } unsafe impl ::windows::core::Interface for RangeValuePatternIdentifiers { type Vtable = IRangeValuePatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf8760f45_33c9_467d_bc9e_d1515263ace1); } impl ::windows::core::RuntimeName for RangeValuePatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.RangeValuePatternIdentifiers"; } impl ::core::convert::From<RangeValuePatternIdentifiers> for ::windows::core::IUnknown { fn from(value: RangeValuePatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&RangeValuePatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &RangeValuePatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for RangeValuePatternIdentifiers { 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 RangeValuePatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<RangeValuePatternIdentifiers> for ::windows::core::IInspectable { fn from(value: RangeValuePatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&RangeValuePatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &RangeValuePatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for RangeValuePatternIdentifiers { 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 RangeValuePatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for RangeValuePatternIdentifiers {} unsafe impl ::core::marker::Sync for RangeValuePatternIdentifiers {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RowOrColumnMajor(pub i32); impl RowOrColumnMajor { pub const RowMajor: RowOrColumnMajor = RowOrColumnMajor(0i32); pub const ColumnMajor: RowOrColumnMajor = RowOrColumnMajor(1i32); pub const Indeterminate: RowOrColumnMajor = RowOrColumnMajor(2i32); } impl ::core::convert::From<i32> for RowOrColumnMajor { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RowOrColumnMajor { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for RowOrColumnMajor { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.RowOrColumnMajor;i4)"); } impl ::windows::core::DefaultType for RowOrColumnMajor { 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 ScrollAmount(pub i32); impl ScrollAmount { pub const LargeDecrement: ScrollAmount = ScrollAmount(0i32); pub const SmallDecrement: ScrollAmount = ScrollAmount(1i32); pub const NoAmount: ScrollAmount = ScrollAmount(2i32); pub const LargeIncrement: ScrollAmount = ScrollAmount(3i32); pub const SmallIncrement: ScrollAmount = ScrollAmount(4i32); } impl ::core::convert::From<i32> for ScrollAmount { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ScrollAmount { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ScrollAmount { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.ScrollAmount;i4)"); } impl ::windows::core::DefaultType for ScrollAmount { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ScrollPatternIdentifiers(pub ::windows::core::IInspectable); impl ScrollPatternIdentifiers { pub fn HorizontallyScrollableProperty() -> ::windows::core::Result<AutomationProperty> { Self::IScrollPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn HorizontalScrollPercentProperty() -> ::windows::core::Result<AutomationProperty> { Self::IScrollPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn HorizontalViewSizeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IScrollPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn NoScroll() -> ::windows::core::Result<f64> { Self::IScrollPatternIdentifiersStatics(|this| unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) }) } pub fn VerticallyScrollableProperty() -> ::windows::core::Result<AutomationProperty> { Self::IScrollPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn VerticalScrollPercentProperty() -> ::windows::core::Result<AutomationProperty> { Self::IScrollPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn VerticalViewSizeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IScrollPatternIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn IScrollPatternIdentifiersStatics<R, F: FnOnce(&IScrollPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<ScrollPatternIdentifiers, IScrollPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for ScrollPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.ScrollPatternIdentifiers;{366b1003-425c-4951-ae83-d521e73bc696})"); } unsafe impl ::windows::core::Interface for ScrollPatternIdentifiers { type Vtable = IScrollPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x366b1003_425c_4951_ae83_d521e73bc696); } impl ::windows::core::RuntimeName for ScrollPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.ScrollPatternIdentifiers"; } impl ::core::convert::From<ScrollPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: ScrollPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&ScrollPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &ScrollPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ScrollPatternIdentifiers { 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 ScrollPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ScrollPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: ScrollPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&ScrollPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &ScrollPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ScrollPatternIdentifiers { 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 ScrollPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ScrollPatternIdentifiers {} unsafe impl ::core::marker::Sync for ScrollPatternIdentifiers {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SelectionItemPatternIdentifiers(pub ::windows::core::IInspectable); impl SelectionItemPatternIdentifiers { pub fn IsSelectedProperty() -> ::windows::core::Result<AutomationProperty> { Self::ISelectionItemPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn SelectionContainerProperty() -> ::windows::core::Result<AutomationProperty> { Self::ISelectionItemPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ISelectionItemPatternIdentifiersStatics<R, F: FnOnce(&ISelectionItemPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<SelectionItemPatternIdentifiers, ISelectionItemPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for SelectionItemPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.SelectionItemPatternIdentifiers;{2dafa41a-3ef8-4bb5-a02b-3ee1b2274740})"); } unsafe impl ::windows::core::Interface for SelectionItemPatternIdentifiers { type Vtable = ISelectionItemPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2dafa41a_3ef8_4bb5_a02b_3ee1b2274740); } impl ::windows::core::RuntimeName for SelectionItemPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.SelectionItemPatternIdentifiers"; } impl ::core::convert::From<SelectionItemPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: SelectionItemPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&SelectionItemPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &SelectionItemPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SelectionItemPatternIdentifiers { 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 SelectionItemPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SelectionItemPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: SelectionItemPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&SelectionItemPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &SelectionItemPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SelectionItemPatternIdentifiers { 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 SelectionItemPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SelectionItemPatternIdentifiers {} unsafe impl ::core::marker::Sync for SelectionItemPatternIdentifiers {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SelectionPatternIdentifiers(pub ::windows::core::IInspectable); impl SelectionPatternIdentifiers { pub fn CanSelectMultipleProperty() -> ::windows::core::Result<AutomationProperty> { Self::ISelectionPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IsSelectionRequiredProperty() -> ::windows::core::Result<AutomationProperty> { Self::ISelectionPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn SelectionProperty() -> ::windows::core::Result<AutomationProperty> { Self::ISelectionPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ISelectionPatternIdentifiersStatics<R, F: FnOnce(&ISelectionPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<SelectionPatternIdentifiers, ISelectionPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for SelectionPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.SelectionPatternIdentifiers;{4aa66fb0-e3f7-475f-b78d-f8a83bb730c4})"); } unsafe impl ::windows::core::Interface for SelectionPatternIdentifiers { type Vtable = ISelectionPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4aa66fb0_e3f7_475f_b78d_f8a83bb730c4); } impl ::windows::core::RuntimeName for SelectionPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.SelectionPatternIdentifiers"; } impl ::core::convert::From<SelectionPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: SelectionPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&SelectionPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &SelectionPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SelectionPatternIdentifiers { 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 SelectionPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SelectionPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: SelectionPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&SelectionPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &SelectionPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SelectionPatternIdentifiers { 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 SelectionPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SelectionPatternIdentifiers {} unsafe impl ::core::marker::Sync for SelectionPatternIdentifiers {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SpreadsheetItemPatternIdentifiers(pub ::windows::core::IInspectable); impl SpreadsheetItemPatternIdentifiers { pub fn FormulaProperty() -> ::windows::core::Result<AutomationProperty> { Self::ISpreadsheetItemPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ISpreadsheetItemPatternIdentifiersStatics<R, F: FnOnce(&ISpreadsheetItemPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<SpreadsheetItemPatternIdentifiers, ISpreadsheetItemPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for SpreadsheetItemPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.SpreadsheetItemPatternIdentifiers;{84347e19-ca4b-46a2-a794-c87928a3b1ab})"); } unsafe impl ::windows::core::Interface for SpreadsheetItemPatternIdentifiers { type Vtable = ISpreadsheetItemPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x84347e19_ca4b_46a2_a794_c87928a3b1ab); } impl ::windows::core::RuntimeName for SpreadsheetItemPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.SpreadsheetItemPatternIdentifiers"; } impl ::core::convert::From<SpreadsheetItemPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: SpreadsheetItemPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&SpreadsheetItemPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &SpreadsheetItemPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpreadsheetItemPatternIdentifiers { 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 SpreadsheetItemPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SpreadsheetItemPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: SpreadsheetItemPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&SpreadsheetItemPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &SpreadsheetItemPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpreadsheetItemPatternIdentifiers { 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 SpreadsheetItemPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SpreadsheetItemPatternIdentifiers {} unsafe impl ::core::marker::Sync for SpreadsheetItemPatternIdentifiers {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct StylesPatternIdentifiers(pub ::windows::core::IInspectable); impl StylesPatternIdentifiers { pub fn ExtendedPropertiesProperty() -> ::windows::core::Result<AutomationProperty> { Self::IStylesPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn FillColorProperty() -> ::windows::core::Result<AutomationProperty> { Self::IStylesPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn FillPatternColorProperty() -> ::windows::core::Result<AutomationProperty> { Self::IStylesPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn FillPatternStyleProperty() -> ::windows::core::Result<AutomationProperty> { Self::IStylesPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ShapeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IStylesPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn StyleIdProperty() -> ::windows::core::Result<AutomationProperty> { Self::IStylesPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn StyleNameProperty() -> ::windows::core::Result<AutomationProperty> { Self::IStylesPatternIdentifiersStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AutomationProperty>(result__) }) } pub fn IStylesPatternIdentifiersStatics<R, F: FnOnce(&IStylesPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<StylesPatternIdentifiers, IStylesPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for StylesPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.StylesPatternIdentifiers;{b0e4e201-e89d-436b-8287-4f7903466879})"); } unsafe impl ::windows::core::Interface for StylesPatternIdentifiers { type Vtable = IStylesPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0e4e201_e89d_436b_8287_4f7903466879); } impl ::windows::core::RuntimeName for StylesPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.StylesPatternIdentifiers"; } impl ::core::convert::From<StylesPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: StylesPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&StylesPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &StylesPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for StylesPatternIdentifiers { 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 StylesPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<StylesPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: StylesPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&StylesPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &StylesPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for StylesPatternIdentifiers { 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 StylesPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for StylesPatternIdentifiers {} unsafe impl ::core::marker::Sync for StylesPatternIdentifiers {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct SupportedTextSelection(pub i32); impl SupportedTextSelection { pub const None: SupportedTextSelection = SupportedTextSelection(0i32); pub const Single: SupportedTextSelection = SupportedTextSelection(1i32); pub const Multiple: SupportedTextSelection = SupportedTextSelection(2i32); } impl ::core::convert::From<i32> for SupportedTextSelection { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for SupportedTextSelection { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for SupportedTextSelection { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.SupportedTextSelection;i4)"); } impl ::windows::core::DefaultType for SupportedTextSelection { 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 SynchronizedInputType(pub i32); impl SynchronizedInputType { pub const KeyUp: SynchronizedInputType = SynchronizedInputType(1i32); pub const KeyDown: SynchronizedInputType = SynchronizedInputType(2i32); pub const LeftMouseUp: SynchronizedInputType = SynchronizedInputType(4i32); pub const LeftMouseDown: SynchronizedInputType = SynchronizedInputType(8i32); pub const RightMouseUp: SynchronizedInputType = SynchronizedInputType(16i32); pub const RightMouseDown: SynchronizedInputType = SynchronizedInputType(32i32); } impl ::core::convert::From<i32> for SynchronizedInputType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for SynchronizedInputType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for SynchronizedInputType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.SynchronizedInputType;i4)"); } impl ::windows::core::DefaultType for SynchronizedInputType { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TableItemPatternIdentifiers(pub ::windows::core::IInspectable); impl TableItemPatternIdentifiers { pub fn ColumnHeaderItemsProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITableItemPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn RowHeaderItemsProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITableItemPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ITableItemPatternIdentifiersStatics<R, F: FnOnce(&ITableItemPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<TableItemPatternIdentifiers, ITableItemPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for TableItemPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.TableItemPatternIdentifiers;{c326e5ad-8077-4c64-98e4-e83bcf1b4389})"); } unsafe impl ::windows::core::Interface for TableItemPatternIdentifiers { type Vtable = ITableItemPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc326e5ad_8077_4c64_98e4_e83bcf1b4389); } impl ::windows::core::RuntimeName for TableItemPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.TableItemPatternIdentifiers"; } impl ::core::convert::From<TableItemPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: TableItemPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&TableItemPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &TableItemPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TableItemPatternIdentifiers { 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 TableItemPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TableItemPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: TableItemPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&TableItemPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &TableItemPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TableItemPatternIdentifiers { 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 TableItemPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TableItemPatternIdentifiers {} unsafe impl ::core::marker::Sync for TableItemPatternIdentifiers {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TablePatternIdentifiers(pub ::windows::core::IInspectable); impl TablePatternIdentifiers { pub fn ColumnHeadersProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITablePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn RowHeadersProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITablePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn RowOrColumnMajorProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITablePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ITablePatternIdentifiersStatics<R, F: FnOnce(&ITablePatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<TablePatternIdentifiers, ITablePatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for TablePatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.TablePatternIdentifiers;{38d104fe-0d0c-412a-bf8d-51ede683baf5})"); } unsafe impl ::windows::core::Interface for TablePatternIdentifiers { type Vtable = ITablePatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x38d104fe_0d0c_412a_bf8d_51ede683baf5); } impl ::windows::core::RuntimeName for TablePatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.TablePatternIdentifiers"; } impl ::core::convert::From<TablePatternIdentifiers> for ::windows::core::IUnknown { fn from(value: TablePatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&TablePatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &TablePatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TablePatternIdentifiers { 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 TablePatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TablePatternIdentifiers> for ::windows::core::IInspectable { fn from(value: TablePatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&TablePatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &TablePatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TablePatternIdentifiers { 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 TablePatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TablePatternIdentifiers {} unsafe impl ::core::marker::Sync for TablePatternIdentifiers {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TogglePatternIdentifiers(pub ::windows::core::IInspectable); impl TogglePatternIdentifiers { pub fn ToggleStateProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITogglePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ITogglePatternIdentifiersStatics<R, F: FnOnce(&ITogglePatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<TogglePatternIdentifiers, ITogglePatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for TogglePatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.TogglePatternIdentifiers;{7e191f6b-34d4-4ae7-83ac-29f88882d985})"); } unsafe impl ::windows::core::Interface for TogglePatternIdentifiers { type Vtable = ITogglePatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7e191f6b_34d4_4ae7_83ac_29f88882d985); } impl ::windows::core::RuntimeName for TogglePatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.TogglePatternIdentifiers"; } impl ::core::convert::From<TogglePatternIdentifiers> for ::windows::core::IUnknown { fn from(value: TogglePatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&TogglePatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &TogglePatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TogglePatternIdentifiers { 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 TogglePatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TogglePatternIdentifiers> for ::windows::core::IInspectable { fn from(value: TogglePatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&TogglePatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &TogglePatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TogglePatternIdentifiers { 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 TogglePatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TogglePatternIdentifiers {} unsafe impl ::core::marker::Sync for TogglePatternIdentifiers {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ToggleState(pub i32); impl ToggleState { pub const Off: ToggleState = ToggleState(0i32); pub const On: ToggleState = ToggleState(1i32); pub const Indeterminate: ToggleState = ToggleState(2i32); } impl ::core::convert::From<i32> for ToggleState { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ToggleState { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ToggleState { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.ToggleState;i4)"); } impl ::windows::core::DefaultType for ToggleState { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TransformPattern2Identifiers(pub ::windows::core::IInspectable); impl TransformPattern2Identifiers { pub fn CanZoomProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITransformPattern2IdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ZoomLevelProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITransformPattern2IdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn MaxZoomProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITransformPattern2IdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn MinZoomProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITransformPattern2IdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ITransformPattern2IdentifiersStatics<R, F: FnOnce(&ITransformPattern2IdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<TransformPattern2Identifiers, ITransformPattern2IdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for TransformPattern2Identifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.TransformPattern2Identifiers;{08aaa03d-dea7-402f-8097-9a2783d60e5d})"); } unsafe impl ::windows::core::Interface for TransformPattern2Identifiers { type Vtable = ITransformPattern2Identifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x08aaa03d_dea7_402f_8097_9a2783d60e5d); } impl ::windows::core::RuntimeName for TransformPattern2Identifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.TransformPattern2Identifiers"; } impl ::core::convert::From<TransformPattern2Identifiers> for ::windows::core::IUnknown { fn from(value: TransformPattern2Identifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&TransformPattern2Identifiers> for ::windows::core::IUnknown { fn from(value: &TransformPattern2Identifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TransformPattern2Identifiers { 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 TransformPattern2Identifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TransformPattern2Identifiers> for ::windows::core::IInspectable { fn from(value: TransformPattern2Identifiers) -> Self { value.0 } } impl ::core::convert::From<&TransformPattern2Identifiers> for ::windows::core::IInspectable { fn from(value: &TransformPattern2Identifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TransformPattern2Identifiers { 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 TransformPattern2Identifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TransformPattern2Identifiers {} unsafe impl ::core::marker::Sync for TransformPattern2Identifiers {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TransformPatternIdentifiers(pub ::windows::core::IInspectable); impl TransformPatternIdentifiers { pub fn CanMoveProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITransformPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn CanResizeProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITransformPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn CanRotateProperty() -> ::windows::core::Result<AutomationProperty> { Self::ITransformPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ITransformPatternIdentifiersStatics<R, F: FnOnce(&ITransformPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<TransformPatternIdentifiers, ITransformPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for TransformPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.TransformPatternIdentifiers;{e4115b8c-c3c8-4a37-b994-2709a7811665})"); } unsafe impl ::windows::core::Interface for TransformPatternIdentifiers { type Vtable = ITransformPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe4115b8c_c3c8_4a37_b994_2709a7811665); } impl ::windows::core::RuntimeName for TransformPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.TransformPatternIdentifiers"; } impl ::core::convert::From<TransformPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: TransformPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&TransformPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &TransformPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TransformPatternIdentifiers { 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 TransformPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TransformPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: TransformPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&TransformPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &TransformPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TransformPatternIdentifiers { 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 TransformPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TransformPatternIdentifiers {} unsafe impl ::core::marker::Sync for TransformPatternIdentifiers {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ValuePatternIdentifiers(pub ::windows::core::IInspectable); impl ValuePatternIdentifiers { pub fn IsReadOnlyProperty() -> ::windows::core::Result<AutomationProperty> { Self::IValuePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn ValueProperty() -> ::windows::core::Result<AutomationProperty> { Self::IValuePatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IValuePatternIdentifiersStatics<R, F: FnOnce(&IValuePatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<ValuePatternIdentifiers, IValuePatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for ValuePatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.ValuePatternIdentifiers;{425bf64c-5333-4e41-b470-2bad14ecd085})"); } unsafe impl ::windows::core::Interface for ValuePatternIdentifiers { type Vtable = IValuePatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x425bf64c_5333_4e41_b470_2bad14ecd085); } impl ::windows::core::RuntimeName for ValuePatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.ValuePatternIdentifiers"; } impl ::core::convert::From<ValuePatternIdentifiers> for ::windows::core::IUnknown { fn from(value: ValuePatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&ValuePatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &ValuePatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ValuePatternIdentifiers { 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 ValuePatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ValuePatternIdentifiers> for ::windows::core::IInspectable { fn from(value: ValuePatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&ValuePatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &ValuePatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ValuePatternIdentifiers { 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 ValuePatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ValuePatternIdentifiers {} unsafe impl ::core::marker::Sync for ValuePatternIdentifiers {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct WindowInteractionState(pub i32); impl WindowInteractionState { pub const Running: WindowInteractionState = WindowInteractionState(0i32); pub const Closing: WindowInteractionState = WindowInteractionState(1i32); pub const ReadyForUserInteraction: WindowInteractionState = WindowInteractionState(2i32); pub const BlockedByModalWindow: WindowInteractionState = WindowInteractionState(3i32); pub const NotResponding: WindowInteractionState = WindowInteractionState(4i32); } impl ::core::convert::From<i32> for WindowInteractionState { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for WindowInteractionState { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for WindowInteractionState { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.WindowInteractionState;i4)"); } impl ::windows::core::DefaultType for WindowInteractionState { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct WindowPatternIdentifiers(pub ::windows::core::IInspectable); impl WindowPatternIdentifiers { pub fn CanMaximizeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IWindowPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn CanMinimizeProperty() -> ::windows::core::Result<AutomationProperty> { Self::IWindowPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IsModalProperty() -> ::windows::core::Result<AutomationProperty> { Self::IWindowPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IsTopmostProperty() -> ::windows::core::Result<AutomationProperty> { Self::IWindowPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn WindowInteractionStateProperty() -> ::windows::core::Result<AutomationProperty> { Self::IWindowPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn WindowVisualStateProperty() -> ::windows::core::Result<AutomationProperty> { Self::IWindowPatternIdentifiersStatics(|this| 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::<AutomationProperty>(result__) }) } pub fn IWindowPatternIdentifiersStatics<R, F: FnOnce(&IWindowPatternIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<WindowPatternIdentifiers, IWindowPatternIdentifiersStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for WindowPatternIdentifiers { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Automation.WindowPatternIdentifiers;{39f78bb4-7032-41e2-b79e-27b74a8628de})"); } unsafe impl ::windows::core::Interface for WindowPatternIdentifiers { type Vtable = IWindowPatternIdentifiers_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x39f78bb4_7032_41e2_b79e_27b74a8628de); } impl ::windows::core::RuntimeName for WindowPatternIdentifiers { const NAME: &'static str = "Windows.UI.Xaml.Automation.WindowPatternIdentifiers"; } impl ::core::convert::From<WindowPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: WindowPatternIdentifiers) -> Self { value.0 .0 } } impl ::core::convert::From<&WindowPatternIdentifiers> for ::windows::core::IUnknown { fn from(value: &WindowPatternIdentifiers) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for WindowPatternIdentifiers { 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 WindowPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<WindowPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: WindowPatternIdentifiers) -> Self { value.0 } } impl ::core::convert::From<&WindowPatternIdentifiers> for ::windows::core::IInspectable { fn from(value: &WindowPatternIdentifiers) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for WindowPatternIdentifiers { 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 WindowPatternIdentifiers { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for WindowPatternIdentifiers {} unsafe impl ::core::marker::Sync for WindowPatternIdentifiers {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct WindowVisualState(pub i32); impl WindowVisualState { pub const Normal: WindowVisualState = WindowVisualState(0i32); pub const Maximized: WindowVisualState = WindowVisualState(1i32); pub const Minimized: WindowVisualState = WindowVisualState(2i32); } impl ::core::convert::From<i32> for WindowVisualState { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for WindowVisualState { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for WindowVisualState { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.WindowVisualState;i4)"); } impl ::windows::core::DefaultType for WindowVisualState { 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 ZoomUnit(pub i32); impl ZoomUnit { pub const NoAmount: ZoomUnit = ZoomUnit(0i32); pub const LargeDecrement: ZoomUnit = ZoomUnit(1i32); pub const SmallDecrement: ZoomUnit = ZoomUnit(2i32); pub const LargeIncrement: ZoomUnit = ZoomUnit(3i32); pub const SmallIncrement: ZoomUnit = ZoomUnit(4i32); } impl ::core::convert::From<i32> for ZoomUnit { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ZoomUnit { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ZoomUnit { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Automation.ZoomUnit;i4)"); } impl ::windows::core::DefaultType for ZoomUnit { type DefaultType = Self; }
use std::fs::File; use std::io::Read; fn main() -> Result<(), std::io::Error> { let mut contents = String::new(); let file_open = File::open("hello_world.rs"); let mut file = match file_open { Ok(f) => f, Err(e) => { eprintln!("Fehler beim öffnen! {:?}", e); } }; file.read_to_string(&mut contents)?; println!("{}", contents); Ok(()) }
use projecteuler::permutation; fn main() { assert_eq!( permutation::permutation_rank_mod(solve(3), 1_000_000_007), 2294 ); assert_eq!( permutation::permutation_rank_mod(solve(5), 1_000_000_007), 641839204 ); assert_eq!(solve_2(3, 1_000_000_007), 2294); assert_eq!(solve_2(5, 1_000_000_007), 641839204); dbg!(solve_2(25, 1_000_000_007)); //dbg!(permutation::permutation_rank_mod(solve(25), 1_000_000_007)); } fn solve(exp: usize) -> Vec<u32> { //idea: construct the permutation and then compute back let n = 2usize.pow(exp as u32); let mut acc = Vec::new(); acc.resize_with(n, || 0); acc[0] = 1; for exp in 0..exp { let elements = 2usize.pow(exp as u32); for i in 0..elements { let j = i + elements; acc[j] = acc[i] * 2; acc[i] = acc[i] * 2 - 1; } if exp >= 2 { let m = elements; acc.swap(m - 1, m); } } acc } //the same as solve but keeps track of smaller elements to the left and right of each value in order to not having to "normalize" the permutation. //reduces runtime from 5s to around 1.5s fn solve_2(exp: usize, m: usize) -> usize { //idea: construct the permutation and then compute back let n = 2usize.pow(exp as u32); let mut perm = Vec::new(); perm.resize_with(n, || (0, 0, 0)); perm[0] = (1, 0, 0); for exp in 0..exp { let elements = 2usize.pow(exp as u32); for i in 0..elements { let j = i + elements; perm[j].0 = perm[i].0 * 2; perm[i].0 = perm[i].0 * 2 - 1; // let left = perm[i].1; let right = perm[i].2; let middle = left + right; perm[i].1 = left; perm[i].2 = middle + right; perm[j].1 = middle + 1 + left; perm[j].2 = right; } if exp >= 2 { let m = elements; perm.swap(m - 1, m); if perm[m - 1].0 < perm[m].0 { perm[m].1 += 1; perm[m].2 -= 1; } else { perm[m - 1].1 -= 1; perm[m - 1].2 += 1; } } } //compute rank of the permutation let mut acc = 0u128; let mut fact = 1; for i in 0..perm.len() { let d = perm[perm.len() - i - 1]; acc += fact * (d.0 - d.1 - 1) as u128; acc %= m as u128; fact *= (i + 1) as u128; fact %= m as u128; } acc as usize }
use anyhow::Result; use std::process::Command; fn main() -> Result<()> { build_ui_files(); vergen::EmitBuilder::builder() .all_cargo() .all_build() .all_git() .all_rustc() .git_describe(true, false, Some("v*")) .emit()?; Ok(()) } fn build_ui_files() { if std::env::var("BUILD_UI").is_err() { return; } let ui_dir = match std::env::current_dir() { Ok(mut d) => { d.push("ui"); d } Err(e) => panic!("Could not get current directory: {}", e), }; let yarn_command = match std::env::var("YARN_PATH") { Ok(c) => c, _ => "yarn".to_string(), }; println!("yarn command: {}", &yarn_command); let ui_build_status = Command::new(yarn_command) .arg("build") .current_dir(ui_dir) .status() .expect("Failed to build UI"); if !ui_build_status.success() { panic!("Could not build UI"); } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type ISpeechRecognitionConstraint = *mut ::core::ffi::c_void; pub type SpeechContinuousRecognitionCompletedEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct SpeechContinuousRecognitionMode(pub i32); impl SpeechContinuousRecognitionMode { pub const Default: Self = Self(0i32); pub const PauseOnRecognition: Self = Self(1i32); } impl ::core::marker::Copy for SpeechContinuousRecognitionMode {} impl ::core::clone::Clone for SpeechContinuousRecognitionMode { fn clone(&self) -> Self { *self } } pub type SpeechContinuousRecognitionResultGeneratedEventArgs = *mut ::core::ffi::c_void; pub type SpeechContinuousRecognitionSession = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct SpeechRecognitionAudioProblem(pub i32); impl SpeechRecognitionAudioProblem { pub const None: Self = Self(0i32); pub const TooNoisy: Self = Self(1i32); pub const NoSignal: Self = Self(2i32); pub const TooLoud: Self = Self(3i32); pub const TooQuiet: Self = Self(4i32); pub const TooFast: Self = Self(5i32); pub const TooSlow: Self = Self(6i32); } impl ::core::marker::Copy for SpeechRecognitionAudioProblem {} impl ::core::clone::Clone for SpeechRecognitionAudioProblem { fn clone(&self) -> Self { *self } } pub type SpeechRecognitionCompilationResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct SpeechRecognitionConfidence(pub i32); impl SpeechRecognitionConfidence { pub const High: Self = Self(0i32); pub const Medium: Self = Self(1i32); pub const Low: Self = Self(2i32); pub const Rejected: Self = Self(3i32); } impl ::core::marker::Copy for SpeechRecognitionConfidence {} impl ::core::clone::Clone for SpeechRecognitionConfidence { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct SpeechRecognitionConstraintProbability(pub i32); impl SpeechRecognitionConstraintProbability { pub const Default: Self = Self(0i32); pub const Min: Self = Self(1i32); pub const Max: Self = Self(2i32); } impl ::core::marker::Copy for SpeechRecognitionConstraintProbability {} impl ::core::clone::Clone for SpeechRecognitionConstraintProbability { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct SpeechRecognitionConstraintType(pub i32); impl SpeechRecognitionConstraintType { pub const Topic: Self = Self(0i32); pub const List: Self = Self(1i32); pub const Grammar: Self = Self(2i32); pub const VoiceCommandDefinition: Self = Self(3i32); } impl ::core::marker::Copy for SpeechRecognitionConstraintType {} impl ::core::clone::Clone for SpeechRecognitionConstraintType { fn clone(&self) -> Self { *self } } pub type SpeechRecognitionGrammarFileConstraint = *mut ::core::ffi::c_void; pub type SpeechRecognitionHypothesis = *mut ::core::ffi::c_void; pub type SpeechRecognitionHypothesisGeneratedEventArgs = *mut ::core::ffi::c_void; pub type SpeechRecognitionListConstraint = *mut ::core::ffi::c_void; pub type SpeechRecognitionQualityDegradingEventArgs = *mut ::core::ffi::c_void; pub type SpeechRecognitionResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct SpeechRecognitionResultStatus(pub i32); impl SpeechRecognitionResultStatus { pub const Success: Self = Self(0i32); pub const TopicLanguageNotSupported: Self = Self(1i32); pub const GrammarLanguageMismatch: Self = Self(2i32); pub const GrammarCompilationFailure: Self = Self(3i32); pub const AudioQualityFailure: Self = Self(4i32); pub const UserCanceled: Self = Self(5i32); pub const Unknown: Self = Self(6i32); pub const TimeoutExceeded: Self = Self(7i32); pub const PauseLimitExceeded: Self = Self(8i32); pub const NetworkFailure: Self = Self(9i32); pub const MicrophoneUnavailable: Self = Self(10i32); } impl ::core::marker::Copy for SpeechRecognitionResultStatus {} impl ::core::clone::Clone for SpeechRecognitionResultStatus { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct SpeechRecognitionScenario(pub i32); impl SpeechRecognitionScenario { pub const WebSearch: Self = Self(0i32); pub const Dictation: Self = Self(1i32); pub const FormFilling: Self = Self(2i32); } impl ::core::marker::Copy for SpeechRecognitionScenario {} impl ::core::clone::Clone for SpeechRecognitionScenario { fn clone(&self) -> Self { *self } } pub type SpeechRecognitionSemanticInterpretation = *mut ::core::ffi::c_void; pub type SpeechRecognitionTopicConstraint = *mut ::core::ffi::c_void; pub type SpeechRecognitionVoiceCommandDefinitionConstraint = *mut ::core::ffi::c_void; pub type SpeechRecognizer = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct SpeechRecognizerState(pub i32); impl SpeechRecognizerState { pub const Idle: Self = Self(0i32); pub const Capturing: Self = Self(1i32); pub const Processing: Self = Self(2i32); pub const SoundStarted: Self = Self(3i32); pub const SoundEnded: Self = Self(4i32); pub const SpeechDetected: Self = Self(5i32); pub const Paused: Self = Self(6i32); } impl ::core::marker::Copy for SpeechRecognizerState {} impl ::core::clone::Clone for SpeechRecognizerState { fn clone(&self) -> Self { *self } } pub type SpeechRecognizerStateChangedEventArgs = *mut ::core::ffi::c_void; pub type SpeechRecognizerTimeouts = *mut ::core::ffi::c_void; pub type SpeechRecognizerUIOptions = *mut ::core::ffi::c_void; pub type VoiceCommandSet = *mut ::core::ffi::c_void;
use Board; use StoneColor; pub fn apply(mut board: &mut Board, color: &StoneColor, coord: (u32, u32)) -> Result<bool, &'static str> { place_stone(&mut board, &color, coord) } fn place_stone(board: &mut Board, color: &StoneColor, coord: (u32, u32)) -> Result<bool, &'static str> { match board.place(&color, coord) { Ok(_) => (), Err(_) => return Result::Err("Failed to place stone"), }; Result::Ok(true) }
extern crate rand; use rand::Rng; fn main() { let mut rng = rand::thread_rng(); let n1: u8 = rng.gen(); }
#[doc = "Reader of register MPCBB2_VCTR27"] pub type R = crate::R<u32, super::MPCBB2_VCTR27>; #[doc = "Writer for register MPCBB2_VCTR27"] pub type W = crate::W<u32, super::MPCBB2_VCTR27>; #[doc = "Register MPCBB2_VCTR27 `reset()`'s with value 0"] impl crate::ResetValue for super::MPCBB2_VCTR27 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `B864`"] pub type B864_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B864`"] pub struct B864_W<'a> { w: &'a mut W, } impl<'a> B864_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `B865`"] pub type B865_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B865`"] pub struct B865_W<'a> { w: &'a mut W, } impl<'a> B865_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `B866`"] pub type B866_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B866`"] pub struct B866_W<'a> { w: &'a mut W, } impl<'a> B866_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `B867`"] pub type B867_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B867`"] pub struct B867_W<'a> { w: &'a mut W, } impl<'a> B867_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `B868`"] pub type B868_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B868`"] pub struct B868_W<'a> { w: &'a mut W, } impl<'a> B868_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `B869`"] pub type B869_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B869`"] pub struct B869_W<'a> { w: &'a mut W, } impl<'a> B869_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `B870`"] pub type B870_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B870`"] pub struct B870_W<'a> { w: &'a mut W, } impl<'a> B870_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `B871`"] pub type B871_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B871`"] pub struct B871_W<'a> { w: &'a mut W, } impl<'a> B871_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `B872`"] pub type B872_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B872`"] pub struct B872_W<'a> { w: &'a mut W, } impl<'a> B872_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `B873`"] pub type B873_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B873`"] pub struct B873_W<'a> { w: &'a mut W, } impl<'a> B873_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `B874`"] pub type B874_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B874`"] pub struct B874_W<'a> { w: &'a mut W, } impl<'a> B874_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `B875`"] pub type B875_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B875`"] pub struct B875_W<'a> { w: &'a mut W, } impl<'a> B875_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `B876`"] pub type B876_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B876`"] pub struct B876_W<'a> { w: &'a mut W, } impl<'a> B876_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `B877`"] pub type B877_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B877`"] pub struct B877_W<'a> { w: &'a mut W, } impl<'a> B877_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `B878`"] pub type B878_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B878`"] pub struct B878_W<'a> { w: &'a mut W, } impl<'a> B878_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `B879`"] pub type B879_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B879`"] pub struct B879_W<'a> { w: &'a mut W, } impl<'a> B879_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `B880`"] pub type B880_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B880`"] pub struct B880_W<'a> { w: &'a mut W, } impl<'a> B880_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `B881`"] pub type B881_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B881`"] pub struct B881_W<'a> { w: &'a mut W, } impl<'a> B881_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `B882`"] pub type B882_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B882`"] pub struct B882_W<'a> { w: &'a mut W, } impl<'a> B882_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `B883`"] pub type B883_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B883`"] pub struct B883_W<'a> { w: &'a mut W, } impl<'a> B883_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `B884`"] pub type B884_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B884`"] pub struct B884_W<'a> { w: &'a mut W, } impl<'a> B884_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `B885`"] pub type B885_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B885`"] pub struct B885_W<'a> { w: &'a mut W, } impl<'a> B885_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `B886`"] pub type B886_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B886`"] pub struct B886_W<'a> { w: &'a mut W, } impl<'a> B886_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `B887`"] pub type B887_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B887`"] pub struct B887_W<'a> { w: &'a mut W, } impl<'a> B887_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `B888`"] pub type B888_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B888`"] pub struct B888_W<'a> { w: &'a mut W, } impl<'a> B888_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `B889`"] pub type B889_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B889`"] pub struct B889_W<'a> { w: &'a mut W, } impl<'a> B889_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `B890`"] pub type B890_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B890`"] pub struct B890_W<'a> { w: &'a mut W, } impl<'a> B890_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `B891`"] pub type B891_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B891`"] pub struct B891_W<'a> { w: &'a mut W, } impl<'a> B891_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `B892`"] pub type B892_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B892`"] pub struct B892_W<'a> { w: &'a mut W, } impl<'a> B892_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `B893`"] pub type B893_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B893`"] pub struct B893_W<'a> { w: &'a mut W, } impl<'a> B893_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `B894`"] pub type B894_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B894`"] pub struct B894_W<'a> { w: &'a mut W, } impl<'a> B894_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `B895`"] pub type B895_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B895`"] pub struct B895_W<'a> { w: &'a mut W, } impl<'a> B895_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 0 - B864"] #[inline(always)] pub fn b864(&self) -> B864_R { B864_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - B865"] #[inline(always)] pub fn b865(&self) -> B865_R { B865_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - B866"] #[inline(always)] pub fn b866(&self) -> B866_R { B866_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - B867"] #[inline(always)] pub fn b867(&self) -> B867_R { B867_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - B868"] #[inline(always)] pub fn b868(&self) -> B868_R { B868_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - B869"] #[inline(always)] pub fn b869(&self) -> B869_R { B869_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - B870"] #[inline(always)] pub fn b870(&self) -> B870_R { B870_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - B871"] #[inline(always)] pub fn b871(&self) -> B871_R { B871_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - B872"] #[inline(always)] pub fn b872(&self) -> B872_R { B872_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - B873"] #[inline(always)] pub fn b873(&self) -> B873_R { B873_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - B874"] #[inline(always)] pub fn b874(&self) -> B874_R { B874_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - B875"] #[inline(always)] pub fn b875(&self) -> B875_R { B875_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - B876"] #[inline(always)] pub fn b876(&self) -> B876_R { B876_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - B877"] #[inline(always)] pub fn b877(&self) -> B877_R { B877_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - B878"] #[inline(always)] pub fn b878(&self) -> B878_R { B878_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - B879"] #[inline(always)] pub fn b879(&self) -> B879_R { B879_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - B880"] #[inline(always)] pub fn b880(&self) -> B880_R { B880_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - B881"] #[inline(always)] pub fn b881(&self) -> B881_R { B881_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - B882"] #[inline(always)] pub fn b882(&self) -> B882_R { B882_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - B883"] #[inline(always)] pub fn b883(&self) -> B883_R { B883_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - B884"] #[inline(always)] pub fn b884(&self) -> B884_R { B884_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - B885"] #[inline(always)] pub fn b885(&self) -> B885_R { B885_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - B886"] #[inline(always)] pub fn b886(&self) -> B886_R { B886_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - B887"] #[inline(always)] pub fn b887(&self) -> B887_R { B887_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - B888"] #[inline(always)] pub fn b888(&self) -> B888_R { B888_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - B889"] #[inline(always)] pub fn b889(&self) -> B889_R { B889_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - B890"] #[inline(always)] pub fn b890(&self) -> B890_R { B890_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - B891"] #[inline(always)] pub fn b891(&self) -> B891_R { B891_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 28 - B892"] #[inline(always)] pub fn b892(&self) -> B892_R { B892_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - B893"] #[inline(always)] pub fn b893(&self) -> B893_R { B893_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - B894"] #[inline(always)] pub fn b894(&self) -> B894_R { B894_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - B895"] #[inline(always)] pub fn b895(&self) -> B895_R { B895_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - B864"] #[inline(always)] pub fn b864(&mut self) -> B864_W { B864_W { w: self } } #[doc = "Bit 1 - B865"] #[inline(always)] pub fn b865(&mut self) -> B865_W { B865_W { w: self } } #[doc = "Bit 2 - B866"] #[inline(always)] pub fn b866(&mut self) -> B866_W { B866_W { w: self } } #[doc = "Bit 3 - B867"] #[inline(always)] pub fn b867(&mut self) -> B867_W { B867_W { w: self } } #[doc = "Bit 4 - B868"] #[inline(always)] pub fn b868(&mut self) -> B868_W { B868_W { w: self } } #[doc = "Bit 5 - B869"] #[inline(always)] pub fn b869(&mut self) -> B869_W { B869_W { w: self } } #[doc = "Bit 6 - B870"] #[inline(always)] pub fn b870(&mut self) -> B870_W { B870_W { w: self } } #[doc = "Bit 7 - B871"] #[inline(always)] pub fn b871(&mut self) -> B871_W { B871_W { w: self } } #[doc = "Bit 8 - B872"] #[inline(always)] pub fn b872(&mut self) -> B872_W { B872_W { w: self } } #[doc = "Bit 9 - B873"] #[inline(always)] pub fn b873(&mut self) -> B873_W { B873_W { w: self } } #[doc = "Bit 10 - B874"] #[inline(always)] pub fn b874(&mut self) -> B874_W { B874_W { w: self } } #[doc = "Bit 11 - B875"] #[inline(always)] pub fn b875(&mut self) -> B875_W { B875_W { w: self } } #[doc = "Bit 12 - B876"] #[inline(always)] pub fn b876(&mut self) -> B876_W { B876_W { w: self } } #[doc = "Bit 13 - B877"] #[inline(always)] pub fn b877(&mut self) -> B877_W { B877_W { w: self } } #[doc = "Bit 14 - B878"] #[inline(always)] pub fn b878(&mut self) -> B878_W { B878_W { w: self } } #[doc = "Bit 15 - B879"] #[inline(always)] pub fn b879(&mut self) -> B879_W { B879_W { w: self } } #[doc = "Bit 16 - B880"] #[inline(always)] pub fn b880(&mut self) -> B880_W { B880_W { w: self } } #[doc = "Bit 17 - B881"] #[inline(always)] pub fn b881(&mut self) -> B881_W { B881_W { w: self } } #[doc = "Bit 18 - B882"] #[inline(always)] pub fn b882(&mut self) -> B882_W { B882_W { w: self } } #[doc = "Bit 19 - B883"] #[inline(always)] pub fn b883(&mut self) -> B883_W { B883_W { w: self } } #[doc = "Bit 20 - B884"] #[inline(always)] pub fn b884(&mut self) -> B884_W { B884_W { w: self } } #[doc = "Bit 21 - B885"] #[inline(always)] pub fn b885(&mut self) -> B885_W { B885_W { w: self } } #[doc = "Bit 22 - B886"] #[inline(always)] pub fn b886(&mut self) -> B886_W { B886_W { w: self } } #[doc = "Bit 23 - B887"] #[inline(always)] pub fn b887(&mut self) -> B887_W { B887_W { w: self } } #[doc = "Bit 24 - B888"] #[inline(always)] pub fn b888(&mut self) -> B888_W { B888_W { w: self } } #[doc = "Bit 25 - B889"] #[inline(always)] pub fn b889(&mut self) -> B889_W { B889_W { w: self } } #[doc = "Bit 26 - B890"] #[inline(always)] pub fn b890(&mut self) -> B890_W { B890_W { w: self } } #[doc = "Bit 27 - B891"] #[inline(always)] pub fn b891(&mut self) -> B891_W { B891_W { w: self } } #[doc = "Bit 28 - B892"] #[inline(always)] pub fn b892(&mut self) -> B892_W { B892_W { w: self } } #[doc = "Bit 29 - B893"] #[inline(always)] pub fn b893(&mut self) -> B893_W { B893_W { w: self } } #[doc = "Bit 30 - B894"] #[inline(always)] pub fn b894(&mut self) -> B894_W { B894_W { w: self } } #[doc = "Bit 31 - B895"] #[inline(always)] pub fn b895(&mut self) -> B895_W { B895_W { w: self } } }
extern crate picl; use picl::repl::Repl; fn main() { let mut repl = Repl::new(); repl.repl() }
use actix_files as fs; use actix_session::Session; use actix_web::http::StatusCode; use actix_web::{get, http, post, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; use askama::Template; use rand::{distributions::Alphanumeric, Rng}; use redis::{Commands, Connection}; use serde::Deserialize; use std::sync::Mutex; use utils::kt_std::*; mod builder; mod utils; #[macro_use] extern crate lazy_static; #[derive(Deserialize)] struct Paste { content: String, } lazy_static! { static ref REDIS_CLIENT: Mutex<Connection> = Mutex::new(builder::redis_client::build("redis://127.0.0.1/")); } #[derive(Template)] #[template(path = "input.html")] struct Input {} #[derive(Template)] #[template(path = "result.html")] struct PasteResult<'a> { url: &'a str, id: &'a str, content: &'a str, } #[actix_rt::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .service(favicon) .service(fs::Files::new("/static", "public/static/").show_files_listing()) .service(index) .service(paste_handler) .service(query_handler) .service(raw_handler) }) .bind("0.0.0.0:8080")? .run() .await } #[get("/favicon.ico")] async fn favicon() -> fs::NamedFile { fs::NamedFile::open("public/static/favicon.ico").unwrap() } #[get("/{id}")] async fn query_handler(req: HttpRequest, id: web::Path<String>) -> impl Responder { PasteResult { url: &req .connection_info() .let_ref(|ctx| format!("{}://{}", ctx.scheme(), ctx.host())), id: &req.uri().to_string(), content: &get_paste(&id), } .let_ref(|paste_result| { HttpResponse::build(StatusCode::OK) .content_type("text/html; charset=utf-8") .body(paste_result.render().unwrap()) }) } #[get("/raw/{id}")] async fn raw_handler(req: HttpRequest, id: web::Path<String>) -> impl Responder { println!("{:?}", id); get_paste(&id) } #[post("/paste")] async fn paste_handler(req: HttpRequest, paste: web::Form<Paste>) -> impl Responder { rand::thread_rng() .sample_iter(&Alphanumeric) .take(5) .collect::<String>() .let_ref(|key| { set_paste(&key, &paste); HttpResponse::Found() .header(http::header::LOCATION, format!("/{}", key)) .finish() }) } #[get("/")] async fn index(session: Session, req: HttpRequest) -> HttpResponse { println!("{:?}", req.match_info()); HttpResponse::build(StatusCode::OK) .content_type("text/html; charset=utf-8") .body(Input {}.render().unwrap()) } fn set_paste(key: &String, paste: &web::Form<Paste>) -> redis::RedisResult<()> { let _: () = REDIS_CLIENT.lock().unwrap().set(key, &paste.content)?; Ok(()) } fn get_paste(key: &String) -> String { REDIS_CLIENT .lock() .unwrap() .get(key) .unwrap_or("None".to_string()) }
use mtree::MTree; pub fn node_count(tree: &MTree) -> usize { let sum_child_nodes: usize = tree.get_children().iter().map(|t| node_count(t)).sum(); 1 + sum_child_nodes } #[cfg(test)] mod tests { use super::*; #[test] fn test_node_count() { assert_eq!(node_count(&MTree::leaf('a')), 1); assert_eq!(node_count(&MTree::node('a', vec![MTree::leaf('f')])), 2); assert_eq!( node_count(&MTree::node( 'a', vec![ MTree::node('f', vec![MTree::leaf('g')]), MTree::leaf('c'), MTree::node('b', vec![MTree::leaf('d'), MTree::leaf('e')]) ] )), 7 ); } }
fn main() { let _s = String::new(); let data = "initial contents"; let _s = data.to_string(); let _s = "initial contents".to_string(); let mut s = String::from("foo"); s.push_str("bar"); let mut s1 = String::from("foo"); let s2 = "bar"; s1.push_str(s2); println!("s2 is {}", s2); let s = String::from("Hello, ") + "world"; // actual signature of add is (String, &str) println!("{}", s); let hello = String::from("Hello, "); let world = String::from("World"); let s = hello + &world; // deref coercion -> in later lessons, &s2 = &s2[..] here println!("{}", s); let s1 = "tic".to_string(); let s2 = "tac".to_string(); let s3 = "toe".to_string(); let s = s1 + "-" + &s2 + "-" + &s3; // s1 gave up oenership to data after addition to s println!("1 - {}", s); let s1 = "tic".to_string(); // re-initializing tic as s1 gave up ownership let s = format!("{}-{}-{}", s1, s2, s3); println!("2 - {}", s); let s = "नमस्ते"; for c in s.chars() { println!("{}", c); } for b in s.bytes() { println!("{}", b); } } fn hello() { let _hello = String::from("السلام عليكم"); let _hello = String::from("Dobrý den"); let _hello = String::from("Hello"); let _hello = String::from("שָׁלוֹם"); let _hello = String::from("नमस्ते"); let _hello = String::from("こんにちは"); let _hello = String::from("안녕하세요"); let _hello = String::from("你好"); let _hello = String::from("Olá"); let _hello = String::from("Здравствуйте"); let _hello = String::from("Hola"); }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fmt::Display; use std::fmt::Formatter; use anyerror::AnyError; use common_exception::ErrorCode; use serde::Deserialize; use serde::Serialize; use crate::principal::UserGrantSet; #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Default)] #[serde(default)] pub struct RoleInfo { pub name: String, pub grants: UserGrantSet, } /// Error when ser/de RoleInfo #[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] pub struct RoleInfoSerdeError { pub message: String, pub source: AnyError, } impl RoleInfo { pub fn new(name: &str) -> Self { Self { name: name.to_string(), grants: UserGrantSet::empty(), } } pub fn identity(&self) -> &str { &self.name } } impl TryFrom<Vec<u8>> for RoleInfo { type Error = RoleInfoSerdeError; fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> { match serde_json::from_slice(&value) { Ok(role_info) => Ok(role_info), Err(serialize_error) => Err(RoleInfoSerdeError { message: "Cannot deserialize RoleInfo from bytes".to_string(), source: AnyError::new(&serialize_error), }), } } } impl Display for RoleInfoSerdeError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{} cause: {}", self.message, self.source) } } impl From<RoleInfoSerdeError> for ErrorCode { fn from(e: RoleInfoSerdeError) -> Self { ErrorCode::InvalidReply(e.to_string()) } }
extern crate chrono; extern crate env_logger; #[macro_use] extern crate log; extern crate robohome_crypto; extern crate robohome_shared; extern crate serde_json; extern crate uuid; extern crate warp; use chrono::{Duration, Utc}; use robohome_crypto::{ bufify_string, gen_pair as gen_auth_key_pair, gen_shared_secret, }; use robohome_shared::{ data::{ get_all_switches, get_auth_age, get_private_shared, new_token, update_flip as db_update_flip, update_switch as db_update_switch, Flip, ScheduledFlip, Switch, }, ipc::send, Error, }; use serde_json::to_string; use std::str::FromStr; use uuid::Uuid; use warp::{ body::{concat, content_length_limit, json}, get2, header, http::Response, path, post2, put2, Buf, Filter, Reply, }; fn main() { ::std::env::set_var("RUST_LOG", "info"); env_logger::init(); let auth_head = header("Authorization"); let flipping = post2() .and(path("flip")) .and(auth_head) .and(json()) .map(flip_switch); let all_switches = get2() .and(path("switches")) .and(auth_head) .map(get_switches); let switch_flips = put2() .and(path("switch")) .and(auth_head) .and(json()) .map(get_switch_flips); let key_exchange = post2() .and(path("key-exchange")) .and(auth_head) .and(content_length_limit(64)) .and(concat()) .map(check_auth_token); let update_switch = post2() .and(path("update_switch")) .and(auth_head) .and(json()) .map(update_switch); let update_flip = post2() .and(path("update_flip")) .and(auth_head) .and(json()) .map(update_flip); let routes = flipping .or(switch_flips) .or(all_switches) .or(update_switch) .or(update_flip) .or(key_exchange) .or(warp::filters::fs::dir("public")); warp::serve(routes.with(warp::log("robohome_flipper"))).run(([0, 0, 0, 0], 3434)); } fn check_auth_header(header: String) -> Result<bool, Error> { let (id, public) = break_auth_header(&header)?; let (private, shared) = get_private_shared(&id)?; let computed_shared = gen_shared_secret(&private, &public).ok_or(Error::new("Invalid public key provided"))?; Ok(&*computed_shared == shared.as_slice()) } fn break_auth_header(header: &str) -> Result<(Uuid, Vec<u8>), Error> { let prefix = "Bearer "; if !header.starts_with(prefix) { return Err(Error::new("Invalid value in Auth header")); } let header = &header[prefix.len()..]; let mut split = header.split('$'); let id_str = split .next() .ok_or(Error::new("Invalid value in Auth header"))?; let public = split .next() .ok_or(Error::new("Invalid value in Auth header"))?; let id = Uuid::from_str(id_str)?; let public = bufify_string(public)?; Ok((id, public)) } fn flip_switch(header: String, flip: Flip) -> impl Reply { info!("POST /flip: {:?}", flip); match check_auth_header(header) { Ok(success) => { if !success { return Response::builder() .status(403) .body(format!(r#"{{"message": "Unauthorized"}}"#)); } } Err(e) => { let (status, body) = error_response(&e); return Response::builder().status(status).body(body); } } match send("switches", &flip) { Ok(_) => Response::builder().body(format!(r#"{{"flipped": {}}}"#, flip.code)), Err(e) => { let (status, body) = error_response(&e); Response::builder().status(status).body(body) } } } fn get_switch_flips(header: String, switch: Switch) -> impl Reply { info!("PUT /switch"); match check_auth_header(header) { Ok(success) => { if !success { return Response::builder() .status(403) .body(format!(r#"{{"message": "Unauthorized"}}"#)); } } Err(e) => { let (status, body) = error_response(&e); return Response::builder().status(status).body(body); } } let (status, body) = get_switch_flips_response(switch); Response::builder().status(status).body(body) } fn get_switches(header: String) -> impl Reply { info!("GET /switches"); match check_auth_header(header) { Ok(success) => { if !success { return Response::builder() .status(403) .body(format!(r#"{{"message": "Unauthorized"}}"#)); } } Err(e) => { let (status, body) = error_response(&e); return Response::builder().status(status).body(body); } } let (status, body) = get_switches_response(); Response::builder().status(status).body(body) } fn update_switch(header: String, switch: Switch) -> impl Reply { info!("POST /switch {:?}", switch); match check_auth_header(header) { Ok(success) => { if !success { return Response::builder() .status(403) .body(format!(r#"{{"message": "Unauthorized"}}"#)); } } Err(e) => { let (status, body) = error_response(&e); return Response::builder().status(status).body(body); } } let (status, body) = get_update_switch_response(switch); Response::builder().status(status).body(body) } fn update_flip(header: String, flip: ScheduledFlip) -> impl Reply { info!("POST /flip {:?}", flip); match check_auth_header(header) { Ok(success) => { if !success { return Response::builder() .status(401) .body(format!(r#"{{"message": "Unauthorized"}}"#)); } } Err(e) => { let (status, body) = error_response(&e); return Response::builder().status(status).body(body); } } let (status, body) = get_update_flip_response(flip); Response::builder().status(status).body(body) } fn get_update_flip_response(flip: ScheduledFlip) -> (u16, String) { match db_update_flip( flip.id, flip.hour, flip.minute, flip.dow, flip.direction, flip.kind, ) { Ok(flip) => match to_string(&flip) { Ok(body) => (200, body), Err(e) => error_response(&Error::from(e)), }, Err(e) => error_response(&e), } } fn get_update_switch_response(switch: Switch) -> (u16, String) { match db_update_switch(switch.id, &switch.name, switch.on_code, switch.off_code) { Ok(sw) => match to_string(&sw) { Ok(body) => (200, body), Err(e) => error_response(&Error::from(e)), }, Err(e) => error_response(&e), } } fn get_switches_response() -> (u16, String) { match get_all_switches() { Ok(switches) => match to_string(&switches) { Ok(body) => (200, body), Err(e) => error_response(&Error::from(e)), }, Err(e) => error_response(&e), } } fn get_switch_flips_response(switch: Switch) -> (u16, String) { match robohome_shared::data::get_flips_for_switch(switch.id) { Ok(flips) => match to_string(&flips) { Ok(body) => (200, body), Err(e) => error_response(&Error::from(e)), }, Err(e) => error_response(&e), } } fn check_auth_token(header: String, body: warp::body::FullBody) -> impl Reply { info!("POST /key-exchange"); let (status, body) = match check_auth_token_response(&header, body) { Ok((status, body)) => (status, body), Err(e) => error_response(&e), }; Response::builder().status(status).body(body) } fn check_auth_token_response( header: &String, body: warp::body::FullBody, ) -> Result<(u16, String), Error> { info!("check_auth_token_response {}", header); let start = "Bearer ".len(); let token = &header[start..]; let token = Uuid::from_str(token)?; info!("parsed token"); let age = get_auth_age(&token)?; info!("got auth age"); if Utc::now().signed_duration_since(age) > Duration::days(1) { return Ok((401, format!(r#"{{"status": "expired"}}"#))); } info!("Extracting body key"); let buf = body.bytes(); info!("Generating server pair"); let key_pair = gen_auth_key_pair(); info!("getting server private key"); let my_private = key_pair.sized_priv(); info!("generating shared key"); let shared = gen_shared_secret(&my_private, buf) .ok_or(Error::new("Failed to generate shared secret"))?; info!("storing key info"); new_token(&my_private, &shared, token)?; Ok((200, format!(r#"{{"status": "success"}}"#))) } fn error_response(e: &Error) -> (u16, String) { (500, format!(r#"{{ "message": "{}" }}"#, e)) }
//! __Rust Life Search__, or __rlifesrc__, //! is a Game of Life pattern searcher written in Rust. //! //! The program is based on David Bell's //! [lifesrc](https://github.com/DavidKinder/Xlife/tree/master/Xlife35/source/lifesearch) //! and Jason Summers's [WinLifeSearch](https://github.com/jsummers/winlifesearch/), //! using [an algorithm invented by Dean Hickerson](https://github.com/DavidKinder/Xlife/blob/master/Xlife35/source/lifesearch/ORIGIN). //! //! Compared to WinLifeSearch, rlifesrc is still slower, and lacks many important features. //! But it supports non-totalistic Life-like rules. //! //! This is the library for rlifesrc. There is also a //! [command-line tool with a TUI](https://github.com/AlephAlpha/rlifesrc/tree/master/tui) //! and a [web app complied to WASM](https://github.com/AlephAlpha/rlifesrc/tree/master/web). //! //! You can try the web app [here](https://alephalpha.github.io/rlifesrc/). //! //! # Example //! //! Finds the [25P3H1V0.1](https://conwaylife.com/wiki/25P3H1V0.1) spaceship. //! //! ```rust //! use rlifesrc_lib::{Config, Status}; //! //! // Configures the world. //! let config = Config::new(16, 5, 3).set_translate(0, 1); //! //! // Creates the world. //! let mut search = config.world().unwrap(); //! //! // Searches and displays the generation 0 of the result. //! if let Status::Found = search.search(None) { //! println!("{}", search.rle_gen(0)) //! } //! ``` //! //! Search result: //! //! ``` plaintext //! x = 16, y = 5, rule = B3/S23 //! ........o.......$ //! .oo.ooo.ooo.....$ //! .oo....o..oo.oo.$ //! o..o.oo...o..oo.$ //! ............o..o! //! ``` mod cells; mod config; mod error; pub mod rules; mod search; mod traits; mod world; #[cfg(feature = "serialize")] mod save; pub use cells::{State, ALIVE, DEAD}; pub use config::{Config, NewState, SearchOrder, Symmetry, Transform}; pub use error::Error; pub use search::Status; pub use traits::Search; pub use world::World; #[cfg(feature = "serialize")] pub use save::WorldSer;
use proconio::input; fn main() { input! { n: usize, k: usize, points: [(i64, i64); n], }; if k == 1 { println!("Infinity"); return; } // (y2 - y1) * x - (x2 - x1) * y + (x2 - x1) * y1 - (y2 - y1) * x1 = 0 let mut x_axis = Vec::new(); let mut y_axis = Vec::new(); let mut abc = Vec::new(); for i in 0..n { for j in (i + 1)..n { let (x1, y1) = points[i]; let (x2, y2) = points[j]; if x1 == x2 { x_axis.push(x1); } else if y1 == y2 { y_axis.push(y1); } else { let a = y2 - y1; let b = -(x2 - x1); let c = (x2 - x1) * y1 - (y2 - y1) * x1; let g = gcd(a.abs() as u64, b.abs() as u64); let g = gcd(g, c.abs() as u64); let a = a / g as i64; let b = b / g as i64; let c = c / g as i64; if a > 0 { abc.push((a, b, c)); } else if a < 0 { abc.push((-a, -b, -c)); } else { unreachable!(); } } } } x_axis.sort(); x_axis.dedup(); y_axis.sort(); y_axis.dedup(); abc.sort(); abc.dedup(); let mut ans = 0; for x1 in x_axis { let mut m = 0; for &(x, _) in &points { if x == x1 { m += 1; } } if m >= k { ans += 1; } } for y1 in y_axis { let mut m = 0; for &(_, y) in &points { if y == y1 { m += 1; } } if m >= k { ans += 1; } } for (a, b, c) in abc { let mut m = 0; for &(x, y) in &points { if a * x + b * y + c == 0 { m += 1; } } if m >= k { ans += 1; } } println!("{}", ans); } fn gcd(a: u64, b: u64) -> u64 { if b == 0 { a } else { gcd(b, a % b) } }
mod vertex; use ecs::{Entity, ECS}; use renderer::{ RendererDevice, Texture, TextureFiltering, TextureStorage, TextureWrapping, }; use std::path::Path; use vertex::Vertex; pub fn load(ecs: &mut ECS) { let context = ecs.resources.get_mut::<RendererDevice>().unwrap(); let idx1 = context.register_texture(Texture::new_initialized( TextureWrapping::ClampToEdge, TextureFiltering::Pixelated, TextureStorage::from_image(&Path::new("textures/normal.jpg")), )); let idx2 = context.register_texture(Texture::new_initialized( TextureWrapping::ClampToEdge, TextureFiltering::Pixelated, TextureStorage::from_image(&Path::new("textures/box.png")), )); let idx3 = context.register_texture(Texture::new_initialized( TextureWrapping::ClampToEdge, TextureFiltering::Pixelated, TextureStorage::from_image(&Path::new("textures/wood.jpg")), )); let idx4 = context.register_texture(Texture::new_initialized( TextureWrapping::ClampToEdge, TextureFiltering::Pixelated, TextureStorage::from_image(&Path::new("textures/metal.jpg")), )); ecs.add_entity( Entity::new() .with(context.new_mesh( &Path::new("shaders/multi-texture.glsl"), vec![ Vertex::new(0.5, 2.0 + 0.5, 0.0, 1.0, 1.0), Vertex::new(-0.5, 2.0 + -0.5, 0.0, 0.0, 0.0), Vertex::new(0.5, 2.0 + -0.5, 0.0, 1.0, 0.0), Vertex::new(-0.5, 2.0 + 0.5, 0.0, 0.0, 1.0), ], Some(vec![0, 1, 2, 0, 3, 1]), vec![ idx1, idx2 ], None, )), ); ecs.add_entity( Entity::new() .with(context.new_mesh( &Path::new("shaders/multi-texture.glsl"), vec![ Vertex::new(0.5, 3.0 + 0.5, 0.0, 1.0, 1.0), Vertex::new(-0.5, 3.0 + -0.5, 0.0, 0.0, 0.0), Vertex::new(0.5, 3.0 + -0.5, 0.0, 1.0, 0.0), Vertex::new(-0.5, 3.0 + 0.5, 0.0, 0.0, 1.0), ], Some(vec![0, 1, 2, 0, 3, 1]), vec![ idx3, idx4 ], None, )), ); }
use {Poll, Async}; use stream::Stream; /// A stream which emits single element and then EOF. /// /// This stream will never block and is always ready. #[derive(Debug)] #[must_use = "streams do nothing unless polled"] pub struct Once<T, E>(Option<Result<T, E>>); /// Creates a stream of single element /// /// ```rust /// use futures::*; /// /// let mut stream = stream::once::<(), _>(Err(17)); /// assert_eq!(Err(17), stream.poll()); /// assert_eq!(Ok(Async::Ready(None)), stream.poll()); /// ``` pub fn once<T, E>(item: Result<T, E>) -> Once<T, E> { Once(Some(item)) } impl<T, E> Stream for Once<T, E> { type Item = T; type Error = E; fn poll(&mut self) -> Poll<Option<T>, E> { match self.0.take() { Some(Ok(e)) => Ok(Async::Ready(Some(e))), Some(Err(e)) => Err(e), None => Ok(Async::Ready(None)), } } }
use crate::{DocBase, VarType}; const DESCRIPTION: &'static str = r#" Difference between current value and previous, `x - x[y]`. "#; const PINE_FN_ARGUMENTS: &'static str = " **source (series(float))** **length (int)** Offset from the current bar to the previous bar. Optional, if not given, length = 1 is used. "; pub fn gen_doc() -> Vec<DocBase> { let fn_doc = DocBase { var_type: VarType::Function, name: "change", signatures: vec![], description: DESCRIPTION, example: "", returns: "Differences series.", arguments: PINE_FN_ARGUMENTS, remarks: "", links: "", }; vec![fn_doc] }
use anyhow::Result; fn part1(input: &[u64]) -> u64 { let (_, ones, threes) = input .iter() .fold((0, 0, 0), |(last, ones, threes), next| match next - last { 1 => (*next, ones + 1, threes), 2 => (*next, ones, threes), 3 => (*next, ones, threes + 1), _ => panic!("Too much differrence"), }); ones * (threes + 1) } fn part2(input: &[u64]) -> u64 { input .iter() .fold([(0, 0), (0, 0), (0, 1)], |history, next| { let cnt = history .iter() .filter(|(v, _)| next - v <= 3) .map(|(_, cnt)| cnt) .sum(); [history[1], history[2], (*next, cnt)] })[2] .1 } fn main() -> Result<()> { let mut input = common::std_input_vec()?; input.sort(); println!("{}", input.len()); println!("Part1: {}", part1(&input)); println!("Part2: {}", part2(&input)); Ok(()) }
/*! Prefix-types are types that derive StableAbi along with the `#[sabi(kind(Prefix(....)))]` helper attribute. This is mostly intended for **vtables** and **modules**. Prefix-types cannot directly be passed through ffi, instead they must be converted to the type declared with `prefix_ref= Foo_Ref`, and then pass that instead. To convert `Foo` to `Foo_Ref` you can use any of (non-exhaustive list): - `PrefixTypeTrait::leak_into_prefix`:<br> Which does the conversion directly,but leaks the value. - `prefix_type::WithMetadata::new`:<br> Use this if you need a compiletime constant.<br> First create a `StaticRef<WithMetadata<Self>>` constant using the [`staticref`] macro, then construct a `Foo_Ref` constant with `Foo_Ref(THE_STATICREF_CONSTANT.as_prefix())`.<br> There are two examples of this, [for modules](#module_construction),and [for vtables](#vtable_construction) All the fields in the `DerivingType` can be accessed in `DerivingType_Ref` using accessor methods named the same as the fields. # Version compatibility ### Adding fields To ensure that libraries stay abi compatible, the first minor version of the library must use the `#[sabi(last_prefix_field)]` attribute on some field, and every minor version after that must add fields at the end (never moving that attribute). Changing the field that `#[sabi(last_prefix_field)]` is applied to is a breaking change. Getter methods for fields after the one to which `#[sabi(last_prefix_field)]` was applied to will return `Option<FieldType>` by default,because those fields might not exist (the struct might come from a previous version of the library). To override how to deal with nonexistent fields, use the `#[sabi(missing_field())]` attribute, applied to either the struct or the field. ### Alignment To ensure that users can define empty vtables/modules that can be extended in semver compatible versions, this library forces the struct converted to ffi-safe form to have an alignment at least that of usize. You must ensure that newer versions don't change the alignment of the struct, because that makes it ABI incompatible. # Grammar Reference For the grammar reference,you can look at the documentation for [`#[derive(StableAbi)]`](../../derive.StableAbi.html). # Examples ### Example 1 Declaring a Prefix-type. ``` use abi_stable::{ std_types::{RDuration, RStr}, StableAbi, }; #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref = Module_Ref)))] #[sabi(missing_field(panic))] pub struct Module { pub lib_name: RStr<'static>, #[sabi(last_prefix_field)] pub elapsed: extern "C" fn() -> RDuration, pub description: RStr<'static>, } # fn main(){} ``` In this example: - `#[sabi(kind(Prefix(prefix_ref= Module_Ref)))]` declares this type as being a prefix-type with an ffi-safe pointer called `Module_Ref` to which `Module` can be converted into. - `#[sabi(missing_field(panic))]` makes the field accessors panic when attempting to access nonexistent fields instead of the default of returning an `Option<FieldType>`. - `#[sabi(last_prefix_field)]`means that it is the last field in the struct that was defined in the first compatible version of the library (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), requiring new fields to always be added below preexisting ones. <span id="module_construction"></span> ### Constructing a module This example demonstrates how you can construct a module. For constructing a vtable, you can look at [the next example](#vtable_construction) ``` use abi_stable::{ extern_fn_panic_handling, prefix_type::{PrefixTypeTrait, WithMetadata}, staticref, std_types::{RDuration, RStr}, StableAbi, }; fn main() { assert_eq!(MODULE_REF.lib_name().as_str(), "foo"); assert_eq!(MODULE_REF.elapsed()(1000), RDuration::from_secs(1)); assert_eq!(MODULE_REF.description().as_str(), "this is a module field"); } #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref = Module_Ref)))] #[sabi(missing_field(panic))] pub struct Module<T> { pub lib_name: RStr<'static>, #[sabi(last_prefix_field)] pub elapsed: extern "C" fn(T) -> RDuration, pub description: RStr<'static>, } impl Module<u64> { // This macro declares a `StaticRef<WithMetadata<Module<u64>>>` constant. staticref!(const MODULE_VAL: WithMetadata<Module<u64>> = WithMetadata::new( Module{ lib_name: RStr::from_str("foo"), elapsed, description: RStr::from_str("this is a module field"), }, )); } const MODULE_REF: Module_Ref<u64> = Module_Ref(Module::MODULE_VAL.as_prefix()); extern "C" fn elapsed(milliseconds: u64) -> RDuration { extern_fn_panic_handling! { RDuration::from_millis(milliseconds) } } ``` <span id="vtable_construction"></span> ### Constructing a vtable This example demonstrates how you can construct a vtable. ```rust use abi_stable::{ extern_fn_panic_handling, marker_type::ErasedObject, prefix_type::{PrefixTypeTrait, WithMetadata}, staticref, StableAbi, }; fn main() { unsafe { let vtable = MakeVTable::<u64>::MAKE; assert_eq!( vtable.get_number()(&3u64 as *const u64 as *const ErasedObject), 12, ); } unsafe { let vtable = MakeVTable::<u8>::MAKE; assert_eq!( vtable.get_number()(&128u8 as *const u8 as *const ErasedObject), 512, ); } } #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref = VTable_Ref)))] #[sabi(missing_field(panic))] pub struct VTable { #[sabi(last_prefix_field)] pub get_number: unsafe extern "C" fn(*const ErasedObject) -> u64, } // A dummy struct, used purely for its associated constants. struct MakeVTable<T>(T); impl<T> MakeVTable<T> where T: Copy + Into<u64>, { unsafe extern "C" fn get_number(this: *const ErasedObject) -> u64 { extern_fn_panic_handling! { (*this.cast::<T>()).into() * 4 } } // This macro declares a `StaticRef<WithMetadata<VTable>>` constant. staticref! {pub const VAL: WithMetadata<VTable> = WithMetadata::new( VTable{get_number: Self::get_number}, )} pub const MAKE: VTable_Ref = VTable_Ref(Self::VAL.as_prefix()); } ``` <span id="example2"></span> ### Example 2:Declaring a type with a VTable Here is the implementation of a Box-like type,which uses a vtable that is a prefix type. ``` use std::{ marker::PhantomData, mem::ManuallyDrop, ops::{Deref, DerefMut}, }; use abi_stable::{ extern_fn_panic_handling, pointer_trait::{CallReferentDrop, TransmuteElement}, prefix_type::{PrefixTypeTrait, WithMetadata}, staticref, StableAbi, }; /// An ffi-safe `Box<T>` #[repr(C)] #[derive(StableAbi)] pub struct BoxLike<T> { data: *mut T, vtable: BoxVtable_Ref<T>, _marker: PhantomData<T>, } impl<T> BoxLike<T> { pub fn new(value: T) -> Self { let box_ = Box::new(value); Self { data: Box::into_raw(box_), vtable: BoxVtable::VTABLE, _marker: PhantomData, } } fn vtable(&self) -> BoxVtable_Ref<T> { self.vtable } /// Extracts the value this owns. pub fn into_inner(self) -> T { let this = ManuallyDrop::new(self); let vtable = this.vtable(); unsafe { // Must copy this before calling `vtable.destructor()` // because otherwise it would be reading from a dangling pointer. let ret = this.data.read(); vtable.destructor()(this.data, CallReferentDrop::No); ret } } } impl<T> Deref for BoxLike<T> { type Target = T; fn deref(&self) -> &T { unsafe { &(*self.data) } } } impl<T> DerefMut for BoxLike<T> { fn deref_mut(&mut self) -> &mut T { unsafe { &mut (*self.data) } } } impl<T> Drop for BoxLike<T> { fn drop(&mut self) { let vtable = self.vtable(); unsafe { vtable.destructor()(self.data, CallReferentDrop::Yes) } } } // `#[sabi(kind(Prefix))]` Declares this type as being a prefix-type, // generating both of these types: // // - BoxVTable_Prefix`: A struct with the fields up to (and including) the field with the // `#[sabi(last_prefix_field)]` attribute. // // - BoxVTable_Ref`: An ffi-safe pointer to a `BoxVtable`, with methods to get // `BoxVtable`'s fields. // #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix))] pub(crate) struct BoxVtable<T> { /// The `#[sabi(last_prefix_field)]` attribute here means that this is /// the last field in this struct that was defined in the /// first compatible version of the library /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), /// requiring new fields to always be added after it. /// /// The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library /// bumps its "major" version, /// at which point it would be moved to the last field at the time. /// #[sabi(last_prefix_field)] destructor: unsafe extern "C" fn(*mut T, CallReferentDrop), } // This is how ffi-safe pointers to generic prefix types are constructed // at compile-time. impl<T> BoxVtable<T> { // This macro declares a `StaticRef<WithMetadata<BoxVtable<T>>>` constant. // // StaticRef represents a reference to data that lives forever, // but is not necessarily `'static` according to the type system, // eg: `BoxVtable<T>`. staticref!(const VTABLE_VAL: WithMetadata<Self> = WithMetadata::new( Self{ destructor:destroy_box::<T>, }, )); const VTABLE: BoxVtable_Ref<T> = { BoxVtable_Ref(Self::VTABLE_VAL.as_prefix()) }; } unsafe extern "C" fn destroy_box<T>(v: *mut T, call_drop: CallReferentDrop) { extern_fn_panic_handling! { let mut box_ = Box::from_raw(v as *mut ManuallyDrop<T>); if call_drop == CallReferentDrop::Yes { ManuallyDrop::drop(&mut *box_); } drop(box_); } } # fn main(){} ``` ### Example 3:module This declares,initializes,and uses a module. ``` use abi_stable::{ prefix_type::{PrefixTypeTrait, WithMetadata}, sabi_extern_fn, std_types::RDuration, StableAbi, }; // `#[sabi(kind(Prefix))]` Declares this type as being a prefix-type, // generating both of these types: // // - PersonMod_Prefix`: A struct with the fields up to (and including) the field with the // `#[sabi(last_prefix_field)]` attribute. // // - PersonMod_Ref`: // An ffi-safe pointer to a `PersonMod`,with methods to get`PersonMod`'s fields. // #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix))] pub struct PersonMod { /// The `#[sabi(last_prefix_field)]` attribute here means that this is /// the last field in this struct that was defined in the /// first compatible version of the library /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), /// requiring new fields to always be added below preexisting ones. /// /// The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library /// bumps its "major" version, /// at which point it would be moved to the last field at the time. /// #[sabi(last_prefix_field)] pub customer_for: extern "C" fn(Id) -> RDuration, // The default behavior for the getter is to return an Option<FieldType>, // if the field exists it returns Some(_), // otherwise it returns None. pub bike_count: extern "C" fn(Id) -> u32, // The getter for this field panics if the field doesn't exist. #[sabi(missing_field(panic))] pub visits: extern "C" fn(Id) -> u32, // The getter for this field returns `default_score()` if the field doesn't exist. #[sabi(missing_field(with = default_score))] pub score: extern "C" fn(Id) -> u32, // The getter for this field returns `Default::default()` if the field doesn't exist. #[sabi(missing_field(default))] pub visit_length: Option<extern "C" fn(Id) -> RDuration>, } fn default_score() -> extern "C" fn(Id) -> u32 { extern "C" fn default(_: Id) -> u32 { 1000 } default } type Id = u32; # static VARS:&[(RDuration,u32)]=&[ # (RDuration::new(1_000,0),10), # (RDuration::new(1_000_000,0),1), # ]; # #[sabi_extern_fn] # fn customer_for(id:Id)->RDuration{ # VARS[id as usize].0 # } # #[sabi_extern_fn] # fn bike_count(id:Id)->u32{ # VARS[id as usize].1 # } # #[sabi_extern_fn] # fn visits(id:Id)->u32{ # VARS[id as usize].1 # } # #[sabi_extern_fn] # fn score(id:Id)->u32{ # VARS[id as usize].1 # } /* ... Elided function definitions ... */ # fn main(){ const _MODULE_WM_: &WithMetadata<PersonMod> = &WithMetadata::new( PersonMod { customer_for, bike_count, visits, score, visit_length: None, }, ); const MODULE: PersonMod_Ref = PersonMod_Ref(_MODULE_WM_.static_as_prefix()); // Getting the value for every field of `MODULE`. let customer_for: extern "C" fn(Id) -> RDuration = MODULE.customer_for(); let bike_count: Option<extern "C" fn(Id) -> u32> = MODULE.bike_count(); let visits: extern "C" fn(Id) -> u32 = MODULE.visits(); let score: extern "C" fn(Id) -> u32 = MODULE.score(); let visit_length: Option<extern "C" fn(Id) -> RDuration> = MODULE.visit_length(); # } ``` [`staticref`]: ../../macro.staticref.html */
use serde::{Deserialize, Serialize}; use crate::domain::CodePoint; use crate::domain::Location; #[repr(C)] #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CodeFunction { pub name: String, // todo: thinking in access pub vars: Vec<String>, pub start: CodePoint, pub end: CodePoint } impl Default for CodeFunction { fn default() -> Self { CodeFunction { name: "".to_string(), vars: vec![], start: Default::default(), end: Default::default() } } } impl Location for CodeFunction { fn set_start(&mut self, row: usize, column: usize) { self.start.row = row; self.start.column = column; } fn set_end(&mut self, row: usize, column: usize) { self.end.row = row; self.end.column = column; } }
mod handshake; use self::handshake::Handshaker; use super::{options::ConnectionPoolOptions, Connection}; use crate::{client::auth::Credential, error::Result, runtime::HttpClient}; /// Contains the logic to establish a connection, including handshaking, authenticating, and /// potentially more. #[derive(Debug)] pub(super) struct ConnectionEstablisher { /// Contains the logic for handshaking a connection. handshaker: Handshaker, http_client: HttpClient, credential: Option<Credential>, } impl ConnectionEstablisher { /// Creates a new ConnectionEstablisher from the given options. pub(super) fn new(http_client: HttpClient, options: Option<&ConnectionPoolOptions>) -> Self { let handshaker = Handshaker::new(options); Self { handshaker, http_client, credential: options.and_then(|options| options.credential.clone()), } } /// Establishes a connection. pub(super) async fn establish_connection(&self, connection: &mut Connection) -> Result<()> { self.handshaker.handshake(connection).await?; if let Some(ref credential) = self.credential { credential .authenticate_stream(connection, &self.http_client) .await?; } Ok(()) } }
use grid_search::around; use procon_reader::ProconReader; #[rustfmt::skip] const DIRS: [(isize, isize); 20] = [ (-2, -1), (-2, 0), (-2, 1), (-1, -2), (-1, -1), (-1, 0), (-1, 1), (-1, 2), (0, -2), (0, -1), (0, 1), (0, 2), (1, -2), (1, -1), (1, 0), (1, 1), (1, 2), (2, -1), (2, 0), (2, 1), ]; const UDLR: [(isize, isize); 4] = [(-1, 0), (1, 0), (0, -1), (0, 1)]; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let h: usize = rd.get(); let w: usize = rd.get(); let s: Vec<Vec<char>> = (0..h).map(|_| rd.get_chars()).collect(); let inf = std::u64::MAX / 2; let mut d = vec![inf; h * w]; d[0] = 0; use std::collections::VecDeque; let mut que = VecDeque::new(); que.push_back(0); while let Some(u) = que.pop_front() { let i = u / w; let j = u % w; for (y, x) in around(i, j).y_range(0..h).x_range(0..w).directions(&UDLR) { let v = y * w + x; if s[y][x] == '.' && d[u] < d[v] { d[v] = d[u]; que.push_front(v); } } for (y, x) in around(i, j).y_range(0..h).x_range(0..w).directions(&DIRS) { let v = y * w + x; if d[u] + 1 < d[v] { d[v] = d[u] + 1; que.push_back(v); } } } println!("{}", d[h * w - 1]); }
extern crate iron; extern crate router; extern crate time; use iron::prelude::*; use iron::status; use router::Router; fn main() { let mut router = Router::new(); router.get("/", handler, "index"); Iron::new(router).http("localhost:3000").unwrap(); fn handler(_: &mut Request) -> IronResult<Response> { let now = time::now(); let midnight = set_hour(now, 0); let midday = set_hour(now, 12); let sunset = set_hour(now, 18); let midnightnextday = set_hour(now, 24); let greeting = if now >= midnight && now < midday { "Good Morning".to_string() } else if now >= midday && now < sunset { "Good Afternoon".to_string() } else if now >= sunset && now < midnightnextday { "Good Evening".to_string() } else { "Hello".to_string() }; Ok(Response::with((status::Ok, greeting))) } } fn set_hour(t: time::Tm, hour: i32) -> time::Tm { let mut t = t; t.tm_hour = hour; t.tm_min = 0; t.tm_sec = 0; t.tm_nsec = 0; t }
#[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::INTENSET { #[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 = "Possible values of the field `RXRDYEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RXRDYENR { #[doc = "No interrupt will be generated when receiver data is available."] NO_INTERRUPT_WILL_BE, #[doc = "An interrupt will be generated when receiver data is available in the RXDAT register."] AN_INTERRUPT_WILL_BE, } impl RXRDYENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { RXRDYENR::NO_INTERRUPT_WILL_BE => false, RXRDYENR::AN_INTERRUPT_WILL_BE => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> RXRDYENR { match value { false => RXRDYENR::NO_INTERRUPT_WILL_BE, true => RXRDYENR::AN_INTERRUPT_WILL_BE, } } #[doc = "Checks if the value of the field is `NO_INTERRUPT_WILL_BE`"] #[inline] pub fn is_no_interrupt_will_be(&self) -> bool { *self == RXRDYENR::NO_INTERRUPT_WILL_BE } #[doc = "Checks if the value of the field is `AN_INTERRUPT_WILL_BE`"] #[inline] pub fn is_an_interrupt_will_be(&self) -> bool { *self == RXRDYENR::AN_INTERRUPT_WILL_BE } } #[doc = "Possible values of the field `TXRDYEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TXRDYENR { #[doc = "No interrupt will be generated when the transmitter holding register is available."] NO_INTERRUPT_WILL_BE, #[doc = "An interrupt will be generated when data may be written to TXDAT."] AN_INTERRUPT_WILL_BE, } impl TXRDYENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { TXRDYENR::NO_INTERRUPT_WILL_BE => false, TXRDYENR::AN_INTERRUPT_WILL_BE => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> TXRDYENR { match value { false => TXRDYENR::NO_INTERRUPT_WILL_BE, true => TXRDYENR::AN_INTERRUPT_WILL_BE, } } #[doc = "Checks if the value of the field is `NO_INTERRUPT_WILL_BE`"] #[inline] pub fn is_no_interrupt_will_be(&self) -> bool { *self == TXRDYENR::NO_INTERRUPT_WILL_BE } #[doc = "Checks if the value of the field is `AN_INTERRUPT_WILL_BE`"] #[inline] pub fn is_an_interrupt_will_be(&self) -> bool { *self == TXRDYENR::AN_INTERRUPT_WILL_BE } } #[doc = "Possible values of the field `RXOVEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RXOVENR { #[doc = "No interrupt will be generated when a receiver overrun occurs."] NO_INTERRUPT_WILL_BE, #[doc = "An interrupt will be generated if a receiver overrun occurs."] AN_INTERRUPT_WILL_BE, } impl RXOVENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { RXOVENR::NO_INTERRUPT_WILL_BE => false, RXOVENR::AN_INTERRUPT_WILL_BE => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> RXOVENR { match value { false => RXOVENR::NO_INTERRUPT_WILL_BE, true => RXOVENR::AN_INTERRUPT_WILL_BE, } } #[doc = "Checks if the value of the field is `NO_INTERRUPT_WILL_BE`"] #[inline] pub fn is_no_interrupt_will_be(&self) -> bool { *self == RXOVENR::NO_INTERRUPT_WILL_BE } #[doc = "Checks if the value of the field is `AN_INTERRUPT_WILL_BE`"] #[inline] pub fn is_an_interrupt_will_be(&self) -> bool { *self == RXOVENR::AN_INTERRUPT_WILL_BE } } #[doc = "Possible values of the field `TXUREN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TXURENR { #[doc = "No interrupt will be generated when the transmitter underruns."] NO_INTERRUPT_WILL_BE, #[doc = "An interrupt will be generated if the transmitter underruns."] AN_INTERRUPT_WILL_BE, } impl TXURENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { TXURENR::NO_INTERRUPT_WILL_BE => false, TXURENR::AN_INTERRUPT_WILL_BE => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> TXURENR { match value { false => TXURENR::NO_INTERRUPT_WILL_BE, true => TXURENR::AN_INTERRUPT_WILL_BE, } } #[doc = "Checks if the value of the field is `NO_INTERRUPT_WILL_BE`"] #[inline] pub fn is_no_interrupt_will_be(&self) -> bool { *self == TXURENR::NO_INTERRUPT_WILL_BE } #[doc = "Checks if the value of the field is `AN_INTERRUPT_WILL_BE`"] #[inline] pub fn is_an_interrupt_will_be(&self) -> bool { *self == TXURENR::AN_INTERRUPT_WILL_BE } } #[doc = "Possible values of the field `SSAEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SSAENR { #[doc = "No interrupt will be generated when any Slave Select transitions from deasserted to asserted."] NO_INTERRUPT_WILL_BE, #[doc = "An interrupt will be generated when any Slave Select transitions from deasserted to asserted."] AN_INTERRUPT_WILL_BE, } impl SSAENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { SSAENR::NO_INTERRUPT_WILL_BE => false, SSAENR::AN_INTERRUPT_WILL_BE => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SSAENR { match value { false => SSAENR::NO_INTERRUPT_WILL_BE, true => SSAENR::AN_INTERRUPT_WILL_BE, } } #[doc = "Checks if the value of the field is `NO_INTERRUPT_WILL_BE`"] #[inline] pub fn is_no_interrupt_will_be(&self) -> bool { *self == SSAENR::NO_INTERRUPT_WILL_BE } #[doc = "Checks if the value of the field is `AN_INTERRUPT_WILL_BE`"] #[inline] pub fn is_an_interrupt_will_be(&self) -> bool { *self == SSAENR::AN_INTERRUPT_WILL_BE } } #[doc = "Possible values of the field `SSDEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SSDENR { #[doc = "No interrupt will be generated when all asserted Slave Selects transition to deasserted."] NO_INTERRUPT_WILL_BE, #[doc = "An interrupt will be generated when all asserted Slave Selects transition to deasserted."] AN_INTERRUPT_WILL_BE, } impl SSDENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { SSDENR::NO_INTERRUPT_WILL_BE => false, SSDENR::AN_INTERRUPT_WILL_BE => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SSDENR { match value { false => SSDENR::NO_INTERRUPT_WILL_BE, true => SSDENR::AN_INTERRUPT_WILL_BE, } } #[doc = "Checks if the value of the field is `NO_INTERRUPT_WILL_BE`"] #[inline] pub fn is_no_interrupt_will_be(&self) -> bool { *self == SSDENR::NO_INTERRUPT_WILL_BE } #[doc = "Checks if the value of the field is `AN_INTERRUPT_WILL_BE`"] #[inline] pub fn is_an_interrupt_will_be(&self) -> bool { *self == SSDENR::AN_INTERRUPT_WILL_BE } } #[doc = "Values that can be written to the field `RXRDYEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RXRDYENW { #[doc = "No interrupt will be generated when receiver data is available."] NO_INTERRUPT_WILL_BE, #[doc = "An interrupt will be generated when receiver data is available in the RXDAT register."] AN_INTERRUPT_WILL_BE, } impl RXRDYENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { RXRDYENW::NO_INTERRUPT_WILL_BE => false, RXRDYENW::AN_INTERRUPT_WILL_BE => true, } } } #[doc = r" Proxy"] pub struct _RXRDYENW<'a> { w: &'a mut W, } impl<'a> _RXRDYENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: RXRDYENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No interrupt will be generated when receiver data is available."] #[inline] pub fn no_interrupt_will_be(self) -> &'a mut W { self.variant(RXRDYENW::NO_INTERRUPT_WILL_BE) } #[doc = "An interrupt will be generated when receiver data is available in the RXDAT register."] #[inline] pub fn an_interrupt_will_be(self) -> &'a mut W { self.variant(RXRDYENW::AN_INTERRUPT_WILL_BE) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `TXRDYEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TXRDYENW { #[doc = "No interrupt will be generated when the transmitter holding register is available."] NO_INTERRUPT_WILL_BE, #[doc = "An interrupt will be generated when data may be written to TXDAT."] AN_INTERRUPT_WILL_BE, } impl TXRDYENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { TXRDYENW::NO_INTERRUPT_WILL_BE => false, TXRDYENW::AN_INTERRUPT_WILL_BE => true, } } } #[doc = r" Proxy"] pub struct _TXRDYENW<'a> { w: &'a mut W, } impl<'a> _TXRDYENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TXRDYENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No interrupt will be generated when the transmitter holding register is available."] #[inline] pub fn no_interrupt_will_be(self) -> &'a mut W { self.variant(TXRDYENW::NO_INTERRUPT_WILL_BE) } #[doc = "An interrupt will be generated when data may be written to TXDAT."] #[inline] pub fn an_interrupt_will_be(self) -> &'a mut W { self.variant(TXRDYENW::AN_INTERRUPT_WILL_BE) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `RXOVEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RXOVENW { #[doc = "No interrupt will be generated when a receiver overrun occurs."] NO_INTERRUPT_WILL_BE, #[doc = "An interrupt will be generated if a receiver overrun occurs."] AN_INTERRUPT_WILL_BE, } impl RXOVENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { RXOVENW::NO_INTERRUPT_WILL_BE => false, RXOVENW::AN_INTERRUPT_WILL_BE => true, } } } #[doc = r" Proxy"] pub struct _RXOVENW<'a> { w: &'a mut W, } impl<'a> _RXOVENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: RXOVENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No interrupt will be generated when a receiver overrun occurs."] #[inline] pub fn no_interrupt_will_be(self) -> &'a mut W { self.variant(RXOVENW::NO_INTERRUPT_WILL_BE) } #[doc = "An interrupt will be generated if a receiver overrun occurs."] #[inline] pub fn an_interrupt_will_be(self) -> &'a mut W { self.variant(RXOVENW::AN_INTERRUPT_WILL_BE) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `TXUREN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TXURENW { #[doc = "No interrupt will be generated when the transmitter underruns."] NO_INTERRUPT_WILL_BE, #[doc = "An interrupt will be generated if the transmitter underruns."] AN_INTERRUPT_WILL_BE, } impl TXURENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { TXURENW::NO_INTERRUPT_WILL_BE => false, TXURENW::AN_INTERRUPT_WILL_BE => true, } } } #[doc = r" Proxy"] pub struct _TXURENW<'a> { w: &'a mut W, } impl<'a> _TXURENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TXURENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No interrupt will be generated when the transmitter underruns."] #[inline] pub fn no_interrupt_will_be(self) -> &'a mut W { self.variant(TXURENW::NO_INTERRUPT_WILL_BE) } #[doc = "An interrupt will be generated if the transmitter underruns."] #[inline] pub fn an_interrupt_will_be(self) -> &'a mut W { self.variant(TXURENW::AN_INTERRUPT_WILL_BE) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 3; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SSAEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SSAENW { #[doc = "No interrupt will be generated when any Slave Select transitions from deasserted to asserted."] NO_INTERRUPT_WILL_BE, #[doc = "An interrupt will be generated when any Slave Select transitions from deasserted to asserted."] AN_INTERRUPT_WILL_BE, } impl SSAENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SSAENW::NO_INTERRUPT_WILL_BE => false, SSAENW::AN_INTERRUPT_WILL_BE => true, } } } #[doc = r" Proxy"] pub struct _SSAENW<'a> { w: &'a mut W, } impl<'a> _SSAENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SSAENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No interrupt will be generated when any Slave Select transitions from deasserted to asserted."] #[inline] pub fn no_interrupt_will_be(self) -> &'a mut W { self.variant(SSAENW::NO_INTERRUPT_WILL_BE) } #[doc = "An interrupt will be generated when any Slave Select transitions from deasserted to asserted."] #[inline] pub fn an_interrupt_will_be(self) -> &'a mut W { self.variant(SSAENW::AN_INTERRUPT_WILL_BE) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SSDEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SSDENW { #[doc = "No interrupt will be generated when all asserted Slave Selects transition to deasserted."] NO_INTERRUPT_WILL_BE, #[doc = "An interrupt will be generated when all asserted Slave Selects transition to deasserted."] AN_INTERRUPT_WILL_BE, } impl SSDENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SSDENW::NO_INTERRUPT_WILL_BE => false, SSDENW::AN_INTERRUPT_WILL_BE => true, } } } #[doc = r" Proxy"] pub struct _SSDENW<'a> { w: &'a mut W, } impl<'a> _SSDENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SSDENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No interrupt will be generated when all asserted Slave Selects transition to deasserted."] #[inline] pub fn no_interrupt_will_be(self) -> &'a mut W { self.variant(SSDENW::NO_INTERRUPT_WILL_BE) } #[doc = "An interrupt will be generated when all asserted Slave Selects transition to deasserted."] #[inline] pub fn an_interrupt_will_be(self) -> &'a mut W { self.variant(SSDENW::AN_INTERRUPT_WILL_BE) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 5; 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 = "Bit 0 - Determines whether an interrupt occurs when receiver data is available."] #[inline] pub fn rxrdyen(&self) -> RXRDYENR { RXRDYENR::_from({ const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 1 - Determines whether an interrupt occurs when the transmitter holding register is available."] #[inline] pub fn txrdyen(&self) -> TXRDYENR { TXRDYENR::_from({ const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 2 - Determines whether an interrupt occurs when a receiver overrun occurs. This happens in slave mode when there is a need for the receiver to move newly received data to the RXDAT register when it is already in use. The interface prevents receiver overrun in Master mode by not allowing a new transmission to begin when a receiver overrun would otherwise occur."] #[inline] pub fn rxoven(&self) -> RXOVENR { RXOVENR::_from({ const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 3 - Determines whether an interrupt occurs when a transmitter underrun occurs. This happens in slave mode when there is a need to transmit data when none is available."] #[inline] pub fn txuren(&self) -> TXURENR { TXURENR::_from({ const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 4 - Determines whether an interrupt occurs when one or more Slave Select is asserted."] #[inline] pub fn ssaen(&self) -> SSAENR { SSAENR::_from({ const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 5 - Determines whether an interrupt occurs when all Slave Selects are deasserted."] #[inline] pub fn ssden(&self) -> SSDENR { SSDENR::_from({ const MASK: bool = true; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Determines whether an interrupt occurs when receiver data is available."] #[inline] pub fn rxrdyen(&mut self) -> _RXRDYENW { _RXRDYENW { w: self } } #[doc = "Bit 1 - Determines whether an interrupt occurs when the transmitter holding register is available."] #[inline] pub fn txrdyen(&mut self) -> _TXRDYENW { _TXRDYENW { w: self } } #[doc = "Bit 2 - Determines whether an interrupt occurs when a receiver overrun occurs. This happens in slave mode when there is a need for the receiver to move newly received data to the RXDAT register when it is already in use. The interface prevents receiver overrun in Master mode by not allowing a new transmission to begin when a receiver overrun would otherwise occur."] #[inline] pub fn rxoven(&mut self) -> _RXOVENW { _RXOVENW { w: self } } #[doc = "Bit 3 - Determines whether an interrupt occurs when a transmitter underrun occurs. This happens in slave mode when there is a need to transmit data when none is available."] #[inline] pub fn txuren(&mut self) -> _TXURENW { _TXURENW { w: self } } #[doc = "Bit 4 - Determines whether an interrupt occurs when one or more Slave Select is asserted."] #[inline] pub fn ssaen(&mut self) -> _SSAENW { _SSAENW { w: self } } #[doc = "Bit 5 - Determines whether an interrupt occurs when all Slave Selects are deasserted."] #[inline] pub fn ssden(&mut self) -> _SSDENW { _SSDENW { w: self } } }
use std::thread; use std::sync::{Arc,Mutex}; use std::vec::Vec; fn main() { let number_of_threads = 20; let mut thread_names = Arc::new(Mutex::new(Vec::new())); for n in 0..number_of_threads { let thread_name = format!("thread-{}", n + 1); thread_names.push(thread_name); } for tn in &thread_names { thread::Builder::new().name(tn).spawn(move || { println!("{}", tn); //println!("{} -- {} -- {}", mp4_path_copy.lock(), ip_addr.lock(), thread_name.lock()); //let mut command = ffmpeg_command(&mp4_path, &ip_addr, &thread_name); /* match command.output() { Err(why) => panic!("\n\nError running command from thread {}: {}\n\n", thread, why.desc), Ok(Output { error: err, output: _, status: exit }) => { if exit.success() { print!("\n\nThread {} finished with success\n\n", thread); } else { let string = String::from_utf8_lossy(&err); print!("\n\nThread {} failed because {}\n\n", thread, string); } }, } */ }); } }
fn largest_prime_factor(n: u64) -> u64 { let mut largest_factor = 1; let mut num = n; while num % 2 == 0 { largest_factor = 2; num = num / 2; } let mut factor = 3; let mut max_factor = (num as f64).sqrt() as u64 + 1; while num > 1 && factor <= max_factor { while num % factor == 0 { largest_factor = factor; num = num / factor; max_factor = (num as f64).sqrt() as u64 + 1; } factor = factor + 2; } if num > largest_factor { largest_factor = num; } largest_factor } fn main() { let n = 600851475143; println!( "The largest prime factor of {} is {}", n, largest_prime_factor(n) ); }
use std::io::{Read, Result as IOResult}; use crate::PrimitiveRead; pub struct Visibility { pub num_clusters: i32, pub byte_offsets: [Box<[i32]>; 2] } impl Visibility { pub fn read(reader: &mut dyn Read) -> IOResult<Self> { let num_clusters = reader.read_i32()?; let mut byte_offsets: [Box<[i32]>; 2] = [ Box::new([0i32; 0]), Box::new([0i32; 0]), ]; for offsets in &mut byte_offsets { let mut offsets_vec = Vec::with_capacity(num_clusters as usize); for _ in 0 .. num_clusters { offsets_vec.push(reader.read_i32()?); } *offsets = offsets_vec.into_boxed_slice(); } Ok(Self { num_clusters, byte_offsets }) } }
#![cfg(feature = "with-deprecated")] #![allow(deprecated)] #![deprecated(since = "0.1.4", note = "replaced with `BiLock` in many cases, otherwise slated \ for removal due to confusion")] use std::prelude::v1::*; use std::sync::Arc; use std::cell::UnsafeCell; use task_impl; // One critical piece of this module's contents are the `TaskRc<A>` handles. // The purpose of this is to conceptually be able to store data in a task, // allowing it to be accessed within multiple futures at once. For example if // you have some concurrent futures working, they may all want mutable access to // some data. We already know that when the futures are being poll'd that we're // entirely synchronized (aka `&mut Task`), so you shouldn't require an // `Arc<Mutex<T>>` to share as the synchronization isn't necessary! // // So the idea here is that you insert data into a task via `Task::insert`, and // a handle to that data is then returned to you. That handle can later get // presented to the task itself to actually retrieve the underlying data. The // invariant is that the data can only ever be accessed with the task present, // and the lifetime of the actual data returned is connected to the lifetime of // the task itself. // // Conceptually I at least like to think of this as "dynamically adding more // struct fields to a `Task`". Each call to insert creates a new "name" for the // struct field, a `TaskRc<A>`, and then you can access the fields of a struct // with the struct itself (`Task`) as well as the name of the field // (`TaskRc<A>`). If that analogy doesn't make sense then oh well, it at least // helped me! // // So anyway, we do some interesting trickery here to actually get it to work. // Each `TaskRc<A>` handle stores `Arc<UnsafeCell<A>>`. So it turns out, we're // not even adding data to the `Task`! Each `TaskRc<A>` contains a reference // to this `Arc`, and `TaskRc` handles can be cloned which just bumps the // reference count on the `Arc` itself. // // As before, though, you can present the `Arc` to a `Task` and if they // originated from the same place you're allowed safe access to the internals. // We allow but shared and mutable access without the `Sync` bound on the data, // crucially noting that a `Task` itself is not `Sync`. // // So hopefully I've convinced you of this point that the `get` and `get_mut` // methods below are indeed safe. The data is always valid as it's stored in an // `Arc`, and access is only allowed with the proof of the associated `Task`. // One thing you might be asking yourself though is what exactly is this "proof // of a task"? Right now it's a `usize` corresponding to the `Task`'s // `TaskHandle` arc allocation. // // Wait a minute, isn't that the ABA problem! That is, we create a task A, add // some data to it, destroy task A, do some work, create a task B, and then ask // to get the data from task B. In this case though the point of the // `task_inner` "proof" field is simply that there's some non-`Sync` token // proving that you can get access to the data. So while weird, this case should // still be safe, as the data's not stored in the task itself. /// A reference to a piece of data that's accessible only within a specific /// `Task`. /// /// This data is `Send` even when `A` is not `Sync`, because the data stored /// within is accessed in a single-threaded way. The thread accessing it may /// change over time, if the task migrates, so `A` must be `Send`. #[derive(Debug)] pub struct TaskRc<A> { task: task_impl::Task, ptr: Arc<UnsafeCell<A>>, } // for safety here, see docs at the top of this module unsafe impl<A: Send> Send for TaskRc<A> {} unsafe impl<A: Sync> Sync for TaskRc<A> {} impl<A> TaskRc<A> { /// Inserts a new piece of task-local data into this task, returning a /// reference to it. /// /// Ownership of the data will be transferred to the task, and the data will /// be destroyed when the task itself is destroyed. The returned value can /// be passed to the `with` method to get a reference back to the original /// data. /// /// Note that the returned handle is cloneable and copyable and can be sent /// to other futures which will be associated with the same task. All /// futures will then have access to this data when passed the reference /// back. /// /// # Panics /// /// This function will panic if a task is not currently running. pub fn new(a: A) -> TaskRc<A> { TaskRc { task: task_impl::park(), ptr: Arc::new(UnsafeCell::new(a)), } } /// Operate with a reference to the underlying data. /// /// This method should be passed a handle previously returned by /// `Task::insert`. That handle, when passed back into this method, will /// retrieve a reference to the original data. /// /// # Panics /// /// This method will panic if a task is not currently running or if `self` /// does not belong to the task that is currently running. That is, if /// another task generated the `data` handle passed in, this method will /// panic. pub fn with<F, R>(&self, f: F) -> R where F: FnOnce(&A) -> R { if !self.task.is_current() { panic!("TaskRc being accessed on task it does not belong to"); } f(unsafe { &*self.ptr.get() }) } } impl<A> Clone for TaskRc<A> { fn clone(&self) -> TaskRc<A> { TaskRc { task: self.task.clone(), ptr: self.ptr.clone(), } } }
// 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. #![feature(repr_align_enum)] #![allow(warnings)] use zerocopy::AsBytes; struct IsAsBytes<T: AsBytes>(T); // Fail compilation if `$ty: !AsBytes`. macro_rules! is_as_bytes { ($ty:ty) => { const _: () = { let _: IsAsBytes<$ty>; }; }; } // An enum is AsBytes if if has a defined repr #[derive(AsBytes)] #[repr(C)] enum C { A, } is_as_bytes!(C); #[derive(AsBytes)] #[repr(u8)] enum U8 { A, } is_as_bytes!(U8); #[derive(AsBytes)] #[repr(u16)] enum U16 { A, } is_as_bytes!(U16); #[derive(AsBytes)] #[repr(u32)] enum U32 { A, } is_as_bytes!(U32); #[derive(AsBytes)] #[repr(u64)] enum U64 { A, } is_as_bytes!(U64); #[derive(AsBytes)] #[repr(usize)] enum Usize { A, } is_as_bytes!(Usize); #[derive(AsBytes)] #[repr(i8)] enum I8 { A, } is_as_bytes!(I8); #[derive(AsBytes)] #[repr(i16)] enum I16 { A, } is_as_bytes!(I16); #[derive(AsBytes)] #[repr(i32)] enum I32 { A, } is_as_bytes!(I32); #[derive(AsBytes)] #[repr(i64)] enum I64 { A, } is_as_bytes!(I64); #[derive(AsBytes)] #[repr(isize)] enum Isize { A, } is_as_bytes!(Isize);
use crate::context::RpcContext; use crate::felt::RpcFelt; use anyhow::{anyhow, Context}; use pathfinder_common::{BlockId, ContractAddress, StorageAddress, StorageValue}; use serde::Deserialize; #[derive(Deserialize, Debug, PartialEq, Eq)] pub struct GetStorageAtInput { pub contract_address: ContractAddress, pub key: StorageAddress, pub block_id: BlockId, } #[serde_with::serde_as] #[derive(serde::Serialize)] pub struct GetStorageOutput(#[serde_as(as = "RpcFelt")] StorageValue); crate::error::generate_rpc_error_subset!(GetStorageAtError: ContractNotFound, BlockNotFound); /// Get the value of the storage at the given address and key. pub async fn get_storage_at( context: RpcContext, input: GetStorageAtInput, ) -> Result<GetStorageOutput, GetStorageAtError> { let block_id = match input.block_id { BlockId::Pending => { match context .pending_data .ok_or_else(|| anyhow!("Pending data not supported in this configuration"))? .state_update() .await { Some(update) => { let pending_value = update .contract_updates .get(&input.contract_address) .and_then(|update| { update .storage .iter() .find_map(|(key, value)| (key == &input.key).then_some(*value)) }); match pending_value { Some(value) => return Ok(GetStorageOutput(value)), None => pathfinder_storage::BlockId::Latest, } } None => pathfinder_storage::BlockId::Latest, } } other => other.try_into().expect("Only pending cast should fail"), }; let storage = context.storage.clone(); let span = tracing::Span::current(); let jh = tokio::task::spawn_blocking(move || { let _g = span.enter(); let mut db = storage .connection() .context("Opening database connection")?; let tx = db.transaction().context("Creating database transaction")?; // Check for block existence. if !tx.block_exists(block_id)? { return Err(GetStorageAtError::BlockNotFound); } let value = tx .storage_value(block_id, input.contract_address, input.key) .context("Querying storage value")?; match value { Some(value) => Ok(GetStorageOutput(value)), None => { if tx.contract_exists(input.contract_address, block_id)? { Ok(GetStorageOutput(StorageValue::ZERO)) } else { Err(GetStorageAtError::ContractNotFound) } } } }); jh.await.context("Database read panic or shutting down")? } #[cfg(test)] mod tests { use super::*; use assert_matches::assert_matches; use jsonrpsee::types::Params; use pathfinder_common::macro_prelude::*; use pathfinder_common::{ContractAddress, StorageAddress}; /// # Important /// /// `BlockId` parsing is tested in [`get_block`][crate::rpc::v02::method::get_block::tests::parsing] /// and is not repeated here. #[test] fn parsing() { let expected = GetStorageAtInput { contract_address: contract_address!("0x1"), key: storage_address!("0x2"), block_id: BlockId::Latest, }; [ r#"["1", "2", "latest"]"#, r#"{"contract_address": "0x1", "key": "0x2", "block_id": "latest"}"#, ] .into_iter() .enumerate() .for_each(|(i, input)| { let actual = Params::new(Some(input)) .parse::<GetStorageAtInput>() .unwrap_or_else(|error| panic!("test case {i}: {input}, {error}")); assert_eq!(actual, expected, "test case {i}: {input}"); }); } type TestCaseHandler = Box<dyn Fn(usize, &Result<StorageValue, GetStorageAtError>)>; /// Execute a single test case and check its outcome for `get_storage_at` async fn check( test_case_idx: usize, test_case: &( RpcContext, ContractAddress, StorageAddress, BlockId, TestCaseHandler, ), ) { let (context, contract_address, key, block_id, f) = test_case; let result = get_storage_at( context.clone(), GetStorageAtInput { contract_address: *contract_address, key: *key, block_id: *block_id, }, ) .await .map(|x| x.0); f(test_case_idx, &result); } /// Common assertion type for most of the happy paths fn assert_value(expected: &'static [u8]) -> TestCaseHandler { Box::new(|i: usize, result| { assert_matches!(result, Ok(value) => assert_eq!( *value, storage_value_bytes!(expected), "test case {i}" ), "test case {i}"); }) } impl PartialEq for GetStorageAtError { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Internal(l), Self::Internal(r)) => l.to_string() == r.to_string(), _ => core::mem::discriminant(self) == core::mem::discriminant(other), } } } /// Common assertion type for most of the error paths fn assert_error(expected: GetStorageAtError) -> TestCaseHandler { Box::new(move |i: usize, result| { assert_matches!(result, Err(error) => assert_eq!(*error, expected, "test case {i}"), "test case {i}"); }) } #[tokio::test] async fn happy_paths_and_major_errors() { let ctx = RpcContext::for_tests_with_pending().await; let ctx_with_pending_empty = RpcContext::for_tests() .with_pending_data(starknet_gateway_types::pending::PendingData::default()); let ctx_with_pending_disabled = RpcContext::for_tests(); let pending_contract0 = contract_address_bytes!(b"pending contract 1 address"); let pending_key0 = storage_address_bytes!(b"pending storage key 0"); let contract1 = contract_address_bytes!(b"contract 1"); let key0 = storage_address_bytes!(b"storage addr 0"); let deployment_block = BlockId::Hash(block_hash_bytes!(b"block 1")); let non_existent_key = storage_address_bytes!(b"non-existent"); let non_existent_contract = contract_address_bytes!(b"non-existent"); let pre_deploy_block = BlockId::Hash(block_hash_bytes!(b"genesis")); let non_existent_block = BlockId::Hash(block_hash_bytes!(b"non-existent")); let cases: &[( RpcContext, ContractAddress, StorageAddress, BlockId, TestCaseHandler, )] = &[ // Pending - happy paths ( ctx.clone(), pending_contract0, pending_key0, BlockId::Pending, assert_value(b"pending storage value 0"), ), ( ctx_with_pending_empty, contract1, key0, BlockId::Pending, // Pending data is absent, fallback to the latest block assert_value(b"storage value 2"), ), // Other block ids - happy paths ( ctx.clone(), contract1, key0, deployment_block, assert_value(b"storage value 1"), ), ( ctx.clone(), contract1, key0, BlockId::Latest, assert_value(b"storage value 2"), ), ( ctx.clone(), contract1, non_existent_key, BlockId::Latest, assert_value(&[0]), ), // Errors ( ctx.clone(), non_existent_contract, key0, BlockId::Latest, assert_error(GetStorageAtError::ContractNotFound), ), ( ctx.clone(), contract1, key0, non_existent_block, assert_error(GetStorageAtError::BlockNotFound), ), ( ctx.clone(), contract1, key0, pre_deploy_block, assert_error(GetStorageAtError::ContractNotFound), ), ( ctx_with_pending_disabled, pending_contract0, pending_key0, BlockId::Pending, assert_error(GetStorageAtError::Internal(anyhow!( "Pending data not supported in this configuration" ))), ), ]; for (i, test_case) in cases.iter().enumerate() { check(i, test_case).await; } } }
use std::fs; #[test] fn validate_3_1() { assert_eq!(algorithm("src/day_3/input_test.txt"), 7); } fn algorithm(file_location: &str) -> usize { let contents = fs::read_to_string(file_location).unwrap(); let values: Vec<&str> = contents.lines().collect(); let max_cols = values.first().unwrap().len(); let mut count = 0; let mut curr_col = 0; for (i, row) in values.iter().enumerate() { let target = row.chars().nth(curr_col).unwrap(); if target == '#' && i != 0 { count = count + 1; } curr_col = (curr_col + 3) % max_cols; } count } pub fn run() { println!( "Right 3, down 1: we hit {} trees.", algorithm("src/day_3/input.txt") ); }
#![allow(dead_code)] #![allow(unused_imports)] #![allow(unused_variables)] extern crate bytes; extern crate env_logger; extern crate futures; extern crate http; extern crate h2; extern crate tokio_connect; extern crate tokio_core; extern crate tower; extern crate tower_grpc; extern crate tower_h2; use std::net::SocketAddr; use bytes::BytesMut; use futures::{Future, Stream}; use tokio_connect::Connect; use tokio_core::net::TcpStream; use tokio_core::reactor::{Core, Handle}; use tower::{Service, NewService}; use self::routeguide::{GetFeature, ListFeatures, RouteGuide, Point, Feature, Rectangle, RouteNote}; // eventually generated? mod routeguide { use futures::{Future, Poll}; use tower::Service; use tower_grpc; use tower_grpc::client::Codec; #[derive(Debug)] pub struct Point { pub latitude: i32, pub longitude: i32, } #[derive(Debug)] pub struct Rectangle { pub lo: Point, pub hi: Point, } #[derive(Debug)] pub struct Feature { pub name: String, pub location: Point, } #[derive(Debug)] pub struct RouteSummary { pub point_count: i32, pub feature_count: i32, pub distance: i32, pub elapsed_time: i32, } #[derive(Debug)] pub struct RouteNote { pub location: Point, pub message: String, } // the full "service" pub struct RouteGuide<GetFeatureRpc, ListFeaturesRpc, RecordRouteRpc, RouteChatRpc> { get_feature: GetFeatureRpc, list_features: ListFeaturesRpc, record_route: RecordRouteRpc, route_chat: RouteChatRpc, } impl<GetFeatureRpc, ListFeaturesRpc, RecordRouteRpc, RouteChatRpc, ListFeaturesStream> RouteGuide<GetFeatureRpc, ListFeaturesRpc, RecordRouteRpc, RouteChatRpc> where GetFeatureRpc: Service< Request=tower_grpc::Request<Point>, Response=tower_grpc::Response<Feature>, >, ListFeaturesRpc: Service< Request=tower_grpc::Request<Rectangle>, Response=tower_grpc::Response<ListFeaturesStream>, >, ListFeaturesStream: ::futures::Stream<Item=Feature>, { pub fn new(get_feature: GetFeatureRpc, list_features: ListFeaturesRpc, record_route: RecordRouteRpc, route_chat: RouteChatRpc) -> Self { RouteGuide { get_feature, list_features, record_route, route_chat, } } pub fn get_feature(&mut self, req: Point) -> ::futures::future::Map<GetFeatureRpc::Future, fn(tower_grpc::Response<Feature>) -> Feature> { let req = tower_grpc::Request::new("/routeguide.RouteGuide/GetFeature", req); self.get_feature.call(req) .map(|res| { res.into_http().into_parts().1 } as _) } //TODO: should this return a Stream wrapping the future? pub fn list_features(&mut self, req: Rectangle) -> ::futures::future::Map<ListFeaturesRpc::Future, fn(tower_grpc::Response<ListFeaturesStream>) -> ListFeaturesStream> { let req = tower_grpc::Request::new("/routeguide.RouteGuide/GetFeature", req); self.list_features.call(req) .map(|res| { res.into_http().into_parts().1 } as _) } } // rpc methods pub struct GetFeature<S> { service: S, } impl<C, S, E> GetFeature<S> where C: Codec<Encode=Point, Decode=Feature>, S: Service< Request=tower_grpc::Request< tower_grpc::client::codec::Unary<Point> >, Response=tower_grpc::Response< tower_grpc::client::codec::DecodingBody<C> >, Error=tower_grpc::Error<E> >, { pub fn new(service: S) -> Self { GetFeature { service, } } } impl<C, S, E> Service for GetFeature<S> where C: Codec<Encode=Point, Decode=Feature>, S: Service< Request=tower_grpc::Request< tower_grpc::client::codec::Unary<Point> >, Response=tower_grpc::Response< tower_grpc::client::codec::DecodingBody<C> >, Error=tower_grpc::Error<E> >, { type Request = tower_grpc::Request<Point>; type Response = tower_grpc::Response<Feature>; type Error = S::Error; type Future = tower_grpc::client::Unary<S::Future, C>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() } fn call(&mut self, req: Self::Request) -> Self::Future { let fut = self.service.call(req.into_unary()); tower_grpc::client::Unary::map_future(fut) } } pub struct ListFeatures<S> { service: S, } impl<C, S, E> ListFeatures<S> where C: Codec<Encode=Rectangle, Decode=Feature>, S: Service< Request=tower_grpc::Request< tower_grpc::client::codec::Unary<Rectangle> >, Response=tower_grpc::Response< tower_grpc::client::codec::DecodingBody<C> >, Error=tower_grpc::Error<E> >, { pub fn new(service: S) -> Self { ListFeatures { service, } } } impl<C, S, E> Service for ListFeatures<S> where C: Codec<Encode=Rectangle, Decode=Feature>, S: Service< Request=tower_grpc::Request< tower_grpc::client::codec::Unary<Rectangle> >, Response=tower_grpc::Response< tower_grpc::client::codec::DecodingBody<C> >, Error=tower_grpc::Error<E> >, { type Request = tower_grpc::Request<Rectangle>; type Response = tower_grpc::Response<tower_grpc::client::codec::DecodingBody<C>>; type Error = S::Error; type Future = S::Future; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() } fn call(&mut self, req: Self::Request) -> Self::Future { self.service.call(req.into_unary()) } } pub struct RecordRoute<S> { service: S, } pub struct RouteChat<S> { service: S, } } pub struct StupidCodec<T, U>(::std::marker::PhantomData<(T, U)>); impl<T, U> StupidCodec<T, U> { fn new() -> Self { StupidCodec(::std::marker::PhantomData) } } impl<T, U> Clone for StupidCodec<T, U> { fn clone(&self) -> Self { StupidCodec(::std::marker::PhantomData) } } impl tower_grpc::client::Codec for StupidCodec<Point, Feature> { const CONTENT_TYPE: &'static str = "application/proto+stupid"; type Encode = Point; type Decode = Feature; type EncodeError = (); type DecodeError = (); fn encode(&mut self, msg: Self::Encode, buf: &mut tower_grpc::client::codec::EncodeBuf) -> Result<(), Self::EncodeError> { Ok(()) } fn decode(&mut self, buf: &mut tower_grpc::client::codec::DecodeBuf) -> Result<Self::Decode, Self::DecodeError> { Ok(Feature { name: String::from("faked"), location: Point { longitude: 5, latitude: 5, } }) } } impl tower_grpc::client::Codec for StupidCodec<Rectangle, Feature> { const CONTENT_TYPE: &'static str = "application/proto+stupid"; type Encode = Rectangle; type Decode = Feature; type EncodeError = (); type DecodeError = (); fn encode(&mut self, msg: Self::Encode, buf: &mut tower_grpc::client::codec::EncodeBuf) -> Result<(), Self::EncodeError> { Ok(()) } fn decode(&mut self, buf: &mut tower_grpc::client::codec::DecodeBuf) -> Result<Self::Decode, Self::DecodeError> { Ok(Feature { name: String::from("faked"), location: Point { longitude: 5, latitude: 5, } }) } } struct Conn(SocketAddr, Handle); impl Connect for Conn { type Connected = TcpStream; type Error = ::std::io::Error; type Future = Box<Future<Item = TcpStream, Error = ::std::io::Error>>; fn connect(&self) -> Self::Future { let c = TcpStream::connect(&self.0, &self.1) .and_then(|tcp| tcp.set_nodelay(true).map(move |_| tcp)); Box::new(c) } } struct AddOrigin<S>(S); impl<S, B> Service for AddOrigin<S> where S: Service<Request=http::Request<B>>, { type Request = S::Request; type Response = S::Response; type Error = S::Error; type Future = S::Future; fn poll_ready(&mut self) -> ::futures::Poll<(), Self::Error> { self.0.poll_ready() } fn call(&mut self, mut req: Self::Request) -> Self::Future { use std::str::FromStr; //TODO: use Uri.into_parts() to be more efficient let full_uri = format!("http://127.0.0.1:8888{}", req.uri().path()); let new_uri = http::Uri::from_str(&full_uri).expect("example uri should work"); *req.uri_mut() = new_uri; self.0.call(req) } } fn main() { drop(env_logger::init()); let mut core = Core::new().unwrap(); let reactor = core.handle(); let addr = "[::1]:8888".parse().unwrap(); let conn = Conn(addr, reactor.clone()); let h2 = tower_h2::Client::new(conn, Default::default(), reactor); let done = h2.new_service() .map_err(|_e| unimplemented!("h2 new_service error")) .and_then(move |orig_service| { let service = AddOrigin(orig_service.clone_handle()); let grpc = tower_grpc::Client::new(StupidCodec::<Point, Feature>::new(), service); let get_feature = GetFeature::new(grpc); let service = AddOrigin(orig_service); let grpc = tower_grpc::Client::new(StupidCodec::<Rectangle, Feature>::new(), service); let list_features = ListFeatures::new(grpc); let mut client = RouteGuide::new(get_feature, list_features, (), ()); let valid_feature = client.get_feature(Point { latitude: 409146138, longitude: -746188906, }).map(|feature| { println!("GetFeature: {:?}", feature); }).map_err(|e| ("GetFeature", e)); let missing_feature = client.get_feature(Point { latitude: 0, longitude: 0, }).map(|feature| { println!("GetFeature: {:?}", feature); }).map_err(|e| ("GetFeature", e)); let features_between = client.list_features(Rectangle { lo: Point { latitude: 400000000, longitude: -750000000, }, hi: Point { latitude: 420000000, longitude: -730000000, } }).and_then(|features| { features.for_each(|feature| { println!("ListFeatures: {:?}", feature); Ok(()) }).map_err(|e| match e { tower_grpc::Error::Inner(h2) => tower_grpc::Error::Inner(h2.into()), tower_grpc::Error::Grpc(status) => tower_grpc::Error::Grpc(status), }) }).map_err(|e| ("ListFeatures", e)); /* let record_route = client.record_route(futures::stream::iter_ok::<_, ()>(vec![ Point { longitude: 1, latitude: 1, }, Point { longitude: 2, latitude: 2, }, ])).map(|summary| { println!("RecordRoute: {:?}", summary); }).map_err(|e| ("RecordRoute", e)); let route_chat = client.route_chat(futures::stream::iter_ok::<_, ()>(vec![ RouteNote { location: Point { longitude: 55, latitude: 55, }, message: "First note".to_string(), }, ])).for_each(|_| { Ok(()) }).map_err(|e| ("RouteChat", e)); */ valid_feature .join(missing_feature) //.join(features_between) //.join(record_route) //.join(route_chat) }) .map_err(|e| println!("error: {:?}", e)); let _ = core.run(done); }
// 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. //! Defines kvapi::KVApi key behaviors. use std::fmt::Debug; use std::string::FromUtf8Error; use crate::kvapi; #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum KeyError { #[error(transparent)] FromUtf8Error(#[from] FromUtf8Error), #[error("Non-ascii char are not supported: '{non_ascii}'")] AsciiError { non_ascii: String }, #[error("Expect {i}-th segment to be '{expect}', but: '{got}'")] InvalidSegment { i: usize, expect: String, got: String, }, #[error("Expect {expect} segments, but: '{got}'")] WrongNumberOfSegments { expect: usize, got: String }, #[error("Expect at least {expect} segments, but {actual} segments found")] AtleastSegments { expect: usize, actual: usize }, #[error("Invalid id string: '{s}': {reason}")] InvalidId { s: String, reason: String }, } /// Convert structured key to a string key used by kvapi::KVApi and backwards pub trait Key: Debug where Self: Sized { const PREFIX: &'static str; /// Encode structured key into a string. fn to_string_key(&self) -> String; /// Decode str into a structured key. fn from_str_key(s: &str) -> Result<Self, kvapi::KeyError>; } impl kvapi::Key for String { const PREFIX: &'static str = ""; fn to_string_key(&self) -> String { self.clone() } fn from_str_key(s: &str) -> Result<Self, kvapi::KeyError> { Ok(s.to_string()) } }
use std::any::Any; use tikv_jemalloc_ctl::{epoch, stats}; use metric::{Attributes, MetricKind, Observation, Reporter}; /// A `metric::Instrument` that reports jemalloc memory statistics, specifically: /// /// - a u64 gauge called "jemalloc_memstats_bytes" #[derive(Debug, Clone)] pub struct JemallocMetrics { active: Attributes, alloc: Attributes, metadata: Attributes, mapped: Attributes, resident: Attributes, retained: Attributes, } impl JemallocMetrics { pub fn new() -> Self { Self { active: Attributes::from(&[("stat", "active")]), alloc: Attributes::from(&[("stat", "alloc")]), metadata: Attributes::from(&[("stat", "metadata")]), mapped: Attributes::from(&[("stat", "mapped")]), resident: Attributes::from(&[("stat", "resident")]), retained: Attributes::from(&[("stat", "retained")]), } } } impl metric::Instrument for JemallocMetrics { fn report(&self, reporter: &mut dyn Reporter) { reporter.start_metric( "jemalloc_memstats_bytes", "jemalloc metrics - http://jemalloc.net/jemalloc.3.html#stats.active", MetricKind::U64Gauge, ); epoch::advance().unwrap(); reporter.report_observation( &self.active, Observation::U64Gauge(stats::active::read().unwrap() as u64), ); reporter.report_observation( &self.alloc, Observation::U64Gauge(stats::allocated::read().unwrap() as u64), ); reporter.report_observation( &self.metadata, Observation::U64Gauge(stats::metadata::read().unwrap() as u64), ); reporter.report_observation( &self.mapped, Observation::U64Gauge(stats::mapped::read().unwrap() as u64), ); reporter.report_observation( &self.resident, Observation::U64Gauge(stats::resident::read().unwrap() as u64), ); reporter.report_observation( &self.retained, Observation::U64Gauge(stats::retained::read().unwrap() as u64), ); reporter.finish_metric(); } fn as_any(&self) -> &dyn Any { self } }
use std::fmt::{Debug, Formatter}; use async_trait::async_trait; use reqwest::header::{HeaderMap, HeaderValue}; use reqwest::Client; use serde::Deserialize; use crate::error::Error; mod code; mod password; mod token; pub use code::CodeAuthenticator; pub use password::PasswordAuthenticator; pub use token::TokenAuthenticator; pub static AUTH_CONTENT_TYPE: HeaderValue = HeaderValue::from_static("application/x-www-form-urlencoded"); #[derive(Deserialize, Debug)] pub struct TokenResponseData { pub access_token: String, pub expires_in: u64, pub scope: String, pub token_type: String, #[serde(default = "default_response")] pub refresh_token: String, } fn default_response() -> String { "".to_string() } #[async_trait(?Send)] pub trait Authenticator: Clone + Send + Sync + Debug { /// Logins to the Reddit API /// true if successful async fn login(&mut self, client: &Client, user_agent: &str) -> Result<bool, Error>; /// Releases the token back to Reddit async fn logout(&mut self, client: &Client, user_agent: &str) -> Result<(), Error>; /// true if successful async fn token_refresh(&mut self, client: &Client, user_agent: &str) -> Result<bool, Error>; /// Header Values required for auth fn headers(&self, headers: &mut HeaderMap); /// Supports OAuth fn oauth(&self) -> bool; /// Does the Token need refresh fn needs_token_refresh(&self) -> bool; /// Returns refresh token fn get_refresh_token(&self) -> Option<String>; } pub trait Authorized: Authenticator {} /// AnonymousAuthenticator #[derive(Clone, Default)] pub struct AnonymousAuthenticator; impl Debug for AnonymousAuthenticator { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "[AnonymousAuthenticator]") } } #[async_trait(?Send)] impl Authenticator for AnonymousAuthenticator { /// Returns true because it is anonymous async fn login(&mut self, _client: &Client, _user_agent: &str) -> Result<bool, Error> { Ok(true) } /// Does nothing async fn logout(&mut self, _client: &Client, _user_agent: &str) -> Result<(), Error> { Ok(()) } /// Returns true because it is anonymous async fn token_refresh(&mut self, _client: &Client, _user_agent: &str) -> Result<bool, Error> { Ok(true) } /// Does Nothing fn headers(&self, _headers: &mut HeaderMap) {} /// False because not logged in fn oauth(&self) -> bool { false } /// Always false fn needs_token_refresh(&self) -> bool { false } /// Always None fn get_refresh_token(&self) -> Option<String> { Option::None } } impl AnonymousAuthenticator { /// Creates a new Authenticator pub fn new() -> AnonymousAuthenticator { AnonymousAuthenticator } }
extern crate criterion; extern crate libdna; use crate::libdna::libdna_ffi; use crate::libdna::native; use criterion::{criterion_group, criterion_main, Criterion}; use std::os::raw::c_char; const LENGTH: usize = 1_000_000; fn mutc(c: char) -> char { const order: [char; 5] = ['A', 'C', 'G', 'T', 'A']; let index = ((c as u8 & 6) / 2 + 1) as usize; order[index] } #[cfg(test)] fn does_mut() { assert!(mutc('A') != 'A'); } fn mutate(forward: &str, stride: usize) -> String { use std::iter::FromIterator; String::from_iter(forward.bytes().enumerate().map(|(i, c)| { let cc = c as char; if i % stride == 0 { mutc(cc) } else { cc } })) } fn first_mismatch(a: &str, b: &str) -> usize { use std::iter::zip; for (i, (a, b)) in zip(a.bytes(), b.bytes()).enumerate() { if a != b { return i; } } a.len() } #[test] fn t() { assert_eq!(first_mismatch("acgt", "acG"), 2); } #[link(name = "dna")] extern "C" { fn dnax_find_first_mismatch( begin: *const c_char, end: *const c_char, other: *const c_char, ) -> *const c_char; } #[inline] fn to_ptrs(forward: &str) -> (*const c_char, *const c_char) { let size = forward.len(); let begin = forward.as_ptr() as *const c_char; let end = unsafe { begin.offset(size as isize) }; (begin, end) } fn find_first_mismatch(a: &str, b: &str) -> usize { let (begin, end) = to_ptrs(a); let (other, _) = to_ptrs(b); let ptr = unsafe { dnax_find_first_mismatch(begin, end, other) }; unsafe { ptr.offset_from(begin) as usize } } fn criterion_benchmark(c: &mut Criterion) { let forward = libdna_ffi::dna4::random(LENGTH, 1729); let other = mutate(&forward, 71); c.bench_function("native", |b| { b.iter(|| { let mut i = 0; while i < forward.len() { i += first_mismatch(&forward[i..], &other[i..]); i += 1; } }) }); c.bench_function("ffi", |b| { b.iter(|| { let mut i = 0; while i < forward.len() { i += find_first_mismatch(&forward[i..], &other[i..]); i += 1; } }) }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
/// `mbe` (short for Macro By Example) crate contains code for handling /// `macro_rules` macros. It uses `TokenTree` (from `ra_tt` package) as the /// interface, although it contains some code to bridge `SyntaxNode`s and /// `TokenTree`s as well! macro_rules! impl_froms { ($e:ident: $($v:ident), *) => { $( impl From<$v> for $e { fn from(it: $v) -> $e { $e::$v(it) } } )* } } // mod tt_cursor; mod mbe_parser; mod mbe_expander; mod syntax_bridge; mod tt_cursor; mod subtree_source; mod subtree_parser; use ra_syntax::SmolStr; pub use tt::{Delimiter, Punct}; #[derive(Debug, PartialEq, Eq)] pub enum ParseError { Expected(String), } #[derive(Debug, PartialEq, Eq)] pub enum ExpandError { NoMatchingRule, UnexpectedToken, BindingError(String), ConversionError, } pub use crate::syntax_bridge::{ ast_to_token_tree, token_tree_to_ast_item_list, syntax_node_to_token_tree, token_tree_to_expr, token_tree_to_pat, token_tree_to_ty, token_tree_to_macro_items, token_tree_to_macro_stmts, }; /// This struct contains AST for a single `macro_rules` definition. What might /// be very confusing is that AST has almost exactly the same shape as /// `tt::TokenTree`, but there's a crucial difference: in macro rules, `$ident` /// and `$()*` have special meaning (see `Var` and `Repeat` data structures) #[derive(Clone, Debug, PartialEq, Eq)] pub struct MacroRules { pub(crate) rules: Vec<Rule>, } impl MacroRules { pub fn parse(tt: &tt::Subtree) -> Result<MacroRules, ParseError> { mbe_parser::parse(tt) } pub fn expand(&self, tt: &tt::Subtree) -> Result<tt::Subtree, ExpandError> { mbe_expander::expand(self, tt) } } #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Rule { pub(crate) lhs: Subtree, pub(crate) rhs: Subtree, } #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum TokenTree { Leaf(Leaf), Subtree(Subtree), Repeat(Repeat), } impl_froms!(TokenTree: Leaf, Subtree, Repeat); #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Leaf { Literal(Literal), Punct(Punct), Ident(Ident), Var(Var), } impl_froms!(Leaf: Literal, Punct, Ident, Var); #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Subtree { pub(crate) delimiter: Delimiter, pub(crate) token_trees: Vec<TokenTree>, } #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Repeat { pub(crate) subtree: Subtree, pub(crate) kind: RepeatKind, pub(crate) separator: Option<char>, } #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum RepeatKind { ZeroOrMore, OneOrMore, ZeroOrOne, } #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Literal { pub(crate) text: SmolStr, } #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Ident { pub(crate) text: SmolStr, } #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Var { pub(crate) text: SmolStr, pub(crate) kind: Option<SmolStr>, } #[cfg(test)] mod tests { use ra_syntax::{ast, AstNode}; use super::*; // Good first issue (although a slightly challenging one): // // * Pick a random test from here // https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt // * Port the test to rust and add it to this module // * Make it pass :-) #[test] fn test_convert_tt() { let macro_definition = r#" macro_rules! impl_froms { ($e:ident: $($v:ident),*) => { $( impl From<$v> for $e { fn from(it: $v) -> $e { $e::$v(it) } } )* } } "#; let macro_invocation = r#" impl_froms!(TokenTree: Leaf, Subtree); "#; let source_file = ast::SourceFile::parse(macro_definition); let macro_definition = source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap(); let source_file = ast::SourceFile::parse(macro_invocation); let macro_invocation = source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap(); let (definition_tt, _) = ast_to_token_tree(macro_definition.token_tree().unwrap()).unwrap(); let (invocation_tt, _) = ast_to_token_tree(macro_invocation.token_tree().unwrap()).unwrap(); let rules = crate::MacroRules::parse(&definition_tt).unwrap(); let expansion = rules.expand(&invocation_tt).unwrap(); assert_eq!( expansion.to_string(), "impl From < Leaf > for TokenTree {fn from (it : Leaf) -> TokenTree {TokenTree :: Leaf (it)}} \ impl From < Subtree > for TokenTree {fn from (it : Subtree) -> TokenTree {TokenTree :: Subtree (it)}}" ) } pub(crate) fn create_rules(macro_definition: &str) -> MacroRules { let source_file = ast::SourceFile::parse(macro_definition); let macro_definition = source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap(); let (definition_tt, _) = ast_to_token_tree(macro_definition.token_tree().unwrap()).unwrap(); crate::MacroRules::parse(&definition_tt).unwrap() } pub(crate) fn expand(rules: &MacroRules, invocation: &str) -> tt::Subtree { let source_file = ast::SourceFile::parse(invocation); let macro_invocation = source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap(); let (invocation_tt, _) = ast_to_token_tree(macro_invocation.token_tree().unwrap()).unwrap(); rules.expand(&invocation_tt).unwrap() } pub(crate) fn expand_to_syntax( rules: &MacroRules, invocation: &str, ) -> ra_syntax::TreeArc<ast::MacroItems> { let expanded = expand(rules, invocation); token_tree_to_macro_items(&expanded).unwrap() } pub(crate) fn assert_expansion(rules: &MacroRules, invocation: &str, expansion: &str) { let expanded = expand(rules, invocation); assert_eq!(expanded.to_string(), expansion); let tree = token_tree_to_macro_items(&expanded); // Eat all white space by parse it back and forth let expansion = ast::SourceFile::parse(expansion); let expansion = syntax_node_to_token_tree(expansion.syntax()).unwrap().0; let file = token_tree_to_macro_items(&expansion); assert_eq!( tree.unwrap().syntax().debug_dump().trim(), file.unwrap().syntax().debug_dump().trim() ); } #[test] fn test_fail_match_pattern_by_first_token() { let rules = create_rules( r#" macro_rules! foo { ($ i:ident) => ( mod $ i {} ); (= $ i:ident) => ( fn $ i() {} ); (+ $ i:ident) => ( struct $ i; ) } "#, ); assert_expansion(&rules, "foo! { foo }", "mod foo {}"); assert_expansion(&rules, "foo! { = bar }", "fn bar () {}"); assert_expansion(&rules, "foo! { + Baz }", "struct Baz ;"); } #[test] fn test_fail_match_pattern_by_last_token() { let rules = create_rules( r#" macro_rules! foo { ($ i:ident) => ( mod $ i {} ); ($ i:ident =) => ( fn $ i() {} ); ($ i:ident +) => ( struct $ i; ) } "#, ); assert_expansion(&rules, "foo! { foo }", "mod foo {}"); assert_expansion(&rules, "foo! { bar = }", "fn bar () {}"); assert_expansion(&rules, "foo! { Baz + }", "struct Baz ;"); } #[test] fn test_fail_match_pattern_by_word_token() { let rules = create_rules( r#" macro_rules! foo { ($ i:ident) => ( mod $ i {} ); (spam $ i:ident) => ( fn $ i() {} ); (eggs $ i:ident) => ( struct $ i; ) } "#, ); assert_expansion(&rules, "foo! { foo }", "mod foo {}"); assert_expansion(&rules, "foo! { spam bar }", "fn bar () {}"); assert_expansion(&rules, "foo! { eggs Baz }", "struct Baz ;"); } #[test] fn test_match_group_pattern_by_separator_token() { let rules = create_rules( r#" macro_rules! foo { ($ ($ i:ident),*) => ($ ( mod $ i {} )*); ($ ($ i:ident)#*) => ($ ( fn $ i() {} )*); ($ i:ident ,# $ j:ident) => ( struct $ i; struct $ j; ) } "#, ); assert_expansion(&rules, "foo! { foo, bar }", "mod foo {} mod bar {}"); assert_expansion(&rules, "foo! { foo# bar }", "fn foo () {} fn bar () {}"); assert_expansion(&rules, "foo! { Foo,# Bar }", "struct Foo ; struct Bar ;"); } #[test] fn test_match_group_pattern_with_multiple_defs() { let rules = create_rules( r#" macro_rules! foo { ($ ($ i:ident),*) => ( struct Bar { $ ( fn $ i {} )*} ); } "#, ); assert_expansion(&rules, "foo! { foo, bar }", "struct Bar {fn foo {} fn bar {}}"); } #[test] fn test_match_group_pattern_with_multiple_statement() { let rules = create_rules( r#" macro_rules! foo { ($ ($ i:ident),*) => ( fn baz { $ ( $ i (); )*} ); } "#, ); assert_expansion(&rules, "foo! { foo, bar }", "fn baz {foo () ; bar () ;}"); } #[test] fn expand_to_item_list() { let rules = create_rules( " macro_rules! structs { ($($i:ident),*) => { $(struct $i { field: u32 } )* } } ", ); let expansion = expand(&rules, "structs!(Foo, Bar)"); let tree = token_tree_to_macro_items(&expansion); assert_eq!( tree.unwrap().syntax().debug_dump().trim(), r#" MACRO_ITEMS@[0; 40) STRUCT_DEF@[0; 20) STRUCT_KW@[0; 6) "struct" NAME@[6; 9) IDENT@[6; 9) "Foo" NAMED_FIELD_DEF_LIST@[9; 20) L_CURLY@[9; 10) "{" NAMED_FIELD_DEF@[10; 19) NAME@[10; 15) IDENT@[10; 15) "field" COLON@[15; 16) ":" PATH_TYPE@[16; 19) PATH@[16; 19) PATH_SEGMENT@[16; 19) NAME_REF@[16; 19) IDENT@[16; 19) "u32" R_CURLY@[19; 20) "}" STRUCT_DEF@[20; 40) STRUCT_KW@[20; 26) "struct" NAME@[26; 29) IDENT@[26; 29) "Bar" NAMED_FIELD_DEF_LIST@[29; 40) L_CURLY@[29; 30) "{" NAMED_FIELD_DEF@[30; 39) NAME@[30; 35) IDENT@[30; 35) "field" COLON@[35; 36) ":" PATH_TYPE@[36; 39) PATH@[36; 39) PATH_SEGMENT@[36; 39) NAME_REF@[36; 39) IDENT@[36; 39) "u32" R_CURLY@[39; 40) "}""# .trim() ); } #[test] fn expand_literals_to_token_tree() { fn to_subtree(tt: &tt::TokenTree) -> &tt::Subtree { if let tt::TokenTree::Subtree(subtree) = tt { return &subtree; } unreachable!("It is not a subtree"); } fn to_literal(tt: &tt::TokenTree) -> &tt::Literal { if let tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) = tt { return lit; } unreachable!("It is not a literal"); } let rules = create_rules( r#" macro_rules! literals { ($i:ident) => { { let a = 'c'; let c = 1000; let f = 12E+99_f64; let s = "rust1"; } } } "#, ); let expansion = expand(&rules, "literals!(foo)"); let stm_tokens = &to_subtree(&expansion.token_trees[0]).token_trees; // [let] [a] [=] ['c'] [;] assert_eq!(to_literal(&stm_tokens[3]).text, "'c'"); // [let] [c] [=] [1000] [;] assert_eq!(to_literal(&stm_tokens[5 + 3]).text, "1000"); // [let] [f] [=] [12E+99_f64] [;] assert_eq!(to_literal(&stm_tokens[10 + 3]).text, "12E+99_f64"); // [let] [s] [=] ["rust1"] [;] assert_eq!(to_literal(&stm_tokens[15 + 3]).text, "\"rust1\""); } #[test] fn test_two_idents() { let rules = create_rules( r#" macro_rules! foo { ($ i:ident, $ j:ident) => { fn foo() { let a = $ i; let b = $j; } } } "#, ); assert_expansion(&rules, "foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}"); } #[test] fn test_tt_to_stmts() { let rules = create_rules( r#" macro_rules! foo { () => { let a = 0; a = 10 + 1; a } } "#, ); let expanded = expand(&rules, "foo!{}"); let stmts = token_tree_to_macro_stmts(&expanded); assert_eq!( stmts.unwrap().syntax().debug_dump().trim(), r#"MACRO_STMTS@[0; 15) LET_STMT@[0; 7) LET_KW@[0; 3) "let" BIND_PAT@[3; 4) NAME@[3; 4) IDENT@[3; 4) "a" EQ@[4; 5) "=" LITERAL@[5; 6) INT_NUMBER@[5; 6) "0" SEMI@[6; 7) ";" EXPR_STMT@[7; 14) BIN_EXPR@[7; 13) PATH_EXPR@[7; 8) PATH@[7; 8) PATH_SEGMENT@[7; 8) NAME_REF@[7; 8) IDENT@[7; 8) "a" EQ@[8; 9) "=" BIN_EXPR@[9; 13) LITERAL@[9; 11) INT_NUMBER@[9; 11) "10" PLUS@[11; 12) "+" LITERAL@[12; 13) INT_NUMBER@[12; 13) "1" SEMI@[13; 14) ";" EXPR_STMT@[14; 15) PATH_EXPR@[14; 15) PATH@[14; 15) PATH_SEGMENT@[14; 15) NAME_REF@[14; 15) IDENT@[14; 15) "a""#, ); } // The following tests are port from intellij-rust directly // https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt #[test] fn test_path() { let rules = create_rules( r#" macro_rules! foo { ($ i:path) => { fn foo() { let a = $ i; } } } "#, ); assert_expansion(&rules, "foo! { foo }", "fn foo () {let a = foo ;}"); assert_expansion( &rules, "foo! { bar::<u8>::baz::<u8> }", "fn foo () {let a = bar :: < u8 > :: baz :: < u8 > ;}", ); } #[test] fn test_two_paths() { let rules = create_rules( r#" macro_rules! foo { ($ i:path, $ j:path) => { fn foo() { let a = $ i; let b = $j; } } } "#, ); assert_expansion(&rules, "foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}"); } #[test] fn test_path_with_path() { let rules = create_rules( r#" macro_rules! foo { ($ i:path) => { fn foo() { let a = $ i :: bar; } } } "#, ); assert_expansion(&rules, "foo! { foo }", "fn foo () {let a = foo :: bar ;}"); } #[test] fn test_expr() { let rules = create_rules( r#" macro_rules! foo { ($ i:expr) => { fn bar() { $ i; } } } "#, ); assert_expansion( &rules, "foo! { 2 + 2 * baz(3).quux() }", "fn bar () {2 + 2 * baz (3) . quux () ;}", ); } #[test] fn test_expr_order() { let rules = create_rules( r#" macro_rules! foo { ($ i:expr) => { fn bar() { $ i * 2; } } } "#, ); assert_eq!( expand_to_syntax(&rules, "foo! { 1 + 1 }").syntax().debug_dump().trim(), r#"MACRO_ITEMS@[0; 15) FN_DEF@[0; 15) FN_KW@[0; 2) "fn" NAME@[2; 5) IDENT@[2; 5) "bar" PARAM_LIST@[5; 7) L_PAREN@[5; 6) "(" R_PAREN@[6; 7) ")" BLOCK@[7; 15) L_CURLY@[7; 8) "{" EXPR_STMT@[8; 14) BIN_EXPR@[8; 13) BIN_EXPR@[8; 11) LITERAL@[8; 9) INT_NUMBER@[8; 9) "1" PLUS@[9; 10) "+" LITERAL@[10; 11) INT_NUMBER@[10; 11) "1" STAR@[11; 12) "*" LITERAL@[12; 13) INT_NUMBER@[12; 13) "2" SEMI@[13; 14) ";" R_CURLY@[14; 15) "}""#, ); } #[test] fn test_last_expr() { let rules = create_rules( r#" macro_rules! vec { ($($item:expr),*) => { { let mut v = Vec::new(); $( v.push($item); )* v } }; } "#, ); assert_expansion( &rules, "vec!(1,2,3)", "{let mut v = Vec :: new () ; v . push (1) ; v . push (2) ; v . push (3) ; v}", ); } #[test] fn test_ty() { let rules = create_rules( r#" macro_rules! foo { ($ i:ty) => ( fn bar() -> $ i { unimplemented!() } ) } "#, ); assert_expansion( &rules, "foo! { Baz<u8> }", "fn bar () -> Baz < u8 > {unimplemented ! ()}", ); } #[test] fn test_pat_() { let rules = create_rules( r#" macro_rules! foo { ($ i:pat) => { fn foo() { let $ i; } } } "#, ); assert_expansion(&rules, "foo! { (a, b) }", "fn foo () {let (a , b) ;}"); } #[test] fn test_stmt() { let rules = create_rules( r#" macro_rules! foo { ($ i:stmt) => ( fn bar() { $ i; } ) } "#, ); assert_expansion(&rules, "foo! { 2 }", "fn bar () {2 ;}"); assert_expansion(&rules, "foo! { let a = 0 }", "fn bar () {let a = 0 ;}"); } #[test] fn test_single_item() { let rules = create_rules( r#" macro_rules! foo { ($ i:item) => ( $ i ) } "#, ); assert_expansion(&rules, "foo! {mod c {}}", "mod c {}"); } #[test] fn test_all_items() { let rules = create_rules( r#" macro_rules! foo { ($ ($ i:item)*) => ($ ( $ i )*) } "#, ); assert_expansion(&rules, r#" foo! { extern crate a; mod b; mod c {} use d; const E: i32 = 0; static F: i32 = 0; impl G {} struct H; enum I { Foo } trait J {} fn h() {} extern {} type T = u8; } "#, r#"extern crate a ; mod b ; mod c {} use d ; const E : i32 = 0 ; static F : i32 = 0 ; impl G {} struct H ; enum I {Foo} trait J {} fn h () {} extern {} type T = u8 ;"#); } }
#![feature(arbitrary_enum_discriminant)] #![feature(associated_type_bounds)] #![feature(try_blocks)] #![feature(generic_associated_types)] #![feature(let_else)] #![feature(once_cell)] pub mod linker; pub mod meta; pub mod passes; use firefly_llvm as llvm; use firefly_mlir as mlir; /// Perform initialization of MLIR/LLVM for code generation pub fn init(options: &firefly_session::Options) -> anyhow::Result<()> { mlir::init(options)?; llvm::init(options)?; Ok(()) }
fn main() { panic!("panic message {can} be formatted", can = "CaN"); }
use af; use af::{Array, Dim4, MatProp}; use std::sync::{Arc, Mutex}; use utils; use activations; use params::Params; use layer::Layer; pub struct RNN { pub input_size: usize, pub output_size: usize, } impl Layer for RNN { fn forward(&self, params: Arc<Mutex<Params>>, inputs: &Array) -> Array { // get a handle to the underlying params let mut ltex = params.lock().unwrap(); let current_unroll = ltex.current_unroll; // z_t = xW [bias added in h_t] let wx = af::matmul(&inputs //activated_input , &ltex.weights[0] , MatProp::NONE , MatProp::NONE); // uh_tm1 = htm1 U [bias added in h_t] // handle case where time = 0 let uhtm1 = match ltex.recurrences.len(){ 0 => { let output_size = ltex.weights[1].dims()[0]; // is [M x M] let init_h_dims = Dim4::new(&[inputs.dims()[0], output_size, 1, 1]); ltex.recurrences.push(utils::constant(init_h_dims, inputs.get_type(), 0f32)); af::matmul(&utils::constant(init_h_dims, inputs.get_type(), 0f32) , &ltex.weights[1] , MatProp::NONE , MatProp::NONE) }, _ => { af::matmul(&ltex.recurrences[ltex.current_unroll] , &ltex.weights[1] , MatProp::NONE , MatProp::NONE) } }; // h_t = uh_tm1 + wx + b let h_t = af::transpose(&af::add(&af::transpose(&uhtm1, false), &af::add(&af::transpose(&wx, false) , &ltex.biases[0], true), false) , false); // a_t = sigma(h_t) let a_t = activations::get_activation(&ltex.activations[0], &h_t).unwrap(); // parameter manager keeps the output & inputs if ltex.inputs.len() > current_unroll { // store in existing ltex.inputs[current_unroll] = inputs.clone(); ltex.outputs[current_unroll] = a_t.clone(); ltex.recurrences[current_unroll] = h_t.clone(); }else{ // add new ltex.inputs.push(inputs.clone()); ltex.outputs.push(a_t.clone()); ltex.recurrences.push(h_t.clone()); } // update location in vector ltex.current_unroll += 1; a_t.clone() // clone just increases the ref count } fn backward(&self, params: Arc<Mutex<Params>>, delta: &Array) -> Array { // get a handle to the underlying params let mut ltex = params.lock().unwrap(); let current_unroll = ltex.current_unroll; assert!(current_unroll > 0 , "Cannot call backward pass without at least 1 forward pass"); // delta_t = (transpose(W_{t+1}) * d_{l+1}) .* dActivation(z) // delta_{t-1} = (transpose(W_{t}) * d_{l}) let dz = activations::get_derivative(&ltex.activations[0] , &ltex.outputs[current_unroll - 1]).unwrap(); let delta_t = af::mul(delta, &dz, false); let dw = af::matmul(&ltex.inputs[current_unroll - 1], &delta_t // delta_w = delta_t * a_{t} , af::MatProp::TRANS , af::MatProp::NONE); let du = af::matmul(&ltex.recurrences[current_unroll - 1], &delta_t // delta_u = delta_t * h_{t-1} , af::MatProp::TRANS , af::MatProp::NONE); let db = af::transpose(&af::sum(&delta_t, 0), false); // delta_b = \sum_{batch} delta ltex.deltas[0] = af::add(&ltex.deltas[0], &dw, false); ltex.deltas[1] = af::add(&ltex.deltas[1], &du, false); ltex.deltas[2] = af::add(&ltex.deltas[2], &db, false); // update location in vector ltex.current_unroll -= 1; af::matmul(&delta_t, &ltex.weights[0], af::MatProp::NONE, af::MatProp::TRANS) } }
use crate::constants; pub fn parse_cli_args<'a>() -> clap::ArgMatches<'a> { clap::app_from_crate!() .arg( clap::Arg::with_name("bind") .value_name("address:port") .help("IP address and port to bind") .short("b") .long("bind") .takes_value(true) .env("SOLDANK_SERVER_BIND"), ) .arg( clap::Arg::with_name("map") .value_name("map name") .help("name of map to load") .short("m") .long("map") .takes_value(true) .default_value(constants::DEFAULT_MAP) .env("SOLDANK_USE_MAP"), ) .arg( clap::Arg::with_name("key") .help("server connection key") .short("k") .long("key") .takes_value(true) .env("SOLDANK_SERVER_KEY"), ) .arg( clap::Arg::with_name("set") .help("set cvar value [multiple]") .long("set") .takes_value(true) .multiple(true) .number_of_values(2) .value_names(&["cvar", "value"]), ) .get_matches() }
// 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_raft_store::key_spaces::RaftStoreEntry; use common_meta_stoerr::MetaStorageError; /// Convert one line of serialized key-value into json. /// /// Exported data is a pair of key with one char prefix and value. /// Both key and value are in Vec<u8> format. /// The prefix identifies the subtree this record belongs to. See [`SledKeySpace`]. /// /// The output json is in form of `(tree_name, {keyspace: {key, value}})`. /// In this impl the `tree_name` can be one of `state`, `log` and `sm`. See [`MetaRaftStore`]. pub fn vec_kv_to_json(tree_name: &str, kv: &[Vec<u8>]) -> Result<String, MetaStorageError> { let kv_entry = RaftStoreEntry::deserialize(&kv[0], &kv[1])?; let tree_kv = (tree_name, kv_entry); let line = serde_json::to_string(&tree_kv)?; Ok(line) }
use crate::lttp::{ logic::{ Availability, RandoLogic, Rule, }, Dungeon, DungeonState, GameState, Medallion, }; use serde::{ Deserialize, Serialize, }; use std::cmp::{ max, min, }; use tracing::error; use ts_rs::TS; #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, TS)] #[ts(export, export_to = "ui/src/server_types/DungeonAvailability.ts")] #[serde(rename_all = "camelCase")] pub enum DungeonAvailability { DesertPalace, EasternPalace, GanonsTower, IcePalace, MiseryMire, PalaceOfDarkness, SkullWoods, SwampPalace, ThievesTown, TowerOfHera, TurtleRock, } impl DungeonAvailability { #[allow(clippy::too_many_lines)] pub fn can_enter( self, state: &GameState, dungeons: &DungeonState, logic: RandoLogic, agahnim_check: bool, allow_out_of_logic_glitches: bool, ) -> bool { #[allow(clippy::match_same_arms, clippy::match_wildcard_for_single_variants)] match self { DungeonAvailability::DesertPalace => { return match logic { RandoLogic::Glitchless => { Rule::Book.check(state) || (Rule::Mirror.check(state) && Rule::CanLiftDarkRocks.check(state) && Rule::CanFly.check(state)) } RandoLogic::OverWorldGlitches => { Rule::Book.check(state) || Rule::Boots.check(state) || (Rule::Mirror.check(state) && Rule::CanEnterMireArea.check_with_options( state, RandoLogic::OverWorldGlitches, agahnim_check, allow_out_of_logic_glitches, )) } RandoLogic::MajorGlitches => { Rule::Book.check(state) || Rule::Boots.check(state) || (Rule::Mirror.check(state) && Rule::CanEnterMireArea.check_with_options( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, )) } } } DungeonAvailability::GanonsTower => { return match logic { RandoLogic::Glitchless => { Rule::AllSevenCrystals.check(state) && Rule::MoonPearl.check(state) && Rule::CanEnterEastDarkWorldDeathMountain.check_with_options( state, RandoLogic::Glitchless, false, allow_out_of_logic_glitches, ) } RandoLogic::OverWorldGlitches => { Rule::Boots.check(state) && Rule::MoonPearl.check(state) } RandoLogic::MajorGlitches => { Rule::CanEnterWestDeathMountain.check_with_options( state, RandoLogic::MajorGlitches, false, allow_out_of_logic_glitches, ) } } } DungeonAvailability::IcePalace => { return match logic { RandoLogic::Glitchless => { Rule::CanLiftDarkRocks.check(state) && Rule::CanMeltThings.check(state) && (allow_out_of_logic_glitches || (Rule::MoonPearl.check(state) && Rule::Flippers.check(state))) } RandoLogic::OverWorldGlitches => { Rule::CanLiftDarkRocks.check(state) && Rule::CanMeltThings.check(state) } RandoLogic::MajorGlitches => { Rule::CanLiftDarkRocks.check(state) || (Rule::Mirror.check(state) && Rule::GlitchedLinkInDarkWorld.check(state) && Rule::CanEnterSouthDarkWorld.check_with_options( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, )) } } } DungeonAvailability::MiseryMire => { return match logic { RandoLogic::Glitchless => { self.has_medallion(state, dungeons) && Rule::Sword1.check(state) && Rule::MoonPearl.check(state) && (Rule::Boots.check(state) || Rule::HookShot.check(state)) && Rule::CanEnterMireArea.check_with_options( state, RandoLogic::Glitchless, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::OverWorldGlitches => { self.has_medallion(state, dungeons) && Rule::Sword1.check(state) && Rule::MoonPearl.check(state) && (Rule::Boots.check(state) || Rule::HookShot.check(state)) && Rule::CanEnterMireArea.check_with_options( state, RandoLogic::OverWorldGlitches, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::MajorGlitches => { self.has_medallion(state, dungeons) && Rule::Sword1.check(state) && (Rule::MoonPearl.check(state) || (Rule::Bottle.check(state) && Rule::Boots.check(state))) && (Rule::Boots.check(state) || Rule::HookShot.check(state)) && Rule::CanEnterMireArea.check_with_options( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) } } } DungeonAvailability::PalaceOfDarkness => { if logic < RandoLogic::MajorGlitches { return Rule::CanEnterNorthEastDarkWorld.check_with_options( state, logic, agahnim_check, allow_out_of_logic_glitches, ) && Rule::MoonPearl.check(state); } return (Rule::GlitchedLinkInDarkWorld.check(state) && Rule::CanEnterNorthEastDarkWorld.check_with_options( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, )) || Rule::CanEnterWestDeathMountain.check_with_options( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ); } DungeonAvailability::SkullWoods => { if logic == RandoLogic::Glitchless { return Rule::MoonPearl.check(state) && Rule::CanEnterNorthWestDarkWorld.check_with_options( state, RandoLogic::Glitchless, agahnim_check, allow_out_of_logic_glitches, ); } return Rule::CanEnterNorthWestDarkWorld.check_with_options( state, logic, agahnim_check, allow_out_of_logic_glitches, ); } DungeonAvailability::SwampPalace => { if logic < RandoLogic::MajorGlitches { return Rule::MoonPearl.check(state) && Rule::Mirror.check(state) && Rule::Flippers.check(state) && Rule::CanEnterSouthDarkWorld.check_with_options( state, logic, agahnim_check, allow_out_of_logic_glitches, ); } return DungeonAvailability::MiseryMire.can_enter( state, dungeons, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) || (Rule::MoonPearl.check(state) && Rule::Mirror.check(state) && Rule::Flippers.check(state) && Rule::CanEnterSouthDarkWorld.check_with_options( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, )); } DungeonAvailability::ThievesTown => { return if logic == RandoLogic::Glitchless { Rule::GlitchedLinkInDarkWorld.check(state) && Rule::CanEnterNorthWestDarkWorld.check_with_options( state, RandoLogic::Glitchless, agahnim_check, allow_out_of_logic_glitches, ) } else { Rule::MoonPearl.check(state) && Rule::CanEnterNorthWestDarkWorld.check_with_options( state, logic, agahnim_check, allow_out_of_logic_glitches, ) }; } DungeonAvailability::TowerOfHera => { return match logic { RandoLogic::Glitchless => { Rule::CanEnterWestDeathMountain.check_with_options( state, RandoLogic::Glitchless, false, allow_out_of_logic_glitches, ) && (Rule::Mirror.check(state) || (Rule::HookShot.check(state) && Rule::Hammer.check(state))) } RandoLogic::OverWorldGlitches => { Rule::Boots.check(state) || (Rule::CanEnterWestDeathMountain.check_with_options( state, RandoLogic::OverWorldGlitches, false, allow_out_of_logic_glitches, ) && (Rule::Mirror.check(state) || (Rule::HookShot.check(state) && Rule::Hammer.check(state)))) } RandoLogic::MajorGlitches => { Rule::Boots.check(state) || (Rule::CanEnterWestDeathMountain.check_with_options( state, RandoLogic::MajorGlitches, false, allow_out_of_logic_glitches, ) && (Rule::Mirror.check(state) || (Rule::HookShot.check(state) && Rule::Hammer.check(state)))) || DungeonAvailability::MiseryMire.can_enter( state, dungeons, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) } }; } DungeonAvailability::TurtleRock => { return match logic { RandoLogic::Glitchless => { Self::upper_can( state, dungeons, RandoLogic::Glitchless, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::OverWorldGlitches => { Self::middle( state, RandoLogic::OverWorldGlitches, agahnim_check, allow_out_of_logic_glitches, ) || Self::upper_can( state, dungeons, RandoLogic::OverWorldGlitches, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::MajorGlitches => { Self::lower( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) || Self::middle( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) || Self::upper_can( state, dungeons, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) } } } x => error!("can_enter not yet implemented for {:?}", x), } false } #[allow(clippy::too_many_lines)] pub fn may_enter( self, state: &GameState, dungeons: &DungeonState, logic: RandoLogic, agahnim_check: bool, allow_out_of_logic_glitches: bool, ) -> bool { match self { DungeonAvailability::MiseryMire => { return match logic { RandoLogic::Glitchless => { self.may_have_medallion(state, dungeons) && Rule::Sword1.check(state) && Rule::MoonPearl.check(state) && (Rule::Boots.check(state) || Rule::HookShot.check(state)) && Rule::CanEnterMireArea.check_with_options( state, RandoLogic::Glitchless, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::OverWorldGlitches => { self.may_have_medallion(state, dungeons) && Rule::Sword1.check(state) && Rule::MoonPearl.check(state) && (Rule::Boots.check(state) || Rule::HookShot.check(state)) && Rule::CanEnterMireArea.check_with_options( state, RandoLogic::OverWorldGlitches, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::MajorGlitches => { self.may_have_medallion(state, dungeons) && Rule::Sword1.check(state) && (Rule::MoonPearl.check(state) || (Rule::Bottle.check(state) && Rule::Boots.check(state))) && (Rule::Boots.check(state) || Rule::HookShot.check(state)) && Rule::CanEnterMireArea.check_with_options( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) } } } DungeonAvailability::TowerOfHera => { if logic < RandoLogic::MajorGlitches { return self.can_enter(state, dungeons, logic, false, false); } return DungeonAvailability::MiseryMire.may_enter( state, dungeons, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ); } DungeonAvailability::TurtleRock => { return match logic { RandoLogic::Glitchless => { Self::upper_may( state, dungeons, RandoLogic::Glitchless, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::OverWorldGlitches => { Self::middle( state, RandoLogic::OverWorldGlitches, agahnim_check, allow_out_of_logic_glitches, ) || Self::upper_may( state, dungeons, RandoLogic::OverWorldGlitches, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::MajorGlitches => { Self::lower( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) || Self::middle( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) || Self::upper_may( state, dungeons, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) } } } #[allow(clippy::match_wildcard_for_single_variants)] x => error!("may_enter not yet implemented for {:?}", x), } false } #[allow(clippy::too_many_lines)] pub fn is_beatable( self, state: &GameState, dungeons: &DungeonState, logic: RandoLogic, ) -> Availability { match self { DungeonAvailability::DesertPalace => { if Rule::CanLiftRocks.check(state) && Rule::CanLightTorches.check(state) { if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::Boots.check(state) { if self.can_hurt_boss(state) { return Availability::Available; } return Availability::GlitchAvailable; } else if self.can_hurt_boss(state) { return Availability::Possible; } return Availability::GlitchPossible; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::Boots.check(state) { if self.can_hurt_boss(state) { return Availability::Available; } return Availability::GlitchAvailable; } else if self.can_hurt_boss(state) { return Availability::Possible; } return Availability::GlitchPossible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, false, ) { if self.can_hurt_boss(state) { return Availability::Agahnim; } return Availability::GlitchAgahnim; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, true, ) { return Availability::GlitchAgahnim; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if Rule::Boots.check(state) { if self.can_hurt_boss(state) { return Availability::Available; } return Availability::GlitchAvailable; } else if self.can_hurt_boss(state) { return Availability::Possible; } return Availability::GlitchPossible; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, true, false, ) { if self.can_hurt_boss(state) { return Availability::Agahnim; } return Availability::GlitchAgahnim; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } } DungeonAvailability::EasternPalace => { if Rule::Bow.check(state) { if Rule::Lantern.check(state) { return Availability::Available; } return Availability::GlitchAvailable; } } DungeonAvailability::GanonsTower => { if Rule::HookShot.check(state) && Rule::Bow.check(state) && Rule::CanLightTorches.check(state) && (Rule::Hammer.check(state) || Rule::Sword1.check(state)) { if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::Boots.check(state) && Rule::Hammer.check(state) && Rule::FireRod.check(state) && Rule::SomariaCane.check(state) { return Availability::Available; } return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, true) { if Rule::Boots.check(state) && Rule::Hammer.check(state) && Rule::FireRod.check(state) && Rule::SomariaCane.check(state) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::Boots.check(state) && Rule::Hammer.check(state) && Rule::FireRod.check(state) && Rule::SomariaCane.check(state) { return Availability::Available; } return Availability::Possible; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if Rule::Boots.check(state) && Rule::Hammer.check(state) && Rule::FireRod.check(state) && Rule::SomariaCane.check(state) { return Availability::Available; } return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, ) { if Rule::Boots.check(state) && Rule::Hammer.check(state) && Rule::FireRod.check(state) && Rule::SomariaCane.check(state) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } } } DungeonAvailability::IcePalace => { if Rule::CanMeltThings.check(state) && Rule::CanLiftRocks.check(state) { if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) && Rule::Hammer.check(state) { if Rule::HookShot.check(state) && Rule::SomariaCane.check(state) { return Availability::Available; } return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, true) { return Availability::GlitchAvailable; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) && Rule::Hammer.check(state) { if Rule::HookShot.check(state) && Rule::SomariaCane.check(state) { return Availability::Available; } return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { return Availability::GlitchAvailable; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) && Rule::Hammer.check(state) { if Rule::HookShot.check(state) && Rule::SomariaCane.check(state) { return Availability::Available; } return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, ) { return Availability::GlitchAvailable; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, true, false, ) && Rule::Hammer.check(state) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } } DungeonAvailability::MiseryMire => { if Rule::SomariaCane.check(state) && self.can_hurt_boss(state) { if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) && Rule::Lantern.check(state) { if Rule::ByrnaCane.check(state) || Rule::Cape.check(state) { return Availability::Available; } return Availability::Possible; } } else if self.may_enter(state, dungeons, RandoLogic::Glitchless, false, false) && Rule::Lantern.check(state) { return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, true) { if Rule::CanLightTorches.check(state) && (Rule::ByrnaCane.check(state) || Rule::Cape.check(state)) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.may_enter(state, dungeons, RandoLogic::Glitchless, false, true) { return Availability::GlitchPossible; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::ByrnaCane.check(state) || Rule::Cape.check(state) { return Availability::Available; } return Availability::Possible; } else if self.may_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, false, ) && Rule::Lantern.check(state) { return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { if Rule::CanLightTorches.check(state) && (Rule::ByrnaCane.check(state) || Rule::Cape.check(state)) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.may_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { return Availability::GlitchPossible; } else if self.may_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, false, ) { return Availability::Agahnim; } else if self.may_enter(state, dungeons, RandoLogic::OverWorldGlitches, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) && Rule::Lantern.check(state) { if Rule::ByrnaCane.check(state) || Rule::Cape.check(state) { return Availability::Available; } return Availability::Possible; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) && Rule::Lantern.check(state) { return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { if Rule::CanLightTorches.check(state) && (Rule::ByrnaCane.check(state) || Rule::Cape.check(state)) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { return Availability::GlitchPossible; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, true, false) { return Availability::Agahnim; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } DungeonAvailability::PalaceOfDarkness => { if Rule::Hammer.check(state) && Rule::Bow.check(state) { if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) && Rule::Lantern.check(state) { return Availability::Available; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, true) { return Availability::GlitchAvailable; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, false) && Rule::Lantern.check(state) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) && Rule::Lantern.check(state) { return Availability::Available; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { return Availability::GlitchAvailable; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, false, ) && Rule::Lantern.check(state) { return Availability::Agahnim; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, true, ) { return Availability::GlitchAgahnim; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) && Rule::Lantern.check(state) { return Availability::Available; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, ) { return Availability::GlitchAvailable; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, true, false, ) && Rule::Lantern.check(state) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } } DungeonAvailability::SkullWoods => { if Rule::MoonPearl.check(state) && Rule::FireRod.check(state) && Rule::Sword1.check(state) { if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { return Availability::Available; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, false) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { return Availability::Available; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { return Availability::GlitchAvailable; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, false, ) { return Availability::Agahnim; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, true, ) { return Availability::GlitchAgahnim; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { return Availability::Available; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, ) { return Availability::GlitchAvailable; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, true, false, ) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } } DungeonAvailability::SwampPalace => { if Rule::Hammer.check(state) && Rule::HookShot.check(state) { if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { return Availability::Available; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, false) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { return Availability::Available; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { return Availability::GlitchAvailable; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, false, ) { return Availability::Agahnim; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, true, ) { return Availability::GlitchAgahnim; } } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if Rule::HookShot.check(state) && Rule::Flippers.check(state) && (Rule::Sword1.check(state) || Rule::Hammer.check(state) || ((Rule::Bow.check(state) || Rule::CanExtendMagic.check(state)) && (Rule::FireRod.check(state) || Rule::IceRod.check(state)))) { if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) && (Rule::Hammer.check(state) || DungeonAvailability::MiseryMire.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, false, )) { return Availability::Available; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, ) && (Rule::Hammer.check(state) || DungeonAvailability::MiseryMire.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, )) { return Availability::GlitchAvailable; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, true, false, ) && (Rule::Hammer.check(state) || DungeonAvailability::MiseryMire.can_enter( state, dungeons, RandoLogic::MajorGlitches, true, false, )) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) && (Rule::Hammer.check(state) || DungeonAvailability::MiseryMire.can_enter( state, dungeons, RandoLogic::MajorGlitches, true, true, )) { return Availability::GlitchAgahnim; } } } DungeonAvailability::ThievesTown => { if self.can_hurt_boss(state) { if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { return Availability::Available; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, false) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { return Availability::Available; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { return Availability::GlitchAvailable; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, false, ) { return Availability::Agahnim; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, true, ) { return Availability::GlitchAgahnim; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { return Availability::Available; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, ) { return Availability::GlitchAvailable; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, true, false, ) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } } DungeonAvailability::TowerOfHera => { if Rule::Sword1.check(state) || Rule::Hammer.check(state) { if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::CanLightTorches.check(state) { return Availability::Available; } return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, true) { if Rule::CanLightTorches.check(state) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::CanLightTorches.check(state) { return Availability::Available; } return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { if Rule::CanLightTorches.check(state) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if Rule::CanLightTorches.check(state) || DungeonAvailability::MiseryMire.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, false, ) { return Availability::Available; } return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, ) { if Rule::CanLightTorches.check(state) || DungeonAvailability::MiseryMire.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, ) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.may_enter( state, dungeons, RandoLogic::MajorGlitches, false, false, ) { return Availability::Possible; } else if self.may_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, ) { return Availability::GlitchPossible; } else if self.may_enter( state, dungeons, RandoLogic::MajorGlitches, true, false, ) { return Availability::Agahnim; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } } DungeonAvailability::TurtleRock => { if Rule::FireRod.check(state) && Rule::IceRod.check(state) && Rule::SomariaCane.check(state) { if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) && Rule::Lantern.check(state) && (Rule::Hammer.check(state) || Rule::Sword2.check(state)) { if Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state) { return Availability::Available; } return Availability::Possible; } else if self.may_enter(state, dungeons, RandoLogic::Glitchless, false, false) { return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, true) { if Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.may_enter(state, dungeons, RandoLogic::Glitchless, false, true) { return Availability::GlitchPossible; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) && Rule::Lantern.check(state) && (Rule::Hammer.check(state) || Rule::Sword2.check(state)) { if Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state) { return Availability::Available; } return Availability::Possible; } else if self.may_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, false, ) { return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { if Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.may_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { return Availability::GlitchPossible; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) && Rule::Lantern.check(state) && (Rule::Hammer.check(state) || Rule::Sword2.check(state)) { if Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state) { return Availability::Available; } return Availability::Possible; } else if self.may_enter( state, dungeons, RandoLogic::MajorGlitches, false, false, ) { return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, ) { if Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.may_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, ) { return Availability::GlitchPossible; } } } } Availability::Unavailable } pub fn can_hurt_boss(self, state: &GameState) -> bool { match self { DungeonAvailability::DesertPalace => { Rule::Sword1.check(state) || Rule::Hammer.check(state) || Rule::Bow.check(state) || Rule::FireRod.check(state) || Rule::IceRod.check(state) || Rule::ByrnaCane.check(state) || Rule::SomariaCane.check(state) } DungeonAvailability::ThievesTown => { Rule::Sword1.check(state) || Rule::Hammer.check(state) || Rule::SomariaCane.check(state) || Rule::ByrnaCane.check(state) } DungeonAvailability::MiseryMire => { Rule::Sword1.check(state) || Rule::Hammer.check(state) || Rule::Bow.check(state) } x => { error!("can_hurt_boss not yet implemented for {:?}", x); false } } } #[allow(clippy::too_many_lines)] pub fn can_get_chest( self, state: &GameState, dungeons: &DungeonState, logic: RandoLogic, ) -> Availability { match self { DungeonAvailability::DesertPalace => { if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::Boots.check(state) && (self.dungeon_from_state(dungeons).remaining_chests() == 2 || (self.can_hurt_boss(state) && Rule::CanLightTorches.check(state) && Rule::CanLiftRocks.check(state))) { return Availability::Available; } return Availability::Possible; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::Boots.check(state) && (self.dungeon_from_state(dungeons).remaining_chests() == 2 || (self.can_hurt_boss(state) && Rule::CanLightTorches.check(state) && Rule::CanLiftRocks.check(state))) { return Availability::Available; } return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, false, ) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if Rule::Boots.check(state) && (self.dungeon_from_state(dungeons).remaining_chests() == 2 || (self.can_hurt_boss(state) && Rule::CanLightTorches.check(state) && Rule::CanLiftRocks.check(state))) { return Availability::Available; } return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, false) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } DungeonAvailability::EasternPalace => { if Rule::Lantern.check(state) { if Rule::Bow.check(state) || self.dungeon_from_state(dungeons).remaining_chests() >= 2 { return Availability::Available; } return Availability::Possible; } else if self.dungeon_from_state(dungeons).remaining_chests() == 3 { return Availability::Available; } return Availability::Possible; } DungeonAvailability::GanonsTower => { let mut small_keys_needed = 0; let mut big_key_needed = 0; let mut big_key_guaranteed = false; // Hope Room x2 let mut min_available_chests: u8 = 2; let mut max_available_chests: u8 = 2; // Bob's Torch if Rule::Boots.check(state) { min_available_chests += 1; max_available_chests += 1; } // DMs Room x4 + Randomizer Room x4 + Firesnake Room if Rule::Hammer.check(state) && Rule::HookShot.check(state) { min_available_chests += 9; max_available_chests += 9; small_keys_needed = 4; } // Map Chest if Rule::Hammer.check(state) && (Rule::Boots.check(state) || Rule::HookShot.check(state)) { min_available_chests += 1; max_available_chests += 1; } // Bob's Chest + Big Key Room x3 if (Rule::Hammer.check(state) && Rule::HookShot.check(state)) || (Rule::FireRod.check(state) && Rule::SomariaCane.check(state)) { min_available_chests += 4; max_available_chests += 4; small_keys_needed = max(3, small_keys_needed); } // Tile Room if Rule::SomariaCane.check(state) { min_available_chests += 1; max_available_chests += 1; } // Compass Room x4 if Rule::FireRod.check(state) && Rule::SomariaCane.check(state) { min_available_chests += 4; max_available_chests += 4; small_keys_needed = max(4, small_keys_needed); } // Big Chest if Rule::Hammer.check(state) && Rule::Boots.check(state) && Rule::HookShot.check(state) && Rule::SomariaCane.check(state) && Rule::FireRod.check(state) { min_available_chests += 1; max_available_chests += 1; big_key_needed = 1; big_key_guaranteed = true; } // Mini Helmasaur Room x2 + Pre-Moldorm Chest if Rule::Bow.check(state) && Rule::CanLightTorches.check(state) { if big_key_guaranteed { min_available_chests += 3; } max_available_chests += 3; small_keys_needed = max(3, small_keys_needed); big_key_needed = 1; } // Moldorm Chest if Rule::HookShot.check(state) && Rule::Bow.check(state) && Rule::CanLightTorches.check(state) && (Rule::Hammer.check(state) || Rule::Sword1.check(state)) { if big_key_guaranteed { min_available_chests += 1; } max_available_chests += 1; small_keys_needed = max(4, small_keys_needed); big_key_needed = 1; } let max_items_available = min( 20, max_available_chests .saturating_sub(small_keys_needed) .saturating_sub(big_key_needed), ); // 4 keys + big key + map + compass let min_items_available = min_available_chests.saturating_sub(7); let this_dungeon = self.dungeon_from_state(dungeons); if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if this_dungeon.remaining_chests() > (20 - min_items_available) { return Availability::Available; } else if this_dungeon.remaining_chests() > (20 - max_items_available) { return Availability::Possible; } } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, true) { if this_dungeon.remaining_chests() > (20 - min_items_available) { return Availability::GlitchAvailable; } else if this_dungeon.remaining_chests() > (20 - max_items_available) { return Availability::GlitchPossible; } } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if this_dungeon.remaining_chests() > (20 - min_items_available) { return Availability::Available; } else if this_dungeon.remaining_chests() > (20 - max_items_available) { return Availability::Possible; } } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if this_dungeon.remaining_chests() > (20 - min_items_available) { return Availability::Available; } else if this_dungeon.remaining_chests() > (20 - max_items_available) { return Availability::Possible; } } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { if this_dungeon.remaining_chests() > (20 - min_items_available) { return Availability::GlitchAvailable; } else if this_dungeon.remaining_chests() > (20 - max_items_available) { return Availability::GlitchPossible; } } } DungeonAvailability::IcePalace => { let this_dungeon = self.dungeon_from_state(dungeons); if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::Hammer.check(state) && Rule::CanLiftRocks.check(state) { if Rule::HookShot.check(state) { return Availability::Available; } else if Rule::ByrnaCane.check(state) || Rule::Cape.check(state) { if this_dungeon.remaining_chests() >= 2 { return Availability::Available; } return Availability::Possible; } return Availability::Possible; } return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, true) { if Rule::Hammer.check(state) && Rule::CanLiftRocks.check(state) { if Rule::HookShot.check(state) || this_dungeon.remaining_chests() >= 2 { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } return Availability::GlitchPossible; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::Hammer.check(state) && Rule::CanLiftRocks.check(state) { if Rule::HookShot.check(state) { return Availability::Available; } else if Rule::ByrnaCane.check(state) || Rule::Cape.check(state) { if this_dungeon.remaining_chests() >= 2 { return Availability::Available; } return Availability::Possible; } return Availability::Possible; } return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { if Rule::Hammer.check(state) && Rule::CanLiftRocks.check(state) { if Rule::HookShot.check(state) || this_dungeon.remaining_chests() >= 2 { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } return Availability::GlitchPossible; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if Rule::Hammer.check(state) && Rule::CanLiftRocks.check(state) { if Rule::HookShot.check(state) { return Availability::Available; } else if Rule::ByrnaCane.check(state) || Rule::Cape.check(state) { if this_dungeon.remaining_chests() >= 2 { return Availability::Available; } return Availability::Possible; } return Availability::Possible; } return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { if Rule::Hammer.check(state) && Rule::CanLiftRocks.check(state) { if Rule::HookShot.check(state) || this_dungeon.remaining_chests() >= 2 { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } return Availability::GlitchPossible; } } DungeonAvailability::MiseryMire => { let this_dungeon = self.dungeon_from_state(dungeons); if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::CanLightTorches.check(state) { if (this_dungeon.remaining_chests() == 2 && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || (Rule::SomariaCane.check(state) && self.can_hurt_boss(state)))) || (this_dungeon.remaining_chests() == 1 && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state)) && Rule::SomariaCane.check(state) && self.can_hurt_boss(state)) { return Availability::Available; } return Availability::Possible; } return Availability::Possible; } else if self.may_enter(state, dungeons, RandoLogic::Glitchless, false, false) { return Availability::Possible; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::CanLightTorches.check(state) { if (this_dungeon.remaining_chests() == 2 && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || (Rule::SomariaCane.check(state) && self.can_hurt_boss(state) && Rule::Lantern.check(state)))) || (this_dungeon.remaining_chests() == 1 && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state)) && Rule::SomariaCane.check(state) && self.can_hurt_boss(state) && Rule::Lantern.check(state)) { return Availability::Available; } return Availability::Possible; } return Availability::Possible; } else if self.may_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, false, ) { return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { if Rule::CanLightTorches.check(state) { if (this_dungeon.remaining_chests() == 2 && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || (Rule::SomariaCane.check(state) && self.can_hurt_boss(state) && Rule::Lantern.check(state)))) || (this_dungeon.remaining_chests() == 1 && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state)) && Rule::SomariaCane.check(state) && self.can_hurt_boss(state) && Rule::Lantern.check(state)) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } return Availability::GlitchPossible; } else if self.may_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { return Availability::GlitchPossible; } else if self.may_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, false, ) { return Availability::Agahnim; } else if self.may_enter(state, dungeons, RandoLogic::OverWorldGlitches, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if Rule::CanLightTorches.check(state) { if (this_dungeon.remaining_chests() == 2 && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || (Rule::SomariaCane.check(state) && self.can_hurt_boss(state) && Rule::Lantern.check(state)))) || (this_dungeon.remaining_chests() == 1 && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state)) && Rule::SomariaCane.check(state) && self.can_hurt_boss(state) && Rule::Lantern.check(state)) { return Availability::Available; } return Availability::Possible; } return Availability::Possible; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { if Rule::CanLightTorches.check(state) { if (this_dungeon.remaining_chests() == 2 && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || (Rule::SomariaCane.check(state) && self.can_hurt_boss(state) && Rule::Lantern.check(state)))) || (this_dungeon.remaining_chests() == 1 && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state)) && Rule::SomariaCane.check(state) && self.can_hurt_boss(state) && Rule::Lantern.check(state)) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } return Availability::GlitchPossible; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { return Availability::GlitchPossible; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, true, false) { return Availability::Agahnim; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } DungeonAvailability::PalaceOfDarkness => { let this_dungeon = self.dungeon_from_state(dungeons); if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::Bow.check(state) && (this_dungeon.remaining_chests() >= 2 || Rule::Hammer.check(state)) { if Rule::Lantern.check(state) { return Availability::Available; } return Availability::Possible; } else if Rule::Lantern.check(state) { return Availability::Possible; } return Availability::GlitchPossible; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, false) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::Bow.check(state) && (this_dungeon.remaining_chests() >= 2 || Rule::Hammer.check(state)) { if Rule::Lantern.check(state) { return Availability::Available; } return Availability::Possible; } else if Rule::Lantern.check(state) { return Availability::Possible; } return Availability::GlitchPossible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { if Rule::Bow.check(state) && (this_dungeon.remaining_chests() >= 2 || Rule::Hammer.check(state)) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, false, ) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if Rule::Bow.check(state) && (this_dungeon.remaining_chests() >= 2 || Rule::Hammer.check(state)) { if Rule::Lantern.check(state) { return Availability::Available; } return Availability::Possible; } else if Rule::Lantern.check(state) { return Availability::Possible; } return Availability::GlitchPossible; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { if Rule::Bow.check(state) && (this_dungeon.remaining_chests() >= 2 || Rule::Hammer.check(state)) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, false) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } DungeonAvailability::SkullWoods => { let this_dungeon = self.dungeon_from_state(dungeons); if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::MoonPearl.check(state) && Rule::FireRod.check(state) && (Rule::Sword1.check(state) || this_dungeon.remaining_chests() == 2) { return Availability::Available; } return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, false) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::MoonPearl.check(state) && Rule::FireRod.check(state) && (Rule::Sword1.check(state) || this_dungeon.remaining_chests() == 2) { return Availability::Available; } return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { if Rule::MoonPearl.check(state) && Rule::FireRod.check(state) && (Rule::Sword1.check(state) || this_dungeon.remaining_chests() == 2) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, false, ) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if Rule::MoonPearl.check(state) && Rule::FireRod.check(state) && (Rule::Sword1.check(state) || this_dungeon.remaining_chests() == 2) { return Availability::Available; } return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { if Rule::MoonPearl.check(state) && Rule::FireRod.check(state) && (Rule::Sword1.check(state) || this_dungeon.remaining_chests() == 2) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, false) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } DungeonAvailability::SwampPalace => { let this_dungeon = self.dungeon_from_state(dungeons); if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::Hammer.check(state) { if Rule::HookShot.check(state) || this_dungeon.remaining_chests() >= 5 { return Availability::Available; } else if this_dungeon.remaining_chests() >= 3 { return Availability::Possible; } } else if this_dungeon.remaining_chests() == 6 { return Availability::Possible; } } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, false) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::Hammer.check(state) { if Rule::HookShot.check(state) || this_dungeon.remaining_chests() >= 5 { return Availability::Available; } else if this_dungeon.remaining_chests() >= 3 { return Availability::Possible; } } else if this_dungeon.remaining_chests() == 6 { return Availability::Possible; } } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { if Rule::Hammer.check(state) { if Rule::HookShot.check(state) || this_dungeon.remaining_chests() >= 5 { return Availability::GlitchAvailable; } else if this_dungeon.remaining_chests() >= 3 { return Availability::GlitchPossible; } } else if this_dungeon.remaining_chests() == 6 { return Availability::GlitchPossible; } } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, false, ) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if Rule::Flippers.check(state) && (Rule::Hammer.check(state) || DungeonAvailability::MiseryMire.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, false, )) { if Rule::HookShot.check(state) { return Availability::Available; } else if this_dungeon.remaining_chests() >= 3 { return Availability::Possible; } } else if this_dungeon.remaining_chests() >= 5 { return Availability::Possible; } } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { if Rule::Flippers.check(state) && (Rule::Hammer.check(state) || DungeonAvailability::MiseryMire.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, true, )) { if Rule::HookShot.check(state) { return Availability::GlitchAvailable; } else if this_dungeon.remaining_chests() >= 3 { return Availability::GlitchPossible; } } else if this_dungeon.remaining_chests() >= 5 { return Availability::GlitchPossible; } } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, false) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } DungeonAvailability::ThievesTown => { let this_dungeon = self.dungeon_from_state(dungeons); if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::Hammer.check(state) || this_dungeon.remaining_chests() >= 3 || (self.can_hurt_boss(state) && this_dungeon.remaining_chests() >= 2) { return Availability::Available; } return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, false) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::Hammer.check(state) || this_dungeon.remaining_chests() >= 3 || (self.can_hurt_boss(state) && this_dungeon.remaining_chests() >= 2) { return Availability::Available; } return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { if Rule::Hammer.check(state) || this_dungeon.remaining_chests() >= 3 || (self.can_hurt_boss(state) && this_dungeon.remaining_chests() >= 2) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, true, false, ) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, true, true) { return Availability::GlitchAgahnim; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if Rule::Hammer.check(state) || this_dungeon.remaining_chests() >= 3 || (self.can_hurt_boss(state) && this_dungeon.remaining_chests() >= 2) { return Availability::Available; } return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { if Rule::Hammer.check(state) || this_dungeon.remaining_chests() >= 3 || (self.can_hurt_boss(state) && this_dungeon.remaining_chests() >= 2) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, false) { return Availability::Agahnim; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } DungeonAvailability::TowerOfHera => { let this_dungeon = self.dungeon_from_state(dungeons); if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::CanLightTorches.check(state) && (this_dungeon.remaining_chests() == 2 || Rule::Sword1.check(state) || Rule::Hammer.check(state)) { return Availability::Available; } return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, true) { if Rule::CanLightTorches.check(state) && (this_dungeon.remaining_chests() == 2 || Rule::Sword1.check(state) || Rule::Hammer.check(state)) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::CanLightTorches.check(state) && (this_dungeon.remaining_chests() == 2 || Rule::Sword1.check(state) || Rule::Hammer.check(state)) { return Availability::Available; } return Availability::Possible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { if Rule::CanLightTorches.check(state) && (this_dungeon.remaining_chests() == 2 || Rule::Sword1.check(state) || Rule::Hammer.check(state)) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if (Rule::CanLightTorches.check(state) || DungeonAvailability::MiseryMire.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, false, )) && (this_dungeon.remaining_chests() == 2 || Rule::Sword1.check(state) || Rule::Hammer.check(state)) { return Availability::Available; } return Availability::Possible; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { if (Rule::CanLightTorches.check(state) || DungeonAvailability::MiseryMire.can_enter( state, dungeons, RandoLogic::MajorGlitches, false, false, )) && (this_dungeon.remaining_chests() == 2 || Rule::Sword1.check(state) || Rule::Hammer.check(state)) { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { return Availability::Possible; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { return Availability::GlitchPossible; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, true, false) { return Availability::Agahnim; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, true, true) { return Availability::GlitchAgahnim; } } DungeonAvailability::TurtleRock => { let this_dungeon = self.dungeon_from_state(dungeons); if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::FireRod.check(state) { if Rule::Lantern.check(state) && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state)) { if this_dungeon.remaining_chests() >= 2 || self.is_beatable(state, dungeons, RandoLogic::Glitchless) == Availability::Available { return Availability::Available; } return Availability::Possible; } else if this_dungeon.remaining_chests() >= 2 { return Availability::Possible; } return Availability::GlitchPossible; } else if (Rule::Lantern.check(state) && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state))) || this_dungeon.remaining_chests() >= 4 { return Availability::Possible; } return Availability::GlitchPossible; } else if self.may_enter(state, dungeons, RandoLogic::Glitchless, false, false) { if Rule::FireRod.check(state) { if (Rule::Lantern.check(state) && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state))) || this_dungeon.remaining_chests() >= 2 { return Availability::Possible; } return Availability::GlitchPossible; } else if (Rule::Lantern.check(state) && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state))) || this_dungeon.remaining_chests() >= 4 { return Availability::Possible; } return Availability::GlitchPossible; } else if self.can_enter(state, dungeons, RandoLogic::Glitchless, false, true) { if Rule::FireRod.check(state) { if this_dungeon.remaining_chests() >= 2 || self.is_beatable(state, dungeons, RandoLogic::Glitchless) == Availability::Available || self.is_beatable(state, dungeons, RandoLogic::Glitchless) == Availability::GlitchAvailable { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } return Availability::GlitchPossible; } else if self.may_enter(state, dungeons, RandoLogic::Glitchless, false, true) { return Availability::GlitchPossible; } if logic < RandoLogic::OverWorldGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::OverWorldGlitches, false, false) { if Rule::FireRod.check(state) { if Rule::Lantern.check(state) && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state)) { if this_dungeon.remaining_chests() >= 2 // TODO: Should this actually be checking if the dungeon is beatable under OverWorld Glitches rules? || self.is_beatable(state, dungeons, RandoLogic::Glitchless) == Availability::Available { return Availability::Available; } return Availability::Possible; } else if this_dungeon.remaining_chests() >= 2 { return Availability::Possible; } return Availability::GlitchPossible; } else if (Rule::Lantern.check(state) && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state))) || this_dungeon.remaining_chests() >= 4 { return Availability::Possible; } return Availability::GlitchPossible; } else if self.may_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, false, ) { if Rule::FireRod.check(state) { if (Rule::Lantern.check(state) && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state))) || this_dungeon.remaining_chests() >= 2 { return Availability::Possible; } return Availability::GlitchPossible; } else if (Rule::Lantern.check(state) && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state))) || this_dungeon.remaining_chests() >= 4 { return Availability::Possible; } return Availability::GlitchPossible; } else if self.can_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { if Rule::FireRod.check(state) { if this_dungeon.remaining_chests() >= 2 // TODO: Should these be checking is_beatable with OverWorldGlitches logic? || self.is_beatable(state, dungeons, RandoLogic::Glitchless) == Availability::Available || self.is_beatable(state, dungeons, RandoLogic::Glitchless) == Availability::GlitchAvailable { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } } else if self.may_enter( state, dungeons, RandoLogic::OverWorldGlitches, false, true, ) { return Availability::GlitchPossible; } if logic < RandoLogic::MajorGlitches { return Availability::Unavailable; } if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if Rule::FireRod.check(state) { if Rule::Lantern.check(state) && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state)) { if this_dungeon.remaining_chests() >= 2 // TODO: Should this be using MajorGlitches logic to check is_beatable? || self.is_beatable(state, dungeons, RandoLogic::Glitchless) == Availability::Available { return Availability::Available; } return Availability::Possible; } else if this_dungeon.remaining_chests() >= 2 { return Availability::Possible; } return Availability::GlitchPossible; } else if (Rule::Lantern.check(state) && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state))) || this_dungeon.remaining_chests() >= 4 { return Availability::Possible; } return Availability::GlitchPossible; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, false, false) { if Rule::FireRod.check(state) { if (Rule::Lantern.check(state) && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state))) || this_dungeon.remaining_chests() >= 2 { return Availability::Possible; } return Availability::GlitchPossible; } else if (Rule::Lantern.check(state) && (Rule::Cape.check(state) || Rule::ByrnaCane.check(state) || Rule::CanBlockLasers.check(state))) || this_dungeon.remaining_chests() >= 4 { return Availability::Possible; } return Availability::GlitchPossible; } else if self.can_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { if Rule::FireRod.check(state) { if this_dungeon.remaining_chests() >= 2 // TODO: Should this be using MajorGlitches logic when checking is_beatable? || self.is_beatable(state, dungeons, RandoLogic::Glitchless) == Availability::Available || self.is_beatable(state, dungeons, RandoLogic::Glitchless) == Availability::GlitchAvailable { return Availability::GlitchAvailable; } return Availability::GlitchPossible; } return Availability::GlitchPossible; } else if self.may_enter(state, dungeons, RandoLogic::MajorGlitches, false, true) { return Availability::GlitchPossible; } } } Availability::Unavailable } fn has_medallion(self, state: &GameState, dungeons: &DungeonState) -> bool { if self == DungeonAvailability::MiseryMire || self == DungeonAvailability::TurtleRock { let this_dungeon = self.dungeon_from_state(dungeons); (match this_dungeon.medallion { Medallion::Bombos => Rule::BombosMedallion.check(state), Medallion::Ether => Rule::EtherMedallion.check(state), Medallion::Quake => Rule::QuakeMedallion.check(state), Medallion::Unknown => false, }) || (Rule::BombosMedallion.check(state) && Rule::EtherMedallion.check(state) && Rule::QuakeMedallion.check(state)) } else { error!("{:?} is not accessed via medallion", self); false } } fn may_have_medallion(self, state: &GameState, dungeons: &DungeonState) -> bool { if self == DungeonAvailability::MiseryMire || self == DungeonAvailability::TurtleRock { let this_dungeon = self.dungeon_from_state(dungeons); !(match this_dungeon.medallion { Medallion::Bombos => !Rule::BombosMedallion.check(state), Medallion::Ether => !Rule::EtherMedallion.check(state), Medallion::Quake => !Rule::QuakeMedallion.check(state), Medallion::Unknown => true, }) || (!Rule::BombosMedallion.check(state) && !Rule::EtherMedallion.check(state) && !Rule::QuakeMedallion.check(state)) } else { error!("{:?} is not accessed via medallion", self); false } } fn lower( // &self, state: &GameState, logic: RandoLogic, agahnim_check: bool, allow_out_of_logic_glitches: bool, ) -> bool { logic == RandoLogic::MajorGlitches && Rule::CanEnterWestDeathMountain.check_with_options( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) && (Rule::MoonPearl.check(state) || (Rule::Bottle.check(state) && Rule::Boots.check(state))) && Rule::Mirror.check(state) } fn middle( // &self, state: &GameState, logic: RandoLogic, agahnim_check: bool, allow_out_of_logic_glitches: bool, ) -> bool { match logic { RandoLogic::Glitchless => false, RandoLogic::OverWorldGlitches => { (Rule::Mirror.check(state) || (Rule::MoonPearl.check(state) && Rule::CanSpinSpeed.check(state))) && (Rule::Boots.check(state) || Rule::SomariaCane.check(state) || Rule::HookShot.check(state)) && Rule::CanEnterEastDarkWorldDeathMountain.check_with_options( state, RandoLogic::OverWorldGlitches, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::MajorGlitches => { (Rule::Mirror.check(state) || (Rule::GlitchedLinkInDarkWorld.check(state) && Rule::CanSpinSpeed.check(state))) && (Rule::Boots.check(state) || Rule::SomariaCane.check(state) || Rule::HookShot.check(state)) && (Rule::CanEnterEastDarkWorldDeathMountain.check_with_options( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, )) } } } fn upper_can( // &self, state: &GameState, dungeons: &DungeonState, logic: RandoLogic, agahnim_check: bool, allow_out_of_logic_glitches: bool, ) -> bool { match logic { RandoLogic::Glitchless => { DungeonAvailability::TurtleRock.has_medallion(state, dungeons) && Rule::Sword1.check(state) && Rule::MoonPearl.check(state) && Rule::SomariaCane.check(state) && Rule::Hammer.check(state) && Rule::CanLiftRocks.check(state) && Rule::CanEnterEastDeathMountain.check_with_options( state, RandoLogic::Glitchless, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::OverWorldGlitches => { DungeonAvailability::TurtleRock.has_medallion(state, dungeons) && Rule::Sword1.check(state) && Rule::MoonPearl.check(state) && Rule::SomariaCane.check(state) && Rule::Hammer.check(state) && (Rule::CanLiftDarkRocks.check(state) || Rule::Boots.check(state)) && Rule::CanEnterEastDeathMountain.check_with_options( state, RandoLogic::OverWorldGlitches, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::MajorGlitches => { DungeonAvailability::TurtleRock.has_medallion(state, dungeons) && Rule::Sword1.check(state) && (Rule::MoonPearl.check(state) || (Rule::Bottle.check(state) && Rule::Boots.check(state))) && Rule::SomariaCane.check(state) && Rule::Hammer.check(state) && (Rule::CanLiftDarkRocks.check(state) || Rule::Boots.check(state)) && Rule::CanEnterEastDeathMountain.check_with_options( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) } } } fn upper_may( // &self, state: &GameState, dungeons: &DungeonState, logic: RandoLogic, agahnim_check: bool, allow_out_of_logic_glitches: bool, ) -> bool { match logic { RandoLogic::Glitchless => { DungeonAvailability::TurtleRock.may_have_medallion(state, dungeons) && Rule::Sword1.check(state) && Rule::MoonPearl.check(state) && Rule::SomariaCane.check(state) && Rule::Hammer.check(state) && Rule::CanLiftDarkRocks.check(state) && Rule::CanEnterEastDeathMountain.check_with_options( state, RandoLogic::Glitchless, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::OverWorldGlitches => { DungeonAvailability::TurtleRock.may_have_medallion(state, dungeons) && Rule::Sword1.check(state) && Rule::MoonPearl.check(state) && Rule::SomariaCane.check(state) && Rule::Hammer.check(state) && (Rule::CanLiftDarkRocks.check(state) || Rule::Boots.check(state)) && Rule::CanEnterEastDeathMountain.check_with_options( state, RandoLogic::OverWorldGlitches, agahnim_check, allow_out_of_logic_glitches, ) } RandoLogic::MajorGlitches => { DungeonAvailability::TurtleRock.may_have_medallion(state, dungeons) && Rule::Sword1.check(state) && (Rule::MoonPearl.check(state) || (Rule::Bottle.check(state) && Rule::Boots.check(state))) && Rule::SomariaCane.check(state) && Rule::Hammer.check(state) && (Rule::CanLiftDarkRocks.check(state) || Rule::Boots.check(state)) && Rule::CanEnterEastDeathMountain.check_with_options( state, RandoLogic::MajorGlitches, agahnim_check, allow_out_of_logic_glitches, ) } } } fn dungeon_from_state(self, dungeons: &DungeonState) -> Dungeon { let dungeon_code = match self { DungeonAvailability::DesertPalace => "DP", DungeonAvailability::EasternPalace => "EP", DungeonAvailability::GanonsTower => "GT", DungeonAvailability::IcePalace => "IP", DungeonAvailability::MiseryMire => "MM", DungeonAvailability::PalaceOfDarkness => "PoD", DungeonAvailability::SkullWoods => "SW", DungeonAvailability::SwampPalace => "SP", DungeonAvailability::ThievesTown => "TT", DungeonAvailability::TowerOfHera => "ToH", DungeonAvailability::TurtleRock => "TR", }; dungeons.get(dungeon_code).unwrap() } }
use std::{default::Default, ffi::CStr, num::NonZeroU32, ops::Deref, sync::mpsc}; // use winit::window::Window; use ash::vk; use vulkayes_core::{ash, log, memory::device::naive::NaiveDeviceMemoryAllocator, prelude::*}; use vulkayes_window::winit::winit; use winit::{event_loop::EventLoop, window::Window}; #[macro_use] pub mod dirty_mark; pub mod state; pub const VALIDATION_LAYER: &'static CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"VK_LAYER_KHRONOS_validation\0") }; pub fn record_command_buffer(command_buffer: &Vrc<CommandBuffer>, f: impl FnOnce(&Vrc<CommandBuffer>)) { unsafe { { let cb_lock = command_buffer.lock().expect("vutex poisoned"); // TODO: This only works because we wait for the fence at the end of each submit. // In real-life applications this isn't viable command_buffer .pool() .device() .reset_command_buffer( *cb_lock, vk::CommandBufferResetFlags::RELEASE_RESOURCES ) .expect("Reset command buffer failed."); let command_buffer_begin_info = vk::CommandBufferBeginInfo::builder().flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); command_buffer .pool() .device() .begin_command_buffer(*cb_lock, &command_buffer_begin_info) .expect("Begin commandbuffer"); } f(command_buffer); { let cb_lock = command_buffer.lock().expect("vutex poisoned"); command_buffer .pool() .device() .end_command_buffer(*cb_lock) .expect("End commandbuffer"); } } } pub fn submit_command_buffer_simple(command_buffer: &Vrc<CommandBuffer>, submit_queue: &Vrc<Queue>) { let submit_fence = vulkayes_core::sync::fence::Fence::new( command_buffer.pool().device().clone(), false, Default::default() ) .expect("Create fence failed."); submit_queue .submit( [], [], [command_buffer.deref()], [], Some(submit_fence.deref()) ) .expect("queue submit failed"); submit_fence .wait(Default::default()) .expect("fence wait failed"); } pub fn submit_command_buffer( command_buffer: &Vrc<CommandBuffer>, submit_queue: &Vrc<Queue>, wait_semaphore: &Vrc<Semaphore>, wait_mask: vk::PipelineStageFlags, signal_semaphore: &Vrc<Semaphore> ) { let submit_fence = vulkayes_core::sync::fence::Fence::new( command_buffer.pool().device().clone(), false, Default::default() ) .expect("Create fence failed."); submit_queue .submit( [wait_semaphore], [wait_mask], [command_buffer], [signal_semaphore], Some(&submit_fence) ) .expect("queue submit failed"); submit_fence .wait(Default::default()) .expect("fence wait failed"); } #[derive(Debug)] enum InputEvent { Exit } pub struct ExampleBase { pub instance: Vrc<Instance>, pub device: Vrc<Device>, input_receiver: mpsc::Receiver<InputEvent>, pub present_queue: Vrc<Queue>, // pub window: winit::window::Window, pub surface_size: ImageSize, pub swapchain: Vrc<Swapchain>, pub swapchain_create_info: SwapchainCreateInfo<[u32; 1]>, pub present_image_views: Vec<Vrc<ImageView>>, pub command_pool: Vrc<CommandPool>, pub draw_command_buffer: Vrc<CommandBuffer>, pub setup_command_buffer: Vrc<CommandBuffer>, pub device_memory_allocator: NaiveDeviceMemoryAllocator, pub depth_image_view: Vrc<ImageView>, pub present_complete_semaphore: BinarySemaphore, pub rendering_complete_semaphore: BinarySemaphore, pub swapchain_outdated: u8 } impl ExampleBase { /// Converts the current thread to the input thread by created an event loop in it. /// /// A new thread is spawned with `new_thread_fn`. /// /// This function is designed this way because on MacOS only the main thread can have an EventLoop on it, /// so this must be called from the main thread. pub fn with_input_thread(window_size: [NonZeroU32; 2], new_thread_fn: impl FnOnce(Self) + Send + 'static) { use edwardium_logger::{ targets::{stderr::StderrTarget, util::ignore_list::IgnoreList}, Logger }; // Register a logger since Vulkayes logs through the log crate let logger = Logger::new( StderrTarget::new( log::Level::Trace, IgnoreList::EMPTY_PATTERNS ), std::time::Instant::now() ); logger.init_boxed().expect("Could not initialize logger"); let event_loop = EventLoop::new(); let window = winit::window::WindowBuilder::new() .with_title("Ash - Example") .with_inner_size(winit::dpi::LogicalSize::new( f64::from(window_size[0].get()), f64::from(window_size[1].get()) )) .build(&event_loop) .expect("could not create window"); // A little something about macOS and winit // On macOS, both the even loop and the window must stay in the main thread while rendering. // However, the window is needed to create surface, which needs an instance, which means it needs to happen in the renderer thread. // Here we have to move the window into the new thread and then send it back using a channel. let (oneoff_sender, oneoff_receiver) = mpsc::channel::<Window>(); let (input_sender, input_receiver) = mpsc::channel::<InputEvent>(); std::thread::spawn(move || { let window = window; let base = Self::new(window_size, &window, input_receiver); oneoff_sender.send(window).expect("could not send window"); new_thread_fn(base); }); // We don't actually need the window after, but it has to be in this thread. Weird. let window = oneoff_receiver .recv() .expect("could not receive window back"); // Technically result is now `!`, but this can be trivially replaced by `run_return` where supported event_loop.run(move |event, _target, control_flow| { // Handle window close event match event { winit::event::Event::WindowEvent { event: winit::event::WindowEvent::CloseRequested, .. } => { input_sender .send(InputEvent::Exit) .expect("could not send input event"); *control_flow = winit::event_loop::ControlFlow::Exit; } _ => () } }) } fn draw(&mut self, f: &impl Fn(&mut Self, u32)) { if self.swapchain_outdated > 120 { panic!("Swapchain outdated for 120 frames"); } else if self.swapchain_outdated > 0 { // let _window_size = self.window.inner_size(); // TODO: Recreate swapchain and framebuffers if self.swapchain_outdated > 1 { log::warn!( "Swapchain outdated for {} frames now", self.swapchain_outdated ); } // self.swapchain_outdated = 0; } let present_index = match self.swapchain.acquire_next( Default::default(), (&self.present_complete_semaphore).into() ) { Ok(vulkayes_core::swapchain::error::AcquireResultValue::SUCCESS(i)) => i, Ok(vulkayes_core::swapchain::error::AcquireResultValue::SUBOPTIMAL_KHR(_)) | Err(vulkayes_core::swapchain::error::AcquireError::ERROR_OUT_OF_DATE_KHR) => { self.swapchain_outdated += 1; return } Err(e) => panic!("{}", e) }; f(self, present_index); match self.present_queue.present( [&self.rendering_complete_semaphore], [self.present_image_views[present_index as usize] .image() .try_as_swapchain_image() .unwrap()] ) { Ok(vulkayes_core::queue::error::QueuePresentSuccess::SUCCESS) => (), Ok(vulkayes_core::queue::error::QueuePresentSuccess::SUBOPTIMAL_KHR) | Err(vulkayes_core::queue::error::QueuePresentError::ERROR_OUT_OF_DATE_KHR) => { self.swapchain_outdated += 1; } Err(e) => panic!("{}", e) } } pub fn render_loop(&mut self, f: impl Fn(&mut Self, u32)) { unsafe { dirty_mark::init(); } 'render: loop { // handle new events while let Ok(event) = self.input_receiver.try_recv() { log::trace!("Input event {:?}", event); match event { InputEvent::Exit => break 'render } } // draw log::trace!("Draw frame before"); let before = dirty_mark::before(); self.draw(&f); unsafe { dirty_mark::after([before, before]); } log::trace!("Draw frame after\n"); } unsafe { dirty_mark::flush(); } } fn new(window_size: [NonZeroU32; 2], window: &Window, input_receiver: mpsc::Receiver<InputEvent>) -> Self { // Create Entry, which is the entry point into the Vulkan API. // The default entry is loaded as a dynamic library. let entry = Entry::new().unwrap(); // Create instance from loaded entry // Also enable validation layers and require surface extensions as defined in vulkayes_window let layers = sub_release! { std::iter::once(VALIDATION_LAYER), std::iter::empty() }; // Lastly, register Default debug callbacks that log using the log crate let instance = Instance::new( entry, ApplicationInfo { application_name: "VulkanTriangle", engine_name: "VulkanTriangle", api_version: VkVersion::new(1, 0, 0), ..Default::default() }, layers, IntoIterator::into_iter(vulkayes_window::winit::required_extensions(&window)).chain(std::iter::once( ash::extensions::ext::DebugUtils::name() )), Default::default(), vulkayes_core::instance::debug::DebugCallback::Default() ) .expect("Could not create instance"); // Create a surface using the vulkayes_window::winit feature let surface = vulkayes_window::winit::create_surface( instance.clone(), &window, Default::default() ) .expect("Could not create surface"); let (device, present_queue) = { let (physical_device, queue_family_index) = instance .physical_devices() .expect("Physical device enumeration error") .into_iter() .filter_map(|physical_device| { for (queue_family_index, info) in physical_device .queue_family_properties() .into_iter() .enumerate() { let supports_graphics = info.queue_flags.contains(vk::QueueFlags::GRAPHICS); let supports_surface = surface .physical_device_surface_support( &physical_device, queue_family_index as u32 ) .unwrap(); if supports_graphics && supports_surface { return Some((physical_device, queue_family_index)) } } None }) .nth(0) .expect("Couldn't find suitable device."); let mut device_data = Device::new( physical_device, [vulkayes_core::device::QueueCreateInfo { queue_family_index: queue_family_index as u32, queue_priorities: [1.0] }], None, std::iter::once(ash::extensions::khr::Swapchain::name()), vk::PhysicalDeviceFeatures { shader_clip_distance: 1, ..Default::default() }, Default::default() ) .expect("Could not create device"); let present_queue = device_data.queues.drain(..).nth(0).unwrap(); (device_data.device, present_queue) }; let device_memory_allocator = NaiveDeviceMemoryAllocator::new(device.clone()); let swapchain_create_info = Self::swapchain_create_info(&surface, &present_queue, window_size); let surface_size: ImageSize = swapchain_create_info.image_info.image_size.into(); let (swapchain, present_images) = { let s = Swapchain::new( device.clone(), surface, swapchain_create_info, Default::default() ) .expect("could not create swapchain"); (s.swapchain, s.images) }; let command_pool = CommandPool::new( &present_queue, vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER, Default::default() ) .expect("Could not create command pool"); let mut command_buffers = CommandBuffer::new_multiple( command_pool.clone(), true, std::num::NonZeroU32::new(2).unwrap() ) .expect("Could not allocate command buffers"); let draw_command_buffer = command_buffers.pop().unwrap(); let setup_command_buffer = command_buffers.pop().unwrap(); let present_image_views: Vec<Vrc<ImageView>> = present_images .into_iter() .map(|image| { ImageView::new( image.into(), ImageViewRange::Type2D(0, NonZeroU32::new(1).unwrap(), 0), None, Default::default(), vk::ImageAspectFlags::COLOR, Default::default() ) .expect("Could not create image view") }) .collect(); let depth_image_view = { let depth_image = Image::new( device.clone(), vk::Format::D16_UNORM, surface_size.into(), Default::default(), vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT, present_queue.deref().into(), ImageAllocatorParams::Some { allocator: &device_memory_allocator, requirements: vk::MemoryPropertyFlags::DEVICE_LOCAL }, Default::default() ) .expect("Could not create depth image"); ImageView::new( depth_image.into(), ImageViewRange::Type2D(0, NonZeroU32::new(1).unwrap(), 0), None, Default::default(), vk::ImageAspectFlags::DEPTH, Default::default() ) .expect("Chould not create depth image view") }; record_command_buffer( &setup_command_buffer, |command_buffer| { let cb_lock = command_buffer.lock().expect("vutex poisoned"); let layout_transition_barriers = vk::ImageMemoryBarrier::builder() .image(*depth_image_view.image().deref().deref()) .old_layout(vk::ImageLayout::UNDEFINED) .dst_access_mask(vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ | vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE) .new_layout(vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL) .subresource_range(vk::ImageSubresourceRangeBuilder::from(depth_image_view.subresource_range()).build()); unsafe { command_buffer.pool().device().cmd_pipeline_barrier( *cb_lock, vk::PipelineStageFlags::BOTTOM_OF_PIPE, vk::PipelineStageFlags::LATE_FRAGMENT_TESTS, vk::DependencyFlags::empty(), &[], &[], &[layout_transition_barriers.build()] ); } } ); submit_command_buffer_simple(&setup_command_buffer, &present_queue); let present_complete_semaphore = Semaphore::binary(device.clone(), Default::default()).expect("Could not create semaphore"); let rendering_complete_semaphore = Semaphore::binary(device.clone(), Default::default()).expect("Could not create semaphore"); ExampleBase { input_receiver, instance, device, present_queue, swapchain, swapchain_create_info, surface_size, present_image_views, command_pool, draw_command_buffer, setup_command_buffer, device_memory_allocator, depth_image_view, present_complete_semaphore, rendering_complete_semaphore, swapchain_outdated: 0 } } pub fn swapchain_create_info( surface: &vulkayes_core::surface::Surface, queue: &Queue, window_size: [NonZeroU32; 2] ) -> SwapchainCreateInfo<[u32; 1]> { let surface_format = surface .physical_device_surface_formats(queue.device().physical_device()) .unwrap() .drain(..) .nth(0) .expect("Unable to find suitable surface format."); let surface_capabilities = surface .physical_device_surface_capabilities(queue.device().physical_device()) .unwrap(); let desired_image_count = match surface_capabilities.max_image_count { 0 => surface_capabilities.min_image_count + 1, a => (surface_capabilities.min_image_count + 1).min(a) }; let surface_resolution = match surface_capabilities.current_extent.width { std::u32::MAX => window_size, _ => [ NonZeroU32::new(surface_capabilities.current_extent.width).unwrap(), NonZeroU32::new(surface_capabilities.current_extent.height).unwrap() ] }; let pre_transform = if surface_capabilities .supported_transforms .contains(vk::SurfaceTransformFlagsKHR::IDENTITY) { vk::SurfaceTransformFlagsKHR::IDENTITY } else { surface_capabilities.current_transform }; let present_mode = sub_release! { surface .physical_device_surface_present_modes(queue.device().physical_device()).unwrap() .into_iter().find(|&mode| mode == vk::PresentModeKHR::MAILBOX).unwrap_or(vk::PresentModeKHR::FIFO), vk::PresentModeKHR::IMMEDIATE }; SwapchainCreateInfo { image_info: SwapchainCreateImageInfo { min_image_count: NonZeroU32::new(desired_image_count).unwrap(), image_format: surface_format.format, image_color_space: surface_format.color_space, image_size: ImageSize::new_2d( surface_resolution[0], surface_resolution[1], NonZeroU32::new(1).unwrap(), MipmapLevels::One() ), image_usage: vk::ImageUsageFlags::COLOR_ATTACHMENT }, sharing_mode: queue.into(), pre_transform, composite_alpha: vk::CompositeAlphaFlagsKHR::OPAQUE, present_mode, clipped: true } } }