text
stringlengths
8
4.13M
// Copyright 2018 Evgeniy Reizner // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::str; use xmlparser::{ StreamError, }; use { Result, Stream, StrSpan, }; /// A pull-based style parser. /// /// # Errors /// /// - Most of the `Error` types can occur. /// /// # Notes /// /// - Entity references must be already resolved. /// - By the SVG spec a `style` attribute can contain any style sheet language, /// but the library only support CSS2, which is default. /// - Objects with `-` prefix will be ignored. /// - All comments are automatically skipped. /// /// # Example /// /// ```rust /// use svgtypes::StyleParser; /// /// let style = "/* comment */fill:red;"; /// let mut p = StyleParser::from(style); /// let (name, value) = p.next().unwrap().unwrap(); /// assert_eq!(name.to_str(), "fill"); /// assert_eq!(value.to_str(), "red"); /// assert_eq!(p.next().is_none(), true); /// ``` #[derive(Clone, Copy, PartialEq, Debug)] pub struct StyleParser<'a> { stream: Stream<'a>, } impl<'a> From<&'a str> for StyleParser<'a> { fn from(v: &'a str) -> Self { Self::from(StrSpan::from(v)) } } impl<'a> From<StrSpan<'a>> for StyleParser<'a> { fn from(span: StrSpan<'a>) -> Self { StyleParser { stream: Stream::from(span), } } } impl<'a> Iterator for StyleParser<'a> { type Item = Result<(StrSpan<'a>, StrSpan<'a>)>; fn next(&mut self) -> Option<Self::Item> { self.stream.skip_spaces(); if self.stream.at_end() { return None; } macro_rules! try2 { ($expr:expr) => { match $expr { Ok(value) => value, Err(e) => { return Some(Err(e.into())); } } } } let c = try2!(self.stream.curr_byte()); if c == b'/' { try2!(skip_comment(&mut self.stream)); self.next() } else if c == b'-' { try2!(parse_prefix(&mut self.stream)); self.next() } else if is_ident_char(c) { Some(parse_attribute(&mut self.stream)) } else { // TODO: use custom error type let pos = self.stream.gen_error_pos(); self.stream.jump_to_end(); Some(Err(StreamError::InvalidChar(vec![c, b'/', b'-'], pos).into())) } } } fn skip_comment(stream: &mut Stream) -> Result<()> { stream.skip_string(b"/*")?; stream.skip_bytes(|_, c| c != b'*'); stream.skip_string(b"*/")?; stream.skip_spaces(); Ok(()) } fn parse_attribute<'a>(stream: &mut Stream<'a>) -> Result<(StrSpan<'a>, StrSpan<'a>)> { let name = stream.consume_bytes(|_, c| is_ident_char(c)); if name.is_empty() { // TODO: this // The error type is irrelevant because we will ignore it anyway. return Err(StreamError::UnexpectedEndOfStream.into()); } stream.skip_spaces(); stream.consume_byte(b':')?; stream.skip_spaces(); let value = if stream.curr_byte()? == b'\'' { stream.advance(1); let v = stream.consume_bytes(|_, c| c != b'\''); stream.consume_byte(b'\'')?; v } else if stream.starts_with(b"&apos;") { stream.advance(6); let v = stream.consume_bytes(|_, c| c != b'&'); stream.skip_string(b"&apos;")?; v } else { stream.consume_bytes(|_, c| c != b';' && c != b'/') }.trim(); if value.len() == 0 { return Err(StreamError::UnexpectedEndOfStream.into()); } stream.skip_spaces(); // ';;;' is valid style data, we need to skip it while stream.is_curr_byte_eq(b';') { stream.advance(1); stream.skip_spaces(); } Ok((name, value)) } fn parse_prefix(stream: &mut Stream) -> Result<()> { // prefixed attributes are not supported, aka '-webkit-*' stream.advance(1); // - let (name, _) = parse_attribute(stream)?; warn!("Style attribute '-{}' is skipped.", name); Ok(()) } // TODO: to xmlparser traits fn is_ident_char(c: u8) -> bool { match c { b'0'...b'9' | b'A'...b'Z' | b'a'...b'z' | b'-' | b'_' => true, _ => false, } } #[cfg(test)] mod tests { use super::*; macro_rules! test { ($name:ident, $text:expr, $(($aname:expr, $avalue:expr)),*) => ( #[test] fn $name() { let mut s = StyleParser::from($text); $( let (name, value) = s.next().unwrap().unwrap(); assert_eq!(name.to_str(), $aname); assert_eq!(value.to_str(), $avalue); )* assert_eq!(s.next().is_none(), true); } ) } test!(parse_1, "fill:none; color:cyan; stroke-width:4.00", ("fill", "none"), ("color", "cyan"), ("stroke-width", "4.00") ); test!(parse_2, "fill:none;", ("fill", "none") ); test!(parse_3, "font-size:24px;font-family:'Arial Bold'", ("font-size", "24px"), ("font-family", "Arial Bold") ); test!(parse_4, "font-size:24px; /* comment */ font-style:normal;", ("font-size", "24px"), ("font-style", "normal") ); test!(parse_5, "font-size:24px;-font-style:normal;font-stretch:normal;", ("font-size", "24px"), ("font-stretch", "normal") ); test!(parse_6, "fill:none;-webkit:hi", ("fill", "none") ); test!(parse_7, "font-family:&apos;Verdana&apos;", ("font-family", "Verdana") ); test!(parse_8, " fill : none ", ("fill", "none") ); test!(parse_10, "/**/", ); test!(parse_11, "font-family:Cantarell;-inkscape-font-specification:&apos;Cantarell Bold&apos;", ("font-family", "Cantarell") ); // TODO: technically incorrect, because value with spaces should be quoted test!(parse_12, "font-family:Neue Frutiger 65", ("font-family", "Neue Frutiger 65") ); test!(parse_13, "/*text*/fill:green/*text*/", ("fill", "green") ); test!(parse_14, " /*text*/ fill:green /*text*/ ", ("fill", "green") ); #[test] fn parse_err_1() { let mut s = StyleParser::from(":"); assert_eq!(s.next().unwrap().unwrap_err().to_string(), "expected '/', '-' not ':' at 1:1"); } #[test] fn parse_err_2() { let mut s = StyleParser::from("name:'"); assert_eq!(s.next().unwrap().unwrap_err().to_string(), "unexpected end of stream"); } #[test] fn parse_err_3() { let mut s = StyleParser::from("&\x0a96M*9"); assert_eq!(s.next().unwrap().unwrap_err().to_string(), "expected '/', '-' not '&' at 1:1"); } #[test] fn parse_err_4() { let mut s = StyleParser::from("/*/**/"); assert_eq!(s.next().unwrap().is_err(), true); } #[test] fn parse_err_5() { let mut s = StyleParser::from("&#x4B2ƿ ;"); assert_eq!(s.next().unwrap().unwrap_err().to_string(), "expected '/', '-' not '&' at 1:1"); } #[test] fn parse_err_6() { let mut s = StyleParser::from("{"); assert_eq!(s.next().unwrap().unwrap_err().to_string(), "expected '/', '-' not '{' at 1:1"); } }
//! Calculate transaction hashes. use crate::reply::transaction::{ DeclareTransaction, DeclareTransactionV0V1, DeclareTransactionV2, DeployAccountTransaction, DeployTransaction, InvokeTransaction, InvokeTransactionV0, InvokeTransactionV1, L1HandlerTransaction, Transaction, }; use pathfinder_common::{ BlockNumber, CasmHash, ClassHash, ContractAddress, EntryPoint, Fee, TransactionHash, TransactionNonce, TransactionVersion, }; use crate::class_hash::truncated_keccak; use pathfinder_common::ChainId; use sha3::{Digest, Keccak256}; use stark_hash::{Felt, HashChain}; #[derive(Copy, Clone, Debug, PartialEq)] pub enum VerifyResult { Match, Mismatch(TransactionHash), NotVerifiable, } pub fn verify(txn: &Transaction, chain_id: ChainId, block_number: BlockNumber) -> VerifyResult { let chain_id = match chain_id { // We don't know how to properly compute hashes of some old L1 Handler transactions // Worse still those are invokes in old snapshots but currently are served as // L1 handler txns. ChainId::MAINNET => { if block_number.get() <= 4399 && matches!(txn, Transaction::L1Handler(_)) { // Unable to compute, skipping return VerifyResult::NotVerifiable; } else { chain_id } } ChainId::TESTNET => { if block_number.get() <= 306007 && matches!(txn, Transaction::L1Handler(_)) { // Unable to compute, skipping return VerifyResult::NotVerifiable; } else { chain_id } } // Earlier blocks on testnet2 used the same chain id as testnet (ie. goerli) ChainId::TESTNET2 => { if block_number.get() <= 21086 { ChainId::TESTNET } else { chain_id } } _ => chain_id, }; let computed_hash = compute_transaction_hash(txn, chain_id); if computed_hash == txn.hash() { VerifyResult::Match } else { VerifyResult::Mismatch(computed_hash) } } /// Computes transaction hash according to the formulas from [starknet docs](https://docs.starknet.io/documentation/architecture_and_concepts/Blocks/transactions/). /// /// ## Important /// /// For __Invoke v0__, __Deploy__ and __L1 Handler__ there is a fallback hash calculation /// algorithm used in case a hash mismatch is encountered and the fallback's result becomes /// the ultimate result of the computation. pub fn compute_transaction_hash(txn: &Transaction, chain_id: ChainId) -> TransactionHash { match txn { Transaction::Declare(DeclareTransaction::V0(txn)) => compute_declare_v0_hash(txn, chain_id), Transaction::Declare(DeclareTransaction::V1(txn)) => compute_declare_v1_hash(txn, chain_id), Transaction::Declare(DeclareTransaction::V2(txn)) => compute_declare_v2_hash(txn, chain_id), Transaction::Deploy(txn) => compute_deploy_hash(txn, chain_id), Transaction::DeployAccount(txn) => compute_deploy_account_hash(txn, chain_id), Transaction::Invoke(InvokeTransaction::V0(txn)) => compute_invoke_v0_hash(txn, chain_id), Transaction::Invoke(InvokeTransaction::V1(txn)) => compute_invoke_v1_hash(txn, chain_id), Transaction::L1Handler(txn) => compute_l1_handler_hash(txn, chain_id), } } /// Computes declare v0 transaction hash based on [this formula](https://docs.starknet.io/documentation/architecture_and_concepts/Blocks/transactions/#v0_hash_calculation_2): /// ```text= /// declare_v0_tx_hash = h("declare", version, sender_address, /// 0, h([]), max_fee, chain_id, class_hash) /// ``` /// /// FIXME: SW should fix the formula in the docs /// /// Where `h` is [Pedersen hash](https://docs.starknet.io/documentation/architecture_and_concepts/Hashing/hash-functions/#pedersen_hash) fn compute_declare_v0_hash(txn: &DeclareTransactionV0V1, chain_id: ChainId) -> TransactionHash { compute_txn_hash( b"declare", TransactionVersion::ZERO, txn.sender_address, None, HashChain::default().finalize(), // Hash of an empty Felt list None, chain_id, txn.class_hash, None, ) } /// Computes declare v1 transaction hash based on [this formula](https://docs.starknet.io/documentation/architecture_and_concepts/Blocks/transactions/#v1_hash_calculation_2): /// ```text= /// declare_v1_tx_hash = h("declare", version, sender_address, /// 0, h([class_hash]), max_fee, chain_id, nonce) /// ``` /// /// FIXME: SW should fix the formula in the docs /// /// Where `h` is [Pedersen hash](https://docs.starknet.io/documentation/architecture_and_concepts/Hashing/hash-functions/#pedersen_hash) fn compute_declare_v1_hash(txn: &DeclareTransactionV0V1, chain_id: ChainId) -> TransactionHash { compute_txn_hash( b"declare", TransactionVersion::ONE, txn.sender_address, None, { let mut h = HashChain::default(); h.update(txn.class_hash.0); h.finalize() }, Some(txn.max_fee), chain_id, txn.nonce, None, ) } /// Computes declare v2 transaction hash based on [this formula](https://docs.starknet.io/documentation/architecture_and_concepts/Blocks/transactions/#v2_hash_calculation): /// ```text= /// declare_v2_tx_hash = h("declare", version, sender_address, /// 0, h([class_hash]), max_fee, chain_id, nonce, compiled_class_hash) /// ``` /// /// FIXME: SW should fix the formula in the docs /// /// Where `h` is [Pedersen hash](https://docs.starknet.io/documentation/architecture_and_concepts/Hashing/hash-functions/#pedersen_hash) fn compute_declare_v2_hash(txn: &DeclareTransactionV2, chain_id: ChainId) -> TransactionHash { compute_txn_hash( b"declare", TransactionVersion::TWO, txn.sender_address, None, { let mut h = HashChain::default(); h.update(txn.class_hash.0); h.finalize() }, Some(txn.max_fee), chain_id, txn.nonce, Some(txn.compiled_class_hash), ) } /// Computes deploy transaction hash based on [this formula](https://docs.starknet.io/documentation/architecture_and_concepts/Blocks/transactions/#deploy_transaction): /// ```text= /// deploy_tx_hash = h( /// "deploy", version, contract_address, sn_keccak("constructor"), /// h(constructor_calldata), 0, chain_id) /// ``` /// /// Where `h` is [Pedersen hash](https://docs.starknet.io/documentation/architecture_and_concepts/Hashing/hash-functions/#pedersen_hash), and `sn_keccak` is [Starknet Keccak](https://docs.starknet.io/documentation/architecture_and_concepts/Hashing/hash-functions/#Starknet-keccak) fn compute_deploy_hash(txn: &DeployTransaction, chain_id: ChainId) -> TransactionHash { lazy_static::lazy_static!( static ref CONSTRUCTOR: EntryPoint = { let mut keccak = Keccak256::default(); keccak.update(b"constructor"); EntryPoint(truncated_keccak(<[u8; 32]>::from(keccak.finalize())))}; ); let constructor_params_hash = { let hh = txn.constructor_calldata.iter().fold( HashChain::default(), |mut hh, constructor_param| { hh.update(constructor_param.0); hh }, ); hh.finalize() }; let h = compute_txn_hash( b"deploy", txn.version, txn.contract_address, Some(*CONSTRUCTOR), constructor_params_hash, None, chain_id, (), None, ); if h == txn.transaction_hash { h } else { legacy_compute_txn_hash( b"deploy", txn.contract_address, Some(*CONSTRUCTOR), constructor_params_hash, chain_id, ) } } /// Computes deploy account transaction hash based on [this formula](https://docs.starknet.io/documentation/architecture_and_concepts/Blocks/transactions/#deploy_account_hash_calculation): /// ```text= /// deploy_account_tx_hash = h( /// "deploy_account", version, contract_address, 0, /// h(class_hash, contract_address_salt, constructor_calldata), /// max_fee, chain_id, nonce) /// ``` /// /// FIXME: SW should fix the formula in the docs /// /// Where `h` is [Pedersen hash](https://docs.starknet.io/documentation/architecture_and_concepts/Hashing/hash-functions/#pedersen_hash) fn compute_deploy_account_hash( txn: &DeployAccountTransaction, chain_id: ChainId, ) -> TransactionHash { compute_txn_hash( b"deploy_account", txn.version, txn.contract_address, None, { let mut hh = HashChain::default(); hh.update(txn.class_hash.0); hh.update(txn.contract_address_salt.0); hh = txn .constructor_calldata .iter() .fold(hh, |mut hh, constructor_param| { hh.update(constructor_param.0); hh }); hh.finalize() }, Some(txn.max_fee), chain_id, txn.nonce, None, ) } /// Computes invoke v0 account transaction hash based on [this formula](https://docs.starknet.io/documentation/architecture_and_concepts/Blocks/transactions/#v0_hash_calculation): /// ```text= /// invoke_v0_tx_hash = h("invoke", version, sender_address, /// entry_point_selector, h(calldata), max_fee, chain_id) /// ``` /// /// FIXME: SW should fix the formula in the docs /// /// Where `h` is [Pedersen hash](https://docs.starknet.io/documentation/architecture_and_concepts/Hashing/hash-functions/#pedersen_hash) fn compute_invoke_v0_hash(txn: &InvokeTransactionV0, chain_id: ChainId) -> TransactionHash { let call_params_hash = { let mut hh = HashChain::default(); hh = txn.calldata.iter().fold(hh, |mut hh, call_param| { hh.update(call_param.0); hh }); hh.finalize() }; let h = compute_txn_hash( b"invoke", TransactionVersion::ZERO, txn.sender_address, Some(txn.entry_point_selector), call_params_hash, Some(txn.max_fee), chain_id, (), None, ); if h == txn.transaction_hash { h } else { legacy_compute_txn_hash( b"invoke", txn.sender_address, Some(txn.entry_point_selector), call_params_hash, chain_id, ) } } /// Computes invoke v1 transaction hash based on [this formula](https://docs.starknet.io/documentation/architecture_and_concepts/Blocks/transactions/#v1_hash_calculation): /// ```text= /// invoke_v1_tx_hash = h("invoke", version, sender_address, /// 0, h(calldata), max_fee, chain_id, nonce) /// ``` /// /// Where `h` is [Pedersen hash](https://docs.starknet.io/documentation/architecture_and_concepts/Hashing/hash-functions/#pedersen_hash) fn compute_invoke_v1_hash(txn: &InvokeTransactionV1, chain_id: ChainId) -> TransactionHash { compute_txn_hash( b"invoke", TransactionVersion::ONE, txn.sender_address, None, { let mut hh = HashChain::default(); hh = txn.calldata.iter().fold(hh, |mut hh, call_param| { hh.update(call_param.0); hh }); hh.finalize() }, Some(txn.max_fee), chain_id, txn.nonce, None, ) } /// Computes l1 handler transaction hash based on [this formula](https://docs.starknet.io/documentation/architecture_and_concepts/L1-L2_Communication/messaging-mechanism/#structure_and_hashing_l1-l2): /// ```text= /// l1_handler_tx_hash = h("l1_handler", version, contract_address, /// entry_point_selector, h(calldata), 0, chain_id, nonce) /// ``` /// /// FIXME: SW should fix the formula in the docs /// /// Where `h` is [Pedersen hash](https://docs.starknet.io/documentation/architecture_and_concepts/Hashing/hash-functions/#pedersen_hash) /// /// ## Important /// /// Guarantees correct computation for Starknet **0.9.1** transactions onwards fn compute_l1_handler_hash(txn: &L1HandlerTransaction, chain_id: ChainId) -> TransactionHash { let call_params_hash = { let mut hh = HashChain::default(); hh = txn.calldata.iter().fold(hh, |mut hh, call_param| { hh.update(call_param.0); hh }); hh.finalize() }; let h = compute_txn_hash( b"l1_handler", txn.version, txn.contract_address, Some(txn.entry_point_selector), call_params_hash, None, chain_id, txn.nonce, None, ); if h == txn.transaction_hash { h } else { legacy_compute_txn_hash( // Oldest L1 Handler transactions were actually Invokes // which later on were "renamed" to be the former, // yet the hashes remain, hence the prefix b"invoke", txn.contract_address, Some(txn.entry_point_selector), call_params_hash, chain_id, ) } } #[derive(Copy, Clone, Debug)] enum NonceOrClassHash { Nonce(TransactionNonce), ClassHash(ClassHash), None, } impl From<TransactionNonce> for NonceOrClassHash { fn from(n: TransactionNonce) -> Self { Self::Nonce(n) } } impl From<ClassHash> for NonceOrClassHash { fn from(c: ClassHash) -> Self { Self::ClassHash(c) } } impl From<()> for NonceOrClassHash { fn from(_: ()) -> Self { Self::None } } /// _Generic_ compute transaction hash for older transactions (pre 0.8-ish) fn legacy_compute_txn_hash( prefix: &[u8], address: ContractAddress, entry_point_selector: Option<EntryPoint>, list_hash: Felt, chain_id: ChainId, ) -> TransactionHash { let mut h = HashChain::default(); h.update(Felt::from_be_slice(prefix).expect("prefix is convertible")); h.update(*address.get()); h.update(entry_point_selector.map(|e| e.0).unwrap_or(Felt::ZERO)); h.update(list_hash); h.update(chain_id.0); TransactionHash(h.finalize()) } /// _Generic_ compute transaction hash for transactions #[allow(clippy::too_many_arguments)] fn compute_txn_hash( prefix: &[u8], version: TransactionVersion, address: ContractAddress, entry_point_selector: Option<EntryPoint>, list_hash: Felt, max_fee: Option<Fee>, chain_id: ChainId, nonce_or_class_hash: impl Into<NonceOrClassHash>, compiled_class_hash: Option<CasmHash>, ) -> TransactionHash { let mut h = HashChain::default(); h.update(Felt::from_be_slice(prefix).expect("prefix is convertible")); h.update(Felt::from_be_slice(version.0.as_bytes()).expect("version is convertible")); h.update(*address.get()); h.update(entry_point_selector.map(|e| e.0).unwrap_or(Felt::ZERO)); h.update(list_hash); h.update(max_fee.map(|e| e.0).unwrap_or(Felt::ZERO)); h.update(chain_id.0); match nonce_or_class_hash.into() { NonceOrClassHash::Nonce(nonce) => h.update(nonce.0), NonceOrClassHash::ClassHash(class_hash) => h.update(class_hash.0), NonceOrClassHash::None => {} } if let Some(compiled_class_hash) = compiled_class_hash { h.update(compiled_class_hash.0); } TransactionHash(h.finalize()) } #[cfg(test)] mod tests { use super::compute_transaction_hash; use pathfinder_common::ChainId; use starknet_gateway_test_fixtures::{v0_11_0, v0_8_2, v0_9_0}; #[derive(serde::Deserialize)] struct TxWrapper { transaction: crate::reply::transaction::Transaction, } macro_rules! case { ($target:expr) => {{ let line = line!(); ( serde_json::from_str::<crate::transaction_hash::tests::TxWrapper>($target) .expect(&format!("deserialization is Ok, line: {line}")) .transaction, line, ) }}; } #[test] fn computation() { // At the beginning testnet2 used chain id of testnet for hash calculation let testnet2_with_wrong_chain_id = serde_json::from_str(v0_11_0::transaction::deploy::v1::GENESIS_TESTNET2).unwrap(); assert_eq!( compute_transaction_hash(&testnet2_with_wrong_chain_id, ChainId::TESTNET), testnet2_with_wrong_chain_id.hash() ); [ // Declare case!(v0_9_0::transaction::DECLARE), // v0 case!(v0_11_0::transaction::declare::v1::BLOCK_463319), case!(v0_11_0::transaction::declare::v1::BLOCK_797215), case!(v0_11_0::transaction::declare::v2::BLOCK_797220), // Deploy case!(v0_11_0::transaction::deploy::v0::GENESIS), case!(v0_9_0::transaction::DEPLOY), // v0 case!(v0_11_0::transaction::deploy::v1::BLOCK_485004), // Deploy account case!(v0_11_0::transaction::deploy_account::v1::BLOCK_375919), case!(v0_11_0::transaction::deploy_account::v1::BLOCK_797K), // Invoke case!(v0_11_0::transaction::invoke::v0::GENESIS), case!(v0_8_2::transaction::INVOKE), case!(v0_9_0::transaction::INVOKE), case!(v0_11_0::transaction::invoke::v1::BLOCK_420K), case!(v0_11_0::transaction::invoke::v1::BLOCK_790K), // L1 Handler case!(v0_11_0::transaction::l1_handler::v0::BLOCK_1564), case!(v0_11_0::transaction::l1_handler::v0::BLOCK_272866), case!(v0_11_0::transaction::l1_handler::v0::BLOCK_790K), ] .iter() .for_each(|(txn, line)| { let actual_hash = compute_transaction_hash(txn, ChainId::TESTNET); assert_eq!(actual_hash, txn.hash(), "line: {line}"); }); } mod verification { use crate::transaction_hash::{verify, VerifyResult}; use pathfinder_common::{BlockNumber, ChainId}; mod skipped { use crate::transaction_hash::{verify, VerifyResult}; use pathfinder_common::{BlockNumber, ChainId}; use starknet_gateway_test_fixtures::v0_11_0; #[test] fn rewritten_old_l1_handler() { let block_854_idx_96 = serde_json::from_str(v0_11_0::transaction::l1_handler::v0::BLOCK_854_IDX_96) .unwrap(); assert_eq!( verify( &block_854_idx_96, ChainId::TESTNET, BlockNumber::new_or_panic(854), ), VerifyResult::NotVerifiable ); } #[test] fn old_l1_handler_in_invoke_v0() { let block_854_idx_96 = serde_json::from_str(v0_11_0::transaction::invoke::v0::BLOCK_854_IDX_96) .unwrap(); assert_eq!( verify( &block_854_idx_96, ChainId::TESTNET, BlockNumber::new_or_panic(854), ), VerifyResult::NotVerifiable ); } } #[test] fn ok() { let (txn, _) = case!(super::v0_11_0::transaction::declare::v2::BLOCK_797220); assert_eq!( verify(&txn, ChainId::TESTNET, BlockNumber::new_or_panic(797220),), VerifyResult::Match ); } #[test] fn failed() { let (txn, _) = case!(super::v0_11_0::transaction::declare::v2::BLOCK_797220); // Wrong chain id to force failure assert!(matches!( verify(&txn, ChainId::MAINNET, BlockNumber::new_or_panic(797220),), VerifyResult::Mismatch(_) )) } } }
macro_rules! boolean_infix_operator { ($left:ident, $right:ident, $operator:tt) => {{ let (left_bool, right_bool) = crate::runtime::context::terms_try_into_bools(stringify!($left), $left, stringify!($right), $right)?; let output_bool = left_bool $operator right_bool; Ok(output_bool.into()) }}; }
use byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt}; use std::fs::{DirBuilder, File, OpenOptions}; use std::io::{self, Seek, SeekFrom}; use std::path::{Path, PathBuf}; mod flock; use self::flock::FileLock; const LOG_PATH: &str = env!("TOBY_LOG_PATH"); const RUNTIME_PATH: &str = env!("TOBY_RUNTIME_PATH"); fn ensure_parent(path: &Path) -> io::Result<()> { // ensure that directory exists if let Some(dir) = path.parent() { DirBuilder::new().recursive(true).create(dir)?; } Ok(()) } fn get_job_id_path(project_name: &str) -> PathBuf { let mut path = PathBuf::from(RUNTIME_PATH); path.push("jobs"); path.push(project_name); path.push("next_id"); path } pub fn job_log_path(project_name: &str, job_id: u64) -> PathBuf { let mut path = PathBuf::from(LOG_PATH); path.push("jobs"); path.push(format!("{}-{}", project_name, job_id)); path.set_extension("log"); path } fn job_archive_path(project_name: &str, job_id: u64) -> PathBuf { let mut path = PathBuf::from(RUNTIME_PATH); path.push("jobs"); path.push(project_name); path.push(job_id.to_string()); path.set_extension("toml"); path } pub(crate) fn get_telegram_chat_id_path() -> PathBuf { let mut path = PathBuf::from(RUNTIME_PATH); path.push("telegram_chat_id"); path } pub(crate) fn get_job_archive_file(project_name: &str, job_id: u64) -> io::Result<File> { let path = job_archive_path(project_name, job_id); ensure_parent(&path)?; OpenOptions::new().create(true).write(true).open(path) } /// /// Determines and creates the log file for a job. /// pub(crate) fn get_job_log(project_name: &str, job_id: u64) -> io::Result<File> { let path = job_log_path(project_name, job_id); ensure_parent(&path)?; OpenOptions::new() .create(true) .write(true) .append(true) .open(path) } /// /// Determines the next job id for a project and increments the counter. /// pub(crate) fn next_job_id(project_name: &str) -> io::Result<u64> { let path = get_job_id_path(project_name); // ensure that directory exists ensure_parent(&path)?; let file = OpenOptions::new() .create(true) .read(true) .write(true) .open(path)?; let mut file = FileLock::exclusive(file)?; // read current id (if file is empty fall back to 1) let next_id = file.read_u64::<NativeEndian>().unwrap_or(1); // move cursor back to beginning file.seek(SeekFrom::Start(0))?; // write next id file.write_u64::<NativeEndian>(next_id + 1)?; // make sure file is truncated to a u64 file.file().set_len(8)?; Ok(next_id) } pub(crate) fn get_telegram_chat_id() -> io::Result<Option<i64>> { let path = get_telegram_chat_id_path(); if !path.exists() { return Ok(None); } let mut file = File::open(path)?; let chat_id = file.read_i64::<NativeEndian>()?; Ok(Some(chat_id)) } pub(crate) fn write_telegram_chat_id(chat_id: i64) -> io::Result<()> { let path = get_telegram_chat_id_path(); ensure_parent(&path)?; let mut file = OpenOptions::new().create(true).write(true).open(path)?; file.write_i64::<NativeEndian>(chat_id)?; Ok(()) }
use crate::models::todo::Todo; use crate::models::user::User; use crate::state::app::AppState; use actix_web::{web, HttpResponse, Responder}; /// Uncheck the todo /// /// @param {String} todo_id /// /// Success code 200: /// ``` /// { /// "id": "06b8ff8c-3e34-4226-b917-cb07bd98785e", /// "user_id": "c4d5f3b2-5149-489e-b103-f9e3b8adc3ff", /// "content": "Do something", /// "checked": false /// } /// ``` /// /// Error: 400 pub async fn handle( req: web::HttpRequest, path: web::Path<String>, state: web::Data<AppState>, ) -> impl Responder { let auth = match req.extensions_mut().remove::<User>() { Some(user) => user, None => return HttpResponse::BadRequest().finish(), }; let connection = &state.get_connection(); let mut todo = match Todo::show(connection, &path.0) { Ok(todo) => todo, Err(_) => return HttpResponse::NotFound().finish(), }; // Allow change only to todos that the user actually owns if &todo.user_id != &auth.id { return HttpResponse::Forbidden().finish(); } match todo.uncheck(connection) { Ok(_) => { todo.checked = false; HttpResponse::Ok().json(todo) } Err(_) => HttpResponse::BadRequest().finish(), } }
pub use libra_language_e2e_tests::account_universe::*;
use libc; use core::str; use core::str::Utf8Error; use alloc::String; use alloc::string::ToString; use alloc::Vec; use alloc::borrow::ToOwned; #[derive(Debug)] pub struct Process(*const libc::c_void); impl Process { pub fn find(pid: isize) -> Option<Process> { extern "C" { fn proc_find(pid: libc::c_int) -> *const libc::c_void; } let process = unsafe { proc_find(pid as libc::c_int) }; if !process.is_null() { Some(Process(process)) } else { None } } pub fn current() -> Process { extern "C" { fn proc_self() -> *const libc::c_void; } unsafe { Process(proc_self()) } } pub fn pid(&self) -> isize { extern "C" { fn proc_pid(process: *const libc::c_void) -> libc::c_int; } let &Process(ref inner) = self; unsafe { proc_pid(inner.to_owned()) as isize } } pub fn ppid(&self) -> isize { extern "C" { fn proc_ppid(process: *const libc::c_void) -> libc::c_int; } let &Process(ref inner) = self; unsafe { proc_ppid(inner.to_owned()) as isize } } pub fn name(&self) -> Result<String, Utf8Error> { extern "C" { fn proc_name(pid: libc::c_int, name: *mut libc::c_char, name_len: libc::c_int); } let mut name = vec![0u8; 1024]; unsafe { proc_name(self.pid() as libc::c_int, name.as_ptr() as *mut libc::c_char, name.len() as libc::c_int) } let len = name.iter().position(|c| *c == b'\0').unwrap_or(0); match str::from_utf8(&name[..len]) { Ok(s) => Ok(s.to_string()), Err(err) => Err(err), } } // pub fn tree(&self) -> Vec<isize> { // if self.ppid() >= 0 { // parent = // } // } } impl Drop for Process { fn drop(&mut self) { extern "C" { fn proc_rele(process: *const libc::c_void); } // println!("Releasing Process Ref"); let &mut Process(ref mut inner) = self; unsafe { proc_rele(inner.to_owned()) }; } }
use super::{insights::Insight, static_panics::StaticPanicsOfMir}; use crate::{ database::Database, features_candy::analyzer::insights::ErrorDiagnostic, server::AnalyzerClient, utils::LspPositionConversion, }; use candy_frontend::{ ast_to_hir::AstToHir, mir_optimize::OptimizeMir, module::Module, TracingConfig, TracingMode, }; use candy_fuzzer::{FuzzablesFinder, Fuzzer, Status}; use candy_vm::{ execution_controller::RunLimitedNumberOfInstructions, fiber::{Panic, VmEnded}, heap::DisplayWithSymbolTable, lir::Lir, mir_to_lir::compile_lir, tracer::{evaluated_values::EvaluatedValuesTracer, stack_trace::StackTracer}, vm::{self, Vm}, }; use extension_trait::extension_trait; use itertools::Itertools; use lsp_types::Diagnostic; use rand::{prelude::SliceRandom, thread_rng}; use std::rc::Rc; use tracing::info; /// A hints finder is responsible for finding hints for a single module. pub struct ModuleAnalyzer { module: Module, state: Option<State>, // only None during state transition } enum State { Initial, /// First, we run the module with tracing of evaluated expressions enabled. /// This enables us to show hints for constants. EvaluateConstants { static_panics: Vec<Panic>, tracer: (StackTracer, EvaluatedValuesTracer), vm: Vm<Lir, (StackTracer, EvaluatedValuesTracer)>, }, /// Next, we run the module again to finds fuzzable functions. This time, we /// disable tracing of evaluated expressions, but we enable registration of /// fuzzable functions. Thus, the found functions to fuzz have the most /// efficient LIR possible. FindFuzzables { static_panics: Vec<Panic>, constants_ended: VmEnded, stack_tracer: StackTracer, evaluated_values: EvaluatedValuesTracer, lir: Rc<Lir>, tracer: FuzzablesFinder, vm: Vm<Rc<Lir>, FuzzablesFinder>, }, /// Then, the functions are actually fuzzed. Fuzz { static_panics: Vec<Panic>, constants_ended: VmEnded, stack_tracer: StackTracer, evaluated_values: EvaluatedValuesTracer, fuzzable_finder_ended: VmEnded, fuzzers: Vec<Fuzzer>, }, } impl ModuleAnalyzer { pub fn for_module(module: Module) -> Self { Self { module, state: Some(State::Initial), } } pub fn module_changed(&mut self) { // PERF: Save some incremental state. self.state = Some(State::Initial); } pub async fn run(&mut self, db: &Database, client: &AnalyzerClient) { let state = self.state.take().unwrap(); let state = self.update_state(db, client, state).await; self.state = Some(state); } async fn update_state(&self, db: &Database, client: &AnalyzerClient, state: State) -> State { match state { State::Initial => { client .update_status(Some(format!("Compiling {}", self.module))) .await; let (mir, _, _) = db .optimized_mir( self.module.clone(), TracingConfig { register_fuzzables: TracingMode::OnlyCurrent, calls: TracingMode::Off, evaluated_expressions: TracingMode::Off, }, ) .unwrap(); let mut mir = (*mir).clone(); let mut static_panics = mir.static_panics(); static_panics.retain(|panic| panic.responsible.module == self.module); let tracing = TracingConfig { register_fuzzables: TracingMode::Off, calls: TracingMode::Off, evaluated_expressions: TracingMode::OnlyCurrent, }; let (lir, _) = compile_lir(db, self.module.clone(), tracing); let mut tracer = ( StackTracer::default(), EvaluatedValuesTracer::new(self.module.clone()), ); let vm = Vm::for_module(lir, &mut tracer); State::EvaluateConstants { static_panics, tracer, vm, } } State::EvaluateConstants { static_panics, mut tracer, mut vm, } => { client .update_status(Some(format!("Evaluating {}", self.module))) .await; vm.run(&mut RunLimitedNumberOfInstructions::new(500), &mut tracer); if !matches!(vm.status(), vm::Status::Done | vm::Status::Panicked(_)) { return State::EvaluateConstants { static_panics, tracer, vm, }; } let constants_ended = vm.tear_down(&mut tracer); let (stack_tracer, evaluated_values) = tracer; let tracing = TracingConfig { register_fuzzables: TracingMode::OnlyCurrent, calls: TracingMode::Off, evaluated_expressions: TracingMode::Off, }; let (lir, _) = compile_lir(db, self.module.clone(), tracing); let lir = Rc::new(lir); let mut tracer = FuzzablesFinder::default(); let vm = Vm::for_module(lir.clone(), &mut tracer); State::FindFuzzables { static_panics, constants_ended, stack_tracer, evaluated_values, lir, tracer, vm, } } State::FindFuzzables { static_panics, constants_ended, stack_tracer, evaluated_values, lir, mut tracer, mut vm, } => { client .update_status(Some(format!("Evaluating {}", self.module))) .await; vm.run(&mut RunLimitedNumberOfInstructions::new(500), &mut tracer); if !matches!(vm.status(), vm::Status::Done | vm::Status::Panicked(_)) { return State::FindFuzzables { static_panics, constants_ended, stack_tracer, evaluated_values, lir, tracer, vm, }; } let fuzzable_finder_ended = vm.tear_down(&mut tracer); let fuzzers = tracer .into_fuzzables() .iter() .map(|(id, function)| Fuzzer::new(lir.clone(), *function, id.clone())) .collect(); State::Fuzz { static_panics, constants_ended, stack_tracer, evaluated_values, fuzzable_finder_ended, fuzzers, } } State::Fuzz { static_panics, constants_ended, stack_tracer, evaluated_values, fuzzable_finder_ended, mut fuzzers, } => { let mut running_fuzzers = fuzzers .iter_mut() .filter(|fuzzer| matches!(fuzzer.status(), Status::StillFuzzing { .. })) .collect_vec(); let Some(fuzzer) = running_fuzzers.choose_mut(&mut thread_rng()) else { client.update_status(None).await; return State::Fuzz { static_panics, constants_ended, stack_tracer, evaluated_values, fuzzable_finder_ended, fuzzers, }; }; client .update_status(Some(format!("Fuzzing {}", fuzzer.function_id))) .await; fuzzer.run(&mut RunLimitedNumberOfInstructions::new(500)); State::Fuzz { static_panics, constants_ended, stack_tracer, evaluated_values, fuzzable_finder_ended, fuzzers, } } } } pub fn insights(&self, db: &Database) -> Vec<Insight> { let mut insights = vec![]; match self.state.as_ref().unwrap() { State::Initial => {} State::EvaluateConstants { static_panics, .. } => { // TODO: Show incremental constant evaluation hints. insights.extend(static_panics.to_insights(db, &self.module)); } State::FindFuzzables { static_panics, evaluated_values, vm, .. } => { insights.extend(static_panics.to_insights(db, &self.module)); insights.extend(evaluated_values.values().iter().flat_map(|(id, value)| { Insight::for_value(db, &vm.lir().symbol_table, id.clone(), *value) })); } State::Fuzz { static_panics, evaluated_values, fuzzers, .. } => { insights.extend(static_panics.to_insights(db, &self.module)); let symbol_table = &fuzzers.first().unwrap().lir().symbol_table; insights.extend(evaluated_values.values().iter().flat_map(|(id, value)| { Insight::for_value(db, symbol_table, id.clone(), *value) })); for fuzzer in fuzzers { insights.append(&mut Insight::for_fuzzer_status(db, fuzzer)); let Status::FoundPanic { input, panic, .. } = fuzzer.status() else { continue; }; let id = fuzzer.function_id.clone(); if !id.is_same_module_and_any_parent_of(&panic.responsible) { // The function panics internally for an input, but it's // the fault of another function that's called // internally. // TODO: The fuzz case should instead be highlighted in // the used function directly. We don't do that right // now because we assume the fuzzer will find the panic // when fuzzing the faulty function, but we should save // the panicking case (or something like that) in the // future. continue; } if db.hir_to_cst_id(id.clone()).is_none() { panic!( "It looks like the generated code {} is at fault for a panic.", panic.responsible, ); } // TODO: In the future, re-run only the failing case with // tracing enabled and also show the arguments to the failing // function in the hint. let call_span = db .hir_id_to_display_span(panic.responsible.clone()) .unwrap(); insights.push(Insight::Diagnostic(Diagnostic::error( db.range_to_lsp_range(self.module.clone(), call_span), format!( "For `{} {}`, this call panics: {}", fuzzer.function_id.function_name(), input .arguments .iter() .map(|argument| DisplayWithSymbolTable::to_string( argument, symbol_table, )) .join(" "), panic.reason, ), ))); } } } info!("Insights: {insights:?}"); insights } } #[extension_trait] pub impl StaticPanics for Vec<Panic> { fn to_insights(&self, db: &Database, module: &Module) -> Vec<Insight> { self.iter() .map(|panic| Insight::for_static_panic(db, module.clone(), panic)) .collect_vec() } }
//! Additional docs for macros, and guides. pub mod library_evolution; pub mod prefix_types; pub mod sabi_nonexhaustive; pub mod sabi_trait_inherent; pub mod troubleshooting; pub mod unsafe_code_guidelines;
// 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. //! C bindings for wlan-mlme crate. extern crate log; // Explicitly declare usage for cbindgen. extern crate wlan_common; extern crate wlan_mlme; #[macro_use] pub mod utils; pub mod ap; pub mod auth; pub mod client; pub mod sequence;
use gl; use gl::types::*; pub trait GLShader { fn to_glenum(&self) -> GLenum; fn get_glsl(&self) -> &'static str; } pub struct GLVertexShader { glsl: &'static str, } impl GLShader for GLVertexShader { fn to_glenum(&self) -> GLenum { return gl::VERTEX_SHADER; } fn get_glsl(&self) -> &'static str { return self.glsl; } } pub struct GLFragmentShader { glsl: &'static str, } impl GLShader for GLFragmentShader { fn to_glenum(&self) -> GLenum { return gl::FRAGMENT_SHADER; } fn get_glsl(&self) -> &'static str { return self.glsl; } } pub struct RenderingPipelineSource { pub vertex_glsl: GLVertexShader, pub fragment_glsl: GLFragmentShader, pub all_vertex_attrs: Vec<VertexAttribute>, pub vertex_width: u8, } pub struct VertexAttribute { pub var_name: &'static str, pub stride: GLsizei, } // Color Pipeline Source Definition pub fn color_pipeline_source() -> RenderingPipelineSource { return RenderingPipelineSource { vertex_glsl: GLVertexShader { glsl: COLOR_VS_GLSL }, fragment_glsl: GLFragmentShader { glsl: COLOR_FS_GLSL }, all_vertex_attrs: vec![VertexAttribute { var_name: "position", stride: 2, }, VertexAttribute { var_name: "color", stride: 3, }], vertex_width: 5, // this is the width of a ColorVertex: x, y, red, green, blue }; } const COLOR_VS_GLSL: &'static str = r#"#version 150 in vec2 position; in vec3 color; out vec3 attr_color; void main() { attr_color = color; gl_Position = vec4(position, 0.0, 1.0); }"#; const COLOR_FS_GLSL: &'static str = r#"#version 150 in vec3 attr_color; out vec4 out_color; void main() { out_color = vec4(attr_color, 1.0); }"#; // Texture Pipeline Source Definition pub fn texture_pipeline_source() -> RenderingPipelineSource { return RenderingPipelineSource { vertex_glsl: GLVertexShader { glsl: TEX_VS_GLSL }, fragment_glsl: GLFragmentShader { glsl: TEX_FS_GLSL }, all_vertex_attrs: vec![VertexAttribute { var_name: "position", stride: 2, }, VertexAttribute { var_name: "texcoord", stride: 2, }], vertex_width: 4, // this is the width of a TexVertex: x, y, tex_x, tex_y }; } const TEX_VS_GLSL: &'static str = r#"#version 150 in vec2 position; in vec2 texcoord; out vec2 attr_texcoord; void main() { attr_texcoord = texcoord; gl_Position = vec4(position, 0.0, 1.0); }"#; const TEX_FS_GLSL: &'static str = r#"#version 150 in vec2 attr_texcoord; uniform sampler2D tex_sample; out vec4 out_color; void main() { out_color = texture(tex_sample, attr_texcoord); }"#;
use crate::consts::MAX_PHYSICAL_PAGES; use spin::Mutex; pub struct SegmentTreeAllocator { a: [u8; MAX_PHYSICAL_PAGES << 1], // root is a[1] m: usize, // m is the leftmost leaf's idx in the segment tree n: usize, // n is the size of the ppn pages offset: usize, // the offset of the ppn pages } // some help macro macro_rules! l_child { ($node:expr) => (($node) << 1) } macro_rules! r_child { ($node:expr) => ((($node) << 1) | 1) } macro_rules! parent { ($node:expr) => (($node) >> 1) } impl SegmentTreeAllocator { // init with ppn range [l, r) pub fn init(&mut self, l: usize, r: usize) { self.offset = l; self.n = r - l; self.m = 1; // m = 2^k, where 2^(k-1) < n <= 2^k while self.m < self.n { self.m = self.m << 1; } // init all the inner nodes with 1 for i in 1..(self.m << 1) { self.a[i] = 1; } // init all the leafs with 0 for i in 0..self.n { self.a[self.m + i] = 0; } // update the inner nodes for i in (1..self.m).rev() { self.a[i] = self.a[l_child!(i)] & self.a[r_child!(i)]; } } pub fn alloc(&mut self) -> usize { // assume that we never run out of physical memory if self.a[1] == 1 { panic!("physical memory depleted!"); } let mut p = 1; while p < self.m { // find an empty node if self.a[l_child!(p)] == 0 { p = l_child!(p) } else { p = r_child!(p) } } self.update(p, 1); // p - m + offset is the idx in the range [l, r) p + self.offset - self.m } pub fn dealloc(&mut self, n: usize) { let p = n + self.m - self.offset; assert!(self.a[p] == 1); self.update(p, 0); } #[inline(always)] fn update(&mut self, mut p: usize, value: u8) { self.a[p] = value; while p != 1 { p = parent!(p); self.a[p] = self.a[l_child!(p)] & self.a[r_child!(p)]; } } } pub static SEGMENT_TREE_ALLOCATOR: Mutex<SegmentTreeAllocator> = Mutex::new(SegmentTreeAllocator { a: [0; MAX_PHYSICAL_PAGES << 1], m: 0, n: 0, offset: 0, });
pub(crate) use _multiprocessing::make_module; #[cfg(windows)] #[pymodule] mod _multiprocessing { use crate::vm::{function::ArgBytesLike, stdlib::os, PyResult, VirtualMachine}; use winapi::um::winsock2::{self, SOCKET}; #[pyfunction] fn closesocket(socket: usize, vm: &VirtualMachine) -> PyResult<()> { let res = unsafe { winsock2::closesocket(socket as SOCKET) }; if res == 0 { Err(os::errno_err(vm)) } else { Ok(()) } } #[pyfunction] fn recv(socket: usize, size: usize, vm: &VirtualMachine) -> PyResult<libc::c_int> { let mut buf = vec![0; size]; let nread = unsafe { winsock2::recv(socket as SOCKET, buf.as_mut_ptr() as *mut _, size as i32, 0) }; if nread < 0 { Err(os::errno_err(vm)) } else { Ok(nread) } } #[pyfunction] fn send(socket: usize, buf: ArgBytesLike, vm: &VirtualMachine) -> PyResult<libc::c_int> { let ret = buf.with_ref(|b| unsafe { winsock2::send(socket as SOCKET, b.as_ptr() as *const _, b.len() as i32, 0) }); if ret < 0 { Err(os::errno_err(vm)) } else { Ok(ret) } } } #[cfg(not(windows))] #[pymodule] mod _multiprocessing {}
use std::io; use std::io::Write; pub trait Print { fn print(&mut self, text: &str) -> io::Result<()>; fn println(&mut self, text: &str) -> io::Result<()>; } pub struct Printer<W> { writer: W, } impl<W: Write> Printer<W> { pub fn new(writer: W) -> Self { Printer { writer } } } impl<W: Write> Print for Printer<W> { fn print(&mut self, text: &str) -> io::Result<()> { write!(self.writer, "{}", text)?; self.writer.flush()?; Ok(()) } fn println(&mut self, text: &str) -> io::Result<()> { writeln!(self.writer, "{}", text) } } mod test { use super::{Print, Printer}; #[test] fn write_works() { let txt = "Make some noise!"; let mut writer = Vec::new(); let mut printer = Printer::new(&mut writer); let result = printer.print(txt); assert!(result.is_ok()); let actual = String::from_utf8(writer.clone()).expect("not utf8"); let expected = txt; assert_eq!(actual, expected); } #[test] fn writeln_works() { let txt = "Make some noise!"; let mut writer = Vec::new(); let mut printer = Printer::new(&mut writer); let result = printer.println(txt); assert!(result.is_ok()); let actual = String::from_utf8(writer.clone()).expect("not utf8"); let expected = format!("{}\n", txt); assert_eq!(actual, expected); } }
use encoding::{get_base_enc, Encoding}; use fontref::FontRef; use graphicsstate::Color; use std::fmt; use std::fs::File; use std::io::{BufWriter, Result, Write}; use units::{LengthUnit, UserSpace}; /// A text object is where text is put on the canvas. /// /// A TextObject should never be created directly by the user. Instead, the /// [Canvas.text](struct.Canvas.html#method.text) method should be called. /// It will create a TextObject and call a callback, before terminating the /// text object properly. /// /// # Example /// /// ``` /// # #[macro_use] /// # extern crate simple_pdf; /// # use simple_pdf::units::{Points, UserSpace, LengthUnit}; /// # use simple_pdf::{Pdf, BuiltinFont, FontSource}; /// # use simple_pdf::graphicsstate::Matrix; /// # use std::io; /// # fn main() -> io::Result<()> { /// # let mut document = Pdf::create("foo.pdf")?; /// # document.render_page(pt!(180), pt!(240), |canvas| { /// let serif = canvas.get_font(&BuiltinFont::Times_Roman); /// // t will be a TextObject /// canvas.text(|t| { /// t.set_font(&serif, pt!(14))?; /// t.set_leading(pt!(18))?; /// t.pos(pt!(10), pt!(300))?; /// t.show("Some lines of text in what might look like a")?; /// t.show_line("paragraph of three lines. Lorem ipsum dolor")?; /// t.show_line("sit amet. Blahonga.") /// })?; /// # Ok(()) /// # })?; /// # document.finish() /// # } /// ``` pub struct TextObject<'a> { output: &'a mut BufWriter<File>, encoding: Encoding, } impl<'a> TextObject<'a> { // Should not be called by user code. pub(crate) fn new(output: &'a mut BufWriter<File>) -> Self { TextObject { output, encoding: get_base_enc().to_encoding().clone(), } } /// Set the font and font-size to be used by the following text operations. pub fn set_font<T: LengthUnit>( &mut self, font: &FontRef, size: UserSpace<T>, ) -> Result<()> { self.encoding = font.encoding().clone(); writeln!(self.output, "{} {} Tf", font, size) } /// Set text render mode, which enables rendering text filled, stroked or /// as clipping boundary. pub fn set_render_mode(&mut self, mode: RenderMode) -> Result<()> { writeln!(self.output, "{} Tr", mode) } /// Set leading, the vertical distance from a line of text to the next. /// This is important for the [show_line](#method.show_line) method. pub fn set_leading<T: LengthUnit>( &mut self, leading: UserSpace<T>, ) -> Result<()> { writeln!(self.output, "{} TL", leading) } /// Set the rise above the baseline for coming text. Calling set_rise again /// with a zero argument will get back to the old baseline. pub fn set_rise<T: LengthUnit>( &mut self, rise: UserSpace<T>, ) -> Result<()> { writeln!(self.output, "{} Ts", rise) } /// Set the amount of extra space between characters, in 1/1000 text unit. pub fn set_char_spacing<T: LengthUnit>( &mut self, c_space: UserSpace<T>, ) -> Result<()> { writeln!(self.output, "{} Tc", c_space) } /// Set the amount of extra space between words, in 1/1000 text unit. pub fn set_word_spacing<T: LengthUnit>( &mut self, w_space: UserSpace<T>, ) -> Result<()> { writeln!(self.output, "{} Tw", w_space) } /// Set color for stroking operations. pub fn set_stroke_color(&mut self, color: Color) -> Result<()> { match color { Color::RGB { .. } => writeln!(self.output, "{} SC", color), Color::Gray { .. } => writeln!(self.output, "{} G", color), } } /// Set color for non-stroking operations. pub fn set_fill_color(&mut self, color: Color) -> Result<()> { match color { Color::RGB { .. } => writeln!(self.output, "{} sc", color), Color::Gray { .. } => writeln!(self.output, "{} g", color), } } /// Move text position. /// /// The first time `pos` is called in a TextObject, (x, y) refers to the /// same point as for [Canvas::move_to](struct.Canvas.html#method.move_to), /// after that, the point is relative to the earlier pos. pub fn pos<T: LengthUnit>( &mut self, x: UserSpace<T>, y: UserSpace<T>, ) -> Result<()> { writeln!(self.output, "{} {} Td", x, y) } /// Show a text. pub fn show(&mut self, text: &str) -> Result<()> { write!(self.output, "(")?; self.output.write_all(&self.encoding.encode_string(text))?; writeln!(self.output, ") Tj") } /// Show one or more text strings, allowing individual glyph positioning. /// /// Each item in param should contain a string to show and a number to /// adjust the position. The adjustment is measured in thousands of unit of /// text space. Positive adjustment brings letters closer, negative widens /// the gap. /// /// # Example /// /// ``` /// # #[macro_use] /// # extern crate simple_pdf; /// # use simple_pdf::units::{Points, UserSpace, LengthUnit}; /// # use simple_pdf::{Pdf, BuiltinFont, FontSource}; /// # use simple_pdf::graphicsstate::Matrix; /// # use std::io; /// # fn main() -> io::Result<()> { /// # let mut document = Pdf::create("foo.pdf")?; /// # document.render_page(pt!(180), pt!(240), |canvas| { /// # let serif = canvas.get_font(&BuiltinFont::Times_Roman); /// # canvas.text(|t| { /// # t.set_font(&serif, pt!(14))?; /// t.show_adjusted(&[("W", 130), ("AN", -40), ("D", 0)]) /// # }) /// # })?; /// # document.finish() /// # } /// ``` pub fn show_adjusted(&mut self, param: &[(&str, i32)]) -> Result<()> { write!(self.output, "[")?; for &(text, offset) in param { write!(self.output, "(")?; self.output.write_all(&self.encoding.encode_string(text))?; write!(self.output, ") {} ", offset)?; } writeln!(self.output, "] TJ") } /// Show a text as a line. See also [set_leading](#method.set_leading). pub fn show_line(&mut self, text: &str) -> Result<()> { write!(self.output, "(")?; self.output.write_all(&self.encoding.encode_string(text))?; writeln!(self.output, ") '") } /// Push the graphics state on a stack. pub fn gsave(&mut self) -> Result<()> { // TODO Push current encoding in self? writeln!(self.output, "q") } /// Pop a graphics state from the [gsave](#method.gsave) stack and restore /// it. pub fn grestore(&mut self) -> Result<()> { // TODO Pop current encoding in self? writeln!(self.output, "Q") } } /// Text rendering modes for the method /// [TextObject.set_render_mode](struct.TextObject.html#method.set_render_mode). #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub enum RenderMode { /// Fills text glyphs with nonstroking color. Fill, /// Draws outline of text glyphs with stroking color. Stroke, /// Fills, then strokes text. FillAndStroke, /// Renders the text invisible. Invisible, /// Adds the filled text glyphs to clipping path. FillAndClipping, /// Adds the stroked text glyphs to clipping path. StrokeAndClipping, /// Adds the filled, then stroked text glyphs to clipping path. FillAndStrokeAndClipping, /// Adds text to clipping path Clipping, } impl fmt::Display for RenderMode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match *self { RenderMode::Fill => 0, RenderMode::Stroke => 1, RenderMode::FillAndStroke => 2, RenderMode::Invisible => 3, RenderMode::FillAndClipping => 4, RenderMode::StrokeAndClipping => 5, RenderMode::FillAndStrokeAndClipping => 6, RenderMode::Clipping => 7, } ) } }
//! ```elixir //! # label 1 //! # pushed to stack: (module, function arguments, before) //! # returned from call: before //! # full stack: (before, module, function arguments) //! # returns: value //! value = apply(module, function, arguments) //! after = :erlang.monotonic_time() //! duration = after - before //! time = :erlang.convert_time_unit(duration, :native, :microsecond) //! {time, value} //! ``` use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; use crate::erlang::apply_3; use super::label_2; // Private #[native_implemented::label] fn result(process: &Process, before: Term, module: Term, function: Term, arguments: Term) -> Term { assert!(before.is_integer()); assert!(module.is_atom(), "module ({:?}) is not an atom", module); assert!(function.is_atom()); assert!(arguments.is_list()); process.queue_frame_with_arguments( apply_3::frame().with_arguments(false, &[module, function, arguments]), ); process.queue_frame_with_arguments(label_2::frame().with_arguments(true, &[before])); Term::NONE }
#![allow(non_snake_case)] #![allow(unused_variables)] use clap::App; use clap::Arg; use colored::*; use std::collections::HashMap; use std::fs::*; use std::net::Ipv4Addr; use std::net::{IpAddr, Ipv6Addr}; pub mod config; pub mod serve; pub mod utils; fn main() { let matches = App::new("dns-rs") .version("1.0.0") .author("9646516@BUPT <zyq855@gmail.com>") .about("Github:github.com/9646516/DNS.rs") .arg( Arg::with_name("debug") .short("d") .long("debug") .value_name("Debug Level") .help( "\ Sets output level.\n\ Less(0):\tOutput Nothing\n\ Default(1):\tOutput the status of Socket\n\ More(2):\tOutput Error Information\n\ All(3):\tOutput Details of every packet\ ", ) .takes_value(true), ) .get_matches(); let path = "dns.conf"; let config = match config::Config::init(path, matches) { Err(err) => { let res = format!("Fatal Error when reading config:{}", err); println!("{}", res.bright_red()); return; } Ok(config) => config, }; println!("{}", "Config load success\n".cyan()); println!("{}\n", config); let mut rule4: HashMap<String, Ipv4Addr> = HashMap::new(); let mut rule6: HashMap<String, Ipv6Addr> = HashMap::new(); let FILE: String = read_to_string(&config.Rule).expect("Rule File load Failed"); for i in FILE.split_terminator('\n') { let res: Vec<&str> = i.trim_end_matches('\r').split_ascii_whitespace().collect(); if res.len() == 2 { let ans: IpAddr = res[0].parse().expect("Host Format Error"); match ans { IpAddr::V4(ip4) => { rule4.insert(res[1].to_string(), ip4); } IpAddr::V6(ip6) => { rule6.insert(res[1].to_string(), ip6); } } } } println!("{}", "Rule load success\n".cyan()); let res = format!( "{} IPv4 hosts which takes approximate {} Bytes (On Theory)\n\ {} IPv6 hosts which takes approximate {} Bytes (On Theory)\n ", rule4.len(), (std::mem::size_of::<String>() + std::mem::size_of::<Ipv4Addr>() + std::mem::size_of::<u64>()) * rule4.capacity() * 11 / 10, rule6.len(), (std::mem::size_of::<String>() + std::mem::size_of::<Ipv6Addr>() + std::mem::size_of::<u64>()) * rule6.capacity() * 11 / 10 ); println!("{}", res.bright_yellow()); let serve = match serve::DNSServe::build(config, rule4, rule6) { Ok(T) => T, Err(err) => { let res = format!("Fatal Error when setup service:{}", err); println!("{}", res.bright_red()); return; } }; println!("{}", "Service setup success\n".cyan()); serve.run(); }
use db::Connector; use db::actions::*; use db::models::*; use interactions::handler::InviteUrl; use interactions::parsing::get_values; use serenity::builder::CreateEmbedField; use serenity::prelude::*; use serenity::model::{Message, User, GuildId, MessageId}; use serenity::framework::standard::Args; use serenity::framework::standard::CommandError; const DEFAULT_DISCORD_AVATAR: &str = "http://is1.mzstatic.com/image/thumb/Purple118/v4/98/0d/81/980d8181-c84b-4c21-cef8-126464197968/source/300x300bb.jpg"; pub fn invite_link(ctx: &mut Context, message: &Message, _: Args) -> Result<(), CommandError> { let data = ctx.data.lock(); let inv_container = data.get::<InviteUrl>(); match inv_container { Some(c) => { message.reply(&c.0)?; }, None => { message.reply("The invite link could not be obtained at this time :(")?; } } Ok(()) } pub fn command_delete_quote(ctx: &mut Context, message: &Message, mut args: Args) -> Result<(), CommandError> { let msg_id = match args.single::<i32>() { Ok(v) => v, Err(_) => { message.reply("No message id was given, example command `!quote delete 30`")?; return Ok(()); } }; let conn = { let data = ctx.data.lock(); let connector = data.get::<Connector>().unwrap(); connector .get_conn() .map_err(|_| "Could not get a connection to the db!")? }; let quote = match find_quote(&conn, msg_id) { Ok(v) => match v { Some(q) => q, None => { message.reply(&format!("A quote with the id of {} was not found.", msg_id))?; return Ok(()); } }, Err(_) => { message.reply("Error while accessing quote database!")?; return Ok(()); } }; let author_id = message.author.id.0.to_string(); if author_id != quote.created_by_id && author_id != quote.quoted_by_id { message.reply("Due to company policy, you must be either the person being quoted or the person who quoted to delete a quote.")?; return Ok(()); } match delete_quote(&conn, &quote) { Ok(deleted) if deleted => { message.reply("Quote was successfully deleted!")?; return Ok(()); } Ok(_) | Err(_) => { message.reply("Error while deleting message!")?; return Ok(()); } } } pub fn command_from( ctx: &mut Context, message: &Message, mut args: Args, ) -> Result<(), CommandError> { let author = match args.single::<User>() { Ok(v) => v, Err(_) => { let _ = message.reply("No user was mentioned!"); return Ok(()); } }; let branch = match args.single::<String>() { Ok(v) => v, Err(_) => { let _ = message.reply("No find types were specified! Consider revising the help list."); return Ok(()); } }; let result = match branch.to_lowercase().as_str() { "rand" => rand_quote(ctx, message, &author, args), "contains" => contains_quotes(ctx, message, &author, args), "list" => list_quotes(ctx, message, &author, args), _ => { message.reply("This find type doesn't exist! Consider revising the help list.")?; return Ok(()); } }; match result { Ok(_) => return Ok(()), Err(e) => { message.channel().ok_or("No channel here?!")?.say(&format!("Error while getting quotes: {}", e))?; return Ok(()) } } } fn rand_quote(ctx: &mut Context, message: &Message, author: &User, _: Args) -> Result<(), String> { let conn = { let data = ctx.data.lock(); let connector = data.get::<Connector>().unwrap(); connector .get_conn() .map_err(|_| "Could not get a connection to the db!")? }; let guild_id = message .guild_id() .ok_or("This isn't a real channel. You're not real.")?; let quotes = find_rand_quote(&conn, &author.id.to_string(), &guild_id.to_string()) .map_err(|_| "Could not read the quote database.")? .ok_or("No quotes found! :(")?; message .channel() .ok_or("This channel is fake!")? .send_message(|reply| reply.embed(|f| f.thumbnail(&author.avatar_url().unwrap_or(DEFAULT_DISCORD_AVATAR.to_string())) .title(format!("A random quote from the lovely {}.", author.name)) .fields(create_quote_embed_section(vec![quotes], &guild_id)) )) .map_err(|e| format!("Could not send message! Error: {:?}", e))?; Ok(()) } fn contains_quotes(ctx: &mut Context, message: &Message, author: &User, args: Args) -> Result<(), String> { let conn = { let data = ctx.data.lock(); let connector = data.get::<Connector>().unwrap(); connector .get_conn() .map_err(|_| "Could not get a connection to the db!")? }; let guild_id = message .guild_id() .ok_or("This isn't a real channel. You're not real.")?; let query = args.full(); let query = query.trim_matches(|c| c == '\"' || c == '"' || c == ' '); let quotes = find_contains_quotes(&conn, &author.id.to_string(), &guild_id.to_string(), &query) .map_err(|_| "Could not read the quote database.")?; if quotes.len() <= 0 { return Err(format!("No quotes that match {} found :(", query)); } message .channel() .ok_or("This channel is fake!")? .send_message(|reply| reply.embed(|f| f.thumbnail(&author.avatar_url().unwrap_or(DEFAULT_DISCORD_AVATAR.to_string())) .title(format!("A collection of quotes that contain {} from {}.", query, author.name)) .fields(create_quote_embed_section(quotes, &guild_id)) )) .map_err(|e| format!("Could not send message! Error: {:?}", e))?; Ok(()) } fn list_quotes(ctx: &mut Context, message: &Message, author: &User, args: Args) -> Result<(), String> { let conn = { let data = ctx.data.lock(); let connector = data.get::<Connector>().unwrap(); connector .get_conn() .map_err(|_| "Could not get a connection to the db!")? }; let guild_id = message .guild_id() .ok_or("This isn't a real channel. You're not real.")?; let rest = args.full(); let set = get_values(&rest)?; let amount = match set.get(&"amount".to_string()) { Some(v) => Some(v.as_str().parse::<i64>().map_err(|_| "Could not parse the amount into a number!")?), None => None, }; let page = match set.get(&"page".to_string()) { Some(v) => Some(v.as_str().parse::<i64>().map_err(|_| "Could not parse the page into a number!")?), None => None, }; let quotes = find_listed_quotes(&conn, &author.id.to_string(), &guild_id.to_string(), ListParams { amount, page, }) .map_err(|_| "Could not read the quote database.")?; if quotes.len() <= 0 { return Err("No quotes found :(".to_string()); } message .channel() .ok_or("This channel is fake!")? .send_message(|reply| reply.embed(|f| f.thumbnail(&author.avatar_url().unwrap_or(DEFAULT_DISCORD_AVATAR.to_string())) .title(format!("A collection of quotes from {}, page: {} max: {}.", author.name, page.unwrap_or(1), amount.unwrap_or(5))) .fields(create_quote_embed_section(quotes, &guild_id)) )) .map_err(|e| format!("Could not send message! Error: {:?}", e))?; Ok(()) } fn create_quote_embed_section(quotes: Vec<Quote>, guild: &GuildId) -> Vec<CreateEmbedField> { quotes .iter() .map(|quote| { CreateEmbedField::default() .value(quote.quote.to_string()) .inline(false) .name( format!( "ID {}, on {}, quoted by {}.", quote.id, MessageId(quote.message_id .parse::<u64>() .unwrap()) .created_at() .format("%a %e %b"), guild .member(quote.quoted_by_id.parse::<u64>().unwrap()) .map(|m| m.display_name().to_string()) .unwrap_or("<user left>".to_string()) ) ) }) .collect() }
pub fn table(data:u32){ println!("WE are in Lib.rs"); for count in 1..=3{ println!("{}*{}= {}", data,count,data*count); } }
fn main() { println!("This is a placeholder for cargo-link!"); }
use super::{Map, MapElement}; /// Generate the test map pub fn generate_test_map() -> Map { info!("Generating Test Map"); let mut map = Map::new(); for x in 20..=22 { for y in 0..=50 { *map.get_mut(x, y) = MapElement::Wall; } } debug!("Done Generating Test Map"); map }
// Standard library use std::sync::{Arc, Mutex}; // This crate use crate::actions::{SayHelloAction, ACT_REG}; use crate::exts::LockIt; use crate::signals::{new_signal_order, poll::PollQuery, Timer, SIG_REG}; use crate::skills::SkillLoader; // Other crates use anyhow::Result; use async_trait::async_trait; use unic_langid::LanguageIdentifier; pub struct EmbeddedLoader {} impl EmbeddedLoader { pub fn new() -> Self { Self {} } } #[async_trait(?Send)] impl SkillLoader for EmbeddedLoader { fn load_skills(&mut self, langs: &[LanguageIdentifier]) -> Result<()> { { let mut mut_sigreg = SIG_REG.lock_it(); mut_sigreg.set_order(Arc::new(Mutex::new(new_signal_order(langs.to_owned()))))?; mut_sigreg.set_poll(Arc::new(Mutex::new(PollQuery::new())))?; mut_sigreg.insert( "embedded", "timer", Arc::new(Mutex::new(Timer::new())), )?; } { let mut mut_actreg = ACT_REG.lock_it(); mut_actreg.insert( "embedded", "say_hello", Arc::new(Mutex::new(SayHelloAction::new())), )?; } Ok(()) } async fn run_loader(&mut self) -> Result<()> { Ok(()) } }
fn main() { let mut x = 10 < 11; assert!(x); }
use arduino_uno::prelude::*; use arduino_uno::adc::Adc; use arduino_uno::hal::port::{ Pin, mode::{Analog, Input, Floating}, portc::{PC0, PC1}, }; use crate::Direction; use super::{InputDevice, InputSignal}; /// Object describing the input received from the JoyStick. #[derive(Copy, Clone)] pub struct JoyStickSignal { // Signed 8-bit integer where negative values indicate magnitude Left // and positive values indicate magnitude Right. pub horiz: i8, // Signed 8-bit integer where negative values indicate magnitude Down // and positive values indicate magnitude Up. pub vert: i8, // Boolean indicating if the button was pressed. pub button: bool, } impl JoyStickSignal { /// Convert the JoyStickSignal object into a single direction, if possible. /// /// If no direction exceeds the threshold value, None value is returned. pub fn to_single_direction(self) -> Option<Direction> { if self.horiz.abs() > self.vert.abs() { if self.horiz < -JoyStick::THRESHOLD { return Some(Direction::Left) } else if self.horiz > JoyStick::THRESHOLD { return Some(Direction::Right) } } if self.vert < -JoyStick::THRESHOLD { return Some(Direction::Down) } else if self.vert > JoyStick::THRESHOLD { return Some(Direction::Up) } None } } /// Object that interfaces with the JoyStick peripheral. pub struct JoyStick { // Analog pin that reads x-axis values. x_axis: PC0<Analog>, // Analog pin that reads y-axis values. y_axis: PC1<Analog>, // Digital pin that reads button presses. z_axis: Pin<Input<Floating>>, } impl JoyStick { const CENTER: i16 = 512; pub const THRESHOLD: i8 = 50; /// Creates a new JoyStick object. pub fn new( x_axis: PC0<Analog>, y_axis: PC1<Analog>, z_axis: Pin<Input<Floating>>, ) -> Self { JoyStick { x_axis, y_axis, z_axis } } } impl InputDevice for JoyStick { /// Read the input data from the JoyStick Peripheral. /// /// # Arguments /// * adc - The Analog-Digital convertor required to read analog data. /// /// # Returns /// Option<InputSignal::JoyStick> fn read(&mut self, adc: &mut Adc) -> Option<InputSignal> { let x: u16 = nb::block!(adc.read(&mut self.x_axis)).void_unwrap(); let y: u16 = nb::block!(adc.read(&mut self.y_axis)).void_unwrap(); let z: bool = self.z_axis.is_low().void_unwrap(); let signal = JoyStickSignal { horiz: (((x as i16) - Self::CENTER) / 4) as i8, vert: (((y as i16) - Self::CENTER) / 4) as i8, button: z, }; if (signal.button) | (signal.horiz.abs() > Self::THRESHOLD) | (signal.vert.abs() > Self::THRESHOLD) { return Some(InputSignal::JoyStick(signal)) } None } }
use once_cell::sync::OnceCell; use std::{ fs::File, process::{Child, Command, Stdio}, sync::{ atomic::{AtomicUsize, Ordering::SeqCst}, Arc, Weak, }, time::Duration, }; use tokio::sync::Mutex; #[macro_export] /// If `TEST_INTEGRATION` is set and InfluxDB 2.0 OSS is available (either locally /// via `influxd` directly if the `INFLUXDB_IOX_INTEGRATION_LOCAL` environment // variable is set, or via `docker` otherwise), set up the server as requested and /// return it to the caller. /// /// If `TEST_INTEGRATION` is not set, skip the calling test by returning early. macro_rules! maybe_skip_integration { ($server_fixture:expr) => {{ let local = std::env::var("INFLUXDB_IOX_INTEGRATION_LOCAL").is_ok(); let command = if local { "influxd" } else { "docker" }; match ( std::process::Command::new("which") .arg(command) .stdout(std::process::Stdio::null()) .status() .expect("should be able to run `which`") .success(), std::env::var("TEST_INTEGRATION").is_ok(), ) { (true, true) => $server_fixture, (false, true) => { panic!( "TEST_INTEGRATION is set which requires running integration tests, but \ `{}` is not available", command ) } _ => { eprintln!( "skipping integration test - set the TEST_INTEGRATION environment variable \ and install `{}` to run", command ); return Ok(()); } } }}; } /// Represents a server that has been started and is available for /// testing. pub struct ServerFixture { server: Arc<TestServer>, } impl ServerFixture { /// Create a new server fixture and wait for it to be ready. This /// is called "create" rather than new because it is async and /// waits. The shared database can be used immediately. /// /// This is currently implemented as a singleton so all tests *must* /// use a new database and not interfere with the existing database. pub async fn create_shared() -> Self { // Try and reuse the same shared server, if there is already // one present static SHARED_SERVER: OnceCell<parking_lot::Mutex<Weak<TestServer>>> = OnceCell::new(); let shared_server = SHARED_SERVER.get_or_init(|| parking_lot::Mutex::new(Weak::new())); let shared_upgraded = { let locked = shared_server.lock(); locked.upgrade() }; // is a shared server already present? let server = match shared_upgraded { Some(server) => server, None => { // if not, create one let mut server = TestServer::new(); // ensure the server is ready server.wait_until_ready(InitialConfig::Onboarded).await; let server = Arc::new(server); // save a reference for other threads that may want to // use this server, but don't prevent it from being // destroyed when going out of scope let mut shared_server = shared_server.lock(); *shared_server = Arc::downgrade(&server); server } }; Self { server } } /// Create a new server fixture and wait for it to be ready. This /// is called "create" rather than new because it is async and /// waits. The database is left unconfigured and is not shared /// with any other tests. pub async fn create_single_use() -> Self { let mut server = TestServer::new(); // ensure the server is ready server.wait_until_ready(InitialConfig::None).await; let server = Arc::new(server); Self { server } } /// Return a client suitable for communicating with this server pub fn client(&self) -> influxdb2_client::Client { match self.server.admin_token.as_ref() { Some(token) => influxdb2_client::Client::new(self.http_base(), token), None => influxdb2_client::Client::new(self.http_base(), ""), } } /// Return the http base URL for the HTTP API pub fn http_base(&self) -> &str { &self.server.http_base } } /// Specifies whether the server should be set up initially #[derive(Debug, Copy, Clone, PartialEq)] enum InitialConfig { /// Don't set up the server, the test will (for testing onboarding) None, /// Onboard the server and set up the client with the associated token (for /// most tests) Onboarded, } // These port numbers are chosen to not collide with a development ioxd/influxd // server running locally. // TODO(786): allocate random free ports instead of hardcoding. // TODO(785): we cannot use localhost here. static NEXT_PORT: AtomicUsize = AtomicUsize::new(8190); /// Represents the current known state of a TestServer #[derive(Debug)] enum ServerState { Started, Ready, Error, } const ADMIN_TEST_USER: &str = "admin-test-user"; const ADMIN_TEST_ORG: &str = "admin-test-org"; const ADMIN_TEST_BUCKET: &str = "admin-test-bucket"; const ADMIN_TEST_PASSWORD: &str = "admin-test-password"; struct TestServer { /// Is the server ready to accept connections? ready: Mutex<ServerState>, /// Handle to the server process being controlled server_process: Child, /// When using Docker, the name of the detached child docker_name: Option<String>, /// HTTP API base http_base: String, /// Admin token, if onboarding has happened admin_token: Option<String>, } impl TestServer { fn new() -> Self { let ready = Mutex::new(ServerState::Started); let http_port = NEXT_PORT.fetch_add(1, SeqCst); let http_base = format!("http://127.0.0.1:{http_port}"); let temp_dir = test_helpers::tmp_dir().unwrap(); let mut log_path = temp_dir.path().to_path_buf(); log_path.push(format!("influxdb_server_fixture_{http_port}.log")); let mut bolt_path = temp_dir.path().to_path_buf(); bolt_path.push(format!("influxd_{http_port}.bolt")); let mut engine_path = temp_dir.path().to_path_buf(); engine_path.push(format!("influxd_{http_port}_engine")); println!("****************"); println!("Server Logging to {log_path:?}"); println!("****************"); let log_file = File::create(log_path).expect("Opening log file"); let stdout_log_file = log_file .try_clone() .expect("cloning file handle for stdout"); let stderr_log_file = log_file; let local = std::env::var("INFLUXDB_IOX_INTEGRATION_LOCAL").is_ok(); let (server_process, docker_name) = if local { let cmd = Command::new("influxd") .arg("--http-bind-address") .arg(format!(":{http_port}")) .arg("--bolt-path") .arg(bolt_path) .arg("--engine-path") .arg(engine_path) // redirect output to log file .stdout(stdout_log_file) .stderr(stderr_log_file) .spawn() .expect("starting of local server process"); (cmd, None) } else { let ci_image = "quay.io/influxdb/rust:ci"; let container_name = format!("influxdb2_{http_port}"); Command::new("docker") .arg("container") .arg("run") .arg("--name") .arg(&container_name) .arg("--publish") .arg(format!("{http_port}:8086")) .arg("--rm") .arg("--pull") .arg("always") .arg("--detach") .arg(ci_image) .arg("influxd") .output() .expect("starting of docker server process"); let cmd = Command::new("docker") .arg("logs") .arg(&container_name) // redirect output to log file .stdout(stdout_log_file) .stderr(stderr_log_file) .spawn() .expect("starting of docker logs process"); (cmd, Some(container_name)) }; Self { ready, server_process, docker_name, http_base, admin_token: None, } } async fn wait_until_ready(&mut self, initial_config: InitialConfig) { let mut ready = self.ready.lock().await; match *ready { ServerState::Started => {} // first time, need to try and start it ServerState::Ready => { return; } ServerState::Error => { panic!("Server was previously found to be in Error, aborting"); } } let try_http_connect = async { let client = reqwest::Client::new(); let url = format!("{}/health", self.http_base); let mut interval = tokio::time::interval(Duration::from_secs(5)); loop { match client.get(&url).send().await { Ok(resp) => { println!("Successfully got a response from HTTP: {resp:?}"); return; } Err(e) => { println!("Waiting for HTTP server to be up: {e}"); } } interval.tick().await; } }; let capped_check = tokio::time::timeout(Duration::from_secs(100), try_http_connect); match capped_check.await { Ok(_) => { println!("Successfully started {self}"); *ready = ServerState::Ready; } Err(e) => { // tell others that this server had some problem *ready = ServerState::Error; std::mem::drop(ready); panic!("Server was not ready in required time: {e}"); } } // Onboard, if requested. if initial_config == InitialConfig::Onboarded { let client = influxdb2_client::Client::new(&self.http_base, ""); let response = client .onboarding( ADMIN_TEST_USER, ADMIN_TEST_ORG, ADMIN_TEST_BUCKET, Some(ADMIN_TEST_PASSWORD.to_string()), Some(0), None, ) .await; match response { Ok(onboarding) => { let token = onboarding .auth .expect("Onboarding should have returned auth info") .token .expect("Onboarding auth should have returned a token"); self.admin_token = Some(token); } Err(e) => { *ready = ServerState::Error; std::mem::drop(ready); panic!("Could not onboard: {e}"); } } } } } impl std::fmt::Display for TestServer { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { write!(f, "TestServer (http api: {})", self.http_base) } } impl Drop for TestServer { fn drop(&mut self) { self.server_process .kill() .expect("Should have been able to kill the test server"); if let Some(docker_name) = &self.docker_name { Command::new("docker") .arg("rm") .arg("--force") .arg(docker_name) .stdout(Stdio::null()) .status() .expect("killing of docker process"); } } }
// 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 super::super::qlib::linux::futex::*; use super::super::kernel::futex::*; use super::super::task::*; use super::super::threadmgr::thread::*; impl Thread { pub fn ExitRobustList(&self, task: &Task) { let addr = { let mut t = self.lock(); let ret = t.robust_list_head; t.robust_list_head = 0; ret }; if addr == 0 { return; } let rl : RobustListHead = match task.CopyInObj(addr) { Err(_) => return, Ok(p) => p, }; let mut next = rl.List; let mut done = 0; let mut pendingLockAddr = 0; if rl.ListOpPending != 0 { pendingLockAddr = rl.ListOpPending + rl.FutexOffset; } // Wake up normal elements. while next != addr { // We traverse to the next element of the list before we // actually wake anything. This prevents the race where waking // this futex causes a modification of the list. let thisLockAddr = (next as i64 + rl.FutexOffset as i64) as u64; // Try to decode the next element in the list before waking the // current futex. But don't check the error until after we've // woken the current futex. Linux does it in this order too next = match task.CopyInObj(next) { Err(_) => { if thisLockAddr != pendingLockAddr { self.WakeRobustListOne(task, thisLockAddr) }; // ignore error return; } Ok(next) => { if thisLockAddr != pendingLockAddr { self.WakeRobustListOne(task, thisLockAddr) }; next } }; // This is a user structure, so it could be a massive list, or // even contain a loop if they are trying to mess with us. We // cap traversal to prevent that. done += 1; if done >= ROBUST_LIST_LIMIT { break; } } // Is there a pending entry to wake? if pendingLockAddr != 0 { self.WakeRobustListOne(task, pendingLockAddr) } } // wakeRobustListOne wakes a single futex from the robust list. pub fn WakeRobustListOne(&self, task: &Task, addr: u64) { // Bit 0 in address signals PI futex. let pi = addr & 1 == 1; let addr = addr & !1; // Load the futex. let mut f = match task.LoadU32(addr) { // if Can't read this single value? Ignore the problem. // We can wake the other futexes in the list. Err(_) => return, Ok(f) => f, }; let tid = self.ThreadID() as u32; loop { // Is this held by someone else? if f & FUTEX_TID_MASK != tid { return } // This thread is dying and it's holding this futex. We need to // set the owner died bit and wake up any waiters. let newF = (f & FUTEX_WAITERS) | FUTEX_OWNER_DIED; let curF = match task.CompareAndSwapU32(addr, f, newF) { // if Can't read this single value? Ignore the problem. // We can wake the other futexes in the list. Err(_) => return, Ok(v) => v, }; if curF != f { f = curF; continue; } // Wake waiters if there are any. if f & FUTEX_WAITERS != 0 { let private = f & FUTEX_WAITERS != 0; if pi { task.futexMgr.UnlockPI(task, addr, tid, private).ok(); return } task.futexMgr.Wake(task, addr, private, FUTEX_BITSET_MATCH_ANY, 1).ok(); } return; } } }
extern crate rustcalc; #[test] fn simple_addition() { let input = "2+2"; match rustcalc::calc(input) { Ok(x) => assert_eq!(4f64, x), _ => assert!(false) } } #[test] fn complex_addition() { let input = "2+ 3 + (-8)"; match rustcalc::calc(input) { Ok(x) => assert_eq!(-3f64, x), _ => assert!(false) } } #[test] fn simple_subtraction() { let input = "3-2"; match rustcalc::calc(input) { Ok(x) => assert_eq!(1f64, x), _ => assert!(false) } } #[test] fn complex_subtraction() { let input = "3--2"; match rustcalc::calc(input) { Ok(x) => assert_eq!(5f64, x), _ => assert!(false) } } #[test] fn simple_multiplication() { let input = "2*2"; match rustcalc::calc(input) { Ok(x) => assert_eq!(4f64, x), _ => assert!(false) } } #[test] fn complex_multiplication() { let input = "2*-2*6"; match rustcalc::calc(input) { Ok(x) => assert_eq!(-24f64, x), _ => assert!(false) } } #[test] fn simple_division() { let input = "4/2"; match rustcalc::calc(input) { Ok(x) => assert_eq!(2f64, x), _ => assert!(false) } } #[test] fn complex_division() { let input = "4/2/-1"; match rustcalc::calc(input) { Ok(x) => assert_eq!(-2f64, x), _ => assert!(false) } } #[test] fn simple_exponentiation() { let input = "2^4"; match rustcalc::calc(input) { Ok(x) => assert_eq!(16f64, x), _ => assert!(false) } } #[test] fn complex_exponentiation() { let input = "2^2^(4/2)"; match rustcalc::calc(input) { Ok(x) => assert_eq!(16f64, x), _ => assert!(false) } } #[test] fn integration_test() { let input = "2 - 5 + 323948234 / 2 ^ (1 * 2)"; match rustcalc::calc(input) { Ok(x) => assert_eq!(-80987061.5, x), _ => assert!(false) } }
use winapi::um::winnt::HANDLE; use winapi::um::winuser::IMAGE_ICON; use crate::win32::resources_helper as rh; use crate::{OemImage, OemIcon, NwgError}; use std::ptr; #[cfg(feature = "embed-resource")] use super::EmbedResource; /** A wrapper over a icon file (*.ico) Windows icons are a legacy thing and should only be used when winapi forces you to use them (ex: when setting a window icon). The `Bitmap` object of NWG not only supports transparency if "image-decoder" is enabled but it can also be create from multiple different sources (including ".ico" files). To display a icon in an application, see the `ImageFrame` control. Note: Loading an icon from binary source (source_bin) REQUIRES the "image-decoder" feature. **Builder parameters:** * `source_file`: The source of the icon if it is a file. * `source_bin`: The source of the icon if it is a binary blob. For example using `include_bytes!("my_icon.ico")`. * `source_system`: The source of the icon if it is a system resource (see OemIcon) * `source_embed`: The source of the icon if it is stored in an embedded file * `source_embed_id`: The number identifier of the icon in the embedded file * `source_embed_str`: The string identifier of the icon in the embedded file * `size`: Optional. Resize the image to this size. * `strict`: Use a system placeholder instead of panicking if the image source do no exists. Example: ```rust use native_windows_gui as nwg; fn load_icon() -> nwg::Icon { nwg::Icon::from_file("hello.ico", true).unwrap() } fn load_icon_builder() -> nwg::Icon { let mut icon = nwg::Icon::default(); nwg::Icon::builder() .source_file(Some("hello.ico")) .strict(true) .build(&mut icon); icon } */ #[allow(unused)] pub struct Icon { pub handle: HANDLE, pub(crate) owned: bool } impl Icon { pub fn builder<'a>() -> IconBuilder<'a> { IconBuilder { source_text: None, source_bin: None, source_system: None, #[cfg(feature = "embed-resource")] source_embed: None, #[cfg(feature = "embed-resource")] source_embed_id: 0, #[cfg(feature = "embed-resource")] source_embed_str: None, size: None, strict: false } } /** Single line helper function over the icon builder api. Use system resources. */ pub fn from_system(sys_icon: OemIcon) -> Icon { let mut icon = Self::default(); // Default icon creation cannot fail Self::builder() .source_system(Some(sys_icon)) .build(&mut icon) .unwrap(); icon } /** Single line helper function over the icon builder api. Use a file resource. */ pub fn from_file(path: &str, strict: bool) -> Result<Icon, NwgError> { let mut icon = Icon::default(); Icon::builder() .source_file(Some(path)) .strict(strict) .build(&mut icon)?; Ok(icon) } /** Single line helper function over the icon builder api. Use a binary resource. */ pub fn from_bin(bin: &[u8]) -> Result<Icon, NwgError> { let mut icon = Icon::default(); Icon::builder() .source_bin(Some(bin)) .build(&mut icon)?; Ok(icon) } /** Single line helper function over the icon builder api. Use an embedded resource. Either `embed_id` or `embed_str` must be defined, not both. Requires the `embed-resource` feature. */ #[cfg(feature = "embed-resource")] pub fn from_embed(embed: &EmbedResource, embed_id: Option<usize>, embed_str: Option<&str>) -> Result<Icon, NwgError> { let mut icon = Icon::default(); Icon::builder() .source_embed(Some(embed)) .source_embed_id(embed_id.unwrap_or(0)) .source_embed_str(embed_str) .build(&mut icon)?; Ok(icon) } } pub struct IconBuilder<'a> { source_text: Option<&'a str>, source_bin: Option<&'a [u8]>, source_system: Option<OemIcon>, #[cfg(feature = "embed-resource")] source_embed: Option<&'a EmbedResource>, #[cfg(feature = "embed-resource")] source_embed_id: usize, #[cfg(feature = "embed-resource")] source_embed_str: Option<&'a str>, size: Option<(u32, u32)>, strict: bool, } impl<'a> IconBuilder<'a> { pub fn source_file(mut self, t: Option<&'a str>) -> IconBuilder<'a> { self.source_text = t; self } pub fn source_bin(mut self, t: Option<&'a [u8]>) -> IconBuilder<'a> { self.source_bin = t; self } pub fn source_system(mut self, t: Option<OemIcon>) -> IconBuilder<'a> { self.source_system = t; self } #[cfg(feature = "embed-resource")] pub fn source_embed(mut self, em: Option<&'a EmbedResource>) -> IconBuilder<'a> { self.source_embed = em; self } #[cfg(feature = "embed-resource")] pub fn source_embed_id(mut self, id: usize) -> IconBuilder<'a> { self.source_embed_id = id; self } #[cfg(feature = "embed-resource")] pub fn source_embed_str(mut self, id: Option<&'a str>) -> IconBuilder<'a> { self.source_embed_str = id; self } pub fn size(mut self, s: Option<(u32, u32)>) -> IconBuilder<'a> { self.size = s; self } pub fn strict(mut self, s: bool) -> IconBuilder<'a> { self.strict = s; self } pub fn build(self, b: &mut Icon) -> Result<(), NwgError> { if let Some(src) = self.source_text { let handle = unsafe { rh::build_image(src, self.size, self.strict, IMAGE_ICON)? }; *b = Icon { handle, owned: true }; } else if let Some(src) = self.source_system { let handle = unsafe { rh::build_oem_image(OemImage::Icon(src), self.size)? }; *b = Icon { handle, owned: true }; } else if let Some(src) = self.source_bin { let handle = unsafe { rh::icon_from_memory(src, self.strict, self.size)? }; *b = Icon { handle, owned: true }; } else { #[cfg(feature = "embed-resource")] fn build_embed(builder: IconBuilder) -> Result<Icon, NwgError> { match builder.source_embed { Some(embed) => { match builder.source_embed_str { Some(src) => embed.icon_str(src, builder.size) .ok_or_else(|| NwgError::resource_create(format!("No icon in embed resource identified by {}", src))), None => embed.icon(builder.source_embed_id, builder.size) .ok_or_else(|| NwgError::resource_create(format!("No icon in embed resource identified by {}", builder.source_embed_id))) } }, None => Err(NwgError::resource_create("No source provided for Icon")) } } #[cfg(not(feature = "embed-resource"))] fn build_embed(_builder: IconBuilder) -> Result<Icon, NwgError> { Err(NwgError::resource_create("No source provided for Icon")) } *b = build_embed(self)?; } Ok(()) } } impl Default for Icon { fn default() -> Icon { Icon { handle: ptr::null_mut(), owned: false } } } impl Drop for Icon { fn drop(&mut self) { if self.owned && !self.handle.is_null() { rh::destroy_icon(self.handle); } } } impl PartialEq for Icon { fn eq(&self, other: &Self) -> bool { self.handle == other.handle } }
pub mod common; pub mod dtos; pub mod pattern_queue; pub mod patterns; pub mod reply_to; pub mod utils;
use super::{Read, ReadError, Write, WriteError}; use alloc::vec::Vec; use core::ops::Deref; /// A stream of bytes pub struct DataStream { /// TODO docs bytes: Vec<u8>, /// TODO docs pos: usize, } impl DataStream { /// Read something from the stream /// /// # Errors /// /// Will return `Err` if there was a problem reading the data. #[inline] pub fn read<T: Read>(&mut self) -> Result<T, ReadError> { T::read(&self.bytes, &mut self.pos) } /// Write something to the stream /// /// # Errors /// /// Will return `Err` if there was a problem writing the data. #[inline] pub fn write<T: Write>(&mut self, thing: T) -> Result<(), WriteError> { thing.write(&mut self.bytes, &mut self.pos) } /// Gets the remaining number of bytes #[inline] #[must_use] pub fn as_bytes(&self) -> &[u8] { &self.bytes } /// Gets remaining bytes as slice #[inline] #[must_use] pub fn as_remaining_bytes(&self) -> Option<&[u8]> { self.bytes.get(self.pos..) } /// Resets the data stream position #[inline] pub fn reset(&mut self) { self.pos = 0; } /// Get the current position #[inline] #[must_use] pub const fn position(&self) -> usize { self.pos } /// Gets the remaining number of bytes #[inline] #[must_use] pub fn remaining(&self) -> usize { self.bytes.len() - self.pos } } impl From<Vec<u8>> for DataStream { #[must_use] fn from(bytes: Vec<u8>) -> Self { Self { bytes, pos: 0 } } } impl From<&[u8]> for DataStream { #[must_use] fn from(bytes: &[u8]) -> Self { Self { bytes: bytes.to_vec(), pos: 0, } } } impl Deref for DataStream { type Target = [u8]; #[must_use] fn deref(&self) -> &Self::Target { self.as_bytes() } } impl AsRef<[u8]> for DataStream { fn as_ref(&self) -> &[u8] { self.as_bytes() } } #[cfg(test)] mod tests { use super::*; use crate::{n, AccountName, Name}; #[test] fn read_write() { let account = AccountName::from(n!("eosio.token")); let name = Name::from(n!("alice")); let mut ds1 = DataStream::from(vec![0; 16]); assert_eq!(ds1.position(), 0); assert_eq!(ds1.remaining(), 16); ds1.write(account).expect("failed to write account"); assert_eq!(ds1.position(), 8); assert_eq!(ds1.remaining(), 8); assert_eq!( ds1.as_remaining_bytes() .expect("failed to get remaining bytes") .len(), 8 ); ds1.write(name).expect("failed to write name"); assert_eq!(ds1.position(), 16); assert_eq!(ds1.remaining(), 0); let bytes = ds1.as_bytes(); let mut ds2 = DataStream::from(bytes); assert_eq!(ds2.position(), 0); assert_eq!(ds2.remaining(), 16); let account2 = ds2.read::<AccountName>().expect("failed to read account"); assert_eq!(ds2.position(), 8); assert_eq!(ds2.remaining(), 8); let name2 = ds2.read::<Name>().expect("failed to read name"); assert_eq!(ds2.position(), 16); assert_eq!(ds2.remaining(), 0); assert_eq!(account, account2); assert_eq!(name, name2); } }
#[allow(unused_imports)] use proconio::marker::{Bytes, Chars}; use proconio::{fastout, input}; #[fastout] fn main() { input! { n: usize, s: [String; n], } let mut ac = 0; let mut wa = 0; let mut tle = 0; let mut re = 0; for i in 0..n { if &s[i] == "AC" { ac += 1; } if &s[i] == "WA" { wa += 1; } if &s[i] == "TLE" { tle += 1; } if &s[i] == "RE" { re += 1; } } println!("AC x {}", ac); println!("WA x {}", wa); println!("TLE x {}", tle); println!("RE x {}", re); }
use std::{fmt::Display, sync::Arc}; use data_types::{CompactionLevel, ParquetFile}; use observability_deps::tracing::info; use parquet_file::ParquetFilePath; use uuid::Uuid; use crate::{ file_classification::{CompactReason, FileToSplit, FilesToSplitOrCompact, SplitReason}, partition_info::PartitionInfo, plan_ir::PlanIR, }; use super::IRPlanner; #[derive(Debug)] pub struct LoggingIRPlannerWrapper<T> where T: IRPlanner, { inner: T, } impl<T> LoggingIRPlannerWrapper<T> where T: IRPlanner, { pub fn new(inner: T) -> Self { Self { inner } } } impl<T> Display for LoggingIRPlannerWrapper<T> where T: IRPlanner, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "logging({})", self.inner) } } impl<T> IRPlanner for LoggingIRPlannerWrapper<T> where T: IRPlanner, { fn create_plans( &self, partition: Arc<PartitionInfo>, target_level: CompactionLevel, split_or_compact: FilesToSplitOrCompact, object_store_ids: Vec<Uuid>, object_store_paths: Vec<ParquetFilePath>, ) -> Vec<PlanIR> { self.inner.create_plans( partition, target_level, split_or_compact, object_store_ids, object_store_paths, ) } fn compact_plan( &self, files: Vec<ParquetFile>, object_store_paths: Vec<ParquetFilePath>, object_store_ids: Vec<Uuid>, reason: CompactReason, partition: Arc<PartitionInfo>, compaction_level: CompactionLevel, ) -> PlanIR { let partition_id = partition.partition_id; let n_input_files = files.len(); let column_count = partition.column_count(); let input_file_size_bytes = files.iter().map(|f| f.file_size_bytes).sum::<i64>(); let plan = self.inner.compact_plan( files, object_store_paths, object_store_ids, reason, partition, compaction_level, ); info!( partition_id = partition_id.get(), n_input_files, column_count, input_file_size_bytes, n_output_files = plan.n_output_files(), compaction_level = compaction_level as i16, ?reason, %plan, "created IR compact plan", ); plan } fn split_plan( &self, file_to_split: FileToSplit, object_store_path: ParquetFilePath, object_store_id: Uuid, reason: SplitReason, partition: Arc<PartitionInfo>, compaction_level: CompactionLevel, ) -> PlanIR { let partition_id = partition.partition_id; let n_input_files = 1; let column_count = partition.column_count(); let input_file_size_bytes = file_to_split.file.file_size_bytes; let plan = self.inner.split_plan( file_to_split, object_store_path, object_store_id, reason, partition, compaction_level, ); info!( partition_id = partition_id.get(), n_input_files, column_count, input_file_size_bytes, n_output_files = plan.n_output_files(), compaction_level = compaction_level as i16, ?reason, %plan, "created IR split plan", ); plan } }
use ggez::{graphics, Context, GameResult, nalgebra as na}; use ggez::graphics::{DrawMode}; use ggez::event::EventHandler; pub struct MyGame { // Your state here... n: f64, d: f64 } impl MyGame { pub fn new(_ctx: &mut Context, n: f64, d: f64) -> MyGame { // Load/create resources such as images here. MyGame { // ... n, d } } } impl EventHandler for MyGame { fn update(&mut self, _ctx: &mut Context) -> GameResult<()> { // Update code here... self.d += 0.03; self.n += 0.01; Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { graphics::clear(ctx, graphics::WHITE); // Draw code here... let window = graphics::screen_coordinates(ctx); let mut points = Vec::new(); let mut i = 0.0; while i < std::f64::consts::PI * 2.0{ let k = i * self.d; let r = 150.0 * (self.n*k).sin(); let x = r * k.cos(); let y = r * k.sin(); points.push(na::Point2::new(x as f32 , y as f32)); i += std::f64::consts::PI / 180.0; } let mut route_points = Vec::new(); let mut j = 0.0; while j < std::f64::consts::PI * 2.0{ let k = j; let r = 150.0 * (self.n*k).sin(); let x = r * k.cos(); let y = r * k.sin(); route_points.push(na::Point2::new(x as f32 , y as f32)); j += std::f64::consts::PI / 180.0; } let circle = graphics::Mesh::new_polygon(ctx,DrawMode::stroke(1.0), &points, graphics::Color::new(0.0, 0.0, 255.0, 1.0))?; let route = graphics::Mesh::new_polygon(ctx,DrawMode::stroke(2.5), &route_points, graphics::Color::new(255.0, 0.0, 255.0, 1.0))?; graphics::draw(ctx, &circle, (na::Point2::new(window.w / 2.0, window.h / 2.0),))?; graphics::draw(ctx, &route, (na::Point2::new(window.w / 2.0, window.h / 2.0),))?; graphics::present(ctx) } }
#![crate_name = "r6"] //! r6.rs is an attempt to implement R6RS Scheme in Rust language #![feature(plugin)] #![feature(slicing_syntax)] #![feature(box_syntax)] //TODO: Allow unstable items until Rust hits 1.0 #![allow(unstable)] #[plugin] extern crate phf_mac; extern crate phf; extern crate unicode; #[macro_use] extern crate log; macro_rules! list{ ($($x:expr),*) => ( vec![$($x),*].into_iter().collect() ) } macro_rules! sym{ ($e:expr) => ( Datum::Sym(Cow::Borrowed($e)) ) } macro_rules! num{ ($e:expr) => ( Datum::Num($e) ) } macro_rules! nil{ () => ( Datum::Nil ) } /// Error values returned from parser, compiler or runtime pub mod error; /// Basic datum types pub mod datum; pub mod parser; pub mod lexer; /// Virtual machine running the bytecode pub mod runtime; /// Primitive functions pub mod primitive; /// Compiles datum into a bytecode pub mod compiler; /// R6RS `base` library pub mod base;
//Floyd cycle delection algorithm enum Working { Process, Stop } pub struct Floyd{ func: fn(&f32) -> f32, xstart: f32, } impl Floyd { pub fn new(xstart:f32, func: fn(f32) -> f32) -> Floyd { Floyd { func:&func, xstart:xstart, } } /*fn start(&self) -> (i32,i32) { let mut tortoise = self.func(self.xstart); let mut hare = self.func(self.func(self.xstart)); let (tortoise, hare) = self.fit(&tortoise, &hare); let mu = self.find_position(tortoise, hare, 0); let lam = self.find_length(tortoise, hare, 1); return (mu, lam); }*/ pub fn fit(&self, tortoise: f32, hare: f32) -> (f32,f32) { let v = self.xstart; match tortoise == hare { True => (tortoise, hare), _ => self.fit(&self.func(tortoise), &self.func(self.func(hare))), } } /*fn find_position(&self, tortoise: f32, hare: f32, mu: f32) ->(f32,f32,f32) { match tortoise != hare { True => (tortoise, hare, mu), _ => self.find_potition(self.func(tortoise), self.func(hare), mu+1), } } fn find_length(&self, tortoise: f32, hare: f32, lam: f32) -> f32 { match tortoise != hare { True => lam, _ => self.find_length(tortoise, self.func(hare), lam+1), } }*/ } #[test] fn it_works() { let mut value = Floyd::new(1, |x:f32| -> f32 { x + 0.47 }); }
// Copyright 2017 Amagicom AB. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Bindings to [`SCPreferences`]. //! //! See the examples directory for examples how to use this module. //! //! [`SCPreferences`]: https://developer.apple.com/documentation/systemconfiguration/scpreferences-ft8 use crate::sys::preferences::{SCPreferencesCreate, SCPreferencesGetTypeID, SCPreferencesRef}; use core_foundation::base::{CFAllocator, TCFType}; use core_foundation::string::CFString; use std::ptr; declare_TCFType! { /// The handle to an open preferences session for accessing system configuration preferences. SCPreferences, SCPreferencesRef } impl_TCFType!(SCPreferences, SCPreferencesRef, SCPreferencesGetTypeID); impl SCPreferences { /// Initiates access to the default system preferences using the default allocator. pub fn default(calling_process_name: &CFString) -> Self { Self::new(None, calling_process_name, None) } /// Initiates access to the given (`prefs_id`) group of configuration preferences using the /// default allocator. To access the default system preferences, use the [`default`] /// constructor. /// /// [`default`]: #method.default pub fn group(calling_process_name: &CFString, prefs_id: &CFString) -> Self { Self::new(None, calling_process_name, Some(prefs_id)) } /// Initiates access to the per-system set of configuration preferences with a given /// allocator and preference group to access. See the underlying [SCPreferencesCreate] function /// documentation for details. Use the helper constructors [`default`] and [`group`] to easier /// create an instance using the default allocator. /// /// [SCPreferencesCreate]: https://developer.apple.com/documentation/systemconfiguration/1516807-scpreferencescreate?language=objc /// [`default`]: #method.default /// [`group`]: #method.group pub fn new( allocator: Option<&CFAllocator>, calling_process_name: &CFString, prefs_id: Option<&CFString>, ) -> Self { let allocator_ref = match allocator { Some(allocator) => allocator.as_concrete_TypeRef(), None => ptr::null(), }; let prefs_id_ref = match prefs_id { Some(prefs_id) => prefs_id.as_concrete_TypeRef(), None => ptr::null(), }; unsafe { SCPreferences::wrap_under_create_rule(SCPreferencesCreate( allocator_ref, calling_process_name.as_concrete_TypeRef(), prefs_id_ref, )) } } } #[cfg(test)] mod tests { use super::*; #[test] fn retain_count() { let preferences = SCPreferences::default(&CFString::new("test")); assert_eq!(preferences.retain_count(), 1); } }
// Copyright 2016 `multipart` Crate Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! Client- and server-side abstractions for HTTP `multipart/form-data` requests. //! //! ### Features: //! This documentation is built with all features enabled. //! //! * `client`: The client-side abstractions for generating multipart requests. //! //! * `server`: The server-side abstractions for parsing multipart requests. //! //! * `mock`: Provides mock implementations of core `client` and `server` traits for debugging //! or non-standard use. //! //! * `hyper`: Integration with the [Hyper](https://crates.io/crates/hyper) HTTP library //! for client and/or server depending on which other feature flags are set. //! //! * `iron`: Integration with the [Iron](http://crates.io/crates/iron) web application //! framework. See the [`server::iron`](server/iron/index.html) module for more information. //! //! * `nickel` (returning in 0.14!): Integration with the [Nickel](https://crates.io/crates/nickel) //! web application framework. See the [`server::nickel`](server/nickel/index.html) module for more //! information. //! //! * `tiny_http`: Integration with the [`tiny_http`](https://crates.io/crates/tiny_http) //! crate. See the [`server::tiny_http`](server/tiny_http/index.html) module for more information. //! //! ### Note: Work in Progress //! I have left a number of Request-for-Comments (RFC) questions on various APIs and other places //! in the code as there are some cases where I'm not sure what the desirable behavior is. //! //! I have opened an issue as a place to collect responses and discussions for these questions //! [on Github](https://github.com/abonander/multipart/issues/96). Please quote the RFC-statement //! (and/or link to its source line) and provide your feedback there. #![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy", deny(clippy))] #![cfg_attr(feature = "bench", feature(test))] #![deny(missing_docs)] #[macro_use] extern crate log; #[macro_use] extern crate mime; extern crate mime_guess; extern crate rand; extern crate tempdir; #[cfg(feature = "quick-error")] #[macro_use] extern crate quick_error; #[cfg(feature = "server")] extern crate safemem; #[cfg(feature = "hyper")] extern crate hyper; #[cfg(feature = "iron")] extern crate iron; #[cfg(feature = "tiny_http")] extern crate tiny_http; #[cfg(test)] extern crate env_logger; #[cfg(any(feature = "mock", test))] pub mod mock; use rand::Rng; /// Chain a series of results together, with or without previous results. /// /// ``` /// #[macro_use] extern crate multipart; /// /// fn try_add_one(val: u32) -> Result<u32, u32> { /// if val < 5 { /// Ok(val + 1) /// } else { /// Err(val) /// } /// } /// /// fn main() { /// let res = chain_result! { /// try_add_one(1), /// prev -> try_add_one(prev), /// prev -> try_add_one(prev), /// prev -> try_add_one(prev) /// }; /// /// println!("{:?}", res); /// } /// /// ``` #[macro_export] macro_rules! chain_result { ($first_expr:expr, $($try_expr:expr),*) => ( $first_expr $(.and_then(|_| $try_expr))* ); ($first_expr:expr, $($($arg:ident),+ -> $try_expr:expr),*) => ( $first_expr $(.and_then(|$($arg),+| $try_expr))* ); } #[cfg(feature = "client")] pub mod client; #[cfg(feature = "server")] pub mod server; #[cfg(all(test, feature = "client", feature = "server"))] mod local_test; fn random_alphanumeric(len: usize) -> String { rand::thread_rng().gen_ascii_chars().take(len).collect() } #[cfg(test)] fn init_log() { let _ = env_logger::try_init(); }
pub type IOpcCertificateEnumerator = *mut ::core::ffi::c_void; pub type IOpcCertificateSet = *mut ::core::ffi::c_void; pub type IOpcDigitalSignature = *mut ::core::ffi::c_void; pub type IOpcDigitalSignatureEnumerator = *mut ::core::ffi::c_void; pub type IOpcDigitalSignatureManager = *mut ::core::ffi::c_void; pub type IOpcFactory = *mut ::core::ffi::c_void; pub type IOpcPackage = *mut ::core::ffi::c_void; pub type IOpcPart = *mut ::core::ffi::c_void; pub type IOpcPartEnumerator = *mut ::core::ffi::c_void; pub type IOpcPartSet = *mut ::core::ffi::c_void; pub type IOpcPartUri = *mut ::core::ffi::c_void; pub type IOpcRelationship = *mut ::core::ffi::c_void; pub type IOpcRelationshipEnumerator = *mut ::core::ffi::c_void; pub type IOpcRelationshipSelector = *mut ::core::ffi::c_void; pub type IOpcRelationshipSelectorEnumerator = *mut ::core::ffi::c_void; pub type IOpcRelationshipSelectorSet = *mut ::core::ffi::c_void; pub type IOpcRelationshipSet = *mut ::core::ffi::c_void; pub type IOpcSignatureCustomObject = *mut ::core::ffi::c_void; pub type IOpcSignatureCustomObjectEnumerator = *mut ::core::ffi::c_void; pub type IOpcSignatureCustomObjectSet = *mut ::core::ffi::c_void; pub type IOpcSignaturePartReference = *mut ::core::ffi::c_void; pub type IOpcSignaturePartReferenceEnumerator = *mut ::core::ffi::c_void; pub type IOpcSignaturePartReferenceSet = *mut ::core::ffi::c_void; pub type IOpcSignatureReference = *mut ::core::ffi::c_void; pub type IOpcSignatureReferenceEnumerator = *mut ::core::ffi::c_void; pub type IOpcSignatureReferenceSet = *mut ::core::ffi::c_void; pub type IOpcSignatureRelationshipReference = *mut ::core::ffi::c_void; pub type IOpcSignatureRelationshipReferenceEnumerator = *mut ::core::ffi::c_void; pub type IOpcSignatureRelationshipReferenceSet = *mut ::core::ffi::c_void; pub type IOpcSigningOptions = *mut ::core::ffi::c_void; pub type IOpcUri = *mut ::core::ffi::c_void; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_CONFLICTING_SETTINGS: ::windows_sys::core::HRESULT = -2142175212i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_COULD_NOT_RECOVER: ::windows_sys::core::HRESULT = -2142175154i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_DEFAULT_DIGEST_METHOD_NOT_SET: ::windows_sys::core::HRESULT = -2142175161i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_DIGEST_VALUE_ERROR: ::windows_sys::core::HRESULT = -2142175206i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_DUPLICATE_PACKAGE_OBJECT_REFERENCES: ::windows_sys::core::HRESULT = -2142175187i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_DUPLICATE_SIGNATURE_ORIGIN_RELATIONSHIP: ::windows_sys::core::HRESULT = -2142175205i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_DUPLICATE_SIGNATURE_PROPERTY_ELEMENT: ::windows_sys::core::HRESULT = -2142175192i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_EXTERNAL_SIGNATURE: ::windows_sys::core::HRESULT = -2142175202i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_EXTERNAL_SIGNATURE_REFERENCE: ::windows_sys::core::HRESULT = -2142175185i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_INVALID_CANONICALIZATION_METHOD: ::windows_sys::core::HRESULT = -2142175198i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_INVALID_CERTIFICATE_RELATIONSHIP: ::windows_sys::core::HRESULT = -2142175203i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_INVALID_OPC_SIGNATURE_TIME_FORMAT: ::windows_sys::core::HRESULT = -2142175196i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_INVALID_RELATIONSHIPS_SIGNING_OPTION: ::windows_sys::core::HRESULT = -2142175197i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_INVALID_RELATIONSHIP_TRANSFORM_XML: ::windows_sys::core::HRESULT = -2142175199i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_INVALID_SIGNATURE_COUNT: ::windows_sys::core::HRESULT = -2142175189i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_INVALID_SIGNATURE_ORIGIN_RELATIONSHIP: ::windows_sys::core::HRESULT = -2142175204i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_INVALID_SIGNATURE_XML: ::windows_sys::core::HRESULT = -2142175190i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_MISSING_CANONICALIZATION_TRANSFORM: ::windows_sys::core::HRESULT = -2142175182i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_MISSING_CERTIFICATE_PART: ::windows_sys::core::HRESULT = -2142175146i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_MISSING_PACKAGE_OBJECT_REFERENCE: ::windows_sys::core::HRESULT = -2142175186i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_MISSING_SIGNATURE_ALGORITHM: ::windows_sys::core::HRESULT = -2142175188i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_MISSING_SIGNATURE_ORIGIN_PART: ::windows_sys::core::HRESULT = -2142175201i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_MISSING_SIGNATURE_PART: ::windows_sys::core::HRESULT = -2142175200i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_MISSING_SIGNATURE_PROPERTIES_ELEMENT: ::windows_sys::core::HRESULT = -2142175194i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_MISSING_SIGNATURE_PROPERTY_ELEMENT: ::windows_sys::core::HRESULT = -2142175193i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_MISSING_SIGNATURE_TIME_PROPERTY: ::windows_sys::core::HRESULT = -2142175191i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_MULTIPLE_RELATIONSHIP_TRANSFORMS: ::windows_sys::core::HRESULT = -2142175183i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_PACKAGE_REFERENCE_URI_RESERVED: ::windows_sys::core::HRESULT = -2142175195i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_REFERENCE_MISSING_CONTENT_TYPE: ::windows_sys::core::HRESULT = -2142175184i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_SIGNATURE_CORRUPT: ::windows_sys::core::HRESULT = -2142175207i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_SIGNATURE_METHOD_NOT_SET: ::windows_sys::core::HRESULT = -2142175162i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_SIGNATURE_ORIGIN_EXISTS: ::windows_sys::core::HRESULT = -2142175148i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_SIGNATURE_PROPERTY_MISSING_TARGET: ::windows_sys::core::HRESULT = -2142175163i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_SIGNATURE_REFERENCE_MISSING_URI: ::windows_sys::core::HRESULT = -2142175165i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DS_UNSIGNED_PACKAGE: ::windows_sys::core::HRESULT = -2142175147i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DUPLICATE_DEFAULT_EXTENSION: ::windows_sys::core::HRESULT = -2142175217i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DUPLICATE_OVERRIDE_PART: ::windows_sys::core::HRESULT = -2142175219i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DUPLICATE_PART: ::windows_sys::core::HRESULT = -2142175221i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DUPLICATE_PIECE: ::windows_sys::core::HRESULT = -2142175211i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_DUPLICATE_RELATIONSHIP: ::windows_sys::core::HRESULT = -2142175213i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ENUM_CANNOT_MOVE_NEXT: ::windows_sys::core::HRESULT = -2142175151i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ENUM_CANNOT_MOVE_PREVIOUS: ::windows_sys::core::HRESULT = -2142175150i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ENUM_COLLECTION_CHANGED: ::windows_sys::core::HRESULT = -2142175152i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ENUM_INVALID_POSITION: ::windows_sys::core::HRESULT = -2142175149i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_INVALID_CONTENT_TYPE: ::windows_sys::core::HRESULT = -2142175164i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_INVALID_CONTENT_TYPE_XML: ::windows_sys::core::HRESULT = -2142175226i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_INVALID_DEFAULT_EXTENSION: ::windows_sys::core::HRESULT = -2142175218i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_INVALID_OVERRIDE_PART_NAME: ::windows_sys::core::HRESULT = -2142175220i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_INVALID_PIECE: ::windows_sys::core::HRESULT = -2142175210i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_INVALID_RELATIONSHIP_ID: ::windows_sys::core::HRESULT = -2142175216i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_INVALID_RELATIONSHIP_TARGET: ::windows_sys::core::HRESULT = -2142175214i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_INVALID_RELATIONSHIP_TARGET_MODE: ::windows_sys::core::HRESULT = -2142175155i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_INVALID_RELATIONSHIP_TYPE: ::windows_sys::core::HRESULT = -2142175215i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_INVALID_RELS_XML: ::windows_sys::core::HRESULT = -2142175222i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_INVALID_XML_ENCODING: ::windows_sys::core::HRESULT = -2142175166i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_INCONSISTENT_PRESERVE_ATTRIBUTES: ::windows_sys::core::HRESULT = -2142175157i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_INCONSISTENT_PRESERVE_ELEMENTS: ::windows_sys::core::HRESULT = -2142175156i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_INCONSISTENT_PROCESS_CONTENT: ::windows_sys::core::HRESULT = -2142175158i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_INVALID_ATTRIBUTES_ON_IGNORABLE_ELEMENT: ::windows_sys::core::HRESULT = -2142175168i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_INVALID_ENUM_TYPE: ::windows_sys::core::HRESULT = -2142175172i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_INVALID_PREFIX_LIST: ::windows_sys::core::HRESULT = -2142175177i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_INVALID_QNAME_LIST: ::windows_sys::core::HRESULT = -2142175176i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_INVALID_XMLNS_ATTRIBUTE: ::windows_sys::core::HRESULT = -2142175167i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_MISSING_CHOICE: ::windows_sys::core::HRESULT = -2142175173i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_MISSING_REQUIRES_ATTR: ::windows_sys::core::HRESULT = -2142175179i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_MULTIPLE_FALLBACK_ELEMENTS: ::windows_sys::core::HRESULT = -2142175159i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_NESTED_ALTERNATE_CONTENT: ::windows_sys::core::HRESULT = -2142175175i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_UNEXPECTED_ATTR: ::windows_sys::core::HRESULT = -2142175178i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_UNEXPECTED_CHOICE: ::windows_sys::core::HRESULT = -2142175174i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_UNEXPECTED_ELEMENT: ::windows_sys::core::HRESULT = -2142175181i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_UNEXPECTED_REQUIRES_ATTR: ::windows_sys::core::HRESULT = -2142175180i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_UNKNOWN_NAMESPACE: ::windows_sys::core::HRESULT = -2142175170i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MC_UNKNOWN_PREFIX: ::windows_sys::core::HRESULT = -2142175169i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MISSING_CONTENT_TYPES: ::windows_sys::core::HRESULT = -2142175225i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_MISSING_PIECE: ::windows_sys::core::HRESULT = -2142175209i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_NONCONFORMING_CONTENT_TYPES_XML: ::windows_sys::core::HRESULT = -2142175224i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_NONCONFORMING_RELS_XML: ::windows_sys::core::HRESULT = -2142175223i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_NONCONFORMING_URI: ::windows_sys::core::HRESULT = -2142175231i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_NO_SUCH_PART: ::windows_sys::core::HRESULT = -2142175208i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_NO_SUCH_RELATIONSHIP: ::windows_sys::core::HRESULT = -2142175160i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_NO_SUCH_SETTINGS: ::windows_sys::core::HRESULT = -2142175145i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_PART_CANNOT_BE_DIRECTORY: ::windows_sys::core::HRESULT = -2142175228i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_RELATIONSHIP_URI_REQUIRED: ::windows_sys::core::HRESULT = -2142175229i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_RELATIVE_URI_REQUIRED: ::windows_sys::core::HRESULT = -2142175230i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_UNEXPECTED_CONTENT_TYPE: ::windows_sys::core::HRESULT = -2142175227i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_UNSUPPORTED_PACKAGE: ::windows_sys::core::HRESULT = -2142175153i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_CENTRAL_DIRECTORY_TOO_LARGE: ::windows_sys::core::HRESULT = -2142171127i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_COMMENT_TOO_LARGE: ::windows_sys::core::HRESULT = -2142171124i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_COMPRESSION_FAILED: ::windows_sys::core::HRESULT = -2142171133i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_CORRUPTED_ARCHIVE: ::windows_sys::core::HRESULT = -2142171134i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_DECOMPRESSION_FAILED: ::windows_sys::core::HRESULT = -2142171132i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_DUPLICATE_NAME: ::windows_sys::core::HRESULT = -2142171125i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_EXTRA_FIELDS_TOO_LARGE: ::windows_sys::core::HRESULT = -2142171123i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_FILE_HEADER_TOO_LARGE: ::windows_sys::core::HRESULT = -2142171122i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_INCONSISTENT_DIRECTORY: ::windows_sys::core::HRESULT = -2142171130i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_INCONSISTENT_FILEITEM: ::windows_sys::core::HRESULT = -2142171131i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_INCORRECT_DATA_SIZE: ::windows_sys::core::HRESULT = -2142171135i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_MISSING_DATA_DESCRIPTOR: ::windows_sys::core::HRESULT = -2142171129i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_MISSING_END_OF_CENTRAL_DIRECTORY: ::windows_sys::core::HRESULT = -2142171121i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_NAME_TOO_LARGE: ::windows_sys::core::HRESULT = -2142171126i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_REQUIRES_64_BIT: ::windows_sys::core::HRESULT = -2142171120i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_E_ZIP_UNSUPPORTEDARCHIVE: ::windows_sys::core::HRESULT = -2142171128i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OpcFactory: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x6b2d6ba0_9f3e_4f27_920b_313cc426a39e); #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub type OPC_CANONICALIZATION_METHOD = i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_CANONICALIZATION_NONE: OPC_CANONICALIZATION_METHOD = 0i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_CANONICALIZATION_C14N: OPC_CANONICALIZATION_METHOD = 1i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_CANONICALIZATION_C14N_WITH_COMMENTS: OPC_CANONICALIZATION_METHOD = 2i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub type OPC_CERTIFICATE_EMBEDDING_OPTION = i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_CERTIFICATE_IN_CERTIFICATE_PART: OPC_CERTIFICATE_EMBEDDING_OPTION = 0i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_CERTIFICATE_IN_SIGNATURE_PART: OPC_CERTIFICATE_EMBEDDING_OPTION = 1i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_CERTIFICATE_NOT_EMBEDDED: OPC_CERTIFICATE_EMBEDDING_OPTION = 2i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub type OPC_COMPRESSION_OPTIONS = i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_COMPRESSION_NONE: OPC_COMPRESSION_OPTIONS = -1i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_COMPRESSION_NORMAL: OPC_COMPRESSION_OPTIONS = 0i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_COMPRESSION_MAXIMUM: OPC_COMPRESSION_OPTIONS = 1i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_COMPRESSION_FAST: OPC_COMPRESSION_OPTIONS = 2i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_COMPRESSION_SUPERFAST: OPC_COMPRESSION_OPTIONS = 3i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub type OPC_READ_FLAGS = i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_READ_DEFAULT: OPC_READ_FLAGS = 0i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_VALIDATE_ON_LOAD: OPC_READ_FLAGS = 1i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_CACHE_ON_ACCESS: OPC_READ_FLAGS = 2i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub type OPC_RELATIONSHIPS_SIGNING_OPTION = i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_RELATIONSHIP_SIGN_USING_SELECTORS: OPC_RELATIONSHIPS_SIGNING_OPTION = 0i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_RELATIONSHIP_SIGN_PART: OPC_RELATIONSHIPS_SIGNING_OPTION = 1i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub type OPC_RELATIONSHIP_SELECTOR = i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_RELATIONSHIP_SELECT_BY_ID: OPC_RELATIONSHIP_SELECTOR = 0i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_RELATIONSHIP_SELECT_BY_TYPE: OPC_RELATIONSHIP_SELECTOR = 1i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub type OPC_SIGNATURE_TIME_FORMAT = i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_SIGNATURE_TIME_FORMAT_MILLISECONDS: OPC_SIGNATURE_TIME_FORMAT = 0i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_SIGNATURE_TIME_FORMAT_SECONDS: OPC_SIGNATURE_TIME_FORMAT = 1i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_SIGNATURE_TIME_FORMAT_MINUTES: OPC_SIGNATURE_TIME_FORMAT = 2i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_SIGNATURE_TIME_FORMAT_DAYS: OPC_SIGNATURE_TIME_FORMAT = 3i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_SIGNATURE_TIME_FORMAT_MONTHS: OPC_SIGNATURE_TIME_FORMAT = 4i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_SIGNATURE_TIME_FORMAT_YEARS: OPC_SIGNATURE_TIME_FORMAT = 5i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub type OPC_SIGNATURE_VALIDATION_RESULT = i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_SIGNATURE_VALID: OPC_SIGNATURE_VALIDATION_RESULT = 0i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_SIGNATURE_INVALID: OPC_SIGNATURE_VALIDATION_RESULT = -1i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub type OPC_STREAM_IO_MODE = i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_STREAM_IO_READ: OPC_STREAM_IO_MODE = 1i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_STREAM_IO_WRITE: OPC_STREAM_IO_MODE = 2i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub type OPC_URI_TARGET_MODE = i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_URI_TARGET_MODE_INTERNAL: OPC_URI_TARGET_MODE = 0i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_URI_TARGET_MODE_EXTERNAL: OPC_URI_TARGET_MODE = 1i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub type OPC_WRITE_FLAGS = i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_WRITE_DEFAULT: OPC_WRITE_FLAGS = 0i32; #[doc = "*Required features: `\"Win32_Storage_Packaging_Opc\"`*"] pub const OPC_WRITE_FORCE_ZIP32: OPC_WRITE_FLAGS = 1i32;
use super::Solution; // 420. Strong Password Checker impl Solution { #[allow(dead_code)] // 420. Strong Password Checker pub fn strong_password_checker(password: String) -> i32 { // let _ = (password.chars().count(), ()); // // Vec of chars, mutable? Then perform the edits, we only care about distance. // // Then calculate edit distance? // let length = password.chars().count(); // let length_ok = (6..=20).contains(&length); // let contains_lower = password.chars().any(|ch| ch.is_ascii_lowercase()); // let contains_upper = password.chars().any(|ch| ch.is_ascii_uppercase()); // let contains_number = password.chars().any(|ch| ch.is_numeric()); // let max_two_repeating = password // .chars() // .collect::<Vec<char>>() // .windows(3) // .all(|chs| chs[0] != chs[1] || chs[1] != chs[2]); let _password: Vec<char> = password.chars().collect(); 0 } // Helpers #[allow(dead_code)] pub fn is_strong_password(password: &str) -> bool { let password = String::from(password); let length = password.chars().count(); let length_ok = (6..=20).contains(&length); let contains_lower = password.chars().any(|ch| ch.is_ascii_lowercase()); let contains_upper = password.chars().any(|ch| ch.is_ascii_uppercase()); let contains_number = password.chars().any(|ch| ch.is_numeric()); let max_two_repeating = password .chars() .collect::<Vec<char>>() .windows(3) .all(|chs| chs[0] != chs[1] || chs[1] != chs[2]); // DeMorgen's this shit length_ok && contains_lower && contains_upper && contains_number && max_two_repeating } } // 493. Reverse Pairs impl Solution { #[allow(dead_code)] pub fn reverse_pairs(nums: Vec<i32>) -> i32 { (0..nums.len()) .map(|i| { ((i + 1)..nums.len()) .filter(|&j| match nums[j].checked_mul(2) { Some(n) => nums[i] > n, None => nums[j] < 0, }) .count() }) .sum::<usize>() as i32 } }
#![feature(core_intrinsics)] #![feature(convert)] //! A a low level NBT decoding library that maps NBT structures onto //! standard library containers. extern crate flate2; pub mod types; pub mod decode; pub mod encode; pub mod util; pub mod traits; pub use types::*; // Trait for encoding values to bytes trait Encodable { fn to_bytes(&self) -> Vec<u8>; } macro_rules! make_encodable { // Encode an integral by shifting by expr, from left to right ($t:ty, $($n:expr),+) => { impl Encodable for $t { fn to_bytes(&self) -> Vec<u8> { vec![ $( (*self >> $n) as u8),+ ] } } }; // Encode a value by transmuting it to another value and using that impl // i.e. transmute f32 to i32 -> i32.to_bytes() ($t:ty => $c:ty) => { impl Encodable for $t { fn to_bytes(&self) -> Vec<u8> { unsafe { std::mem::transmute::<$t, $c>(*self) }.to_bytes() } } }; } make_encodable!(i8, 0); make_encodable!(i16, 8, 0); make_encodable!(i32, 24, 16, 8, 0); make_encodable!(i64, 56, 48, 40, 32, 24, 16, 8, 0); make_encodable!(f32 => i32); make_encodable!(f64 => i64); macro_rules! make_decodable { ($t:ty, $s:expr, $($n:expr),+) => { impl Decodable for $t { fn from_bytes(d: &[u8]) -> Option<Self> { if d.len() != $s { return None; } Some($((d[$n] as $t) << (8 * ($s - $n - 1)))|+) } } }; ($t:ty => $c:ty) => { impl Decodable for $t { fn from_bytes(d: &[u8]) -> Option<Self> { match <$c as Decodable>::from_bytes(d) { Some(x) => Some(unsafe { std::mem::transmute(x) }), None => None } } } }; } // Trait for decoding values from bytes trait Decodable { fn from_bytes(d: &[u8]) -> Option<Self>; } make_decodable!(i8, 1, 0); make_decodable!(i16, 2, 0, 1); make_decodable!(i32, 4, 0, 1, 2, 3); make_decodable!(i64, 8, 0, 1, 2, 3, 4, 5, 6, 7); make_decodable!(f32 => i32); make_decodable!(f64 => i64); #[test] fn test_encode_decode() { assert_eq!(Some(0x1A2B_i16), i16::from_bytes(&0x1A2B_i16.to_bytes())); assert_eq!(Some(-3.14_f32), f32::from_bytes(&(-3.14_f32).to_bytes())); }
use std::fs::{read_dir, remove_dir_all, remove_file, File}; use std::io::{BufRead, BufReader, Lines, Result}; use std::path::Path; /// Counts lines in the source `handle`. /// /// # Examples /// ```ignore /// let lines: usize = count_lines(std::fs::File::open("Cargo.toml").unwrap()).unwrap(); /// ``` /// /// Credit: https://github.com/eclarke/linecount/blob/master/src/lib.rs pub fn count_lines<R: std::io::Read>(handle: R) -> std::io::Result<usize> { let mut reader = std::io::BufReader::with_capacity(1024 * 32, handle); let mut count = 0; loop { let len = { let buf = reader.fill_buf()?; if buf.is_empty() { break; } count += bytecount::count(buf, b'\n'); buf.len() }; reader.consume(len); } Ok(count) } /// Removes all the file and directories under `target_dir`. pub fn remove_dir_contents<P: AsRef<Path>>(target_dir: P) -> Result<()> { let entries = read_dir(target_dir)?; for entry in entries.into_iter().flatten() { let path = entry.path(); if path.is_dir() { remove_dir_all(path)?; } else { remove_file(path)?; } } Ok(()) } /// Attempts to write an entire buffer into the file. /// /// Creates one if the file does not exist. pub fn create_or_overwrite<P: AsRef<Path>>(path: P, buf: &[u8]) -> Result<()> { use std::io::Write; // Overwrite it. let mut f = std::fs::OpenOptions::new() .write(true) .create(true) .truncate(true) .open(path)?; f.write_all(buf)?; f.flush()?; Ok(()) } /// Returns an Iterator to the Reader of the lines of the file. /// /// The output is wrapped in a Result to allow matching on errors. pub fn read_lines<P>(path: P) -> Result<Lines<BufReader<File>>> where P: AsRef<Path>, { let file = File::open(path)?; Ok(BufReader::new(file).lines()) } /// Returns the first number lines given the file path. pub fn read_first_lines<P: AsRef<Path>>( path: P, number: usize, ) -> Result<impl Iterator<Item = String>> { read_lines_from(path, 0usize, number) } /// Returns a `number` of lines starting from the line number `from`. pub fn read_lines_from<P: AsRef<Path>>( path: P, from: usize, number: usize, ) -> Result<impl Iterator<Item = String>> { let file = File::open(path)?; Ok(BufReader::new(file) .lines() .skip(from) .filter_map(Result::ok) .take(number)) } /// Works for utf-8 lines only. #[allow(unused)] fn read_preview_lines_utf8<P: AsRef<Path>>( path: P, target_line: usize, size: usize, ) -> Result<(impl Iterator<Item = String>, usize)> { let (start, end, highlight_lnum) = if target_line > size { (target_line - size, target_line + size, size) } else { (0, 2 * size, target_line) }; Ok((read_lines_from(path, start, end - start)?, highlight_lnum)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_count_lines() { let f: &[u8] = b"some text\nwith\nfour\nlines\n"; assert_eq!(count_lines(f).unwrap(), 4); } }
extern crate image; extern crate glob; use crate::animation::Animation; use crate::animation::AnimationManager; use image::GenericImageView; use std::fs::File; use std::io::Read; use std::collections::HashMap; use std::error::Error; use sdl2::render::BlendMode; use sdl2::render::Texture; use sdl2::render::TextureCreator; use sdl2::pixels::PixelFormatEnum; use sdl2::rect::Rect; use glob::glob; use serde::{Serialize, Deserialize}; use cgmath::Vector3; use cgmath::Vector2; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Sprite { pub name: String, pub tex_id: String, #[serde(default)] pub width: u32, #[serde(default)] pub height: u32, pub u_scale: f64, // horizontal scale pub v_scale: f64, // vertical scale pub u_move: i32, // horizontal move pub v_move: i32, // vertical move #[serde(default)] pub rotating: bool, } #[derive(Clone, Debug)] pub struct Entity { pub id: u32, pub name: String, pub sprite: Sprite, pub pos: Vector3<f64>, pub dir: Vector2<f64>, pub collidable: bool, pub collision_radius: f64, pub animation: Option<Animation>, pub dead: bool, } // Template for instantiating entities #[derive(Serialize, Deserialize, Debug, Clone)] pub struct EntityTmpl { pub name: String, pub sprite_name: String, #[serde(default)] pub collidable: bool, #[serde(default)] pub collision_radius: f64, } pub struct EntityManager<'a> { entity_tmpls: HashMap<String, EntityTmpl>, sprite_manager: &'a SpriteManager<'a>, id_counter: u32, } impl<'a> EntityManager<'_> { pub fn new(manager: &'a SpriteManager) -> EntityManager<'a> { EntityManager { entity_tmpls: HashMap::new(), sprite_manager: manager, id_counter: 0, } } pub fn init(&mut self) -> Result<&Self, Box<dyn Error>> { let mut map = HashMap::new(); let paths = glob("./data/entities/*.json")? .filter_map(Result::ok); for path in paths { let mut file = File::open(path)?; let mut data = String::new(); file.read_to_string(&mut data)?; let ent: EntityTmpl = serde_json::from_str(&data)?; map.insert(ent.name.clone(), ent); } self.entity_tmpls = map; return Ok(self); } pub fn create_entity(&mut self, name: &str) -> Option<Entity> { let ent_tmpl = self.entity_tmpls.get(name)?; let sprite = self.sprite_manager.get_sprite(&ent_tmpl.sprite_name)?; let ent = Entity { id: self.id_counter, name: String::from(name), sprite: sprite.clone(), pos: Vector3::new(0.0, 0.0, 0.0), dir: Vector2::new(0.0, 0.0), collidable: ent_tmpl.collidable, collision_radius: ent_tmpl.collision_radius, animation: None, dead: false, }; self.id_counter += 1; return Some(ent); } } pub struct SpriteManager<'a> { sprite_textures: HashMap<String, Texture<'a>>, sprites: HashMap<String, Sprite>, } impl<'a> SpriteManager<'a> { pub fn new() -> SpriteManager<'a> { SpriteManager { sprite_textures: HashMap::new(), sprites: HashMap::new(), } } pub fn init(&mut self, creator: &'a TextureCreator<sdl2::video::WindowContext>) -> Result<&Self, Box<dyn Error>> { let mut map = HashMap::new(); let mut tex_map = HashMap::new(); let meta_paths = glob("./data/textures/sprites/*_meta.json")? .filter_map(Result::ok); for meta in meta_paths { // Init 'sprites' map with all sprite metadata let mut file = File::open(meta)?; let mut data = String::new(); file.read_to_string(&mut data)?; let mut sprite: Sprite = serde_json::from_str(&data)?; // Init sprite_textures map let sprite_name = &sprite.name; let path = format!("./data/textures/sprites/{}.png", sprite_name); let img = image::open(path)?; let dim = img.dimensions(); // (width, height) sprite.width = dim.0; sprite.height = dim.1; let img_raw = img.to_rgba().into_vec(); let mut texture = creator.create_texture_static(PixelFormatEnum::RGBA32, sprite.width, sprite.height).unwrap(); texture.update(None, &img_raw, (sprite.width * 4) as usize)?; texture.set_blend_mode(BlendMode::Blend); tex_map.insert(sprite.tex_id.clone(), texture); map.insert(sprite.name.clone(), sprite); } self.sprites = map; self.sprite_textures = tex_map; return Ok(self); } pub fn get_texture(&self, id: &str) -> Option<&Texture> { self.sprite_textures.get(id) } pub fn get_sprite(&self, id: &str) -> Option<&Sprite> { self.sprites.get(id) } } impl Entity { // Get the correct rectangle to render from the sprite sheet // Based on current angle to player and animation frame (if applicable) // x_slice: desired slice of sprite on screen // sprite_screen_x: sprite's starting point on screen // sprite_screen_width: width of sprite on screen (used to calc starting x coord on sprite sheet) // angle: angle between sprite's dir and player pub fn get_frame_rect (&self, x_slice: i32, sprite_screen_x: i32, sprite_screen_width: i32, angle: f64) -> Rect { let mut width = self.sprite.width; // Width of sprite let mut height = self.sprite.height; // Height of sprite let mut x = 0; // Starting x pos of sprite (top left) if self.sprite.rotating { width = width / 8; height = height / 7 + 1; if !self.dead { let step = 2.0 * std::f64::consts::PI / 8.0; let step_num = ((angle + std::f64::consts::PI) / step) as i32; let img_step = self.sprite.width as i32 / 8; x = img_step * step_num; } } let y = match &self.animation { None => 0, Some(a) => height * a.get_current_frame_immut().y_pos, } as i32; x = match &self.animation { None => x, Some(a) => x + (width * a.get_current_frame_immut().x_pos) as i32, }; x = x + ((x_slice - (-sprite_screen_width / 2 + sprite_screen_x)) * width as i32 / sprite_screen_width) as i32; // Returns a vertical strip at the right location return Rect::new(x, y, 1, height); } // Move animation by 1 frame (if there IS an active animation) // 1. decrement time in current frame // 2. if time is up, go to next frame // 3. if there is no next frame, either loop or remove the animation entirely // frame_time: time that the last frame took in seconds pub fn tick_animation (&mut self, frame_time: f64) { match &mut self.animation { None => return, Some(a) => { let curr_frame = a.get_current_frame(); curr_frame.time_remaining -= frame_time; if curr_frame.time_remaining <= 0.0 { // Reset duration on frame in case we're looping curr_frame.time_remaining = curr_frame.duration; a.curr_frame += 1; if a.curr_frame >= a.get_num_frames() { if a.do_loop { a.curr_frame = 0; } else if !a.perm { self.animation = None; } else { // Stay on last frame a.curr_frame = a.get_num_frames() - 1; } } } } }; } pub fn kill (&mut self, manager: &AnimationManager) { self.dead = true; self.collidable = false; self.animation = manager.get_animation("die"); } pub fn revive (&mut self) { self.dead = false; self.animation = None; } }
//! # Analog to Digital Converter. //! //! ## Examples //! //! Check out [examles/adc.rs][]. //! //! It can be built for the STM32F3Discovery running //! `cargo build --example adc --features=stm32f303xc` //! //! [examples/adc.rs]: https://github.com/stm32-rs/stm32f3xx-hal/blob/v0.7.0/examples/adc.rs use crate::{ gpio::Analog, rcc::{Clocks, AHB}, }; use cortex_m::asm; use embedded_hal::adc::{Channel, OneShot}; use crate::{ gpio::{gpioa, gpiob, gpioc}, pac::{ADC1, ADC1_2, ADC2}, }; use stm32f3::stm32f303::{adc1::cfgr::ALIGN_A, adc1_2::ccr::CKMODE_A}; const MAX_ADVREGEN_STARTUP_US: u32 = 10; #[cfg(any( feature = "stm32f303xb", feature = "stm32f303xc", feature = "stm32f303xd", feature = "stm32f303xe", ))] use crate::{ gpio::{gpiod, gpioe, gpiof}, pac::{ADC3, ADC3_4, ADC4}, }; /// Analog Digital Converter Peripheral // TODO: Remove `pub` from the register block once all functionalities are implemented. // Leave it here until then as it allows easy access to the registers. pub struct Adc<ADC> { /// ADC Register pub rb: ADC, clocks: Clocks, ckmode: CkMode, operation_mode: Option<OperationMode>, } /// ADC sampling time /// /// Each channel can be sampled with a different sample time. /// There is always an overhead of 13 ADC clock cycles. /// E.g. For Sampletime T_19 the total conversion time (in ADC clock cycles) is /// 13 + 19 = 32 ADC Clock Cycles pub enum SampleTime { /// 1.5 ADC clock cycles T_1, /// 2.5 ADC clock cycles T_2, /// 4.5 ADC clock cycles T_4, /// 7.5 ADC clock cycles T_7, /// 19.5 ADC clock cycles T_19, /// 61.5 ADC clock cycles T_61, /// 181.5 ADC clock cycles T_181, /// 601.5 ADC clock cycles T_601, } impl Default for SampleTime { /// T_1 is also the reset value. fn default() -> Self { SampleTime::T_1 } } impl SampleTime { /// Conversion to bits for SMP fn bitcode(&self) -> u8 { match self { SampleTime::T_1 => 0b000, SampleTime::T_2 => 0b001, SampleTime::T_4 => 0b010, SampleTime::T_7 => 0b011, SampleTime::T_19 => 0b100, SampleTime::T_61 => 0b101, SampleTime::T_181 => 0b110, SampleTime::T_601 => 0b111, } } } #[derive(Clone, Copy, PartialEq)] /// ADC operation mode // TODO: Implement other modes (DMA, Differential,…) pub enum OperationMode { /// OneShot Mode OneShot, } #[derive(Clone, Copy, PartialEq)] /// ADC CkMode // TODO: Add ASYNCHRONOUS mode pub enum CkMode { // /// Use Kernel Clock adc_ker_ck_input divided by PRESC. Asynchronous to AHB clock // ASYNCHRONOUS = 0, /// Use AHB clock rcc_hclk3. In this case rcc_hclk must equal sys_d1cpre_ck SYNCDIV1 = 1, /// Use AHB clock rcc_hclk3 divided by 2 SYNCDIV2 = 2, /// Use AHB clock rcc_hclk3 divided by 4 SYNCDIV4 = 4, } impl Default for CkMode { fn default() -> Self { CkMode::SYNCDIV2 } } // ADC3_2 returns a pointer to a adc1_2 type, so this from is ok for both. impl From<CkMode> for CKMODE_A { fn from(ckmode: CkMode) -> Self { match ckmode { //CkMode::ASYNCHRONOUS => CKMODE_A::ASYNCHRONOUS, CkMode::SYNCDIV1 => CKMODE_A::SYNCDIV1, CkMode::SYNCDIV2 => CKMODE_A::SYNCDIV2, CkMode::SYNCDIV4 => CKMODE_A::SYNCDIV4, } } } /// ADC data register alignment pub enum Align { /// Right alignment of output data Right, /// Left alignment of output data Left, } impl Default for Align { fn default() -> Self { Align::Right } } impl From<Align> for ALIGN_A { fn from(align: Align) -> ALIGN_A { match align { Align::Right => ALIGN_A::RIGHT, Align::Left => ALIGN_A::LEFT, } } } /// Maps pins to ADC Channels. macro_rules! adc_pins { ($ADC:ident, $($pin:ty => $chan:expr),+ $(,)*) => { $( impl Channel<$ADC> for $pin { type ID = u8; fn channel() -> u8 { $chan } } )+ }; } // # ADC1 Pin/Channel mapping // ## f303 #[cfg(feature = "stm32f303")] adc_pins!(ADC1, gpioa::PA0<Analog> => 1, gpioa::PA1<Analog> => 2, gpioa::PA2<Analog> => 3, gpioa::PA3<Analog> => 4, gpioc::PC0<Analog> => 6, gpioc::PC1<Analog> => 7, gpioc::PC2<Analog> => 8, gpioc::PC3<Analog> => 9, ); #[cfg(any(feature = "stm32f303x6", feature = "stm32f303x8"))] adc_pins!(ADC1, gpiob::PB0<Analog> => 11, gpiob::PB1<Analog> => 12, gpiob::PB13<Analog> => 13, ); #[cfg(any( feature = "stm32f303xb", feature = "stm32f303xc", feature = "stm32f303xd", feature = "stm32f303xe", ))] adc_pins!(ADC1, gpiof::PF4<Analog> => 5, gpiof::PF2<Analog> => 10, ); // # ADC2 Pin/Channel mapping // ## f303 #[cfg(feature = "stm32f303")] adc_pins!(ADC2, gpioa::PA4<Analog> => 1, gpioa::PA5<Analog> => 2, gpioa::PA6<Analog> => 3, gpioa::PA7<Analog> => 4, gpioc::PC4<Analog> => 5, gpioc::PC0<Analog> => 6, gpioc::PC1<Analog> => 7, gpioc::PC2<Analog> => 8, gpioc::PC3<Analog> => 9, gpioc::PC5<Analog> => 11, gpiob::PB2<Analog> => 12, ); #[cfg(any(feature = "stm32f303x6", feature = "stm32f303x8"))] adc_pins!(ADC2, gpiob::PB12<Analog> => 13, gpiob::PB14<Analog> => 14, gpiob::PB15<Analog> => 15, ); #[cfg(any( feature = "stm32f303xb", feature = "stm32f303xc", feature = "stm32f303xd", feature = "stm32f303xe", ))] adc_pins!(ADC2, gpiof::PF2<Analog> => 10, ); // # ADC3 Pin/Channel mapping // ## f303 #[cfg(any( feature = "stm32f303xb", feature = "stm32f303xc", feature = "stm32f303xd", feature = "stm32f303xe", ))] adc_pins!(ADC3, gpiob::PB1<Analog> => 1, gpioe::PE9<Analog> => 2, gpioe::PE13<Analog> => 3, // There is no ADC3 Channel #4 gpiob::PB13<Analog> => 5, gpioe::PE8<Analog> => 6, gpiod::PD10<Analog> => 7, gpiod::PD11<Analog> => 8, gpiod::PD12<Analog> => 9, gpiod::PD13<Analog> => 10, gpiod::PD14<Analog> => 11, gpiob::PB0<Analog> => 12, gpioe::PE7<Analog> => 13, gpioe::PE10<Analog> => 14, gpioe::PE11<Analog> => 15, gpioe::PE12<Analog> => 16, ); // # ADC4 Pin/Channel mapping // ## f303 #[cfg(any( feature = "stm32f303xb", feature = "stm32f303xc", feature = "stm32f303xd", feature = "stm32f303xe", ))] adc_pins!(ADC4, gpioe::PE14<Analog> => 1, gpioe::PE15<Analog> => 2, gpiob::PB12<Analog> => 3, gpiob::PB14<Analog> => 4, gpiob::PB15<Analog> => 5, gpioe::PE8<Analog> => 6, gpiod::PD10<Analog> => 7, gpiod::PD11<Analog> => 8, gpiod::PD12<Analog> => 9, gpiod::PD13<Analog> => 10, gpiod::PD14<Analog> => 11, gpiod::PD8<Analog> => 12, gpiod::PD9<Analog> => 13, ); // Abstract implementation of ADC functionality // Do not use directly. See adc12_hal for a applicable Macro. // TODO: Extend/generalize beyond f303 macro_rules! adc_hal { ($( $ADC:ident: ($adcx:ident, $ADC_COMMON:ident), )+) => { $( impl Adc<$ADC> { /// Init a new ADC /// /// Enables the clock, performs a calibration and enables the ADC /// /// # Panics /// If one of the following occurs: /// * the clocksetting is not well defined. /// * the clock was already enabled with a different setting /// pub fn $adcx( rb: $ADC, adc_common : &mut $ADC_COMMON, ahb: &mut AHB, ckmode: CkMode, clocks: Clocks, ) -> Self { let mut this_adc = Self { rb, clocks, ckmode, operation_mode: None, }; if !(this_adc.clocks_welldefined(clocks)) { crate::panic!("Clock settings not well defined"); } if !(this_adc.enable_clock(ahb, adc_common)){ crate::panic!("Clock already enabled with a different setting"); } this_adc.set_align(Align::default()); this_adc.calibrate(); // ADEN bit cannot be set during ADCAL=1 // and 4 ADC clock cycle after the ADCAL // bit is cleared by hardware this_adc.wait_adc_clk_cycles(4); this_adc.enable(); this_adc } /// Releases the ADC peripheral and associated pins pub fn free(mut self) -> $ADC { self.disable(); self.rb } /// Software can use CkMode::SYNCDIV1 only if /// hclk and sysclk are the same. (see reference manual 15.3.3) fn clocks_welldefined(&self, clocks: Clocks) -> bool { if (self.ckmode == CkMode::SYNCDIV1) { clocks.hclk().0 == clocks.sysclk().0 } else { true } } /// sets up adc in one shot mode for a single channel pub fn setup_oneshot(&mut self) { self.rb.cr.modify(|_, w| w.adstp().stop()); self.rb.isr.modify(|_, w| w.ovr().clear()); self.rb.cfgr.modify(|_, w| w .cont().single() .ovrmod().preserve() ); self.set_sequence_len(1); self.operation_mode = Some(OperationMode::OneShot); } fn set_sequence_len(&mut self, len: u8) { crate::assert!(len - 1 < 16, "ADC sequence length must be in 1..=16"); self.rb.sqr1.modify(|_, w| w.l().bits(len - 1)); } fn set_align(&self, align: Align) { self.rb.cfgr.modify(|_, w| w.align().variant(align.into())); } /// Software procedure to enable the ADC /// According to RM0316 15.3.9 fn enable(&mut self) { // This check assumes, that the ADC was enabled before and it was waited until // ADRDY=1 was set. // This assumption is true, if the peripheral was initially enabled through // this method. if !self.rb.cr.read().aden().is_enable() { // Set ADEN=1 self.rb.cr.modify(|_, w| w.aden().enable()); // Wait until ADRDY=1 (ADRDY is set after the ADC startup time). This can be // done using the associated interrupt (setting ADRDYIE=1). while self.rb.isr.read().adrdy().is_not_ready() {} } } /// Disable according to RM0316 15.3.9 fn disable(&mut self) { // NOTE: Software is allowed to set ADSTP only when ADSTART=1 and ADDIS=0 // (ADC is enabled and eventually converting a regular conversion and there is no // pending request to disable the ADC) if self.rb.cr.read().addis().bit() == false && (self.rb.cr.read().adstart().bit() || self.rb.cr.read().jadstart().bit()) { self.rb.cr.modify(|_, w| w.adstp().stop()); // NOTE: In auto-injection mode (JAUTO=1), setting ADSTP bit aborts both // regular and injected conversions (do not use JADSTP) if !self.rb.cfgr.read().jauto().is_enabled() { self.rb.cr.modify(|_, w| w.jadstp().stop()); } while self.rb.cr.read().adstp().bit() || self.rb.cr.read().jadstp().bit() { } } // NOTE: Software is allowed to set ADDIS only when ADEN=1 and both ADSTART=0 // and JADSTART=0 (which ensures that no conversion is ongoing) if self.rb.cr.read().aden().is_enable() { self.rb.cr.modify(|_, w| w.addis().disable()); while self.rb.cr.read().addis().bit() { } } } /// Calibrate according to RM0316 15.3.8 fn calibrate(&mut self) { if !self.rb.cr.read().advregen().is_enabled() { self.advregen_enable(); self.wait_advregen_startup(); } self.disable(); self.rb.cr.modify(|_, w| w .adcaldif().single_ended() .adcal() .calibration()); while self.rb.cr.read().adcal().is_calibration() {} } fn wait_adc_clk_cycles(&self, cycles: u32) { // using a match statement here so compilation will fail once asynchronous clk // mode is implemented (CKMODE[1:0] = 00b). This will force whoever is working // on it to rethink what needs to be done here :) let adc_per_cpu_cycles = match self.ckmode { CkMode::SYNCDIV1 => 1, CkMode::SYNCDIV2 => 2, CkMode::SYNCDIV4 => 4, }; asm::delay(adc_per_cpu_cycles * cycles); } fn advregen_enable(&mut self){ // need to go through intermediate first self.rb.cr.modify(|_, w| w.advregen().intermediate()); self.rb.cr.modify(|_, w| w.advregen().enabled()); } /// wait for the advregen to startup. /// /// This is based on the MAX_ADVREGEN_STARTUP_US of the device. fn wait_advregen_startup(&self) { asm::delay((MAX_ADVREGEN_STARTUP_US * 1_000_000) / self.clocks.sysclk().0); } /// busy ADC read fn convert_one(&mut self, chan: u8) -> u16 { if self.operation_mode != Some(OperationMode::OneShot) { self.setup_oneshot(); } self.set_chan_smps(chan, SampleTime::default()); self.select_single_chan(chan); self.rb.cr.modify(|_, w| w.adstart().start()); while self.rb.isr.read().eos().is_not_complete() {} self.rb.isr.modify(|_, w| w.eos().clear()); return self.rb.dr.read().rdata().bits(); } /// This should only be invoked with the defined channels for the particular /// device. (See Pin/Channel mapping above) fn select_single_chan(&self, chan: u8) { self.rb.sqr1.modify(|_, w| // NOTE(unsafe): chan is the x in ADCn_INx unsafe { w.sq1().bits(chan) } ); } /// Note: only allowed when ADSTART = 0 // TODO: there are boundaries on how this can be set depending on the hardware. fn set_chan_smps(&self, chan: u8, smp: SampleTime) { match chan { 1 => self.rb.smpr1.modify(|_, w| w.smp1().bits(smp.bitcode())), 2 => self.rb.smpr1.modify(|_, w| w.smp2().bits(smp.bitcode())), 3 => self.rb.smpr1.modify(|_, w| w.smp3().bits(smp.bitcode())), 4 => self.rb.smpr1.modify(|_, w| w.smp4().bits(smp.bitcode())), 5 => self.rb.smpr1.modify(|_, w| w.smp5().bits(smp.bitcode())), 6 => self.rb.smpr1.modify(|_, w| w.smp6().bits(smp.bitcode())), 7 => self.rb.smpr1.modify(|_, w| w.smp7().bits(smp.bitcode())), 8 => self.rb.smpr1.modify(|_, w| w.smp8().bits(smp.bitcode())), 9 => self.rb.smpr1.modify(|_, w| w.smp9().bits(smp.bitcode())), 11 => self.rb.smpr2.modify(|_, w| w.smp10().bits(smp.bitcode())), 12 => self.rb.smpr2.modify(|_, w| w.smp12().bits(smp.bitcode())), 13 => self.rb.smpr2.modify(|_, w| w.smp13().bits(smp.bitcode())), 14 => self.rb.smpr2.modify(|_, w| w.smp14().bits(smp.bitcode())), 15 => self.rb.smpr2.modify(|_, w| w.smp15().bits(smp.bitcode())), 16 => self.rb.smpr2.modify(|_, w| w.smp16().bits(smp.bitcode())), 17 => self.rb.smpr2.modify(|_, w| w.smp17().bits(smp.bitcode())), 18 => self.rb.smpr2.modify(|_, w| w.smp18().bits(smp.bitcode())), _ => crate::unreachable!(), }; } } impl<Word, Pin> OneShot<$ADC, Word, Pin> for Adc<$ADC> where Word: From<u16>, Pin: Channel<$ADC, ID = u8>, { type Error = (); fn read(&mut self, _pin: &mut Pin) -> nb::Result<Word, Self::Error> { // TODO: Convert back to previous mode after use. let res = self.convert_one(Pin::channel()); return Ok(res.into()); } } )+ } } // Macro to implement ADC functionallity for ADC1 and ADC2 // TODO: Extend/differentiate beyond f303. macro_rules! adc12_hal { ($( $ADC:ident: ($adcx:ident), )+) => { $( impl Adc<$ADC> { /// Returns true iff /// the clock can be enabled with the given settings /// or the clock was already enabled with the same settings fn enable_clock(&self, ahb: &mut AHB, adc_common: &mut ADC1_2) -> bool { if ahb.enr().read().adc12en().is_enabled() { return (adc_common.ccr.read().ckmode().variant() == self.ckmode.into()); } ahb.enr().modify(|_, w| w.adc12en().enabled()); adc_common.ccr.modify(|_, w| w .ckmode().variant(self.ckmode.into()) ); true } } adc_hal! { $ADC: ($adcx, ADC1_2), } )+ } } // Macro to implement ADC functionallity for ADC3 and ADC4 // TODO: Extend/differentiate beyond f303. #[cfg(any( feature = "stm32f303xb", feature = "stm32f303xc", feature = "stm32f303xd", feature = "stm32f303xe", ))] macro_rules! adc34_hal { ($( $ADC:ident: ($adcx:ident), )+) => { $( impl Adc<$ADC> { /// Returns true iff /// the clock can be enabled with the given settings /// or the clock was already enabled with the same settings fn enable_clock(&self, ahb: &mut AHB, adc_common: &mut ADC3_4) -> bool { if ahb.enr().read().adc34en().is_enabled() { return (adc_common.ccr.read().ckmode().variant() == self.ckmode.into()); } ahb.enr().modify(|_, w| w.adc34en().enabled()); adc_common.ccr.modify(|_, w| w .ckmode().variant(self.ckmode.into()) ); true } } adc_hal! { $ADC: ($adcx, ADC3_4), } )+ } } #[cfg(feature = "stm32f303")] adc12_hal! { ADC1: (adc1), ADC2: (adc2), } #[cfg(any( feature = "stm32f303xb", feature = "stm32f303xc", feature = "stm32f303xd", feature = "stm32f303xe", ))] adc34_hal! { ADC3: (adc3), ADC4: (adc4), }
use hal::register::Register; pub struct Rcc { pub cr: Cr, pub cfgr: Register<u32>, pub cir: Register<u32>, pub apb2rstr: Register<u32>, pub apb1rstr: Register<u32>, pub ahbenr: AhbEnr, pub apb2enr: Apb2Enr, pub apb1enr: Apb1Enr, pub bdcr: Register<u32>, pub csr: Register<u32>, pub ahbrstr: Register<u32>, pub cfgr2: Register<u32>, pub cfgr3: Register<u32> } register!(Cr; hsi_on, set_hsi_on, 0..0; hsi_rdy, set_hsi_rdy, 1..1; hsi_trim, set_hsi_trim, 3..7; hsi_cal, set_hsi_cal, 8..15; hse_on, set_hse_on, 16..16; hse_rdy, set_hse_rdy, 17..17; hse_byp, set_hse_byp, 18..18; css_on, set_css_on, 19..19; pll_on, set_pll_on, 24..24; pll_rdy, set_pll_rdy, 25..25 ); register!(AhbEnr; dma1_en, set_dma1_en, 0..0; dma2_en, set_dma2_en, 1..1; sram_en, set_sram_en, 2..2; flitf_en, set_flitf_en, 4..4; fmc_en, set_fmc_en, 5..5; crc_en, set_crc_en, 6..6; gpioa_en, set_gpioa_en, 17..17; gpiob_en, set_gpiob_en, 18..18; gpioc_en, set_gpioc_en, 19..19; gpiod_en, set_gpiod_en, 20..20; gpioe_en, set_gpioe_en, 21..21; gpiof_en, set_gpiof_en, 22..22; gpiog_en, set_gpiog_en, 23..23; // Only on STM32F303 xD xE. tsc_en, set_tsc_en, 24..24; adc12_en, set_adc12_en, 28..28; adc34_en, set_adc34_en, 29..29 ); register!(Apb2Enr; sys_cfg_en, set_sys_cfg_en, 0..0; tim1_en, set_tim1_en, 11..11; spi1_en, set_spi1_en, 12..12; tim8_en, set_tim8_en, 13..13; usart1_en, set_usart1_en, 14..14; spi4_en, set_spi4_en, 15..15; tim15_en, set_tim15_en, 16..16; tim16_en, set_tim16_en, 17..17; tim17_en, set_tim17_en, 18..18; tim20_en, set_tim20_en, 20..20 ); register!(Apb1Enr; tim2_en, set_tim2_en, 0..0; tim3_en, set_tim3_en, 1..1; tim4_en, set_tim4_en, 2..2; tim6_en, set_tim6_en, 4..4; tim7_en, set_tim7_en, 5..5; wwdg_en, set_wwdg_en, 11..11; spi2_en, set_spi2_en, 14..14; spi3_en, set_spi3_en, 15..15; usart2_en, set_usart2_en, 17..17; usart3_en, set_usart3_en, 18..18; uart4_en, set_uart4_en, 19..19; uart5_en, set_uart5_en, 20..20; i2c1_en, set_i2c1_en, 21..21; i2c2_en, set_i2c2_en, 22..22; usb_en, set_usb_en, 23..23; can_en, set_can_en, 25..25; dac2_en, set_dac2_en, 26..26; pwr_en, set_pwr_en, 28..28; dac1_en, set_dac1_en, 29..29; i2c3_en, set_i2c3_en, 30..30 );
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[cfg(feature = "Storage_Pickers_Provider")] pub mod Provider; #[link(name = "windows")] extern "system" {} pub type FileExtensionVector = *mut ::core::ffi::c_void; pub type FileOpenPicker = *mut ::core::ffi::c_void; pub type FilePickerFileTypesOrderedMap = *mut ::core::ffi::c_void; pub type FilePickerSelectedFilesArray = *mut ::core::ffi::c_void; pub type FileSavePicker = *mut ::core::ffi::c_void; pub type FolderPicker = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct PickerLocationId(pub i32); impl PickerLocationId { pub const DocumentsLibrary: Self = Self(0i32); pub const ComputerFolder: Self = Self(1i32); pub const Desktop: Self = Self(2i32); pub const Downloads: Self = Self(3i32); pub const HomeGroup: Self = Self(4i32); pub const MusicLibrary: Self = Self(5i32); pub const PicturesLibrary: Self = Self(6i32); pub const VideosLibrary: Self = Self(7i32); pub const Objects3D: Self = Self(8i32); pub const Unspecified: Self = Self(9i32); } impl ::core::marker::Copy for PickerLocationId {} impl ::core::clone::Clone for PickerLocationId { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct PickerViewMode(pub i32); impl PickerViewMode { pub const List: Self = Self(0i32); pub const Thumbnail: Self = Self(1i32); } impl ::core::marker::Copy for PickerViewMode {} impl ::core::clone::Clone for PickerViewMode { fn clone(&self) -> Self { *self } }
pub mod full_stats; pub mod stone_stats; pub mod stone_score;
fn main() { println!(r"cargo:rustc-link-search=/home/maxking/Documents/weechat-relay/build/lib"); }
use std::convert::From; use min_max::*; use crate::rgb::*; #[derive(Debug, PartialEq)] pub struct Cmyk { pub c: f32, pub m: f32, pub y: f32, pub k: f32, } impl Cmyk { fn new(c: f32, m: f32, y: f32, k: f32) -> Self { Self { c, m, y, k } } } impl From<RgbScaled> for Cmyk { fn from(rgb: RgbScaled) -> Self { let mut c = 1.0 - rgb.r; let mut m = 1.0 - rgb.g; let mut y = 1.0 - rgb.b; let k = min_partial!(c, m, y); c = (c - k) / (1.0 - k); m = (m - k) / (1.0 - k); y = (y - k) / (1.0 - k); Self { c, m, y, k } } } impl From<Rgb> for Cmyk { fn from(rgb: Rgb) -> Self { Self::from(RgbScaled::from(rgb)) } } /// Integer representation of CMYK color space. /// /// Each of `c`, `m`, `y` and `k` is an `u8` between 0 and 255 inclusive. #[derive(Debug, PartialEq)] pub struct CmykInt { pub c: u8, pub m: u8, pub y: u8, pub k: u8, } impl CmykInt { fn new(c: u8, m: u8, y: u8, k: u8) -> Self { Self { c, m, y, k } } } impl From<Cmyk> for CmykInt { fn from(cmyk: Cmyk) -> CmykInt { Self { c: (cmyk.c * 100.0).round() as u8, m: (cmyk.m * 100.0).round() as u8, y: (cmyk.y * 100.0).round() as u8, k: (cmyk.k * 100.0).round() as u8, } } } impl From<CmykInt> for Cmyk { fn from(cmyk: CmykInt) -> Cmyk { Self { c: cmyk.c as f32 / 100., m: cmyk.m as f32 / 100., y: cmyk.y as f32 / 100., k: cmyk.k as f32 / 100., } } }
use hdk::{ self, error::ZomeApiResult, holochain_core_types::{ entry::Entry, }, holochain_persistence_api::{ cas::content::{Address, AddressableContent}, }, }; use crate::anchors::{ RootAnchor, Anchor }; use crate::{ ROOT_ANCHOR_ENTRY, ROOT_ANCHOR_LINK_TO, ANCHOR_ENTRY }; use hdk::prelude::*; // Will only create a new root anchor if the Agent is not synched or its first hardTimeout // will accumulate headers for each agent that adds. // Ideally it would be cool to be able to linkn to the root_anchor_entry.address() and it not be an entry. pub (crate) fn root_anchor() -> ZomeApiResult<Address> { let root_anchor_entry = Entry::App( ROOT_ANCHOR_ENTRY.into(), RootAnchor {anchor_type: "root_anchor".into()}.into() ); let root_anchor_entry_address = root_anchor_entry.address(); if hdk::get_entry(&root_anchor_entry_address)?.is_none() { Ok(hdk::commit_entry(&root_anchor_entry)?) } else { Ok(root_anchor_entry_address) } } pub(crate) fn handle_create_anchor(anchor_type: String, anchor_text: String) -> ZomeApiResult<Address> { let anchor_entry = Entry::App( ANCHOR_ENTRY.into(), Anchor { anchor_type, anchor_text }.into() ); let anchor_address = hdk::commit_entry(&anchor_entry)?; hdk::link_entries(&root_anchor().unwrap(), &anchor_address, ROOT_ANCHOR_LINK_TO, "")?; Ok(anchor_address) } pub(crate) fn handle_get_anchor(anchor_address: Address) -> ZomeApiResult<Option<Entry>> { hdk::get_entry(&anchor_address) } pub(crate) fn handle_get_anchors() -> ZomeApiResult<Vec<Address>> { let root_anchor_entry = Entry::App( ROOT_ANCHOR_ENTRY.into(), RootAnchor {anchor_type: "root_anchor".into()}.into() ); let root_anchor_entry_address = root_anchor_entry.address(); Ok(hdk::get_links(&root_anchor_entry_address, LinkMatch::Exactly(ROOT_ANCHOR_LINK_TO), LinkMatch::Any)?.addresses().to_owned()) }
pub use self::add_venue_to_organization_request::*; pub use self::admin_display_ticket_type::*; pub use self::display_ticket_pricing::*; pub use self::facebook_web_login_token::*; pub use self::paging::*; pub use self::path_parameters::*; pub use self::register_request::*; pub use self::user_display_ticket_type::*; pub use self::user_profile_attributes::*; mod add_venue_to_organization_request; mod admin_display_ticket_type; mod display_ticket_pricing; mod facebook_web_login_token; mod paging; mod path_parameters; mod register_request; mod user_display_ticket_type; mod user_profile_attributes;
//! Private module for selective re-export. use crate::semantics::SequentialSpec; /// An implementation of this trait tests the [consistency] of a concurrent system with respect to /// a "reference sequential specification" [`SequentialSpec`]. The interface for doing so involves /// recording operation invocations and returns. /// /// Currently Stateright includes implementations in the form of a [`LinearizabilityTester`] and /// [`SequentialConsistencyTester`]. /// /// [consistency]: https://en.wikipedia.org/wiki/Consistency_model /// [`LinearizabilityTester`]: crate::semantics::LinearizabilityTester /// [`SequentialConsistencyTester`]: crate::semantics::SequentialConsistencyTester pub trait ConsistencyTester<T, RefObj> where RefObj: SequentialSpec, T: Copy, { /// Indicates that a thread invoked an operation. Returns `Ok(...)` if the /// history is valid, even if it is not consistent. fn on_invoke(&mut self, thread_id: T, op: RefObj::Op) -> Result<&mut Self, String>; /// Indicates that a thread's earlier operation invocation returned. Returns /// `Ok(...)` if the history is valid, even if it is not consistent. fn on_return(&mut self, thread_id: T, ret: RefObj::Ret) -> Result<&mut Self, String>; /// Indicates whether the recorded history is consistent with the semantics expected by the /// tester. fn is_consistent(&self) -> bool; /// A helper that indicates both an operation and corresponding return /// value for a thread. Returns `Ok(...)` if the history is valid, even if /// it is not consistent. fn on_invret( &mut self, thread_id: T, op: RefObj::Op, ret: RefObj::Ret, ) -> Result<&mut Self, String> { self.on_invoke(thread_id, op)?.on_return(thread_id, ret) } }
extern crate proconio; use proconio::input; fn main() { input! { a: i64, b: i64, } let mut h = std::collections::HashMap::<i64, i64>::new(); for mut x in (b + 1)..=a { let mut y = 2; while y * y <= x { while x % y == 0 { let c = h.entry(y).or_insert(0); *c += 1; x = x / y; } y += 1; } if x > 1 { let c = h.entry(x).or_insert(0); *c += 1; } } let mo = 1_000_000_000 + 7; let mut ans = 1 as i64; for c in h.values() { ans = ans * (c + 1) % mo; } println!("{}", ans); }
#![allow(non_camel_case_types, non_snake_case)] use otspec::de::CountedDeserializer; use otspec::de::Deserializer as OTDeserializer; use otspec::types::*; use otspec::{ deserialize_visitor, read_field, read_field_counted, read_remainder, stateful_deserializer, }; use otspec_macros::tables; use serde::de::{DeserializeSeed, SeqAccess, Visitor}; use serde::ser::SerializeSeq; use serde::Serializer; use serde::{Deserialize, Deserializer, Serialize}; tables!( fvarcore { uint16 majorVersion uint16 minorVersion uint16 axesArrayOffset uint16 reserved uint16 axisCount uint16 axisSize uint16 instanceCount uint16 instanceSize } VariationAxisRecord { Tag axisTag Fixed minValue Fixed defaultValue Fixed maxValue uint16 flags uint16 axisNameID } ); /// Struct representing a named instance within the variable font's design space #[derive(Debug, PartialEq)] pub struct InstanceRecord { /// The name ID for entries in the 'name' table that provide subfamily names for this instance. pub subfamilyNameID: uint16, /// Location of this instance in the design space. pub coordinates: Tuple, /// The name ID for entries in the 'name' table that provide PostScript names for this instance. pub postscriptNameID: Option<uint16>, } stateful_deserializer!( Vec<InstanceRecord>, InstanceRecordDeserializer, { axisCount: uint16, instanceCount: uint16, has_postscript_name_id: bool }, fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Vec<InstanceRecord>, A::Error> where A: SeqAccess<'de> { let mut res = vec![]; for _ in 0..self.instanceCount { let subfamilyNameID = read_field!(seq, uint16, "instance record family name ID"); let _flags = read_field!(seq, uint16, "instance record flags"); let coordinates = (read_field_counted!(seq, self.axisCount, "a coordinate") as Vec<i32>) .iter() .map(|x| Fixed::unpack(*x)) .collect(); let postscriptNameID = if self.has_postscript_name_id { Some(read_field!( seq, uint16, "instance record postscript name ID" )) } else { None }; res.push(InstanceRecord { subfamilyNameID, coordinates, postscriptNameID, }); println!("Got a record {:?}", res); } Ok(res) } ); /// Represents a font's fvar (Font Variations) table #[derive(Debug, PartialEq)] pub struct fvar { /// The font's axes of variation pub axes: Vec<VariationAxisRecord>, /// Any named instances within the design space pub instances: Vec<InstanceRecord>, } deserialize_visitor!( fvar, FvarVisitor, fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> { let core = read_field!(seq, fvarcore, "an fvar table header"); let remainder = read_remainder!(seq, "an fvar table"); let offset = core.axesArrayOffset as usize; let offset_base: usize = 16; let axis_count = core.axisCount as usize; let axis_records = &remainder[offset - offset_base..]; let mut de = OTDeserializer::from_bytes(axis_records); let cs: CountedDeserializer<VariationAxisRecord> = CountedDeserializer::with_len(axis_count); let axes: Vec<VariationAxisRecord> = cs .deserialize(&mut de) .map_err(|_| serde::de::Error::custom("Expecting a VariationAxisRecord"))?; let instance_records = &remainder[offset - offset_base + (core.axisCount * core.axisSize) as usize..]; let mut de2 = otspec::de::Deserializer::from_bytes(instance_records); let cs2 = InstanceRecordDeserializer { axisCount: core.axisCount, instanceCount: core.instanceCount, has_postscript_name_id: core.instanceSize == core.axisCount * 4 + 6, }; let instances: Vec<InstanceRecord> = cs2.deserialize(&mut de2).map_err(|e| { serde::de::Error::custom(format!("Expecting a InstanceRecord: {:?}", e)) })?; Ok(fvar { axes, instances }) } ); impl Serialize for fvar { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let has_postscript_name_id = self.instances.iter().any(|x| x.postscriptNameID.is_some()); if has_postscript_name_id && !self.instances.iter().all(|x| x.postscriptNameID.is_some()) { return Err(serde::ser::Error::custom( "Inconsistent use of postscriptNameID in fvar instances", )); } let core = fvarcore { majorVersion: 1, minorVersion: 0, axesArrayOffset: 16, reserved: 2, axisCount: self.axes.len() as uint16, axisSize: 20, instanceCount: self.instances.len() as uint16, instanceSize: (self.axes.len() * 4 + if has_postscript_name_id { 6 } else { 4 }) as uint16, }; let mut seq = serializer.serialize_seq(None)?; seq.serialize_element(&core)?; for axis in &self.axes { seq.serialize_element(&axis)?; } for instance in &self.instances { // Have to do this by hand seq.serialize_element(&instance.subfamilyNameID)?; seq.serialize_element::<uint16>(&0)?; seq.serialize_element::<Vec<i32>>( &instance .coordinates .iter() .map(|x| Fixed::pack(*x)) .collect(), )?; if has_postscript_name_id { seq.serialize_element(&instance.postscriptNameID.unwrap())?; } } seq.end() } } #[cfg(test)] mod tests { use crate::fvar; use crate::fvar::InstanceRecord; #[test] fn fvar_de() { let ffvar = fvar::fvar { axes: vec![ fvar::VariationAxisRecord { axisTag: *b"wght", flags: 0, minValue: 200.0, defaultValue: 200.0, maxValue: 1000.0, axisNameID: 256, }, fvar::VariationAxisRecord { axisTag: *b"ital", flags: 0, minValue: 0.0, defaultValue: 0.0, maxValue: 9.0, axisNameID: 257, }, ], instances: vec![ InstanceRecord { subfamilyNameID: 17, coordinates: vec![200.0, 0.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 258, coordinates: vec![300.0, 0.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 259, coordinates: vec![400.0, 0.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 260, coordinates: vec![600.0, 0.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 261, coordinates: vec![700.0, 0.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 262, coordinates: vec![800.0, 0.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 263, coordinates: vec![900.0, 0.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 259, coordinates: vec![1000.0, 0.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 264, coordinates: vec![200.0, 9.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 265, coordinates: vec![300.0, 9.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 257, coordinates: vec![400.0, 9.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 266, coordinates: vec![600.0, 9.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 267, coordinates: vec![700.0, 9.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 268, coordinates: vec![800.0, 9.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 269, coordinates: vec![900.0, 9.0], postscriptNameID: None, }, InstanceRecord { subfamilyNameID: 257, coordinates: vec![1000.0, 9.0], postscriptNameID: None, }, ], }; let binary_fvar = vec![ 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x02, 0x00, 0x02, 0x00, 0x14, 0x00, 0x10, 0x00, 0x0c, 0x77, 0x67, 0x68, 0x74, 0x00, 0xc8, 0x00, 0x00, 0x00, 0xc8, 0x00, 0x00, 0x03, 0xe8, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x69, 0x74, 0x61, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x11, 0x00, 0x00, 0x00, 0xc8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x02, 0x58, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x05, 0x00, 0x00, 0x02, 0xbc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x06, 0x00, 0x00, 0x03, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x00, 0x00, 0x03, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x03, 0xe8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0xc8, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x01, 0x09, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x01, 0x0a, 0x00, 0x00, 0x02, 0x58, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x01, 0x0b, 0x00, 0x00, 0x02, 0xbc, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x01, 0x0c, 0x00, 0x00, 0x03, 0x20, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x01, 0x0d, 0x00, 0x00, 0x03, 0x84, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x03, 0xe8, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, ]; let deserialized: fvar::fvar = otspec::de::from_bytes(&binary_fvar).unwrap(); assert_eq!(deserialized, ffvar); let serialized = otspec::ser::to_bytes(&deserialized).unwrap(); assert_eq!(serialized, binary_fvar); } }
use std::fs::File; use std::io::Read; use std::str::FromStr; use computer::IntCodeComputer; fn main() { let mut in_dat_fh = File::open("./data/input.txt").unwrap(); let mut in_dat = String::new(); in_dat_fh.read_to_string(&mut in_dat).unwrap(); let mut icc = IntCodeComputer::from_str(&in_dat).unwrap(); icc.add_input(vec![1]); if let Err(err) = icc.run() { println!("Running the program encountered and error: {:?}", err); std::process::exit(1); }; println!("Output of program part 1 was: {:?}", icc.output()); icc.reset(); icc.add_input(vec![5]); if let Err(err) = icc.run() { println!("Running the program encountered and error: {:?}", err); std::process::exit(1); }; println!("Output of program part 2 was: {:?}", icc.output()); }
use proconio::{input, marker::Chars}; fn main() { input! { n: usize, a: [Chars; n], }; for i in 0..n { for j in 0..n { if i == j { continue; } let ng = match a[i][j] { 'W' => a[j][i] != 'L', 'L' => a[j][i] != 'W', 'D' => a[j][i] != 'D', _ => unreachable!(), }; if ng { println!("incorrect"); return; } } } println!("correct"); }
use std::thread::sleep; use core::borrow::Borrow; use std::time::Duration; use std::cmp::Ordering::Greater; // 把红绿灯看成一个状态机,状态转换过程如下: //+-----------+ +------------+ +---------+ //| Green +----->+ Yellow +----->+ Red | //+-----+-----+ +------------+ +----+----+ // ^ | // | | // +-------------------------------------+ #[derive(Debug)] struct Red { wait_time: Duration } impl Red { fn new() -> Self { Red{ wait_time: Duration::new(60, 0) } } } #[derive(Debug)] struct Green { wait_time: std::time::Duration } impl Green { fn new() -> Self { Green{ wait_time: Duration::new(60, 0) } } } #[derive(Debug)] struct Yellow { wait_time: std::time::Duration } impl Yellow { fn new() -> Self { Yellow{ wait_time: Duration::new(10, 0) } } } #[derive(Debug)] struct TrafficLight<TLS> { state: TLS, } impl TrafficLight<Green> { fn new() -> Self { TrafficLight { state: Green::new(), } } } impl From<TrafficLight<Green>> for TrafficLight<Yellow> { fn from(green: TrafficLight<Green>) -> TrafficLight<Yellow> { println!("last state is {:?}", green); sleep(green.state.wait_time); TrafficLight { state: Yellow::new(), } } } impl From<TrafficLight<Yellow>> for TrafficLight<Red> { fn from(yellow: TrafficLight<Yellow>) -> TrafficLight<Red> { println!("last state is {:?}", yellow); sleep(yellow.state.wait_time); TrafficLight { state: Red::new(), } } } impl From<TrafficLight<Red>> for TrafficLight<Green> { fn from(red: TrafficLight<Red>) -> TrafficLight<Green> { println!("last state is {:?}", red); sleep(red.state.wait_time); TrafficLight { state: Green::new(), } } } enum TrafficLightWrapper { Red(TrafficLight<Red>), Green(TrafficLight<Green>), Yellow(TrafficLight<Yellow>), } impl TrafficLightWrapper { fn new() -> Self { TrafficLightWrapper::Green(TrafficLight::new()) } fn step(mut self) -> Self { match self { TrafficLightWrapper::Green(green) => TrafficLightWrapper::Yellow(green.into()), TrafficLightWrapper::Yellow(yellow) => TrafficLightWrapper::Red(yellow.into()), TrafficLightWrapper::Red(red) => TrafficLightWrapper::Green(red.into()) } } } fn main() { let mut state_machine = TrafficLightWrapper::new(); loop { state_machine = state_machine.step(); } }
/// Cetak vector menjadi string /// e.g. [1,2,3,4,5] /// fn main() { let mut val = vec![1,2,3,4,5]; println!("{}", val.len()); val.insert(1, 7); println!("[{}]", val.iter().fold(String::new(), |acc, &num| acc + &num.to_string() + ", ")); }
use super::{rpc_manager::RpcInfo, PartialHashBatch}; use crate::bls::SIG_SIZE; use crossbeam_channel::Receiver; use log::trace; use randomx::{HashChain, Vm, HASH_SIZE}; use std::{ cmp::Ordering, sync::{atomic, Arc}, }; fn less_than_rev(a: &[u8; 32], b: &[u8; 32]) -> bool { let mut i = 31; while i > 0 { match a[i].cmp(&b[i]) { Ordering::Less => return true, Ordering::Greater => return false, Ordering::Equal => {} } i -= 1; } false } fn run( rpc_info: Arc<RpcInfo>, inputs_chan: Receiver<PartialHashBatch<[u8; HASH_SIZE + SIG_SIZE]>>, ) { let mut template = rpc_info.latest_template.read().clone(); let mut vm = Vm::new(template.randomx_cache.clone()).expect("Failed to create RandomX VM"); loop { let inputs = match inputs_chan.recv() { Ok(x) => x, Err(_) => return, }; if inputs.height < template.height { continue; } let mut prev_input = inputs.items[0]; let mut hash_chain = HashChain::new(&mut vm, &prev_input.1); trace!("second_hasher loaded template with seq {}", template.seq); for input in inputs.items[1..].iter() { let out = hash_chain.next(&input.1); if less_than_rev(&out, &template.max_hash) { let mut sig = [0u8; SIG_SIZE]; sig.copy_from_slice(&prev_input.1[HASH_SIZE..]); let data = (inputs.seq, prev_input.0, sig, out); if rpc_info.publish_channel.send(data).is_err() { return; } } prev_input = *input; } let out = hash_chain.last(); if less_than_rev(&out, &template.max_hash) { let mut sig = [0u8; SIG_SIZE]; sig.copy_from_slice(&prev_input.1[HASH_SIZE..]); let data = (inputs.seq, prev_input.0, sig, out); if rpc_info.publish_channel.send(data).is_err() { return; } } rpc_info .num_hashes_rec .fetch_add(1, atomic::Ordering::Relaxed); if rpc_info.latest_seq.load(atomic::Ordering::Relaxed) > template.seq { std::mem::drop(template); let vm_no_cache = vm.drop_cache(); template = rpc_info.latest_template.read().clone(); vm = vm_no_cache .set_cache(template.randomx_cache.clone()) .expect("Failed to set RandomX cache"); } } } pub fn start( rpc_info: Arc<RpcInfo>, inputs_chan: Receiver<PartialHashBatch<[u8; HASH_SIZE + SIG_SIZE]>>, ) { std::thread::spawn(|| run(rpc_info, inputs_chan)); }
use std::iter::{Peekable}; use crate::token::*; use crate::json_syntax::*; use std::collections::{HashMap}; pub struct Parser { tokens: Peekable<std::vec::IntoIter<Token>>, current: Token } impl Parser { pub fn new(tokens: Vec<Token>) -> Self { let mut iter = tokens.into_iter().peekable(); let first = iter.next().unwrap(); Self { tokens: iter, current: first } } fn advance(&mut self) -> Option<()> { self.current = self.tokens.next()?; Some(()) } fn skip(&mut self, n: usize) -> Option<()> { for _ in 0..n { self.advance()? } Some(()) } fn eat(&mut self, t: TokenKind) -> Option<()> { match &self.current { t => { self.advance(); Some(()) }, _ => None } } fn dict_entry(&mut self) -> Option<(String, JSONSyntax)> { let mut key = String::new(); match self.anything()? { JSONSyntax::Str(value) => { key = value }, _ => return None } self.advance()?; self.eat(TokenKind::Syntax(SyntaxKind::Colon))?; Some((key, self.anything()?)) } fn dict(&mut self) -> Option<HashMap<String, JSONSyntax>> { let mut result: HashMap<String, JSONSyntax> = HashMap::new(); self.advance()?; while self.current.kind != TokenKind::Syntax(SyntaxKind::RBracket) { let entry = self.dict_entry()?; result.insert(entry.0, entry.1); self.advance(); if self.current.kind == TokenKind::Syntax(SyntaxKind::RBracket) { break } else if self.current.kind == TokenKind::Syntax(SyntaxKind::Comma) && self.tokens.peek()?.kind == TokenKind::Syntax(SyntaxKind::RBracket) { self.skip(1); break } else { self.eat(TokenKind::Syntax(SyntaxKind::Comma))?; } } Some(result) } fn list(&mut self) -> Option<Vec<JSONSyntax>> { let mut result: Vec<JSONSyntax> = Vec::new(); self.advance()?; while self.current.kind != TokenKind::Syntax(SyntaxKind::RSBracket) { result.push(self.anything()?); self.advance()?; if self.current.kind == TokenKind::Syntax(SyntaxKind::RSBracket) { break } else if self.current.kind == TokenKind::Syntax(SyntaxKind::Comma) && self.tokens.peek()?.kind == TokenKind::Syntax(SyntaxKind::RSBracket) { self.skip(1); break } else { self.eat(TokenKind::Syntax(SyntaxKind::Comma)); } } Some(result) } fn anything(&mut self) -> Option<JSONSyntax> { match &self.current { Token { kind: TokenKind::Syntax(SyntaxKind::LBracket) } => Some( JSONSyntax::Container(self.dict()?) ), Token { kind: TokenKind::Syntax(SyntaxKind::LSBracket) } => Some( JSONSyntax::List(self.list()?) ), Token { kind: TokenKind::Type(TypeKind::Str(value)) } => Some( JSONSyntax::Str(value.clone()) ), Token { kind: TokenKind::Type(TypeKind::Numeric(value)) } => Some( JSONSyntax::Num(value.clone()) ), Token { kind: TokenKind::Type(TypeKind::Boolean(value)) } => Some( JSONSyntax::Bool(value.clone()) ), Token { kind: TokenKind::Type(TypeKind::Null) } => Some( JSONSyntax::Null ), _ => None } } pub fn parse<'a>(mut self) -> Option<JSONSyntax> { match self.current { Token { kind: TokenKind::Syntax(SyntaxKind::LBracket) } => Some(JSONSyntax::Container(self.dict()?)), Token { kind: TokenKind::Syntax(SyntaxKind::LSBracket) } => Some(JSONSyntax::List(self.list()?)), _ => return None } } }
use crate::plugins::config::DebugConfig; use game_lib::bevy::{ecs as bevy_ecs, prelude::*}; #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, SystemLabel)] pub struct ConfigPlugin; impl Plugin for ConfigPlugin { fn build(&self, app: &mut AppBuilder) { app.register_type::<DebugConfig>() .init_resource::<DebugConfig>(); } }
use std::ops::{Deref, DerefMut}; #[cfg(windows)] fn allocate_rwx(size: usize) -> *mut u8 { extern "system" { fn VirtualAlloc(base: *mut u8, size: usize, alloc_type: u32, prot: u32) -> *mut u8; } const MEM_COMMIT_RESERVE: u32 = 0x1000 | 0x2000; const PAGE_EXECUTE_READWRITE: u32 = 0x40; let prot = PAGE_EXECUTE_READWRITE; let result = unsafe { VirtualAlloc(std::ptr::null_mut(), size, MEM_COMMIT_RESERVE, prot) }; let success = !result.is_null(); assert!(success, "Allocating memory with size of {} bytes failed.", size); result } #[cfg(unix)] fn allocate_rwx(size: usize) -> *mut u8 { extern "system" { fn mmap(base: *mut u8, size: usize, prot: u32, flags: u32, fd: u32, offset: usize) -> *mut u8; } const MAP_PRIVATE_ANONYMOUS: u32 = 0x02 | 0x20; const PROT_READ: u32 = 1; const PROT_WRITE: u32 = 2; const PROT_EXEC: u32 = 4; let prot = PROT_READ | PROT_WRITE | PROT_EXEC; let result = unsafe { mmap(std::ptr::null_mut(), size, prot, MAP_PRIVATE_ANONYMOUS, 1u32.wrapping_neg(), 0) }; let success = !result.is_null() && result as isize > 0; assert!(success, "Allocating memory with size of {} bytes failed.", size); result } #[cfg(windows)] unsafe fn free_rwx(base: *mut u8, _size: usize) { extern "system" { fn VirtualFree(base: *mut u8, size: usize, free_type: u32) -> u32; } const MEM_RELEASE: u32 = 0x8000; let result = VirtualFree(base, 0, MEM_RELEASE); assert!(result != 0, "Freeing memory at addresss {:p} failed.", base); } #[cfg(unix)] unsafe fn free_rwx(base: *mut u8, size: usize) { extern "system" { fn munmap(base: *mut u8, size: usize) -> i32; } let result = munmap(base, size); assert_eq!(result, 0, "Freeing memory at addresss {:p} failed.", base); } pub struct ExecutableMemory { base: *mut u8, size: usize, } unsafe impl Send for ExecutableMemory {} unsafe impl Sync for ExecutableMemory {} impl ExecutableMemory { pub fn new(size: usize) -> Self { let base = allocate_rwx(size); Self { base, size, } } pub fn from_buffer(buffer: &[u8]) -> Self { let mut memory = Self::new(buffer.len()); memory.copy_from_slice(buffer); memory } } impl Drop for ExecutableMemory { fn drop(&mut self) { unsafe { free_rwx(self.base, self.size); } } } impl Deref for ExecutableMemory { type Target = [u8]; fn deref(&self) -> &Self::Target { unsafe { std::slice::from_raw_parts(self.base, self.size) } } } impl DerefMut for ExecutableMemory { fn deref_mut(&mut self) -> &mut Self::Target { unsafe { std::slice::from_raw_parts_mut(self.base, self.size) } } }
/// /// Cannot create object while /// you do not have all fields, self validating #[derive(Debug, Clone)] struct Relation { src: String, dst: String } #[derive(Debug)] struct CurrentRelation { history_index: usize, relations: Vec<Relation> } fn new_relation(src: String, dst: String, state: CurrentRelation) -> CurrentRelation { let r = Relation { src, dst }; // let idx = state.relations.len(); let idx = state.history_index; let mut vec2 = state.relations.clone(); vec2.push(r); CurrentRelation { history_index: idx, relations: vec2 } } fn undo(state: CurrentRelation) -> CurrentRelation { let idx = (state.history_index as i32 - 1).abs() as usize; CurrentRelation { history_index: idx, relations: state.relations } } fn redo(state: CurrentRelation) -> CurrentRelation { let idx = (state.history_index as i32 + 1).abs() as usize; CurrentRelation { history_index: idx, relations: state.relations } } pub fn run() { println!("-------------------- {} --------------------", file!()); let init_state = CurrentRelation { history_index: 0, relations: vec![] }; let state = redo(new_relation("Milanówek".to_string(), "Błonie".to_string(), undo(new_relation("Grodzisk".to_string(), "Płońsk".to_string(), new_relation("Gdańsk".to_string(), "Radom".to_string(), new_relation( "Warszawa".to_string(), "Rzeszów".to_string(), init_state)))))); println!("{:?}", state); }
extern crate cassandra; use cassandra::*; static CONTACT_POINTS:&'static str = "127.0.0.1"; static NUM_CONCURRENT_REQUESTS:isize=100; static CREATE_KEYSPACE:&'static str = "CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { \ \'class\': \'SimpleStrategy\', \'replication_factor\': \ \'1\' };"; static CREATE_TABLE:&'static str = "CREATE TABLE IF NOT EXISTS examples.paging (key ascii, value \ text, PRIMARY KEY (key));"; static SELECT_QUERY:&'static str = "SELECT * FROM paging"; static INSERT_QUERY:&'static str = "INSERT INTO paging (key, value) VALUES (?, ?);"; //FIXME uuids not yet working fn insert_into_paging(session: &mut CassSession /* , uuid_gen:&mut CassUuidGen */) -> Result<Vec<Option<ResultFuture>>, CassError> { let mut futures = Vec::with_capacity(NUM_CONCURRENT_REQUESTS as usize); let mut results = Vec::with_capacity(NUM_CONCURRENT_REQUESTS as usize); for i in 0..NUM_CONCURRENT_REQUESTS { let key = i.to_string(); println!("key ={:?}", key); let mut statement = CassStatement::new(INSERT_QUERY, 2); try!(statement.bind_string(0, &key)); try!(statement.bind_string(1, &key)); let future = session.execute_statement(&statement); futures.push(future); } while !futures.is_empty() { results.push(futures.pop()); } Ok(results) } fn select_from_paging(session: &mut CassSession) -> Result<(), CassError> { let has_more_pages = true; let mut statement = CassStatement::new(SELECT_QUERY, 0); statement.set_paging_size(100).unwrap(); //FIXME must understaned statement lifetime better for paging while has_more_pages { let result = try!(session.execute_statement(&statement).wait()); //println!("{:?}", result); for row in result.iter() { match try!(row.get_column(0)).get_string() { Ok(key) => { let key_str = key.to_string(); let value = try!(row.get_column(1)); print!("key: '{:?}' value: '{:?}'\n", key_str, &value.get_string().unwrap()); } Err(err) => panic!(err), } } // if result.has_more_pages() { // try!(statement.set_paging_state(&result)); // } // has_more_pages = result.has_more_pages(); } Ok(()) } fn main() { //let uuid_gen = &mut CassUuidGen::new(); let mut cluster = CassCluster::new(); cluster .set_contact_points(CONTACT_POINTS).unwrap() .set_load_balance_round_robin().unwrap(); let mut session = CassSession::new().connect(&cluster).wait().unwrap(); session.execute(CREATE_KEYSPACE,0).wait().unwrap(); session.execute(CREATE_TABLE,0).wait().unwrap(); session.execute("USE examples",0).wait().unwrap(); let results = insert_into_paging(&mut session/*, uuid_gen*/).unwrap(); for result in results { print!("{:?}", result.unwrap().wait().unwrap()); } select_from_paging(&mut session).unwrap(); session.close().wait().unwrap(); }
use bigneon_db::dev::TestProject; use bigneon_db::models::*; #[test] fn find_fee_item() { let project = TestProject::new(); let connection = project.get_connection(); let organization = project .create_organization() .with_fee_schedule(&project.create_fee_schedule().finish()) .finish(); let event = project .create_event() .with_organization(&organization) .with_tickets() .with_ticket_pricing() .finish(); let user = project.create_user().finish(); let cart = Order::find_or_create_cart(&user, connection).unwrap(); let ticket = &event.ticket_types(connection).unwrap()[0]; cart.add_tickets(ticket.id, 10, connection).unwrap(); let order_item = cart.items(connection).unwrap().remove(0); let fee_item = order_item.find_fee_item(connection).unwrap().unwrap(); assert_eq!(fee_item.parent_id, Some(order_item.id)); assert_eq!(fee_item.item_type, OrderItemTypes::PerUnitFees.to_string()); } #[test] fn calculate_quantity() { let project = TestProject::new(); let connection = project.get_connection(); let organization = project .create_organization() .with_fee_schedule(&project.create_fee_schedule().finish()) .finish(); let event = project .create_event() .with_organization(&organization) .with_tickets() .with_ticket_pricing() .finish(); let user = project.create_user().finish(); let cart = Order::find_or_create_cart(&user, connection).unwrap(); let ticket = &event.ticket_types(connection).unwrap()[0]; cart.add_tickets(ticket.id, 10, connection).unwrap(); let order_item = cart.items(connection).unwrap().remove(0); assert_eq!(order_item.calculate_quantity(connection), Ok(10)); //let datetime_in_past = NaiveDate::from_ymd(2018, 9, 16).and_hms(12, 12, 12); //diesel::update(ticket_instances::table.filter(ticket_instances::id.eq(tickets[0].id))) // .set(ticket_instances::reserved_until.eq(datetime_in_past)) // .get_result::<TicketInstance>(connection) // .unwrap(); //assert_eq!(order_item.calculate_quantity(connection), Ok(9)); }
pub mod getter; pub mod server; pub mod tester;
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qabstractitemdelegate.h // dst-file: /src/widgets/qabstractitemdelegate.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::super::core::qobject::*; // 771 use std::ops::Deref; // use super::qvector::*; // 775 use super::super::core::qobjectdefs::*; // 771 use super::qwidget::*; // 773 use super::qstyleoption::*; // 773 use super::super::core::qabstractitemmodel::*; // 771 use super::super::gui::qfontmetrics::*; // 771 use super::super::core::qstring::*; // 771 use super::super::gui::qpainter::*; // 771 use super::super::core::qsize::*; // 771 use super::super::core::qcoreevent::*; // 771 use super::super::gui::qevent::*; // 771 use super::qabstractitemview::*; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QAbstractItemDelegate_Class_Size() -> c_int; // proto: QVector<int> QAbstractItemDelegate::paintingRoles(); fn C_ZNK21QAbstractItemDelegate13paintingRolesEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: const QMetaObject * QAbstractItemDelegate::metaObject(); fn C_ZNK21QAbstractItemDelegate10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QAbstractItemDelegate::updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index); fn C_ZNK21QAbstractItemDelegate20updateEditorGeometryEP7QWidgetRK20QStyleOptionViewItemRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: void QAbstractItemDelegate::setEditorData(QWidget * editor, const QModelIndex & index); fn C_ZNK21QAbstractItemDelegate13setEditorDataEP7QWidgetRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); // proto: void QAbstractItemDelegate::QAbstractItemDelegate(QObject * parent); fn C_ZN21QAbstractItemDelegateC2EP7QObject(arg0: *mut c_void) -> u64; // proto: QWidget * QAbstractItemDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index); fn C_ZNK21QAbstractItemDelegate12createEditorEP7QWidgetRK20QStyleOptionViewItemRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> *mut c_void; // proto: void QAbstractItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index); fn C_ZNK21QAbstractItemDelegate5paintEP8QPainterRK20QStyleOptionViewItemRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: QSize QAbstractItemDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index); fn C_ZNK21QAbstractItemDelegate8sizeHintERK20QStyleOptionViewItemRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void; // proto: bool QAbstractItemDelegate::editorEvent(QEvent * event, QAbstractItemModel * model, const QStyleOptionViewItem & option, const QModelIndex & index); fn C_ZN21QAbstractItemDelegate11editorEventEP6QEventP18QAbstractItemModelRK20QStyleOptionViewItemRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void, arg3: *mut c_void) -> c_char; // proto: bool QAbstractItemDelegate::helpEvent(QHelpEvent * event, QAbstractItemView * view, const QStyleOptionViewItem & option, const QModelIndex & index); fn C_ZN21QAbstractItemDelegate9helpEventEP10QHelpEventP17QAbstractItemViewRK20QStyleOptionViewItemRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void, arg3: *mut c_void) -> c_char; // proto: void QAbstractItemDelegate::~QAbstractItemDelegate(); fn C_ZN21QAbstractItemDelegateD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QAbstractItemDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index); fn C_ZNK21QAbstractItemDelegate12setModelDataEP7QWidgetP18QAbstractItemModelRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: void QAbstractItemDelegate::destroyEditor(QWidget * editor, const QModelIndex & index); fn C_ZNK21QAbstractItemDelegate13destroyEditorEP7QWidgetRK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); fn QAbstractItemDelegate_SlotProxy_connect__ZN21QAbstractItemDelegate15sizeHintChangedERK11QModelIndex(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QAbstractItemDelegate_SlotProxy_connect__ZN21QAbstractItemDelegate10commitDataEP7QWidget(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QAbstractItemDelegate)=1 #[derive(Default)] pub struct QAbstractItemDelegate { qbase: QObject, pub qclsinst: u64 /* *mut c_void*/, pub _closeEditor: QAbstractItemDelegate_closeEditor_signal, pub _commitData: QAbstractItemDelegate_commitData_signal, pub _sizeHintChanged: QAbstractItemDelegate_sizeHintChanged_signal, } impl /*struct*/ QAbstractItemDelegate { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QAbstractItemDelegate { return QAbstractItemDelegate{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QAbstractItemDelegate { type Target = QObject; fn deref(&self) -> &QObject { return & self.qbase; } } impl AsRef<QObject> for QAbstractItemDelegate { fn as_ref(& self) -> & QObject { return & self.qbase; } } // proto: QVector<int> QAbstractItemDelegate::paintingRoles(); impl /*struct*/ QAbstractItemDelegate { pub fn paintingRoles<RetType, T: QAbstractItemDelegate_paintingRoles<RetType>>(& self, overload_args: T) -> RetType { return overload_args.paintingRoles(self); // return 1; } } pub trait QAbstractItemDelegate_paintingRoles<RetType> { fn paintingRoles(self , rsthis: & QAbstractItemDelegate) -> RetType; } // proto: QVector<int> QAbstractItemDelegate::paintingRoles(); impl<'a> /*trait*/ QAbstractItemDelegate_paintingRoles<u64> for () { fn paintingRoles(self , rsthis: & QAbstractItemDelegate) -> u64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK21QAbstractItemDelegate13paintingRolesEv()}; let mut ret = unsafe {C_ZNK21QAbstractItemDelegate13paintingRolesEv(rsthis.qclsinst)}; return ret as u64; // 5 // return 1; } } // proto: const QMetaObject * QAbstractItemDelegate::metaObject(); impl /*struct*/ QAbstractItemDelegate { pub fn metaObject<RetType, T: QAbstractItemDelegate_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QAbstractItemDelegate_metaObject<RetType> { fn metaObject(self , rsthis: & QAbstractItemDelegate) -> RetType; } // proto: const QMetaObject * QAbstractItemDelegate::metaObject(); impl<'a> /*trait*/ QAbstractItemDelegate_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QAbstractItemDelegate) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK21QAbstractItemDelegate10metaObjectEv()}; let mut ret = unsafe {C_ZNK21QAbstractItemDelegate10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QAbstractItemDelegate::updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index); impl /*struct*/ QAbstractItemDelegate { pub fn updateEditorGeometry<RetType, T: QAbstractItemDelegate_updateEditorGeometry<RetType>>(& self, overload_args: T) -> RetType { return overload_args.updateEditorGeometry(self); // return 1; } } pub trait QAbstractItemDelegate_updateEditorGeometry<RetType> { fn updateEditorGeometry(self , rsthis: & QAbstractItemDelegate) -> RetType; } // proto: void QAbstractItemDelegate::updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index); impl<'a> /*trait*/ QAbstractItemDelegate_updateEditorGeometry<()> for (&'a QWidget, &'a QStyleOptionViewItem, &'a QModelIndex) { fn updateEditorGeometry(self , rsthis: & QAbstractItemDelegate) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK21QAbstractItemDelegate20updateEditorGeometryEP7QWidgetRK20QStyleOptionViewItemRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; unsafe {C_ZNK21QAbstractItemDelegate20updateEditorGeometryEP7QWidgetRK20QStyleOptionViewItemRK11QModelIndex(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: void QAbstractItemDelegate::setEditorData(QWidget * editor, const QModelIndex & index); impl /*struct*/ QAbstractItemDelegate { pub fn setEditorData<RetType, T: QAbstractItemDelegate_setEditorData<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setEditorData(self); // return 1; } } pub trait QAbstractItemDelegate_setEditorData<RetType> { fn setEditorData(self , rsthis: & QAbstractItemDelegate) -> RetType; } // proto: void QAbstractItemDelegate::setEditorData(QWidget * editor, const QModelIndex & index); impl<'a> /*trait*/ QAbstractItemDelegate_setEditorData<()> for (&'a QWidget, &'a QModelIndex) { fn setEditorData(self , rsthis: & QAbstractItemDelegate) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK21QAbstractItemDelegate13setEditorDataEP7QWidgetRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZNK21QAbstractItemDelegate13setEditorDataEP7QWidgetRK11QModelIndex(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QAbstractItemDelegate::QAbstractItemDelegate(QObject * parent); impl /*struct*/ QAbstractItemDelegate { pub fn new<T: QAbstractItemDelegate_new>(value: T) -> QAbstractItemDelegate { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QAbstractItemDelegate_new { fn new(self) -> QAbstractItemDelegate; } // proto: void QAbstractItemDelegate::QAbstractItemDelegate(QObject * parent); impl<'a> /*trait*/ QAbstractItemDelegate_new for (Option<&'a QObject>) { fn new(self) -> QAbstractItemDelegate { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN21QAbstractItemDelegateC2EP7QObject()}; let ctysz: c_int = unsafe{QAbstractItemDelegate_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN21QAbstractItemDelegateC2EP7QObject(arg0)}; let rsthis = QAbstractItemDelegate{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QWidget * QAbstractItemDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index); impl /*struct*/ QAbstractItemDelegate { pub fn createEditor<RetType, T: QAbstractItemDelegate_createEditor<RetType>>(& self, overload_args: T) -> RetType { return overload_args.createEditor(self); // return 1; } } pub trait QAbstractItemDelegate_createEditor<RetType> { fn createEditor(self , rsthis: & QAbstractItemDelegate) -> RetType; } // proto: QWidget * QAbstractItemDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index); impl<'a> /*trait*/ QAbstractItemDelegate_createEditor<QWidget> for (&'a QWidget, &'a QStyleOptionViewItem, &'a QModelIndex) { fn createEditor(self , rsthis: & QAbstractItemDelegate) -> QWidget { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK21QAbstractItemDelegate12createEditorEP7QWidgetRK20QStyleOptionViewItemRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK21QAbstractItemDelegate12createEditorEP7QWidgetRK20QStyleOptionViewItemRK11QModelIndex(rsthis.qclsinst, arg0, arg1, arg2)}; let mut ret1 = QWidget::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QAbstractItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index); impl /*struct*/ QAbstractItemDelegate { pub fn paint<RetType, T: QAbstractItemDelegate_paint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.paint(self); // return 1; } } pub trait QAbstractItemDelegate_paint<RetType> { fn paint(self , rsthis: & QAbstractItemDelegate) -> RetType; } // proto: void QAbstractItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index); impl<'a> /*trait*/ QAbstractItemDelegate_paint<()> for (&'a QPainter, &'a QStyleOptionViewItem, &'a QModelIndex) { fn paint(self , rsthis: & QAbstractItemDelegate) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK21QAbstractItemDelegate5paintEP8QPainterRK20QStyleOptionViewItemRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; unsafe {C_ZNK21QAbstractItemDelegate5paintEP8QPainterRK20QStyleOptionViewItemRK11QModelIndex(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: QSize QAbstractItemDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index); impl /*struct*/ QAbstractItemDelegate { pub fn sizeHint<RetType, T: QAbstractItemDelegate_sizeHint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.sizeHint(self); // return 1; } } pub trait QAbstractItemDelegate_sizeHint<RetType> { fn sizeHint(self , rsthis: & QAbstractItemDelegate) -> RetType; } // proto: QSize QAbstractItemDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index); impl<'a> /*trait*/ QAbstractItemDelegate_sizeHint<QSize> for (&'a QStyleOptionViewItem, &'a QModelIndex) { fn sizeHint(self , rsthis: & QAbstractItemDelegate) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK21QAbstractItemDelegate8sizeHintERK20QStyleOptionViewItemRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK21QAbstractItemDelegate8sizeHintERK20QStyleOptionViewItemRK11QModelIndex(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QAbstractItemDelegate::editorEvent(QEvent * event, QAbstractItemModel * model, const QStyleOptionViewItem & option, const QModelIndex & index); impl /*struct*/ QAbstractItemDelegate { pub fn editorEvent<RetType, T: QAbstractItemDelegate_editorEvent<RetType>>(& self, overload_args: T) -> RetType { return overload_args.editorEvent(self); // return 1; } } pub trait QAbstractItemDelegate_editorEvent<RetType> { fn editorEvent(self , rsthis: & QAbstractItemDelegate) -> RetType; } // proto: bool QAbstractItemDelegate::editorEvent(QEvent * event, QAbstractItemModel * model, const QStyleOptionViewItem & option, const QModelIndex & index); impl<'a> /*trait*/ QAbstractItemDelegate_editorEvent<i8> for (&'a QEvent, &'a QAbstractItemModel, &'a QStyleOptionViewItem, &'a QModelIndex) { fn editorEvent(self , rsthis: & QAbstractItemDelegate) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN21QAbstractItemDelegate11editorEventEP6QEventP18QAbstractItemModelRK20QStyleOptionViewItemRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; let arg3 = self.3.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN21QAbstractItemDelegate11editorEventEP6QEventP18QAbstractItemModelRK20QStyleOptionViewItemRK11QModelIndex(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; return ret as i8; // 1 // return 1; } } // proto: bool QAbstractItemDelegate::helpEvent(QHelpEvent * event, QAbstractItemView * view, const QStyleOptionViewItem & option, const QModelIndex & index); impl /*struct*/ QAbstractItemDelegate { pub fn helpEvent<RetType, T: QAbstractItemDelegate_helpEvent<RetType>>(& self, overload_args: T) -> RetType { return overload_args.helpEvent(self); // return 1; } } pub trait QAbstractItemDelegate_helpEvent<RetType> { fn helpEvent(self , rsthis: & QAbstractItemDelegate) -> RetType; } // proto: bool QAbstractItemDelegate::helpEvent(QHelpEvent * event, QAbstractItemView * view, const QStyleOptionViewItem & option, const QModelIndex & index); impl<'a> /*trait*/ QAbstractItemDelegate_helpEvent<i8> for (&'a QHelpEvent, &'a QAbstractItemView, &'a QStyleOptionViewItem, &'a QModelIndex) { fn helpEvent(self , rsthis: & QAbstractItemDelegate) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN21QAbstractItemDelegate9helpEventEP10QHelpEventP17QAbstractItemViewRK20QStyleOptionViewItemRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; let arg3 = self.3.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN21QAbstractItemDelegate9helpEventEP10QHelpEventP17QAbstractItemViewRK20QStyleOptionViewItemRK11QModelIndex(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; return ret as i8; // 1 // return 1; } } // proto: void QAbstractItemDelegate::~QAbstractItemDelegate(); impl /*struct*/ QAbstractItemDelegate { pub fn free<RetType, T: QAbstractItemDelegate_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QAbstractItemDelegate_free<RetType> { fn free(self , rsthis: & QAbstractItemDelegate) -> RetType; } // proto: void QAbstractItemDelegate::~QAbstractItemDelegate(); impl<'a> /*trait*/ QAbstractItemDelegate_free<()> for () { fn free(self , rsthis: & QAbstractItemDelegate) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN21QAbstractItemDelegateD2Ev()}; unsafe {C_ZN21QAbstractItemDelegateD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QAbstractItemDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index); impl /*struct*/ QAbstractItemDelegate { pub fn setModelData<RetType, T: QAbstractItemDelegate_setModelData<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setModelData(self); // return 1; } } pub trait QAbstractItemDelegate_setModelData<RetType> { fn setModelData(self , rsthis: & QAbstractItemDelegate) -> RetType; } // proto: void QAbstractItemDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index); impl<'a> /*trait*/ QAbstractItemDelegate_setModelData<()> for (&'a QWidget, &'a QAbstractItemModel, &'a QModelIndex) { fn setModelData(self , rsthis: & QAbstractItemDelegate) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK21QAbstractItemDelegate12setModelDataEP7QWidgetP18QAbstractItemModelRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; unsafe {C_ZNK21QAbstractItemDelegate12setModelDataEP7QWidgetP18QAbstractItemModelRK11QModelIndex(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: void QAbstractItemDelegate::destroyEditor(QWidget * editor, const QModelIndex & index); impl /*struct*/ QAbstractItemDelegate { pub fn destroyEditor<RetType, T: QAbstractItemDelegate_destroyEditor<RetType>>(& self, overload_args: T) -> RetType { return overload_args.destroyEditor(self); // return 1; } } pub trait QAbstractItemDelegate_destroyEditor<RetType> { fn destroyEditor(self , rsthis: & QAbstractItemDelegate) -> RetType; } // proto: void QAbstractItemDelegate::destroyEditor(QWidget * editor, const QModelIndex & index); impl<'a> /*trait*/ QAbstractItemDelegate_destroyEditor<()> for (&'a QWidget, &'a QModelIndex) { fn destroyEditor(self , rsthis: & QAbstractItemDelegate) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK21QAbstractItemDelegate13destroyEditorEP7QWidgetRK11QModelIndex()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZNK21QAbstractItemDelegate13destroyEditorEP7QWidgetRK11QModelIndex(rsthis.qclsinst, arg0, arg1)}; // return 1; } } #[derive(Default)] // for QAbstractItemDelegate_closeEditor pub struct QAbstractItemDelegate_closeEditor_signal{poi:u64} impl /* struct */ QAbstractItemDelegate { pub fn closeEditor(&self) -> QAbstractItemDelegate_closeEditor_signal { return QAbstractItemDelegate_closeEditor_signal{poi:self.qclsinst}; } } impl /* struct */ QAbstractItemDelegate_closeEditor_signal { pub fn connect<T: QAbstractItemDelegate_closeEditor_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QAbstractItemDelegate_closeEditor_signal_connect { fn connect(self, sigthis: QAbstractItemDelegate_closeEditor_signal); } #[derive(Default)] // for QAbstractItemDelegate_commitData pub struct QAbstractItemDelegate_commitData_signal{poi:u64} impl /* struct */ QAbstractItemDelegate { pub fn commitData(&self) -> QAbstractItemDelegate_commitData_signal { return QAbstractItemDelegate_commitData_signal{poi:self.qclsinst}; } } impl /* struct */ QAbstractItemDelegate_commitData_signal { pub fn connect<T: QAbstractItemDelegate_commitData_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QAbstractItemDelegate_commitData_signal_connect { fn connect(self, sigthis: QAbstractItemDelegate_commitData_signal); } #[derive(Default)] // for QAbstractItemDelegate_sizeHintChanged pub struct QAbstractItemDelegate_sizeHintChanged_signal{poi:u64} impl /* struct */ QAbstractItemDelegate { pub fn sizeHintChanged(&self) -> QAbstractItemDelegate_sizeHintChanged_signal { return QAbstractItemDelegate_sizeHintChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QAbstractItemDelegate_sizeHintChanged_signal { pub fn connect<T: QAbstractItemDelegate_sizeHintChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QAbstractItemDelegate_sizeHintChanged_signal_connect { fn connect(self, sigthis: QAbstractItemDelegate_sizeHintChanged_signal); } // sizeHintChanged(const class QModelIndex &) extern fn QAbstractItemDelegate_sizeHintChanged_signal_connect_cb_0(rsfptr:fn(QModelIndex), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QModelIndex::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QAbstractItemDelegate_sizeHintChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QModelIndex)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QModelIndex::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QAbstractItemDelegate_sizeHintChanged_signal_connect for fn(QModelIndex) { fn connect(self, sigthis: QAbstractItemDelegate_sizeHintChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QAbstractItemDelegate_sizeHintChanged_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QAbstractItemDelegate_SlotProxy_connect__ZN21QAbstractItemDelegate15sizeHintChangedERK11QModelIndex(arg0, arg1, arg2)}; } } impl /* trait */ QAbstractItemDelegate_sizeHintChanged_signal_connect for Box<Fn(QModelIndex)> { fn connect(self, sigthis: QAbstractItemDelegate_sizeHintChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QAbstractItemDelegate_sizeHintChanged_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QAbstractItemDelegate_SlotProxy_connect__ZN21QAbstractItemDelegate15sizeHintChangedERK11QModelIndex(arg0, arg1, arg2)}; } } // commitData(class QWidget *) extern fn QAbstractItemDelegate_commitData_signal_connect_cb_1(rsfptr:fn(QWidget), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QWidget::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QAbstractItemDelegate_commitData_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn(QWidget)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QWidget::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QAbstractItemDelegate_commitData_signal_connect for fn(QWidget) { fn connect(self, sigthis: QAbstractItemDelegate_commitData_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QAbstractItemDelegate_commitData_signal_connect_cb_1 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QAbstractItemDelegate_SlotProxy_connect__ZN21QAbstractItemDelegate10commitDataEP7QWidget(arg0, arg1, arg2)}; } } impl /* trait */ QAbstractItemDelegate_commitData_signal_connect for Box<Fn(QWidget)> { fn connect(self, sigthis: QAbstractItemDelegate_commitData_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QAbstractItemDelegate_commitData_signal_connect_cb_box_1 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QAbstractItemDelegate_SlotProxy_connect__ZN21QAbstractItemDelegate10commitDataEP7QWidget(arg0, arg1, arg2)}; } } // <= body block end
use std::io::Error; use std::path::PathBuf; use crate::io; use crate::consts::{ASSETS_DIR, DRIVE_NAME, TMP_DIR}; pub fn create_drive(drive_name: &str) -> Result<(), Error> { let drive_src = PathBuf::from(format!("{}/{}.ext4", ASSETS_DIR, DRIVE_NAME)); let drive_dest = PathBuf::from(format!("{}/{}.ext4", TMP_DIR, drive_name)); io::copy_file(drive_src, drive_dest) } pub fn delete_drive(drive_name: &str) -> Result<(), Error> { let drive_dest = PathBuf::from(format!("{}/{}.ext4", TMP_DIR, drive_name)); io::delete_file(drive_dest) }
// Implementasi trait `ToString` untuk struk `Person` untuk dapat menggunakan fungsi `to_string` // struct Person { name: String, age: u8, } impl ToString for Person { fn to_string(&self) -> String { format!("Nama saya {} dan umur saya {}", self.name, self.age) } } fn main() { let agus = Person { name: String::from("Agus"), age: 35 }; println!("{}", agus.to_string()); }
use super::root::*; use color::Color; use sided_mask::*; use mask::*; use side::*; use mask::masks::*; impl Position { pub fn pseudo_legal_pawn_moves(&self) -> Mask { if self.active == Color::White { self.pseudo_legal_pawn_moves_of::<White>().0 } else { self.pseudo_legal_pawn_moves_of::<Black>().0 } } pub fn pseudo_legal_pawn_moves_of<S: Side>(&self) -> S::Mask { let pawns = self.board.pawns::<S>(); let empty_squares = !self.board.occupation(); let attacks = pawns.attack(); let non_enp_captures = attacks.filter( self.board.occupation_gen::<S::Opposite>()); let enp_captures = attacks.filter(self.en_passant_take_square_mask::<S>()); let single_pushes = pawns.advance().filter(empty_squares); let double_pushes = single_pushes.advance() .filter(empty_squares & S::DOUBLE_PUSH_RANK_MASK); enp_captures .and(non_enp_captures) .and(single_pushes) .and(double_pushes) } pub fn en_passant_take_square_mask<S: Side>(&self) -> Mask { self.en_passant.map_or(EMPTY, |file| Mask::from_file_rank(file, S::EN_PASSANT_RANK)) } #[allow(unused_variables)] pub fn is_pseudo_legal_pawn_move(&self, from: Mask, to: Mask) -> bool { // captures // single push // double push // en-passant true } } #[cfg(test)] mod test { use super::*; #[test] fn generate_pseudo_legal_white_pawn_moves_single_push() { assert_pseudo_legal_pawn_moves( "8/8/8/3P4/8/8/8/8 w KQkq - 0 1", D6 ); } #[test] fn generate_pseudo_legal_white_pawn_moves_take_to_the_left() { assert_pseudo_legal_pawn_moves( "8/8/2pp4/3P4/8/8/8/8 w KQkq - 0 1", C6 ); } #[test] fn generate_pseudo_legal_black_pawn_moves_take_to_the_left() { assert_pseudo_legal_pawn_moves( "8/8/3p4/2PP4/8/8/8/8 b KQkq - 0 1", C5 ); } #[test] fn generate_pseudo_legal_white_pawn_moves_take_to_the_right() { assert_pseudo_legal_pawn_moves( "8/8/3pp3/3P4/8/8/8/8 w KQkq - 0 1", E6 ); } #[test] fn generate_pseudo_legal_white_pawn_moves_en_passant() { assert_pseudo_legal_pawn_moves( "8/8/3p4/3P4/8/8/8/8 w KQkq e 0 1", E6 ); } #[test] fn generate_pseudo_legal_white_pawn_moves_double_push() { assert_pseudo_legal_pawn_moves( "8/8/8/8/8/8/3P4/8 w KQkq - 0 1", D3 | D4 ); } #[test] fn generate_pseudo_legal_black_pawn_moves_double_push() { assert_pseudo_legal_pawn_moves( "8/3p4/8/8/8/8/8/8 b KQkq - 0 1", D6 | D5 ); } #[test] fn generate_pseudo_legal_black_pawn_moves_double_push_blocked() { assert_pseudo_legal_pawn_moves( "8/3p4/8/3p4/8/8/8/8 b KQkq - 0 1", D6 | D4 ); } #[test] fn generate_pseudo_legal_black_pawn_moves_double_push_opposed() { assert_pseudo_legal_pawn_moves( "8/3p4/8/3P4/8/8/8/8 b KQkq - 0 1", D6 ); } #[test] fn generate_pseudo_legal_white_pawn_moves_random() { assert_pseudo_legal_pawn_moves( "N4p2/P3P2P/8/8/p1p3kp/1P4P1/Kp4p1/P6P w - - 0 1", E8 |F8|H8|A4|B4|C4|H4|B2|G2|H2 ); } fn assert_pseudo_legal_pawn_moves(fen: &str, expected: Mask) { assert_eq!(Position::parse(fen).pseudo_legal_pawn_moves(), expected); } }
use utils::ipoint::IPoint; use state::world::World; use design::blueprint::Blueprint; use player::player::PlayerData; use state::object::Pixel; use state::object::Object; use serde_json; use objects::player::Player; use print_raw; use print; pub struct GameState { pub game: World, pub player: PlayerData } impl GameState { pub fn new(size: IPoint) -> GameState { let mut game = World::new(); let idx = game.next_id(); let level = Blueprint::example(size).level_from_blueprint(&mut game); let empty_tile = level.tiles().iter().filter(|(_p, tile)| !tile.iter().any(|e| e.object().is_blocking()) ).next(); let empty_pos = match empty_tile { None => panic!(), Some(p) => p.0 }; level.add_entity(Box::new(Player::new(idx)), *empty_pos); GameState { game, player: PlayerData::new(idx) } } pub fn process_key(&mut self, string: &str) { //print("press key".to_string()); self.player.process_key(&mut self.game, string); } pub fn get_view(&mut self) -> String { let empty = &Pixel::empty(); let view = self.player.build_view(&self.game); let mut result = Vec::new(); for y in 0..view.size.y { let mut row = Vec::new(); for x in 0..view.size.x { row.push(view.tiles.get(&IPoint{x, y}).unwrap_or(empty)); } result.push(row); } serde_json::to_string(&result).unwrap() } pub fn get_messages(&mut self, count: i32) -> String { let messages = self.player.get_messages(); let start_idx = (messages.len() as i32 - count).max(0) as usize; let part = &messages[start_idx..]; serde_json::to_string(part).unwrap() } }
use super::helpers::deserealize_currency; use serde::Deserialize; /// Информация о подписке /// https://developers.xsolla.com/ru/api/v2/getting-started/#api_param_webhooks_payment_purchase_subscription #[derive(Debug, Deserialize)] pub struct Subscription { pub plan_id: String, pub subscription_id: String, pub product_id: String, pub tags: Vec<String>, pub date_create: chrono::DateTime<chrono::Utc>, pub date_next_charge: chrono::DateTime<chrono::Utc>, #[serde(deserialize_with = "deserealize_currency")] pub currency: &'static iso4217::CurrencyCode, pub amount: f32, }
use utilities::prelude::*; use crate::allocator::{block::Block, device_allocator::DeviceAllocator}; use crate::impl_vk_handle; use crate::loader::*; use crate::prelude::*; use crate::sampler_manager::SamplerManager; use crate::Extensions; use std::cmp::min; use std::fmt; use std::mem::{size_of, MaybeUninit}; use std::ptr; use std::sync::{Arc, Mutex}; use std::time::Duration; use core::ffi::c_void; Extensions!(DeviceExtensions, { (nv_ray_tracing, "VK_NV_ray_tracing"), (amd_rasterization_order, "VK_AMD_rasterization_order"), (maintenance3, "VK_KHR_maintenance3"), (descriptor_indexing, "VK_EXT_descriptor_indexing"), (memory_requirements2, "VK_KHR_get_memory_requirements2"), (swapchain, "VK_KHR_swapchain"), (memory_budget, "VK_EXT_memory_budget"), (memory_priority, "VK_EXT_memory_priority"), (debug_marker, "VK_EXT_debug_marker"), }); pub use vulkan_sys::prelude::VkPhysicalDeviceFeatures as DeviceFeatures; pub struct MemoryHeap { pub usage: VkDeviceSize, pub budget: VkDeviceSize, } pub struct Device { device_functions: DeviceFunctions, device_wsi_functions: DeviceWSIFunctions, maintenance3_functions: Maintenance3Functions, nv_ray_tracing_functions: NVRayTracingFunctions, enabled_extensions: DeviceExtensions, physical_device: Arc<PhysicalDevice>, device: VkDevice, memory_allocator: Mutex<DeviceAllocator>, sampler_manager: Mutex<SamplerManager>, } impl Device { pub fn new( physical_device: Arc<PhysicalDevice>, extensions: DeviceExtensions, queue_infos: &[VkDeviceQueueCreateInfo], requested_device_features: DeviceFeatures, ) -> VerboseResult<Arc<Device>> { let device_extensions = physical_device.extensions(); let mut checked_extensions = Vec::new(); let extension_list = extensions.as_list(); for extension in extension_list { for ext_prop in device_extensions { if *ext_prop == extension { checked_extensions.push(extension); break; } } } let names = VkNames::new(checked_extensions.as_slice()); println!("\nenabled device extensions ({}):", names.len()); for extension_name in names.iter() { println!("\t- {:?}", extension_name); } println!(); if !requested_device_features.is_subset_of(&physical_device.features()) { create_error!("Device does not support requested features"); } let mut device_ci = VkDeviceCreateInfo::new( VK_DEVICE_CREATE_NULL_BIT, queue_infos, &names, &requested_device_features, ); let descriptor_indexing_features = physical_device.descriptor_indexing_features(); device_ci.chain(&descriptor_indexing_features); let instance = physical_device.instance(); let device = instance.create_device(physical_device.vk_handle(), &device_ci)?; let device_functions = load_device( |device, name| instance.get_device_proc_addr_raw(device, name), device, ); let device_wsi_functions = load_device_wsi( |device, name| instance.get_device_proc_addr_raw(device, name), device, ); let nv_ray_tracing_functions = load_nv_ray_tracing( |device, name| instance.get_device_proc_addr_raw(device, name), device, ); let maintenance3_functions = load_maintenance3( |device, name| instance.get_device_proc_addr_raw(device, name), device, ); let enabled_extensions = DeviceExtensions::from_list(&checked_extensions); if let Err(missing_extensions) = extensions.check_availability(&enabled_extensions) { for m in missing_extensions { println!("{}", m); } } Ok(Arc::new(Device { device_functions, device_wsi_functions, maintenance3_functions, nv_ray_tracing_functions, enabled_extensions, physical_device, device, // request chunks in 100 MiB memory_allocator: Mutex::new(DeviceAllocator::new(104857600)), sampler_manager: SamplerManager::new(), })) } pub fn get_queue( device: &Arc<Device>, queue_family_index: u32, queue_index: u32, ) -> Arc<Mutex<Queue>> { Queue::new( device.clone(), device.get_device_queue(queue_family_index, queue_index), queue_family_index, queue_index, ) } pub fn memory_type_from_properties( &self, device_reqs: impl Into<VkMemoryPropertyFlagBits>, host_reqs: impl Into<VkMemoryPropertyFlagBits>, ) -> VerboseResult<u32> { let memory_types = self.physical_device().memory_properties().memory_types(); let device_requirements = device_reqs.into(); let host_requirements = host_reqs.into(); for (i, memory_type) in memory_types.iter().enumerate() { if (device_requirements & (1u32 << i)) != 0 && host_requirements == (memory_type.propertyFlagBits & host_requirements) { return Ok(i as u32); } } create_error!("failed finding device requirements") } pub fn physical_device(&self) -> &Arc<PhysicalDevice> { &self.physical_device } pub fn wait_for_fences( &self, fences: &[&Arc<Fence>], wait_all: bool, timeout: Duration, ) -> VerboseResult<()> { let vkfences: Vec<VkFence> = fences.iter().map(|fence| fence.vk_handle()).collect(); self.device_wait_for_fences(vkfences.as_slice(), wait_all, timeout.as_nanos() as u64)?; Ok(()) } pub fn enabled_extensions(&self) -> &DeviceExtensions { &self.enabled_extensions } pub fn memory_budgets(&self) -> Vec<MemoryHeap> { let phys_dev = self.physical_device(); let (budget, count) = phys_dev .instance() .physical_device_memory_budget(phys_dev.vk_handle()); let mut heaps = Vec::with_capacity(count as usize); let usages = budget.heap_usages(count); let budgets = budget.heap_budgets(count); for i in 0..count { heaps.push(MemoryHeap { usage: usages[i as usize], budget: budgets[i as usize], }) } heaps } pub fn max_supported_sample_count( &self, requested_sample_count: VkSampleCountFlags, ) -> VkSampleCountFlags { let dev_props = self.physical_device.properties(); let phys_counts = min( dev_props.limits.framebufferColorSampleCounts, dev_props.limits.framebufferDepthSampleCounts, ); let counts = min(phys_counts, requested_sample_count.into()); if (counts & VK_SAMPLE_COUNT_64_BIT) != 0 { VK_SAMPLE_COUNT_64_BIT } else if (counts & VK_SAMPLE_COUNT_32_BIT) != 0 { VK_SAMPLE_COUNT_32_BIT } else if (counts & VK_SAMPLE_COUNT_16_BIT) != 0 { VK_SAMPLE_COUNT_16_BIT } else if (counts & VK_SAMPLE_COUNT_8_BIT) != 0 { VK_SAMPLE_COUNT_8_BIT } else if (counts & VK_SAMPLE_COUNT_4_BIT) != 0 { VK_SAMPLE_COUNT_4_BIT } else if (counts & VK_SAMPLE_COUNT_2_BIT) != 0 { VK_SAMPLE_COUNT_2_BIT } else { VK_SAMPLE_COUNT_1_BIT } } } impl_vk_handle!(Device, VkDevice, device); impl fmt::Debug for Device { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Device {{ device: {:#?}, physical_device: {:#?} }}", self.device, self.physical_device ) } } impl Drop for Device { fn drop(&mut self) { unsafe { self.sampler_manager .lock() .expect("failed to lock sampler manager at drop of device") .clear(self); } self.destroy_device(); } } impl Device { pub fn device_proc_addr(&self, name: VkString) -> PFN_vkVoidFunction { self.physical_device .instance() .get_device_proc_addr(self.device, name) } fn destroy_device(&self) { unsafe { self.device_functions .vkDestroyDevice(self.device, ptr::null()); } } fn get_device_queue(&self, queue_family_index: u32, queue_index: u32) -> VkQueue { unsafe { let mut queue = MaybeUninit::uninit(); self.device_functions.vkGetDeviceQueue( self.device, queue_family_index, queue_index, queue.as_mut_ptr(), ); queue.assume_init() } } fn device_wait_for_fences( &self, fences: &[VkFence], wait_all: impl Into<VkBool32>, timeout: u64, ) -> VerboseResult<()> { unsafe { let result = self.device_functions.vkWaitForFences( self.device, fences.len() as u32, fences.as_ptr(), wait_all.into(), timeout, ); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed waiting for fences {:?}", result)) } } } pub fn query_pool_results<T>( &self, query_pool: VkQueryPool, first_query: u32, query_count: u32, data: &mut T, stride: VkDeviceSize, flags: impl Into<VkQueryResultFlagBits>, ) -> VerboseResult<()> { unsafe { let result = self.device_functions.vkGetQueryPoolResults( self.device, query_pool, first_query, query_count, size_of::<T>(), data as *mut T as *mut c_void, stride, flags.into(), ); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed getting query pool results {:?}", result)) } } } pub fn queue_submit( &self, queue: VkQueue, submits: &[VkSubmitInfo], fence: VkFence, ) -> VerboseResult<()> { unsafe { let result = self.device_functions.vkQueueSubmit( queue, submits.len() as u32, submits.as_ptr(), fence, ); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed submitting to queue {:?}", result)) } } } pub fn queue_wait_idle(&self, queue: VkQueue) -> VerboseResult<()> { unsafe { let result = self.device_functions.vkQueueWaitIdle(queue); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed waiting for queue idling {:?}", result)) } } } pub fn create_buffer(&self, create_info: &VkBufferCreateInfo) -> VerboseResult<VkBuffer> { unsafe { let mut buffer = MaybeUninit::uninit(); let result = self.device_functions.vkCreateBuffer( self.device, create_info, ptr::null(), buffer.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(buffer.assume_init()) } else { create_error!(format!("failed creating buffer {:?}", result)) } } } pub fn destroy_buffer(&self, buffer: VkBuffer) { unsafe { self.device_functions .vkDestroyBuffer(self.device, buffer, ptr::null()) }; } pub fn buffer_memory_requirements(&self, buffer: VkBuffer) -> VkMemoryRequirements { unsafe { let mut memory_requirements = MaybeUninit::uninit(); self.device_functions.vkGetBufferMemoryRequirements( self.device, buffer, memory_requirements.as_mut_ptr(), ); memory_requirements.assume_init() } } pub(crate) fn allocate_memory_from_allocator( me: &Arc<Device>, allocation_size: VkDeviceSize, memory_type_index: u32, alignment: VkDeviceSize, ) -> VerboseResult<Block> { me.memory_allocator.lock()?.allocate( me.clone(), allocation_size, memory_type_index, alignment, ) } pub(crate) fn free_memory_from_allocator(&self, block: &Block) -> VerboseResult<()> { self.memory_allocator.lock()?.deallocate(block); Ok(()) } pub fn allocate_memory( &self, allocate_info: &VkMemoryAllocateInfo, ) -> VerboseResult<VkDeviceMemory> { unsafe { let mut memory = MaybeUninit::uninit(); let result = self.device_functions.vkAllocateMemory( self.device, allocate_info, ptr::null(), memory.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(memory.assume_init()) } else { create_error!(format!("failed allocating memory {:?}", result)) } } } pub fn free_memory(&self, memory: VkDeviceMemory) { unsafe { self.device_functions .vkFreeMemory(self.device, memory, ptr::null()) }; } pub(crate) fn map_memory_raw( &self, memory: VkDeviceMemory, offset: VkDeviceSize, size: VkDeviceSize, flags: impl Into<VkMemoryMapFlags>, ) -> VerboseResult<*mut c_void> { unsafe { let mut data = MaybeUninit::uninit(); let result = self.device_functions.vkMapMemory( self.device, memory, offset, size, flags.into(), data.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(data.assume_init()) } else { create_error!(format!("failed mapping memory {:?}", result)) } } } // pub fn map_memory<U: Clone>( // &self, // memory: VkDeviceMemory, // offset: VkDeviceSize, // length: VkDeviceSize, // flags: impl Into<VkMemoryMapFlags>, // ) -> VerboseResult<VkMappedMemory<'_, U>> { // let size = length * size_of::<U>() as VkDeviceSize; // let ptr = self.map_memory_raw(memory, offset, size, flags)?; // let slice = unsafe { slice::from_raw_parts_mut(ptr as *mut U, length as usize) }; // Ok(VkMappedMemory::new(self, memory, slice)) // } pub fn unmap_memory(&self, memory: VkDeviceMemory) { unsafe { self.device_functions.vkUnmapMemory(self.device, memory) }; } pub fn bind_buffer_memory( &self, buffer: VkBuffer, memory: VkDeviceMemory, offset: VkDeviceSize, ) -> VerboseResult<()> { unsafe { let result = self.device_functions .vkBindBufferMemory(self.device, buffer, memory, offset); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed binding buffer to memory {:?}", result)) } } } pub fn create_render_pass( &self, create_info: &VkRenderPassCreateInfo, ) -> VerboseResult<VkRenderPass> { unsafe { let mut render_pass = MaybeUninit::uninit(); let result = self.device_functions.vkCreateRenderPass( self.device, create_info, ptr::null(), render_pass.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(render_pass.assume_init()) } else { create_error!(format!("failed creating render pass {:?}", result)) } } } pub fn destroy_render_pass(&self, render_pass: VkRenderPass) { unsafe { self.device_functions .vkDestroyRenderPass(self.device, render_pass, ptr::null()) }; } pub fn create_image(&self, create_info: &VkImageCreateInfo) -> VerboseResult<VkImage> { unsafe { let mut image = MaybeUninit::uninit(); let result = self.device_functions.vkCreateImage( self.device, create_info, ptr::null(), image.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(image.assume_init()) } else { create_error!(format!("failed creating image {:?}", result)) } } } pub fn destroy_image(&self, image: VkImage) { unsafe { self.device_functions .vkDestroyImage(self.device, image, ptr::null()) }; } pub fn image_subresource_layout( &self, image: VkImage, subresource: &VkImageSubresource, ) -> VkSubresourceLayout { unsafe { let mut subresource_layout = MaybeUninit::uninit(); self.device_functions.vkGetImageSubresourceLayout( self.device, image, subresource, subresource_layout.as_mut_ptr(), ); subresource_layout.assume_init() } } pub fn create_image_view( &self, create_info: &VkImageViewCreateInfo, ) -> VerboseResult<VkImageView> { unsafe { let mut image_view = MaybeUninit::uninit(); let result = self.device_functions.vkCreateImageView( self.device, create_info, ptr::null(), image_view.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(image_view.assume_init()) } else { create_error!(format!("failed creating image view {:?}", result)) } } } pub fn destroy_image_view(&self, image_view: VkImageView) { unsafe { self.device_functions .vkDestroyImageView(self.device, image_view, ptr::null()) }; } pub fn image_memory_requirements(&self, image: VkImage) -> VkMemoryRequirements { unsafe { let mut memory_requirements = MaybeUninit::uninit(); self.device_functions.vkGetImageMemoryRequirements( self.device, image, memory_requirements.as_mut_ptr(), ); memory_requirements.assume_init() } } pub fn image_sparse_memory_requirements( &self, image: VkImage, ) -> Vec<VkSparseImageMemoryRequirements> { let mut count: u32 = 0; unsafe { self.device_functions.vkGetImageSparseMemoryRequirements( self.device, image, &mut count, ptr::null_mut(), ) }; let mut sparse_memory_requirements = Vec::with_capacity(count as usize); unsafe { sparse_memory_requirements.set_len(count as usize) }; unsafe { self.device_functions.vkGetImageSparseMemoryRequirements( self.device, image, &mut count, sparse_memory_requirements.as_mut_ptr(), ) }; sparse_memory_requirements } pub fn bind_image_memory( &self, image: VkImage, memory: VkDeviceMemory, offset: VkDeviceSize, ) -> VerboseResult<()> { unsafe { let result = self.device_functions .vkBindImageMemory(self.device, image, memory, offset); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed binding image to memory {:?}", result)) } } } pub(crate) fn create_sampler_from_manager( &self, create_info: VkSamplerCreateInfo, ) -> VerboseResult<Arc<Sampler>> { self.sampler_manager .lock()? .create_sampler(create_info, self) } pub fn create_sampler(&self, create_info: &VkSamplerCreateInfo) -> VerboseResult<VkSampler> { unsafe { let mut sampler = MaybeUninit::uninit(); let result = self.device_functions.vkCreateSampler( self.device, create_info, ptr::null(), sampler.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(sampler.assume_init()) } else { create_error!(format!("failed creating sampler {:?}", result)) } } } pub fn destroy_sampler(&self, sampler: VkSampler) { unsafe { self.device_functions .vkDestroySampler(self.device, sampler, ptr::null()) }; } pub fn create_buffer_view( &self, create_info: &VkBufferViewCreateInfo, ) -> VerboseResult<VkBufferView> { unsafe { let mut buffer_view = MaybeUninit::uninit(); let result = self.device_functions.vkCreateBufferView( self.device, create_info, ptr::null(), buffer_view.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(buffer_view.assume_init()) } else { create_error!(format!("failed creating buffer view {:?}", result)) } } } pub fn destroy_buffer_view(&self, buffer_view: VkBufferView) { unsafe { self.device_functions .vkDestroyBufferView(self.device, buffer_view, ptr::null()) }; } pub fn create_fence(&self, create_info: &VkFenceCreateInfo) -> VerboseResult<VkFence> { unsafe { let mut fence = MaybeUninit::uninit(); let result = self.device_functions.vkCreateFence( self.device, create_info, ptr::null(), fence.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(fence.assume_init()) } else { create_error!(format!("failed creating fence {:?}", result)) } } } pub fn destroy_fence(&self, fence: VkFence) { unsafe { self.device_functions .vkDestroyFence(self.device, fence, ptr::null()) }; } pub fn reset_fences(&self, fences: &[VkFence]) -> VerboseResult<()> { unsafe { let result = self.device_functions.vkResetFences( self.device, fences.len() as u32, fences.as_ptr(), ); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed resetting fences {:?}", result)) } } } pub fn create_semaphore( &self, create_info: &VkSemaphoreCreateInfo, ) -> VerboseResult<VkSemaphore> { unsafe { let mut semaphore = MaybeUninit::uninit(); let result = self.device_functions.vkCreateSemaphore( self.device, create_info, ptr::null(), semaphore.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(semaphore.assume_init()) } else { create_error!(format!("failed creating semaphore {:?}", result)) } } } pub fn destroy_semaphore(&self, semaphore: VkSemaphore) { unsafe { self.device_functions .vkDestroySemaphore(self.device, semaphore, ptr::null()) }; } pub fn create_shader_module( &self, create_info: &VkShaderModuleCreateInfo, ) -> VerboseResult<VkShaderModule> { unsafe { let mut shader_module = MaybeUninit::uninit(); let result = self.device_functions.vkCreateShaderModule( self.device, create_info, ptr::null(), shader_module.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(shader_module.assume_init()) } else { create_error!(format!("failed creating shader module {:?}", result)) } } } pub fn destroy_shader_module(&self, shader_module: VkShaderModule) { unsafe { self.device_functions .vkDestroyShaderModule(self.device, shader_module, ptr::null()) }; } pub fn create_descriptor_pool( &self, create_info: &VkDescriptorPoolCreateInfo, ) -> VerboseResult<VkDescriptorPool> { unsafe { let mut descriptor_pool = MaybeUninit::uninit(); let result = self.device_functions.vkCreateDescriptorPool( self.device, create_info, ptr::null(), descriptor_pool.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(descriptor_pool.assume_init()) } else { create_error!(format!("failed creating descriptor pool {:?}", result)) } } } pub fn destroy_descriptor_pool(&self, descriptor_pool: VkDescriptorPool) { unsafe { self.device_functions .vkDestroyDescriptorPool(self.device, descriptor_pool, ptr::null()) }; } pub fn reset_descriptor_pool<T>( &self, descriptor_pool: VkDescriptorPool, flags: T, ) -> VerboseResult<()> where T: Into<VkDescriptorPoolResetFlags>, { unsafe { let result = self.device_functions.vkResetDescriptorPool( self.device, descriptor_pool, flags.into(), ); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed resetting descriptor pool {:?}", result)) } } } pub fn create_descriptor_set_layout( &self, create_info: &VkDescriptorSetLayoutCreateInfo, ) -> VerboseResult<VkDescriptorSetLayout> { unsafe { let mut descriptor_set_layout = MaybeUninit::uninit(); let result = self.device_functions.vkCreateDescriptorSetLayout( self.device, create_info, ptr::null(), descriptor_set_layout.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(descriptor_set_layout.assume_init()) } else { create_error!(format!( "failed creating descriptor set layout {:?}", result )) } } } pub fn destroy_descriptor_set_layout(&self, descriptor_set_layout: VkDescriptorSetLayout) { unsafe { self.device_functions.vkDestroyDescriptorSetLayout( self.device, descriptor_set_layout, ptr::null(), ) }; } pub fn allocate_descriptor_sets<'a>( &self, allocate_info: &VkDescriptorSetAllocateInfo<'a>, ) -> VerboseResult<Vec<VkDescriptorSet>> { unsafe { let count = allocate_info.descriptorSetCount as usize; let mut descriptor_sets = Vec::with_capacity(count); descriptor_sets.set_len(count); let result = self.device_functions.vkAllocateDescriptorSets( self.device, allocate_info, descriptor_sets.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(descriptor_sets) } else { create_error!(format!("failed allocating descriptor sets {:?}", result)) } } } pub fn free_descriptor_sets( &self, descriptor_pool: VkDescriptorPool, descriptor_sets: &[VkDescriptorSet], ) -> VerboseResult<()> { unsafe { let result = self.device_functions.vkFreeDescriptorSets( self.device, descriptor_pool, descriptor_sets.len() as u32, descriptor_sets.as_ptr(), ); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed freeing descriptor sets {:?}", result)) } } } pub fn update_descriptor_sets( &self, writes: &[VkWriteDescriptorSet], copies: &[VkCopyDescriptorSet], ) { unsafe { self.device_functions.vkUpdateDescriptorSets( self.device, writes.len() as u32, writes.as_ptr(), copies.len() as u32, copies.as_ptr(), ); } } pub fn create_event(&self, create_info: &VkEventCreateInfo) -> VerboseResult<VkEvent> { unsafe { let mut event = MaybeUninit::uninit(); let result = self.device_functions.vkCreateEvent( self.device, create_info, ptr::null(), event.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(event.assume_init()) } else { create_error!(format!("failed creating event {:?}", result)) } } } pub fn destroy_event(&self, event: VkEvent) { unsafe { self.device_functions .vkDestroyEvent(self.device, event, ptr::null()) }; } pub fn event_status(&self, event: VkEvent) -> VerboseResult<()> { unsafe { let result = self.device_functions.vkGetEventStatus(self.device, event); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed getting event status {:?}", result)) } } } pub fn set_event(&self, event: VkEvent) -> VerboseResult<()> { unsafe { let result = self.device_functions.vkSetEvent(self.device, event); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed setting event {:?}", result)) } } } pub fn reset_event(&self, event: VkEvent) -> VerboseResult<()> { unsafe { let result = self.device_functions.vkResetEvent(self.device, event); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed resetting event {:?}", result)) } } } pub fn create_command_pool( &self, create_info: &VkCommandPoolCreateInfo, ) -> VerboseResult<VkCommandPool> { unsafe { let mut command_pool = MaybeUninit::uninit(); let result = self.device_functions.vkCreateCommandPool( self.device, create_info, ptr::null(), command_pool.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(command_pool.assume_init()) } else { create_error!(format!("failed creating command pool {:?}", result)) } } } pub fn destroy_command_pool(&self, command_pool: VkCommandPool) { unsafe { self.device_functions .vkDestroyCommandPool(self.device, command_pool, ptr::null()) }; } pub fn reset_command_pool<T>(&self, command_pool: VkCommandPool, flags: T) -> VerboseResult<()> where T: Into<VkCommandPoolResetFlags>, { unsafe { let result = self.device_functions .vkResetCommandPool(self.device, command_pool, flags.into()); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed resetting command pool {:?}", result)) } } } pub fn trim_command_pool<T>(&self, command_pool: VkCommandPool, flags: T) where T: Into<VkCommandPoolTrimFlags>, { unsafe { self.device_functions .vkTrimCommandPool(self.device, command_pool, flags.into()); } } pub fn create_framebuffer( &self, create_info: &VkFramebufferCreateInfo, ) -> VerboseResult<VkFramebuffer> { unsafe { let mut framebuffer = MaybeUninit::uninit(); let result = self.device_functions.vkCreateFramebuffer( self.device, create_info, ptr::null(), framebuffer.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(framebuffer.assume_init()) } else { create_error!(format!("failed creating framebuffer {:?}", result)) } } } pub fn destroy_framebuffer(&self, framebuffer: VkFramebuffer) { unsafe { self.device_functions .vkDestroyFramebuffer(self.device, framebuffer, ptr::null()) }; } pub fn allocate_command_buffers( &self, allocate_info: &VkCommandBufferAllocateInfo, ) -> VerboseResult<Vec<VkCommandBuffer>> { unsafe { let count = allocate_info.commandBufferCount as usize; let mut command_buffers = Vec::with_capacity(count); command_buffers.set_len(count); let result = self.device_functions.vkAllocateCommandBuffers( self.device, allocate_info, command_buffers.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(command_buffers) } else { create_error!(format!("failed allocating commandbuffers {:?}", result)) } } } pub fn free_command_buffers( &self, command_pool: VkCommandPool, command_buffers: &[VkCommandBuffer], ) { unsafe { self.device_functions.vkFreeCommandBuffers( self.device, command_pool, command_buffers.len() as u32, command_buffers.as_ptr(), ) } } pub fn create_query_pool( &self, create_info: &VkQueryPoolCreateInfo, ) -> VerboseResult<VkQueryPool> { unsafe { let mut query_pool = MaybeUninit::uninit(); let result = self.device_functions.vkCreateQueryPool( self.device, create_info, ptr::null(), query_pool.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(query_pool.assume_init()) } else { create_error!(format!("failed creating query pool {:?}", result)) } } } pub fn destroy_query_pool(&self, query_pool: VkQueryPool) { unsafe { self.device_functions .vkDestroyQueryPool(self.device, query_pool, ptr::null()) }; } pub fn create_pipeline_cache( &self, create_info: &VkPipelineCacheCreateInfo, ) -> VerboseResult<VkPipelineCache> { unsafe { let mut pipeline_cache = MaybeUninit::uninit(); let result = self.device_functions.vkCreatePipelineCache( self.device, create_info, ptr::null(), pipeline_cache.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(pipeline_cache.assume_init()) } else { create_error!(format!("failed creating pipeline cache {:?}", result)) } } } pub fn destroy_pipeline_cache(&self, pipeline_cache: VkPipelineCache) { unsafe { self.device_functions .vkDestroyPipelineCache(self.device, pipeline_cache, ptr::null()) }; } pub fn pipeline_cache_data<T>(&self, pipeline_cache: VkPipelineCache) -> VerboseResult<T> { let mut count = 0; let result = unsafe { self.device_functions.vkGetPipelineCacheData( self.device, pipeline_cache, &mut count, ptr::null_mut(), ) }; if result != VK_SUCCESS { create_error!(format!("failed getting pipeline cache data {:?}", result)) } if count != size_of::<T>() { create_error!(format!("failed getting pipeline cache data {:?}", result)) } unsafe { let mut data = MaybeUninit::<T>::uninit(); let result = self.device_functions.vkGetPipelineCacheData( self.device, pipeline_cache, &mut count, data.as_mut_ptr() as *mut c_void, ); if result == VK_SUCCESS { Ok(data.assume_init()) } else { create_error!(format!("failed getting pipeline cache data {:?}", result)) } } } pub fn merge_pipeline_cache( &self, sources: &[VkPipelineCache], destination: VkPipelineCache, ) -> VerboseResult<()> { unsafe { let result = self.device_functions.vkMergePipelineCaches( self.device, destination, sources.len() as u32, sources.as_ptr(), ); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed merging pipeline caches {:?}", result)) } } } pub fn create_pipeline_layout( &self, create_info: &VkPipelineLayoutCreateInfo, ) -> VerboseResult<VkPipelineLayout> { unsafe { let mut pipeline_layout = MaybeUninit::uninit(); let result = self.device_functions.vkCreatePipelineLayout( self.device, create_info, ptr::null(), pipeline_layout.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(pipeline_layout.assume_init()) } else { create_error!(format!("failed creating pipeline layout {:?}", result)) } } } pub fn destroy_pipeline_layout(&self, pipeline_layout: VkPipelineLayout) { unsafe { self.device_functions .vkDestroyPipelineLayout(self.device, pipeline_layout, ptr::null()) }; } pub fn create_graphics_pipelines( &self, pipeline_cache: Option<VkPipelineCache>, create_infos: &[VkGraphicsPipelineCreateInfo], ) -> VerboseResult<Vec<VkPipeline>> { unsafe { let count = create_infos.len() as usize; let mut pipelines = Vec::with_capacity(count); pipelines.set_len(count); let result = self.device_functions.vkCreateGraphicsPipelines( self.device, match pipeline_cache { Some(cache) => cache, None => VkPipelineCache::NULL_HANDLE, }, create_infos.len() as u32, create_infos.as_ptr(), ptr::null(), pipelines.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(pipelines) } else { create_error!(format!("failed creating graphic pipelines {:?}", result)) } } } pub fn create_compute_pipelines( &self, pipeline_cache: Option<VkPipelineCache>, create_infos: &[VkComputePipelineCreateInfo], ) -> VerboseResult<Vec<VkPipeline>> { unsafe { let count = create_infos.len() as usize; let mut pipelines = Vec::with_capacity(count); pipelines.set_len(count); let result = self.device_functions.vkCreateComputePipelines( self.device, match pipeline_cache { Some(cache) => cache, None => VkPipelineCache::NULL_HANDLE, }, create_infos.len() as u32, create_infos.as_ptr(), ptr::null(), pipelines.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(pipelines) } else { create_error!(format!("failed creating compute pipelines {:?}", result)) } } } pub fn destroy_pipeline(&self, pipeline: VkPipeline) { unsafe { self.device_functions .vkDestroyPipeline(self.device, pipeline, ptr::null()) }; } pub fn queue_present( &self, queue: VkQueue, present_info: &VkPresentInfoKHR, ) -> VerboseResult<OutOfDate<()>> { unsafe { let result = self .device_wsi_functions .vkQueuePresentKHR(queue, present_info); if result == VK_SUCCESS { Ok(OutOfDate::Ok(())) } else if result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR { Ok(OutOfDate::OutOfDate) } else { create_error!(format!("failed presenting queue {:?}", result)) } } } pub fn create_swapchain( &self, create_info: &VkSwapchainCreateInfoKHR, ) -> VerboseResult<VkSwapchainKHR> { unsafe { let mut swapchain = MaybeUninit::uninit(); let result = self.device_wsi_functions.vkCreateSwapchainKHR( self.device, create_info, ptr::null(), swapchain.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(swapchain.assume_init()) } else { create_error!(format!("failed creating swapchain {:?}", result)) } } } pub fn destroy_swapchain(&self, swapchain: VkSwapchainKHR) { unsafe { self.device_wsi_functions .vkDestroySwapchainKHR(self.device, swapchain, ptr::null()) }; } pub fn swapchain_images(&self, swapchain: VkSwapchainKHR) -> VerboseResult<Vec<VkImage>> { let mut count = 0; let result = unsafe { self.device_wsi_functions.vkGetSwapchainImagesKHR( self.device, swapchain, &mut count, ptr::null_mut(), ) }; if result != VK_SUCCESS { create_error!(format!("failed getting swapchain images {:?}", result)) } let mut images = Vec::with_capacity(count as usize); unsafe { images.set_len(count as usize) }; let result = unsafe { self.device_wsi_functions.vkGetSwapchainImagesKHR( self.device, swapchain, &mut count, images.as_mut_ptr(), ) }; if result == VK_SUCCESS { Ok(images) } else { create_error!(format!("failed getting swapchain images {:?}", result)) } } pub fn acquire_next_image( &self, swapchain: VkSwapchainKHR, timeout: u64, semaphore: Option<VkSemaphore>, fence: Option<VkFence>, ) -> VerboseResult<OutOfDate<u32>> { unsafe { let mut image_index = 0; let result = self.device_wsi_functions.vkAcquireNextImageKHR( self.device, swapchain, timeout, match semaphore { Some(sem) => sem, None => VkSemaphore::NULL_HANDLE, }, match fence { Some(fence) => fence, None => VkFence::NULL_HANDLE, }, &mut image_index, ); if result == VK_SUCCESS { Ok(OutOfDate::Ok(image_index)) } else if result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR { Ok(OutOfDate::OutOfDate) } else { create_error!(format!( "failed acquiring next swapchain image {:?}", result )) } } } } // command buffer functions impl Device { pub fn begin_command_buffer( &self, command_buffer: VkCommandBuffer, begin_info: &VkCommandBufferBeginInfo, ) -> VerboseResult<()> { unsafe { let result = self .device_functions .vkBeginCommandBuffer(command_buffer, begin_info); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed beginning command buffer {:?}", result)) } } } pub fn end_command_buffer(&self, command_buffer: VkCommandBuffer) -> VerboseResult<()> { unsafe { let result = self.device_functions.vkEndCommandBuffer(command_buffer); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed ending command buffer {:?}", result)) } } } pub fn reset_command_buffer( &self, command_buffer: VkCommandBuffer, flags: impl Into<VkCommandBufferResetFlagBits>, ) -> VerboseResult<()> { unsafe { let result = self .device_functions .vkResetCommandBuffer(command_buffer, flags.into()); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed resetting command buffer {:?}", result)) } } } pub fn cmd_bind_pipeline( &self, command_buffer: VkCommandBuffer, pipeline_bind_point: VkPipelineBindPoint, pipeline: VkPipeline, ) { unsafe { self.device_functions .vkCmdBindPipeline(command_buffer, pipeline_bind_point, pipeline); } } pub fn cmd_set_viewport( &self, command_buffer: VkCommandBuffer, first: u32, viewports: &[VkViewport], ) { unsafe { self.device_functions.vkCmdSetViewport( command_buffer, first, viewports.len() as u32, viewports.as_ptr(), ) } } pub fn cmd_set_scissor( &self, command_buffer: VkCommandBuffer, first: u32, scissors: &[VkRect2D], ) { unsafe { self.device_functions.vkCmdSetScissor( command_buffer, first, scissors.len() as u32, scissors.as_ptr(), ) } } pub fn cmd_set_depth_bias( &self, command_buffer: VkCommandBuffer, depth_bias_constant_factor: f32, depth_bias_clamp: f32, depth_bias_slope_factor: f32, ) { unsafe { self.device_functions.vkCmdSetDepthBias( command_buffer, depth_bias_constant_factor, depth_bias_clamp, depth_bias_slope_factor, ) } } pub fn cmd_bind_descriptor_sets( &self, command_buffer: VkCommandBuffer, pipeline_bind_point: VkPipelineBindPoint, pipeline_layout: VkPipelineLayout, first_set: u32, descriptor_sets: &[VkDescriptorSet], dynamic_offsets: &[u32], ) { unsafe { self.device_functions.vkCmdBindDescriptorSets( command_buffer, pipeline_bind_point, pipeline_layout, first_set, descriptor_sets.len() as u32, descriptor_sets.as_ptr(), dynamic_offsets.len() as u32, dynamic_offsets.as_ptr(), ) } } pub fn cmd_bind_index_buffer( &self, command_buffer: VkCommandBuffer, buffer: VkBuffer, offset: VkDeviceSize, index_type: VkIndexType, ) { unsafe { self.device_functions .vkCmdBindIndexBuffer(command_buffer, buffer, offset, index_type) } } pub fn cmd_bind_vertex_buffers( &self, command_buffer: VkCommandBuffer, first_binding: u32, buffers: &[VkBuffer], offsets: &[VkDeviceSize], ) { // sanity check debug_assert!(buffers.len() == offsets.len()); unsafe { self.device_functions.vkCmdBindVertexBuffers( command_buffer, first_binding, buffers.len() as u32, buffers.as_ptr(), offsets.as_ptr(), ) } } pub fn cmd_draw( &self, command_buffer: VkCommandBuffer, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32, ) { unsafe { self.device_functions.vkCmdDraw( command_buffer, vertex_count, instance_count, first_vertex, first_instance, ) } } pub fn cmd_draw_indexed( &self, command_buffer: VkCommandBuffer, index_count: u32, instance_count: u32, first_index: u32, vertex_offset: i32, first_instance: u32, ) { unsafe { self.device_functions.vkCmdDrawIndexed( command_buffer, index_count, instance_count, first_index, vertex_offset, first_instance, ); } } pub fn cmd_dispatch(&self, command_buffer: VkCommandBuffer, x: u32, y: u32, z: u32) { unsafe { self.device_functions.vkCmdDispatch(command_buffer, x, y, z) } } pub fn cmd_begin_render_pass( &self, command_buffer: VkCommandBuffer, render_pass_begin: &VkRenderPassBeginInfo, contents: VkSubpassContents, ) { unsafe { self.device_functions .vkCmdBeginRenderPass(command_buffer, render_pass_begin, contents) } } pub fn cmd_next_subpass(&self, command_buffer: VkCommandBuffer, contents: VkSubpassContents) { unsafe { self.device_functions .vkCmdNextSubpass(command_buffer, contents) } } pub fn cmd_end_render_pass(&self, command_buffer: VkCommandBuffer) { unsafe { self.device_functions.vkCmdEndRenderPass(command_buffer) } } pub fn cmd_execute_commands( &self, command_buffer: VkCommandBuffer, command_buffers: &[VkCommandBuffer], ) { unsafe { self.device_functions.vkCmdExecuteCommands( command_buffer, command_buffers.len() as u32, command_buffers.as_ptr(), ) } } pub fn cmd_pipeline_barrier( &self, command_buffer: VkCommandBuffer, src_stage_mask: impl Into<VkPipelineStageFlagBits>, dst_stage_mask: impl Into<VkPipelineStageFlagBits>, dependency_flags: impl Into<VkDependencyFlagBits>, memory_barriers: &[VkMemoryBarrier], buffer_memory_barriers: &[VkBufferMemoryBarrier], image_memory_barriers: &[VkImageMemoryBarrier], ) { unsafe { self.device_functions.vkCmdPipelineBarrier( command_buffer, src_stage_mask.into(), dst_stage_mask.into(), dependency_flags.into(), memory_barriers.len() as u32, memory_barriers.as_ptr(), buffer_memory_barriers.len() as u32, buffer_memory_barriers.as_ptr(), image_memory_barriers.len() as u32, image_memory_barriers.as_ptr(), ) } } pub fn cmd_copy_buffer( &self, command_buffer: VkCommandBuffer, src_buffer: VkBuffer, dst_buffer: VkBuffer, regions: &[VkBufferCopy], ) { unsafe { self.device_functions.vkCmdCopyBuffer( command_buffer, src_buffer, dst_buffer, regions.len() as u32, regions.as_ptr(), ) } } pub fn cmd_copy_image( &self, command_buffer: VkCommandBuffer, src_image: VkImage, src_image_layout: VkImageLayout, dst_image: VkImage, dst_image_layout: VkImageLayout, regions: &[VkImageCopy], ) { unsafe { self.device_functions.vkCmdCopyImage( command_buffer, src_image, src_image_layout, dst_image, dst_image_layout, regions.len() as u32, regions.as_ptr(), ) } } pub fn cmd_blit_image( &self, command_buffer: VkCommandBuffer, src_image: VkImage, src_image_layout: VkImageLayout, dst_image: VkImage, dst_image_layout: VkImageLayout, regions: &[VkImageBlit], filter: VkFilter, ) { unsafe { self.device_functions.vkCmdBlitImage( command_buffer, src_image, src_image_layout, dst_image, dst_image_layout, regions.len() as u32, regions.as_ptr(), filter, ) } } pub fn cmd_copy_buffer_to_image( &self, command_buffer: VkCommandBuffer, src_buffer: VkBuffer, dst_image: VkImage, dst_image_layout: VkImageLayout, regions: &[VkBufferImageCopy], ) { unsafe { self.device_functions.vkCmdCopyBufferToImage( command_buffer, src_buffer, dst_image, dst_image_layout, regions.len() as u32, regions.as_ptr(), ) } } pub fn cmd_copy_image_to_buffer( &self, command_buffer: VkCommandBuffer, src_image: VkImage, src_image_layout: VkImageLayout, dst_buffer: VkBuffer, regions: &[VkBufferImageCopy], ) { unsafe { self.device_functions.vkCmdCopyImageToBuffer( command_buffer, src_image, src_image_layout, dst_buffer, regions.len() as u32, regions.as_ptr(), ) } } pub fn cmd_push_constants<T>( &self, command_buffer: VkCommandBuffer, pipeline_layout: VkPipelineLayout, stage_flags: impl Into<VkShaderStageFlagBits>, offset: u32, data: &T, ) { unsafe { self.device_functions.vkCmdPushConstants( command_buffer, pipeline_layout, stage_flags.into(), offset, size_of::<T>() as u32, data as *const T as *const c_void, ) } } pub fn cmd_begin_query( &self, command_buffer: VkCommandBuffer, query_pool: VkQueryPool, query: u32, flags: impl Into<VkQueryControlFlagBits>, ) { unsafe { self.device_functions .vkCmdBeginQuery(command_buffer, query_pool, query, flags.into()) } } pub fn cmd_end_query( &self, command_buffer: VkCommandBuffer, query_pool: VkQueryPool, query: u32, ) { unsafe { self.device_functions .vkCmdEndQuery(command_buffer, query_pool, query) } } pub fn cmd_reset_query_pool( &self, command_buffer: VkCommandBuffer, query_pool: VkQueryPool, first_query: u32, query_count: u32, ) { unsafe { self.device_functions.vkCmdResetQueryPool( command_buffer, query_pool, first_query, query_count, ) } } pub fn cmd_write_timestamp( &self, command_buffer: VkCommandBuffer, pipeline_stage: impl Into<VkPipelineStageFlagBits>, query_pool: VkQueryPool, query: u32, ) { unsafe { self.device_functions.vkCmdWriteTimestamp( command_buffer, pipeline_stage.into(), query_pool, query, ) } } pub fn cmd_clear_color_image( &self, command_buffer: VkCommandBuffer, image: VkImage, image_layout: VkImageLayout, clear_color: VkClearColorValue, ranges: &[VkImageSubresourceRange], ) { unsafe { self.device_functions.vkCmdClearColorImage( command_buffer, image, image_layout, &clear_color, ranges.len() as u32, ranges.as_ptr(), ) } } pub fn descriptor_set_layout_support( &self, create_info: &VkDescriptorSetLayoutCreateInfo, support: &mut VkDescriptorSetLayoutSupport, ) { unsafe { self.maintenance3_functions.vkGetDescriptorSetLayoutSupport( self.device, create_info, support, ); } } } // nv ray tracing impl Device { pub fn cmd_build_acceleration_structure( &self, command_buffer: VkCommandBuffer, info: &VkAccelerationStructureInfoNV, instance_data: VkBuffer, instance_offset: VkDeviceSize, update: impl Into<VkBool32>, dst: VkAccelerationStructureNV, src: VkAccelerationStructureNV, scratch: VkBuffer, scratch_offset: VkDeviceSize, ) { unsafe { self.nv_ray_tracing_functions .vkCmdBuildAccelerationStructureNV( command_buffer, info, instance_data, instance_offset, update.into(), dst, src, scratch, scratch_offset, ); } } pub fn cmd_copy_acceleration_structure( &self, command_buffer: VkCommandBuffer, dst: VkAccelerationStructureNV, src: VkAccelerationStructureNV, mode: VkCopyAccelerationStructureModeNV, ) { unsafe { self.nv_ray_tracing_functions .vkCmdCopyAccelerationStructureNV(command_buffer, dst, src, mode); } } pub fn cmd_trace_rays( &self, command_buffer: VkCommandBuffer, raygen_shader_binding_table_buffer: VkBuffer, raygen_shader_binding_offset: VkDeviceSize, miss_shader_binding_table_buffer: VkBuffer, miss_shader_binding_offset: VkDeviceSize, miss_shader_binding_stride: VkDeviceSize, hit_shader_binding_table_buffer: VkBuffer, hit_shader_binding_offset: VkDeviceSize, hit_shader_binding_stride: VkDeviceSize, callable_shader_binding_table_offset: VkBuffer, callable_shader_binding_offset: VkDeviceSize, callable_shader_binding_stride: VkDeviceSize, width: u32, height: u32, depth: u32, ) { unsafe { self.nv_ray_tracing_functions.vkCmdTraceRaysNV( command_buffer, raygen_shader_binding_table_buffer, raygen_shader_binding_offset, miss_shader_binding_table_buffer, miss_shader_binding_offset, miss_shader_binding_stride, hit_shader_binding_table_buffer, hit_shader_binding_offset, hit_shader_binding_stride, callable_shader_binding_table_offset, callable_shader_binding_offset, callable_shader_binding_stride, width, height, depth, ); } } pub fn cmd_write_acceleration_structure_properties( &self, command_buffer: VkCommandBuffer, acceleration_structures: &[VkAccelerationStructureNV], query_type: VkQueryType, query_pool: VkQueryPool, first_query: u32, ) { unsafe { self.nv_ray_tracing_functions .vkCmdWriteAccelerationStructurePropertiesNV( command_buffer, acceleration_structures.len() as u32, acceleration_structures.as_ptr(), query_type, query_pool, first_query, ); } } pub fn create_acceleration_structure( &self, create_info: &VkAccelerationStructureCreateInfoNV, ) -> VerboseResult<VkAccelerationStructureNV> { unsafe { let mut acceleration_structure = MaybeUninit::uninit(); let result = self .nv_ray_tracing_functions .vkCreateAccelerationStructureNV( self.device, create_info, ptr::null(), acceleration_structure.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(acceleration_structure.assume_init()) } else { create_error!(format!( "failed creating acceleration structure {:?}", result )) } } } pub fn destroy_acceleration_structure( &self, acceleration_structure: VkAccelerationStructureNV, ) { unsafe { self.nv_ray_tracing_functions .vkDestroyAccelerationStructureNV(self.device, acceleration_structure, ptr::null()); } } /// needs to be called after binding the as to the memory pub fn acceleration_structure_handle( &self, acceleration_structure: VkAccelerationStructureNV, ) -> VerboseResult<u64> { unsafe { let mut handle = 0; let handle_ptr: *mut u64 = &mut handle; let result = self .nv_ray_tracing_functions .vkGetAccelerationStructureHandleNV( self.device, acceleration_structure, size_of::<u64>(), handle_ptr as *mut c_void, ); if result == VK_SUCCESS { Ok(handle) } else { create_error!(format!( "failed creating acceleration structure handle {:?}", result )) } } } pub fn create_ray_tracing_pipelines( &self, pipeline_cache: Option<VkPipelineCache>, pipeline_create_infos: &[VkRayTracingPipelineCreateInfoNV], ) -> VerboseResult<Vec<VkPipeline>> { unsafe { let count = pipeline_create_infos.len() as usize; let mut pipelines = Vec::with_capacity(count); pipelines.set_len(count); let result = self.nv_ray_tracing_functions.vkCreateRayTracingPipelinesNV( self.device, match pipeline_cache { Some(cache) => cache, None => VkPipelineCache::NULL_HANDLE, }, pipeline_create_infos.len() as u32, pipeline_create_infos.as_ptr(), ptr::null(), pipelines.as_mut_ptr(), ); if result == VK_SUCCESS { Ok(pipelines) } else { create_error!(format!( "failed creating ray tracing pipelines {:?}", result )) } } } pub fn ray_tracing_shader_group_handles( &self, pipeline: VkPipeline, first_group: u32, group_count: u32, shader_group_handle_size: u32, ) -> VerboseResult<Vec<u8>> { unsafe { let mut data = vec![255; (group_count * shader_group_handle_size) as usize]; let result = self .nv_ray_tracing_functions .vkGetRayTracingShaderGroupHandlesNV( self.device, pipeline, first_group, group_count, data.len(), data.as_mut_ptr() as *mut c_void, ); if result == VK_SUCCESS { Ok(data) } else { create_error!(format!( "failed gettting ray tracing shader group handles {:?}", result )) } } } pub fn compile_deferred(&self, pipeline: VkPipeline, shader: u32) -> VerboseResult<()> { unsafe { let result = self.nv_ray_tracing_functions .vkCompileDeferredNV(self.device, pipeline, shader); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!("failed compiling pipeline deferred {:?}", result)) } } } pub fn acceleration_structure_memory_requirements( &self, info: &VkAccelerationStructureMemoryRequirementsInfoNV, ) -> VkMemoryRequirements2KHR { unsafe { let mut memory_requirements = MaybeUninit::uninit(); self.nv_ray_tracing_functions .vkGetAccelerationStructureMemoryRequirementsNV( self.device, info, memory_requirements.as_mut_ptr(), ); memory_requirements.assume_init() } } pub fn bind_acceleration_structure_memory( &self, bind_infos: &[VkBindAccelerationStructureMemoryInfoNV], ) -> VerboseResult<()> { unsafe { let result = self .nv_ray_tracing_functions .vkBindAccelerationStructureMemoryNV( self.device, bind_infos.len() as u32, bind_infos.as_ptr(), ); if result == VK_SUCCESS { Ok(()) } else { create_error!(format!( "failed binding acceleration structure to memory {:?}", result )) } } } }
//! Generic B-Tree implementation. //! //! This module defines a `Btree<K, V>` type which provides similar functionality to //! `BtreeMap<K, V>`, but with some important differences in the implementation: //! //! 1. Memory is allocated from a `NodePool<K, V>` instead of the global heap. //! 2. The footprint of a BTree is only 4 bytes. //! 3. A BTree doesn't implement `Drop`, leaving it to the pool to manage memory. //! //! The node pool is intended to be used as a LIFO allocator. After building up a larger data //! structure with many list references, the whole thing can be discarded quickly by clearing the //! pool. use std::marker::PhantomData; // A Node reference is a direct index to an element of the pool. type NodeRef = u32; /// A B-tree data structure which nodes are allocated from a pool. pub struct BTree<K, V> { index: NodeRef, unused1: PhantomData<K>, unused2: PhantomData<V>, } /// An enum representing a B-tree node. /// Keys and values are required to implement Default. enum Node<K, V> { Inner { size: u8, keys: [K; 7], nodes: [NodeRef; 8], }, Leaf { size: u8, keys: [K; 7], values: [V; 7], }, } /// Memory pool for nodes. struct NodePool<K, V> { // The array containing the nodes. data: Vec<Node<K, V>>, // A free list freelist: Vec<NodeRef>, } impl<K: Default, V: Default> NodePool<K, V> { /// Create a new NodePool. pub fn new() -> NodePool<K, V> { NodePool { data: Vec::new(), freelist: Vec::new(), } } /// Get a B-tree node. pub fn get(&self, index: u32) -> Option<&Node<K, V>> { unimplemented!() } } impl<K: Default, V: Default> BTree<K, V> { /// Search for `key` and return a `Cursor` that either points at `key` or the position /// where it would be inserted. pub fn search(&mut self, key: K) -> Cursor<K, V> { unimplemented!() } } pub struct Cursor<'a, K: 'a, V: 'a> { pool: &'a mut NodePool<K, V>, height: usize, path: [(NodeRef, u8); 16], } impl<'a, K: Default, V: Default> Cursor<'a, K, V> { /// The key at the cursor position. Returns `None` when the cursor points off the end. pub fn key(&self) -> Option<K> { unimplemented!() } /// The value at the cursor position. Returns `None` when the cursor points off the end. pub fn value(&self) -> Option<&V> { unimplemented!() } /// Move to the next element. /// Returns `false` if that moves the cursor off the end. pub fn next(&mut self) -> bool { unimplemented!() } /// Move to the previous element. /// Returns `false` if this moves the cursor before the beginning. pub fn prev(&mut self) -> bool { unimplemented!() } /// Insert a `(key, value)` pair at the cursor position. /// It is an error to insert a key that would be out of order at this position. pub fn insert(&mut self, key: K, value: V) { unimplemented!() } /// Remove the current element. pub fn remove(&mut self) { unimplemented!() } }
use std::path::Path; use std::sync::Arc; use std::sync::Mutex; use vulkano::sync::GpuFuture; use wayland_client::protocol::{wl_keyboard, wl_seat}; use wayland_client::Filter; mod vulkan; mod window; use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer}; use vulkano::command_buffer::AutoCommandBufferBuilder; use vulkano::framebuffer::Subpass; use vulkano::pipeline::GraphicsPipeline; use vulkano::swapchain; mod shader; #[derive(PartialEq, Eq)] pub enum Status { Running, Closing, } lazy_static! { pub static ref STATUS: Arc<Mutex<Status>> = Arc::new(Mutex::new(Status::Running)); } pub struct Drawer { vk: vulkan::VkSession, } impl Drawer { pub fn initialize() -> Drawer { let window = window::Window::spawn(500, 500, 0, 0).unwrap(); let physical_device_id = 0; let vk = vulkan::VkSession::initialize(physical_device_id, window).unwrap(); Self { vk } } fn window(&self) -> &window::Window { self.vk.draw_surface.window() } pub fn listen_events(mut self) { let common_filter = Filter::new(move |event, _| match event { Events::Keyboard { event, .. } => match event { wl_keyboard::Event::Enter { .. } => println!("Gained keyboard focus"), wl_keyboard::Event::Leave { .. } => println!("Lost keyboard focus"), wl_keyboard::Event::Key { key, state, .. } => { if key == 1 && state == wl_keyboard::KeyState::Pressed { println!("Setting closing status"); *STATUS.lock().unwrap() = Status::Closing; } else { print!("{} ", key); } } _ => (), }, }); let mut keyboard_created = false; self.window() .globals .instantiate_exact::<wl_seat::WlSeat>(1) .unwrap() .assign_mono(move |seat, event| { use wayland_client::protocol::wl_seat::{Capability, Event as SeatEvent}; if let SeatEvent::Capabilities { capabilities } = event { if !keyboard_created && capabilities.contains(Capability::Keyboard) { keyboard_created = true; seat.get_keyboard().assign(common_filter.clone()) } } }); self.test_draw(); /* std::thread::spawn(|| { std::thread::sleep_ms(6000); *STATUS.lock().unwrap() = Status::Closing; }); */ loop { self.window() .events .borrow_mut() .dispatch(|_, _| {}) .unwrap(); eprintln!("Event dispatch!"); if *STATUS.lock().unwrap() == Status::Closing { println!( "{}", self.window() .events .borrow_mut() .sync_roundtrip(|_, _| {}) .unwrap() ); return; } } } fn test_draw(&mut self) { let (image_num, acquire_future) = swapchain::acquire_next_image(self.vk.swapchain.clone(), None).unwrap(); eprintln!("Got swapchain image"); let clear = vec![[1.0, 1.0, 0.0, 1.0].into()]; let vertex_buffer = { CpuAccessibleBuffer::from_iter( self.vk.device.clone(), BufferUsage::all(), [ shader::Vertex { position: [-0.5, -0.25], color: [0.2, 0.2, 0.2], }, shader::Vertex { position: [0.0, 0.5], color: [0.2, 0.2, 0.2], }, shader::Vertex { position: [0.25, -0.1], color: [0.2, 0.2, 0.2], }, ] .iter() .cloned(), ) .unwrap() }; let vs = shader::open( Path::new("src/draw/shader/test_vert.spv"), self.vk.device.clone(), ); let fs = shader::open( Path::new("src/draw/shader/test_frag.spv"), self.vk.device.clone(), ); eprintln!("Loaded shaders"); let (framebuffers, render_pass) = self.vk.new_framebuffers(); eprintln!("Generated framebuffer and renderpass"); let pipeline = Arc::new( GraphicsPipeline::start() .vertex_input_single_buffer() .vertex_shader(shader::get_entry_vertex(&vs), ()) .triangle_list() .viewports_dynamic_scissors_irrelevant(1) .fragment_shader(shader::get_entry_fragment(&fs), ()) .render_pass(Subpass::from(render_pass.clone(), 0).unwrap()) .build(self.vk.device.clone()) .unwrap(), ); eprintln!("Generated pipeline"); let cb = AutoCommandBufferBuilder::primary_one_time_submit( self.vk.device.clone(), self.vk.queue.family(), ) .unwrap() .begin_render_pass(framebuffers[image_num].clone(), false, clear) .unwrap() .draw( pipeline.clone(), &self.vk.dynamic_state, vertex_buffer.clone(), (), (), ) .unwrap() .end_render_pass() .unwrap() .build() .unwrap(); eprintln!("Built command_buffer"); let _frame_end = acquire_future .then_execute(self.vk.queue.clone(), cb) .unwrap() .then_swapchain_present(self.vk.queue.clone(), self.vk.swapchain.clone(), image_num); eprintln!("Presented swapchain"); } } event_enum!( Events | Keyboard => wl_keyboard::WlKeyboard );
pub use self::redis_client::*; pub mod redis_client;
//! Views are organized as a tree. A view might receive / send events and render itself. //! //! The z-level of the n-th child of a view is less or equal to the z-level of its n+1-th child. //! //! Events travel from the root to the leaves, only the leaf views will handle the root events, but //! any view can send events to its parent. From the events it receives from its children, a view //! resends the ones it doesn't handle to its own parent. Hence an event sent from a child might //! bubble up to the root. If it reaches the root without being captured by any view, then it will //! be written to the main event channel and will be sent to every leaf in one of the next loop //! iterations. //pub mod common; //pub mod filler; //pub mod icon; //pub mod label; //pub mod button; //pub mod rounded_button; //pub mod slider; //pub mod input_field; //pub mod page_label; //pub mod named_input; //////pub mod search_bar; //pub mod confirmation; ////pub mod notification; //pub mod intermission; //pub mod frontlight; //pub mod presets_list; //pub mod preset; //pub mod menu; ////pub mod menu_entry; //pub mod clock; //pub mod battery; //pub mod keyboard; pub mod key; ////pub mod home; //pub mod reader; use std::time::Duration; //use std::path::PathBuf; use std::sync::mpsc::Sender; use std::collections::VecDeque; use std::fmt::{self, Debug}; use fnv::FnvHashMap; //use downcast_rs::Downcast; //use font::Fonts; //use document::TocEntry; //use metadata::{Info, SortMethod, PageScheme, Margin}; use framebuffer::{Framebuffer, UpdateMode}; use input::{DeviceEvent, FingerStatus}; use gesture::GestureEvent; use view::key::KeyKind; use app::Context; use geom::{LinearDir, CycleDir, Rectangle}; pub const THICKNESS_SMALL: f32 = 1.0; pub const THICKNESS_MEDIUM: f32 = 2.0; pub const THICKNESS_LARGE: f32 = 3.0; pub const BORDER_RADIUS_SMALL: f32 = 6.0; pub const BORDER_RADIUS_MEDIUM: f32 = 9.0; pub const BORDER_RADIUS_LARGE: f32 = 12.0; pub const CLOSE_IGNITION_DELAY: Duration = Duration::from_millis(150); type Bus = VecDeque<Event>; type Hub = Sender<Event>; pub trait View: Downcast { fn handle_event(&mut self, evt: &Event, hub: &Hub, bus: &mut Bus, context: &mut Context) -> bool; fn render(&self, fb: &mut Framebuffer, fonts: &mut Fonts); fn rect(&self) -> &Rectangle; fn rect_mut(&mut self) -> &mut Rectangle; fn children(&self) -> &Vec<Box<View>>; fn children_mut(&mut self) -> &mut Vec<Box<View>>; fn child(&self, index: usize) -> &View { self.children()[index].as_ref() } fn child_mut(&mut self, index: usize) -> &mut View { self.children_mut()[index].as_mut() } fn len(&self) -> usize { self.children().len() } fn might_skip(&self, _evt: &Event) -> bool { false } fn is_background(&self) -> bool { false } fn id(&self) -> Option<ViewId> { None } } impl_downcast!(View); impl Debug for Box<View> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Box<View>") } } // We start delivering events from the highest z-level to prevent views from capturing // gestures that occurred in higher views. // The consistency must also be ensured by the views: popups, for example, need to // capture any tap gesture with a touch point inside their rectangle. // A child can send events to the main channel through the *hub* or communicate with its parent through the *bus*. pub fn handle_event(view: &mut View, evt: &Event, hub: &Hub, parent_bus: &mut Bus, context: &mut Context) -> bool { if view.len() > 0 { let mut captured = false; if view.might_skip(evt) { return captured; } let mut child_bus: Bus = VecDeque::with_capacity(1); for i in (0..view.len()).rev() { if handle_event(view.child_mut(i), evt, hub, &mut child_bus, context) { captured = true; break; } } child_bus.retain(|child_evt| !view.handle_event(child_evt, hub, parent_bus, context)); parent_bus.append(&mut child_bus); captured || view.handle_event(evt, hub, parent_bus, context) } else { view.handle_event(evt, hub, parent_bus, context) } } pub fn render(view: &View, rect: &mut Rectangle, fb: &mut Framebuffer, fonts: &mut Fonts, updating: &mut FnvHashMap<u32, Rectangle>) { render_aux(view, rect, fb, fonts, &mut false, true, updating); } pub fn render_no_wait(view: &View, rect: &mut Rectangle, fb: &mut Framebuffer, fonts: &mut Fonts, updating: &mut FnvHashMap<u32, Rectangle>) { render_aux(view, rect, fb, fonts, &mut false, false, updating); } // We don't start rendering until we reach the z-level of the view that generated the event. // Once we reach that z-level, we start comparing the candidate rectangles with the source // rectangle. If there is an overlap, we render the corresponding view. And update the source // rectangle by absorbing the candidate rectangle into it. fn render_aux(view: &View, rect: &mut Rectangle, fb: &mut Framebuffer, fonts: &mut Fonts, above: &mut bool, wait: bool, updating: &mut FnvHashMap<u32, Rectangle>) { if !*above && view.rect() == rect { *above = true; } if *above && view.rect().overlaps(rect) { if wait { updating.retain(|tok, urect| { !view.rect().overlaps(urect) || fb.wait(*tok).is_err() }); } view.render(fb, fonts); rect.absorb(view.rect()); } for i in 0..view.len() { render_aux(view.child(i), rect, fb, fonts, above, wait, updating); } } // When a floating window is destroyed, it leaves a crack underneath. // Each view intersecting the crack's rectangle needs to be redrawn. pub fn fill_crack(view: &View, rect: &mut Rectangle, fb: &mut Framebuffer, fonts: &mut Fonts, updating: &mut FnvHashMap<u32, Rectangle>) { if (view.len() == 0 || view.is_background()) && view.rect().overlaps(rect) { updating.retain(|tok, urect| { !view.rect().overlaps(urect) || fb.wait(*tok).is_err() }); view.render(fb, fonts); rect.absorb(view.rect()); } for i in 0..view.len() { fill_crack(view.child(i), rect, fb, fonts, updating); } } #[derive(Debug, Clone)] pub enum Event { Render(Rectangle, UpdateMode), RenderNoWait(Rectangle, UpdateMode), Expose(Rectangle), Device(DeviceEvent), Gesture(GestureEvent), Keyboard(KeyboardEvent), Key(KeyKind), Open(Box<Info>), OpenToc(Vec<TocEntry>, usize), Invalid(Box<Info>), Remove(Box<Info>), Page(CycleDir), ResultsPage(CycleDir), GoTo(usize), ResultsGoTo(usize), CropMargins(Box<Margin>), Chapter(CycleDir), Sort(SortMethod), ToggleSelectCategory(String), ToggleNegateCategory(String), ToggleNegateCategoryChildren(String), ResizeSummary(i32), Focus(Option<ViewId>), Select(EntryId), PropagateSelect(EntryId), Submit(ViewId, String), Slider(SliderId, f32, FingerStatus), ToggleNear(ViewId, Rectangle), ToggleBookMenu(Rectangle, usize), TogglePresetMenu(Rectangle, usize), SubMenu(Rectangle, Vec<EntryKind>), Toggle(ViewId), Show(ViewId), Close(ViewId), CloseSub(ViewId), SearchResult(usize, Rectangle), EndOfSearch, Finished, ClockTick, BatteryTick, ToggleFrontlight, Load(PathBuf), LoadPreset(usize), Save, Guess, Suspend, Mount, Validate, Cancel, Reseed, Back, Quit, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum ViewId { Home, Reader, SortMenu, MainMenu, Frontlight, FontSizeMenu, MatchesMenu, PageMenu, BookMenu, PresetMenu, MarginCropperMenu, SearchMenu, GoToPage, GoToPageInput, GoToResultsPage, GoToResultsPageInput, ExportAs, ExportAsInput, AddCategories, AddCategoriesInput, SearchInput, SearchBar, Keyboard, ConfirmMount, MarginCropper, TopBottomBars, TableOfContents, FinishedNotif, TakeScreenshotNotif, NoSearchResultsNotif, InvalidSearchQueryNotif, NetUpNotif, SubMenu(u8), } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum SliderId { FontSize, LightIntensity, LightWarmth, } impl SliderId { pub fn label(&self) -> String { match *self { SliderId::LightIntensity => "Intensity".to_string(), SliderId::LightWarmth => "Warmth".to_string(), SliderId::FontSize => "Font Size".to_string(), } } } #[derive(Debug, Clone)] pub enum Align { Left(i32), Right(i32), Center, } impl Align { #[inline] pub fn offset(&self, width: i32, container_width: i32) -> i32 { match *self { Align::Left(dx) => dx, Align::Right(dx) => container_width - width - dx, Align::Center => (container_width - width) / 2, } } } #[derive(Debug, Copy, Clone)] pub enum KeyboardEvent { Append(char), Partial(char), Move { target: TextKind, dir: LinearDir }, Delete { target: TextKind, dir: LinearDir }, Submit, } #[derive(Debug, Copy, Clone)] pub enum TextKind { Char, Word, Extremum, } #[derive(Debug, Clone)] pub enum EntryKind { Command(String, EntryId), CheckBox(String, EntryId, bool), RadioButton(String, EntryId, bool), SubMenu(String, Vec<EntryKind>), Separator, } #[derive(Debug, Clone, Eq, PartialEq)] pub enum EntryId { Column(Column), Sort(SortMethod), ApplyCroppings(usize, PageScheme), RemoveCroppings, Remove(PathBuf), SearchDirection(LinearDir), AddBookCategories(PathBuf), RemoveBookCategory(PathBuf, String), RemoveMatches, RemovePreset(usize), AddMatchesCategories, RemoveMatchesCategory(String), Load(PathBuf), ExportMatches, ToggleFirstPage, ReverseOrder, ToggleInverted, ToggleMonochrome, ToggleWifi, TakeScreenshot, StartNickel, Reboot, Quit, Undo, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Column { First(FirstColumn), Second(SecondColumn), } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum FirstColumn { TitleAndAuthor, Title, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum SecondColumn { Year, Progress, Nothing, } impl EntryKind { pub fn is_separator(&self) -> bool { match *self { EntryKind::Separator => true, _ => false, } } pub fn text(&self) -> &str { match *self { EntryKind::Command(ref s, ..) | EntryKind::CheckBox(ref s, ..) | EntryKind::RadioButton(ref s, ..) | EntryKind::SubMenu(ref s, ..) => s, _ => "", } } pub fn get(&self) -> Option<bool> { match *self { EntryKind::CheckBox(_, _, v) | EntryKind::RadioButton(_, _, v) => Some(v), _ => None, } } pub fn set(&mut self, value: bool) { match *self { EntryKind::CheckBox(_, _, ref mut v) | EntryKind::RadioButton(_, _, ref mut v) => *v = value, _ => (), } } }
use std::thread; use std::time::Duration; struct Philosopher { name: String, } impl Philosopher { fn new(name: &str) -> Philosopher { Philosopher { name: name.to_string() } } fn eat(&self) { println!("{} is eating.", self.name); thread::sleep(Duration::from_millis(1000)); println!("{} is done eating.", self.name); } } fn main() { let philosophers = vec![ Philosopher::new("A"), Philosopher::new("B"), Philosopher::new("C"), Philosopher::new("D"), Philosopher::new("E")]; let handles: Vec<_> = philosophers.into_iter() .map(|p| { thread::spawn(move || { p.eat(); }) }) .collect(); for h in handles { h.join().unwrap(); } }
use glam::{Quat, Vec3}; use crate::Serializable; use std::{ fmt, time::{SystemTime, UNIX_EPOCH}, }; #[derive(Clone, Debug, PartialEq, Eq)] pub struct ServerInfo { pub name: String, pub description: String, pub host: String, } impl fmt::Display for ServerInfo { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "\n{}:\n About: {}\n Hosted by {}.", self.name, self.description, self.host ) } } impl Serializable for ServerInfo { fn serialize(&self, buf: &mut Vec<u8>) { self.name.serialize(buf); self.description.serialize(buf); self.host.serialize(buf); } fn deserialize(buf: &mut crate::ReadBuffer) -> Result<Self, crate::error::ReadValueError> { Ok(Self { name: String::deserialize(buf)?, description: String::deserialize(buf)?, host: String::deserialize(buf)?, }) } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Authentication { pub username: String, pub password: String, } impl Serializable for Authentication { fn serialize(&self, buf: &mut Vec<u8>) { self.username.serialize(buf); self.password.serialize(buf); } fn deserialize(buf: &mut crate::ReadBuffer) -> Result<Self, crate::error::ReadValueError> { Ok(Self { username: String::deserialize(buf)?, password: String::deserialize(buf)?, }) } } #[derive(Clone, Debug, PartialEq)] pub struct Unit { start: Quat, end: Quat, start_time: u128, duration: u128, class: usize, } impl Unit { fn time() -> u128 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_millis() } fn duration(start: Quat, end: Quat, class: usize) -> u128 { (start.angle_between(end) / game_statics::UNIT_TYPES[class as usize].speed * 1000.) as u128 } pub fn new(start: Vec3, end: Vec3, class: usize) -> Self { let (start, end) = (Quat::from_scaled_axis(start), Quat::from_scaled_axis(end)); Self { start, end, start_time: Self::time(), duration: Self::duration(start, end, class), class, } } fn get_quat_position(&self) -> Quat { let time = ((Self::time() - self.start_time) as f32) / self.duration as f32; if time > 1. { self.end } else { self.start.lerp(self.end, time) } } pub fn get_position(&self) -> Vec3 { self.get_quat_position().to_axis_angle().0 } pub fn set_destination(&mut self, end: &Vec3) { self.start = self.get_quat_position(); self.end = Quat::from_scaled_axis(*end); self.start_time = Self::time(); self.duration = Self::duration(self.start, self.end, self.class); } } impl Serializable for Unit { fn serialize(&self, buf: &mut Vec<u8>) { self.start.serialize(buf); self.end.serialize(buf); self.start_time.serialize(buf); (self.class as u32).serialize(buf); } fn deserialize(buf: &mut crate::ReadBuffer) -> Result<Self, crate::error::ReadValueError> { let (start, end) = (Quat::deserialize(buf)?, Quat::deserialize(buf)?); let start_time = u128::deserialize(buf)?; let class = u32::deserialize(buf)? as usize; Ok(Self { start, end, start_time, duration: Self::duration(start, end, class), class, }) } } #[test] fn test_get_position() { let japan = Vec3::new(0.52484196, 0.5836691, -0.6195735); let germany = Vec3::new(0.14106606, 0.79356587, 0.59190667); let mut unit = Unit::new(japan, germany, 0); assert_eq!(unit.duration, 1255); assert_eq!(unit.get_position(), japan); unit.start_time -= unit.duration; assert_eq!(unit.get_position(), germany); }
use crate::{DocBase, VarType}; const DESCRIPTION: &'static str = r#" If ... then ... else ... "#; const EXAMPLES: &'static str = r#" ```pine // Draw circles at the bars where open crosses close s1 = iff(cross(open, close), avg(open,close), na) plot(s1, style=plot.style_circles, linewidth=4, color=color.green) ``` "#; const ARGUMENTS: &'static str = r#" **condition (series)** Series with condition values. Zero value (0 and also NaN, +Infinity, -Infinity) is considered to be false, any other value is true. **then (series)** Series with values to return if condition is true. **_else (series)** Series with values to return if condition is false. Use na for `_else` argument if you do not need 'else' branch. "#; pub fn gen_doc() -> Vec<DocBase> { let fn_doc = DocBase { var_type: VarType::Function, name: "iff", signatures: vec![], description: DESCRIPTION, example: EXAMPLES, returns: "y or z series.", arguments: ARGUMENTS, remarks: "iff does exactly the same thing as ternary conditional operator ?: but in a functional style. Also iff is slightly less efficient than operator ?:", links: "[na](#fun-na)", }; vec![fn_doc] }
pub fn selection_sort(mut arr: Vec<i32>) -> Vec<i32> { for i in (1..(arr.len())).rev() { let mut el = i; for j in 0..i { if arr[j] > arr[el] { el = j; } } arr.swap(i, el); } arr } #[test] fn tests() { assert_eq!( selection_sort(vec![7, 2, 1, 5, 6, 3, 4, 8]), vec![1, 2, 3, 4, 5, 6, 7, 8] ); assert_eq!(selection_sort(vec![]), vec![]); assert_eq!(selection_sort(vec![1]), vec![1]); }
use mkit::{ cbor::{FromCbor, IntoCbor}, Cborize, }; #[allow(unused_imports)] use crate::wral::Wal; use crate::{entry::Entry, Result}; /// Callback trait for updating application state in relation to [Wal] type. pub trait State: 'static + Clone + Sync + Send + IntoCbor + FromCbor { fn on_add_entry(&mut self, new_entry: &Entry) -> Result<()>; } /// Default parameter, implementing [State] trait, for [Wal] type. #[derive(Clone, Eq, PartialEq, Debug, Cborize)] pub struct NoState; impl NoState { const ID: u32 = 0x0; } impl State for NoState { fn on_add_entry(&mut self, _: &Entry) -> Result<()> { Ok(()) } }
extern crate image; extern crate cgmath; extern crate glium_text_rusttype as glium_text; use crate::data_loader; use cgmath::{Matrix4, Vector2}; use glium::glutin; use glium::Surface; use glium::texture::Texture2d; use self::image::{RgbImage}; use std::collections::HashMap; use data_loader::TitleContainer; use std::borrow::BorrowMut; #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], } #[derive(Clone)] pub(crate) struct Rectangle { pub(crate) center: [f32; 2], pub(crate) size: [f32; 2], pub(crate) texture_key: String, } impl Rectangle{ fn draw(&self, frame: &mut glium::Frame, indices: &glium::IndexBuffer<u16>, display: &glium::Display, program: &glium::Program, tex_cache: &HashMap<String, Texture2d>, perspective: [[f32; 4]; 4]){ let vb = glium::VertexBuffer::empty_dynamic(display, 4).unwrap(); let rect_size = Vector2 { x: self.size[0], y: self.size[1], }; let rect_position = Vector2 { x: self.center[0], y: self.center[1], }; let left = rect_position.x - rect_size.x / 2.0; let right = rect_position.x + rect_size.x / 2.0; let top = rect_position.y + rect_size.y / 2.0; let bottom = rect_position.y - rect_size.y / 2.0; let v0 = Vertex{ position: [left, top]}; let v1 = Vertex{ position: [right, top]}; let v2 = Vertex{ position: [left, bottom]}; let v3 = Vertex{ position: [right, bottom]}; let shape = vec![v0, v1, v2, v3]; vb.write(&shape); let texture = match tex_cache.get(&self.texture_key){ Some(e) => e, None => tex_cache.get("whitesquare").expect("missing fallback texture") }; let uniforms = uniform!{ projection: perspective, tex: texture }; frame.draw(&vb, indices, program, &uniforms, &Default::default()).unwrap(); } fn get_nw_corner(&self)->(f32, f32){ let rect_size = Vector2 { x: self.size[0], y: self.size[1], }; let rect_position = Vector2 { x: self.center[0], y: self.center[1], }; let left = rect_position.x - rect_size.x / 2.0; let bottom = rect_position.y - rect_size.y / 2.0; (left, bottom) } } implement_vertex!(Vertex, position); fn keyboard_input(event: &glutin::event::WindowEvent<'_>, debounce: &mut bool) -> (i32, i32) { let input = match *event { glutin::event::WindowEvent::KeyboardInput { input, .. } => input, _ => return (0, 0), }; let pressed = input.state == glutin::event::ElementState::Pressed; if pressed && !*debounce{ *debounce = true; }else if pressed && *debounce{ return (0, 0); }else{ *debounce = false; return (0, 0); } let key = match input.virtual_keycode { Some(key) => key, None => return (0, 0), }; match key { glutin::event::VirtualKeyCode::Up => (0,-1), glutin::event::VirtualKeyCode::Down => (0, 1), glutin::event::VirtualKeyCode::Left => (-1, 0), glutin::event::VirtualKeyCode::Right => (1, 0), glutin::event::VirtualKeyCode::Return => (1, 1), _ => (0, 0), } } const SCREEN_WIDTH: u32 = 1024; const SCREEN_HEIGHT: u32 = 768; const NUM_ROWS: u32 = 4; const NUM_COLS: u32 = 6; const PADDING: u32 = 16; const CENTER_DIST_HORZ: u32 = SCREEN_WIDTH / NUM_COLS; const CENTER_DIST_VERT: u32 = SCREEN_HEIGHT / NUM_ROWS; const TILE_SIZE: f32 = (SCREEN_WIDTH / NUM_COLS - (PADDING * 2)) as f32; const VERTEX_SHADER_SRC: &str = r#" #version 140 // Input parameter from the Vertex struct. in vec2 position; // Uniform parameter passed in from the frame.draw() call. uniform mat4 projection; // Output texture coordinates that gets passed into the fragment shader. out vec2 v_tex_coords; void main() { // In order to return the texture coordinate for a specific // vertex we have to know what vertex is currently being passed in. // We do this through gl_VertexID which increments with every vertex passed in. // We can figure out the rectangle specific index from the vertex id by modding it // by 4. Example: if a vertex has id 16, then it is the first vertex of the fourth // rectangle being drawn. 16 % 4 == 0 which correctly returns the first index. if (gl_VertexID % 4 == 0) { // First vertex v_tex_coords = vec2(0.0, 1.0); } else if (gl_VertexID % 4 == 1) { // Second vertex v_tex_coords = vec2(1.0, 1.0); } else if (gl_VertexID % 4 == 2) { // Third vertex v_tex_coords = vec2(0.0, 0.0); } else { // Fourth vertex v_tex_coords = vec2(1.0, 0.0); } gl_Position = projection * vec4(position, 0.0, 1.0); } "#; const FRAGMENT_SHADER_SRC: &str = r#" #version 140 // Input texture coordinates passed from the vertex shader. in vec2 v_tex_coords; // Outputs the color for the specific fragment. out vec4 color; // Uniform parameter passed in from the frame.draw() call. uniform sampler2D tex; void main() { // Applies a texture to the rectangle. color = texture(tex, v_tex_coords); } "#; struct Menu{ selected_tile: [i32; 2], tiles: Vec<Vec<Rectangle>>, texture_map: HashMap<String, Texture2d>, selection_square: Rectangle, headings: Vec<String>, popup: Rectangle, popup_enabled: bool, row_offset: i32, col_offsets: Vec<i32>, titles: Vec<TitleContainer>, title_desc_lookup: HashMap<String, String> } impl Menu{ fn new(titles: Vec<TitleContainer>)->Menu{ let mut active_rows: Vec<Vec<Rectangle>> = Vec::new(); for row_num in 1..NUM_ROWS { let trow = &titles[row_num as usize - 1]; let mut active_cols: Vec<Rectangle> = Vec::new(); for col_num in 1..NUM_COLS { let tkey = trow.items[col_num as usize - 1].image_url.clone(); active_cols.push(Rectangle{ center: [(col_num * CENTER_DIST_HORZ) as f32, (row_num * CENTER_DIST_VERT) as f32], size: [TILE_SIZE, TILE_SIZE], texture_key: tkey }) } active_rows.push(active_cols); } active_rows[0][0].size = [Menu::selected_tile_size(); 2]; let mut headings: Vec<String> = Vec::new(); let mut tlookup = HashMap::new(); for t in &titles{ headings.push(t.name.clone()); for t2 in &t.items{ tlookup.insert(t2.image_url.clone(), t2.to_string()); } } let hm = HashMap::new(); let ctile = active_rows.get(0).unwrap().get(0).unwrap().center; Menu{ selected_tile: [0; 2], tiles: active_rows, texture_map: hm, selection_square: Rectangle { center: ctile, size: [Menu::selection_backdrop_size(); 2], texture_key: "whitesquare".to_string(), }, headings, popup: Rectangle{ center: [SCREEN_WIDTH as f32 / 2., SCREEN_HEIGHT as f32 / 2.], size: [SCREEN_WIDTH as f32 * 0.5, SCREEN_HEIGHT as f32 * 0.9], texture_key: "popup".to_string() }, popup_enabled: false, row_offset: 0, col_offsets: vec![0; titles.len()], titles, title_desc_lookup: tlookup } } fn update_tile_textures(&mut self){ for row_num in 0..(NUM_ROWS-1) as usize { for col_num in 0..(NUM_COLS-1) as usize { let t: &mut Rectangle = &mut self.tiles[row_num][col_num]; let cidx = row_num + self.row_offset as usize; t.texture_key = self.titles[cidx].items[col_num + self.col_offsets[cidx] as usize].image_url.clone(); } } } #[allow(dead_code)] fn add_texture_from_path(&mut self, path: &str, key: String, display: &glium::Display){ let image = image::open(path).unwrap().to_rgb8(); self.add_texture_from_rgb(image, key, display); } fn add_texture_from_rgb(&mut self, image: RgbImage, key: String, display: &glium::Display){ let dim = image.dimensions(); let img = glium::texture::RawImage2d::from_raw_rgb(image.into_raw(), dim); let tex: glium::texture::Texture2d = glium::texture::Texture2d::new(display, img).unwrap(); self.texture_map.insert(key, tex); } fn change_selected_tile(&mut self, change: (i32, i32)){ let (x, y) = change; if x == 1 && y == 1{ self.popup_enabled = !self.popup_enabled; return; }else{ self.popup_enabled = false; } let (lx, ly) = (self.selected_tile[0] as usize, self.selected_tile[1] as usize); { let Menu { ref mut tiles, .. } = self; let Rectangle { ref mut size, .. } = tiles[lx][ly]; size[0] = TILE_SIZE; size[1] = TILE_SIZE; } self.selected_tile[0] += y; self.selected_tile[1] += x; // change the row or column if on edge of screen if self.selected_tile[0] < 0{ self.selected_tile[0] = 0; self.row_offset = (self.row_offset - 1).max(0); self.update_tile_textures(); }else if self.selected_tile[0] > NUM_ROWS as i32 - 2{ self.selected_tile[0] = NUM_ROWS as i32 - 2; self.row_offset = (self.row_offset + 1).min((self.headings.len() - NUM_ROWS as usize - 1) as i32); self.update_tile_textures(); }else if self.selected_tile[1] < 0{ self.selected_tile[1] = 0; let current_row = (self.row_offset + self.selected_tile[0]) as usize; self.col_offsets[current_row] -= 1; self.col_offsets[current_row] = self.col_offsets[current_row].max(0); self.update_tile_textures(); }else if self.selected_tile[1] > NUM_COLS as i32 - 2{ self.selected_tile[1] = NUM_COLS as i32 - 2; let current_row = (self.row_offset + self.selected_tile[0]) as usize; self.col_offsets[current_row] += 1; self.col_offsets[current_row] = self.col_offsets[current_row].min((self.titles[current_row].items.len() - NUM_COLS as usize) as i32); self.update_tile_textures(); } // let current_row = (self.row_offset + self.selected_tile[0]) as usize; // println!("Current Row: {}, Col Offset: {}",current_row, self.col_offsets[current_row]); let (nx, ny) = (self.selected_tile[0] as usize, self.selected_tile[1] as usize); let sel_center = self.selection_square.borrow_mut().center.as_mut(); { let Menu { ref mut tiles, .. } = self; let Rectangle { ref mut size, center, .. } = tiles[nx][ny]; size[0] = Menu::selected_tile_size(); size[1] = Menu::selected_tile_size(); sel_center[0] = center[0]; sel_center[1] = center[1]; } } fn selection_backdrop_size()->f32{ ((TILE_SIZE as f32) + (PADDING as f32 * 1.25) + 4.) as f32 } fn selected_tile_size()->f32{ (TILE_SIZE as f32 + (PADDING as f32 * 1.25)) as f32 } fn x_y_to_mat(x: f32, y: f32) -> (f32, f32) { let xrise = 1. - (-1.); let xrun = SCREEN_WIDTH as f32; let xslope = xrise / xrun; let xb = 1. - (SCREEN_WIDTH as f32 * xslope); let retx = xslope * x + xb; let yrise = 1. - (-1.); let yrun = SCREEN_HEIGHT as f32; let yslope = yrise / yrun; let yb = 1. - (SCREEN_HEIGHT as f32 * yslope); let rety = -(yslope * y + yb); (retx , rety) } fn write_popup(&self, tstr: &str, frame: &mut glium::Frame, text_system: &glium_text::TextSystem, font: &glium_text::FontTexture){ let strings = tstr.lines(); let (xoffset, yoffset) = self.popup.get_nw_corner(); for (idx, s) in strings.enumerate(){ let text = glium_text::TextDisplay::new(text_system, font, s); let (x, y) = Menu::x_y_to_mat(xoffset + 32., yoffset + 64. + (32. * idx as f32)); const TSIZE: f32 = 0.05; let loc_mat: [[f32; 4]; 4] = cgmath::Matrix4::new( TSIZE, 0.0, 0.0, 0.0, 0.0, TSIZE, 0.0, 0.0, 0.0, 0.0, TSIZE, 0.0, x, y, 0.0, 1.0f32, ).into(); glium_text::draw(&text, text_system, frame, loc_mat, (1.0, 1.0, 1.0, 1.0)).unwrap(); } } #[allow(clippy::too_many_arguments)] fn draw(&mut self, frame: &mut glium::Frame, indices: &glium::IndexBuffer<u16>, display: &glium::Display, program: &glium::Program, perspective: [[f32; 4]; 4], text_system: &glium_text::TextSystem, font: &glium_text::FontTexture) { // draw text for (tidx, ridx) in (self.row_offset..self.row_offset+NUM_ROWS as i32-1).enumerate(){ let idx = ridx as usize; let heading = match self.headings.get(idx){ None=> break, Some(e) => e }; let text = glium_text::TextDisplay::new(text_system, font, heading.as_str()); let yoffset = self.tiles[tidx][0].center[1] - TILE_SIZE as f32 / 2. - (PADDING as f32); let xoffset = self.tiles[tidx][0].center[0] - TILE_SIZE as f32 / 2.; let (x, y) = Menu::x_y_to_mat(xoffset, yoffset); const TSIZE: f32 = 0.05; let loc_mat: [[f32; 4]; 4] = cgmath::Matrix4::new( TSIZE, 0.0, 0.0, 0.0, 0.0, TSIZE, 0.0, 0.0, 0.0, 0.0, TSIZE, 0.0, x, y, 0.0, 1.0f32, ).into(); glium_text::draw(&text, text_system, frame, loc_mat, (1.0, 1.0, 1.0, 1.0)).unwrap(); } // draw selection border let tile = self.selection_square.borrow_mut(); tile.draw(frame, indices, display, program, &self.texture_map, perspective); // draw tiles for row in &self.tiles{ for tile in row { tile.draw(frame, indices, display, program, &self.texture_map, perspective); } } if self.popup_enabled{ self.popup.draw(frame, indices, display, program, &self.texture_map, perspective); let (i1, i2) = (self.selected_tile[0] as usize, self.selected_tile[1] as usize); let title_str = self.title_desc_lookup.get(self.tiles[i1][i2].texture_key.as_str()).unwrap(); self.write_popup(&title_str, frame, text_system, font); } } } pub fn launch_window(title_data: Vec<TitleContainer>, img_cache: HashMap<String, RgbImage>){ let events_loop = glutin::event_loop::EventLoop::new(); let wb = glutin::window::WindowBuilder::new().with_inner_size( glium::glutin::dpi::LogicalSize::new(SCREEN_WIDTH, SCREEN_HEIGHT) ).with_title("DSS - Chilton").with_resizable(false); let cb = glutin::ContextBuilder::new(); let display = glium::Display::new(wb, cb, &events_loop).unwrap(); let text_system = glium_text::TextSystem::new(&display); let font = glium_text::FontTexture::new(&display, &include_bytes!("OpenSans-Bold.ttf")[..], 70, glium_text::FontTexture::ascii_character_list()).unwrap(); let program = glium::Program::from_source(&display, VERTEX_SHADER_SRC, FRAGMENT_SHADER_SRC, None).unwrap(); let perspective = { let matrix: Matrix4<f32> = cgmath::ortho( 0.0, SCREEN_WIDTH as f32, SCREEN_HEIGHT as f32, 0.0, -1.0, 1.0 ); Into::<[[f32; 4]; 4]>::into(matrix) }; // 0 1 // +------+ // | / | // | / | // |/ | // +------+ // 2 3 let ib_data: Vec<u16> = vec![0, 1, 2, 1, 3, 2]; let indices = glium::IndexBuffer::new( &display, glium::index::PrimitiveType::TrianglesList, &ib_data ).unwrap(); let mut debounce = false; let mut menu = Menu::new(title_data); let white_square_img: RgbImage = image::load_from_memory(include_bytes!("whitesquare.png")).unwrap().to_rgb8(); let popup_img: RgbImage = image::load_from_memory(include_bytes!("popup.png")).unwrap().to_rgb8(); menu.add_texture_from_rgb(white_square_img, "whitesquare".to_string(), &display); menu.add_texture_from_rgb(popup_img, "popup".to_string(), &display); for (key, img) in img_cache{ menu.add_texture_from_rgb(img, key, &display); } let mut redraw = true; // add listen handler for window close request events_loop.run(move |ev, _, control_flow|{ if redraw { let mut target = display.draw(); target.clear_color(0.01, 0.01, 0.01, 1.0); menu.draw(&mut target, &indices, &display, &program, perspective, &text_system, &font); target.finish().unwrap(); redraw = false; } let next_frame_time = std::time::Instant::now() + std::time::Duration::from_nanos(166_666_667); *control_flow = glutin::event_loop::ControlFlow::WaitUntil(next_frame_time); if let glutin::event::Event::WindowEvent { event, .. } = ev { match event { glutin::event::WindowEvent::CloseRequested => { *control_flow = glutin::event_loop::ControlFlow::Exit; }, glutin::event::WindowEvent::KeyboardInput { .. } => { let input = keyboard_input(&event, &mut debounce); if input != (0,0) { menu.change_selected_tile(input); } redraw = true; } _ => {}, } } }); }
use std::cmp::min; use std::sync::atomic::AtomicU64; use std::sync::Arc; use ash::vk; use sourcerenderer_core::graphics::*; use crate::buffer::VkBufferSlice; use crate::pipeline::{ VkGraphicsPipelineInfo, VkPipeline, VkShader, }; use crate::queue::{ VkQueue, VkQueueInfo, VkQueueType, }; use crate::raw::{ RawVkDevice, RawVkInstance, VkFeatures, }; use crate::renderpass::{ VkAttachmentInfo, VkRenderPassInfo, VkSubpassInfo, }; use crate::rt::VkAccelerationStructure; use crate::sync::VkTimelineSemaphore; use crate::texture::{ VkSampler, VkTexture, VkTextureView, }; use crate::transfer::VkTransfer; use crate::{ VkBackend, VkShared, VkThreadManager, }; pub struct VkDevice { device: Arc<RawVkDevice>, graphics_queue: Arc<VkQueue>, compute_queue: Option<Arc<VkQueue>>, transfer_queue: Option<Arc<VkQueue>>, context: Arc<VkThreadManager>, transfer: VkTransfer, shared: Arc<VkShared>, query_count: AtomicU64, } impl VkDevice { pub fn new( device: ash::Device, instance: &Arc<RawVkInstance>, physical_device: vk::PhysicalDevice, graphics_queue_info: VkQueueInfo, compute_queue_info: Option<VkQueueInfo>, transfer_queue_info: Option<VkQueueInfo>, features: VkFeatures, max_surface_image_count: u32, ) -> Self { let mut vma_flags = vma_sys::VmaAllocatorCreateFlags::default(); if features.intersects(VkFeatures::DEDICATED_ALLOCATION) { vma_flags |= vma_sys::VmaAllocatorCreateFlagBits_VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT as u32; } if features.intersects(VkFeatures::RAY_TRACING) { vma_flags |= vma_sys::VmaAllocatorCreateFlagBits_VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT as u32; } let allocator = unsafe { unsafe extern "system" fn get_instance_proc_addr_stub( _instance: ash::vk::Instance, _p_name: *const ::std::os::raw::c_char, ) -> ash::vk::PFN_vkVoidFunction { panic!("VMA_DYNAMIC_VULKAN_FUNCTIONS is unsupported") } unsafe extern "system" fn get_get_device_proc_stub( _device: ash::vk::Device, _p_name: *const ::std::os::raw::c_char, ) -> ash::vk::PFN_vkVoidFunction { panic!("VMA_DYNAMIC_VULKAN_FUNCTIONS is unsupported") } let routed_functions = vma_sys::VmaVulkanFunctions { vkGetInstanceProcAddr: None, vkGetDeviceProcAddr: None, vkGetPhysicalDeviceProperties: Some( instance.fp_v1_0().get_physical_device_properties, ), vkGetPhysicalDeviceMemoryProperties: Some( instance.fp_v1_0().get_physical_device_memory_properties, ), vkAllocateMemory: Some(device.fp_v1_0().allocate_memory), vkFreeMemory: Some(device.fp_v1_0().free_memory), vkMapMemory: Some(device.fp_v1_0().map_memory), vkUnmapMemory: Some(device.fp_v1_0().unmap_memory), vkFlushMappedMemoryRanges: Some(device.fp_v1_0().flush_mapped_memory_ranges), vkInvalidateMappedMemoryRanges: Some( device.fp_v1_0().invalidate_mapped_memory_ranges, ), vkBindBufferMemory: Some(device.fp_v1_0().bind_buffer_memory), vkBindImageMemory: Some(device.fp_v1_0().bind_image_memory), vkGetBufferMemoryRequirements: Some( device.fp_v1_0().get_buffer_memory_requirements, ), vkGetImageMemoryRequirements: Some(device.fp_v1_0().get_image_memory_requirements), vkCreateBuffer: Some(device.fp_v1_0().create_buffer), vkDestroyBuffer: Some(device.fp_v1_0().destroy_buffer), vkCreateImage: Some(device.fp_v1_0().create_image), vkDestroyImage: Some(device.fp_v1_0().destroy_image), vkCmdCopyBuffer: Some(device.fp_v1_0().cmd_copy_buffer), vkGetBufferMemoryRequirements2KHR: Some( device.fp_v1_1().get_buffer_memory_requirements2, ), vkGetImageMemoryRequirements2KHR: Some( device.fp_v1_1().get_image_memory_requirements2, ), vkBindBufferMemory2KHR: Some(device.fp_v1_1().bind_buffer_memory2), vkBindImageMemory2KHR: Some(device.fp_v1_1().bind_image_memory2), vkGetPhysicalDeviceMemoryProperties2KHR: Some( instance.fp_v1_1().get_physical_device_memory_properties2, ), vkGetDeviceBufferMemoryRequirements: None, // device.fp_v1_3().get_device_buffer_memory_requirements, vkGetDeviceImageMemoryRequirements: None, // device.fp_v1_3().get_device_image_memory_requirements, }; let vma_create_info = vma_sys::VmaAllocatorCreateInfo { flags: vma_flags, physicalDevice: physical_device, device: device.handle(), preferredLargeHeapBlockSize: 0, pAllocationCallbacks: std::ptr::null(), pDeviceMemoryCallbacks: std::ptr::null(), pHeapSizeLimit: std::ptr::null(), pVulkanFunctions: &routed_functions, instance: instance.handle(), vulkanApiVersion: vk::API_VERSION_1_1, pTypeExternalMemoryHandleTypes: std::ptr::null(), }; let mut allocator: vma_sys::VmaAllocator = std::ptr::null_mut(); assert_eq!( vma_sys::vmaCreateAllocator(&vma_create_info, &mut allocator), vk::Result::SUCCESS ); allocator }; let raw_graphics_queue = unsafe { device.get_device_queue( graphics_queue_info.queue_family_index as u32, graphics_queue_info.queue_index as u32, ) }; let raw_compute_queue = compute_queue_info.map(|info| unsafe { device.get_device_queue(info.queue_family_index as u32, info.queue_index as u32) }); let raw_transfer_queue = transfer_queue_info.map(|info| unsafe { device.get_device_queue(info.queue_family_index as u32, info.queue_index as u32) }); let raw = Arc::new(RawVkDevice::new( device, allocator, physical_device, instance.clone(), features, graphics_queue_info, compute_queue_info, transfer_queue_info, raw_graphics_queue, raw_compute_queue, raw_transfer_queue, )); let shared = Arc::new(VkShared::new(&raw)); let context = Arc::new(VkThreadManager::new( &raw, &graphics_queue_info, compute_queue_info.as_ref(), transfer_queue_info.as_ref(), &shared, min(3, max_surface_image_count), )); let graphics_queue = { Arc::new(VkQueue::new( graphics_queue_info, VkQueueType::Graphics, &raw, &shared, &context, )) }; let compute_queue = compute_queue_info.map(|info| { Arc::new(VkQueue::new( info, VkQueueType::Compute, &raw, &shared, &context, )) }); let transfer_queue = transfer_queue_info.map(|info| { Arc::new(VkQueue::new( info, VkQueueType::Transfer, &raw, &shared, &context, )) }); let transfer = VkTransfer::new(&raw, &graphics_queue, &transfer_queue, &shared); VkDevice { device: raw, graphics_queue, compute_queue, transfer_queue, context, transfer, shared, query_count: AtomicU64::new(0), } } #[inline] pub fn inner(&self) -> &Arc<RawVkDevice> { &self.device } #[inline] pub fn graphics_queue(&self) -> &Arc<VkQueue> { &self.graphics_queue } #[inline] pub fn compute_queue(&self) -> Option<&Arc<VkQueue>> { self.compute_queue.as_ref() } #[inline] pub fn transfer_queue(&self) -> Option<&Arc<VkQueue>> { self.transfer_queue.as_ref() } } impl Device<VkBackend> for VkDevice { fn create_buffer( &self, info: &BufferInfo, memory_usage: MemoryUsage, name: Option<&str>, ) -> Arc<VkBufferSlice> { self.context .shared() .buffer_allocator() .get_slice(info, memory_usage, name) } fn upload_data<T>( &self, data: &[T], memory_usage: MemoryUsage, usage: BufferUsage, ) -> Arc<VkBufferSlice> where T: 'static + Send + Sync + Sized + Clone, { assert_ne!(memory_usage, MemoryUsage::VRAM); let slice = self.context.shared().buffer_allocator().get_slice( &BufferInfo { size: std::mem::size_of_val(data), usage, }, memory_usage, None, ); unsafe { let ptr = slice.map_unsafe(false).expect("Failed to map buffer slice"); std::ptr::copy(data.as_ptr(), ptr as *mut T, data.len()); slice.unmap_unsafe(true); } slice } fn create_shader( &self, shader_type: ShaderType, bytecode: &[u8], name: Option<&str>, ) -> Arc<VkShader> { Arc::new(VkShader::new(&self.device, shader_type, bytecode, name)) } fn create_texture(&self, info: &TextureInfo, name: Option<&str>) -> Arc<VkTexture> { Arc::new(VkTexture::new(&self.device, info, name)) } fn create_texture_view( &self, texture: &Arc<VkTexture>, info: &TextureViewInfo, name: Option<&str>, ) -> Arc<VkTextureView> { Arc::new(VkTextureView::new(&self.device, texture, info, name)) } fn create_sampler(&self, info: &SamplerInfo) -> Arc<VkSampler> { Arc::new(VkSampler::new(&self.device, info)) } fn create_compute_pipeline( &self, shader: &Arc<VkShader>, name: Option<&str>, ) -> Arc<VkPipeline> { Arc::new(VkPipeline::new_compute( &self.device, shader, self.context.shared(), name, )) } fn wait_for_idle(&self) { self.graphics_queue.wait_for_idle(); if let Some(queue) = self.transfer_queue.as_ref() { queue.wait_for_idle(); } if let Some(queue) = self.compute_queue.as_ref() { queue.wait_for_idle(); } self.device.wait_for_idle(); } fn create_graphics_pipeline( &self, info: &GraphicsPipelineInfo<VkBackend>, renderpass_info: &RenderPassInfo, subpass: u32, name: Option<&str>, ) -> Arc<<VkBackend as Backend>::GraphicsPipeline> { let shared = self.context.shared(); let rp_info = VkRenderPassInfo { attachments: renderpass_info .attachments .iter() .map(|a| VkAttachmentInfo { format: a.format, samples: a.samples, load_op: LoadOp::DontCare, store_op: StoreOp::DontCare, stencil_load_op: LoadOp::DontCare, stencil_store_op: StoreOp::DontCare, }) .collect(), subpasses: renderpass_info .subpasses .iter() .map(|sp| VkSubpassInfo { input_attachments: sp.input_attachments.iter().cloned().collect(), output_color_attachments: sp.output_color_attachments.iter().cloned().collect(), depth_stencil_attachment: sp.depth_stencil_attachment.clone(), }) .collect(), }; let rp = shared.get_render_pass(rp_info); let vk_info = VkGraphicsPipelineInfo { info, render_pass: &rp, sub_pass: subpass, }; Arc::new(VkPipeline::new_graphics( &self.device, &vk_info, shared, name, )) } fn init_texture( &self, texture: &Arc<VkTexture>, buffer: &Arc<VkBufferSlice>, mip_level: u32, array_layer: u32, buffer_offset: usize, ) { self.transfer .init_texture(texture, buffer, mip_level, array_layer, buffer_offset); } fn init_texture_async( &self, texture: &Arc<VkTexture>, buffer: &Arc<VkBufferSlice>, mip_level: u32, array_layer: u32, buffer_offset: usize, ) -> Option<FenceValuePair<VkBackend>> { self.transfer .init_texture_async(texture, buffer, mip_level, array_layer, buffer_offset) } fn init_buffer( &self, src_buffer: &Arc<VkBufferSlice>, dst_buffer: &Arc<VkBufferSlice>, src_offset: usize, dst_offset: usize, length: usize, ) { self.transfer .init_buffer(src_buffer, dst_buffer, src_offset, dst_offset, length); } fn flush_transfers(&self) { self.transfer.flush(); } fn free_completed_transfers(&self) { self.transfer.try_free_used_buffers(); } fn create_fence(&self) -> Arc<VkTimelineSemaphore> { Arc::new(VkTimelineSemaphore::new(&self.device)) } fn graphics_queue(&self) -> &Arc<VkQueue> { &self.graphics_queue } fn prerendered_frames(&self) -> u32 { self.context.prerendered_frames() } fn supports_bindless(&self) -> bool { self.device .features .contains(VkFeatures::DESCRIPTOR_INDEXING) } fn supports_ray_tracing(&self) -> bool { self.device.features.contains(VkFeatures::RAY_TRACING) } fn supports_indirect(&self) -> bool { self.device.features.contains(VkFeatures::ADVANCED_INDIRECT) } fn supports_min_max_filter(&self) -> bool { self.device.features.contains(VkFeatures::MIN_MAX_FILTER) } fn insert_texture_into_bindless_heap(&self, texture: &Arc<VkTextureView>) -> u32 { let bindless_set = self .shared .bindless_texture_descriptor_set() .expect("Descriptor indexing is not supported on this device."); let slot = bindless_set.write_texture_descriptor(texture); texture.texture().set_bindless_slot(bindless_set, slot); slot } fn get_bottom_level_acceleration_structure_size( &self, info: &BottomLevelAccelerationStructureInfo<VkBackend>, ) -> AccelerationStructureSizes { VkAccelerationStructure::bottom_level_size(&self.device, info) } fn get_top_level_acceleration_structure_size( &self, info: &TopLevelAccelerationStructureInfo<VkBackend>, ) -> AccelerationStructureSizes { VkAccelerationStructure::top_level_size(&self.device, info) } fn create_raytracing_pipeline( &self, info: &RayTracingPipelineInfo<VkBackend>, ) -> Arc<VkPipeline> { Arc::new(VkPipeline::new_ray_tracing( &self.device, info, &self.shared, )) } fn supports_barycentrics(&self) -> bool { self.device.features.contains(VkFeatures::BARYCENTRICS) } fn begin_frame(&self) { self.context.begin_frame(); } } impl Drop for VkDevice { fn drop(&mut self) { self.wait_for_idle(); } } #[derive(Debug)] pub(crate) struct VulkanMemoryFlags { pub(crate) preferred: vk::MemoryPropertyFlags, pub(crate) required: vk::MemoryPropertyFlags, } pub(crate) fn memory_usage_to_vma(memory_usage: MemoryUsage) -> VulkanMemoryFlags { use vk::MemoryPropertyFlags as VkMem; match memory_usage { MemoryUsage::CachedRAM => VulkanMemoryFlags { preferred: VkMem::HOST_COHERENT, required: VkMem::HOST_VISIBLE | VkMem::HOST_CACHED, }, MemoryUsage::VRAM => VulkanMemoryFlags { preferred: VkMem::DEVICE_LOCAL, required: VkMem::empty(), }, MemoryUsage::UncachedRAM => VulkanMemoryFlags { preferred: VkMem::HOST_COHERENT, required: VkMem::HOST_VISIBLE, }, MemoryUsage::MappableVRAM => VulkanMemoryFlags { preferred: VkMem::DEVICE_LOCAL | VkMem::HOST_COHERENT, // Fall back to uncached RAM required: VkMem::HOST_VISIBLE, }, } }
/// Module defining all possible events we might receive from neovim #[derive(Debug)] pub enum Event { Shutdown, Search, }
#[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::FLOWCTL { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct EMAC_FLOWCTL_FCBBPAR { bits: bool, } impl EMAC_FLOWCTL_FCBBPAR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FLOWCTL_FCBBPAW<'a> { w: &'a mut W, } impl<'a> _EMAC_FLOWCTL_FCBBPAW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FLOWCTL_TFER { bits: bool, } impl EMAC_FLOWCTL_TFER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FLOWCTL_TFEW<'a> { w: &'a mut W, } impl<'a> _EMAC_FLOWCTL_TFEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FLOWCTL_RFER { bits: bool, } impl EMAC_FLOWCTL_RFER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FLOWCTL_RFEW<'a> { w: &'a mut W, } impl<'a> _EMAC_FLOWCTL_RFEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FLOWCTL_UPR { bits: bool, } impl EMAC_FLOWCTL_UPR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FLOWCTL_UPW<'a> { w: &'a mut W, } impl<'a> _EMAC_FLOWCTL_UPW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = "Possible values of the field `EMAC_FLOWCTL_PLT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EMAC_FLOWCTL_PLTR { #[doc = "The threshold is Pause time minus 4 slot times (PT - 4 slot times)"] EMAC_FLOWCTL_PLT_4, #[doc = "The threshold is Pause time minus 28 slot times (PT - 28 slot times)"] EMAC_FLOWCTL_PLT_28, #[doc = "The threshold is Pause time minus 144 slot times (PT - 144 slot times)"] EMAC_FLOWCTL_PLT_144, #[doc = "The threshold is Pause time minus 256 slot times (PT - 256 slot times)"] EMAC_FLOWCTL_PLT_156, } impl EMAC_FLOWCTL_PLTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EMAC_FLOWCTL_PLTR::EMAC_FLOWCTL_PLT_4 => 0, EMAC_FLOWCTL_PLTR::EMAC_FLOWCTL_PLT_28 => 1, EMAC_FLOWCTL_PLTR::EMAC_FLOWCTL_PLT_144 => 2, EMAC_FLOWCTL_PLTR::EMAC_FLOWCTL_PLT_156 => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EMAC_FLOWCTL_PLTR { match value { 0 => EMAC_FLOWCTL_PLTR::EMAC_FLOWCTL_PLT_4, 1 => EMAC_FLOWCTL_PLTR::EMAC_FLOWCTL_PLT_28, 2 => EMAC_FLOWCTL_PLTR::EMAC_FLOWCTL_PLT_144, 3 => EMAC_FLOWCTL_PLTR::EMAC_FLOWCTL_PLT_156, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `EMAC_FLOWCTL_PLT_4`"] #[inline(always)] pub fn is_emac_flowctl_plt_4(&self) -> bool { *self == EMAC_FLOWCTL_PLTR::EMAC_FLOWCTL_PLT_4 } #[doc = "Checks if the value of the field is `EMAC_FLOWCTL_PLT_28`"] #[inline(always)] pub fn is_emac_flowctl_plt_28(&self) -> bool { *self == EMAC_FLOWCTL_PLTR::EMAC_FLOWCTL_PLT_28 } #[doc = "Checks if the value of the field is `EMAC_FLOWCTL_PLT_144`"] #[inline(always)] pub fn is_emac_flowctl_plt_144(&self) -> bool { *self == EMAC_FLOWCTL_PLTR::EMAC_FLOWCTL_PLT_144 } #[doc = "Checks if the value of the field is `EMAC_FLOWCTL_PLT_156`"] #[inline(always)] pub fn is_emac_flowctl_plt_156(&self) -> bool { *self == EMAC_FLOWCTL_PLTR::EMAC_FLOWCTL_PLT_156 } } #[doc = "Values that can be written to the field `EMAC_FLOWCTL_PLT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EMAC_FLOWCTL_PLTW { #[doc = "The threshold is Pause time minus 4 slot times (PT - 4 slot times)"] EMAC_FLOWCTL_PLT_4, #[doc = "The threshold is Pause time minus 28 slot times (PT - 28 slot times)"] EMAC_FLOWCTL_PLT_28, #[doc = "The threshold is Pause time minus 144 slot times (PT - 144 slot times)"] EMAC_FLOWCTL_PLT_144, #[doc = "The threshold is Pause time minus 256 slot times (PT - 256 slot times)"] EMAC_FLOWCTL_PLT_156, } impl EMAC_FLOWCTL_PLTW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EMAC_FLOWCTL_PLTW::EMAC_FLOWCTL_PLT_4 => 0, EMAC_FLOWCTL_PLTW::EMAC_FLOWCTL_PLT_28 => 1, EMAC_FLOWCTL_PLTW::EMAC_FLOWCTL_PLT_144 => 2, EMAC_FLOWCTL_PLTW::EMAC_FLOWCTL_PLT_156 => 3, } } } #[doc = r"Proxy"] pub struct _EMAC_FLOWCTL_PLTW<'a> { w: &'a mut W, } impl<'a> _EMAC_FLOWCTL_PLTW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EMAC_FLOWCTL_PLTW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "The threshold is Pause time minus 4 slot times (PT - 4 slot times)"] #[inline(always)] pub fn emac_flowctl_plt_4(self) -> &'a mut W { self.variant(EMAC_FLOWCTL_PLTW::EMAC_FLOWCTL_PLT_4) } #[doc = "The threshold is Pause time minus 28 slot times (PT - 28 slot times)"] #[inline(always)] pub fn emac_flowctl_plt_28(self) -> &'a mut W { self.variant(EMAC_FLOWCTL_PLTW::EMAC_FLOWCTL_PLT_28) } #[doc = "The threshold is Pause time minus 144 slot times (PT - 144 slot times)"] #[inline(always)] pub fn emac_flowctl_plt_144(self) -> &'a mut W { self.variant(EMAC_FLOWCTL_PLTW::EMAC_FLOWCTL_PLT_144) } #[doc = "The threshold is Pause time minus 256 slot times (PT - 256 slot times)"] #[inline(always)] pub fn emac_flowctl_plt_156(self) -> &'a mut W { self.variant(EMAC_FLOWCTL_PLTW::EMAC_FLOWCTL_PLT_156) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 4); self.w.bits |= ((value as u32) & 3) << 4; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FLOWCTL_DZQPR { bits: bool, } impl EMAC_FLOWCTL_DZQPR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EMAC_FLOWCTL_DZQPW<'a> { w: &'a mut W, } impl<'a> _EMAC_FLOWCTL_DZQPW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 7); self.w.bits |= ((value as u32) & 1) << 7; self.w } } #[doc = r"Value of the field"] pub struct EMAC_FLOWCTL_PTR { bits: u16, } impl EMAC_FLOWCTL_PTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u16 { self.bits } } #[doc = r"Proxy"] pub struct _EMAC_FLOWCTL_PTW<'a> { w: &'a mut W, } impl<'a> _EMAC_FLOWCTL_PTW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits &= !(65535 << 16); self.w.bits |= ((value as u32) & 65535) << 16; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Flow Control Busy or Back-pressure Activate"] #[inline(always)] pub fn emac_flowctl_fcbbpa(&self) -> EMAC_FLOWCTL_FCBBPAR { let bits = ((self.bits >> 0) & 1) != 0; EMAC_FLOWCTL_FCBBPAR { bits } } #[doc = "Bit 1 - Transmit Flow Control Enable"] #[inline(always)] pub fn emac_flowctl_tfe(&self) -> EMAC_FLOWCTL_TFER { let bits = ((self.bits >> 1) & 1) != 0; EMAC_FLOWCTL_TFER { bits } } #[doc = "Bit 2 - Receive Flow Control Enable"] #[inline(always)] pub fn emac_flowctl_rfe(&self) -> EMAC_FLOWCTL_RFER { let bits = ((self.bits >> 2) & 1) != 0; EMAC_FLOWCTL_RFER { bits } } #[doc = "Bit 3 - Unicast Pause Frame Detect"] #[inline(always)] pub fn emac_flowctl_up(&self) -> EMAC_FLOWCTL_UPR { let bits = ((self.bits >> 3) & 1) != 0; EMAC_FLOWCTL_UPR { bits } } #[doc = "Bits 4:5 - Pause Low Threshold"] #[inline(always)] pub fn emac_flowctl_plt(&self) -> EMAC_FLOWCTL_PLTR { EMAC_FLOWCTL_PLTR::_from(((self.bits >> 4) & 3) as u8) } #[doc = "Bit 7 - Disable Zero-Quanta Pause"] #[inline(always)] pub fn emac_flowctl_dzqp(&self) -> EMAC_FLOWCTL_DZQPR { let bits = ((self.bits >> 7) & 1) != 0; EMAC_FLOWCTL_DZQPR { bits } } #[doc = "Bits 16:31 - Pause Time"] #[inline(always)] pub fn emac_flowctl_pt(&self) -> EMAC_FLOWCTL_PTR { let bits = ((self.bits >> 16) & 65535) as u16; EMAC_FLOWCTL_PTR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Flow Control Busy or Back-pressure Activate"] #[inline(always)] pub fn emac_flowctl_fcbbpa(&mut self) -> _EMAC_FLOWCTL_FCBBPAW { _EMAC_FLOWCTL_FCBBPAW { w: self } } #[doc = "Bit 1 - Transmit Flow Control Enable"] #[inline(always)] pub fn emac_flowctl_tfe(&mut self) -> _EMAC_FLOWCTL_TFEW { _EMAC_FLOWCTL_TFEW { w: self } } #[doc = "Bit 2 - Receive Flow Control Enable"] #[inline(always)] pub fn emac_flowctl_rfe(&mut self) -> _EMAC_FLOWCTL_RFEW { _EMAC_FLOWCTL_RFEW { w: self } } #[doc = "Bit 3 - Unicast Pause Frame Detect"] #[inline(always)] pub fn emac_flowctl_up(&mut self) -> _EMAC_FLOWCTL_UPW { _EMAC_FLOWCTL_UPW { w: self } } #[doc = "Bits 4:5 - Pause Low Threshold"] #[inline(always)] pub fn emac_flowctl_plt(&mut self) -> _EMAC_FLOWCTL_PLTW { _EMAC_FLOWCTL_PLTW { w: self } } #[doc = "Bit 7 - Disable Zero-Quanta Pause"] #[inline(always)] pub fn emac_flowctl_dzqp(&mut self) -> _EMAC_FLOWCTL_DZQPW { _EMAC_FLOWCTL_DZQPW { w: self } } #[doc = "Bits 16:31 - Pause Time"] #[inline(always)] pub fn emac_flowctl_pt(&mut self) -> _EMAC_FLOWCTL_PTW { _EMAC_FLOWCTL_PTW { w: self } } }
pub struct Solution; impl Solution { pub fn compute_area(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32) -> i32 { let area1 = (c - a) * (d - b); let area2 = (g - e) * (h - f); let i = a.max(e); let j = b.max(f); let k = c.min(g); let l = d.min(h); let intersection = if i < k && j < l { (k - i) * (l - j) } else { 0 }; area1 - intersection + area2 } } #[test] fn test0223() { fn case(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32, want: i32) { let got = Solution::compute_area(a, b, c, d, e, f, g, h); assert_eq!(got, want); } case(-3, 0, 3, 4, 0, -1, 9, 2, 45); }
// iter() -> &T // iter() -> &mut T // into_iter() -> T // iterator is a more basic concept than pointer // fold function fn use_names_for_something_else(_names: Vec<&str>) {} fn test_fold() { let names = vec!["Jane", "Jill", "Jack", "John"]; let total_bytes = names .iter() .map(|name: &&str| name.len()) // this line can be changed // .map(|&&name| name.len()) -- the closure captures the variable .fold(0, |acc, len| acc + len ); // running sum standard usage assert_eq!(total_bytes, 16); use_names_for_something_else(names); } // sort_by funciton fn test_sort_by() { let mut teams = [ [ ("Jack", 20), ("Jane", 23), ("Jill", 18), ("John", 19), ], [ ("Bill", 17), ("Brenda", 16), ("Brad", 18), ("Barbara", 17), ] ]; let teams_in_score_order = teams .iter_mut() .map(|team| { team.sort_by(|&a, &b| a.1.cmp(&b.1).reverse()); // like cmp funciton passed to c++ qsort team }) .collect::<Vec<_>>(); println!("Teams: {:?}", teams_in_score_order); } // the iter & loop fn error_loop_0() { let values = vec![1, 2, 3, 4]; // ownship moved for x in values { println!("{}", x); } let y = values; // move error } fn error_loop_1 { let values = vec![1, 2, 3, 4]; // make no sense that we consume the vec itself let mut it = values.into_iter(); loop { match it.next() { Some(x) => println!("{}", x), None => break, } } } fn test_loop() { let values = vec![1, 2, 3, 4]; for x in &values { println!("{}", x); } let y = values; // perfectly valid } // core::iter::Cloned fn test_iter() { let x = vec!["Jill", "Jack", "Jane", "John"]; let iter_all = x .clone() // clone the vector .into_iter() // into_iter() will consume the caller .collect::<Vec<_>>(); let iter_first_two_0 = x .clone() .into_iter() .take(2) // take() is usually used to transfer infinite iter to finite one // also see skip() .collect::<Vec<_>>(); let iter_first_two_1 = x .iter() .map(|i| i.clone()) .take(2) .collect::<Vec<_>>(); let iter_first_two_2 = x .iter() .cloned() // clone the iter (watch the type) .take(2) .collect::<Vec<_>>(); }
import str::sbuf; #[cfg(target_os = "linux")] #[cfg(target_os = "macos")] fn getenv(n: str) -> option::t[str] { let s = os::libc::getenv(str::buf(n)); ret if s as int == 0 { option::none[str] } else { option::some[str](str::str_from_cstr(s)) }; } #[cfg(target_os = "linux")] #[cfg(target_os = "macos")] fn setenv(n: str, v: str) { let nbuf = str::buf(n); let vbuf = str::buf(v); os::libc::setenv(nbuf, vbuf, 1); } #[cfg(target_os = "win32")] fn getenv(n: str) -> option::t[str] { let nbuf = str::buf(n); let nsize = 256u; while true { let vstr = str::alloc(nsize - 1u); let vbuf = str::buf(vstr); let res = os::kernel32::GetEnvironmentVariableA(nbuf, vbuf, nsize); if res == 0u { ret option::none; } else if (res < nsize) { ret option::some(str::str_from_cstr(vbuf)); } else { nsize = res; } } fail; } #[cfg(target_os = "win32")] fn setenv(n: str, v: str) { let nbuf = str::buf(n); let vbuf = str::buf(v); os::kernel32::SetEnvironmentVariableA(nbuf, vbuf); } // Local Variables: // mode: rust; // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // compile-command: "make -k -C .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'"; // End:
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. //! Emulates virtual and hardware devices. extern crate epoll; extern crate libc; extern crate dumbo; #[macro_use] extern crate logger; extern crate net_gen; extern crate rate_limiter; extern crate virtio_gen; extern crate vm_memory; use rate_limiter::Error as RateLimiterError; use std::io; mod bus; pub mod legacy; pub mod virtio; pub use self::bus::{Bus, BusDevice, Error as BusError, RawIOHandler}; use virtio::AsAny; pub type DeviceEventT = u16; type Result<T> = std::result::Result<T, Error>; pub trait EpollHandler: AsAny + Send { fn handle_event(&mut self, device_event: DeviceEventT, evset: epoll::Events) -> Result<()>; } #[derive(Debug)] pub enum Error { FailedReadingQueue { event_type: &'static str, underlying: io::Error, }, FailedReadTap, FailedSignalingUsedQueue(io::Error), RateLimited(RateLimiterError), PayloadExpected, UnknownEvent { device: &'static str, event: DeviceEventT, }, IoError(io::Error), NoAvailBuffers, }
use crate::Actor; use crate::Assistant; use async_trait::async_trait; use std::fmt::Debug; /// This Trait allow Actors to receive messages. /// /// Following the example in the [Actor documentation](./trait.Actor.html)... /// ```rust,no_run /// use async_trait::async_trait; /// # use acteur::{Actor}; /// # #[derive(Debug)] /// # struct Employee { /// # id: u32, /// # salary: u32, /// # } /// # /// # #[async_trait] /// # impl Actor for Employee { /// # type Id = u32; /// # /// # async fn activate(id: Self::Id) -> Self { /// # println!("Employee {:?} activated!", id); /// # Employee { /// # id, /// # salary: 0 //Load from DB, set a default, etc /// # } /// # } /// # /// # async fn deactivate(&mut self) { /// # println!("Employee {:?} deactivated!", self.id); /// # } /// # } /// use acteur::{Assistant, Handle, System}; /// /// #[derive(Debug)] /// struct SalaryChanged(u32); /// /// #[async_trait] /// impl Handle<SalaryChanged> for Employee { /// async fn handle(&mut self, message: SalaryChanged, _: Assistant) { /// self.salary = message.0; /// } /// } /// /// fn main() { /// let sys = System::new(); /// /// sys.send::<Employee, SalaryChanged>(42, SalaryChanged(55000)); /// /// sys.wait_until_stopped(); /// } /// /// ``` /// /// This actor will send messages counting until one million and then stop the system. /// /// You can use the [Assistant](./struct.Assistant.html) in order to interact with other actors and the system. /// /// Note: You usually don't call stop_system in there, as it will stop the whole actor framework. /// #[async_trait] pub trait Handle<T: Debug>: Actor { /// This method is called each time a message is received. You can use the [Assistant](./struct.Assistant.html) to send messages async fn handle(&mut self, message: T, assistant: Assistant); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "ApplicationModel_Payments_Provider")] pub mod Provider; #[repr(transparent)] #[doc(hidden)] pub struct IPaymentAddress(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentAddress { type Vtable = IPaymentAddress_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5f2264e9_6f3a_4166_a018_0a0b06bb32b5); } #[repr(C)] #[doc(hidden)] pub struct IPaymentAddress_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::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, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentCanMakePaymentResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentCanMakePaymentResult { type Vtable = IPaymentCanMakePaymentResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7696fe55_d5d3_4d3d_b345_45591759c510); } #[repr(C)] #[doc(hidden)] pub struct IPaymentCanMakePaymentResult_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 PaymentCanMakePaymentResultStatus) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentCanMakePaymentResultFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentCanMakePaymentResultFactory { type Vtable = IPaymentCanMakePaymentResultFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbbdcaa3e_7d49_4f69_aa53_2a0f8164b7c9); } #[repr(C)] #[doc(hidden)] pub struct IPaymentCanMakePaymentResultFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: PaymentCanMakePaymentResultStatus, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentCurrencyAmount(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentCurrencyAmount { type Vtable = IPaymentCurrencyAmount_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe3a3e9e0_b41f_4987_bdcb_071331f2daa4); } #[repr(C)] #[doc(hidden)] pub struct IPaymentCurrencyAmount_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentCurrencyAmountFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentCurrencyAmountFactory { type Vtable = IPaymentCurrencyAmountFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3257d338_140c_4575_8535_f773178c09a7); } #[repr(C)] #[doc(hidden)] pub struct IPaymentCurrencyAmountFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, currency: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, currency: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, currencysystem: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentDetails(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentDetails { type Vtable = IPaymentDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x53bb2d7d_e0eb_4053_8eae_ce7c48e02945); } #[repr(C)] #[doc(hidden)] pub struct IPaymentDetails_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, value: ::windows::core::RawPtr) -> ::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, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentDetailsFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentDetailsFactory { type Vtable = IPaymentDetailsFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcfe8afee_c0ea_4ca1_8bc7_6de67b1f3763); } #[repr(C)] #[doc(hidden)] pub struct IPaymentDetailsFactory_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, total: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, total: ::windows::core::RawPtr, displayitems: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentDetailsModifier(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentDetailsModifier { type Vtable = IPaymentDetailsModifier_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbe1c7d65_4323_41d7_b305_dfcb765f69de); } #[repr(C)] #[doc(hidden)] pub struct IPaymentDetailsModifier_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentDetailsModifierFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentDetailsModifierFactory { type Vtable = IPaymentDetailsModifierFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79005286_54de_429c_9e4f_5dce6e10ebce); } #[repr(C)] #[doc(hidden)] pub struct IPaymentDetailsModifierFactory_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, supportedmethodids: ::windows::core::RawPtr, total: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, supportedmethodids: ::windows::core::RawPtr, total: ::windows::core::RawPtr, additionaldisplayitems: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, supportedmethodids: ::windows::core::RawPtr, total: ::windows::core::RawPtr, additionaldisplayitems: ::windows::core::RawPtr, jsondata: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentItem(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentItem { type Vtable = IPaymentItem_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x685ac88b_79b2_4b76_9e03_a876223dfe72); } #[repr(C)] #[doc(hidden)] pub struct IPaymentItem_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, 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, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, 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 IPaymentItemFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentItemFactory { type Vtable = IPaymentItemFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc6ab7ad8_2503_4d1d_a778_02b2e5927b2c); } #[repr(C)] #[doc(hidden)] pub struct IPaymentItemFactory_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, label: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, amount: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentMediator(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentMediator { type Vtable = IPaymentMediator_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb0ee829_ec0c_449a_83da_7ae3073365a2); } #[repr(C)] #[doc(hidden)] pub struct IPaymentMediator_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, paymentrequest: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, paymentrequest: ::windows::core::RawPtr, changehandler: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentMediator2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentMediator2 { type Vtable = IPaymentMediator2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xceef98f1_e407_4128_8e73_d93d5f822786); } #[repr(C)] #[doc(hidden)] pub struct IPaymentMediator2_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, paymentrequest: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentMerchantInfo(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentMerchantInfo { type Vtable = IPaymentMerchantInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x63445050_0e94_4ed6_aacb_e6012bd327a7); } #[repr(C)] #[doc(hidden)] pub struct IPaymentMerchantInfo_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[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 IPaymentMerchantInfoFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentMerchantInfoFactory { type Vtable = IPaymentMerchantInfoFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9e89ced3_ccb7_4167_a8ec_e10ae96dbcd1); } #[repr(C)] #[doc(hidden)] pub struct IPaymentMerchantInfoFactory_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, uri: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentMethodData(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentMethodData { type Vtable = IPaymentMethodData_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd1d3caf4_de98_4129_b1b7_c3ad86237bf4); } #[repr(C)] #[doc(hidden)] pub struct IPaymentMethodData_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentMethodDataFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentMethodDataFactory { type Vtable = IPaymentMethodDataFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8addd27f_9baa_4a82_8342_a8210992a36b); } #[repr(C)] #[doc(hidden)] pub struct IPaymentMethodDataFactory_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, supportedmethodids: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, supportedmethodids: ::windows::core::RawPtr, jsondata: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentOptions(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentOptions { type Vtable = IPaymentOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaaa30854_1f2b_4365_8251_01b58915a5bc); } #[repr(C)] #[doc(hidden)] pub struct IPaymentOptions_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 PaymentOptionPresence) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: PaymentOptionPresence) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PaymentOptionPresence) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: PaymentOptionPresence) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PaymentOptionPresence) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: PaymentOptionPresence) -> ::windows::core::HRESULT, 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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PaymentShippingType) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: PaymentShippingType) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentRequest(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentRequest { type Vtable = IPaymentRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb74942e1_ed7b_47eb_bc08_78cc5d6896b6); } #[repr(C)] #[doc(hidden)] pub struct IPaymentRequest_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, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentRequest2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentRequest2 { type Vtable = IPaymentRequest2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb63ccfb5_5998_493e_a04c_67048a50f141); } #[repr(C)] #[doc(hidden)] pub struct IPaymentRequest2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentRequestChangedArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentRequestChangedArgs { type Vtable = IPaymentRequestChangedArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc6145e44_cd8b_4be4_b555_27c99194c0c5); } #[repr(C)] #[doc(hidden)] pub struct IPaymentRequestChangedArgs_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 PaymentRequestChangeKind) -> ::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, changeresult: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentRequestChangedResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentRequestChangedResult { type Vtable = IPaymentRequestChangedResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdf699e5c_16c4_47ad_9401_8440ec0757db); } #[repr(C)] #[doc(hidden)] pub struct IPaymentRequestChangedResult_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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 IPaymentRequestChangedResultFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentRequestChangedResultFactory { type Vtable = IPaymentRequestChangedResultFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x08740f56_1d33_4431_814b_67ea24bf21db); } #[repr(C)] #[doc(hidden)] pub struct IPaymentRequestChangedResultFactory_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, changeacceptedbymerchant: bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, changeacceptedbymerchant: bool, updatedpaymentdetails: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentRequestFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentRequestFactory { type Vtable = IPaymentRequestFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3e8a79dc_6b74_42d3_b103_f0de35fb1848); } #[repr(C)] #[doc(hidden)] pub struct IPaymentRequestFactory_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, details: ::windows::core::RawPtr, methoddata: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, details: ::windows::core::RawPtr, methoddata: ::windows::core::RawPtr, merchantinfo: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, details: ::windows::core::RawPtr, methoddata: ::windows::core::RawPtr, merchantinfo: ::windows::core::RawPtr, options: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentRequestFactory2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentRequestFactory2 { type Vtable = IPaymentRequestFactory2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe6ce1325_a506_4372_b7ef_1a031d5662d1); } #[repr(C)] #[doc(hidden)] pub struct IPaymentRequestFactory2_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, details: ::windows::core::RawPtr, methoddata: ::windows::core::RawPtr, merchantinfo: ::windows::core::RawPtr, options: ::windows::core::RawPtr, id: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentRequestSubmitResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentRequestSubmitResult { type Vtable = IPaymentRequestSubmitResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7b9c3912_30f2_4e90_b249_8ce7d78ffe56); } #[repr(C)] #[doc(hidden)] pub struct IPaymentRequestSubmitResult_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 PaymentRequestStatus) -> ::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 IPaymentResponse(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentResponse { type Vtable = IPaymentResponse_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe1389457_8bd2_4888_9fa8_97985545108e); } #[repr(C)] #[doc(hidden)] pub struct IPaymentResponse_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, status: PaymentRequestCompletionStatus, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentShippingOption(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentShippingOption { type Vtable = IPaymentShippingOption_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x13372ada_9753_4574_8966_93145a76c7f9); } #[repr(C)] #[doc(hidden)] pub struct IPaymentShippingOption_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, 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, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentShippingOptionFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentShippingOptionFactory { type Vtable = IPaymentShippingOptionFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5de5f917_b2d7_446b_9d73_6123fbca3bc6); } #[repr(C)] #[doc(hidden)] pub struct IPaymentShippingOptionFactory_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, label: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, amount: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, label: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, amount: ::windows::core::RawPtr, selected: bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, label: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, amount: ::windows::core::RawPtr, selected: bool, tag: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentToken(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentToken { type Vtable = IPaymentToken_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbbcac013_ccd0_41f2_b2a1_0a2e4b5dce25); } #[repr(C)] #[doc(hidden)] pub struct IPaymentToken_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPaymentTokenFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPaymentTokenFactory { type Vtable = IPaymentTokenFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x988cd7aa_4753_4904_8373_dd7b08b995c1); } #[repr(C)] #[doc(hidden)] pub struct IPaymentTokenFactory_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, paymentmethodid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, paymentmethodid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, jsondetails: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentAddress(pub ::windows::core::IInspectable); impl PaymentAddress { 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<PaymentAddress, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn Country(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetCountry<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn AddressLines(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn SetAddressLines<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>>(&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 Region(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetRegion<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn City(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetCity<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn DependentLocality(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetDependentLocality<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn PostalCode(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetPostalCode<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn SortingCode(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetSortingCode<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn LanguageCode(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetLanguageCode<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Organization(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetOrganization<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Recipient(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetRecipient<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn PhoneNumber(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetPhoneNumber<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn Properties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::ValueSet> { let this = self; 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::<super::super::Foundation::Collections::ValueSet>(result__) } } } unsafe impl ::windows::core::RuntimeType for PaymentAddress { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentAddress;{5f2264e9-6f3a-4166-a018-0a0b06bb32b5})"); } unsafe impl ::windows::core::Interface for PaymentAddress { type Vtable = IPaymentAddress_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5f2264e9_6f3a_4166_a018_0a0b06bb32b5); } impl ::windows::core::RuntimeName for PaymentAddress { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentAddress"; } impl ::core::convert::From<PaymentAddress> for ::windows::core::IUnknown { fn from(value: PaymentAddress) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentAddress> for ::windows::core::IUnknown { fn from(value: &PaymentAddress) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentAddress { 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 PaymentAddress { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentAddress> for ::windows::core::IInspectable { fn from(value: PaymentAddress) -> Self { value.0 } } impl ::core::convert::From<&PaymentAddress> for ::windows::core::IInspectable { fn from(value: &PaymentAddress) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentAddress { 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 PaymentAddress { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentAddress {} unsafe impl ::core::marker::Sync for PaymentAddress {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentCanMakePaymentResult(pub ::windows::core::IInspectable); impl PaymentCanMakePaymentResult { pub fn Status(&self) -> ::windows::core::Result<PaymentCanMakePaymentResultStatus> { let this = self; unsafe { let mut result__: PaymentCanMakePaymentResultStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PaymentCanMakePaymentResultStatus>(result__) } } pub fn Create(value: PaymentCanMakePaymentResultStatus) -> ::windows::core::Result<PaymentCanMakePaymentResult> { Self::IPaymentCanMakePaymentResultFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<PaymentCanMakePaymentResult>(result__) }) } pub fn IPaymentCanMakePaymentResultFactory<R, F: FnOnce(&IPaymentCanMakePaymentResultFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PaymentCanMakePaymentResult, IPaymentCanMakePaymentResultFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PaymentCanMakePaymentResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentCanMakePaymentResult;{7696fe55-d5d3-4d3d-b345-45591759c510})"); } unsafe impl ::windows::core::Interface for PaymentCanMakePaymentResult { type Vtable = IPaymentCanMakePaymentResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7696fe55_d5d3_4d3d_b345_45591759c510); } impl ::windows::core::RuntimeName for PaymentCanMakePaymentResult { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentCanMakePaymentResult"; } impl ::core::convert::From<PaymentCanMakePaymentResult> for ::windows::core::IUnknown { fn from(value: PaymentCanMakePaymentResult) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentCanMakePaymentResult> for ::windows::core::IUnknown { fn from(value: &PaymentCanMakePaymentResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentCanMakePaymentResult { 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 PaymentCanMakePaymentResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentCanMakePaymentResult> for ::windows::core::IInspectable { fn from(value: PaymentCanMakePaymentResult) -> Self { value.0 } } impl ::core::convert::From<&PaymentCanMakePaymentResult> for ::windows::core::IInspectable { fn from(value: &PaymentCanMakePaymentResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentCanMakePaymentResult { 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 PaymentCanMakePaymentResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentCanMakePaymentResult {} unsafe impl ::core::marker::Sync for PaymentCanMakePaymentResult {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PaymentCanMakePaymentResultStatus(pub i32); impl PaymentCanMakePaymentResultStatus { pub const Unknown: PaymentCanMakePaymentResultStatus = PaymentCanMakePaymentResultStatus(0i32); pub const Yes: PaymentCanMakePaymentResultStatus = PaymentCanMakePaymentResultStatus(1i32); pub const No: PaymentCanMakePaymentResultStatus = PaymentCanMakePaymentResultStatus(2i32); pub const NotAllowed: PaymentCanMakePaymentResultStatus = PaymentCanMakePaymentResultStatus(3i32); pub const UserNotSignedIn: PaymentCanMakePaymentResultStatus = PaymentCanMakePaymentResultStatus(4i32); pub const SpecifiedPaymentMethodIdsNotSupported: PaymentCanMakePaymentResultStatus = PaymentCanMakePaymentResultStatus(5i32); pub const NoQualifyingCardOnFile: PaymentCanMakePaymentResultStatus = PaymentCanMakePaymentResultStatus(6i32); } impl ::core::convert::From<i32> for PaymentCanMakePaymentResultStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PaymentCanMakePaymentResultStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PaymentCanMakePaymentResultStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Payments.PaymentCanMakePaymentResultStatus;i4)"); } impl ::windows::core::DefaultType for PaymentCanMakePaymentResultStatus { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentCurrencyAmount(pub ::windows::core::IInspectable); impl PaymentCurrencyAmount { pub fn Currency(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetCurrency<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn CurrencySystem(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetCurrencySystem<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&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 Value(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetValue<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(value: Param0, currency: Param1) -> ::windows::core::Result<PaymentCurrencyAmount> { Self::IPaymentCurrencyAmountFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi(), currency.into_param().abi(), &mut result__).from_abi::<PaymentCurrencyAmount>(result__) }) } pub fn CreateWithCurrencySystem<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(value: Param0, currency: Param1, currencysystem: Param2) -> ::windows::core::Result<PaymentCurrencyAmount> { Self::IPaymentCurrencyAmountFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi(), currency.into_param().abi(), currencysystem.into_param().abi(), &mut result__).from_abi::<PaymentCurrencyAmount>(result__) }) } pub fn IPaymentCurrencyAmountFactory<R, F: FnOnce(&IPaymentCurrencyAmountFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PaymentCurrencyAmount, IPaymentCurrencyAmountFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PaymentCurrencyAmount { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentCurrencyAmount;{e3a3e9e0-b41f-4987-bdcb-071331f2daa4})"); } unsafe impl ::windows::core::Interface for PaymentCurrencyAmount { type Vtable = IPaymentCurrencyAmount_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe3a3e9e0_b41f_4987_bdcb_071331f2daa4); } impl ::windows::core::RuntimeName for PaymentCurrencyAmount { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentCurrencyAmount"; } impl ::core::convert::From<PaymentCurrencyAmount> for ::windows::core::IUnknown { fn from(value: PaymentCurrencyAmount) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentCurrencyAmount> for ::windows::core::IUnknown { fn from(value: &PaymentCurrencyAmount) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentCurrencyAmount { 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 PaymentCurrencyAmount { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentCurrencyAmount> for ::windows::core::IInspectable { fn from(value: PaymentCurrencyAmount) -> Self { value.0 } } impl ::core::convert::From<&PaymentCurrencyAmount> for ::windows::core::IInspectable { fn from(value: &PaymentCurrencyAmount) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentCurrencyAmount { 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 PaymentCurrencyAmount { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentCurrencyAmount {} unsafe impl ::core::marker::Sync for PaymentCurrencyAmount {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentDetails(pub ::windows::core::IInspectable); impl PaymentDetails { 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<PaymentDetails, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn Total(&self) -> ::windows::core::Result<PaymentItem> { 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::<PaymentItem>(result__) } } pub fn SetTotal<'a, Param0: ::windows::core::IntoParam<'a, PaymentItem>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn DisplayItems(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PaymentItem>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PaymentItem>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn SetDisplayItems<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IVectorView<PaymentItem>>>(&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() } } #[cfg(feature = "Foundation_Collections")] pub fn ShippingOptions(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PaymentShippingOption>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PaymentShippingOption>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn SetShippingOptions<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IVectorView<PaymentShippingOption>>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn Modifiers(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PaymentDetailsModifier>> { let this = self; 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::super::Foundation::Collections::IVectorView<PaymentDetailsModifier>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn SetModifiers<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IVectorView<PaymentDetailsModifier>>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, PaymentItem>>(total: Param0) -> ::windows::core::Result<PaymentDetails> { Self::IPaymentDetailsFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), total.into_param().abi(), &mut result__).from_abi::<PaymentDetails>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn CreateWithDisplayItems<'a, Param0: ::windows::core::IntoParam<'a, PaymentItem>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<PaymentItem>>>(total: Param0, displayitems: Param1) -> ::windows::core::Result<PaymentDetails> { Self::IPaymentDetailsFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), total.into_param().abi(), displayitems.into_param().abi(), &mut result__).from_abi::<PaymentDetails>(result__) }) } pub fn IPaymentDetailsFactory<R, F: FnOnce(&IPaymentDetailsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PaymentDetails, IPaymentDetailsFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PaymentDetails { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentDetails;{53bb2d7d-e0eb-4053-8eae-ce7c48e02945})"); } unsafe impl ::windows::core::Interface for PaymentDetails { type Vtable = IPaymentDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x53bb2d7d_e0eb_4053_8eae_ce7c48e02945); } impl ::windows::core::RuntimeName for PaymentDetails { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentDetails"; } impl ::core::convert::From<PaymentDetails> for ::windows::core::IUnknown { fn from(value: PaymentDetails) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentDetails> for ::windows::core::IUnknown { fn from(value: &PaymentDetails) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentDetails { 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 PaymentDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentDetails> for ::windows::core::IInspectable { fn from(value: PaymentDetails) -> Self { value.0 } } impl ::core::convert::From<&PaymentDetails> for ::windows::core::IInspectable { fn from(value: &PaymentDetails) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentDetails { 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 PaymentDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentDetails {} unsafe impl ::core::marker::Sync for PaymentDetails {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentDetailsModifier(pub ::windows::core::IInspectable); impl PaymentDetailsModifier { pub fn JsonData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn SupportedMethodIds(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } pub fn Total(&self) -> ::windows::core::Result<PaymentItem> { 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::<PaymentItem>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn AdditionalDisplayItems(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PaymentItem>> { 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::Foundation::Collections::IVectorView<PaymentItem>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param1: ::windows::core::IntoParam<'a, PaymentItem>>(supportedmethodids: Param0, total: Param1) -> ::windows::core::Result<PaymentDetailsModifier> { Self::IPaymentDetailsModifierFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), supportedmethodids.into_param().abi(), total.into_param().abi(), &mut result__).from_abi::<PaymentDetailsModifier>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn CreateWithAdditionalDisplayItems<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param1: ::windows::core::IntoParam<'a, PaymentItem>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<PaymentItem>>>(supportedmethodids: Param0, total: Param1, additionaldisplayitems: Param2) -> ::windows::core::Result<PaymentDetailsModifier> { Self::IPaymentDetailsModifierFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), supportedmethodids.into_param().abi(), total.into_param().abi(), additionaldisplayitems.into_param().abi(), &mut result__).from_abi::<PaymentDetailsModifier>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn CreateWithAdditionalDisplayItemsAndJsonData<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param1: ::windows::core::IntoParam<'a, PaymentItem>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<PaymentItem>>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( supportedmethodids: Param0, total: Param1, additionaldisplayitems: Param2, jsondata: Param3, ) -> ::windows::core::Result<PaymentDetailsModifier> { Self::IPaymentDetailsModifierFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), supportedmethodids.into_param().abi(), total.into_param().abi(), additionaldisplayitems.into_param().abi(), jsondata.into_param().abi(), &mut result__).from_abi::<PaymentDetailsModifier>(result__) }) } pub fn IPaymentDetailsModifierFactory<R, F: FnOnce(&IPaymentDetailsModifierFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PaymentDetailsModifier, IPaymentDetailsModifierFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PaymentDetailsModifier { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentDetailsModifier;{be1c7d65-4323-41d7-b305-dfcb765f69de})"); } unsafe impl ::windows::core::Interface for PaymentDetailsModifier { type Vtable = IPaymentDetailsModifier_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbe1c7d65_4323_41d7_b305_dfcb765f69de); } impl ::windows::core::RuntimeName for PaymentDetailsModifier { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentDetailsModifier"; } impl ::core::convert::From<PaymentDetailsModifier> for ::windows::core::IUnknown { fn from(value: PaymentDetailsModifier) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentDetailsModifier> for ::windows::core::IUnknown { fn from(value: &PaymentDetailsModifier) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentDetailsModifier { 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 PaymentDetailsModifier { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentDetailsModifier> for ::windows::core::IInspectable { fn from(value: PaymentDetailsModifier) -> Self { value.0 } } impl ::core::convert::From<&PaymentDetailsModifier> for ::windows::core::IInspectable { fn from(value: &PaymentDetailsModifier) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentDetailsModifier { 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 PaymentDetailsModifier { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentDetailsModifier {} unsafe impl ::core::marker::Sync for PaymentDetailsModifier {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentItem(pub ::windows::core::IInspectable); impl PaymentItem { pub fn Label(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetLabel<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Amount(&self) -> ::windows::core::Result<PaymentCurrencyAmount> { 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::<PaymentCurrencyAmount>(result__) } } pub fn SetAmount<'a, Param0: ::windows::core::IntoParam<'a, PaymentCurrencyAmount>>(&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 Pending(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetPending(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, PaymentCurrencyAmount>>(label: Param0, amount: Param1) -> ::windows::core::Result<PaymentItem> { Self::IPaymentItemFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), label.into_param().abi(), amount.into_param().abi(), &mut result__).from_abi::<PaymentItem>(result__) }) } pub fn IPaymentItemFactory<R, F: FnOnce(&IPaymentItemFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PaymentItem, IPaymentItemFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PaymentItem { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentItem;{685ac88b-79b2-4b76-9e03-a876223dfe72})"); } unsafe impl ::windows::core::Interface for PaymentItem { type Vtable = IPaymentItem_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x685ac88b_79b2_4b76_9e03_a876223dfe72); } impl ::windows::core::RuntimeName for PaymentItem { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentItem"; } impl ::core::convert::From<PaymentItem> for ::windows::core::IUnknown { fn from(value: PaymentItem) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentItem> for ::windows::core::IUnknown { fn from(value: &PaymentItem) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentItem { 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 PaymentItem { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentItem> for ::windows::core::IInspectable { fn from(value: PaymentItem) -> Self { value.0 } } impl ::core::convert::From<&PaymentItem> for ::windows::core::IInspectable { fn from(value: &PaymentItem) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentItem { 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 PaymentItem { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentItem {} unsafe impl ::core::marker::Sync for PaymentItem {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentMediator(pub ::windows::core::IInspectable); impl PaymentMediator { 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<PaymentMediator, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetSupportedMethodIdsAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>>(result__) } } #[cfg(feature = "Foundation")] pub fn SubmitPaymentRequestAsync<'a, Param0: ::windows::core::IntoParam<'a, PaymentRequest>>(&self, paymentrequest: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PaymentRequestSubmitResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), paymentrequest.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PaymentRequestSubmitResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn SubmitPaymentRequestWithChangeHandlerAsync<'a, Param0: ::windows::core::IntoParam<'a, PaymentRequest>, Param1: ::windows::core::IntoParam<'a, PaymentRequestChangedHandler>>(&self, paymentrequest: Param0, changehandler: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PaymentRequestSubmitResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), paymentrequest.into_param().abi(), changehandler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PaymentRequestSubmitResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn CanMakePaymentAsync<'a, Param0: ::windows::core::IntoParam<'a, PaymentRequest>>(&self, paymentrequest: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PaymentCanMakePaymentResult>> { let this = &::windows::core::Interface::cast::<IPaymentMediator2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), paymentrequest.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PaymentCanMakePaymentResult>>(result__) } } } unsafe impl ::windows::core::RuntimeType for PaymentMediator { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentMediator;{fb0ee829-ec0c-449a-83da-7ae3073365a2})"); } unsafe impl ::windows::core::Interface for PaymentMediator { type Vtable = IPaymentMediator_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb0ee829_ec0c_449a_83da_7ae3073365a2); } impl ::windows::core::RuntimeName for PaymentMediator { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentMediator"; } impl ::core::convert::From<PaymentMediator> for ::windows::core::IUnknown { fn from(value: PaymentMediator) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentMediator> for ::windows::core::IUnknown { fn from(value: &PaymentMediator) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentMediator { 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 PaymentMediator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentMediator> for ::windows::core::IInspectable { fn from(value: PaymentMediator) -> Self { value.0 } } impl ::core::convert::From<&PaymentMediator> for ::windows::core::IInspectable { fn from(value: &PaymentMediator) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentMediator { 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 PaymentMediator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentMediator {} unsafe impl ::core::marker::Sync for PaymentMediator {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentMerchantInfo(pub ::windows::core::IInspectable); impl PaymentMerchantInfo { 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<PaymentMerchantInfo, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn PackageFullName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::Foundation::Uri> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(uri: Param0) -> ::windows::core::Result<PaymentMerchantInfo> { Self::IPaymentMerchantInfoFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uri.into_param().abi(), &mut result__).from_abi::<PaymentMerchantInfo>(result__) }) } pub fn IPaymentMerchantInfoFactory<R, F: FnOnce(&IPaymentMerchantInfoFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PaymentMerchantInfo, IPaymentMerchantInfoFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PaymentMerchantInfo { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentMerchantInfo;{63445050-0e94-4ed6-aacb-e6012bd327a7})"); } unsafe impl ::windows::core::Interface for PaymentMerchantInfo { type Vtable = IPaymentMerchantInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x63445050_0e94_4ed6_aacb_e6012bd327a7); } impl ::windows::core::RuntimeName for PaymentMerchantInfo { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentMerchantInfo"; } impl ::core::convert::From<PaymentMerchantInfo> for ::windows::core::IUnknown { fn from(value: PaymentMerchantInfo) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentMerchantInfo> for ::windows::core::IUnknown { fn from(value: &PaymentMerchantInfo) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentMerchantInfo { 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 PaymentMerchantInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentMerchantInfo> for ::windows::core::IInspectable { fn from(value: PaymentMerchantInfo) -> Self { value.0 } } impl ::core::convert::From<&PaymentMerchantInfo> for ::windows::core::IInspectable { fn from(value: &PaymentMerchantInfo) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentMerchantInfo { 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 PaymentMerchantInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentMerchantInfo {} unsafe impl ::core::marker::Sync for PaymentMerchantInfo {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentMethodData(pub ::windows::core::IInspectable); impl PaymentMethodData { #[cfg(feature = "Foundation_Collections")] pub fn SupportedMethodIds(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } pub fn JsonData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(supportedmethodids: Param0) -> ::windows::core::Result<PaymentMethodData> { Self::IPaymentMethodDataFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), supportedmethodids.into_param().abi(), &mut result__).from_abi::<PaymentMethodData>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn CreateWithJsonData<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(supportedmethodids: Param0, jsondata: Param1) -> ::windows::core::Result<PaymentMethodData> { Self::IPaymentMethodDataFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), supportedmethodids.into_param().abi(), jsondata.into_param().abi(), &mut result__).from_abi::<PaymentMethodData>(result__) }) } pub fn IPaymentMethodDataFactory<R, F: FnOnce(&IPaymentMethodDataFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PaymentMethodData, IPaymentMethodDataFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PaymentMethodData { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentMethodData;{d1d3caf4-de98-4129-b1b7-c3ad86237bf4})"); } unsafe impl ::windows::core::Interface for PaymentMethodData { type Vtable = IPaymentMethodData_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd1d3caf4_de98_4129_b1b7_c3ad86237bf4); } impl ::windows::core::RuntimeName for PaymentMethodData { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentMethodData"; } impl ::core::convert::From<PaymentMethodData> for ::windows::core::IUnknown { fn from(value: PaymentMethodData) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentMethodData> for ::windows::core::IUnknown { fn from(value: &PaymentMethodData) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentMethodData { 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 PaymentMethodData { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentMethodData> for ::windows::core::IInspectable { fn from(value: PaymentMethodData) -> Self { value.0 } } impl ::core::convert::From<&PaymentMethodData> for ::windows::core::IInspectable { fn from(value: &PaymentMethodData) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentMethodData { 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 PaymentMethodData { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentMethodData {} unsafe impl ::core::marker::Sync for PaymentMethodData {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PaymentOptionPresence(pub i32); impl PaymentOptionPresence { pub const None: PaymentOptionPresence = PaymentOptionPresence(0i32); pub const Optional: PaymentOptionPresence = PaymentOptionPresence(1i32); pub const Required: PaymentOptionPresence = PaymentOptionPresence(2i32); } impl ::core::convert::From<i32> for PaymentOptionPresence { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PaymentOptionPresence { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PaymentOptionPresence { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Payments.PaymentOptionPresence;i4)"); } impl ::windows::core::DefaultType for PaymentOptionPresence { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentOptions(pub ::windows::core::IInspectable); impl PaymentOptions { 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<PaymentOptions, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn RequestPayerEmail(&self) -> ::windows::core::Result<PaymentOptionPresence> { let this = self; unsafe { let mut result__: PaymentOptionPresence = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PaymentOptionPresence>(result__) } } pub fn SetRequestPayerEmail(&self, value: PaymentOptionPresence) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn RequestPayerName(&self) -> ::windows::core::Result<PaymentOptionPresence> { let this = self; unsafe { let mut result__: PaymentOptionPresence = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PaymentOptionPresence>(result__) } } pub fn SetRequestPayerName(&self, value: PaymentOptionPresence) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() } } pub fn RequestPayerPhoneNumber(&self) -> ::windows::core::Result<PaymentOptionPresence> { let this = self; unsafe { let mut result__: PaymentOptionPresence = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PaymentOptionPresence>(result__) } } pub fn SetRequestPayerPhoneNumber(&self, value: PaymentOptionPresence) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } pub fn RequestShipping(&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 SetRequestShipping(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() } } pub fn ShippingType(&self) -> ::windows::core::Result<PaymentShippingType> { let this = self; unsafe { let mut result__: PaymentShippingType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PaymentShippingType>(result__) } } pub fn SetShippingType(&self, value: PaymentShippingType) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() } } } unsafe impl ::windows::core::RuntimeType for PaymentOptions { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentOptions;{aaa30854-1f2b-4365-8251-01b58915a5bc})"); } unsafe impl ::windows::core::Interface for PaymentOptions { type Vtable = IPaymentOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaaa30854_1f2b_4365_8251_01b58915a5bc); } impl ::windows::core::RuntimeName for PaymentOptions { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentOptions"; } impl ::core::convert::From<PaymentOptions> for ::windows::core::IUnknown { fn from(value: PaymentOptions) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentOptions> for ::windows::core::IUnknown { fn from(value: &PaymentOptions) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentOptions { 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 PaymentOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentOptions> for ::windows::core::IInspectable { fn from(value: PaymentOptions) -> Self { value.0 } } impl ::core::convert::From<&PaymentOptions> for ::windows::core::IInspectable { fn from(value: &PaymentOptions) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentOptions { 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 PaymentOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentOptions {} unsafe impl ::core::marker::Sync for PaymentOptions {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentRequest(pub ::windows::core::IInspectable); impl PaymentRequest { pub fn MerchantInfo(&self) -> ::windows::core::Result<PaymentMerchantInfo> { 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::<PaymentMerchantInfo>(result__) } } pub fn Details(&self) -> ::windows::core::Result<PaymentDetails> { 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::<PaymentDetails>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn MethodData(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PaymentMethodData>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PaymentMethodData>>(result__) } } pub fn Options(&self) -> ::windows::core::Result<PaymentOptions> { 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::<PaymentOptions>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, PaymentDetails>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<PaymentMethodData>>>(details: Param0, methoddata: Param1) -> ::windows::core::Result<PaymentRequest> { Self::IPaymentRequestFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), details.into_param().abi(), methoddata.into_param().abi(), &mut result__).from_abi::<PaymentRequest>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn CreateWithMerchantInfo<'a, Param0: ::windows::core::IntoParam<'a, PaymentDetails>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<PaymentMethodData>>, Param2: ::windows::core::IntoParam<'a, PaymentMerchantInfo>>(details: Param0, methoddata: Param1, merchantinfo: Param2) -> ::windows::core::Result<PaymentRequest> { Self::IPaymentRequestFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), details.into_param().abi(), methoddata.into_param().abi(), merchantinfo.into_param().abi(), &mut result__).from_abi::<PaymentRequest>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn CreateWithMerchantInfoAndOptions<'a, Param0: ::windows::core::IntoParam<'a, PaymentDetails>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<PaymentMethodData>>, Param2: ::windows::core::IntoParam<'a, PaymentMerchantInfo>, Param3: ::windows::core::IntoParam<'a, PaymentOptions>>(details: Param0, methoddata: Param1, merchantinfo: Param2, options: Param3) -> ::windows::core::Result<PaymentRequest> { Self::IPaymentRequestFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), details.into_param().abi(), methoddata.into_param().abi(), merchantinfo.into_param().abi(), options.into_param().abi(), &mut result__).from_abi::<PaymentRequest>(result__) }) } pub fn Id(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPaymentRequest2>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn CreateWithMerchantInfoOptionsAndId<'a, Param0: ::windows::core::IntoParam<'a, PaymentDetails>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<PaymentMethodData>>, Param2: ::windows::core::IntoParam<'a, PaymentMerchantInfo>, Param3: ::windows::core::IntoParam<'a, PaymentOptions>, Param4: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( details: Param0, methoddata: Param1, merchantinfo: Param2, options: Param3, id: Param4, ) -> ::windows::core::Result<PaymentRequest> { Self::IPaymentRequestFactory2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), details.into_param().abi(), methoddata.into_param().abi(), merchantinfo.into_param().abi(), options.into_param().abi(), id.into_param().abi(), &mut result__).from_abi::<PaymentRequest>(result__) }) } pub fn IPaymentRequestFactory<R, F: FnOnce(&IPaymentRequestFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PaymentRequest, IPaymentRequestFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IPaymentRequestFactory2<R, F: FnOnce(&IPaymentRequestFactory2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PaymentRequest, IPaymentRequestFactory2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PaymentRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentRequest;{b74942e1-ed7b-47eb-bc08-78cc5d6896b6})"); } unsafe impl ::windows::core::Interface for PaymentRequest { type Vtable = IPaymentRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb74942e1_ed7b_47eb_bc08_78cc5d6896b6); } impl ::windows::core::RuntimeName for PaymentRequest { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentRequest"; } impl ::core::convert::From<PaymentRequest> for ::windows::core::IUnknown { fn from(value: PaymentRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentRequest> for ::windows::core::IUnknown { fn from(value: &PaymentRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentRequest { 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 PaymentRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentRequest> for ::windows::core::IInspectable { fn from(value: PaymentRequest) -> Self { value.0 } } impl ::core::convert::From<&PaymentRequest> for ::windows::core::IInspectable { fn from(value: &PaymentRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentRequest { 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 PaymentRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentRequest {} unsafe impl ::core::marker::Sync for PaymentRequest {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PaymentRequestChangeKind(pub i32); impl PaymentRequestChangeKind { pub const ShippingOption: PaymentRequestChangeKind = PaymentRequestChangeKind(0i32); pub const ShippingAddress: PaymentRequestChangeKind = PaymentRequestChangeKind(1i32); } impl ::core::convert::From<i32> for PaymentRequestChangeKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PaymentRequestChangeKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PaymentRequestChangeKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Payments.PaymentRequestChangeKind;i4)"); } impl ::windows::core::DefaultType for PaymentRequestChangeKind { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentRequestChangedArgs(pub ::windows::core::IInspectable); impl PaymentRequestChangedArgs { pub fn ChangeKind(&self) -> ::windows::core::Result<PaymentRequestChangeKind> { let this = self; unsafe { let mut result__: PaymentRequestChangeKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PaymentRequestChangeKind>(result__) } } pub fn ShippingAddress(&self) -> ::windows::core::Result<PaymentAddress> { 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::<PaymentAddress>(result__) } } pub fn SelectedShippingOption(&self) -> ::windows::core::Result<PaymentShippingOption> { 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::<PaymentShippingOption>(result__) } } pub fn Acknowledge<'a, Param0: ::windows::core::IntoParam<'a, PaymentRequestChangedResult>>(&self, changeresult: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), changeresult.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for PaymentRequestChangedArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentRequestChangedArgs;{c6145e44-cd8b-4be4-b555-27c99194c0c5})"); } unsafe impl ::windows::core::Interface for PaymentRequestChangedArgs { type Vtable = IPaymentRequestChangedArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc6145e44_cd8b_4be4_b555_27c99194c0c5); } impl ::windows::core::RuntimeName for PaymentRequestChangedArgs { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentRequestChangedArgs"; } impl ::core::convert::From<PaymentRequestChangedArgs> for ::windows::core::IUnknown { fn from(value: PaymentRequestChangedArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentRequestChangedArgs> for ::windows::core::IUnknown { fn from(value: &PaymentRequestChangedArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentRequestChangedArgs { 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 PaymentRequestChangedArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentRequestChangedArgs> for ::windows::core::IInspectable { fn from(value: PaymentRequestChangedArgs) -> Self { value.0 } } impl ::core::convert::From<&PaymentRequestChangedArgs> for ::windows::core::IInspectable { fn from(value: &PaymentRequestChangedArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentRequestChangedArgs { 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 PaymentRequestChangedArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentRequestChangedArgs {} unsafe impl ::core::marker::Sync for PaymentRequestChangedArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentRequestChangedHandler(::windows::core::IUnknown); impl PaymentRequestChangedHandler { pub fn new<F: FnMut(&::core::option::Option<PaymentRequest>, &::core::option::Option<PaymentRequestChangedArgs>) -> ::windows::core::Result<()> + 'static>(invoke: F) -> Self { let com = PaymentRequestChangedHandler_box::<F> { vtable: &PaymentRequestChangedHandler_box::<F>::VTABLE, count: ::windows::core::RefCount::new(1), invoke, }; unsafe { core::mem::transmute(::windows::core::alloc::boxed::Box::new(com)) } } pub fn Invoke<'a, Param0: ::windows::core::IntoParam<'a, PaymentRequest>, Param1: ::windows::core::IntoParam<'a, PaymentRequestChangedArgs>>(&self, paymentrequest: Param0, args: Param1) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).3)(::core::mem::transmute_copy(this), paymentrequest.into_param().abi(), args.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for PaymentRequestChangedHandler { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"delegate({5078b9e1-f398-4f2c-a27e-94d371cf6c7d})"); } unsafe impl ::windows::core::Interface for PaymentRequestChangedHandler { type Vtable = PaymentRequestChangedHandler_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5078b9e1_f398_4f2c_a27e_94d371cf6c7d); } #[repr(C)] #[doc(hidden)] pub struct PaymentRequestChangedHandler_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, paymentrequest: ::windows::core::RawPtr, args: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(C)] struct PaymentRequestChangedHandler_box<F: FnMut(&::core::option::Option<PaymentRequest>, &::core::option::Option<PaymentRequestChangedArgs>) -> ::windows::core::Result<()> + 'static> { vtable: *const PaymentRequestChangedHandler_abi, invoke: F, count: ::windows::core::RefCount, } impl<F: FnMut(&::core::option::Option<PaymentRequest>, &::core::option::Option<PaymentRequestChangedArgs>) -> ::windows::core::Result<()> + 'static> PaymentRequestChangedHandler_box<F> { const VTABLE: PaymentRequestChangedHandler_abi = PaymentRequestChangedHandler_abi(Self::QueryInterface, Self::AddRef, Self::Release, Self::Invoke); unsafe extern "system" fn QueryInterface(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; *interface = if iid == &<PaymentRequestChangedHandler as ::windows::core::Interface>::IID || iid == &<::windows::core::IUnknown as ::windows::core::Interface>::IID || iid == &<::windows::core::IAgileObject as ::windows::core::Interface>::IID { &mut (*this).vtable as *mut _ as _ } else { ::core::ptr::null_mut() }; if (*interface).is_null() { ::windows::core::HRESULT(0x8000_4002) } else { (*this).count.add_ref(); ::windows::core::HRESULT(0) } } unsafe extern "system" fn AddRef(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; (*this).count.add_ref() } unsafe extern "system" fn Release(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; let remaining = (*this).count.release(); if remaining == 0 { ::windows::core::alloc::boxed::Box::from_raw(this); } remaining } unsafe extern "system" fn Invoke(this: ::windows::core::RawPtr, paymentrequest: ::windows::core::RawPtr, args: ::windows::core::RawPtr) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; ((*this).invoke)( &*(&paymentrequest as *const <PaymentRequest as ::windows::core::Abi>::Abi as *const <PaymentRequest as ::windows::core::DefaultType>::DefaultType), &*(&args as *const <PaymentRequestChangedArgs as ::windows::core::Abi>::Abi as *const <PaymentRequestChangedArgs as ::windows::core::DefaultType>::DefaultType), ) .into() } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentRequestChangedResult(pub ::windows::core::IInspectable); impl PaymentRequestChangedResult { pub fn ChangeAcceptedByMerchant(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetChangeAcceptedByMerchant(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn Message(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetMessage<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&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 UpdatedPaymentDetails(&self) -> ::windows::core::Result<PaymentDetails> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PaymentDetails>(result__) } } pub fn SetUpdatedPaymentDetails<'a, Param0: ::windows::core::IntoParam<'a, PaymentDetails>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Create(changeacceptedbymerchant: bool) -> ::windows::core::Result<PaymentRequestChangedResult> { Self::IPaymentRequestChangedResultFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), changeacceptedbymerchant, &mut result__).from_abi::<PaymentRequestChangedResult>(result__) }) } pub fn CreateWithPaymentDetails<'a, Param1: ::windows::core::IntoParam<'a, PaymentDetails>>(changeacceptedbymerchant: bool, updatedpaymentdetails: Param1) -> ::windows::core::Result<PaymentRequestChangedResult> { Self::IPaymentRequestChangedResultFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), changeacceptedbymerchant, updatedpaymentdetails.into_param().abi(), &mut result__).from_abi::<PaymentRequestChangedResult>(result__) }) } pub fn IPaymentRequestChangedResultFactory<R, F: FnOnce(&IPaymentRequestChangedResultFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PaymentRequestChangedResult, IPaymentRequestChangedResultFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PaymentRequestChangedResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentRequestChangedResult;{df699e5c-16c4-47ad-9401-8440ec0757db})"); } unsafe impl ::windows::core::Interface for PaymentRequestChangedResult { type Vtable = IPaymentRequestChangedResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdf699e5c_16c4_47ad_9401_8440ec0757db); } impl ::windows::core::RuntimeName for PaymentRequestChangedResult { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentRequestChangedResult"; } impl ::core::convert::From<PaymentRequestChangedResult> for ::windows::core::IUnknown { fn from(value: PaymentRequestChangedResult) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentRequestChangedResult> for ::windows::core::IUnknown { fn from(value: &PaymentRequestChangedResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentRequestChangedResult { 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 PaymentRequestChangedResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentRequestChangedResult> for ::windows::core::IInspectable { fn from(value: PaymentRequestChangedResult) -> Self { value.0 } } impl ::core::convert::From<&PaymentRequestChangedResult> for ::windows::core::IInspectable { fn from(value: &PaymentRequestChangedResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentRequestChangedResult { 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 PaymentRequestChangedResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentRequestChangedResult {} unsafe impl ::core::marker::Sync for PaymentRequestChangedResult {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PaymentRequestCompletionStatus(pub i32); impl PaymentRequestCompletionStatus { pub const Succeeded: PaymentRequestCompletionStatus = PaymentRequestCompletionStatus(0i32); pub const Failed: PaymentRequestCompletionStatus = PaymentRequestCompletionStatus(1i32); pub const Unknown: PaymentRequestCompletionStatus = PaymentRequestCompletionStatus(2i32); } impl ::core::convert::From<i32> for PaymentRequestCompletionStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PaymentRequestCompletionStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PaymentRequestCompletionStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Payments.PaymentRequestCompletionStatus;i4)"); } impl ::windows::core::DefaultType for PaymentRequestCompletionStatus { 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 PaymentRequestStatus(pub i32); impl PaymentRequestStatus { pub const Succeeded: PaymentRequestStatus = PaymentRequestStatus(0i32); pub const Failed: PaymentRequestStatus = PaymentRequestStatus(1i32); pub const Canceled: PaymentRequestStatus = PaymentRequestStatus(2i32); } impl ::core::convert::From<i32> for PaymentRequestStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PaymentRequestStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PaymentRequestStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Payments.PaymentRequestStatus;i4)"); } impl ::windows::core::DefaultType for PaymentRequestStatus { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentRequestSubmitResult(pub ::windows::core::IInspectable); impl PaymentRequestSubmitResult { pub fn Status(&self) -> ::windows::core::Result<PaymentRequestStatus> { let this = self; unsafe { let mut result__: PaymentRequestStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PaymentRequestStatus>(result__) } } pub fn Response(&self) -> ::windows::core::Result<PaymentResponse> { 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::<PaymentResponse>(result__) } } } unsafe impl ::windows::core::RuntimeType for PaymentRequestSubmitResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentRequestSubmitResult;{7b9c3912-30f2-4e90-b249-8ce7d78ffe56})"); } unsafe impl ::windows::core::Interface for PaymentRequestSubmitResult { type Vtable = IPaymentRequestSubmitResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7b9c3912_30f2_4e90_b249_8ce7d78ffe56); } impl ::windows::core::RuntimeName for PaymentRequestSubmitResult { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentRequestSubmitResult"; } impl ::core::convert::From<PaymentRequestSubmitResult> for ::windows::core::IUnknown { fn from(value: PaymentRequestSubmitResult) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentRequestSubmitResult> for ::windows::core::IUnknown { fn from(value: &PaymentRequestSubmitResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentRequestSubmitResult { 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 PaymentRequestSubmitResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentRequestSubmitResult> for ::windows::core::IInspectable { fn from(value: PaymentRequestSubmitResult) -> Self { value.0 } } impl ::core::convert::From<&PaymentRequestSubmitResult> for ::windows::core::IInspectable { fn from(value: &PaymentRequestSubmitResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentRequestSubmitResult { 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 PaymentRequestSubmitResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentRequestSubmitResult {} unsafe impl ::core::marker::Sync for PaymentRequestSubmitResult {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentResponse(pub ::windows::core::IInspectable); impl PaymentResponse { pub fn PaymentToken(&self) -> ::windows::core::Result<PaymentToken> { 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::<PaymentToken>(result__) } } pub fn ShippingOption(&self) -> ::windows::core::Result<PaymentShippingOption> { 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::<PaymentShippingOption>(result__) } } pub fn ShippingAddress(&self) -> ::windows::core::Result<PaymentAddress> { 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::<PaymentAddress>(result__) } } pub fn PayerEmail(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn PayerName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn PayerPhoneNumber(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn CompleteAsync(&self, status: PaymentRequestCompletionStatus) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), status, &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } } unsafe impl ::windows::core::RuntimeType for PaymentResponse { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentResponse;{e1389457-8bd2-4888-9fa8-97985545108e})"); } unsafe impl ::windows::core::Interface for PaymentResponse { type Vtable = IPaymentResponse_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe1389457_8bd2_4888_9fa8_97985545108e); } impl ::windows::core::RuntimeName for PaymentResponse { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentResponse"; } impl ::core::convert::From<PaymentResponse> for ::windows::core::IUnknown { fn from(value: PaymentResponse) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentResponse> for ::windows::core::IUnknown { fn from(value: &PaymentResponse) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentResponse { 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 PaymentResponse { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentResponse> for ::windows::core::IInspectable { fn from(value: PaymentResponse) -> Self { value.0 } } impl ::core::convert::From<&PaymentResponse> for ::windows::core::IInspectable { fn from(value: &PaymentResponse) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentResponse { 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 PaymentResponse { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentResponse {} unsafe impl ::core::marker::Sync for PaymentResponse {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentShippingOption(pub ::windows::core::IInspectable); impl PaymentShippingOption { pub fn Label(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetLabel<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Amount(&self) -> ::windows::core::Result<PaymentCurrencyAmount> { 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::<PaymentCurrencyAmount>(result__) } } pub fn SetAmount<'a, Param0: ::windows::core::IntoParam<'a, PaymentCurrencyAmount>>(&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 Tag(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetTag<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn IsSelected(&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 SetIsSelected(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() } } pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, PaymentCurrencyAmount>>(label: Param0, amount: Param1) -> ::windows::core::Result<PaymentShippingOption> { Self::IPaymentShippingOptionFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), label.into_param().abi(), amount.into_param().abi(), &mut result__).from_abi::<PaymentShippingOption>(result__) }) } pub fn CreateWithSelected<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, PaymentCurrencyAmount>>(label: Param0, amount: Param1, selected: bool) -> ::windows::core::Result<PaymentShippingOption> { Self::IPaymentShippingOptionFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), label.into_param().abi(), amount.into_param().abi(), selected, &mut result__).from_abi::<PaymentShippingOption>(result__) }) } pub fn CreateWithSelectedAndTag<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, PaymentCurrencyAmount>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(label: Param0, amount: Param1, selected: bool, tag: Param3) -> ::windows::core::Result<PaymentShippingOption> { Self::IPaymentShippingOptionFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), label.into_param().abi(), amount.into_param().abi(), selected, tag.into_param().abi(), &mut result__).from_abi::<PaymentShippingOption>(result__) }) } pub fn IPaymentShippingOptionFactory<R, F: FnOnce(&IPaymentShippingOptionFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PaymentShippingOption, IPaymentShippingOptionFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PaymentShippingOption { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentShippingOption;{13372ada-9753-4574-8966-93145a76c7f9})"); } unsafe impl ::windows::core::Interface for PaymentShippingOption { type Vtable = IPaymentShippingOption_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x13372ada_9753_4574_8966_93145a76c7f9); } impl ::windows::core::RuntimeName for PaymentShippingOption { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentShippingOption"; } impl ::core::convert::From<PaymentShippingOption> for ::windows::core::IUnknown { fn from(value: PaymentShippingOption) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentShippingOption> for ::windows::core::IUnknown { fn from(value: &PaymentShippingOption) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentShippingOption { 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 PaymentShippingOption { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentShippingOption> for ::windows::core::IInspectable { fn from(value: PaymentShippingOption) -> Self { value.0 } } impl ::core::convert::From<&PaymentShippingOption> for ::windows::core::IInspectable { fn from(value: &PaymentShippingOption) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentShippingOption { 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 PaymentShippingOption { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentShippingOption {} unsafe impl ::core::marker::Sync for PaymentShippingOption {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PaymentShippingType(pub i32); impl PaymentShippingType { pub const Shipping: PaymentShippingType = PaymentShippingType(0i32); pub const Delivery: PaymentShippingType = PaymentShippingType(1i32); pub const Pickup: PaymentShippingType = PaymentShippingType(2i32); } impl ::core::convert::From<i32> for PaymentShippingType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PaymentShippingType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PaymentShippingType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Payments.PaymentShippingType;i4)"); } impl ::windows::core::DefaultType for PaymentShippingType { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PaymentToken(pub ::windows::core::IInspectable); impl PaymentToken { pub fn PaymentMethodId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn JsonDetails(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(paymentmethodid: Param0) -> ::windows::core::Result<PaymentToken> { Self::IPaymentTokenFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), paymentmethodid.into_param().abi(), &mut result__).from_abi::<PaymentToken>(result__) }) } pub fn CreateWithJsonDetails<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(paymentmethodid: Param0, jsondetails: Param1) -> ::windows::core::Result<PaymentToken> { Self::IPaymentTokenFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), paymentmethodid.into_param().abi(), jsondetails.into_param().abi(), &mut result__).from_abi::<PaymentToken>(result__) }) } pub fn IPaymentTokenFactory<R, F: FnOnce(&IPaymentTokenFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PaymentToken, IPaymentTokenFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PaymentToken { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Payments.PaymentToken;{bbcac013-ccd0-41f2-b2a1-0a2e4b5dce25})"); } unsafe impl ::windows::core::Interface for PaymentToken { type Vtable = IPaymentToken_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbbcac013_ccd0_41f2_b2a1_0a2e4b5dce25); } impl ::windows::core::RuntimeName for PaymentToken { const NAME: &'static str = "Windows.ApplicationModel.Payments.PaymentToken"; } impl ::core::convert::From<PaymentToken> for ::windows::core::IUnknown { fn from(value: PaymentToken) -> Self { value.0 .0 } } impl ::core::convert::From<&PaymentToken> for ::windows::core::IUnknown { fn from(value: &PaymentToken) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PaymentToken { 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 PaymentToken { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PaymentToken> for ::windows::core::IInspectable { fn from(value: PaymentToken) -> Self { value.0 } } impl ::core::convert::From<&PaymentToken> for ::windows::core::IInspectable { fn from(value: &PaymentToken) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PaymentToken { 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 PaymentToken { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PaymentToken {} unsafe impl ::core::marker::Sync for PaymentToken {}
use projecteuler::helper; fn main() { helper::check_bench(|| { solve(); }); assert_eq!(solve(), 49); dbg!(solve()); } fn solve() -> usize { /* a.pow(b) if a is greater equal 10, a.pow(b) will always have more digits than b when does a**b has the correct number of digits? 10^(b-1) <= a**b < 10^b 10^(b-1) = a**b 0.1 * 10^b = a**b log(0.1) + log(10)*b = log(a)*b log(0.1) = b*(log(a) - log(10)) b = log(0.1)/(log(a) - log(10)) */ let mut acc = 0; for a in 1u128..10 { //computes the same value as the following loop, just without the loop acc += (0.1f64.log2() / ((a as f64).log2() - (10.0f64.log2()))).floor() as usize; /* for b in 1u128.. { let x = a.pow(b as u32); let digits = format!("{}", x).len() as u128; if digits == b { acc += 1; } if digits < b { break; } } */ } acc }
#[doc = "Writer for register C0IFCR"] pub type W = crate::W<u32, super::C0IFCR>; #[doc = "Register C0IFCR `reset()`'s with value 0"] impl crate::ResetValue for super::C0IFCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `CTEIF0`"] pub struct CTEIF0_W<'a> { w: &'a mut W, } impl<'a> CTEIF0_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 = "Write proxy for field `CCTCIF0`"] pub struct CCTCIF0_W<'a> { w: &'a mut W, } impl<'a> CCTCIF0_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 = "Write proxy for field `CBRTIF0`"] pub struct CBRTIF0_W<'a> { w: &'a mut W, } impl<'a> CBRTIF0_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 = "Write proxy for field `CBTIF0`"] pub struct CBTIF0_W<'a> { w: &'a mut W, } impl<'a> CBTIF0_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 = "Write proxy for field `CLTCIF0`"] pub struct CLTCIF0_W<'a> { w: &'a mut W, } impl<'a> CLTCIF0_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 } } impl W { #[doc = "Bit 0 - Channel x clear transfer error interrupt flag Writing a 1 into this bit clears TEIFx in the MDMA_ISRy register"] #[inline(always)] pub fn cteif0(&mut self) -> CTEIF0_W { CTEIF0_W { w: self } } #[doc = "Bit 1 - Clear Channel transfer complete interrupt flag for channel x Writing a 1 into this bit clears CTCIFx in the MDMA_ISRy register"] #[inline(always)] pub fn cctcif0(&mut self) -> CCTCIF0_W { CCTCIF0_W { w: self } } #[doc = "Bit 2 - Channel x clear block repeat transfer complete interrupt flag Writing a 1 into this bit clears BRTIFx in the MDMA_ISRy register"] #[inline(always)] pub fn cbrtif0(&mut self) -> CBRTIF0_W { CBRTIF0_W { w: self } } #[doc = "Bit 3 - Channel x Clear block transfer complete interrupt flag Writing a 1 into this bit clears BTIFx in the MDMA_ISRy register"] #[inline(always)] pub fn cbtif0(&mut self) -> CBTIF0_W { CBTIF0_W { w: self } } #[doc = "Bit 4 - CLear buffer Transfer Complete Interrupt Flag for channel x Writing a 1 into this bit clears TCIFx in the MDMA_ISRy register"] #[inline(always)] pub fn cltcif0(&mut self) -> CLTCIF0_W { CLTCIF0_W { w: self } } }
use super::Part; use crate::codec::{Decode, Encode}; use crate::{remote_type, RemoteObject}; remote_type!( /// A light. Obtained by calling `Part::light().` object SpaceCenter.Light { properties: { { Part { /// Returns the part object for this light. /// /// **Game Scenes**: All get: part -> Part } } { Active { /// Returns whether the light is switched on. /// /// **Game Scenes**: All get: is_active -> bool, /// Sets whether the light is switched on. /// /// **Game Scenes**: All set: set_active(bool) } } { Color { /// Returns the color of the light, as an RGB triple. /// /// **Game Scenes**: All get: color -> (f32, f32, f32), /// Sets the color of the light, as an RGB triple. /// /// **Game Scenes**: All set: set_color((f32, f32, f32)) } } { PowerUsage { /// Returns the current power usage, in units of charge per second. /// /// **Game Scenes**: All get: power_usage -> f32 } } } });
use crate::{ iter::Slice2DIterMut, slice::{Shape2D, SlicePtrMut}, }; pub trait Slice2DFill<T> { fn fill(&mut self, value: T) where T: Clone; fn fill_with<F>(&mut self, f: F) where F: FnMut() -> T; } impl<T: Clone, S> Slice2DFill<T> for S where S: Shape2D + SlicePtrMut<T> + Slice2DIterMut<T, S>, { #[inline] fn fill(&mut self, value: T) where T: Clone, { self.row_iter_mut() .flatten() .for_each(|e| *e = value.clone()); } #[inline] fn fill_with<F>(&mut self, mut f: F) where F: FnMut() -> T, { self.row_iter_mut().flatten().for_each(|e| *e = f()); } }
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn parse_http_generic_error( response: &http::Response<bytes::Bytes>, ) -> Result<smithy_types::Error, smithy_json::deserialize::Error> { crate::json_errors::parse_generic_error(response.body(), response.headers()) } pub fn deser_structure_entity_not_exists_exceptionjson_err( input: &[u8], mut builder: crate::error::entity_not_exists_exception::Builder, ) -> Result<crate::error::entity_not_exists_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "EntityIds" => { builder = builder .set_entity_ids(crate::json_deser::deser_list_entity_id_list(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_failed_dependency_exceptionjson_err( input: &[u8], mut builder: crate::error::failed_dependency_exception::Builder, ) -> Result<crate::error::failed_dependency_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_prohibited_state_exceptionjson_err( input: &[u8], mut builder: crate::error::prohibited_state_exception::Builder, ) -> Result<crate::error::prohibited_state_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_service_unavailable_exceptionjson_err( input: &[u8], mut builder: crate::error::service_unavailable_exception::Builder, ) -> Result<crate::error::service_unavailable_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_unauthorized_operation_exceptionjson_err( input: &[u8], mut builder: crate::error::unauthorized_operation_exception::Builder, ) -> Result<crate::error::unauthorized_operation_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Code" => { builder = builder.set_code( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_unauthorized_resource_access_exceptionjson_err( input: &[u8], mut builder: crate::error::unauthorized_resource_access_exception::Builder, ) -> Result< crate::error::unauthorized_resource_access_exception::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_activate_user( input: &[u8], mut builder: crate::output::activate_user_output::Builder, ) -> Result<crate::output::activate_user_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "User" => { builder = builder.set_user(crate::json_deser::deser_structure_user(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_add_resource_permissions( input: &[u8], mut builder: crate::output::add_resource_permissions_output::Builder, ) -> Result<crate::output::add_resource_permissions_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "ShareResults" => { builder = builder.set_share_results( crate::json_deser::deser_list_share_results_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_document_locked_for_comments_exceptionjson_err( input: &[u8], mut builder: crate::error::document_locked_for_comments_exception::Builder, ) -> Result< crate::error::document_locked_for_comments_exception::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_invalid_comment_operation_exceptionjson_err( input: &[u8], mut builder: crate::error::invalid_comment_operation_exception::Builder, ) -> Result< crate::error::invalid_comment_operation_exception::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_create_comment( input: &[u8], mut builder: crate::output::create_comment_output::Builder, ) -> Result<crate::output::create_comment_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Comment" => { builder = builder .set_comment(crate::json_deser::deser_structure_comment(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_custom_metadata_limit_exceeded_exceptionjson_err( input: &[u8], mut builder: crate::error::custom_metadata_limit_exceeded_exception::Builder, ) -> Result< crate::error::custom_metadata_limit_exceeded_exception::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_conflicting_operation_exceptionjson_err( input: &[u8], mut builder: crate::error::conflicting_operation_exception::Builder, ) -> Result<crate::error::conflicting_operation_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_entity_already_exists_exceptionjson_err( input: &[u8], mut builder: crate::error::entity_already_exists_exception::Builder, ) -> Result<crate::error::entity_already_exists_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_limit_exceeded_exceptionjson_err( input: &[u8], mut builder: crate::error::limit_exceeded_exception::Builder, ) -> Result<crate::error::limit_exceeded_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_create_folder( input: &[u8], mut builder: crate::output::create_folder_output::Builder, ) -> Result<crate::output::create_folder_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Metadata" => { builder = builder.set_metadata( crate::json_deser::deser_structure_folder_metadata(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_too_many_labels_exceptionjson_err( input: &[u8], mut builder: crate::error::too_many_labels_exception::Builder, ) -> Result<crate::error::too_many_labels_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_too_many_subscriptions_exceptionjson_err( input: &[u8], mut builder: crate::error::too_many_subscriptions_exception::Builder, ) -> Result<crate::error::too_many_subscriptions_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_create_notification_subscription( input: &[u8], mut builder: crate::output::create_notification_subscription_output::Builder, ) -> Result< crate::output::create_notification_subscription_output::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Subscription" => { builder = builder.set_subscription( crate::json_deser::deser_structure_subscription(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_create_user( input: &[u8], mut builder: crate::output::create_user_output::Builder, ) -> Result<crate::output::create_user_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "User" => { builder = builder.set_user(crate::json_deser::deser_structure_user(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_concurrent_modification_exceptionjson_err( input: &[u8], mut builder: crate::error::concurrent_modification_exception::Builder, ) -> Result<crate::error::concurrent_modification_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_invalid_argument_exceptionjson_err( input: &[u8], mut builder: crate::error::invalid_argument_exception::Builder, ) -> Result<crate::error::invalid_argument_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_activities( input: &[u8], mut builder: crate::output::describe_activities_output::Builder, ) -> Result<crate::output::describe_activities_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Marker" => { builder = builder.set_marker( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "UserActivities" => { builder = builder.set_user_activities( crate::json_deser::deser_list_user_activities(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_comments( input: &[u8], mut builder: crate::output::describe_comments_output::Builder, ) -> Result<crate::output::describe_comments_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Comments" => { builder = builder .set_comments(crate::json_deser::deser_list_comment_list(tokens)?); } "Marker" => { builder = builder.set_marker( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_document_versions( input: &[u8], mut builder: crate::output::describe_document_versions_output::Builder, ) -> Result< crate::output::describe_document_versions_output::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "DocumentVersions" => { builder = builder.set_document_versions( crate::json_deser::deser_list_document_version_metadata_list(tokens)?, ); } "Marker" => { builder = builder.set_marker( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_folder_contents( input: &[u8], mut builder: crate::output::describe_folder_contents_output::Builder, ) -> Result<crate::output::describe_folder_contents_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Documents" => { builder = builder.set_documents( crate::json_deser::deser_list_document_metadata_list(tokens)?, ); } "Folders" => { builder = builder.set_folders( crate::json_deser::deser_list_folder_metadata_list(tokens)?, ); } "Marker" => { builder = builder.set_marker( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_groups( input: &[u8], mut builder: crate::output::describe_groups_output::Builder, ) -> Result<crate::output::describe_groups_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Groups" => { builder = builder .set_groups(crate::json_deser::deser_list_group_metadata_list(tokens)?); } "Marker" => { builder = builder.set_marker( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_notification_subscriptions( input: &[u8], mut builder: crate::output::describe_notification_subscriptions_output::Builder, ) -> Result< crate::output::describe_notification_subscriptions_output::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Marker" => { builder = builder.set_marker( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Subscriptions" => { builder = builder.set_subscriptions( crate::json_deser::deser_list_subscription_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_resource_permissions( input: &[u8], mut builder: crate::output::describe_resource_permissions_output::Builder, ) -> Result< crate::output::describe_resource_permissions_output::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Marker" => { builder = builder.set_marker( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Principals" => { builder = builder .set_principals(crate::json_deser::deser_list_principal_list(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_root_folders( input: &[u8], mut builder: crate::output::describe_root_folders_output::Builder, ) -> Result<crate::output::describe_root_folders_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Folders" => { builder = builder.set_folders( crate::json_deser::deser_list_folder_metadata_list(tokens)?, ); } "Marker" => { builder = builder.set_marker( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_requested_entity_too_large_exceptionjson_err( input: &[u8], mut builder: crate::error::requested_entity_too_large_exception::Builder, ) -> Result< crate::error::requested_entity_too_large_exception::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_users( input: &[u8], mut builder: crate::output::describe_users_output::Builder, ) -> Result<crate::output::describe_users_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Marker" => { builder = builder.set_marker( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "TotalNumberOfUsers" => { builder = builder.set_total_number_of_users( smithy_json::deserialize::token::expect_number_or_null(tokens.next())? .map(|v| v.to_i64()), ); } "Users" => { builder = builder.set_users( crate::json_deser::deser_list_organization_user_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_get_current_user( input: &[u8], mut builder: crate::output::get_current_user_output::Builder, ) -> Result<crate::output::get_current_user_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "User" => { builder = builder.set_user(crate::json_deser::deser_structure_user(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_invalid_password_exceptionjson_err( input: &[u8], mut builder: crate::error::invalid_password_exception::Builder, ) -> Result<crate::error::invalid_password_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_get_document( input: &[u8], mut builder: crate::output::get_document_output::Builder, ) -> Result<crate::output::get_document_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "CustomMetadata" => { builder = builder.set_custom_metadata( crate::json_deser::deser_map_custom_metadata_map(tokens)?, ); } "Metadata" => { builder = builder.set_metadata( crate::json_deser::deser_structure_document_metadata(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_get_document_path( input: &[u8], mut builder: crate::output::get_document_path_output::Builder, ) -> Result<crate::output::get_document_path_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Path" => { builder = builder .set_path(crate::json_deser::deser_structure_resource_path(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_get_document_version( input: &[u8], mut builder: crate::output::get_document_version_output::Builder, ) -> Result<crate::output::get_document_version_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "CustomMetadata" => { builder = builder.set_custom_metadata( crate::json_deser::deser_map_custom_metadata_map(tokens)?, ); } "Metadata" => { builder = builder.set_metadata( crate::json_deser::deser_structure_document_version_metadata(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_get_folder( input: &[u8], mut builder: crate::output::get_folder_output::Builder, ) -> Result<crate::output::get_folder_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "CustomMetadata" => { builder = builder.set_custom_metadata( crate::json_deser::deser_map_custom_metadata_map(tokens)?, ); } "Metadata" => { builder = builder.set_metadata( crate::json_deser::deser_structure_folder_metadata(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_get_folder_path( input: &[u8], mut builder: crate::output::get_folder_path_output::Builder, ) -> Result<crate::output::get_folder_path_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Path" => { builder = builder .set_path(crate::json_deser::deser_structure_resource_path(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_get_resources( input: &[u8], mut builder: crate::output::get_resources_output::Builder, ) -> Result<crate::output::get_resources_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Documents" => { builder = builder.set_documents( crate::json_deser::deser_list_document_metadata_list(tokens)?, ); } "Folders" => { builder = builder.set_folders( crate::json_deser::deser_list_folder_metadata_list(tokens)?, ); } "Marker" => { builder = builder.set_marker( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_draft_upload_out_of_sync_exceptionjson_err( input: &[u8], mut builder: crate::error::draft_upload_out_of_sync_exception::Builder, ) -> Result< crate::error::draft_upload_out_of_sync_exception::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_resource_already_checked_out_exceptionjson_err( input: &[u8], mut builder: crate::error::resource_already_checked_out_exception::Builder, ) -> Result< crate::error::resource_already_checked_out_exception::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_storage_limit_exceeded_exceptionjson_err( input: &[u8], mut builder: crate::error::storage_limit_exceeded_exception::Builder, ) -> Result<crate::error::storage_limit_exceeded_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_storage_limit_will_exceed_exceptionjson_err( input: &[u8], mut builder: crate::error::storage_limit_will_exceed_exception::Builder, ) -> Result< crate::error::storage_limit_will_exceed_exception::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_initiate_document_version_upload( input: &[u8], mut builder: crate::output::initiate_document_version_upload_output::Builder, ) -> Result< crate::output::initiate_document_version_upload_output::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Metadata" => { builder = builder.set_metadata( crate::json_deser::deser_structure_document_metadata(tokens)?, ); } "UploadMetadata" => { builder = builder.set_upload_metadata( crate::json_deser::deser_structure_upload_metadata(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_invalid_operation_exceptionjson_err( input: &[u8], mut builder: crate::error::invalid_operation_exception::Builder, ) -> Result<crate::error::invalid_operation_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_deactivating_last_system_user_exceptionjson_err( input: &[u8], mut builder: crate::error::deactivating_last_system_user_exception::Builder, ) -> Result< crate::error::deactivating_last_system_user_exception::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Code" => { builder = builder.set_code( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_illegal_user_state_exceptionjson_err( input: &[u8], mut builder: crate::error::illegal_user_state_exception::Builder, ) -> Result<crate::error::illegal_user_state_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_update_user( input: &[u8], mut builder: crate::output::update_user_output::Builder, ) -> Result<crate::output::update_user_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "User" => { builder = builder.set_user(crate::json_deser::deser_structure_user(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn or_empty_doc(data: &[u8]) -> &[u8] { if data.is_empty() { b"{}" } else { data } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_entity_id_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_user<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::User>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::User::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Id" => { builder = builder.set_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Username" => { builder = builder.set_username( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "EmailAddress" => { builder = builder.set_email_address( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "GivenName" => { builder = builder.set_given_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Surname" => { builder = builder.set_surname( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "OrganizationId" => { builder = builder.set_organization_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "RootFolderId" => { builder = builder.set_root_folder_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "RecycleBinFolderId" => { builder = builder.set_recycle_bin_folder_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Status" => { builder = builder.set_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::UserStatusType::from(u.as_ref())) }) .transpose()?, ); } "Type" => { builder = builder.set_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::UserType::from(u.as_ref())) }) .transpose()?, ); } "CreatedTimestamp" => { builder = builder.set_created_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "ModifiedTimestamp" => { builder = builder.set_modified_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "TimeZoneId" => { builder = builder.set_time_zone_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Locale" => { builder = builder.set_locale( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::LocaleType::from(u.as_ref())) }) .transpose()?, ); } "Storage" => { builder = builder.set_storage( crate::json_deser::deser_structure_user_storage_metadata( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_share_results_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::ShareResult>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_share_result(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_comment<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Comment>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Comment::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "CommentId" => { builder = builder.set_comment_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "ParentId" => { builder = builder.set_parent_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "ThreadId" => { builder = builder.set_thread_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Text" => { builder = builder.set_text( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Contributor" => { builder = builder.set_contributor( crate::json_deser::deser_structure_user(tokens)?, ); } "CreatedTimestamp" => { builder = builder.set_created_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "Status" => { builder = builder.set_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CommentStatusType::from(u.as_ref()) }) }) .transpose()?, ); } "Visibility" => { builder = builder.set_visibility( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CommentVisibilityType::from(u.as_ref()) }) }) .transpose()?, ); } "RecipientId" => { builder = builder.set_recipient_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_folder_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::FolderMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::FolderMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Id" => { builder = builder.set_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Name" => { builder = builder.set_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "CreatorId" => { builder = builder.set_creator_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "ParentFolderId" => { builder = builder.set_parent_folder_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "CreatedTimestamp" => { builder = builder.set_created_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "ModifiedTimestamp" => { builder = builder.set_modified_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "ResourceState" => { builder = builder.set_resource_state( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ResourceStateType::from(u.as_ref()) }) }) .transpose()?, ); } "Signature" => { builder = builder.set_signature( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Labels" => { builder = builder.set_labels( crate::json_deser::deser_list_shared_labels(tokens)?, ); } "Size" => { builder = builder.set_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i64()), ); } "LatestVersionSize" => { builder = builder.set_latest_version_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i64()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_subscription<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Subscription>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Subscription::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "SubscriptionId" => { builder = builder.set_subscription_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "EndPoint" => { builder = builder.set_end_point( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Protocol" => { builder = builder.set_protocol( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::SubscriptionProtocolType::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_user_activities<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Activity>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_activity(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_comment_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Comment>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_comment(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_document_version_metadata_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::DocumentVersionMetadata>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_document_version_metadata(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_document_metadata_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::DocumentMetadata>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_document_metadata(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_folder_metadata_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::FolderMetadata>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_folder_metadata(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_group_metadata_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::GroupMetadata>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_group_metadata(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_subscription_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Subscription>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_subscription(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_principal_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Principal>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_principal(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_organization_user_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::User>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_user(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_custom_metadata_map<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::collections::HashMap<std::string::String, std::string::String>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key.to_unescaped().map(|u| u.into_owned())?; let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_document_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DocumentMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DocumentMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Id" => { builder = builder.set_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "CreatorId" => { builder = builder.set_creator_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "ParentFolderId" => { builder = builder.set_parent_folder_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "CreatedTimestamp" => { builder = builder.set_created_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "ModifiedTimestamp" => { builder = builder.set_modified_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "LatestVersionMetadata" => { builder = builder.set_latest_version_metadata( crate::json_deser::deser_structure_document_version_metadata( tokens, )?, ); } "ResourceState" => { builder = builder.set_resource_state( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ResourceStateType::from(u.as_ref()) }) }) .transpose()?, ); } "Labels" => { builder = builder.set_labels( crate::json_deser::deser_list_shared_labels(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_resource_path<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ResourcePath>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ResourcePath::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Components" => { builder = builder.set_components( crate::json_deser::deser_list_resource_path_component_list( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_document_version_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DocumentVersionMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DocumentVersionMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Id" => { builder = builder.set_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Name" => { builder = builder.set_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "ContentType" => { builder = builder.set_content_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Size" => { builder = builder.set_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i64()), ); } "Signature" => { builder = builder.set_signature( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Status" => { builder = builder.set_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DocumentStatusType::from(u.as_ref()) }) }) .transpose()?, ); } "CreatedTimestamp" => { builder = builder.set_created_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "ModifiedTimestamp" => { builder = builder.set_modified_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "ContentCreatedTimestamp" => { builder = builder.set_content_created_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "ContentModifiedTimestamp" => { builder = builder.set_content_modified_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "CreatorId" => { builder = builder.set_creator_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Thumbnail" => { builder = builder.set_thumbnail( crate::json_deser::deser_map_document_thumbnail_url_map( tokens, )?, ); } "Source" => { builder = builder.set_source( crate::json_deser::deser_map_document_source_url_map(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_upload_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::UploadMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::UploadMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "UploadUrl" => { builder = builder.set_upload_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "SignedHeaders" => { builder = builder.set_signed_headers( crate::json_deser::deser_map_signed_header_map(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_user_storage_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::UserStorageMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::UserStorageMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "StorageUtilizedInBytes" => { builder = builder.set_storage_utilized_in_bytes( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i64()), ); } "StorageRule" => { builder = builder.set_storage_rule( crate::json_deser::deser_structure_storage_rule_type(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_share_result<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ShareResult>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ShareResult::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "PrincipalId" => { builder = builder.set_principal_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "InviteePrincipalId" => { builder = builder.set_invitee_principal_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Role" => { builder = builder.set_role( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::RoleType::from(u.as_ref())) }) .transpose()?, ); } "Status" => { builder = builder.set_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ShareStatusType::from(u.as_ref()) }) }) .transpose()?, ); } "ShareId" => { builder = builder.set_share_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "StatusMessage" => { builder = builder.set_status_message( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_shared_labels<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_activity<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Activity>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Activity::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Type" => { builder = builder.set_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ActivityType::from(u.as_ref())) }) .transpose()?, ); } "TimeStamp" => { builder = builder.set_time_stamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "IsIndirectActivity" => { builder = builder.set_is_indirect_activity( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "OrganizationId" => { builder = builder.set_organization_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Initiator" => { builder = builder.set_initiator( crate::json_deser::deser_structure_user_metadata(tokens)?, ); } "Participants" => { builder = builder.set_participants( crate::json_deser::deser_structure_participants(tokens)?, ); } "ResourceMetadata" => { builder = builder.set_resource_metadata( crate::json_deser::deser_structure_resource_metadata(tokens)?, ); } "OriginalParent" => { builder = builder.set_original_parent( crate::json_deser::deser_structure_resource_metadata(tokens)?, ); } "CommentMetadata" => { builder = builder.set_comment_metadata( crate::json_deser::deser_structure_comment_metadata(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_group_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::GroupMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::GroupMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Id" => { builder = builder.set_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Name" => { builder = builder.set_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_principal<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Principal>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Principal::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Id" => { builder = builder.set_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Type" => { builder = builder.set_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::PrincipalType::from(u.as_ref())) }) .transpose()?, ); } "Roles" => { builder = builder.set_roles( crate::json_deser::deser_list_permission_info_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_resource_path_component_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::ResourcePathComponent>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_resource_path_component(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_document_thumbnail_url_map<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::collections::HashMap<crate::model::DocumentThumbnailType, std::string::String>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key .to_unescaped() .map(|u| crate::model::DocumentThumbnailType::from(u.as_ref()))?; let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_document_source_url_map<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::collections::HashMap<crate::model::DocumentSourceType, std::string::String>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key .to_unescaped() .map(|u| crate::model::DocumentSourceType::from(u.as_ref()))?; let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_signed_header_map<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::collections::HashMap<std::string::String, std::string::String>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key.to_unescaped().map(|u| u.into_owned())?; let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_storage_rule_type<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::StorageRuleType>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::StorageRuleType::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "StorageAllocatedInBytes" => { builder = builder.set_storage_allocated_in_bytes( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i64()), ); } "StorageType" => { builder = builder.set_storage_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::StorageType::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_user_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::UserMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::UserMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Id" => { builder = builder.set_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Username" => { builder = builder.set_username( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "GivenName" => { builder = builder.set_given_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Surname" => { builder = builder.set_surname( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "EmailAddress" => { builder = builder.set_email_address( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_participants<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Participants>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Participants::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Users" => { builder = builder.set_users( crate::json_deser::deser_list_user_metadata_list(tokens)?, ); } "Groups" => { builder = builder.set_groups( crate::json_deser::deser_list_group_metadata_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_resource_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ResourceMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ResourceMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Type" => { builder = builder.set_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ResourceType::from(u.as_ref())) }) .transpose()?, ); } "Name" => { builder = builder.set_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "OriginalName" => { builder = builder.set_original_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Id" => { builder = builder.set_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "VersionId" => { builder = builder.set_version_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Owner" => { builder = builder.set_owner( crate::json_deser::deser_structure_user_metadata(tokens)?, ); } "ParentId" => { builder = builder.set_parent_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_comment_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CommentMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CommentMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "CommentId" => { builder = builder.set_comment_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Contributor" => { builder = builder.set_contributor( crate::json_deser::deser_structure_user(tokens)?, ); } "CreatedTimestamp" => { builder = builder.set_created_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "CommentStatus" => { builder = builder.set_comment_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CommentStatusType::from(u.as_ref()) }) }) .transpose()?, ); } "RecipientId" => { builder = builder.set_recipient_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_permission_info_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::PermissionInfo>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_permission_info(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_resource_path_component<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ResourcePathComponent>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ResourcePathComponent::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Id" => { builder = builder.set_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Name" => { builder = builder.set_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_user_metadata_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::UserMetadata>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_user_metadata(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_permission_info<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::PermissionInfo>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::PermissionInfo::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Role" => { builder = builder.set_role( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::RoleType::from(u.as_ref())) }) .transpose()?, ); } "Type" => { builder = builder.set_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::RolePermissionType::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } }
pub struct DSU { par: Vec<usize>, size: Vec<i32>, comps: usize, } impl DSU { pub fn new(n: usize) -> Self { Self { par: (0..n).collect(), size: vec![1; n], comps: n, } } pub fn root(&mut self, a: usize) -> usize { if a != self.par[a] { self.par[a] = self.root(self.par[a]); } self.par[a] } pub fn join(&mut self, mut a: usize, mut b: usize) -> bool { a = self.root(a); b = self.root(b); if a == b { return false; } if self.size[a] < self.size[b] { std::mem::swap(&mut a, &mut b); } self.size[a] += self.size[b]; self.par[b] = a; self.comps -= 1; true } pub fn comps(&self) -> usize { self.comps } #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> usize { self.par.len() } }
mod camera; mod render_state; mod tex2d; mod vertex; use cfg_if::cfg_if; use color_eyre::{eyre::WrapErr, Result}; use log::error; use log::{info, warn}; use winit::event::VirtualKeyCode; use winit::event_loop::ControlFlow; use winit::event_loop::EventLoop; use winit::window::WindowBuilder; use winit_input_helper::WinitInputHelper; #[cfg(target_arch = "wasm32")] use wasm_bindgen::prelude::*; use crate::render_state::RenderState; pub async fn run() -> Result<()> { color_eyre::install()?; cfg_if! { if #[cfg(target_arch = "wasm32")] { std::panic::set_hook(Box::new(console_error_panic_hook::hook)); console_log::init_with_level(log::Level::Debug) .expect("Couldn't initialize logger"); } else { use env_logger::Env; let env = Env::default().default_filter_or("wgpu_experiments=debug"); env_logger::Builder::from_env(env).init(); } } let event_loop = EventLoop::new(); let window = WindowBuilder::new().build(&event_loop).unwrap(); #[cfg(target_arch = "wasm32")] { // Winit prevents sizing with CSS, so we have to set // the size manually when on web. use winit::dpi::PhysicalSize; use winit::platform::web::WindowExtWebSys; web_sys::window() .and_then(|win| win.document()) .and_then(|doc| { let parent = doc.get_element_by_id("wgpu-parent")?; let width = parent.client_width() as u32; let height = parent.client_height() as u32; info!("width: {}, height: {}", width, height); window.set_inner_size(PhysicalSize::new(width, height)); let canvas = window.canvas(); let style = canvas.style(); style.remove_property("width").unwrap(); style.remove_property("height").unwrap(); parent.append_child(&canvas).ok()?; Some(()) }) .expect("Couldn't append canvas to document body."); } let mut input = WinitInputHelper::new(); let mut state = RenderState::new(window) .await .wrap_err("Error when initializing wgpu state")?; info!("Starting event loop"); event_loop.run(move |event, _e_loop, control_flow| { // When true, input_helper is done processing events. if !input.update(&event) { return; } // Handle close events { if input.key_pressed(VirtualKeyCode::Escape) || input.close_requested() || input.destroyed() { info!("Close Requested"); *control_flow = ControlFlow::Exit; return; } } if let Some(size) = input.window_resized() { state.resize(size); } state.update(&input); use wgpu::SurfaceError as E; match state.render() { Ok(_) => {} Err(E::Lost) => state.resize(state.size()), Err(E::OutOfMemory) => { error!("Out of memory!"); *control_flow = ControlFlow::Exit; } Err(err) => { warn!("Error in event loop: {:?}", err); } } }) } #[cfg(target_arch = "wasm32")] #[wasm_bindgen(start)] pub async fn wasm_start() -> Result<(), JsError> { run().await.map_err(|e| { let e: &(dyn std::error::Error + Send + Sync + 'static) = e.as_ref(); JsError::from(e) // let b: Box<dyn std::error::Error + 'static> = e.into(); // JsError::from(b) }) }
/** This attribute is used for functions which export a module in an `implementation crate`. This is applied to functions like this: ```rust use abi_stable::prefix_type::PrefixTypeTrait; #[abi_stable::export_root_module] pub fn get_hello_world_mod() -> TextOperationsMod_Ref { TextOperationsMod { reverse_string }.leak_into_prefix() } # #[repr(C)] # #[derive(abi_stable::StableAbi)] # #[sabi(kind(Prefix(prefix_ref= TextOperationsMod_Ref)))] # #[sabi(missing_field(panic))] # pub struct TextOperationsMod { # #[sabi(last_prefix_field)] # pub reverse_string: extern "C" fn(), # } # # extern "C" fn reverse_string() {} # impl abi_stable::library::RootModule for TextOperationsMod_Ref { # abi_stable::declare_root_module_statics!{TextOperationsMod_Ref} # const BASE_NAME: &'static str = "stuff"; # const NAME: &'static str = "stuff"; # const VERSION_STRINGS: abi_stable::sabi_types::VersionStrings = # abi_stable::package_version_strings!(); # } # fn main(){} ``` # Return Type The return type of the annotated function can be one of: - Any type that implements `abi_stable::library::RootModule` - `Result<M, RBoxError>`, where `M` is any type that implements `abi_stable::library::RootModule` - `RResult<M, RBoxError>`, where `M` is any type that implements `abi_stable::library::RootModule` All those types are supported through the [`IntoRootModuleResult`] trait, which you can implement if you want to return some other type. # Generated code Exporting the root module creates a `static THE_NAME_USED_FOR_ALL_ROOT_MODULES: `[`LibHeader`]` = ... ;` with these things: - The version of `abi_stable` used. - A `#[no_mangle]` function that wraps the annotated root-module constructor function, converting the return value to [`RootModuleResult`](./library/type.RootModuleResult.html). - The type layout of the root module, for checking that the types are compatible with whatever loads that library. - The version number of the library. - A [`LateStaticRef`] of the root module. The name used for generated static is the value of [`abi_stable::library::ROOT_MODULE_LOADER_NAME`](./library/constant.ROOT_MODULE_LOADER_NAME.html). # Remove type layout constant One can avoid generating the type layout constant for the exported root module by using the `#[unsafe_no_layout_constant]` attribute, with the downside that if the layout changes(in an incompatible way) it could be Undefined Behavior. This attribute is useful if one wants to minimize the size of the dynamic library when doing a public release. This attribute should not be used unconditionally, it should be disabled in Continuous Integration so that the binary compatibility of a dynamic library is checked at some point before releasing it. # More examples For a more detailed example look in the README in the repository for this crate. [`IntoRootModuleResult`]: ./library/trait.IntoRootModuleResult.html [`LateStaticRef`]: ./sabi_types/struct.LateStaticRef.html [`LibHeader`]: ./library/struct.LibHeader.html */ #[doc(inline)] pub use abi_stable_derive::export_root_module;
use ckb_simple_account_layer::{CkbBlake2bHasher, Config}; use ckb_types::{ bytes::{BufMut, Bytes, BytesMut}, core::{DepType, EpochNumberWithFraction, ScriptHashType}, h256, packed, prelude::*, H160, H256, }; use ckb_vm::{Error as VMError, Memory, Register, SupportMachine}; use serde::{Deserialize, Serialize}; use sparse_merkle_tree::{default_store::DefaultStore, SparseMerkleTree, H256 as SmtH256}; use std::collections::HashMap; use std::convert::TryFrom; use crate::storage::{value, Key}; pub const ONE_CKB: u64 = 100_000_000; pub const MIN_CELL_CAPACITY: u64 = 61 * ONE_CKB; pub const SIGHASH_TYPE_HASH: H256 = h256!("0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8"); pub const ALWAYS_SUCCESS_CODE_HASH: H256 = h256!("0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5"); pub const CELLBASE_MATURITY: EpochNumberWithFraction = EpochNumberWithFraction::new_unchecked(4, 0, 1); lazy_static::lazy_static! { pub static ref SECP256K1: secp256k1::Secp256k1<secp256k1::All> = secp256k1::Secp256k1::new(); pub static ref SIGHASH_CELL_DEP: packed::CellDep = { let out_point = packed::OutPoint::new_builder() .tx_hash(h256!("0xace5ea83c478bb866edf122ff862085789158f5cbff155b7bb5f13058555b708").pack()) .index(0u32.pack()) .build(); packed::CellDep::new_builder() .out_point(out_point) .dep_type(DepType::DepGroup.into()) .build() }; pub static ref ALWAYS_SUCCESS_OUT_POINT: packed::OutPoint = { // FIXME: replace this later packed::OutPoint::new_builder() .tx_hash(h256!("0x1111111111111111111111111111111111111111111111111111111111111111").pack()) .index(0u32.pack()) .build() }; pub static ref ALWAYS_SUCCESS_CELL_DEP: packed::CellDep = { packed::CellDep::new_builder() .out_point(ALWAYS_SUCCESS_OUT_POINT.clone()) .dep_type(DepType::Code.into()) .build() }; pub static ref ALWAYS_SUCCESS_SCRIPT: packed::Script = { packed::Script::new_builder() .code_hash(ALWAYS_SUCCESS_CODE_HASH.pack()) .hash_type(ScriptHashType::Data.into()) .build() }; } #[derive(Debug, Clone)] pub struct RunConfig { pub generator: Bytes, // Type script (validator) pub type_dep: packed::CellDep, pub type_script: packed::Script, // Lock script pub lock_dep: packed::CellDep, pub lock_script: packed::Script, } /// A contract account's cell data pub struct ContractCell { /// The merkle root of key-value storage pub storage_root: H256, /// The transaction code hash (code_hash = blake2b(code), to verify the code in witness) pub code_hash: H256, } /// The witness data will be serialized and put into CKB transaction. /// NOTE: /// - Cannot put this witness in lock field /// - May not work with Nervos DAO #[derive(Clone, Debug, Eq, PartialEq)] pub struct WitnessData { /// The signature of CKB transaction. /// data_1 = [0u8; 65] /// data_2 = program.len() ++ program /// data_3 = return_data.len() ++ return_data /// program_data = data_1 ++ data_2 ++ data_3 /// /// FIXME: update it /// data_1 = tx_hash /// data_2 = program_data.len() ++ program_data /// data_3 = run_proof /// signature = sign_recoverable(data_1 ++ data_2 ++ data_3) /// pub signature: Bytes, /// The ethereum program(transaction) to run. pub program: Program, /// The return data (for read by other contract when contract call contract) pub return_data: Bytes, /// The call's selfdestruct target pub selfdestruct: Option<H160>, /// For verify every contract have exact number of programs in specific /// positions pub calls: Vec<(ContractAddress, u32)>, /// Provide storage diff and diff proofs. pub run_proof: Bytes, } #[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq, Hash)] #[serde(rename_all = "lowercase")] #[repr(u8)] pub enum CallKind { // < Request CALL. CALL = 0, // < Request DELEGATECALL. Valid since Homestead. The value param ignored. DELEGATECALL = 1, // < Request CALLCODE. CALLCODE = 2, // < Request CREATE. CREATE = 3, // < Request CREATE2. Valid since Constantinople. CREATE2 = 4, } /// Represent an ethereum transaction // TODO: pub value: U256 #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct Program { /// The kind of the call. For zero-depth calls ::EVMC_CALL SHOULD be used. pub kind: CallKind, /// Additional flags modifying the call execution behavior. /// In the current version the only valid values are ::EVMC_STATIC or 0. pub flags: u32, /// The call depth. pub depth: u32, /// The transaction origin address (EoA sender address) /// NOTE: There must only have one tx_origin in a CKB transaction, otherwise /// it will be too complex. pub tx_origin: EoaAddress, /// The sender of the message. (MUST be verified by the signature in witness data) pub sender: H160, /// The destination of the message (MUST be verified by the script args). pub destination: ContractAddress, /// The code to create/call the contract pub code: Bytes, /// The input data to create/call the contract pub input: Bytes, } /// The contract metadata pub struct ContractMeta { pub address: ContractAddress, pub code: Bytes, /// The hash of the transaction where the contract created pub tx_hash: H256, /// The output index of the transaction where the contract created pub output_index: u32, pub destructed: bool, } /// Represent a change record of a contract call #[derive(Default)] pub struct ContractChange { pub tx_origin: EoaAddress, pub address: ContractAddress, /// Block number pub number: u64, /// Transaction index in current block pub tx_index: u32, /// Output index in current transaction pub output_index: u32, pub tx_hash: H256, pub new_storage: HashMap<H256, H256>, pub logs: Vec<(Vec<H256>, Bytes)>, pub capacity: u64, /// The change is create the contract pub is_create: bool, } /// The EOA account address. /// Just the secp256k1_blake160 lock args, can be calculated from signature. /// /// address = blake2b(pubkey)[0..20] /// #[derive(Default, Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)] pub struct EoaAddress(pub H160); /// The contract account address. /// Use `type_id` logic to ensure it's uniqueness. /// Please see: https://github.com/nervosnetwork/ckb/blob/v0.31.1/script/src/type_id.rs /// /// data_1 = first_input.as_slice(); /// data_2 = first_output_index_in_current_group.to_le_bytes() /// address = blake2b(data_1 ++ data_2)[0..20] /// #[derive(Default, Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)] pub struct ContractAddress(pub H160); #[derive(Default, Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)] pub struct LogInfo { pub block_number: u64, pub tx_index: u32, pub address: ContractAddress, pub topics: Vec<H256>, pub data: Bytes, } impl From<&RunConfig> for Config { fn from(cfg: &RunConfig) -> Config { let mut config = Config::default(); config.generator = cfg.generator.clone(); config.validator_outpoint = cfg.type_dep.out_point(); config.type_script = cfg.type_script.clone(); config } } impl ContractCell { pub fn new(storage_root: H256, code_hash: H256) -> ContractCell { ContractCell { storage_root, code_hash, } } pub fn serialize(&self) -> Bytes { let mut data = BytesMut::default(); data.put(self.storage_root.as_bytes()); data.put(self.code_hash.as_bytes()); data.freeze() } } impl From<ContractAddress> for H160 { fn from(addr: ContractAddress) -> H160 { addr.0 } } impl From<H160> for ContractAddress { fn from(inner: H160) -> ContractAddress { ContractAddress(inner) } } impl TryFrom<&[u8]> for ContractAddress { type Error = String; fn try_from(source: &[u8]) -> Result<ContractAddress, String> { H160::from_slice(source) .map(ContractAddress) .map_err(|err| err.to_string()) } } impl From<EoaAddress> for H160 { fn from(addr: EoaAddress) -> H160 { addr.0 } } impl From<H160> for EoaAddress { fn from(inner: H160) -> EoaAddress { EoaAddress(inner) } } impl Default for CallKind { fn default() -> CallKind { CallKind::CALL } } impl Program { pub fn new_create(tx_origin: EoaAddress, sender: H160, code: Bytes) -> Program { Program { kind: CallKind::CREATE, flags: 0, depth: 0, tx_origin, sender, destination: ContractAddress::default(), code, input: Bytes::default(), } } pub fn new_call( tx_origin: EoaAddress, sender: H160, destination: ContractAddress, code: Bytes, input: Bytes, is_static: bool, ) -> Program { let flags = if is_static { 1 } else { 0 }; Program { kind: CallKind::CALL, flags, depth: 0, tx_origin, sender, destination, code, input, } } pub fn is_create(&self) -> bool { self.kind == CallKind::CREATE } pub fn serialize(&self) -> Bytes { let mut buf = BytesMut::default(); buf.put(&[self.kind as u8][..]); buf.put(&self.flags.to_le_bytes()[..]); buf.put(&self.depth.to_le_bytes()[..]); buf.put(self.tx_origin.0.as_bytes()); buf.put(self.sender.as_bytes()); buf.put(self.destination.0.as_bytes()); buf.put(&(self.code.len() as u32).to_le_bytes()[..]); buf.put(self.code.as_ref()); buf.put(&(self.input.len() as u32).to_le_bytes()[..]); buf.put(self.input.as_ref()); buf.freeze() } } impl TryFrom<&[u8]> for Program { type Error = String; fn try_from(data: &[u8]) -> Result<Program, String> { // Make sure access data[0] not panic if data.is_empty() { return Err(format!( "Not enough data length for parse Program: {}", data.len() )); } let kind = CallKind::try_from(data[0])?; let mut offset: usize = 1; let flags = load_u32(data, &mut offset)?; let depth = load_u32(data, &mut offset)?; let tx_origin = EoaAddress(load_h160(data, &mut offset)?); let sender = load_h160(data, &mut offset)?; let destination = ContractAddress(load_h160(data, &mut offset)?); let code = load_var_slice(data, &mut offset)?; let input = load_var_slice(data, &mut offset)?; if !data[offset..].is_empty() { return Err(format!("To much data for parse Program: {}", data.len())); } Ok(Program { kind, flags, depth, tx_origin, sender, destination, code: Bytes::from(code.to_vec()), input: Bytes::from(input.to_vec()), }) } } impl TryFrom<u8> for CallKind { type Error = String; fn try_from(value: u8) -> Result<CallKind, String> { match value { 0 => Ok(CallKind::CALL), 1 => Ok(CallKind::DELEGATECALL), 2 => Ok(CallKind::CALLCODE), 3 => Ok(CallKind::CREATE), 4 => Ok(CallKind::CREATE2), _ => Err(format!("Invalid call kind: {}", value)), } } } impl WitnessData { pub fn load_from(data: &[u8]) -> Result<Option<(usize, WitnessData)>, String> { let mut offset = 0; let (signature, program, return_data, selfdestruct, calls) = { let program_data = load_var_slice(data, &mut offset)?; if program_data.is_empty() { // The end of all programs (just like '\0' of C string) return Ok(None); } log::trace!("program_data: {}", hex::encode(&program_data)); let mut inner_offset = 0; let mut signature = [0u8; 65]; let tmp = load_slice_with_length(program_data, 65, &mut inner_offset)?; signature.copy_from_slice(tmp.as_ref()); let program_slice = load_var_slice(program_data, &mut inner_offset)?; log::trace!("program: {}", hex::encode(&program_slice)); let program = Program::try_from(program_slice)?; let return_data = load_var_slice(program_data, &mut inner_offset)?; let selfdestruct_target = load_h160(program_data, &mut inner_offset)?; let selfdestruct = if selfdestruct_target == H160::default() { None } else { Some(selfdestruct_target) }; let mut calls = Vec::new(); let calls_len = load_u32(program_data, &mut inner_offset)?; for _ in 0..calls_len { let contract_address = load_h160(program_data, &mut inner_offset)?; let program_index = load_u32(program_data, &mut inner_offset)?; calls.push((ContractAddress(contract_address), program_index)); } ( Bytes::from(signature[..].to_vec()), program, Bytes::from(return_data.to_vec()), selfdestruct, calls, ) }; let mut end = offset; { // see: RunProofResult::serialize_pure() let read_values_len = load_u32(&data, &mut end)?; end += 64 * read_values_len as usize; let read_proof_len = load_u32(&data, &mut end)?; end += read_proof_len as usize; let write_values_len = load_u32(&data, &mut end)?; end += 32 * write_values_len as usize; let write_old_proof_len = load_u32(&data, &mut end)?; end += write_old_proof_len as usize; } let run_proof = Bytes::from(data[offset..end].to_vec()); let witness_data = WitnessData { signature, program, return_data, selfdestruct, run_proof, calls, }; Ok(Some((end, witness_data))) } pub fn new(program: Program) -> WitnessData { WitnessData { signature: Bytes::from(vec![0u8; 65]), program, return_data: Bytes::default(), selfdestruct: None, run_proof: Bytes::default(), calls: Vec::new(), } } // The witness program item pub fn serialize(&self) -> Bytes { let mut buf = BytesMut::default(); let program_data = self.program_data(); buf.put(&(program_data.len() as u32).to_le_bytes()[..]); buf.put(program_data.as_ref()); buf.put(self.run_proof.as_ref()); buf.freeze() } // The data pass into execute_vm() in validator.h pub fn program_data(&self) -> Bytes { let mut buf = BytesMut::default(); let program = self.program.serialize(); log::trace!("program: {}", hex::encode(program.as_ref())); buf.put(self.signature.as_ref()); buf.put(&(program.len() as u32).to_le_bytes()[..]); buf.put(program.as_ref()); // Return data buf.put(&(self.return_data.len() as u32).to_le_bytes()[..]); buf.put(self.return_data.as_ref()); // selfdestruct beneficiary: H160 buf.put(self.selfdestruct.clone().unwrap_or_default().as_bytes()); // calls: Vec<(H160, u32)> buf.put(&(self.calls.len() as u32).to_le_bytes()[..]); for (contract_address, program_index) in &self.calls { buf.put(contract_address.0.as_bytes()); buf.put(&program_index.to_le_bytes()[..]); } buf.freeze() } } impl ContractMeta { pub fn db_key(&self) -> Key { Key::ContractMeta(self.address.clone()) } pub fn db_value(&self) -> value::ContractMeta { value::ContractMeta { code: self.code.clone(), tx_hash: self.tx_hash.clone(), output_index: self.output_index, destructed: self.destructed, } } } impl ContractChange { pub fn merkle_tree( &self, ) -> SparseMerkleTree<CkbBlake2bHasher, SmtH256, DefaultStore<SmtH256>> { let mut tree = SparseMerkleTree::default(); for (key, value) in &self.new_storage { tree.update(h256_to_smth256(key), h256_to_smth256(value)) .unwrap(); } tree } pub fn out_point(&self) -> packed::OutPoint { packed::OutPoint::new_builder() .tx_hash(self.tx_hash.pack()) .index(self.output_index.pack()) .build() } pub fn db_key(&self) -> Key { Key::ContractChange { address: self.address.clone(), number: Some(self.number), tx_index: Some(self.tx_index), output_index: Some(self.output_index), } } pub fn db_value(&self) -> value::ContractChange { value::ContractChange { tx_hash: self.tx_hash.clone(), tx_origin: self.tx_origin.clone(), new_storage: self.new_storage.clone().into_iter().collect(), capacity: self.capacity, is_create: self.is_create, } } pub fn db_key_logs(&self) -> Option<Key> { if self.logs.is_empty() { None } else { Some(Key::ContractLogs { address: self.address.clone(), number: Some(self.number), tx_index: Some(self.tx_index), output_index: Some(self.output_index), }) } } pub fn db_value_logs(&self) -> value::ContractLogs { value::ContractLogs(self.logs.clone()) } } pub fn smth256_to_h256(hash: &SmtH256) -> H256 { H256::from_slice(hash.as_slice()).unwrap() } pub fn h256_to_smth256(hash: &H256) -> SmtH256 { let mut buf = [0u8; 32]; buf.copy_from_slice(hash.as_bytes()); SmtH256::from(buf) } pub fn load_u32(data: &[u8], offset: &mut usize) -> Result<u32, String> { let offset_value = *offset; if data[offset_value..].len() < 4 { return Err(format!( "Not enough data length to parse u32: data.len={}, offset={}", data.len(), offset )); } let mut buf = [0u8; 4]; buf.copy_from_slice(&data[offset_value..offset_value + 4]); let value = u32::from_le_bytes(buf); log::trace!( "[load] u32 : offset={:>3}, value ={:>3}, slice={}", offset, value, hex::encode(&buf[..]) ); *offset += 4; Ok(value) } pub fn load_fixed_hash<T: std::fmt::LowerHex, F: Fn(&[u8]) -> T>( type_name: &str, data: &[u8], offset: &mut usize, converter: F, ) -> Result<T, String> { let hash_size: usize = std::mem::size_of::<T>(); let offset_value = *offset; if data[offset_value..].len() < hash_size { return Err(format!( "Not enough data length to parse {}: data.len={}, offset={}", type_name, data.len(), offset_value )); } let inner = converter(&data[offset_value..offset_value + hash_size]); log::trace!( "[load] {} : offset={:>3}, value={:x}", type_name, offset, inner ); *offset += hash_size; Ok(inner) } pub fn load_h160(data: &[u8], offset: &mut usize) -> Result<H160, String> { load_fixed_hash("H160", data, offset, |slice| { H160::from_slice(slice).unwrap() }) } pub fn load_h256(data: &[u8], offset: &mut usize) -> Result<H256, String> { load_fixed_hash("H256", data, offset, |slice| { H256::from_slice(slice).unwrap() }) } pub fn load_slice_with_length<'a>( data: &'a [u8], length: u32, offset: &mut usize, ) -> Result<&'a [u8], String> { let offset_value = *offset; let length = length as usize; if data[offset_value..].len() < length { return Err(format!( "Not enough data length to parse Bytes: data.len={}, length={}, offset={}", data.len(), length, offset_value )); } let target = &data[offset_value..offset_value + length]; log::trace!( "[load] slice: offset={:>3}, length={:>3}, slice={}", offset, length, hex::encode(target) ); *offset += length; Ok(target) } pub fn load_var_slice<'a>(data: &'a [u8], offset: &mut usize) -> Result<&'a [u8], String> { let length = load_u32(data, offset)?; load_slice_with_length(data, length, offset) } pub fn vm_load_u8<Mac: SupportMachine>(machine: &mut Mac, address: u64) -> Result<u8, VMError> { let data = vm_load_data(machine, address, 1)?; Ok(data[0]) } pub fn vm_load_i32<Mac: SupportMachine>(machine: &mut Mac, address: u64) -> Result<i32, VMError> { let data = vm_load_data(machine, address, 4)?; let mut i32_bytes = [0u8; 4]; i32_bytes.copy_from_slice(&data); Ok(i32::from_le_bytes(i32_bytes)) } pub fn vm_load_u32<Mac: SupportMachine>(machine: &mut Mac, address: u64) -> Result<u32, VMError> { let data = vm_load_data(machine, address, 4)?; let mut u32_bytes = [0u8; 4]; u32_bytes.copy_from_slice(&data); Ok(u32::from_le_bytes(u32_bytes)) } pub fn vm_load_i64<Mac: SupportMachine>(machine: &mut Mac, address: u64) -> Result<i64, VMError> { let data = vm_load_data(machine, address, 8)?; let mut i64_bytes = [0u8; 8]; i64_bytes.copy_from_slice(&data); Ok(i64::from_le_bytes(i64_bytes)) } pub fn vm_load_h160<Mac: SupportMachine>(machine: &mut Mac, address: u64) -> Result<H160, VMError> { let data = vm_load_data(machine, address, 20)?; Ok(H160::from_slice(&data).unwrap()) } pub fn vm_load_h256<Mac: SupportMachine>(machine: &mut Mac, address: u64) -> Result<H256, VMError> { let data = vm_load_data(machine, address, 32)?; Ok(H256::from_slice(&data).unwrap()) } pub fn vm_load_data<Mac: SupportMachine>( machine: &mut Mac, address: u64, length: u32, ) -> Result<Vec<u8>, VMError> { let mut data = vec![0u8; length as usize]; for (i, c) in data.iter_mut().enumerate() { *c = machine .memory_mut() .load8(&Mac::REG::from_u64(address).overflowing_add(&Mac::REG::from_u64(i as u64)))? .to_u8(); } Ok(data) } pub fn parse_log(raw: &[u8]) -> Result<(Vec<H256>, Bytes), String> { let mut offset = 0; let data_slice = load_var_slice(raw, &mut offset)?; let mut topics = Vec::new(); let topics_count = load_u32(raw, &mut offset)?; for _ in 0..topics_count { topics.push(load_h256(raw, &mut offset)?); } Ok((topics, Bytes::from(data_slice.to_vec()))) } #[cfg(test)] mod test { use super::*; use ckb_simple_account_layer::RunProofResult; use ckb_types::h160; #[test] fn test_serde_program() { let program1 = Program::new_create( Default::default(), Default::default(), Bytes::from("abcdef"), ); let binary = program1.serialize(); let program2 = Program::try_from(binary.as_ref()).unwrap(); assert_eq!(program1, program2); } #[test] fn test_serde_witness_data() { // let data = hex::decode("95010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000038010000000000000000000000c8328aabcd9b9e8e64fbc566c4385c3bdeb219d7fa36e4fb6bf83b0d4ff5ac34c10e1f56893c9e4edb00000060806040526004361060295760003560e01c806360fe47b114602f5780636d4ce63c14605b576029565b60006000fd5b60596004803603602081101560445760006000fd5b81019080803590602001909291905050506084565b005b34801560675760006000fd5b50606e6094565b6040518082815260200191505060405180910390f35b8060006000508190909055505b50565b6000600060005054905060a2565b9056fea26469706673582212204e58804e375d4a732a7b67cce8d8ffa904fa534d4555e655a433ce0a5e0d339f64736f6c634300060600332400000060fe47b100000000000000000000000000000000000000000000000000000000000000230000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000022010000004c").unwrap(); // WitnessData::load_from(data.as_slice()).unwrap(); let mut run_proof = RunProofResult::default(); run_proof.read_values = vec![(SmtH256::default(), SmtH256::default())]; run_proof.read_proof = Bytes::from("xxyyzz"); run_proof.write_values = vec![(SmtH256::default(), SmtH256::default(), SmtH256::default())]; run_proof.write_old_proof = Bytes::from("beef"); let run_proof_data = run_proof.serialize_pure().unwrap(); let witness_data1 = WitnessData { signature: Bytes::from([1u8; 65].to_vec()), program: Program::new_create( Default::default(), Default::default(), Bytes::from("abcdef"), ), return_data: Bytes::from("return data"), selfdestruct: None, run_proof: Bytes::from(run_proof_data), calls: vec![ (ContractAddress(h160!("0x33")), 0), (ContractAddress(h160!("0x44")), 3), ], }; let program_data = witness_data1.program_data(); let binary = run_proof.serialize(&program_data).unwrap(); let witness_data2 = WitnessData::load_from(binary.as_ref()).unwrap().unwrap().1; assert_eq!(witness_data1, witness_data2); } }