text
stringlengths
8
4.13M
//! A crate to wait on a child process with a particular timeout. //! //! This crate is an implementation for Unix and Windows of the ability to wait //! on a child process with a timeout specified. On Windows the implementation //! is fairly trivial as it's just a call to `WaitForSingleObject` with a //! timeout argument, but on Unix the implementation is much more involved. The //! current implementation registeres a `SIGCHLD` handler and initializes some //! global state. If your application is otherwise handling `SIGCHLD` then bugs //! may arise. //! //! # Example //! //! ```no_run //! use std::process::Command; //! use wait_timeout::ChildExt; //! use std::time::Duration; //! //! let mut child = Command::new("foo").spawn().unwrap(); //! //! let one_sec = Duration::from_secs(1); //! let status_code = match child.wait_timeout(one_sec).unwrap() { //! Some(status) => status.code(), //! None => { //! // child hasn't exited yet //! child.kill().unwrap(); //! child.wait().unwrap().code() //! } //! }; //! ``` #![deny(missing_docs, warnings)] #![doc(html_root_url = "https://docs.rs/wait-timeout/0.1")] extern crate libc; use std::fmt; use std::io; use std::process::Child; use std::time::Duration; /// Exit status from a child process. /// /// This type mirrors that in `std::process` but currently must be distinct as /// the one in `std::process` cannot be created. #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct ExitStatus(imp::ExitStatus); #[cfg(unix)] #[path = "unix.rs"] mod imp; #[cfg(windows)] #[path = "windows.rs"] mod imp; /// Extension methods for the standard `std::process::Child` type. pub trait ChildExt { /// Deprecated, use `wait_timeout` instead. #[doc(hidden)] fn wait_timeout_ms(&mut self, ms: u32) -> io::Result<Option<ExitStatus>> { self.wait_timeout(Duration::from_millis(ms as u64)) } /// Wait for this child to exit, timing out after `ms` milliseconds have /// elapsed. /// /// If `Ok(None)` is returned then the timeout period elapsed without the /// child exiting, and if `Ok(Some(..))` is returned then the child exited /// with the specified exit code. /// /// # Warning /// /// Currently this function must be called with great care. If the child /// has already been waited on (e.g. `wait` returned a success) then this /// function will either wait on another process or fail spuriously on some /// platforms. This function may only be reliably called if the process has /// not already been waited on. /// /// Additionally, once this method completes the original child cannot be /// waited on reliably. The `wait` method on the original child may return /// spurious errors or have odd behavior on some platforms. If this /// function returns `Ok(None)`, however, it is safe to wait on the child /// with the normal libstd `wait` method. fn wait_timeout(&mut self, dur: Duration) -> io::Result<Option<ExitStatus>>; } impl ChildExt for Child { fn wait_timeout(&mut self, dur: Duration) -> io::Result<Option<ExitStatus>> { imp::wait_timeout(self, dur).map(|m| m.map(ExitStatus)) } } impl ExitStatus { /// Returns whether this exit status represents a successful execution. /// /// This typically means that the child process successfully exited with a /// status code of 0. pub fn success(&self) -> bool { self.0.success() } /// Returns the code associated with the child's exit event. /// /// On Unix this can return `None` if the child instead exited because of a /// signal. On Windows, however, this will always return `Some`. pub fn code(&self) -> Option<i32> { self.0.code() } /// Returns the Unix signal which terminated this process. /// /// Note that on Windows this will always return `None` and on Unix this /// will return `None` if the process successfully exited otherwise. pub fn unix_signal(&self) -> Option<i32> { self.0.unix_signal() } } impl fmt::Display for ExitStatus { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(c) = self.code() { write!(f, "exit code: {}", c) } else if let Some(s) = self.unix_signal() { write!(f, "signal: {}", s) } else { write!(f, "exit status: unknown") } } }
use crate::{ event::{self, Event, LogEvent, Value}, transforms::{ json_parser::{JsonParser, JsonParserConfig}, Transform, }, }; use chrono::{DateTime, Utc}; use lazy_static::lazy_static; use snafu::{OptionExt, ResultExt, Snafu}; use string_cache::DefaultAtom as Atom; lazy_static! { pub static ref TIME: Atom = Atom::from("time"); pub static ref LOG: Atom = Atom::from("log"); } /// Parser for the docker log format. /// /// Expects logs to arrive in a JSONLines format with the fields names and /// contents specific to the implementation of the Docker `json` log driver. /// /// Normalizes parsed data for consistency. #[derive(Debug)] pub struct Docker { json_parser: JsonParser, } impl Docker { /// Create a new [`Docker`] parser. pub fn new() -> Self { let json_parser = { let mut config = JsonParserConfig::default(); config.drop_field = true; // Drop so that it's possible to detect if message is in json format. config.drop_invalid = true; config.into() }; Self { json_parser } } } impl Transform for Docker { fn transform(&mut self, event: Event) -> Option<Event> { let mut event = self.json_parser.transform(event)?; normalize_event(event.as_mut_log()).ok()?; Some(event) } } const DOCKER_MESSAGE_SPLIT_THRESHOLD: usize = 16 * 1024; // 16 Kib fn normalize_event(log: &mut LogEvent) -> Result<(), NormalizationError> { // Parse and rename timestamp. let time = log.remove(&TIME).context(TimeFieldMissing)?; let time = match time { Value::Bytes(val) => val, _ => return Err(NormalizationError::TimeValueUnexpectedType), }; let time = DateTime::parse_from_rfc3339(String::from_utf8_lossy(time.as_ref()).as_ref()) .context(TimeParsing)?; log.insert( event::log_schema().timestamp_key(), time.with_timezone(&Utc), ); // Parse message, remove trailing newline and detect if it's partial. let message = log.remove(&LOG).context(LogFieldMissing)?; let mut message = match message { Value::Bytes(val) => val, _ => return Err(NormalizationError::LogValueUnexpectedType), }; // Here we apply out heuristics to detect if messge is partial. // Partial messages are only split in docker at the maximum message length // (`DOCKER_MESSAGE_SPLIT_THRESHOLD`). // Thus, for a message to be partial it also has to have exactly that // length. // Now, whether that message will or won't actually be partial if it has // exactly the max length is unknown. We consider all messages with the // exact length of `DOCKER_MESSAGE_SPLIT_THRESHOLD` bytes partial // by default, and then, if they end with newline - consider that // an exception and make them non-partial. // This is still not ideal, and can potentially be improved. let mut is_partial = message.len() == DOCKER_MESSAGE_SPLIT_THRESHOLD; if message.last().map(|&b| b as char == '\n').unwrap_or(false) { message.truncate(message.len() - 1); is_partial = false; }; log.insert(event::log_schema().message_key(), message); // For partial messages add a partial event indicator. if is_partial { log.insert(event::PARTIAL_STR, true); } Ok(()) } #[derive(Debug, Snafu)] enum NormalizationError { TimeFieldMissing, TimeValueUnexpectedType, TimeParsing { source: chrono::ParseError }, LogFieldMissing, LogValueUnexpectedType, } #[cfg(test)] pub mod tests { use super::super::test_util; use super::Docker; use crate::event::LogEvent; fn make_long_string(base: &str, len: usize) -> String { base.chars().cycle().take(len).collect() } /// Shared test cases. pub fn cases() -> Vec<(String, LogEvent)> { vec![ ( r#"{"log": "The actual log line\n", "stream": "stderr", "time": "2016-10-05T00:00:30.082640485Z"}"#.into(), test_util::make_log_event( "The actual log line", "2016-10-05T00:00:30.082640485Z", "stderr", false, ), ), ( r#"{"log": "A line without newline chan at the end", "stream": "stdout", "time": "2016-10-05T00:00:30.082640485Z"}"#.into(), test_util::make_log_event( "A line without newline chan at the end", "2016-10-05T00:00:30.082640485Z", "stdout", false, ), ), // Partial message due to message length. ( [ r#"{"log": ""#, make_long_string("partial ", 16 * 1024).as_str(), r#"", "stream": "stdout", "time": "2016-10-05T00:00:30.082640485Z"}"#, ] .join(""), test_util::make_log_event( make_long_string("partial ",16 * 1024).as_str(), "2016-10-05T00:00:30.082640485Z", "stdout", true, ), ), // Non-partial message, because message length matches but // the message also ends with newline. ( [ r#"{"log": ""#, make_long_string("non-partial ", 16 * 1024 - 1).as_str(), r"\n", r#"", "stream": "stdout", "time": "2016-10-05T00:00:30.082640485Z"}"#, ] .join(""), test_util::make_log_event( make_long_string("non-partial ", 16 * 1024 - 1).as_str(), "2016-10-05T00:00:30.082640485Z", "stdout", false, ), ), ] } #[test] fn test_parsing() { test_util::test_parser(Docker::new, cases()); } }
pub mod pgr { pub fn pgr_function(key: String, text: String, diference : usize) -> Vec<u8> { let mut new_key = Vec::with_capacity(128); let len_key = key.chars().count(); let key_chars: Vec<char> = key.chars().collect(); let seed = ['c', 'h', 'a', 'p', 'o', 'r', 'o', 'o']; let mut seed_expand = shift_seed(seed, key, text); let mut n = 0; while n < diference { new_key.push(seed_expand[n]); n = n + 1; } n = 0; while n < len_key{ new_key.push(key_chars[n]); n = n + 1; } let key_as_String : String = new_key.into_iter().collect(); let key_expand = key_as_String.as_bytes(); return Vec::from(key_expand); } pub fn shift_seed(seed: [char; 8], key: String, text: String) -> Vec<char> { let diference = text.chars().count() - key.chars().count(); let mut new_seed = Vec::with_capacity(128); let mut n = 0; if diference < 5 { while n < diference { new_seed.push(seed[7 - n]); n = n + 1; } } else { new_seed.push(seed[7]); new_seed.push(seed[0]); new_seed.push(seed[6]); new_seed.push(seed[5]); new_seed.push(seed[4]); new_seed.push(seed[2]); new_seed.push(seed[1]); new_seed.push(seed[3]); } return new_seed; } }
pub use crate::{ abi_stability::{ extra_checks::StoredExtraChecks, get_static_equivalent::{GetStaticEquivalent, GetStaticEquivalent_}, stable_abi_trait::{ PrefixStableAbi, StableAbi, __opaque_field_type_layout, __sabi_opaque_field_type_layout, get_prefix_field_type_layout, get_type_layout, EXTERN_FN_LAYOUT, UNSAFE_EXTERN_FN_LAYOUT, }, ConstGeneric, }, erased_types::{MakeVTable as MakeDynTraitVTable, VTable_Ref as DynTraitVTable_Ref}, extern_fn_panic_handling, inline_storage::{GetAlignerFor, InlineStorage}, marker_type::{ NonOwningPhantom, NotCopyNotClone, SyncSend, SyncUnsend, UnsafeIgnoredType, UnsyncSend, UnsyncUnsend, }, nonexhaustive_enum::{ assert_correct_default_storage, assert_correct_storage, AssertCsArgs, EnumInfo, GetEnumInfo, GetVTable as NonExhaustiveMarkerVTable, NonExhaustive, NonExhaustiveMarker, ValidDiscriminant, }, pointer_trait::{AsMutPtr, AsPtr, GetPointerKind, PK_Reference}, prefix_type::{ panic_on_missing_field_ty, FieldAccessibility, FieldConditionality, IsAccessible, IsConditional, PTStructLayout, PrefixRef, PrefixRefTrait, PrefixTypeTrait, WithMetadata_, }, reflection::ModReflMode, sabi_trait::vtable::{GetRObjectVTable, RObjectVtable, RObjectVtable_Ref}, sabi_types::{Constructor, MovePtr, RMut, RRef, VersionStrings}, std_types::{utypeid::new_utypeid, RErr, RNone, ROk, ROption, RResult, RSlice, RSome}, type_layout::{ CompTLFields, CompTLFunction, DiscriminantRepr, FieldAccessor, GenericTLData, GenericTLEnum, GenericTLPrefixType, IsExhaustive, LifetimeIndex, MakeTLNonExhaustive, MonoSharedVars, MonoTLData, MonoTLEnum, MonoTLPrefixType, MonoTypeLayout, ReprAttr, SharedVars, StartLen, TLDiscriminants, TLFunction, TLFunctionQualifiers, TLFunctions, TLNonExhaustive, Tag, TypeLayout, _private_MonoTypeLayoutDerive, _private_TypeLayoutDerive, }, type_level::{ downcasting::TD_Opaque, impl_enum::{ImplFrom, Implemented, Unimplemented}, trait_marker, }, }; pub use std::{ concat, convert::{identity, From}, fmt::{Debug, Formatter, Result as FmtResult}, mem::ManuallyDrop, option::Option, primitive::{str, u8, usize}, ptr::NonNull, vec, }; pub use repr_offset::offset_calc::next_field_offset; pub use core_extensions::{ count_tts, type_asserts::AssertEq, type_level_bool::{False, True}, }; pub use ::paste::paste; pub mod renamed { pub use super::{ CompTLFields as __CompTLFields, CompTLFunction as __CompTLFunction, ConstGeneric as __ConstGeneric, DiscriminantRepr as __DiscriminantRepr, FieldAccessor as __FieldAccessor, GetStaticEquivalent as __GetStaticEquivalent, GetStaticEquivalent_ as __GetStaticEquivalent_, IsExhaustive as __IsExhaustive, LifetimeIndex as __LifetimeIndex, ModReflMode as __ModReflMode, PTStructLayout as __PTStructLayout, RMut as __RMut, RNone as __RNone, RRef as __RRef, RSome as __RSome, ReprAttr as __ReprAttr, StableAbi as __StableAbi, StartLen as __StartLen, TLDiscriminants as __TLDiscriminants, TLFunction as __TLFunction, TLFunctionQualifiers as __TLFunctionQualifiers, TLFunctions as __TLFunctions, WithMetadata_ as __WithMetadata_, _private_TypeLayoutDerive as __private_TypeLayoutDerive, EXTERN_FN_LAYOUT as __EXTERN_FN_LAYOUT, UNSAFE_EXTERN_FN_LAYOUT as __UNSAFE_EXTERN_FN_LAYOUT, }; }
use crate::utils::de_float_from_str; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize, Debug)] pub struct RawOrderBook { pub lastUpdateId: u64, pub bids: Vec<[String; 2]>, pub asks: Vec<[String; 2]>, } #[derive(Debug, Deserialize, Serialize)] pub struct OfferData { pub price: f32, pub size: f32, } #[derive(Debug, Deserialize, Serialize)] pub struct OrderBookDTO { pub lastUpdateId: u64, pub bids: Vec<OfferData>, pub asks: Vec<OfferData>, } #[derive(Debug, Deserialize, Serialize)] pub struct Trade { id: u64, #[serde(deserialize_with = "de_float_from_str")] price: f32, #[serde(deserialize_with = "de_float_from_str")] qty: f32, #[serde(deserialize_with = "de_float_from_str")] quoteQty: f32, time: u64, isBuyerMaker: bool, isBestMatch: bool, }
// use std::cmp::Ordering; // ======UnionFind====== // ======Kruskal====== mod Kruscal { #[derive(Debug)] struct UnionFind { // size= 親なら負のサイズ、子なら親 // number= 集合の数 table: Vec<i64>, number: usize, } impl UnionFind { fn new(n: usize) -> Self { let table = vec![-1; n]; UnionFind { table: table, number: n, } } } impl UnionFind { fn root(&mut self, x: usize) -> usize { let par = self.table[x]; if par < 0 { x } else { let tmp = self.root(par as usize); self.table[x] = tmp as i64; tmp } } fn same(&mut self, a: usize, b: usize) -> bool { self.root(a) == self.root(b) } fn union(&mut self, a: usize, b: usize) -> () { let a_root = self.root(a); let b_root = self.root(b); if a_root == b_root { return (); } // 負なので小さい法が大きい. 大きい方につける if self.table[a_root] > self.table[b_root] { self.table[b_root] += self.table[a_root]; self.table[a_root] = b_root as i64; } else { self.table[a_root] += self.table[b_root]; self.table[b_root] = a_root as i64; } self.number -= 1; } // 親のサイズを返す fn size(&mut self, x: usize) -> usize { let ri = self.root(x); -self.table[ri] as usize } fn count(&self) -> usize { self.number } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Edge { pub from: usize, pub to: usize, pub cost: i64, } impl Ord for Edge { fn cmp(&self, other: &Edge) -> std::cmp::Ordering { self.cost.cmp(&other.cost) } } impl PartialOrd for Edge { fn partial_cmp(&self, other: &Edge) -> Option<std::cmp::Ordering> { Some(self.cmp(&other)) } } pub fn build(v: usize, edges: &mut Vec<Edge>) -> (Vec<Edge>, i64) { let mut uf = UnionFind::new(v); // sort ascending order edges.sort(); // remove duplicated edge edges.dedup(); let mut res_tree: Vec<Edge> = vec![]; let mut res: i64 = 0; // till all edges are checked for e in edges { if !uf.same(e.from, e.to) { uf.union(e.from, e.to); res_tree.push(*e); res += e.cost; } } (res_tree, res) } } #[cfg(test)] mod tests { use super::*; #[test] fn check_kruscal() { let v = 6; let e = 9; // from, to, cost let data: Vec<(usize, usize, i64)> = vec![ (0, 1, 1), (0, 2, 3), (1, 2, 1), (1, 3, 7), (2, 4, 1), (1, 4, 3), (3, 4, 1), (3, 5, 1), (4, 5, 6), ]; let mut edges: Vec<Edge> = data .iter() .map(|(f, t, c): &(usize, usize, i64)| Edge { from: *f, to: *t, cost: *c, }) .collect(); let k = Kruscal::build(v, &mut edges); println!("{:?}", k); } #[test] fn union_root_same() { let mut uf = UnionFind::new(10); // はじめは自分をさしてる for i in 0..10 { assert_eq!(uf.root(i), i); } // つなぐ uf.union(0, 1); println!("{:?}", uf); uf.union(0, 0); uf.union(1, 2); uf.union(2, 9); assert_eq!(uf.same(0, 1), true); assert_eq!(uf.same(0, 2), true); assert_eq!(uf.same(0, 3), false); assert_eq!(uf.same(0, 4), false); assert_eq!(uf.same(0, 9), true); assert_eq!(uf.size(0), 4); assert_eq!(uf.size(3), 1); } #[test] fn check_size() { let mut uf = UnionFind::new(10); uf.union(1, 2); uf.union(4, 6); uf.union(9, 1); assert_eq!(uf.size(0), 1); assert_eq!(uf.size(1), 3); assert_eq!(uf.size(2), 3); assert_eq!(uf.size(3), 1); assert_eq!(uf.size(4), 2); assert_eq!(uf.size(5), 1); assert_eq!(uf.size(6), 2); assert_eq!(uf.size(9), 3); } } fn main() {}
extern crate sfml; use std::error::Error; use std::fs::File; use std::io::prelude::*; use machine::Machine; pub mod cpu; pub mod machine; pub fn run(config: Config) -> Result<(), Box<Error>> { let mut f = File::open(config.filename)?; let mut buffer = Vec::new(); f.read_to_end(&mut buffer)?; let mut machine = Machine::new(buffer); machine.emulate(); Ok(()) } pub struct Config { pub filename: String, pub debug: bool, } impl Config { pub fn new(mut args: std::env::Args) -> Result<Config, &'static str> { args.next(); let filename = match args.next() { Some(arg) => arg, None => return Err("Filename missing"), }; Ok(Config { filename, debug: false, }) } }
fn main() { let names = vec!["Agus", "Susilo", "Nurhayati"]; for (index, name) in names.iter().enumerate() { println!("{} {}", index, name); } }
use crate::mem; pub struct ExtFn { pub(crate) ptr: usize } impl ExtFn { pub fn f(&self) -> extern fn() { unsafe { mem::transmute(self.ptr) } } pub unsafe fn fn0<Res>(&self) -> extern fn() -> Res { mem::transmute(self.ptr) } pub unsafe fn fn1<A, Res>(&self) -> extern fn(A) -> Res { mem::transmute(self.ptr) } pub unsafe fn fn2<A, B, Res>(&self) -> extern fn(A, B) -> Res { mem::transmute(self.ptr) } pub unsafe fn fn3<A, B, C, Res>(&self) -> extern fn(A, B, C) -> Res { mem::transmute(self.ptr) } pub unsafe fn fn4<A, B, C, D, Res>(&self) -> extern fn(A, B, C, D) -> Res { mem::transmute(self.ptr) } pub unsafe fn fn5<A, B, C, D, E, Res>(&self) -> extern fn(A, B, C, D, E) -> Res { mem::transmute(self.ptr) } pub unsafe fn fn_var<A, Res>(&self) -> extern fn(A, ...) -> Res { mem::transmute(self.ptr) } }
extern crate binjs; extern crate itertools; use binjs::generic::{FromJSON, IdentifierName, InterfaceName, Offset, PropertyKey, SharedString}; use binjs::io::entropy; use binjs::io::entropy::dictionary::{DictionaryBuilder, FilesContaining}; use binjs::io::entropy::probabilities::InstancesToProbabilities; use binjs::io::{Deserialization, TokenSerializer}; use binjs::source::{Shift, SourceParser}; use binjs::specialized::es6::ast::{Script, Visitor, WalkPath, Walker}; use binjs::specialized::es6::io::IOPath; use std::collections::HashMap; use itertools::Itertools; const DEPTH: usize = 2; const WIDTH: usize = 32; #[macro_use] extern crate test_logger; /// A visitor designed to reset offsets to 0. struct OffsetCleanerVisitor; impl Visitor<()> for OffsetCleanerVisitor { fn visit_offset(&mut self, _path: &WalkPath, node: &mut Offset) -> Result<(), ()> { *node = binjs::generic::Offset(0); Ok(()) } } test!(test_entropy_roundtrip, { let parser = Shift::try_new().expect("Could not launch Shift"); let dict_sources = [ "var x = y", "let x = y", "'use strict'", "function foo(x, y) { var i; for (i = 0; i < 100; ++i) { console.log('Some text', x, y + i, x + y + i, x + y + i + 1); } }", "function foo() { if (Math.PI != 3) console.log(\"That's alright\"); }", ]; let mut builder = DictionaryBuilder::new(DEPTH, WIDTH); for source in &dict_sources { println!("Parsing"); let ast = parser.parse_str(source).expect("Could not parse source"); let mut ast = binjs::specialized::es6::ast::Script::import(&ast).expect("Could not import AST"); println!("Annotating"); binjs::specialized::es6::scopes::AnnotationVisitor::new().annotate_script(&mut ast); println!("Extracting dictionary"); let mut serializer = binjs::specialized::es6::io::Serializer::new(&mut builder); let mut path = IOPath::new(); serializer .serialize(&ast, &mut path) .expect("Could not walk"); let _ = serializer.done().expect("Could not walk"); } println!("Checking identifiers per file"); check_strings( &builder.files_containing().identifier_name_instances, vec![ ("Math", 1), ("console", 2), ("foo", 2), ("i", 1), ("x", 3), ("y", 3), ], |name| Some(IdentifierName::from_string(name.to_string())), ); println!("Checking property keys per file"); check_strings( &builder.files_containing().property_key_instances, vec![("PI", 1), ("log", 2)], |name| Some(PropertyKey::from_string(name.to_string())), ); println!("Checking interface names per file"); check_strings( &builder.files_containing().interface_name_instances, vec![ ("", 2), // FIXME: Where is this `null`? ("AssertedBlockScope", 1), ("AssertedDeclaredName", 4), ("AssertedParameterScope", 2), ("AssertedPositionalParameterName", 1), // FIXME: Where is this? ("AssertedScriptGlobalScope", 5), ("AssertedVarScope", 2), ("AssignmentExpression", 1), ("AssignmentTargetIdentifier", 1), ("BinaryExpression", 2), ("BindingIdentifier", 4), ("Block", 1), ("CallExpression", 2), ("Directive", 1), ("EagerFunctionDeclaration", 2), ("ExpressionStatement", 2), ("ForStatement", 1), ("FormalParameters", 2), ("FunctionOrMethodContents", 2), ("IdentifierExpression", 4), ("IfStatement", 1), ("LiteralNumericExpression", 2), ("LiteralStringExpression", 2), ("Script", 5), ("StaticMemberExpression", 2), ("UpdateExpression", 1), ("VariableDeclaration", 3), ("VariableDeclarator", 3), ], |name| InterfaceName::from_string(name.to_string()), ); println!("String literals per file"); check_strings( &builder.files_containing().string_literal_instances, vec![("Some text", 1), ("That\'s alright", 1), ("use strict", 1)], |value| Some(SharedString::from_string(value.to_string())), ); // We may now access data. let dictionary = builder.done(0.into() /* Keep all user-extensible data */); println!("Built a dictionary with {} states", dictionary.len()); let options = entropy::Options::new(dictionary.instances_to_probabilities("dictionary")); println!("Starting roundtrip with dictionary"); for source in &dict_sources { test_with_options(&parser, source, &options); } println!("Starting roundtrip that exceed dictionary"); let out_of_dictionary = [ "var z = y", "'use asm';", "function not_in_the_dictionary() {}", "function foo() { if (Math.E != 4) console.log(\"That's also normal.\"); }", ]; for source in &out_of_dictionary { test_with_options(&parser, source, &options); } }); fn test_with_options<S>(parser: &S, source: &str, options: &entropy::Options) where S: SourceParser, { println!("Parsing with dictionary: {}", source); let ast = parser.parse_str(source).expect("Could not parse source"); let mut ast = binjs::specialized::es6::ast::Script::import(&ast).expect("Could not import AST"); println!("Reannotating"); binjs::specialized::es6::scopes::AnnotationVisitor::new().annotate_script(&mut ast); let mut path = IOPath::new(); println!("Serializing with entropy"); let encoder = entropy::write::Encoder::new(None, options.clone()); let mut serializer = binjs::specialized::es6::io::Serializer::new(encoder); serializer .serialize(&ast, &mut path) .expect("Could not walk"); let data = serializer.done().expect("Could not walk"); assert_eq!(path.len(), 0); println!("Deserializing {} bytes with entropy", data.len()); let decoder = entropy::read::Decoder::new(&options, std::io::Cursor::new(data)) .expect("Could not create decoder"); let mut deserializer = binjs::specialized::es6::io::Deserializer::new(decoder); let mut script: Script = deserializer .deserialize(&mut path) .expect("Could not deserialize"); println!("Checking equality between ASTs"); println!("{}", source); // At this stage, we have a problem: offsets are 0 in `ast`, but not necessarily // in `decoded`. script .walk(&mut WalkPath::new(), &mut OffsetCleanerVisitor) .expect("Could not cleanup offsets"); assert_eq!(ast, script); } fn check_strings<T, F>(found: &HashMap<T, FilesContaining>, expected: Vec<(&str, usize)>, f: F) where F: Fn(&str) -> T, T: Eq + std::hash::Hash + Ord + Clone + std::fmt::Debug, { let found = found .iter() .map(|(name, instances)| ((*name).clone(), *instances)) .sorted(); let expected = expected .into_iter() .map(|(name, instances)| (f(name), FilesContaining(instances))) .sorted(); assert_eq!(found, expected); }
//! Tests auto-converted from "sass-spec/spec/libsass/parent-selector" #[allow(unused)] use super::rsass; #[allow(unused)] use rsass::precision; /// From "sass-spec/spec/libsass/parent-selector/basic" #[test] fn basic() { assert_eq!( rsass( "foo bar {\n baz & {\n bam: true;\n }\n}\n\nfoo {\n bar baz & {\n bam: true;\n }\n}\n" ) .unwrap(), "baz foo bar {\n bam: true;\n}\n\nbar baz foo {\n bam: true;\n}\n" ); } /// From "sass-spec/spec/libsass/parent-selector/inner-combinator" #[test] fn inner_combinator() { assert_eq!( rsass( "foo {\n & bar baz {\n bam: true;\n }\n bar baz & {\n bam: true;\n }\n}\n\nfoo {\n & bar + baz {\n bam: true;\n }\n bar + baz & {\n bam: true;\n }\n}\n\nfoo {\n & bar > baz {\n bam: true;\n }\n bar > baz & {\n bam: true;\n }\n}\n\nfoo {\n & bar ~ baz {\n bam: true;\n }\n bar ~ baz & {\n bam: true;\n }\n}\n" ) .unwrap(), "foo bar baz {\n bam: true;\n}\nbar baz foo {\n bam: true;\n}\n\nfoo bar + baz {\n bam: true;\n}\nbar + baz foo {\n bam: true;\n}\n\nfoo bar > baz {\n bam: true;\n}\nbar > baz foo {\n bam: true;\n}\n\nfoo bar ~ baz {\n bam: true;\n}\nbar ~ baz foo {\n bam: true;\n}\n" ); } /// From "sass-spec/spec/libsass/parent-selector/inner-pseudo" #[test] fn inner_pseudo() { assert_eq!( rsass( "foo {\n &:bar baz {\n bam: true;\n }\n}\n\nfoo {\n &:bar + baz {\n bam: true;\n }\n}\n\nfoo {\n &:bar > baz {\n bam: true;\n }\n}\n\nfoo {\n &:bar ~ baz {\n bam: true;\n }\n}\n" ) .unwrap(), "foo:bar baz {\n bam: true;\n}\n\nfoo:bar + baz {\n bam: true;\n}\n\nfoo:bar > baz {\n bam: true;\n}\n\nfoo:bar ~ baz {\n bam: true;\n}\n" ); } // Ignoring "missing", tests with expected error not implemented yet. /// From "sass-spec/spec/libsass/parent-selector/outer-combinator" #[test] fn outer_combinator() { assert_eq!( rsass( "foo bar {\n & baz {\n bam: true;\n }\n baz & {\n bam: true;\n }\n}\n\nfoo + bar {\n & baz {\n bam: true;\n }\n baz & {\n bam: true;\n }\n}\n\nfoo > bar {\n & baz {\n bam: true;\n }\n baz & {\n bam: true;\n }\n}\n\nfoo ~ bar {\n & baz {\n bam: true;\n }\n baz & {\n bam: true;\n }\n}\n" ) .unwrap(), "foo bar baz {\n bam: true;\n}\nbaz foo bar {\n bam: true;\n}\n\nfoo + bar baz {\n bam: true;\n}\nbaz foo + bar {\n bam: true;\n}\n\nfoo > bar baz {\n bam: true;\n}\nbaz foo > bar {\n bam: true;\n}\n\nfoo ~ bar baz {\n bam: true;\n}\nbaz foo ~ bar {\n bam: true;\n}\n" ); } /// From "sass-spec/spec/libsass/parent-selector/outer-pseudo" #[test] fn outer_pseudo() { assert_eq!( rsass( "foo bar {\n &:baz {\n bam: true;\n }\n}\n\nfoo + bar {\n &:baz {\n bam: true;\n }\n}\n\nfoo > bar {\n &:baz {\n bam: true;\n }\n}\n\nfoo ~ bar {\n &:baz {\n bam: true;\n }\n}\n" ) .unwrap(), "foo bar:baz {\n bam: true;\n}\n\nfoo + bar:baz {\n bam: true;\n}\n\nfoo > bar:baz {\n bam: true;\n}\n\nfoo ~ bar:baz {\n bam: true;\n}\n" ); }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::vec::Vec; use super::super::qlib::common::*; use super::super::qlib::uring::sys::sys::*; use super::super::qlib::uring::*; use super::super::*; use super::host_uring::*; //#[derive(Debug)] pub struct UringMgr { pub fd: i32, pub eventfd: i32, pub fds: Vec<i32>, pub ring: IoUring, } pub const FDS_SIZE : usize = 4096; impl UringMgr { pub fn New(size: usize) -> Self { let mut fds = Vec::with_capacity(FDS_SIZE); for _i in 0..FDS_SIZE { fds.push(-1); } //let ring = Builder::default().setup_sqpoll(50).setup_sqpoll_cpu(0).build(size as u32).expect("InitUring fail"); let ring = Builder::default().setup_sqpoll(10).build(size as u32).expect("InitUring fail"); let ret = Self { fd: ring.fd.0, eventfd: 0, fds: fds, ring: ring, }; ret.Register(IORING_REGISTER_FILES, &ret.fds[0] as * const _ as u64, ret.fds.len() as u32).expect("InitUring register files fail"); return ret; } pub fn Setup(&mut self, submission: u64, completion: u64) -> Result<i32> { self.ring.CopyTo(submission, completion); return Ok(0) } pub fn SetupEventfd(&mut self, eventfd: i32) { self.eventfd = eventfd; self.Register(IORING_REGISTER_EVENTFD, &self.eventfd as * const _ as u64, 1).expect("InitUring register eventfd fail"); } pub fn Enter(&mut self, toSumbit: u32, minComplete:u32, flags: u32) -> Result<i32> { let ret = IOUringEnter(self.fd, toSumbit, minComplete, flags); if ret < 0 { return Err(Error::SysError(-ret as i32)) } return Ok(ret as i32) } pub fn Wake(&self) -> Result<()> { let ret = IOUringEnter(self.fd, 1, 0, IORING_ENTER_SQ_WAKEUP); if ret < 0 { return Err(Error::SysError(-ret as i32)) } return Ok(()); } pub fn Register(&self, opcode: u32, arg: u64, nrArgs: u32) -> Result<()> { let ret = IOUringRegister(self.fd, opcode, arg, nrArgs); if ret < 0 { error!("IOUringRegister get fail {}", ret); return Err(Error::SysError(-ret as i32)) } return Ok(()) } pub fn UnRegisterFile(&mut self) -> Result<()> { return self.Register(IORING_UNREGISTER_FILES, 0, 0) } pub fn Addfd(&mut self, fd: i32) -> Result<()> { self.fds[fd as usize] = fd; let fu = sys::io_uring_files_update { offset : fd as u32, resv: 0, fds: self.fds[fd as usize..].as_ptr() as _, }; return self.Register(IORING_REGISTER_FILES_UPDATE, &fu as * const _ as u64, 1); } pub fn Removefd(&mut self, fd: i32) -> Result<()> { self.fds[fd as usize] = -1; let fu = sys::io_uring_files_update { offset : fd as u32, resv: 0, fds: self.fds[fd as usize..].as_ptr() as _, }; return self.Register(IORING_REGISTER_FILES_UPDATE, &fu as * const _ as u64, 1); } }
use crate::config::Config; use crate::format_arg; use log::*; use spatialos_sdk_code_generator::{generator, schema_bundle}; use std::fs::{self, File}; use std::io::prelude::*; use std::path::*; use std::process::Command; /// Performs code generation for the project described by `config`. /// /// Assumes that the current working directory is the root directory of the project, /// i.e. the directory that has the `Spatial.toml` file. pub fn run_codegen(config: &Config) -> Result<(), Box<dyn std::error::Error>> { assert!( crate::current_dir_is_root(), "Current directory should be the project root" ); // Ensure that the path to the Spatial SDK has been specified. let spatial_lib_dir = config.spatial_lib_dir() .map(PathBuf::from) .ok_or("spatial_lib_dir value must be set in the config, or the SPATIAL_LIB_DIR environment variable must be set")?; // Determine the paths the the schema compiler and protoc relative the the lib // dir path. let schema_compiler_path = spatial_lib_dir.join("schema-compiler/schema_compiler"); let std_lib_path = spatial_lib_dir.join("std-lib"); // Calculate the various output directories relative to `output_dir`. let output_dir = PathBuf::from(config.schema_build_dir()); let bundle_json_path = output_dir.join("bundle.json"); let schema_descriptor_path = output_dir.join("schema.descriptor"); // Create the output directory if it doesn't already exist. fs::create_dir_all(&output_dir) .map_err(|_| format!("Failed to create {}", output_dir.display()))?; trace!("Created schema output dir: {}", output_dir.display()); // Prepare initial flags for the schema compiler. let schema_path_arg = format_arg("schema_path", &std_lib_path); let bundle_json_arg = format_arg("bundle_json_out", &bundle_json_path); let descriptor_out_arg = format_arg("descriptor_set_out", &schema_descriptor_path); // Run the schema compiler for all schema files in the project. // // This will generated the schema descriptor file that SpatialOS loads directly, as // well as the schema bundle file that's used for code generation. All schema files // in the project are included, as well as the schema files in the standard schema // library let mut command = Command::new(&schema_compiler_path); command .arg(&schema_path_arg) .arg(&bundle_json_arg) .arg(&descriptor_out_arg) .arg("--load_all_schema_on_schema_path"); // Add all the root schema paths. for schema_path in &config.schema_paths { command.arg(&format_arg("schema_path", schema_path)); } trace!("{:#?}", command); let status = command .status() .map_err(|_| "Failed to compile schema files")?; if !status.success() { return Err("Failed to run schema compilation".into()); } // Load bundle.json, which describes the schema definitions for all components. let mut input_file = File::open(&bundle_json_path).map_err(|_| "Failed to open bundle.json")?; let mut contents = String::new(); input_file .read_to_string(&mut contents) .map_err(|_| "Failed to read contents of bundle.json")?; // Run code generation. let bundle = schema_bundle::load_bundle(&contents) .map_err(|_| "Failed to parse contents of bundle.json")?; let generated_file = generator::generate_code(bundle); // Write the generated code to the output file. File::create(&config.codegen_out) .map_err(|_| "Unable to create codegen output file")? .write_all(generated_file.as_bytes()) .map_err(|_| "Failed to write generated code to file")?; Ok(()) }
#[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::SSOP2 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct ADC_SSOP2_S0DCOPR { bits: bool, } impl ADC_SSOP2_S0DCOPR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSOP2_S0DCOPW<'a> { w: &'a mut W, } impl<'a> _ADC_SSOP2_S0DCOPW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSOP2_S1DCOPR { bits: bool, } impl ADC_SSOP2_S1DCOPR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSOP2_S1DCOPW<'a> { w: &'a mut W, } impl<'a> _ADC_SSOP2_S1DCOPW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSOP2_S2DCOPR { bits: bool, } impl ADC_SSOP2_S2DCOPR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSOP2_S2DCOPW<'a> { w: &'a mut W, } impl<'a> _ADC_SSOP2_S2DCOPW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 8); self.w.bits |= ((value as u32) & 1) << 8; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSOP2_S3DCOPR { bits: bool, } impl ADC_SSOP2_S3DCOPR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _ADC_SSOP2_S3DCOPW<'a> { w: &'a mut W, } impl<'a> _ADC_SSOP2_S3DCOPW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 12); self.w.bits |= ((value as u32) & 1) << 12; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Sample 0 Digital Comparator Operation"] #[inline(always)] pub fn adc_ssop2_s0dcop(&self) -> ADC_SSOP2_S0DCOPR { let bits = ((self.bits >> 0) & 1) != 0; ADC_SSOP2_S0DCOPR { bits } } #[doc = "Bit 4 - Sample 1 Digital Comparator Operation"] #[inline(always)] pub fn adc_ssop2_s1dcop(&self) -> ADC_SSOP2_S1DCOPR { let bits = ((self.bits >> 4) & 1) != 0; ADC_SSOP2_S1DCOPR { bits } } #[doc = "Bit 8 - Sample 2 Digital Comparator Operation"] #[inline(always)] pub fn adc_ssop2_s2dcop(&self) -> ADC_SSOP2_S2DCOPR { let bits = ((self.bits >> 8) & 1) != 0; ADC_SSOP2_S2DCOPR { bits } } #[doc = "Bit 12 - Sample 3 Digital Comparator Operation"] #[inline(always)] pub fn adc_ssop2_s3dcop(&self) -> ADC_SSOP2_S3DCOPR { let bits = ((self.bits >> 12) & 1) != 0; ADC_SSOP2_S3DCOPR { 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 - Sample 0 Digital Comparator Operation"] #[inline(always)] pub fn adc_ssop2_s0dcop(&mut self) -> _ADC_SSOP2_S0DCOPW { _ADC_SSOP2_S0DCOPW { w: self } } #[doc = "Bit 4 - Sample 1 Digital Comparator Operation"] #[inline(always)] pub fn adc_ssop2_s1dcop(&mut self) -> _ADC_SSOP2_S1DCOPW { _ADC_SSOP2_S1DCOPW { w: self } } #[doc = "Bit 8 - Sample 2 Digital Comparator Operation"] #[inline(always)] pub fn adc_ssop2_s2dcop(&mut self) -> _ADC_SSOP2_S2DCOPW { _ADC_SSOP2_S2DCOPW { w: self } } #[doc = "Bit 12 - Sample 3 Digital Comparator Operation"] #[inline(always)] pub fn adc_ssop2_s3dcop(&mut self) -> _ADC_SSOP2_S3DCOPW { _ADC_SSOP2_S3DCOPW { w: self } } }
#![allow(dead_code)] extern crate rand; #[macro_use] extern crate rand_derive; use rand::Rng; #[derive(Rand)] struct Struct { x: u16, y: Option<f64>, } #[derive(Rand)] struct Tuple(i16, Option<f64>); #[derive(Rand)] struct Unit; #[derive(Rand)] enum Enum { X { x: u8, y: isize }, Y([bool; 4]), Z, } #[test] fn smoke() { let mut rng = rand::XorShiftRng::new_unseeded(); // check nothing horrible happens internally: for _ in 0..100 { let _ = rng.gen::<Struct>(); let _ = rng.gen::<Tuple>(); let _ = rng.gen::<Unit>(); let _ = rng.gen::<Enum>(); } }
use dbus::arg::RefArg; use dbus::stdintf::org_freedesktop_dbus::PropertiesPropertiesChanged; use dbus::MessageType::Signal; use dbus::{BusType, Connection, ConnectionItem, SignalArgs}; use std::boxed::Box; use std::error::Error; use std::time::SystemTime; use std::time::Duration; use crate::cli::Cli; use dbus_common::org_bluez_adapter1::OrgBluezAdapter1; use dbus_common::org_bluez_device1::OrgFreedesktopDBusProperties; use dbus_common::utils::{SERVICE_NAME, DEVICE_INTERFACE, get_adapter}; use crate::weight_data::WeightData; static BODY_COMPOSITION_UUID: &'static str = "0000181b-0000-1000-8000-00805f9b34fb"; pub struct Scanner<'a> { connection: Connection, cli: &'a Cli, } impl<'a> Scanner<'a> { pub fn new(cli: &'a Cli) -> Result<Scanner, Box<dyn Error>> { let connection = Connection::get_private(BusType::System)?; Ok(Scanner { connection, cli }) } pub fn listen_for_signals(&self) -> Result<(), Box<dyn Error>> { self.connection .add_match(&PropertiesPropertiesChanged::match_str(None, None))?; let now = SystemTime::now(); let adapter = self .connection .with_path(SERVICE_NAME, get_adapter(&self.connection)?, 1000); let mut last_weight_data_seen = SystemTime::now(); let mut last_weight_data : Option<WeightData> = None; adapter.start_discovery()?; for n in self.connection.iter(1000) { match n { ConnectionItem::Signal(signal) => { match self.handle_signal(&signal)? { Some(weight_data) => { debug!(" got data, debouncing it"); if weight_data.weight.is_none() { debug!(" empty reading, ignoring"); } else { last_weight_data = Some(weight_data); last_weight_data_seen = SystemTime::now(); } }, None => {} } } _ => (), } if let Some(weight_data) = &last_weight_data { if weight_data.done() || last_weight_data_seen.elapsed()? > Duration::new(30,0) { debug!(" outputing weight data"); weight_data.dump()?; last_weight_data = None; if self.cli.until_data { debug!(" stopping as requested via params"); break; } } } if self.cli.duration > 0 { let elapsed = now.elapsed()?; if elapsed.as_secs() > self.cli.duration { debug!(" stopping as exceeding max duration defined via params"); break; } } } adapter.stop_discovery()?; Ok(()) } fn handle_signal(&self, signal: &dbus::Message) -> Result<Option<WeightData>, Box<dyn Error>> { let (message_type, path, interface, member) = signal.headers(); debug!("got signal message_type={:?}, path={:?}, interface={:?}, member={:?}", message_type, path, interface, member); if message_type == Signal && interface == Some("org.freedesktop.DBus.Properties".to_string()) && member == Some("PropertiesChanged".to_string()) { let items = signal.get_items(); if items[0] == dbus::MessageItem::Str(DEVICE_INTERFACE.to_string()) && path.is_some() { if let dbus::MessageItem::Array(e) = &items[1] { return self.inquiry_changed_properties(&path.unwrap(), e.to_vec()); } } } Ok(None) } fn inquiry_changed_properties( &self, path: &String, item_vec: Vec<dbus::MessageItem>, ) -> Result<Option<WeightData>, Box<dyn Error>> { let device = self.connection.with_path(SERVICE_NAME, path, 1000); let properties = device.get_all(DEVICE_INTERFACE)?; let btaddr = if let Some(btaddr) = properties.get("Address") { btaddr } else { return Ok(None) }; let name = if let Some(name) = properties.get("Name") { name } else { return Ok(None) }; let uuids = if let Some(uuids) = properties.get("UUIDs") { uuids } else { return Ok(None) }; debug!("changed properties:"); debug!(" btaddr {:?}", btaddr); debug!(" name {:?}", name); debug!(" uuids {:?}", uuids); match uuids.as_iter() { None => { debug!(" discarding - wrong type"); return Ok(None); }, Some(ref mut iter) => { if !iter.any(|a| a.as_str() == Some(BODY_COMPOSITION_UUID)) { debug!(" discarding due to missing uuid"); return Ok(None); } } } for item in item_vec { debug!(" {:?}", item); if let dbus::MessageItem::DictEntry(key, value) = item { if let Some(btaddr_str) = (*btaddr).as_str() { return self.inquiry_service_data(&key, &value, btaddr_str); } } } Ok(None) } fn inquiry_service_data_values( &self, value: &dbus::MessageItem, btaddr: &str, ) -> Result<Option<WeightData>, Box<dyn Error>> { if let dbus::MessageItem::Array(value) = value { for v in value.as_ref() { if let dbus::MessageItem::DictEntry(key, value) = v { return self.extract_body_composition(&key, &value, btaddr); } } } Ok(None) } fn inquiry_service_data( &self, key: &dbus::MessageItem, value: &dbus::MessageItem, btaddr: &str, ) -> Result<Option<WeightData>, Box<dyn Error>> { if let dbus::MessageItem::Str(key) = key { if key == "ServiceData" { debug!(" Got service data!"); if let dbus::MessageItem::Variant(value) = value { return self.inquiry_service_data_values(value, btaddr); } } } Ok(None) } fn extract_body_composition( &self, key: &dbus::MessageItem, value: &dbus::MessageItem, btaddr: &str, ) -> Result<Option<WeightData>, Box<dyn Error>> { if let dbus::MessageItem::Str(key) = key { debug!(" service-data uuid : {:?}", key); if key != BODY_COMPOSITION_UUID { return Ok(None); } if let dbus::MessageItem::Variant(value) = value { let value: &dbus::MessageItem = value; if let dbus::MessageItem::Array(value) = value { let bytes = value .as_ref() .to_vec() .into_iter() .filter_map(|x| x.inner::<u8>().ok()) .collect(); return Ok(Some(WeightData::decode(&bytes, btaddr)?)); } } } Ok(None) } }
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use borrow_check::nll::constraints::{ConstraintCategory, OutlivesConstraint}; use borrow_check::nll::type_check::{BorrowCheckContext, Locations}; use borrow_check::nll::universal_regions::UniversalRegions; use borrow_check::nll::ToRegionVid; use rustc::infer::canonical::{Canonical, CanonicalVarInfos}; use rustc::infer::{InferCtxt, NLLRegionVariableOrigin}; use rustc::traits::query::Fallible; use rustc::ty::fold::{TypeFoldable, TypeVisitor}; use rustc::ty::relate::{self, Relate, RelateResult, TypeRelation}; use rustc::ty::subst::Kind; use rustc::ty::{self, CanonicalTy, CanonicalVar, RegionVid, Ty, TyCtxt}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::indexed_vec::IndexVec; /// Adds sufficient constraints to ensure that `a <: b`. pub(super) fn sub_types<'tcx>( infcx: &InferCtxt<'_, '_, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>, locations: Locations, category: ConstraintCategory, borrowck_context: Option<&mut BorrowCheckContext<'_, 'tcx>>, ) -> Fallible<()> { debug!("sub_types(a={:?}, b={:?}, locations={:?})", a, b, locations); TypeRelating::new( infcx, ty::Variance::Covariant, locations, category, borrowck_context, ty::List::empty(), ).relate(&a, &b)?; Ok(()) } /// Adds sufficient constraints to ensure that `a == b`. pub(super) fn eq_types<'tcx>( infcx: &InferCtxt<'_, '_, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>, locations: Locations, category: ConstraintCategory, borrowck_context: Option<&mut BorrowCheckContext<'_, 'tcx>>, ) -> Fallible<()> { debug!("eq_types(a={:?}, b={:?}, locations={:?})", a, b, locations); TypeRelating::new( infcx, ty::Variance::Invariant, locations, category, borrowck_context, ty::List::empty(), ).relate(&a, &b)?; Ok(()) } /// Adds sufficient constraints to ensure that `a <: b`, where `b` is /// a user-given type (which means it may have canonical variables /// encoding things like `_`). pub(super) fn relate_type_and_user_type<'tcx>( infcx: &InferCtxt<'_, '_, 'tcx>, a: Ty<'tcx>, v: ty::Variance, b: CanonicalTy<'tcx>, locations: Locations, category: ConstraintCategory, borrowck_context: Option<&mut BorrowCheckContext<'_, 'tcx>>, ) -> Fallible<()> { debug!( "sub_type_and_user_type(a={:?}, b={:?}, locations={:?})", a, b, locations ); let Canonical { variables: b_variables, value: b_value, } = b; // The `TypeRelating` code assumes that the "canonical variables" // appear in the "a" side, so flip `Contravariant` ambient // variance to get the right relationship. let v1 = ty::Contravariant.xform(v); TypeRelating::new( infcx, v1, locations, category, borrowck_context, b_variables, ).relate(&b_value, &a)?; Ok(()) } struct TypeRelating<'cx, 'bccx: 'cx, 'gcx: 'tcx, 'tcx: 'bccx> { infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>, /// How are we relating `a` and `b`? /// /// - covariant means `a <: b` /// - contravariant means `b <: a` /// - invariant means `a == b /// - bivariant means that it doesn't matter ambient_variance: ty::Variance, /// When we pass through a set of binders (e.g., when looking into /// a `fn` type), we push a new bound region scope onto here. This /// will contain the instantiated region for each region in those /// binders. When we then encounter a `ReLateBound(d, br)`, we can /// use the debruijn index `d` to find the right scope, and then /// bound region name `br` to find the specific instantiation from /// within that scope. See `replace_bound_region`. /// /// This field stores the instantiations for late-bound regions in /// the `a` type. a_scopes: Vec<BoundRegionScope>, /// Same as `a_scopes`, but for the `b` type. b_scopes: Vec<BoundRegionScope>, /// Where (and why) is this relation taking place? locations: Locations, category: ConstraintCategory, /// This will be `Some` when we are running the type check as part /// of NLL, and `None` if we are running a "sanity check". borrowck_context: Option<&'cx mut BorrowCheckContext<'bccx, 'tcx>>, /// As we execute, the type on the LHS *may* come from a canonical /// source. In that case, we will sometimes find a constraint like /// `?0 = B`, where `B` is a type from the RHS. The first time we /// find that, we simply record `B` (and the list of scopes that /// tells us how to *interpret* `B`). The next time we encounter /// `?0`, then, we can read this value out and use it. /// /// One problem: these variables may be in some other universe, /// how can we enforce that? I guess I could add some kind of /// "minimum universe constraint" that we can feed to the NLL checker. /// --> also, we know this doesn't happen canonical_var_values: IndexVec<CanonicalVar, Option<Kind<'tcx>>>, } #[derive(Clone, Debug)] struct ScopesAndKind<'tcx> { scopes: Vec<BoundRegionScope>, kind: Kind<'tcx>, } #[derive(Clone, Debug, Default)] struct BoundRegionScope { map: FxHashMap<ty::BoundRegion, RegionVid>, } #[derive(Copy, Clone)] struct UniversallyQuantified(bool); impl<'cx, 'bccx, 'gcx, 'tcx> TypeRelating<'cx, 'bccx, 'gcx, 'tcx> { fn new( infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>, ambient_variance: ty::Variance, locations: Locations, category: ConstraintCategory, borrowck_context: Option<&'cx mut BorrowCheckContext<'bccx, 'tcx>>, canonical_var_infos: CanonicalVarInfos<'tcx>, ) -> Self { let canonical_var_values = IndexVec::from_elem_n(None, canonical_var_infos.len()); Self { infcx, ambient_variance, borrowck_context, locations, canonical_var_values, category, a_scopes: vec![], b_scopes: vec![], } } fn ambient_covariance(&self) -> bool { match self.ambient_variance { ty::Variance::Covariant | ty::Variance::Invariant => true, ty::Variance::Contravariant | ty::Variance::Bivariant => false, } } fn ambient_contravariance(&self) -> bool { match self.ambient_variance { ty::Variance::Contravariant | ty::Variance::Invariant => true, ty::Variance::Covariant | ty::Variance::Bivariant => false, } } fn create_scope( &mut self, value: &ty::Binder<impl TypeFoldable<'tcx>>, universally_quantified: UniversallyQuantified, ) -> BoundRegionScope { let mut scope = BoundRegionScope::default(); value.skip_binder().visit_with(&mut ScopeInstantiator { infcx: self.infcx, target_index: ty::INNERMOST, universally_quantified, bound_region_scope: &mut scope, }); scope } /// When we encounter binders during the type traversal, we record /// the value to substitute for each of the things contained in /// that binder. (This will be either a universal placeholder or /// an existential inference variable.) Given the debruijn index /// `debruijn` (and name `br`) of some binder we have now /// encountered, this routine finds the value that we instantiated /// the region with; to do so, it indexes backwards into the list /// of ambient scopes `scopes`. fn lookup_bound_region( debruijn: ty::DebruijnIndex, br: &ty::BoundRegion, first_free_index: ty::DebruijnIndex, scopes: &[BoundRegionScope], ) -> RegionVid { // The debruijn index is a "reverse index" into the // scopes listing. So when we have INNERMOST (0), we // want the *last* scope pushed, and so forth. let debruijn_index = debruijn.index() - first_free_index.index(); let scope = &scopes[scopes.len() - debruijn_index - 1]; // Find this bound region in that scope to map to a // particular region. scope.map[br] } /// If `r` is a bound region, find the scope in which it is bound /// (from `scopes`) and return the value that we instantiated it /// with. Otherwise just return `r`. fn replace_bound_region( &self, universal_regions: &UniversalRegions<'tcx>, r: ty::Region<'tcx>, first_free_index: ty::DebruijnIndex, scopes: &[BoundRegionScope], ) -> RegionVid { match r { ty::ReLateBound(debruijn, br) => { Self::lookup_bound_region(*debruijn, br, first_free_index, scopes) } ty::ReVar(v) => *v, _ => universal_regions.to_region_vid(r), } } /// Push a new outlives requirement into our output set of /// constraints. fn push_outlives(&mut self, sup: RegionVid, sub: RegionVid) { debug!("push_outlives({:?}: {:?})", sup, sub); if let Some(borrowck_context) = &mut self.borrowck_context { borrowck_context .constraints .outlives_constraints .push(OutlivesConstraint { sup, sub, locations: self.locations, category: self.category, }); // FIXME all facts! } } /// When we encounter a canonical variable `var` in the output, /// equate it with `kind`. If the variable has been previously /// equated, then equate it again. fn relate_var( &mut self, var: CanonicalVar, b_kind: Kind<'tcx>, ) -> RelateResult<'tcx, Kind<'tcx>> { debug!("equate_var(var={:?}, b_kind={:?})", var, b_kind); let generalized_kind = match self.canonical_var_values[var] { Some(v) => v, None => { let generalized_kind = self.generalize_value(b_kind); self.canonical_var_values[var] = Some(generalized_kind); generalized_kind } }; // The generalized values we extract from `canonical_var_values` have // been fully instantiated and hence the set of scopes we have // doesn't matter -- just to be sure, put an empty vector // in there. let old_a_scopes = ::std::mem::replace(&mut self.a_scopes, vec![]); // Relate the generalized kind to the original one. let result = self.relate(&generalized_kind, &b_kind); // Restore the old scopes now. self.a_scopes = old_a_scopes; debug!("equate_var: complete, result = {:?}", result); return result; } fn generalize_value( &self, kind: Kind<'tcx>, ) -> Kind<'tcx> { TypeGeneralizer { type_rel: self, first_free_index: ty::INNERMOST, ambient_variance: self.ambient_variance, // These always correspond to an `_` or `'_` written by // user, and those are always in the root universe. universe: ty::UniverseIndex::ROOT, }.relate(&kind, &kind) .unwrap() } } impl<'cx, 'bccx, 'gcx, 'tcx> TypeRelation<'cx, 'gcx, 'tcx> for TypeRelating<'cx, 'bccx, 'gcx, 'tcx> { fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> { self.infcx.tcx } fn tag(&self) -> &'static str { "nll::subtype" } fn a_is_expected(&self) -> bool { true } fn relate_with_variance<T: Relate<'tcx>>( &mut self, variance: ty::Variance, a: &T, b: &T, ) -> RelateResult<'tcx, T> { debug!( "relate_with_variance(variance={:?}, a={:?}, b={:?})", variance, a, b ); let old_ambient_variance = self.ambient_variance; self.ambient_variance = self.ambient_variance.xform(variance); debug!( "relate_with_variance: ambient_variance = {:?}", self.ambient_variance ); let r = self.relate(a, b)?; self.ambient_variance = old_ambient_variance; debug!("relate_with_variance: r={:?}", r); Ok(r) } fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { // Watch out for the case that we are matching a `?T` against the // right-hand side. if let ty::Infer(ty::CanonicalTy(var)) = a.sty { self.relate_var(var, b.into())?; Ok(a) } else { debug!( "tys(a={:?}, b={:?}, variance={:?})", a, b, self.ambient_variance ); relate::super_relate_tys(self, a, b) } } fn regions( &mut self, a: ty::Region<'tcx>, b: ty::Region<'tcx>, ) -> RelateResult<'tcx, ty::Region<'tcx>> { if let Some(&mut BorrowCheckContext { universal_regions, .. }) = self.borrowck_context { if let ty::ReCanonical(var) = a { self.relate_var(*var, b.into())?; return Ok(a); } debug!( "regions(a={:?}, b={:?}, variance={:?})", a, b, self.ambient_variance ); let v_a = self.replace_bound_region(universal_regions, a, ty::INNERMOST, &self.a_scopes); let v_b = self.replace_bound_region(universal_regions, b, ty::INNERMOST, &self.b_scopes); debug!("regions: v_a = {:?}", v_a); debug!("regions: v_b = {:?}", v_b); if self.ambient_covariance() { // Covariance: a <= b. Hence, `b: a`. self.push_outlives(v_b, v_a); } if self.ambient_contravariance() { // Contravariant: b <= a. Hence, `a: b`. self.push_outlives(v_a, v_b); } } Ok(a) } fn binders<T>( &mut self, a: &ty::Binder<T>, b: &ty::Binder<T>, ) -> RelateResult<'tcx, ty::Binder<T>> where T: Relate<'tcx>, { // We want that // // ``` // for<'a> fn(&'a u32) -> &'a u32 <: // fn(&'b u32) -> &'b u32 // ``` // // but not // // ``` // fn(&'a u32) -> &'a u32 <: // for<'b> fn(&'b u32) -> &'b u32 // ``` // // We therefore proceed as follows: // // - Instantiate binders on `b` universally, yielding a universe U1. // - Instantiate binders on `a` existentially in U1. debug!( "binders({:?}: {:?}, ambient_variance={:?})", a, b, self.ambient_variance ); if self.ambient_covariance() { // Covariance, so we want `for<..> A <: for<..> B` -- // therefore we compare any instantiation of A (i.e., A // instantiated with existentials) against every // instantiation of B (i.e., B instantiated with // universals). let b_scope = self.create_scope(b, UniversallyQuantified(true)); let a_scope = self.create_scope(a, UniversallyQuantified(false)); debug!("binders: a_scope = {:?} (existential)", a_scope); debug!("binders: b_scope = {:?} (universal)", b_scope); self.b_scopes.push(b_scope); self.a_scopes.push(a_scope); // Reset the ambient variance to covariant. This is needed // to correctly handle cases like // // for<'a> fn(&'a u32, &'a u3) == for<'b, 'c> fn(&'b u32, &'c u32) // // Somewhat surprisingly, these two types are actually // **equal**, even though the one on the right looks more // polymorphic. The reason is due to subtyping. To see it, // consider that each function can call the other: // // - The left function can call the right with `'b` and // `'c` both equal to `'a` // // - The right function can call the left with `'a` set to // `{P}`, where P is the point in the CFG where the call // itself occurs. Note that `'b` and `'c` must both // include P. At the point, the call works because of // subtyping (i.e., `&'b u32 <: &{P} u32`). let variance = ::std::mem::replace(&mut self.ambient_variance, ty::Variance::Covariant); self.relate(a.skip_binder(), b.skip_binder())?; self.ambient_variance = variance; self.b_scopes.pop().unwrap(); self.a_scopes.pop().unwrap(); } if self.ambient_contravariance() { // Contravariance, so we want `for<..> A :> for<..> B` // -- therefore we compare every instantiation of A (i.e., // A instantiated with universals) against any // instantiation of B (i.e., B instantiated with // existentials). Opposite of above. let a_scope = self.create_scope(a, UniversallyQuantified(true)); let b_scope = self.create_scope(b, UniversallyQuantified(false)); debug!("binders: a_scope = {:?} (universal)", a_scope); debug!("binders: b_scope = {:?} (existential)", b_scope); self.a_scopes.push(a_scope); self.b_scopes.push(b_scope); // Reset ambient variance to contravariance. See the // covariant case above for an explanation. let variance = ::std::mem::replace( &mut self.ambient_variance, ty::Variance::Contravariant, ); self.relate(a.skip_binder(), b.skip_binder())?; self.ambient_variance = variance; self.b_scopes.pop().unwrap(); self.a_scopes.pop().unwrap(); } Ok(a.clone()) } } /// When we encounter a binder like `for<..> fn(..)`, we actually have /// to walk the `fn` value to find all the values bound by the `for` /// (these are not explicitly present in the ty representation right /// now). This visitor handles that: it descends the type, tracking /// binder depth, and finds late-bound regions targeting the /// `for<..`>. For each of those, it creates an entry in /// `bound_region_scope`. struct ScopeInstantiator<'cx, 'gcx: 'tcx, 'tcx: 'cx> { infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>, // The debruijn index of the scope we are instantiating. target_index: ty::DebruijnIndex, universally_quantified: UniversallyQuantified, bound_region_scope: &'cx mut BoundRegionScope, } impl<'cx, 'gcx, 'tcx> TypeVisitor<'tcx> for ScopeInstantiator<'cx, 'gcx, 'tcx> { fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool { self.target_index.shift_in(1); t.super_visit_with(self); self.target_index.shift_out(1); false } fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool { let ScopeInstantiator { infcx, universally_quantified, .. } = *self; match r { ty::ReLateBound(debruijn, br) if *debruijn == self.target_index => { self.bound_region_scope.map.entry(*br).or_insert_with(|| { let origin = if universally_quantified.0 { NLLRegionVariableOrigin::BoundRegion(infcx.create_subuniverse()) } else { NLLRegionVariableOrigin::Existential }; infcx.next_nll_region_var(origin).to_region_vid() }); } _ => {} } false } } /// The "type generalize" is used when handling inference variables. /// /// The basic strategy for handling a constraint like `?A <: B` is to /// apply a "generalization strategy" to the type `B` -- this replaces /// all the lifetimes in the type `B` with fresh inference /// variables. (You can read more about the strategy in this [blog /// post].) /// /// As an example, if we had `?A <: &'x u32`, we would generalize `&'x /// u32` to `&'0 u32` where `'0` is a fresh variable. This becomes the /// value of `A`. Finally, we relate `&'0 u32 <: &'x u32`, which /// establishes `'0: 'x` as a constraint. /// /// As a side-effect of this generalization procedure, we also replace /// all the bound regions that we have traversed with concrete values, /// so that the resulting generalized type is independent from the /// scopes. /// /// [blog post]: https://is.gd/0hKvIr struct TypeGeneralizer<'me, 'bccx: 'me, 'gcx: 'tcx, 'tcx: 'bccx> { type_rel: &'me TypeRelating<'me, 'bccx, 'gcx, 'tcx>, /// After we generalize this type, we are going to relative it to /// some other type. What will be the variance at this point? ambient_variance: ty::Variance, first_free_index: ty::DebruijnIndex, universe: ty::UniverseIndex, } impl TypeRelation<'me, 'gcx, 'tcx> for TypeGeneralizer<'me, 'bbcx, 'gcx, 'tcx> { fn tcx(&self) -> TyCtxt<'me, 'gcx, 'tcx> { self.type_rel.infcx.tcx } fn tag(&self) -> &'static str { "nll::generalizer" } fn a_is_expected(&self) -> bool { true } fn relate_with_variance<T: Relate<'tcx>>( &mut self, variance: ty::Variance, a: &T, b: &T, ) -> RelateResult<'tcx, T> { debug!( "TypeGeneralizer::relate_with_variance(variance={:?}, a={:?}, b={:?})", variance, a, b ); let old_ambient_variance = self.ambient_variance; self.ambient_variance = self.ambient_variance.xform(variance); debug!( "TypeGeneralizer::relate_with_variance: ambient_variance = {:?}", self.ambient_variance ); let r = self.relate(a, b)?; self.ambient_variance = old_ambient_variance; debug!("TypeGeneralizer::relate_with_variance: r={:?}", r); Ok(r) } fn tys(&mut self, a: Ty<'tcx>, _: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { debug!("TypeGeneralizer::tys(a={:?})", a,); match a.sty { ty::Infer(ty::TyVar(_)) | ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) => { bug!( "unexpected inference variable encountered in NLL generalization: {:?}", a ); } _ => relate::super_relate_tys(self, a, a), } } fn regions( &mut self, a: ty::Region<'tcx>, _: ty::Region<'tcx>, ) -> RelateResult<'tcx, ty::Region<'tcx>> { debug!("TypeGeneralizer::regions(a={:?})", a,); if let ty::ReLateBound(debruijn, _) = a { if *debruijn < self.first_free_index { return Ok(a); } } // For now, we just always create a fresh region variable to // replace all the regions in the source type. In the main // type checker, we special case the case where the ambient // variance is `Invariant` and try to avoid creating a fresh // region variable, but since this comes up so much less in // NLL (only when users use `_` etc) it is much less // important. // // As an aside, since these new variables are created in // `self.universe` universe, this also serves to enforce the // universe scoping rules. // // FIXME(#54105) -- if the ambient variance is bivariant, // though, we may however need to check well-formedness or // risk a problem like #41677 again. let replacement_region_vid = self.type_rel .infcx .next_nll_region_var_in_universe(NLLRegionVariableOrigin::Existential, self.universe); Ok(replacement_region_vid) } fn binders<T>( &mut self, a: &ty::Binder<T>, _: &ty::Binder<T>, ) -> RelateResult<'tcx, ty::Binder<T>> where T: Relate<'tcx>, { debug!("TypeGeneralizer::binders(a={:?})", a,); self.first_free_index.shift_in(1); let result = self.relate(a.skip_binder(), a.skip_binder())?; self.first_free_index.shift_out(1); Ok(ty::Binder::bind(result)) } }
use crate::ast::*; use diagnostics::{FileId, Reporter, Span}; use parser::error::Result; use parser::literal::IntLiteral; use parser::parse::ParseStream; parser::token![punct "+" TAdd/1]; parser::token![punct "-" TSub/1]; parser::token![punct "*" TMul/1]; parser::token![punct "/" TDiv/1]; parser::token![punct "(" TLParen/1]; parser::token![punct ")" TRParen/1]; pub fn parse(reporter: &Reporter, file: FileId) -> Result<Ast> { let mut lexer = parser::lexer::Lexer::new(&file.source, file, reporter); let tokens = lexer.run(); let buffer = parser::parse::ParseBuffer::new(tokens.begin(), reporter, (), Span::empty(file)); Ast::parse_add_sub(&buffer) } impl Ast { fn parse_add_sub(input: ParseStream) -> Result<Self> { let start = input.span(); let mut result = Self::parse_mul_div(input)?; while !input.is_empty() && (input.peek::<TAdd>() || input.peek::<TSub>()) { if let Ok(_) = input.parse::<TAdd>() { let right = Self::parse_mul_div(input)?; result = Self::Op { span: start.to(input.prev_span()), op: Op::Add, left: Box::new(result), right: Box::new(right), }; } else { input.parse::<TSub>()?; let right = Self::parse_int(input)?; result = Self::Op { span: start.to(input.prev_span()), op: Op::Sub, left: Box::new(result), right: Box::new(right), }; } } Ok(result) } fn parse_mul_div(input: ParseStream) -> Result<Self> { let start = input.span(); let mut result = Self::parse_int(input)?; while !input.is_empty() && (input.peek::<TMul>() || input.peek::<TDiv>()) { if let Ok(_) = input.parse::<TMul>() { let right = Self::parse_int(input)?; result = Self::Op { span: start.to(input.prev_span()), op: Op::Mul, left: Box::new(result), right: Box::new(right), }; } else { input.parse::<TDiv>()?; let right = Self::parse_int(input)?; result = Self::Op { span: start.to(input.prev_span()), op: Op::Div, left: Box::new(result), right: Box::new(right), }; } } Ok(result) } fn parse_int(input: ParseStream) -> Result<Self> { if let Ok(lparen) = input.parse::<TLParen>() { let sub = Self::parse_add_sub(input)?; input.parse::<TRParen>()?; Ok(Self::Group { span: lparen.span.to(input.prev_span()), expr: Box::new(sub), }) } else { let lit = input.parse::<IntLiteral>()?; Ok(Self::Int { span: lit.span, val: lit.int as u64, }) } } }
use super::{PathComponent, PathIter, Value}; use std::{cmp::Ordering, collections::BTreeMap, iter::Peekable, mem}; /// Removes field value specified by the given path and return its value. /// /// A special case worth mentioning: if there is a nested array and an item is removed /// from the middle of this array, then it is just replaced by `Value::Null`. pub fn remove(fields: &mut BTreeMap<String, Value>, path: &str, prune: bool) -> Option<Value> { remove_map(fields, PathIter::new(path).peekable(), prune).map(|(value, _)| value) } /// Recursively iterate through the path, and remove the last path /// element. This is the top-level function which can remove from any /// type of `Value`. fn remove_rec(value: &mut Value, path: Peekable<PathIter>, prune: bool) -> Option<(Value, bool)> { match value { Value::Map(map) => remove_map(map, path, prune), Value::Array(map) => remove_array(map, path, prune), _ => None, } } fn remove_array( array: &mut Vec<Value>, mut path: Peekable<PathIter>, prune: bool, ) -> Option<(Value, bool)> { match path.next()? { PathComponent::Index(index) => match path.peek() { None => array_remove(array, index).map(|v| (v, false)), Some(_) => array .get_mut(index) .and_then(|value| Some((remove_rec(value, path, prune)?.0, false))), }, _ => None, } } fn remove_map( fields: &mut BTreeMap<String, Value>, mut path: Peekable<PathIter>, prune: bool, ) -> Option<(Value, bool)> { match path.next()? { PathComponent::Key(key) => match path.peek() { None => fields.remove(&key).map(|v| (v, fields.is_empty())), Some(_) => { let (result, empty) = fields .get_mut(&key) .and_then(|value| remove_rec(value, path, prune))?; if prune && empty { fields.remove(&key); } Some((result, fields.is_empty())) } }, _ => None, } } fn array_remove(values: &mut Vec<Value>, index: usize) -> Option<Value> { match (index + 1).cmp(&values.len()) { Ordering::Less => Some(mem::replace(&mut values[index], Value::Null)), Ordering::Equal => values.pop(), Ordering::Greater => None, } } #[cfg(test)] mod test { use super::super::test::fields_from_json; use super::*; use serde_json::json; #[test] fn array_remove_from_middle() { let mut array = vec![Value::Null, Value::Integer(3)]; assert_eq!(array_remove(&mut array, 0), Some(Value::Null)); assert_eq!(array_remove(&mut array, 0), Some(Value::Null)); assert_eq!(array_remove(&mut array, 1), Some(Value::Integer(3))); assert_eq!(array_remove(&mut array, 1), None); assert_eq!(array_remove(&mut array, 0), Some(Value::Null)); assert_eq!(array_remove(&mut array, 0), None); } #[test] fn remove_simple() { let mut fields = fields_from_json(json!({ "field": 123 })); assert_eq!( remove(&mut fields, "field", false), Some(Value::Integer(123)) ); assert_eq!(remove(&mut fields, "field", false), None); } #[test] fn remove_nested() { let mut fields = fields_from_json(json!({ "a": { "b": { "c": 5 }, "d": 4, "array": [null, 3, { "x": 1 }, [2]] } })); let queries = [ ("a.b.c", Some(Value::Integer(5)), None), ("a.d", Some(Value::Integer(4)), None), ("a.array[1]", Some(Value::Integer(3)), Some(Value::Null)), ("a.array[2].x", Some(Value::Integer(1)), None), ("a.array[3][0]", Some(Value::Integer(2)), None), ("a.array[3][1]", None, None), ("a.x", None, None), ("z", None, None), (".123", None, None), ("", None, None), ]; for (query, expected_first, expected_second) in queries.iter() { assert_eq!( remove(&mut fields, query, false), *expected_first, "{}", query ); assert_eq!( remove(&mut fields, query, false), *expected_second, "{}", query ); } assert_eq!( fields, fields_from_json(json!({ "a": { "b": {}, "array": [ null, null, {}, [], ], }, })) ); } #[test] fn remove_prune() { let mut fields = fields_from_json(json!({ "a": { "b": { "c": 5 }, "d": 4, } })); assert_eq!(remove(&mut fields, "a.d", true), Some(Value::Integer(4))); assert_eq!( fields, fields_from_json(json!({ "a": { "b": { "c": 5 } } })) ); assert_eq!(remove(&mut fields, "a.b.c", true), Some(Value::Integer(5))); assert_eq!(fields, fields_from_json(json!({}))); } }
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // Test that `<Type as Trait>::Output` and `Self::Output` are accepted as type annotations in let // bindings // pretty-expanded FIXME #23616 trait Int { fn one() -> Self; fn leading_zeros(self) -> usize; } trait Foo { type T : Int; fn test(&self) { let r: <Self as Foo>::T = Int::one(); let r: Self::T = Int::one(); } } fn main() {}
use std::fmt::Debug; use std::str::FromStr; #[allow(dead_code)] #[allow(deprecated)] fn read_line_from_stdin() -> String { let mut buffer = String::new(); std::io::stdin().read_line(&mut buffer).unwrap(); buffer.trim_right().to_owned() } #[allow(dead_code)] #[allow(deprecated)] fn parse_line_to_single<T>() -> T where T: FromStr, T::Err: Debug, { let mut buffer = String::new(); std::io::stdin().read_line(&mut buffer).unwrap(); T::from_str(buffer.trim_right()).unwrap() } #[allow(dead_code)] #[allow(deprecated)] fn parse_line_to_multiple<T>() -> Vec<T> where T: FromStr, T::Err: Debug, { let mut buffer = String::new(); std::io::stdin().read_line(&mut buffer).unwrap(); buffer .trim_right() .split_whitespace() .flat_map(|s| T::from_str(s)) .collect() } #[allow(unused_macros)] macro_rules! parse_line { [$( $x:tt : $t:ty ),+] => { //declare variables $( let $x: $t; )+ { use std::str::FromStr; // read let mut buf = String::new(); std::io::stdin().read_line(&mut buf).unwrap(); #[allow(deprecated)] let mut splits = buf.trim_right().split_whitespace(); // assign each variable $( $x = splits.next().and_then(|s| <$t>::from_str(s).ok()).unwrap(); )+ // all strs should be used for assignment assert!(splits.next().is_none()); } }; } fn main() {}
#[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::_0_FLTSEN { #[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 PWM_0_FLTSEN_FAULT0R { bits: bool, } impl PWM_0_FLTSEN_FAULT0R { #[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 _PWM_0_FLTSEN_FAULT0W<'a> { w: &'a mut W, } impl<'a> _PWM_0_FLTSEN_FAULT0W<'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 PWM_0_FLTSEN_FAULT1R { bits: bool, } impl PWM_0_FLTSEN_FAULT1R { #[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 _PWM_0_FLTSEN_FAULT1W<'a> { w: &'a mut W, } impl<'a> _PWM_0_FLTSEN_FAULT1W<'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 PWM_0_FLTSEN_FAULT2R { bits: bool, } impl PWM_0_FLTSEN_FAULT2R { #[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 _PWM_0_FLTSEN_FAULT2W<'a> { w: &'a mut W, } impl<'a> _PWM_0_FLTSEN_FAULT2W<'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 PWM_0_FLTSEN_FAULT3R { bits: bool, } impl PWM_0_FLTSEN_FAULT3R { #[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 _PWM_0_FLTSEN_FAULT3W<'a> { w: &'a mut W, } impl<'a> _PWM_0_FLTSEN_FAULT3W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Fault0 Sense"] #[inline(always)] pub fn pwm_0_fltsen_fault0(&self) -> PWM_0_FLTSEN_FAULT0R { let bits = ((self.bits >> 0) & 1) != 0; PWM_0_FLTSEN_FAULT0R { bits } } #[doc = "Bit 1 - Fault1 Sense"] #[inline(always)] pub fn pwm_0_fltsen_fault1(&self) -> PWM_0_FLTSEN_FAULT1R { let bits = ((self.bits >> 1) & 1) != 0; PWM_0_FLTSEN_FAULT1R { bits } } #[doc = "Bit 2 - Fault2 Sense"] #[inline(always)] pub fn pwm_0_fltsen_fault2(&self) -> PWM_0_FLTSEN_FAULT2R { let bits = ((self.bits >> 2) & 1) != 0; PWM_0_FLTSEN_FAULT2R { bits } } #[doc = "Bit 3 - Fault3 Sense"] #[inline(always)] pub fn pwm_0_fltsen_fault3(&self) -> PWM_0_FLTSEN_FAULT3R { let bits = ((self.bits >> 3) & 1) != 0; PWM_0_FLTSEN_FAULT3R { 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 - Fault0 Sense"] #[inline(always)] pub fn pwm_0_fltsen_fault0(&mut self) -> _PWM_0_FLTSEN_FAULT0W { _PWM_0_FLTSEN_FAULT0W { w: self } } #[doc = "Bit 1 - Fault1 Sense"] #[inline(always)] pub fn pwm_0_fltsen_fault1(&mut self) -> _PWM_0_FLTSEN_FAULT1W { _PWM_0_FLTSEN_FAULT1W { w: self } } #[doc = "Bit 2 - Fault2 Sense"] #[inline(always)] pub fn pwm_0_fltsen_fault2(&mut self) -> _PWM_0_FLTSEN_FAULT2W { _PWM_0_FLTSEN_FAULT2W { w: self } } #[doc = "Bit 3 - Fault3 Sense"] #[inline(always)] pub fn pwm_0_fltsen_fault3(&mut self) -> _PWM_0_FLTSEN_FAULT3W { _PWM_0_FLTSEN_FAULT3W { w: self } } }
// NOTE: those are only the base addresses of the registers. According to the required quantity, // as many values as needed are fetched. See `Format` and `Register::format`. //! Register numbers and other constants. //! # Note about register numbers //! The constants in this module only point to the first register of a particular category. //! //! The others are automatically determined according to the quantity of the specific register //! and - if applicable - the line. //! For example, `REGISTER_VOLTAGE_L1` is `28` and its `quantity` is `2`, as such the relevant //! register numbers are `28` and `29`. The register which contains `L2` immediately follows, and //! has id `30`. The general formula is `base_no + 2 * (line_no - 1)`. //! //! For `base_no` = `28` and `line_no` = `2`, `register_no` = `28 + 2 * 1` = `30`. /// Line-agnostic register which contains the input voltage. pub const REGISTER_VOLTAGE: u8 = 0; /// Register which contains the input voltage for L1. pub const REGISTER_VOLTAGE_L1: u8 = 28; /// Line-agnostic register which contains the current. pub const REGISTER_CURRENT: u8 = 2; /// Register which contains the current for L1. pub const REGISTER_CURRENT_L1: u8 = 34; /// Line-agnostic register which contains the power. pub const REGISTER_POWER: u8 = 4; /// Register which contains the power for L1. pub const REGISTER_POWER_L1: u8 = 40; /// Line-agnostic register which contains the power factor. pub const REGISTER_POWER_FACTOR: u8 = 10; /// Line-agnostic register which contains the active energy. pub const REGISTER_ACTIVE_ENERGY: u8 = 20; /// Line-agnostic register which contains the reactive energy. pub const REGISTER_REACTIVE_ENERGY: u8 = 23;
use bulletproofs::r1cs::ConstraintSystem; use error::SpacesuitError; use gadgets::{merge, padded_shuffle, range_proof, split, value_shuffle}; use std::cmp::max; use value::AllocatedValue; /// Enforces that the outputs are a valid rearrangement of the inputs, following the /// soundness and secrecy requirements in the spacesuit transaction spec: /// https://github.com/interstellar/spacesuit/blob/master/spec.md pub fn fill_cs<CS: ConstraintSystem>( cs: &mut CS, inputs: Vec<AllocatedValue>, merge_in: Vec<AllocatedValue>, merge_mid: Vec<AllocatedValue>, merge_out: Vec<AllocatedValue>, split_in: Vec<AllocatedValue>, split_mid: Vec<AllocatedValue>, split_out: Vec<AllocatedValue>, outputs: Vec<AllocatedValue>, ) -> Result<(), SpacesuitError> { let m = inputs.len(); let n = outputs.len(); let inner_merge_count = max(m, 2) - 2; // max(m - 2, 0) let inner_split_count = max(n, 2) - 2; // max(n - 2, 0) if inputs.len() != merge_in.len() || merge_in.len() != merge_out.len() || split_in.len() != split_out.len() || split_out.len() != outputs.len() || merge_mid.len() != inner_merge_count || split_mid.len() != inner_split_count { return Err(SpacesuitError::InvalidR1CSConstruction); } // Shuffle 1 // Check that `merge_in` is a valid reordering of `inputs` // when `inputs` are grouped by flavor. value_shuffle::fill_cs(cs, inputs, merge_in.clone())?; // Merge // Check that `merge_out` is a valid combination of `merge_in`, // when all values of the same flavor in `merge_in` are combined. merge::fill_cs(cs, merge_in, merge_mid, merge_out.clone())?; // Shuffle 2 // Check that `split_in` is a valid reordering of `merge_out`, allowing for // the adding or dropping of padding values (quantity = 0) if m != n. padded_shuffle::fill_cs(cs, merge_out, split_in.clone())?; // Split // Check that `split_in` is a valid combination of `split_out`, // when all values of the same flavor in `split_out` are combined. split::fill_cs(cs, split_in, split_mid, split_out.clone())?; // Shuffle 3 // Check that `split_out` is a valid reordering of `outputs` // when `outputs` are grouped by flavor. value_shuffle::fill_cs(cs, split_out, outputs.clone())?; // Range Proof // Check that each of the quantities in `outputs` lies in [0, 2^64). for output in outputs { range_proof::fill_cs(cs, output.quantity(), 64)?; } Ok(()) }
//! Adapter for gfx-hal use hal::{self, Device as HalDevice}; use std::{borrow::Borrow, marker::PhantomData, ops::Range, ptr::NonNull}; use device::Device; use error::*; use heaps::*; use memory::*; use util::*; impl From<hal::device::OutOfMemory> for OutOfMemoryError { fn from(_: hal::device::OutOfMemory) -> OutOfMemoryError { OutOfMemoryError::OutOfDeviceMemory } } impl From<hal::device::OutOfMemory> for MappingError { fn from(_: hal::device::OutOfMemory) -> MappingError { OutOfMemoryError::OutOfDeviceMemory.into() } } impl From<hal::device::OutOfMemory> for AllocationError { fn from(_: hal::device::OutOfMemory) -> AllocationError { OutOfMemoryError::OutOfDeviceMemory.into() } } impl From<hal::device::OutOfMemory> for MemoryError { fn from(_: hal::device::OutOfMemory) -> MemoryError { OutOfMemoryError::OutOfDeviceMemory.into() } } impl From<hal::mapping::Error> for MappingError { fn from(error: hal::mapping::Error) -> MappingError { match error { hal::mapping::Error::InvalidAccess => MappingError::HostInvisible, hal::mapping::Error::OutOfBounds => MappingError::OutOfBounds, hal::mapping::Error::OutOfMemory => OutOfMemoryError::OutOfHostMemory.into(), } } } impl From<hal::mapping::Error> for MemoryError { fn from(error: hal::mapping::Error) -> MemoryError { match error { hal::mapping::Error::InvalidAccess => MappingError::HostInvisible.into(), hal::mapping::Error::OutOfBounds => MappingError::OutOfBounds.into(), hal::mapping::Error::OutOfMemory => OutOfMemoryError::OutOfHostMemory.into(), } } } impl From<hal::memory::Properties> for Properties { fn from(value: hal::memory::Properties) -> Self { let mut result = Properties::empty(); if value.contains(hal::memory::Properties::DEVICE_LOCAL) { result |= Properties::DEVICE_LOCAL; } if value.contains(hal::memory::Properties::COHERENT) { result |= Properties::HOST_COHERENT; } if value.contains(hal::memory::Properties::CPU_CACHED) { result |= Properties::HOST_CACHED; } if value.contains(hal::memory::Properties::CPU_VISIBLE) { result |= Properties::HOST_VISIBLE; } if value.contains(hal::memory::Properties::LAZILY_ALLOCATED) { result |= Properties::LAZILY_ALLOCATED; } result } } impl<D, B> Device for (D, PhantomData<B>) where B: hal::Backend, D: Borrow<B::Device>, { type Memory = B::Memory; unsafe fn allocate(&self, index: u32, size: u64) -> Result<B::Memory, AllocationError> { assert!( fits_usize(index), "Numbers of memory types can't exceed usize limit" ); let index = index as usize; Ok(self .0 .borrow() .allocate_memory(hal::MemoryTypeId(index), size)?) } unsafe fn free(&self, memory: B::Memory) { self.0.borrow().free_memory(memory) } unsafe fn map( &self, memory: &B::Memory, range: Range<u64>, ) -> Result<NonNull<u8>, MappingError> { let ptr = self.0.borrow().map_memory(memory, range)?; debug_assert!(!ptr.is_null()); Ok(NonNull::new_unchecked(ptr)) } unsafe fn unmap(&self, memory: &B::Memory) { self.0.borrow().unmap_memory(memory) } unsafe fn invalidate<'a>( &self, regions: impl IntoIterator<Item = (&'a B::Memory, Range<u64>)>, ) -> Result<(), OutOfMemoryError> { self.0.borrow().invalidate_mapped_memory_ranges(regions); Ok(()) } unsafe fn flush<'a>( &self, regions: impl IntoIterator<Item = (&'a B::Memory, Range<u64>)>, ) -> Result<(), OutOfMemoryError> { self.0.borrow().flush_mapped_memory_ranges(regions); Ok(()) } } /// Fetch data necessary from `Backend::PhysicalDevice` #[allow(unused)] unsafe fn heaps_from_physical_device<B>( physical: &B::PhysicalDevice, config: Config, ) -> Heaps<B::Memory> where B: hal::Backend, { let memory_properties = ::hal::PhysicalDevice::memory_properties(physical); Heaps::new( memory_properties .memory_types .into_iter() .map(|mt| (mt.properties.into(), mt.heap_index as u32, config)), memory_properties.memory_heaps, ) }
use ansi_term::Colour::{self, Blue, Cyan, Green, Purple, Red, White, Yellow, RGB}; use rand::{ distributions::{Distribution, Standard}, Rng, }; #[allow(non_upper_case_globals)] const Orange: Colour = RGB(255, 165, 0); #[derive(Debug, PartialEq, Clone, Hash, Eq)] pub enum Color { Red, Green, Blue, Purple, Orange, Yellow, White, Cyan, } impl Distribution<Color> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Color { match rng.gen_range(0..=7) { 0 => Color::Red, 1 => Color::Green, 2 => Color::Blue, 3 => Color::Purple, 4 => Color::Orange, 5 => Color::Yellow, 6 => Color::White, _ => Color::Cyan, } } } pub struct MasterMindResponse { pub guess: Vec<Color>, pub valid: bool, pub good: usize, pub wrong: usize, } pub struct MasterMind { secret_len: usize, secret: Vec<Color>, pub tries: u64, } impl MasterMind { pub fn new(secret_len: usize) -> Self { Self { secret_len, secret: (0..secret_len).map(|_| rand::random()).collect(), tries: 0, } } pub fn to_mastermind_colors(&self, input: &str) -> Result<Vec<Color>, String> { let mut colors = vec![]; let letters = input.trim(); if letters.len() != self.secret_len { return Err(format!( "A minimum of {} colors should be given", self.secret_len )); } for letter in letters.chars() { let color = match letter.to_ascii_uppercase() { 'R' => Color::Red, 'G' => Color::Green, 'B' => Color::Blue, 'P' => Color::Purple, 'O' => Color::Orange, 'Y' => Color::Yellow, 'W' => Color::White, 'C' => Color::Cyan, _ => { return Err(format!( "Color '{}' is invalid - you can only use the following colors:", letter )); } }; colors.push(color); } Ok(colors) } pub fn guess(&mut self, combination: &[Color]) -> MasterMindResponse { self.tries += 1; let good = Self::number_of_well_placed_pawns(&self.secret, combination); let wrong = Self::number_of_not_well_placed_pawns(&self.secret, combination); MasterMindResponse { guess: combination.to_vec(), valid: good == self.secret_len, good, wrong, } } pub fn number_of_well_placed_pawns(secret: &[Color], combination: &[Color]) -> usize { secret .iter() .enumerate() .filter(|&(i, color)| combination[i] == *color) .count() } pub fn number_of_not_well_placed_pawns(secret: &[Color], combination: &[Color]) -> usize { secret.len() - MasterMind::number_of_well_placed_pawns(secret, combination) } pub fn print_welcome(&self) { println!( " __ __ ______ ______ ______ ______ ______ __ __ __ __ __ _____" ); println!("/\\ \"-./ \\ /\\ __ \\ /\\ ___\\ /\\__ _\\ /\\ ___\\ /\\ == \\ /\\ \"-./ \\ /\\ \\ /\\ \"-.\\ \\ /\\ __-."); println!("\\ \\ \\-./\\ \\ \\ \\ __ \\ \\ \\___ \\ \\/_/\\ \\/ \\ \\ __\\ \\ \\ __< \\ \\ \\-./\\ \\ \\ \\ \\ \\ \\ \\-. \\ \\ \\ \\/\\ \\"); println!(" \\ \\_\\ \\ \\_\\ \\ \\_\\ \\_\\ \\/\\_____\\ \\ \\_\\ \\ \\_____\\ \\ \\_\\ \\_\\ \\ \\_\\ \\ \\_\\ \\ \\_\\ \\ \\_\\\\\"\\_\\ \\ \\____-"); println!(" \\/_/ \\/_/ \\/_/\\/_/ \\/_____/ \\/_/ \\/_____/ \\/_/ /_/ \\/_/ \\/_/ \\/_/ \\/_/ \\/_/ \\/____/"); println!(); println!( "Welcome against the MasterMind! You need to find the color combination constitued of {} colors with a minimum of tries. Good luck.", self.secret_len ); println!(); println!("Possible colors are:"); Self::print_possible_colors(); } pub fn fancy_print_guess(guess: &[Color]) { for color in guess { match color { Color::Red => print!("{}", Red.paint("R")), Color::Green => print!("{}", Green.paint("G")), Color::Blue => print!("{}", Blue.paint("B")), Color::Purple => print!("{}", Purple.paint("P")), Color::Orange => print!("{}", Orange.paint("O")), Color::Yellow => print!("{}", Yellow.paint("Y")), Color::White => print!("{}", White.paint("W")), Color::Cyan => print!("{}", Cyan.paint("C")), } } println!(); } fn print_possible_colors() { println!("{} for {}", Red.bold().paint("R"), Red.bold().paint("Red")); println!( "{} for {}", Green.bold().paint("G"), Green.bold().paint("Green") ); println!( "{} for {}", Blue.bold().paint("B"), Blue.bold().paint("Blue") ); println!( "{} for {}", Purple.bold().paint("P"), Purple.bold().paint("Purple") ); println!( "{} for {}", Orange.bold().paint("O"), Orange.bold().paint("Orange") ); println!( "{} for {}", Yellow.bold().paint("Y"), Yellow.bold().paint("Yellow") ); println!( "{} for {}", White.bold().paint("W"), White.bold().paint("White") ); println!( "{} for {}", Cyan.bold().paint("C"), Cyan.bold().paint("Cyan") ); } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[inline] pub unsafe fn CreateVssExpressWriterInternal() -> ::windows::core::Result<IVssExpressWriter> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CreateVssExpressWriterInternal(ppwriter: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; } let mut result__: <IVssExpressWriter as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); CreateVssExpressWriterInternal(&mut result__).from_abi::<IVssExpressWriter>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssAdmin(pub ::windows::core::IUnknown); impl IVssAdmin { pub unsafe fn RegisterProvider<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param5: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, pproviderid: Param0, classid: Param1, pwszprovidername: *const u16, eprovidertype: VSS_PROVIDER_TYPE, pwszproviderversion: *const u16, providerversionid: Param5) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pproviderid.into_param().abi(), classid.into_param().abi(), ::core::mem::transmute(pwszprovidername), ::core::mem::transmute(eprovidertype), ::core::mem::transmute(pwszproviderversion), providerversionid.into_param().abi()).ok() } pub unsafe fn UnregisterProvider<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, providerid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), providerid.into_param().abi()).ok() } pub unsafe fn QueryProviders(&self) -> ::windows::core::Result<IVssEnumObject> { let mut result__: <IVssEnumObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVssEnumObject>(result__) } pub unsafe fn AbortAllSnapshotsInProgress(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self)).ok() } } unsafe impl ::windows::core::Interface for IVssAdmin { type Vtable = IVssAdmin_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x77ed5996_2f63_11d3_8a39_00c04f72d8e3); } impl ::core::convert::From<IVssAdmin> for ::windows::core::IUnknown { fn from(value: IVssAdmin) -> Self { value.0 } } impl ::core::convert::From<&IVssAdmin> for ::windows::core::IUnknown { fn from(value: &IVssAdmin) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssAdmin { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssAdmin { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssAdmin_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, pproviderid: ::windows::core::GUID, classid: ::windows::core::GUID, pwszprovidername: *const u16, eprovidertype: VSS_PROVIDER_TYPE, pwszproviderversion: *const u16, providerversionid: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, providerid: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssAdminEx(pub ::windows::core::IUnknown); impl IVssAdminEx { pub unsafe fn RegisterProvider<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param5: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, pproviderid: Param0, classid: Param1, pwszprovidername: *const u16, eprovidertype: VSS_PROVIDER_TYPE, pwszproviderversion: *const u16, providerversionid: Param5) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pproviderid.into_param().abi(), classid.into_param().abi(), ::core::mem::transmute(pwszprovidername), ::core::mem::transmute(eprovidertype), ::core::mem::transmute(pwszproviderversion), providerversionid.into_param().abi()).ok() } pub unsafe fn UnregisterProvider<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, providerid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), providerid.into_param().abi()).ok() } pub unsafe fn QueryProviders(&self) -> ::windows::core::Result<IVssEnumObject> { let mut result__: <IVssEnumObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVssEnumObject>(result__) } pub unsafe fn AbortAllSnapshotsInProgress(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn GetProviderCapability<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, pproviderid: Param0) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), pproviderid.into_param().abi(), &mut result__).from_abi::<u64>(result__) } pub unsafe fn GetProviderContext<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, providerid: Param0) -> ::windows::core::Result<i32> { let mut result__: <i32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), providerid.into_param().abi(), &mut result__).from_abi::<i32>(result__) } pub unsafe fn SetProviderContext<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, providerid: Param0, lcontext: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), providerid.into_param().abi(), ::core::mem::transmute(lcontext)).ok() } } unsafe impl ::windows::core::Interface for IVssAdminEx { type Vtable = IVssAdminEx_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7858a9f8_b1fa_41a6_964f_b9b36b8cd8d8); } impl ::core::convert::From<IVssAdminEx> for ::windows::core::IUnknown { fn from(value: IVssAdminEx) -> Self { value.0 } } impl ::core::convert::From<&IVssAdminEx> for ::windows::core::IUnknown { fn from(value: &IVssAdminEx) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssAdminEx { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssAdminEx { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IVssAdminEx> for IVssAdmin { fn from(value: IVssAdminEx) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IVssAdminEx> for IVssAdmin { fn from(value: &IVssAdminEx) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IVssAdmin> for IVssAdminEx { fn into_param(self) -> ::windows::core::Param<'a, IVssAdmin> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IVssAdmin> for &IVssAdminEx { fn into_param(self) -> ::windows::core::Param<'a, IVssAdmin> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IVssAdminEx_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, pproviderid: ::windows::core::GUID, classid: ::windows::core::GUID, pwszprovidername: *const u16, eprovidertype: VSS_PROVIDER_TYPE, pwszproviderversion: *const u16, providerversionid: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, providerid: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pproviderid: ::windows::core::GUID, plloriginalcapabilitymask: *mut u64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, providerid: ::windows::core::GUID, plcontext: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, providerid: ::windows::core::GUID, lcontext: i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssAsync(pub ::windows::core::IUnknown); impl IVssAsync { pub unsafe fn Cancel(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Wait(&self, dwmilliseconds: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwmilliseconds)).ok() } pub unsafe fn QueryStatus(&self, phrresult: *mut ::windows::core::HRESULT, preserved: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(phrresult), ::core::mem::transmute(preserved)).ok() } } unsafe impl ::windows::core::Interface for IVssAsync { type Vtable = IVssAsync_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x507c37b4_cf5b_4e95_b0af_14eb9767467e); } impl ::core::convert::From<IVssAsync> for ::windows::core::IUnknown { fn from(value: IVssAsync) -> Self { value.0 } } impl ::core::convert::From<&IVssAsync> for ::windows::core::IUnknown { fn from(value: &IVssAsync) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssAsync { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssAsync { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssAsync_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) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwmilliseconds: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, phrresult: *mut ::windows::core::HRESULT, preserved: *mut i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssComponent(pub ::windows::core::IUnknown); impl IVssComponent { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetLogicalPath(&self, pbstrpath: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrpath)).ok() } pub unsafe fn GetComponentType(&self, pct: *mut VSS_COMPONENT_TYPE) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pct)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetComponentName(&self, pbstrname: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrname)).ok() } pub unsafe fn GetBackupSucceeded(&self, pbsucceeded: *mut bool) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbsucceeded)).ok() } pub unsafe fn GetAlternateLocationMappingCount(&self, pcmappings: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcmappings)).ok() } pub unsafe fn GetAlternateLocationMapping(&self, imapping: u32) -> ::windows::core::Result<IVssWMFiledesc> { let mut result__: <IVssWMFiledesc as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(imapping), &mut result__).from_abi::<IVssWMFiledesc>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetBackupMetadata<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszdata: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), wszdata.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetBackupMetadata(&self, pbstrdata: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrdata)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddPartialFile<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszpath: Param0, wszfilename: Param1, wszranges: Param2, wszmetadata: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), wszpath.into_param().abi(), wszfilename.into_param().abi(), wszranges.into_param().abi(), wszmetadata.into_param().abi()).ok() } pub unsafe fn GetPartialFileCount(&self, pcpartialfiles: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcpartialfiles)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPartialFile(&self, ipartialfile: u32, pbstrpath: *mut super::super::Foundation::BSTR, pbstrfilename: *mut super::super::Foundation::BSTR, pbstrrange: *mut super::super::Foundation::BSTR, pbstrmetadata: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(ipartialfile), ::core::mem::transmute(pbstrpath), ::core::mem::transmute(pbstrfilename), ::core::mem::transmute(pbstrrange), ::core::mem::transmute(pbstrmetadata)).ok() } pub unsafe fn IsSelectedForRestore(&self, pbselectedforrestore: *mut bool) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbselectedforrestore)).ok() } pub unsafe fn GetAdditionalRestores(&self, pbadditionalrestores: *mut bool) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbadditionalrestores)).ok() } pub unsafe fn GetNewTargetCount(&self, pcnewtarget: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcnewtarget)).ok() } pub unsafe fn GetNewTarget(&self, inewtarget: u32) -> ::windows::core::Result<IVssWMFiledesc> { let mut result__: <IVssWMFiledesc as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(inewtarget), &mut result__).from_abi::<IVssWMFiledesc>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddDirectedTarget<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param5: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>( &self, wszsourcepath: Param0, wszsourcefilename: Param1, wszsourcerangelist: Param2, wszdestinationpath: Param3, wszdestinationfilename: Param4, wszdestinationrangelist: Param5, ) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), wszsourcepath.into_param().abi(), wszsourcefilename.into_param().abi(), wszsourcerangelist.into_param().abi(), wszdestinationpath.into_param().abi(), wszdestinationfilename.into_param().abi(), wszdestinationrangelist.into_param().abi()).ok() } pub unsafe fn GetDirectedTargetCount(&self, pcdirectedtarget: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdirectedtarget)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetDirectedTarget(&self, idirectedtarget: u32, pbstrsourcepath: *mut super::super::Foundation::BSTR, pbstrsourcefilename: *mut super::super::Foundation::BSTR, pbstrsourcerangelist: *mut super::super::Foundation::BSTR, pbstrdestinationpath: *mut super::super::Foundation::BSTR, pbstrdestinationfilename: *mut super::super::Foundation::BSTR, pbstrdestinationrangelist: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)( ::core::mem::transmute_copy(self), ::core::mem::transmute(idirectedtarget), ::core::mem::transmute(pbstrsourcepath), ::core::mem::transmute(pbstrsourcefilename), ::core::mem::transmute(pbstrsourcerangelist), ::core::mem::transmute(pbstrdestinationpath), ::core::mem::transmute(pbstrdestinationfilename), ::core::mem::transmute(pbstrdestinationrangelist), ) .ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetRestoreMetadata<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszrestoremetadata: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), wszrestoremetadata.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRestoreMetadata(&self, pbstrrestoremetadata: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrrestoremetadata)).ok() } pub unsafe fn SetRestoreTarget(&self, target: VSS_RESTORE_TARGET) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).23)(::core::mem::transmute_copy(self), ::core::mem::transmute(target)).ok() } pub unsafe fn GetRestoreTarget(&self, ptarget: *mut VSS_RESTORE_TARGET) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).24)(::core::mem::transmute_copy(self), ::core::mem::transmute(ptarget)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetPreRestoreFailureMsg<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszprerestorefailuremsg: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).25)(::core::mem::transmute_copy(self), wszprerestorefailuremsg.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPreRestoreFailureMsg(&self, pbstrprerestorefailuremsg: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).26)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrprerestorefailuremsg)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetPostRestoreFailureMsg<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszpostrestorefailuremsg: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).27)(::core::mem::transmute_copy(self), wszpostrestorefailuremsg.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPostRestoreFailureMsg(&self, pbstrpostrestorefailuremsg: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).28)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrpostrestorefailuremsg)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetBackupStamp<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszbackupstamp: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).29)(::core::mem::transmute_copy(self), wszbackupstamp.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetBackupStamp(&self, pbstrbackupstamp: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).30)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrbackupstamp)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPreviousBackupStamp(&self, pbstrbackupstamp: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).31)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrbackupstamp)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetBackupOptions(&self, pbstrbackupoptions: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).32)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrbackupoptions)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRestoreOptions(&self, pbstrrestoreoptions: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).33)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrrestoreoptions)).ok() } pub unsafe fn GetRestoreSubcomponentCount(&self, pcrestoresubcomponent: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).34)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcrestoresubcomponent)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRestoreSubcomponent(&self, icomponent: u32, pbstrlogicalpath: *mut super::super::Foundation::BSTR, pbstrcomponentname: *mut super::super::Foundation::BSTR, pbrepair: *mut bool) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).35)(::core::mem::transmute_copy(self), ::core::mem::transmute(icomponent), ::core::mem::transmute(pbstrlogicalpath), ::core::mem::transmute(pbstrcomponentname), ::core::mem::transmute(pbrepair)).ok() } pub unsafe fn GetFileRestoreStatus(&self, pstatus: *mut VSS_FILE_RESTORE_STATUS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).36)(::core::mem::transmute_copy(self), ::core::mem::transmute(pstatus)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddDifferencedFilesByLastModifyTime<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::FILETIME>>(&self, wszpath: Param0, wszfilespec: Param1, brecursive: Param2, ftlastmodifytime: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).37)(::core::mem::transmute_copy(self), wszpath.into_param().abi(), wszfilespec.into_param().abi(), brecursive.into_param().abi(), ftlastmodifytime.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddDifferencedFilesByLastModifyLSN<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, wszpath: Param0, wszfilespec: Param1, brecursive: Param2, bstrlsnstring: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).38)(::core::mem::transmute_copy(self), wszpath.into_param().abi(), wszfilespec.into_param().abi(), brecursive.into_param().abi(), bstrlsnstring.into_param().abi()).ok() } pub unsafe fn GetDifferencedFilesCount(&self, pcdifferencedfiles: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).39)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdifferencedfiles)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetDifferencedFile(&self, idifferencedfile: u32, pbstrpath: *mut super::super::Foundation::BSTR, pbstrfilespec: *mut super::super::Foundation::BSTR, pbrecursive: *mut super::super::Foundation::BOOL, pbstrlsnstring: *mut super::super::Foundation::BSTR, pftlastmodifytime: *mut super::super::Foundation::FILETIME) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).40)(::core::mem::transmute_copy(self), ::core::mem::transmute(idifferencedfile), ::core::mem::transmute(pbstrpath), ::core::mem::transmute(pbstrfilespec), ::core::mem::transmute(pbrecursive), ::core::mem::transmute(pbstrlsnstring), ::core::mem::transmute(pftlastmodifytime)).ok() } } unsafe impl ::windows::core::Interface for IVssComponent { type Vtable = IVssComponent_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd2c72c96_c121_4518_b627_e5a93d010ead); } impl ::core::convert::From<IVssComponent> for ::windows::core::IUnknown { fn from(value: IVssComponent) -> Self { value.0 } } impl ::core::convert::From<&IVssComponent> for ::windows::core::IUnknown { fn from(value: &IVssComponent) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssComponent { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssComponent { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssComponent_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pct: *mut VSS_COMPONENT_TYPE) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrname: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbsucceeded: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcmappings: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, imapping: u32, ppfiledesc: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszdata: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrdata: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR, wszfilename: super::super::Foundation::PWSTR, wszranges: super::super::Foundation::PWSTR, wszmetadata: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcpartialfiles: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ipartialfile: u32, pbstrpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrfilename: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrrange: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrmetadata: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbselectedforrestore: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbadditionalrestores: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcnewtarget: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inewtarget: u32, ppfiledesc: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszsourcepath: super::super::Foundation::PWSTR, wszsourcefilename: super::super::Foundation::PWSTR, wszsourcerangelist: super::super::Foundation::PWSTR, wszdestinationpath: super::super::Foundation::PWSTR, wszdestinationfilename: super::super::Foundation::PWSTR, wszdestinationrangelist: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdirectedtarget: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn( this: ::windows::core::RawPtr, idirectedtarget: u32, pbstrsourcepath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrsourcefilename: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrsourcerangelist: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrdestinationpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrdestinationfilename: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrdestinationrangelist: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, ) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszrestoremetadata: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrrestoremetadata: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, target: VSS_RESTORE_TARGET) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ptarget: *mut VSS_RESTORE_TARGET) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszprerestorefailuremsg: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrprerestorefailuremsg: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpostrestorefailuremsg: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpostrestorefailuremsg: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszbackupstamp: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrbackupstamp: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrbackupstamp: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrbackupoptions: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrrestoreoptions: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcrestoresubcomponent: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, icomponent: u32, pbstrlogicalpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrcomponentname: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbrepair: *mut bool) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pstatus: *mut VSS_FILE_RESTORE_STATUS) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, brecursive: super::super::Foundation::BOOL, ftlastmodifytime: super::super::Foundation::FILETIME) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, brecursive: super::super::Foundation::BOOL, bstrlsnstring: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdifferencedfiles: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, idifferencedfile: u32, pbstrpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrfilespec: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbrecursive: *mut super::super::Foundation::BOOL, pbstrlsnstring: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pftlastmodifytime: *mut super::super::Foundation::FILETIME) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssComponentEx(pub ::windows::core::IUnknown); impl IVssComponentEx { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetLogicalPath(&self, pbstrpath: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrpath)).ok() } pub unsafe fn GetComponentType(&self, pct: *mut VSS_COMPONENT_TYPE) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pct)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetComponentName(&self, pbstrname: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrname)).ok() } pub unsafe fn GetBackupSucceeded(&self, pbsucceeded: *mut bool) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbsucceeded)).ok() } pub unsafe fn GetAlternateLocationMappingCount(&self, pcmappings: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcmappings)).ok() } pub unsafe fn GetAlternateLocationMapping(&self, imapping: u32) -> ::windows::core::Result<IVssWMFiledesc> { let mut result__: <IVssWMFiledesc as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(imapping), &mut result__).from_abi::<IVssWMFiledesc>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetBackupMetadata<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszdata: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), wszdata.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetBackupMetadata(&self, pbstrdata: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrdata)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddPartialFile<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszpath: Param0, wszfilename: Param1, wszranges: Param2, wszmetadata: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), wszpath.into_param().abi(), wszfilename.into_param().abi(), wszranges.into_param().abi(), wszmetadata.into_param().abi()).ok() } pub unsafe fn GetPartialFileCount(&self, pcpartialfiles: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcpartialfiles)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPartialFile(&self, ipartialfile: u32, pbstrpath: *mut super::super::Foundation::BSTR, pbstrfilename: *mut super::super::Foundation::BSTR, pbstrrange: *mut super::super::Foundation::BSTR, pbstrmetadata: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(ipartialfile), ::core::mem::transmute(pbstrpath), ::core::mem::transmute(pbstrfilename), ::core::mem::transmute(pbstrrange), ::core::mem::transmute(pbstrmetadata)).ok() } pub unsafe fn IsSelectedForRestore(&self, pbselectedforrestore: *mut bool) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbselectedforrestore)).ok() } pub unsafe fn GetAdditionalRestores(&self, pbadditionalrestores: *mut bool) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbadditionalrestores)).ok() } pub unsafe fn GetNewTargetCount(&self, pcnewtarget: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcnewtarget)).ok() } pub unsafe fn GetNewTarget(&self, inewtarget: u32) -> ::windows::core::Result<IVssWMFiledesc> { let mut result__: <IVssWMFiledesc as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(inewtarget), &mut result__).from_abi::<IVssWMFiledesc>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddDirectedTarget<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param5: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>( &self, wszsourcepath: Param0, wszsourcefilename: Param1, wszsourcerangelist: Param2, wszdestinationpath: Param3, wszdestinationfilename: Param4, wszdestinationrangelist: Param5, ) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), wszsourcepath.into_param().abi(), wszsourcefilename.into_param().abi(), wszsourcerangelist.into_param().abi(), wszdestinationpath.into_param().abi(), wszdestinationfilename.into_param().abi(), wszdestinationrangelist.into_param().abi()).ok() } pub unsafe fn GetDirectedTargetCount(&self, pcdirectedtarget: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdirectedtarget)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetDirectedTarget(&self, idirectedtarget: u32, pbstrsourcepath: *mut super::super::Foundation::BSTR, pbstrsourcefilename: *mut super::super::Foundation::BSTR, pbstrsourcerangelist: *mut super::super::Foundation::BSTR, pbstrdestinationpath: *mut super::super::Foundation::BSTR, pbstrdestinationfilename: *mut super::super::Foundation::BSTR, pbstrdestinationrangelist: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)( ::core::mem::transmute_copy(self), ::core::mem::transmute(idirectedtarget), ::core::mem::transmute(pbstrsourcepath), ::core::mem::transmute(pbstrsourcefilename), ::core::mem::transmute(pbstrsourcerangelist), ::core::mem::transmute(pbstrdestinationpath), ::core::mem::transmute(pbstrdestinationfilename), ::core::mem::transmute(pbstrdestinationrangelist), ) .ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetRestoreMetadata<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszrestoremetadata: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), wszrestoremetadata.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRestoreMetadata(&self, pbstrrestoremetadata: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrrestoremetadata)).ok() } pub unsafe fn SetRestoreTarget(&self, target: VSS_RESTORE_TARGET) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).23)(::core::mem::transmute_copy(self), ::core::mem::transmute(target)).ok() } pub unsafe fn GetRestoreTarget(&self, ptarget: *mut VSS_RESTORE_TARGET) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).24)(::core::mem::transmute_copy(self), ::core::mem::transmute(ptarget)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetPreRestoreFailureMsg<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszprerestorefailuremsg: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).25)(::core::mem::transmute_copy(self), wszprerestorefailuremsg.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPreRestoreFailureMsg(&self, pbstrprerestorefailuremsg: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).26)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrprerestorefailuremsg)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetPostRestoreFailureMsg<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszpostrestorefailuremsg: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).27)(::core::mem::transmute_copy(self), wszpostrestorefailuremsg.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPostRestoreFailureMsg(&self, pbstrpostrestorefailuremsg: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).28)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrpostrestorefailuremsg)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetBackupStamp<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszbackupstamp: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).29)(::core::mem::transmute_copy(self), wszbackupstamp.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetBackupStamp(&self, pbstrbackupstamp: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).30)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrbackupstamp)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPreviousBackupStamp(&self, pbstrbackupstamp: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).31)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrbackupstamp)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetBackupOptions(&self, pbstrbackupoptions: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).32)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrbackupoptions)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRestoreOptions(&self, pbstrrestoreoptions: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).33)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrrestoreoptions)).ok() } pub unsafe fn GetRestoreSubcomponentCount(&self, pcrestoresubcomponent: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).34)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcrestoresubcomponent)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRestoreSubcomponent(&self, icomponent: u32, pbstrlogicalpath: *mut super::super::Foundation::BSTR, pbstrcomponentname: *mut super::super::Foundation::BSTR, pbrepair: *mut bool) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).35)(::core::mem::transmute_copy(self), ::core::mem::transmute(icomponent), ::core::mem::transmute(pbstrlogicalpath), ::core::mem::transmute(pbstrcomponentname), ::core::mem::transmute(pbrepair)).ok() } pub unsafe fn GetFileRestoreStatus(&self, pstatus: *mut VSS_FILE_RESTORE_STATUS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).36)(::core::mem::transmute_copy(self), ::core::mem::transmute(pstatus)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddDifferencedFilesByLastModifyTime<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::FILETIME>>(&self, wszpath: Param0, wszfilespec: Param1, brecursive: Param2, ftlastmodifytime: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).37)(::core::mem::transmute_copy(self), wszpath.into_param().abi(), wszfilespec.into_param().abi(), brecursive.into_param().abi(), ftlastmodifytime.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddDifferencedFilesByLastModifyLSN<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, wszpath: Param0, wszfilespec: Param1, brecursive: Param2, bstrlsnstring: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).38)(::core::mem::transmute_copy(self), wszpath.into_param().abi(), wszfilespec.into_param().abi(), brecursive.into_param().abi(), bstrlsnstring.into_param().abi()).ok() } pub unsafe fn GetDifferencedFilesCount(&self, pcdifferencedfiles: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).39)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdifferencedfiles)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetDifferencedFile(&self, idifferencedfile: u32, pbstrpath: *mut super::super::Foundation::BSTR, pbstrfilespec: *mut super::super::Foundation::BSTR, pbrecursive: *mut super::super::Foundation::BOOL, pbstrlsnstring: *mut super::super::Foundation::BSTR, pftlastmodifytime: *mut super::super::Foundation::FILETIME) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).40)(::core::mem::transmute_copy(self), ::core::mem::transmute(idifferencedfile), ::core::mem::transmute(pbstrpath), ::core::mem::transmute(pbstrfilespec), ::core::mem::transmute(pbrecursive), ::core::mem::transmute(pbstrlsnstring), ::core::mem::transmute(pftlastmodifytime)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetPrepareForBackupFailureMsg<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszfailuremsg: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).41)(::core::mem::transmute_copy(self), wszfailuremsg.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetPostSnapshotFailureMsg<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszfailuremsg: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).42)(::core::mem::transmute_copy(self), wszfailuremsg.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPrepareForBackupFailureMsg(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> { let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).43)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPostSnapshotFailureMsg(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> { let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).44)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__) } pub unsafe fn GetAuthoritativeRestore(&self) -> ::windows::core::Result<bool> { let mut result__: <bool as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).45)(::core::mem::transmute_copy(self), &mut result__).from_abi::<bool>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRollForward(&self, prolltype: *mut VSS_ROLLFORWARD_TYPE, pbstrpoint: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).46)(::core::mem::transmute_copy(self), ::core::mem::transmute(prolltype), ::core::mem::transmute(pbstrpoint)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRestoreName(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> { let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).47)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__) } } unsafe impl ::windows::core::Interface for IVssComponentEx { type Vtable = IVssComponentEx_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x156c8b5e_f131_4bd7_9c97_d1923be7e1fa); } impl ::core::convert::From<IVssComponentEx> for ::windows::core::IUnknown { fn from(value: IVssComponentEx) -> Self { value.0 } } impl ::core::convert::From<&IVssComponentEx> for ::windows::core::IUnknown { fn from(value: &IVssComponentEx) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssComponentEx { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssComponentEx { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IVssComponentEx> for IVssComponent { fn from(value: IVssComponentEx) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IVssComponentEx> for IVssComponent { fn from(value: &IVssComponentEx) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IVssComponent> for IVssComponentEx { fn into_param(self) -> ::windows::core::Param<'a, IVssComponent> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IVssComponent> for &IVssComponentEx { fn into_param(self) -> ::windows::core::Param<'a, IVssComponent> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IVssComponentEx_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pct: *mut VSS_COMPONENT_TYPE) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrname: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbsucceeded: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcmappings: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, imapping: u32, ppfiledesc: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszdata: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrdata: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR, wszfilename: super::super::Foundation::PWSTR, wszranges: super::super::Foundation::PWSTR, wszmetadata: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcpartialfiles: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ipartialfile: u32, pbstrpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrfilename: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrrange: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrmetadata: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbselectedforrestore: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbadditionalrestores: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcnewtarget: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inewtarget: u32, ppfiledesc: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszsourcepath: super::super::Foundation::PWSTR, wszsourcefilename: super::super::Foundation::PWSTR, wszsourcerangelist: super::super::Foundation::PWSTR, wszdestinationpath: super::super::Foundation::PWSTR, wszdestinationfilename: super::super::Foundation::PWSTR, wszdestinationrangelist: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdirectedtarget: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn( this: ::windows::core::RawPtr, idirectedtarget: u32, pbstrsourcepath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrsourcefilename: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrsourcerangelist: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrdestinationpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrdestinationfilename: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrdestinationrangelist: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, ) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszrestoremetadata: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrrestoremetadata: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, target: VSS_RESTORE_TARGET) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ptarget: *mut VSS_RESTORE_TARGET) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszprerestorefailuremsg: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrprerestorefailuremsg: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpostrestorefailuremsg: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpostrestorefailuremsg: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszbackupstamp: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrbackupstamp: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrbackupstamp: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrbackupoptions: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrrestoreoptions: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcrestoresubcomponent: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, icomponent: u32, pbstrlogicalpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrcomponentname: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbrepair: *mut bool) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pstatus: *mut VSS_FILE_RESTORE_STATUS) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, brecursive: super::super::Foundation::BOOL, ftlastmodifytime: super::super::Foundation::FILETIME) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, brecursive: super::super::Foundation::BOOL, bstrlsnstring: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdifferencedfiles: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, idifferencedfile: u32, pbstrpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrfilespec: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbrecursive: *mut super::super::Foundation::BOOL, pbstrlsnstring: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pftlastmodifytime: *mut super::super::Foundation::FILETIME) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszfailuremsg: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszfailuremsg: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrfailuremsg: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrfailuremsg: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbauth: *mut bool) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, prolltype: *mut VSS_ROLLFORWARD_TYPE, pbstrpoint: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrname: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssComponentEx2(pub ::windows::core::IUnknown); impl IVssComponentEx2 { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetLogicalPath(&self, pbstrpath: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrpath)).ok() } pub unsafe fn GetComponentType(&self, pct: *mut VSS_COMPONENT_TYPE) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pct)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetComponentName(&self, pbstrname: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrname)).ok() } pub unsafe fn GetBackupSucceeded(&self, pbsucceeded: *mut bool) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbsucceeded)).ok() } pub unsafe fn GetAlternateLocationMappingCount(&self, pcmappings: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcmappings)).ok() } pub unsafe fn GetAlternateLocationMapping(&self, imapping: u32) -> ::windows::core::Result<IVssWMFiledesc> { let mut result__: <IVssWMFiledesc as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(imapping), &mut result__).from_abi::<IVssWMFiledesc>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetBackupMetadata<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszdata: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), wszdata.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetBackupMetadata(&self, pbstrdata: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrdata)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddPartialFile<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszpath: Param0, wszfilename: Param1, wszranges: Param2, wszmetadata: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), wszpath.into_param().abi(), wszfilename.into_param().abi(), wszranges.into_param().abi(), wszmetadata.into_param().abi()).ok() } pub unsafe fn GetPartialFileCount(&self, pcpartialfiles: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcpartialfiles)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPartialFile(&self, ipartialfile: u32, pbstrpath: *mut super::super::Foundation::BSTR, pbstrfilename: *mut super::super::Foundation::BSTR, pbstrrange: *mut super::super::Foundation::BSTR, pbstrmetadata: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(ipartialfile), ::core::mem::transmute(pbstrpath), ::core::mem::transmute(pbstrfilename), ::core::mem::transmute(pbstrrange), ::core::mem::transmute(pbstrmetadata)).ok() } pub unsafe fn IsSelectedForRestore(&self, pbselectedforrestore: *mut bool) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbselectedforrestore)).ok() } pub unsafe fn GetAdditionalRestores(&self, pbadditionalrestores: *mut bool) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbadditionalrestores)).ok() } pub unsafe fn GetNewTargetCount(&self, pcnewtarget: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcnewtarget)).ok() } pub unsafe fn GetNewTarget(&self, inewtarget: u32) -> ::windows::core::Result<IVssWMFiledesc> { let mut result__: <IVssWMFiledesc as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(inewtarget), &mut result__).from_abi::<IVssWMFiledesc>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddDirectedTarget<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param5: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>( &self, wszsourcepath: Param0, wszsourcefilename: Param1, wszsourcerangelist: Param2, wszdestinationpath: Param3, wszdestinationfilename: Param4, wszdestinationrangelist: Param5, ) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), wszsourcepath.into_param().abi(), wszsourcefilename.into_param().abi(), wszsourcerangelist.into_param().abi(), wszdestinationpath.into_param().abi(), wszdestinationfilename.into_param().abi(), wszdestinationrangelist.into_param().abi()).ok() } pub unsafe fn GetDirectedTargetCount(&self, pcdirectedtarget: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdirectedtarget)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetDirectedTarget(&self, idirectedtarget: u32, pbstrsourcepath: *mut super::super::Foundation::BSTR, pbstrsourcefilename: *mut super::super::Foundation::BSTR, pbstrsourcerangelist: *mut super::super::Foundation::BSTR, pbstrdestinationpath: *mut super::super::Foundation::BSTR, pbstrdestinationfilename: *mut super::super::Foundation::BSTR, pbstrdestinationrangelist: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)( ::core::mem::transmute_copy(self), ::core::mem::transmute(idirectedtarget), ::core::mem::transmute(pbstrsourcepath), ::core::mem::transmute(pbstrsourcefilename), ::core::mem::transmute(pbstrsourcerangelist), ::core::mem::transmute(pbstrdestinationpath), ::core::mem::transmute(pbstrdestinationfilename), ::core::mem::transmute(pbstrdestinationrangelist), ) .ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetRestoreMetadata<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszrestoremetadata: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), wszrestoremetadata.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRestoreMetadata(&self, pbstrrestoremetadata: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrrestoremetadata)).ok() } pub unsafe fn SetRestoreTarget(&self, target: VSS_RESTORE_TARGET) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).23)(::core::mem::transmute_copy(self), ::core::mem::transmute(target)).ok() } pub unsafe fn GetRestoreTarget(&self, ptarget: *mut VSS_RESTORE_TARGET) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).24)(::core::mem::transmute_copy(self), ::core::mem::transmute(ptarget)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetPreRestoreFailureMsg<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszprerestorefailuremsg: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).25)(::core::mem::transmute_copy(self), wszprerestorefailuremsg.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPreRestoreFailureMsg(&self, pbstrprerestorefailuremsg: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).26)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrprerestorefailuremsg)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetPostRestoreFailureMsg<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszpostrestorefailuremsg: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).27)(::core::mem::transmute_copy(self), wszpostrestorefailuremsg.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPostRestoreFailureMsg(&self, pbstrpostrestorefailuremsg: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).28)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrpostrestorefailuremsg)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetBackupStamp<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszbackupstamp: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).29)(::core::mem::transmute_copy(self), wszbackupstamp.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetBackupStamp(&self, pbstrbackupstamp: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).30)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrbackupstamp)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPreviousBackupStamp(&self, pbstrbackupstamp: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).31)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrbackupstamp)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetBackupOptions(&self, pbstrbackupoptions: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).32)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrbackupoptions)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRestoreOptions(&self, pbstrrestoreoptions: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).33)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrrestoreoptions)).ok() } pub unsafe fn GetRestoreSubcomponentCount(&self, pcrestoresubcomponent: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).34)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcrestoresubcomponent)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRestoreSubcomponent(&self, icomponent: u32, pbstrlogicalpath: *mut super::super::Foundation::BSTR, pbstrcomponentname: *mut super::super::Foundation::BSTR, pbrepair: *mut bool) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).35)(::core::mem::transmute_copy(self), ::core::mem::transmute(icomponent), ::core::mem::transmute(pbstrlogicalpath), ::core::mem::transmute(pbstrcomponentname), ::core::mem::transmute(pbrepair)).ok() } pub unsafe fn GetFileRestoreStatus(&self, pstatus: *mut VSS_FILE_RESTORE_STATUS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).36)(::core::mem::transmute_copy(self), ::core::mem::transmute(pstatus)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddDifferencedFilesByLastModifyTime<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::FILETIME>>(&self, wszpath: Param0, wszfilespec: Param1, brecursive: Param2, ftlastmodifytime: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).37)(::core::mem::transmute_copy(self), wszpath.into_param().abi(), wszfilespec.into_param().abi(), brecursive.into_param().abi(), ftlastmodifytime.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddDifferencedFilesByLastModifyLSN<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, wszpath: Param0, wszfilespec: Param1, brecursive: Param2, bstrlsnstring: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).38)(::core::mem::transmute_copy(self), wszpath.into_param().abi(), wszfilespec.into_param().abi(), brecursive.into_param().abi(), bstrlsnstring.into_param().abi()).ok() } pub unsafe fn GetDifferencedFilesCount(&self, pcdifferencedfiles: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).39)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcdifferencedfiles)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetDifferencedFile(&self, idifferencedfile: u32, pbstrpath: *mut super::super::Foundation::BSTR, pbstrfilespec: *mut super::super::Foundation::BSTR, pbrecursive: *mut super::super::Foundation::BOOL, pbstrlsnstring: *mut super::super::Foundation::BSTR, pftlastmodifytime: *mut super::super::Foundation::FILETIME) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).40)(::core::mem::transmute_copy(self), ::core::mem::transmute(idifferencedfile), ::core::mem::transmute(pbstrpath), ::core::mem::transmute(pbstrfilespec), ::core::mem::transmute(pbrecursive), ::core::mem::transmute(pbstrlsnstring), ::core::mem::transmute(pftlastmodifytime)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetPrepareForBackupFailureMsg<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszfailuremsg: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).41)(::core::mem::transmute_copy(self), wszfailuremsg.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetPostSnapshotFailureMsg<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszfailuremsg: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).42)(::core::mem::transmute_copy(self), wszfailuremsg.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPrepareForBackupFailureMsg(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> { let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).43)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPostSnapshotFailureMsg(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> { let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).44)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__) } pub unsafe fn GetAuthoritativeRestore(&self) -> ::windows::core::Result<bool> { let mut result__: <bool as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).45)(::core::mem::transmute_copy(self), &mut result__).from_abi::<bool>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRollForward(&self, prolltype: *mut VSS_ROLLFORWARD_TYPE, pbstrpoint: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).46)(::core::mem::transmute_copy(self), ::core::mem::transmute(prolltype), ::core::mem::transmute(pbstrpoint)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRestoreName(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> { let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).47)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetFailure<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, hr: ::windows::core::HRESULT, hrapplication: ::windows::core::HRESULT, wszapplicationmessage: Param2, dwreserved: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).48)(::core::mem::transmute_copy(self), ::core::mem::transmute(hr), ::core::mem::transmute(hrapplication), wszapplicationmessage.into_param().abi(), ::core::mem::transmute(dwreserved)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetFailure(&self, phr: *mut ::windows::core::HRESULT, phrapplication: *mut ::windows::core::HRESULT, pbstrapplicationmessage: *mut super::super::Foundation::BSTR, pdwreserved: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).49)(::core::mem::transmute_copy(self), ::core::mem::transmute(phr), ::core::mem::transmute(phrapplication), ::core::mem::transmute(pbstrapplicationmessage), ::core::mem::transmute(pdwreserved)).ok() } } unsafe impl ::windows::core::Interface for IVssComponentEx2 { type Vtable = IVssComponentEx2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3b5be0f2_07a9_4e4b_bdd3_cfdc8e2c0d2d); } impl ::core::convert::From<IVssComponentEx2> for ::windows::core::IUnknown { fn from(value: IVssComponentEx2) -> Self { value.0 } } impl ::core::convert::From<&IVssComponentEx2> for ::windows::core::IUnknown { fn from(value: &IVssComponentEx2) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssComponentEx2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssComponentEx2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IVssComponentEx2> for IVssComponentEx { fn from(value: IVssComponentEx2) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IVssComponentEx2> for IVssComponentEx { fn from(value: &IVssComponentEx2) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IVssComponentEx> for IVssComponentEx2 { fn into_param(self) -> ::windows::core::Param<'a, IVssComponentEx> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IVssComponentEx> for &IVssComponentEx2 { fn into_param(self) -> ::windows::core::Param<'a, IVssComponentEx> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } impl ::core::convert::From<IVssComponentEx2> for IVssComponent { fn from(value: IVssComponentEx2) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IVssComponentEx2> for IVssComponent { fn from(value: &IVssComponentEx2) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IVssComponent> for IVssComponentEx2 { fn into_param(self) -> ::windows::core::Param<'a, IVssComponent> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IVssComponent> for &IVssComponentEx2 { fn into_param(self) -> ::windows::core::Param<'a, IVssComponent> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IVssComponentEx2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pct: *mut VSS_COMPONENT_TYPE) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrname: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbsucceeded: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcmappings: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, imapping: u32, ppfiledesc: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszdata: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrdata: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR, wszfilename: super::super::Foundation::PWSTR, wszranges: super::super::Foundation::PWSTR, wszmetadata: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcpartialfiles: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ipartialfile: u32, pbstrpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrfilename: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrrange: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrmetadata: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbselectedforrestore: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbadditionalrestores: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcnewtarget: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inewtarget: u32, ppfiledesc: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszsourcepath: super::super::Foundation::PWSTR, wszsourcefilename: super::super::Foundation::PWSTR, wszsourcerangelist: super::super::Foundation::PWSTR, wszdestinationpath: super::super::Foundation::PWSTR, wszdestinationfilename: super::super::Foundation::PWSTR, wszdestinationrangelist: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdirectedtarget: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn( this: ::windows::core::RawPtr, idirectedtarget: u32, pbstrsourcepath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrsourcefilename: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrsourcerangelist: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrdestinationpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrdestinationfilename: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrdestinationrangelist: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, ) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszrestoremetadata: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrrestoremetadata: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, target: VSS_RESTORE_TARGET) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ptarget: *mut VSS_RESTORE_TARGET) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszprerestorefailuremsg: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrprerestorefailuremsg: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpostrestorefailuremsg: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpostrestorefailuremsg: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszbackupstamp: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrbackupstamp: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrbackupstamp: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrbackupoptions: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrrestoreoptions: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcrestoresubcomponent: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, icomponent: u32, pbstrlogicalpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrcomponentname: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbrepair: *mut bool) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pstatus: *mut VSS_FILE_RESTORE_STATUS) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, brecursive: super::super::Foundation::BOOL, ftlastmodifytime: super::super::Foundation::FILETIME) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, brecursive: super::super::Foundation::BOOL, bstrlsnstring: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcdifferencedfiles: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, idifferencedfile: u32, pbstrpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbstrfilespec: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbrecursive: *mut super::super::Foundation::BOOL, pbstrlsnstring: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pftlastmodifytime: *mut super::super::Foundation::FILETIME) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszfailuremsg: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszfailuremsg: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrfailuremsg: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrfailuremsg: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbauth: *mut bool) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, prolltype: *mut VSS_ROLLFORWARD_TYPE, pbstrpoint: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrname: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hr: ::windows::core::HRESULT, hrapplication: ::windows::core::HRESULT, wszapplicationmessage: super::super::Foundation::PWSTR, dwreserved: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, phr: *mut ::windows::core::HRESULT, phrapplication: *mut ::windows::core::HRESULT, pbstrapplicationmessage: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pdwreserved: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssCreateExpressWriterMetadata(pub ::windows::core::IUnknown); impl IVssCreateExpressWriterMetadata { #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddExcludeFiles<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszpath: Param0, wszfilespec: Param1, brecursive: u8) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), wszpath.into_param().abi(), wszfilespec.into_param().abi(), ::core::mem::transmute(brecursive)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddComponent<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>( &self, ct: VSS_COMPONENT_TYPE, wszlogicalpath: Param1, wszcomponentname: Param2, wszcaption: Param3, pbicon: *const u8, cbicon: u32, brestoremetadata: u8, bnotifyonbackupcomplete: u8, bselectable: u8, bselectableforrestore: u8, dwcomponentflags: u32, ) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ct), wszlogicalpath.into_param().abi(), wszcomponentname.into_param().abi(), wszcaption.into_param().abi(), ::core::mem::transmute(pbicon), ::core::mem::transmute(cbicon), ::core::mem::transmute(brestoremetadata), ::core::mem::transmute(bnotifyonbackupcomplete), ::core::mem::transmute(bselectable), ::core::mem::transmute(bselectableforrestore), ::core::mem::transmute(dwcomponentflags), ) .ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddFilesToFileGroup<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param5: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>( &self, wszlogicalpath: Param0, wszgroupname: Param1, wszpath: Param2, wszfilespec: Param3, brecursive: u8, wszalternatelocation: Param5, dwbackuptypemask: u32, ) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), wszlogicalpath.into_param().abi(), wszgroupname.into_param().abi(), wszpath.into_param().abi(), wszfilespec.into_param().abi(), ::core::mem::transmute(brecursive), wszalternatelocation.into_param().abi(), ::core::mem::transmute(dwbackuptypemask)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetRestoreMethod<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, method: VSS_RESTOREMETHOD_ENUM, wszservice: Param1, wszuserprocedure: Param2, writerrestore: VSS_WRITERRESTORE_ENUM, brebootrequired: u8) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(method), wszservice.into_param().abi(), wszuserprocedure.into_param().abi(), ::core::mem::transmute(writerrestore), ::core::mem::transmute(brebootrequired)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddComponentDependency<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>( &self, wszforlogicalpath: Param0, wszforcomponentname: Param1, onwriterid: Param2, wszonlogicalpath: Param3, wszoncomponentname: Param4, ) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), wszforlogicalpath.into_param().abi(), wszforcomponentname.into_param().abi(), onwriterid.into_param().abi(), wszonlogicalpath.into_param().abi(), wszoncomponentname.into_param().abi()).ok() } pub unsafe fn SetBackupSchema(&self, dwschemamask: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwschemamask)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SaveAsXML(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> { let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__) } } unsafe impl ::windows::core::Interface for IVssCreateExpressWriterMetadata { type Vtable = IVssCreateExpressWriterMetadata_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9c772e77_b26e_427f_92dd_c996f41ea5e3); } impl ::core::convert::From<IVssCreateExpressWriterMetadata> for ::windows::core::IUnknown { fn from(value: IVssCreateExpressWriterMetadata) -> Self { value.0 } } impl ::core::convert::From<&IVssCreateExpressWriterMetadata> for ::windows::core::IUnknown { fn from(value: &IVssCreateExpressWriterMetadata) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssCreateExpressWriterMetadata { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssCreateExpressWriterMetadata { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssCreateExpressWriterMetadata_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, brecursive: u8) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ct: VSS_COMPONENT_TYPE, wszlogicalpath: super::super::Foundation::PWSTR, wszcomponentname: super::super::Foundation::PWSTR, wszcaption: super::super::Foundation::PWSTR, pbicon: *const u8, cbicon: u32, brestoremetadata: u8, bnotifyonbackupcomplete: u8, bselectable: u8, bselectableforrestore: u8, dwcomponentflags: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszlogicalpath: super::super::Foundation::PWSTR, wszgroupname: super::super::Foundation::PWSTR, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, brecursive: u8, wszalternatelocation: super::super::Foundation::PWSTR, dwbackuptypemask: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, method: VSS_RESTOREMETHOD_ENUM, wszservice: super::super::Foundation::PWSTR, wszuserprocedure: super::super::Foundation::PWSTR, writerrestore: VSS_WRITERRESTORE_ENUM, brebootrequired: u8) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszforlogicalpath: super::super::Foundation::PWSTR, wszforcomponentname: super::super::Foundation::PWSTR, onwriterid: ::windows::core::GUID, wszonlogicalpath: super::super::Foundation::PWSTR, wszoncomponentname: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwschemamask: u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrxml: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssCreateWriterMetadata(pub ::windows::core::IUnknown); impl IVssCreateWriterMetadata { #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddIncludeFiles<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszpath: Param0, wszfilespec: Param1, brecursive: u8, wszalternatelocation: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), wszpath.into_param().abi(), wszfilespec.into_param().abi(), ::core::mem::transmute(brecursive), wszalternatelocation.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddExcludeFiles<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszpath: Param0, wszfilespec: Param1, brecursive: u8) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), wszpath.into_param().abi(), wszfilespec.into_param().abi(), ::core::mem::transmute(brecursive)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddComponent<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>( &self, ct: VSS_COMPONENT_TYPE, wszlogicalpath: Param1, wszcomponentname: Param2, wszcaption: Param3, pbicon: *const u8, cbicon: u32, brestoremetadata: u8, bnotifyonbackupcomplete: u8, bselectable: u8, bselectableforrestore: u8, dwcomponentflags: u32, ) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ct), wszlogicalpath.into_param().abi(), wszcomponentname.into_param().abi(), wszcaption.into_param().abi(), ::core::mem::transmute(pbicon), ::core::mem::transmute(cbicon), ::core::mem::transmute(brestoremetadata), ::core::mem::transmute(bnotifyonbackupcomplete), ::core::mem::transmute(bselectable), ::core::mem::transmute(bselectableforrestore), ::core::mem::transmute(dwcomponentflags), ) .ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddDatabaseFiles<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszlogicalpath: Param0, wszdatabasename: Param1, wszpath: Param2, wszfilespec: Param3, dwbackuptypemask: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), wszlogicalpath.into_param().abi(), wszdatabasename.into_param().abi(), wszpath.into_param().abi(), wszfilespec.into_param().abi(), ::core::mem::transmute(dwbackuptypemask)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddDatabaseLogFiles<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszlogicalpath: Param0, wszdatabasename: Param1, wszpath: Param2, wszfilespec: Param3, dwbackuptypemask: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), wszlogicalpath.into_param().abi(), wszdatabasename.into_param().abi(), wszpath.into_param().abi(), wszfilespec.into_param().abi(), ::core::mem::transmute(dwbackuptypemask)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddFilesToFileGroup<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param5: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>( &self, wszlogicalpath: Param0, wszgroupname: Param1, wszpath: Param2, wszfilespec: Param3, brecursive: u8, wszalternatelocation: Param5, dwbackuptypemask: u32, ) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), wszlogicalpath.into_param().abi(), wszgroupname.into_param().abi(), wszpath.into_param().abi(), wszfilespec.into_param().abi(), ::core::mem::transmute(brecursive), wszalternatelocation.into_param().abi(), ::core::mem::transmute(dwbackuptypemask)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetRestoreMethod<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, method: VSS_RESTOREMETHOD_ENUM, wszservice: Param1, wszuserprocedure: Param2, writerrestore: VSS_WRITERRESTORE_ENUM, brebootrequired: u8) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(method), wszservice.into_param().abi(), wszuserprocedure.into_param().abi(), ::core::mem::transmute(writerrestore), ::core::mem::transmute(brebootrequired)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddAlternateLocationMapping<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszsourcepath: Param0, wszsourcefilespec: Param1, brecursive: u8, wszdestination: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), wszsourcepath.into_param().abi(), wszsourcefilespec.into_param().abi(), ::core::mem::transmute(brecursive), wszdestination.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddComponentDependency<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>( &self, wszforlogicalpath: Param0, wszforcomponentname: Param1, onwriterid: Param2, wszonlogicalpath: Param3, wszoncomponentname: Param4, ) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), wszforlogicalpath.into_param().abi(), wszforcomponentname.into_param().abi(), onwriterid.into_param().abi(), wszonlogicalpath.into_param().abi(), wszoncomponentname.into_param().abi()).ok() } pub unsafe fn SetBackupSchema(&self, dwschemamask: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwschemamask)).ok() } #[cfg(feature = "Win32_Data_Xml_MsXml")] pub unsafe fn GetDocument(&self) -> ::windows::core::Result<super::super::Data::Xml::MsXml::IXMLDOMDocument> { let mut result__: <super::super::Data::Xml::MsXml::IXMLDOMDocument as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Data::Xml::MsXml::IXMLDOMDocument>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SaveAsXML(&self, pbstrxml: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrxml)).ok() } } unsafe impl ::windows::core::Interface for IVssCreateWriterMetadata { type Vtable = IVssCreateWriterMetadata_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IVssCreateWriterMetadata> for ::windows::core::IUnknown { fn from(value: IVssCreateWriterMetadata) -> Self { value.0 } } impl ::core::convert::From<&IVssCreateWriterMetadata> for ::windows::core::IUnknown { fn from(value: &IVssCreateWriterMetadata) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssCreateWriterMetadata { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssCreateWriterMetadata { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssCreateWriterMetadata_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, brecursive: u8, wszalternatelocation: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, brecursive: u8) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ct: VSS_COMPONENT_TYPE, wszlogicalpath: super::super::Foundation::PWSTR, wszcomponentname: super::super::Foundation::PWSTR, wszcaption: super::super::Foundation::PWSTR, pbicon: *const u8, cbicon: u32, brestoremetadata: u8, bnotifyonbackupcomplete: u8, bselectable: u8, bselectableforrestore: u8, dwcomponentflags: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszlogicalpath: super::super::Foundation::PWSTR, wszdatabasename: super::super::Foundation::PWSTR, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, dwbackuptypemask: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszlogicalpath: super::super::Foundation::PWSTR, wszdatabasename: super::super::Foundation::PWSTR, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, dwbackuptypemask: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszlogicalpath: super::super::Foundation::PWSTR, wszgroupname: super::super::Foundation::PWSTR, wszpath: super::super::Foundation::PWSTR, wszfilespec: super::super::Foundation::PWSTR, brecursive: u8, wszalternatelocation: super::super::Foundation::PWSTR, dwbackuptypemask: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, method: VSS_RESTOREMETHOD_ENUM, wszservice: super::super::Foundation::PWSTR, wszuserprocedure: super::super::Foundation::PWSTR, writerrestore: VSS_WRITERRESTORE_ENUM, brebootrequired: u8) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszsourcepath: super::super::Foundation::PWSTR, wszsourcefilespec: super::super::Foundation::PWSTR, brecursive: u8, wszdestination: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszforlogicalpath: super::super::Foundation::PWSTR, wszforcomponentname: super::super::Foundation::PWSTR, onwriterid: ::windows::core::GUID, wszonlogicalpath: super::super::Foundation::PWSTR, wszoncomponentname: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwschemamask: u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Data_Xml_MsXml")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdoc: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Data_Xml_MsXml"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrxml: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssDifferentialSoftwareSnapshotMgmt(pub ::windows::core::IUnknown); impl IVssDifferentialSoftwareSnapshotMgmt { pub unsafe fn AddDiffArea(&self, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pwszdiffareavolumename), ::core::mem::transmute(llmaximumdiffspace)).ok() } pub unsafe fn ChangeDiffAreaMaximumSize(&self, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pwszdiffareavolumename), ::core::mem::transmute(llmaximumdiffspace)).ok() } pub unsafe fn QueryVolumesSupportedForDiffAreas(&self, pwszoriginalvolumename: *const u16) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszoriginalvolumename), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } pub unsafe fn QueryDiffAreasForVolume(&self, pwszvolumename: *const u16) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } pub unsafe fn QueryDiffAreasOnVolume(&self, pwszvolumename: *const u16) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } pub unsafe fn QueryDiffAreasForSnapshot<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotid: Param0) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), snapshotid.into_param().abi(), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } } unsafe impl ::windows::core::Interface for IVssDifferentialSoftwareSnapshotMgmt { type Vtable = IVssDifferentialSoftwareSnapshotMgmt_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x214a0f28_b737_4026_b847_4f9e37d79529); } impl ::core::convert::From<IVssDifferentialSoftwareSnapshotMgmt> for ::windows::core::IUnknown { fn from(value: IVssDifferentialSoftwareSnapshotMgmt) -> Self { value.0 } } impl ::core::convert::From<&IVssDifferentialSoftwareSnapshotMgmt> for ::windows::core::IUnknown { fn from(value: &IVssDifferentialSoftwareSnapshotMgmt) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssDifferentialSoftwareSnapshotMgmt { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssDifferentialSoftwareSnapshotMgmt { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssDifferentialSoftwareSnapshotMgmt_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, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszoriginalvolumename: *const u16, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotid: ::windows::core::GUID, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssDifferentialSoftwareSnapshotMgmt2(pub ::windows::core::IUnknown); impl IVssDifferentialSoftwareSnapshotMgmt2 { pub unsafe fn AddDiffArea(&self, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pwszdiffareavolumename), ::core::mem::transmute(llmaximumdiffspace)).ok() } pub unsafe fn ChangeDiffAreaMaximumSize(&self, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pwszdiffareavolumename), ::core::mem::transmute(llmaximumdiffspace)).ok() } pub unsafe fn QueryVolumesSupportedForDiffAreas(&self, pwszoriginalvolumename: *const u16) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszoriginalvolumename), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } pub unsafe fn QueryDiffAreasForVolume(&self, pwszvolumename: *const u16) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } pub unsafe fn QueryDiffAreasOnVolume(&self, pwszvolumename: *const u16) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } pub unsafe fn QueryDiffAreasForSnapshot<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotid: Param0) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), snapshotid.into_param().abi(), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn ChangeDiffAreaMaximumSizeEx<'a, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64, bvolatile: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pwszdiffareavolumename), ::core::mem::transmute(llmaximumdiffspace), bvolatile.into_param().abi()).ok() } pub unsafe fn MigrateDiffAreas(&self, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, pwsznewdiffareavolumename: *const u16) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pwszdiffareavolumename), ::core::mem::transmute(pwsznewdiffareavolumename)).ok() } pub unsafe fn QueryMigrationStatus(&self, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16) -> ::windows::core::Result<IVssAsync> { let mut result__: <IVssAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pwszdiffareavolumename), &mut result__).from_abi::<IVssAsync>(result__) } pub unsafe fn SetSnapshotPriority<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, idsnapshot: Param0, priority: u8) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), idsnapshot.into_param().abi(), ::core::mem::transmute(priority)).ok() } } unsafe impl ::windows::core::Interface for IVssDifferentialSoftwareSnapshotMgmt2 { type Vtable = IVssDifferentialSoftwareSnapshotMgmt2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x949d7353_675f_4275_8969_f044c6277815); } impl ::core::convert::From<IVssDifferentialSoftwareSnapshotMgmt2> for ::windows::core::IUnknown { fn from(value: IVssDifferentialSoftwareSnapshotMgmt2) -> Self { value.0 } } impl ::core::convert::From<&IVssDifferentialSoftwareSnapshotMgmt2> for ::windows::core::IUnknown { fn from(value: &IVssDifferentialSoftwareSnapshotMgmt2) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssDifferentialSoftwareSnapshotMgmt2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssDifferentialSoftwareSnapshotMgmt2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IVssDifferentialSoftwareSnapshotMgmt2> for IVssDifferentialSoftwareSnapshotMgmt { fn from(value: IVssDifferentialSoftwareSnapshotMgmt2) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IVssDifferentialSoftwareSnapshotMgmt2> for IVssDifferentialSoftwareSnapshotMgmt { fn from(value: &IVssDifferentialSoftwareSnapshotMgmt2) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IVssDifferentialSoftwareSnapshotMgmt> for IVssDifferentialSoftwareSnapshotMgmt2 { fn into_param(self) -> ::windows::core::Param<'a, IVssDifferentialSoftwareSnapshotMgmt> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IVssDifferentialSoftwareSnapshotMgmt> for &IVssDifferentialSoftwareSnapshotMgmt2 { fn into_param(self) -> ::windows::core::Param<'a, IVssDifferentialSoftwareSnapshotMgmt> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IVssDifferentialSoftwareSnapshotMgmt2_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, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszoriginalvolumename: *const u16, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotid: ::windows::core::GUID, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64, bvolatile: super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, pwsznewdiffareavolumename: *const u16) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, idsnapshot: ::windows::core::GUID, priority: u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssDifferentialSoftwareSnapshotMgmt3(pub ::windows::core::IUnknown); impl IVssDifferentialSoftwareSnapshotMgmt3 { pub unsafe fn AddDiffArea(&self, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pwszdiffareavolumename), ::core::mem::transmute(llmaximumdiffspace)).ok() } pub unsafe fn ChangeDiffAreaMaximumSize(&self, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pwszdiffareavolumename), ::core::mem::transmute(llmaximumdiffspace)).ok() } pub unsafe fn QueryVolumesSupportedForDiffAreas(&self, pwszoriginalvolumename: *const u16) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszoriginalvolumename), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } pub unsafe fn QueryDiffAreasForVolume(&self, pwszvolumename: *const u16) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } pub unsafe fn QueryDiffAreasOnVolume(&self, pwszvolumename: *const u16) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } pub unsafe fn QueryDiffAreasForSnapshot<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotid: Param0) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), snapshotid.into_param().abi(), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn ChangeDiffAreaMaximumSizeEx<'a, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64, bvolatile: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pwszdiffareavolumename), ::core::mem::transmute(llmaximumdiffspace), bvolatile.into_param().abi()).ok() } pub unsafe fn MigrateDiffAreas(&self, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, pwsznewdiffareavolumename: *const u16) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pwszdiffareavolumename), ::core::mem::transmute(pwsznewdiffareavolumename)).ok() } pub unsafe fn QueryMigrationStatus(&self, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16) -> ::windows::core::Result<IVssAsync> { let mut result__: <IVssAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pwszdiffareavolumename), &mut result__).from_abi::<IVssAsync>(result__) } pub unsafe fn SetSnapshotPriority<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, idsnapshot: Param0, priority: u8) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), idsnapshot.into_param().abi(), ::core::mem::transmute(priority)).ok() } pub unsafe fn SetVolumeProtectLevel(&self, pwszvolumename: *const u16, protectionlevel: VSS_PROTECTION_LEVEL) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(protectionlevel)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetVolumeProtectLevel(&self, pwszvolumename: *const u16) -> ::windows::core::Result<VSS_VOLUME_PROTECTION_INFO> { let mut result__: <VSS_VOLUME_PROTECTION_INFO as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), &mut result__).from_abi::<VSS_VOLUME_PROTECTION_INFO>(result__) } pub unsafe fn ClearVolumeProtectFault(&self, pwszvolumename: *const u16) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename)).ok() } pub unsafe fn DeleteUnusedDiffAreas(&self, pwszdiffareavolumename: *const u16) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszdiffareavolumename)).ok() } pub unsafe fn QuerySnapshotDeltaBitmap<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, idsnapshotolder: Param0, idsnapshotyounger: Param1, pcblocksizeperbit: *mut u32, pcbitmaplength: *mut u32, ppbbitmap: *mut *mut u8) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), idsnapshotolder.into_param().abi(), idsnapshotyounger.into_param().abi(), ::core::mem::transmute(pcblocksizeperbit), ::core::mem::transmute(pcbitmaplength), ::core::mem::transmute(ppbbitmap)).ok() } } unsafe impl ::windows::core::Interface for IVssDifferentialSoftwareSnapshotMgmt3 { type Vtable = IVssDifferentialSoftwareSnapshotMgmt3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x383f7e71_a4c5_401f_b27f_f826289f8458); } impl ::core::convert::From<IVssDifferentialSoftwareSnapshotMgmt3> for ::windows::core::IUnknown { fn from(value: IVssDifferentialSoftwareSnapshotMgmt3) -> Self { value.0 } } impl ::core::convert::From<&IVssDifferentialSoftwareSnapshotMgmt3> for ::windows::core::IUnknown { fn from(value: &IVssDifferentialSoftwareSnapshotMgmt3) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssDifferentialSoftwareSnapshotMgmt3 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssDifferentialSoftwareSnapshotMgmt3 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IVssDifferentialSoftwareSnapshotMgmt3> for IVssDifferentialSoftwareSnapshotMgmt2 { fn from(value: IVssDifferentialSoftwareSnapshotMgmt3) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IVssDifferentialSoftwareSnapshotMgmt3> for IVssDifferentialSoftwareSnapshotMgmt2 { fn from(value: &IVssDifferentialSoftwareSnapshotMgmt3) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IVssDifferentialSoftwareSnapshotMgmt2> for IVssDifferentialSoftwareSnapshotMgmt3 { fn into_param(self) -> ::windows::core::Param<'a, IVssDifferentialSoftwareSnapshotMgmt2> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IVssDifferentialSoftwareSnapshotMgmt2> for &IVssDifferentialSoftwareSnapshotMgmt3 { fn into_param(self) -> ::windows::core::Param<'a, IVssDifferentialSoftwareSnapshotMgmt2> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } impl ::core::convert::From<IVssDifferentialSoftwareSnapshotMgmt3> for IVssDifferentialSoftwareSnapshotMgmt { fn from(value: IVssDifferentialSoftwareSnapshotMgmt3) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IVssDifferentialSoftwareSnapshotMgmt3> for IVssDifferentialSoftwareSnapshotMgmt { fn from(value: &IVssDifferentialSoftwareSnapshotMgmt3) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IVssDifferentialSoftwareSnapshotMgmt> for IVssDifferentialSoftwareSnapshotMgmt3 { fn into_param(self) -> ::windows::core::Param<'a, IVssDifferentialSoftwareSnapshotMgmt> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IVssDifferentialSoftwareSnapshotMgmt> for &IVssDifferentialSoftwareSnapshotMgmt3 { fn into_param(self) -> ::windows::core::Param<'a, IVssDifferentialSoftwareSnapshotMgmt> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IVssDifferentialSoftwareSnapshotMgmt3_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, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszoriginalvolumename: *const u16, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotid: ::windows::core::GUID, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, llmaximumdiffspace: i64, bvolatile: super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, pwsznewdiffareavolumename: *const u16) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, pwszdiffareavolumename: *const u16, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, idsnapshot: ::windows::core::GUID, priority: u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, protectionlevel: VSS_PROTECTION_LEVEL) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, protectionlevel: *mut VSS_VOLUME_PROTECTION_INFO) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszdiffareavolumename: *const u16) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, idsnapshotolder: ::windows::core::GUID, idsnapshotyounger: ::windows::core::GUID, pcblocksizeperbit: *mut u32, pcbitmaplength: *mut u32, ppbbitmap: *mut *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssEnumMgmtObject(pub ::windows::core::IUnknown); impl IVssEnumMgmtObject { pub unsafe fn Next(&self, celt: u32, rgelt: *mut VSS_MGMT_OBJECT_PROP, pceltfetched: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(celt), ::core::mem::transmute(rgelt), ::core::mem::transmute(pceltfetched)).ok() } pub unsafe fn Skip(&self, celt: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(celt)).ok() } pub unsafe fn Reset(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Clone(&self, ppenum: *mut ::core::option::Option<IVssEnumMgmtObject>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ppenum)).ok() } } unsafe impl ::windows::core::Interface for IVssEnumMgmtObject { type Vtable = IVssEnumMgmtObject_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x01954e6b_9254_4e6e_808c_c9e05d007696); } impl ::core::convert::From<IVssEnumMgmtObject> for ::windows::core::IUnknown { fn from(value: IVssEnumMgmtObject) -> Self { value.0 } } impl ::core::convert::From<&IVssEnumMgmtObject> for ::windows::core::IUnknown { fn from(value: &IVssEnumMgmtObject) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssEnumMgmtObject { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssEnumMgmtObject { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssEnumMgmtObject_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, celt: u32, rgelt: *mut VSS_MGMT_OBJECT_PROP, pceltfetched: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, celt: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssEnumObject(pub ::windows::core::IUnknown); impl IVssEnumObject { pub unsafe fn Next(&self, celt: u32, rgelt: *mut VSS_OBJECT_PROP, pceltfetched: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(celt), ::core::mem::transmute(rgelt), ::core::mem::transmute(pceltfetched)).ok() } pub unsafe fn Skip(&self, celt: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(celt)).ok() } pub unsafe fn Reset(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Clone(&self, ppenum: *mut ::core::option::Option<IVssEnumObject>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ppenum)).ok() } } unsafe impl ::windows::core::Interface for IVssEnumObject { type Vtable = IVssEnumObject_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xae1c7110_2f60_11d3_8a39_00c04f72d8e3); } impl ::core::convert::From<IVssEnumObject> for ::windows::core::IUnknown { fn from(value: IVssEnumObject) -> Self { value.0 } } impl ::core::convert::From<&IVssEnumObject> for ::windows::core::IUnknown { fn from(value: &IVssEnumObject) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssEnumObject { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssEnumObject { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssEnumObject_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, celt: u32, rgelt: *mut VSS_OBJECT_PROP, pceltfetched: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, celt: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(C)] #[derive(:: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy)] pub struct IVssExamineWriterMetadata(pub u8); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssExpressWriter(pub ::windows::core::IUnknown); impl IVssExpressWriter { #[cfg(feature = "Win32_Foundation")] pub unsafe fn CreateMetadata<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, writerid: Param0, writername: Param1, usagetype: VSS_USAGE_TYPE, versionmajor: u32, versionminor: u32, reserved: u32) -> ::windows::core::Result<IVssCreateExpressWriterMetadata> { let mut result__: <IVssCreateExpressWriterMetadata as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), writerid.into_param().abi(), writername.into_param().abi(), ::core::mem::transmute(usagetype), ::core::mem::transmute(versionmajor), ::core::mem::transmute(versionminor), ::core::mem::transmute(reserved), &mut result__).from_abi::<IVssCreateExpressWriterMetadata>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn LoadMetadata<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, metadata: Param0, reserved: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), metadata.into_param().abi(), ::core::mem::transmute(reserved)).ok() } pub unsafe fn Register(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Unregister<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, writerid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), writerid.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IVssExpressWriter { type Vtable = IVssExpressWriter_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe33affdc_59c7_47b1_97d5_4266598f6235); } impl ::core::convert::From<IVssExpressWriter> for ::windows::core::IUnknown { fn from(value: IVssExpressWriter) -> Self { value.0 } } impl ::core::convert::From<&IVssExpressWriter> for ::windows::core::IUnknown { fn from(value: &IVssExpressWriter) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssExpressWriter { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssExpressWriter { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssExpressWriter_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, writerid: ::windows::core::GUID, writername: super::super::Foundation::PWSTR, usagetype: VSS_USAGE_TYPE, versionmajor: u32, versionminor: u32, reserved: u32, ppmetadata: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, metadata: super::super::Foundation::PWSTR, reserved: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, writerid: ::windows::core::GUID) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssFileShareSnapshotProvider(pub ::windows::core::IUnknown); impl IVssFileShareSnapshotProvider { pub unsafe fn SetContext(&self, lcontext: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(lcontext)).ok() } pub unsafe fn GetSnapshotProperties<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotid: Param0) -> ::windows::core::Result<VSS_SNAPSHOT_PROP> { let mut result__: <VSS_SNAPSHOT_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), snapshotid.into_param().abi(), &mut result__).from_abi::<VSS_SNAPSHOT_PROP>(result__) } pub unsafe fn Query<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, queriedobjectid: Param0, equeriedobjecttype: VSS_OBJECT_TYPE, ereturnedobjectstype: VSS_OBJECT_TYPE) -> ::windows::core::Result<IVssEnumObject> { let mut result__: <IVssEnumObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), queriedobjectid.into_param().abi(), ::core::mem::transmute(equeriedobjecttype), ::core::mem::transmute(ereturnedobjectstype), &mut result__).from_abi::<IVssEnumObject>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn DeleteSnapshots<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, sourceobjectid: Param0, esourceobjecttype: VSS_OBJECT_TYPE, bforcedelete: Param2, pldeletedsnapshots: *mut i32, pnondeletedsnapshotid: *mut ::windows::core::GUID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), sourceobjectid.into_param().abi(), ::core::mem::transmute(esourceobjecttype), bforcedelete.into_param().abi(), ::core::mem::transmute(pldeletedsnapshots), ::core::mem::transmute(pnondeletedsnapshotid)).ok() } pub unsafe fn BeginPrepareSnapshot<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param4: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotsetid: Param0, snapshotid: Param1, pwszsharepath: *const u16, lnewcontext: i32, providerid: Param4) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), snapshotsetid.into_param().abi(), snapshotid.into_param().abi(), ::core::mem::transmute(pwszsharepath), ::core::mem::transmute(lnewcontext), providerid.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn IsPathSupported(&self, pwszsharepath: *const u16) -> ::windows::core::Result<super::super::Foundation::BOOL> { let mut result__: <super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszsharepath), &mut result__).from_abi::<super::super::Foundation::BOOL>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn IsPathSnapshotted(&self, pwszsharepath: *const u16, pbsnapshotspresent: *mut super::super::Foundation::BOOL, plsnapshotcompatibility: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszsharepath), ::core::mem::transmute(pbsnapshotspresent), ::core::mem::transmute(plsnapshotcompatibility)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe fn SetSnapshotProperty<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param2: ::windows::core::IntoParam<'a, super::super::System::Com::VARIANT>>(&self, snapshotid: Param0, esnapshotpropertyid: VSS_SNAPSHOT_PROPERTY_ID, vproperty: Param2) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), snapshotid.into_param().abi(), ::core::mem::transmute(esnapshotpropertyid), vproperty.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IVssFileShareSnapshotProvider { type Vtable = IVssFileShareSnapshotProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc8636060_7c2e_11df_8c4a_0800200c9a66); } impl ::core::convert::From<IVssFileShareSnapshotProvider> for ::windows::core::IUnknown { fn from(value: IVssFileShareSnapshotProvider) -> Self { value.0 } } impl ::core::convert::From<&IVssFileShareSnapshotProvider> for ::windows::core::IUnknown { fn from(value: &IVssFileShareSnapshotProvider) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssFileShareSnapshotProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssFileShareSnapshotProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssFileShareSnapshotProvider_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, lcontext: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotid: ::windows::core::GUID, pprop: *mut VSS_SNAPSHOT_PROP) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, queriedobjectid: ::windows::core::GUID, equeriedobjecttype: VSS_OBJECT_TYPE, ereturnedobjectstype: VSS_OBJECT_TYPE, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sourceobjectid: ::windows::core::GUID, esourceobjecttype: VSS_OBJECT_TYPE, bforcedelete: super::super::Foundation::BOOL, pldeletedsnapshots: *mut i32, pnondeletedsnapshotid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotsetid: ::windows::core::GUID, snapshotid: ::windows::core::GUID, pwszsharepath: *const u16, lnewcontext: i32, providerid: ::windows::core::GUID) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszsharepath: *const u16, pbsupportedbythisprovider: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszsharepath: *const u16, pbsnapshotspresent: *mut super::super::Foundation::BOOL, plsnapshotcompatibility: *mut i32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotid: ::windows::core::GUID, esnapshotpropertyid: VSS_SNAPSHOT_PROPERTY_ID, vproperty: ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssHardwareSnapshotProvider(pub ::windows::core::IUnknown); impl IVssHardwareSnapshotProvider { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn AreLunsSupported(&self, lluncount: i32, lcontext: i32, rgwszdevices: *const *const u16, pluninformation: *mut super::VirtualDiskService::VDS_LUN_INFORMATION, pbissupported: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(lluncount), ::core::mem::transmute(lcontext), ::core::mem::transmute(rgwszdevices), ::core::mem::transmute(pluninformation), ::core::mem::transmute(pbissupported)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn FillInLunInfo(&self, wszdevicename: *const u16, pluninfo: *mut super::VirtualDiskService::VDS_LUN_INFORMATION, pbissupported: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(wszdevicename), ::core::mem::transmute(pluninfo), ::core::mem::transmute(pbissupported)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn BeginPrepareSnapshot<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotsetid: Param0, snapshotid: Param1, lcontext: i32, lluncount: i32, rgdevicenames: *const *const u16, rgluninformation: *mut super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), snapshotsetid.into_param().abi(), snapshotid.into_param().abi(), ::core::mem::transmute(lcontext), ::core::mem::transmute(lluncount), ::core::mem::transmute(rgdevicenames), ::core::mem::transmute(rgluninformation)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn GetTargetLuns(&self, lluncount: i32, rgdevicenames: *const *const u16, rgsourceluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, rgdestinationluns: *mut super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(lluncount), ::core::mem::transmute(rgdevicenames), ::core::mem::transmute(rgsourceluns), ::core::mem::transmute(rgdestinationluns)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn LocateLuns(&self, lluncount: i32, rgsourceluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(lluncount), ::core::mem::transmute(rgsourceluns)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn OnLunEmpty(&self, wszdevicename: *const u16, pinformation: *const super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(wszdevicename), ::core::mem::transmute(pinformation)).ok() } } unsafe impl ::windows::core::Interface for IVssHardwareSnapshotProvider { type Vtable = IVssHardwareSnapshotProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9593a157_44e9_4344_bbeb_44fbf9b06b10); } impl ::core::convert::From<IVssHardwareSnapshotProvider> for ::windows::core::IUnknown { fn from(value: IVssHardwareSnapshotProvider) -> Self { value.0 } } impl ::core::convert::From<&IVssHardwareSnapshotProvider> for ::windows::core::IUnknown { fn from(value: &IVssHardwareSnapshotProvider) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssHardwareSnapshotProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssHardwareSnapshotProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssHardwareSnapshotProvider_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lluncount: i32, lcontext: i32, rgwszdevices: *const *const u16, pluninformation: *mut super::VirtualDiskService::VDS_LUN_INFORMATION, pbissupported: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszdevicename: *const u16, pluninfo: *mut super::VirtualDiskService::VDS_LUN_INFORMATION, pbissupported: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotsetid: ::windows::core::GUID, snapshotid: ::windows::core::GUID, lcontext: i32, lluncount: i32, rgdevicenames: *const *const u16, rgluninformation: *mut super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lluncount: i32, rgdevicenames: *const *const u16, rgsourceluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, rgdestinationluns: *mut super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lluncount: i32, rgsourceluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszdevicename: *const u16, pinformation: *const super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssHardwareSnapshotProviderEx(pub ::windows::core::IUnknown); impl IVssHardwareSnapshotProviderEx { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn AreLunsSupported(&self, lluncount: i32, lcontext: i32, rgwszdevices: *const *const u16, pluninformation: *mut super::VirtualDiskService::VDS_LUN_INFORMATION, pbissupported: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(lluncount), ::core::mem::transmute(lcontext), ::core::mem::transmute(rgwszdevices), ::core::mem::transmute(pluninformation), ::core::mem::transmute(pbissupported)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn FillInLunInfo(&self, wszdevicename: *const u16, pluninfo: *mut super::VirtualDiskService::VDS_LUN_INFORMATION, pbissupported: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(wszdevicename), ::core::mem::transmute(pluninfo), ::core::mem::transmute(pbissupported)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn BeginPrepareSnapshot<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotsetid: Param0, snapshotid: Param1, lcontext: i32, lluncount: i32, rgdevicenames: *const *const u16, rgluninformation: *mut super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), snapshotsetid.into_param().abi(), snapshotid.into_param().abi(), ::core::mem::transmute(lcontext), ::core::mem::transmute(lluncount), ::core::mem::transmute(rgdevicenames), ::core::mem::transmute(rgluninformation)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn GetTargetLuns(&self, lluncount: i32, rgdevicenames: *const *const u16, rgsourceluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, rgdestinationluns: *mut super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(lluncount), ::core::mem::transmute(rgdevicenames), ::core::mem::transmute(rgsourceluns), ::core::mem::transmute(rgdestinationluns)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn LocateLuns(&self, lluncount: i32, rgsourceluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(lluncount), ::core::mem::transmute(rgsourceluns)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn OnLunEmpty(&self, wszdevicename: *const u16, pinformation: *const super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(wszdevicename), ::core::mem::transmute(pinformation)).ok() } pub unsafe fn GetProviderCapabilities(&self) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u64>(result__) } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn OnLunStateChange(&self, psnapshotluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, poriginalluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, dwcount: u32, dwflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(psnapshotluns), ::core::mem::transmute(poriginalluns), ::core::mem::transmute(dwcount), ::core::mem::transmute(dwflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn ResyncLuns(&self, psourceluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, ptargetluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, dwcount: u32) -> ::windows::core::Result<IVssAsync> { let mut result__: <IVssAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(psourceluns), ::core::mem::transmute(ptargetluns), ::core::mem::transmute(dwcount), &mut result__).from_abi::<IVssAsync>(result__) } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe fn OnReuseLuns(&self, psnapshotluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, poriginalluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, dwcount: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(psnapshotluns), ::core::mem::transmute(poriginalluns), ::core::mem::transmute(dwcount)).ok() } } unsafe impl ::windows::core::Interface for IVssHardwareSnapshotProviderEx { type Vtable = IVssHardwareSnapshotProviderEx_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7f5ba925_cdb1_4d11_a71f_339eb7e709fd); } impl ::core::convert::From<IVssHardwareSnapshotProviderEx> for ::windows::core::IUnknown { fn from(value: IVssHardwareSnapshotProviderEx) -> Self { value.0 } } impl ::core::convert::From<&IVssHardwareSnapshotProviderEx> for ::windows::core::IUnknown { fn from(value: &IVssHardwareSnapshotProviderEx) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssHardwareSnapshotProviderEx { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssHardwareSnapshotProviderEx { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IVssHardwareSnapshotProviderEx> for IVssHardwareSnapshotProvider { fn from(value: IVssHardwareSnapshotProviderEx) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IVssHardwareSnapshotProviderEx> for IVssHardwareSnapshotProvider { fn from(value: &IVssHardwareSnapshotProviderEx) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IVssHardwareSnapshotProvider> for IVssHardwareSnapshotProviderEx { fn into_param(self) -> ::windows::core::Param<'a, IVssHardwareSnapshotProvider> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IVssHardwareSnapshotProvider> for &IVssHardwareSnapshotProviderEx { fn into_param(self) -> ::windows::core::Param<'a, IVssHardwareSnapshotProvider> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IVssHardwareSnapshotProviderEx_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lluncount: i32, lcontext: i32, rgwszdevices: *const *const u16, pluninformation: *mut super::VirtualDiskService::VDS_LUN_INFORMATION, pbissupported: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszdevicename: *const u16, pluninfo: *mut super::VirtualDiskService::VDS_LUN_INFORMATION, pbissupported: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotsetid: ::windows::core::GUID, snapshotid: ::windows::core::GUID, lcontext: i32, lluncount: i32, rgdevicenames: *const *const u16, rgluninformation: *mut super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lluncount: i32, rgdevicenames: *const *const u16, rgsourceluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, rgdestinationluns: *mut super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lluncount: i32, rgsourceluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszdevicename: *const u16, pinformation: *const super::VirtualDiskService::VDS_LUN_INFORMATION) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, plloriginalcapabilitymask: *mut u64) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psnapshotluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, poriginalluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, dwcount: u32, dwflags: u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psourceluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, ptargetluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, dwcount: u32, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psnapshotluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, poriginalluns: *const super::VirtualDiskService::VDS_LUN_INFORMATION, dwcount: u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_VirtualDiskService")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssProviderCreateSnapshotSet(pub ::windows::core::IUnknown); impl IVssProviderCreateSnapshotSet { pub unsafe fn EndPrepareSnapshots<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotsetid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), snapshotsetid.into_param().abi()).ok() } pub unsafe fn PreCommitSnapshots<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotsetid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), snapshotsetid.into_param().abi()).ok() } pub unsafe fn CommitSnapshots<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotsetid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), snapshotsetid.into_param().abi()).ok() } pub unsafe fn PostCommitSnapshots<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotsetid: Param0, lsnapshotscount: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), snapshotsetid.into_param().abi(), ::core::mem::transmute(lsnapshotscount)).ok() } pub unsafe fn PreFinalCommitSnapshots<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotsetid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), snapshotsetid.into_param().abi()).ok() } pub unsafe fn PostFinalCommitSnapshots<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotsetid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), snapshotsetid.into_param().abi()).ok() } pub unsafe fn AbortSnapshots<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotsetid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), snapshotsetid.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IVssProviderCreateSnapshotSet { type Vtable = IVssProviderCreateSnapshotSet_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5f894e5b_1e39_4778_8e23_9abad9f0e08c); } impl ::core::convert::From<IVssProviderCreateSnapshotSet> for ::windows::core::IUnknown { fn from(value: IVssProviderCreateSnapshotSet) -> Self { value.0 } } impl ::core::convert::From<&IVssProviderCreateSnapshotSet> for ::windows::core::IUnknown { fn from(value: &IVssProviderCreateSnapshotSet) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssProviderCreateSnapshotSet { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssProviderCreateSnapshotSet { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssProviderCreateSnapshotSet_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, snapshotsetid: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotsetid: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotsetid: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotsetid: ::windows::core::GUID, lsnapshotscount: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotsetid: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotsetid: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotsetid: ::windows::core::GUID) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssProviderNotifications(pub ::windows::core::IUnknown); impl IVssProviderNotifications { pub unsafe fn OnLoad<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, pcallback: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pcallback.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn OnUnload<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, bforceunload: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), bforceunload.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IVssProviderNotifications { type Vtable = IVssProviderNotifications_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe561901f_03a5_4afe_86d0_72baeece7004); } impl ::core::convert::From<IVssProviderNotifications> for ::windows::core::IUnknown { fn from(value: IVssProviderNotifications) -> Self { value.0 } } impl ::core::convert::From<&IVssProviderNotifications> for ::windows::core::IUnknown { fn from(value: &IVssProviderNotifications) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssProviderNotifications { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssProviderNotifications { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssProviderNotifications_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, pcallback: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bforceunload: super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssSnapshotMgmt(pub ::windows::core::IUnknown); impl IVssSnapshotMgmt { pub unsafe fn GetProviderMgmtInterface<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, providerid: Param0, interfaceid: *const ::windows::core::GUID) -> ::windows::core::Result<::windows::core::IUnknown> { let mut result__: <::windows::core::IUnknown as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), providerid.into_param().abi(), ::core::mem::transmute(interfaceid), &mut result__).from_abi::<::windows::core::IUnknown>(result__) } pub unsafe fn QueryVolumesSupportedForSnapshots<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, providerid: Param0, lcontext: i32) -> ::windows::core::Result<IVssEnumMgmtObject> { let mut result__: <IVssEnumMgmtObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), providerid.into_param().abi(), ::core::mem::transmute(lcontext), &mut result__).from_abi::<IVssEnumMgmtObject>(result__) } pub unsafe fn QuerySnapshotsByVolume<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, pwszvolumename: *const u16, providerid: Param1) -> ::windows::core::Result<IVssEnumObject> { let mut result__: <IVssEnumObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), providerid.into_param().abi(), &mut result__).from_abi::<IVssEnumObject>(result__) } } unsafe impl ::windows::core::Interface for IVssSnapshotMgmt { type Vtable = IVssSnapshotMgmt_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfa7df749_66e7_4986_a27f_e2f04ae53772); } impl ::core::convert::From<IVssSnapshotMgmt> for ::windows::core::IUnknown { fn from(value: IVssSnapshotMgmt) -> Self { value.0 } } impl ::core::convert::From<&IVssSnapshotMgmt> for ::windows::core::IUnknown { fn from(value: &IVssSnapshotMgmt) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssSnapshotMgmt { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssSnapshotMgmt { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssSnapshotMgmt_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, providerid: ::windows::core::GUID, interfaceid: *const ::windows::core::GUID, ppitf: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, providerid: ::windows::core::GUID, lcontext: i32, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, providerid: ::windows::core::GUID, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssSnapshotMgmt2(pub ::windows::core::IUnknown); impl IVssSnapshotMgmt2 { pub unsafe fn GetMinDiffAreaSize(&self) -> ::windows::core::Result<i64> { let mut result__: <i64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<i64>(result__) } } unsafe impl ::windows::core::Interface for IVssSnapshotMgmt2 { type Vtable = IVssSnapshotMgmt2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0f61ec39_fe82_45f2_a3f0_768b5d427102); } impl ::core::convert::From<IVssSnapshotMgmt2> for ::windows::core::IUnknown { fn from(value: IVssSnapshotMgmt2) -> Self { value.0 } } impl ::core::convert::From<&IVssSnapshotMgmt2> for ::windows::core::IUnknown { fn from(value: &IVssSnapshotMgmt2) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssSnapshotMgmt2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssSnapshotMgmt2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssSnapshotMgmt2_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, pllmindiffareasize: *mut i64) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssSoftwareSnapshotProvider(pub ::windows::core::IUnknown); impl IVssSoftwareSnapshotProvider { pub unsafe fn SetContext(&self, lcontext: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(lcontext)).ok() } pub unsafe fn GetSnapshotProperties<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotid: Param0) -> ::windows::core::Result<VSS_SNAPSHOT_PROP> { let mut result__: <VSS_SNAPSHOT_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), snapshotid.into_param().abi(), &mut result__).from_abi::<VSS_SNAPSHOT_PROP>(result__) } pub unsafe fn Query<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, queriedobjectid: Param0, equeriedobjecttype: VSS_OBJECT_TYPE, ereturnedobjectstype: VSS_OBJECT_TYPE) -> ::windows::core::Result<IVssEnumObject> { let mut result__: <IVssEnumObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), queriedobjectid.into_param().abi(), ::core::mem::transmute(equeriedobjecttype), ::core::mem::transmute(ereturnedobjectstype), &mut result__).from_abi::<IVssEnumObject>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn DeleteSnapshots<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, sourceobjectid: Param0, esourceobjecttype: VSS_OBJECT_TYPE, bforcedelete: Param2, pldeletedsnapshots: *mut i32, pnondeletedsnapshotid: *mut ::windows::core::GUID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), sourceobjectid.into_param().abi(), ::core::mem::transmute(esourceobjecttype), bforcedelete.into_param().abi(), ::core::mem::transmute(pldeletedsnapshots), ::core::mem::transmute(pnondeletedsnapshotid)).ok() } pub unsafe fn BeginPrepareSnapshot<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotsetid: Param0, snapshotid: Param1, pwszvolumename: *const u16, lnewcontext: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), snapshotsetid.into_param().abi(), snapshotid.into_param().abi(), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(lnewcontext)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn IsVolumeSupported(&self, pwszvolumename: *const u16) -> ::windows::core::Result<super::super::Foundation::BOOL> { let mut result__: <super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), &mut result__).from_abi::<super::super::Foundation::BOOL>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn IsVolumeSnapshotted(&self, pwszvolumename: *const u16, pbsnapshotspresent: *mut super::super::Foundation::BOOL, plsnapshotcompatibility: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolumename), ::core::mem::transmute(pbsnapshotspresent), ::core::mem::transmute(plsnapshotcompatibility)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe fn SetSnapshotProperty<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param2: ::windows::core::IntoParam<'a, super::super::System::Com::VARIANT>>(&self, snapshotid: Param0, esnapshotpropertyid: VSS_SNAPSHOT_PROPERTY_ID, vproperty: Param2) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), snapshotid.into_param().abi(), ::core::mem::transmute(esnapshotpropertyid), vproperty.into_param().abi()).ok() } pub unsafe fn RevertToSnapshot<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, snapshotid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), snapshotid.into_param().abi()).ok() } pub unsafe fn QueryRevertStatus(&self, pwszvolume: *const u16) -> ::windows::core::Result<IVssAsync> { let mut result__: <IVssAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszvolume), &mut result__).from_abi::<IVssAsync>(result__) } } unsafe impl ::windows::core::Interface for IVssSoftwareSnapshotProvider { type Vtable = IVssSoftwareSnapshotProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x609e123e_2c5a_44d3_8f01_0b1d9a47d1ff); } impl ::core::convert::From<IVssSoftwareSnapshotProvider> for ::windows::core::IUnknown { fn from(value: IVssSoftwareSnapshotProvider) -> Self { value.0 } } impl ::core::convert::From<&IVssSoftwareSnapshotProvider> for ::windows::core::IUnknown { fn from(value: &IVssSoftwareSnapshotProvider) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssSoftwareSnapshotProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssSoftwareSnapshotProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssSoftwareSnapshotProvider_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, lcontext: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotid: ::windows::core::GUID, pprop: *mut VSS_SNAPSHOT_PROP) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, queriedobjectid: ::windows::core::GUID, equeriedobjecttype: VSS_OBJECT_TYPE, ereturnedobjectstype: VSS_OBJECT_TYPE, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sourceobjectid: ::windows::core::GUID, esourceobjecttype: VSS_OBJECT_TYPE, bforcedelete: super::super::Foundation::BOOL, pldeletedsnapshots: *mut i32, pnondeletedsnapshotid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotsetid: ::windows::core::GUID, snapshotid: ::windows::core::GUID, pwszvolumename: *const u16, lnewcontext: i32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, pbsupportedbythisprovider: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolumename: *const u16, pbsnapshotspresent: *mut super::super::Foundation::BOOL, plsnapshotcompatibility: *mut i32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotid: ::windows::core::GUID, esnapshotpropertyid: VSS_SNAPSHOT_PROPERTY_ID, vproperty: ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, snapshotid: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszvolume: *const u16, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssWMDependency(pub ::windows::core::IUnknown); impl IVssWMDependency { pub unsafe fn GetWriterId(&self, pwriterid: *mut ::windows::core::GUID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwriterid)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetLogicalPath(&self, pbstrlogicalpath: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrlogicalpath)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetComponentName(&self, pbstrcomponentname: *mut super::super::Foundation::BSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbstrcomponentname)).ok() } } unsafe impl ::windows::core::Interface for IVssWMDependency { type Vtable = IVssWMDependency_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IVssWMDependency> for ::windows::core::IUnknown { fn from(value: IVssWMDependency) -> Self { value.0 } } impl ::core::convert::From<&IVssWMDependency> for ::windows::core::IUnknown { fn from(value: &IVssWMDependency) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssWMDependency { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssWMDependency { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssWMDependency_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, pwriterid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrlogicalpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrcomponentname: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssWMFiledesc(pub ::windows::core::IUnknown); impl IVssWMFiledesc { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPath(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> { let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetFilespec(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> { let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__) } pub unsafe fn GetRecursive(&self) -> ::windows::core::Result<bool> { let mut result__: <bool as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<bool>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetAlternateLocation(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> { let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__) } pub unsafe fn GetBackupTypeMask(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } } unsafe impl ::windows::core::Interface for IVssWMFiledesc { type Vtable = IVssWMFiledesc_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IVssWMFiledesc> for ::windows::core::IUnknown { fn from(value: IVssWMFiledesc) -> Self { value.0 } } impl ::core::convert::From<&IVssWMFiledesc> for ::windows::core::IUnknown { fn from(value: &IVssWMFiledesc) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssWMFiledesc { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssWMFiledesc { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssWMFiledesc_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpath: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrfilespec: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbrecursive: *mut bool) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstralternatelocation: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwtypemask: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssWriterComponents(pub ::windows::core::IUnknown); impl IVssWriterComponents { pub unsafe fn GetComponentCount(&self, pccomponents: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pccomponents)).ok() } pub unsafe fn GetWriterInfo(&self, pidinstance: *mut ::windows::core::GUID, pidwriter: *mut ::windows::core::GUID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pidinstance), ::core::mem::transmute(pidwriter)).ok() } pub unsafe fn GetComponent(&self, icomponent: u32) -> ::windows::core::Result<IVssComponent> { let mut result__: <IVssComponent as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(icomponent), &mut result__).from_abi::<IVssComponent>(result__) } } unsafe impl ::windows::core::Interface for IVssWriterComponents { type Vtable = IVssWriterComponents_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IVssWriterComponents> for ::windows::core::IUnknown { fn from(value: IVssWriterComponents) -> Self { value.0 } } impl ::core::convert::From<&IVssWriterComponents> for ::windows::core::IUnknown { fn from(value: &IVssWriterComponents) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssWriterComponents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssWriterComponents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssWriterComponents_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, pccomponents: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pidinstance: *mut ::windows::core::GUID, pidwriter: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, icomponent: u32, ppcomponent: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVssWriterImpl(pub ::windows::core::IUnknown); impl IVssWriterImpl { #[cfg(feature = "Win32_Foundation")] pub unsafe fn Initialize<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>( &self, writerid: Param0, wszwritername: Param1, wszwriterinstancename: Param2, dwmajorversion: u32, dwminorversion: u32, ut: VSS_USAGE_TYPE, st: VSS_SOURCE_TYPE, nlevel: VSS_APPLICATION_LEVEL, dwtimeout: u32, aws: VSS_ALTERNATE_WRITER_STATE, biothrottlingonly: u8, ) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)( ::core::mem::transmute_copy(self), writerid.into_param().abi(), wszwritername.into_param().abi(), wszwriterinstancename.into_param().abi(), ::core::mem::transmute(dwmajorversion), ::core::mem::transmute(dwminorversion), ::core::mem::transmute(ut), ::core::mem::transmute(st), ::core::mem::transmute(nlevel), ::core::mem::transmute(dwtimeout), ::core::mem::transmute(aws), ::core::mem::transmute(biothrottlingonly), ) .ok() } pub unsafe fn Subscribe(&self, dwsubscribetimeout: u32, dweventflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwsubscribetimeout), ::core::mem::transmute(dweventflags)).ok() } pub unsafe fn Unsubscribe(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Uninitialize(&self) { ::core::mem::transmute((::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self))) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetCurrentVolumeArray(&self) -> *mut super::super::Foundation::PWSTR { ::core::mem::transmute((::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self))) } pub unsafe fn GetCurrentVolumeCount(&self) -> u32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self))) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetSnapshotDeviceName<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszoriginalvolume: Param0) -> ::windows::core::Result<super::super::Foundation::PWSTR> { let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), wszoriginalvolume.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } pub unsafe fn GetCurrentSnapshotSetId(&self) -> ::windows::core::GUID { let mut result__: ::windows::core::GUID = ::core::default::Default::default(); (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), &mut result__); result__ } pub unsafe fn GetContext(&self) -> i32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self))) } pub unsafe fn GetCurrentLevel(&self) -> VSS_APPLICATION_LEVEL { ::core::mem::transmute((::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self))) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn IsPathAffected<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, wszpath: Param0) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), wszpath.into_param().abi())) } pub unsafe fn IsBootableSystemStateBackedUp(&self) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self))) } pub unsafe fn AreComponentsSelected(&self) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self))) } pub unsafe fn GetBackupType(&self) -> VSS_BACKUP_TYPE { ::core::mem::transmute((::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self))) } pub unsafe fn GetRestoreType(&self) -> VSS_RESTORE_TYPE { ::core::mem::transmute((::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self))) } pub unsafe fn SetWriterFailure(&self, hr: ::windows::core::HRESULT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(hr)).ok() } pub unsafe fn IsPartialFileSupportEnabled(&self) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self))) } pub unsafe fn InstallAlternateWriter<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, idwriter: Param0, clsid: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), idwriter.into_param().abi(), clsid.into_param().abi()).ok() } pub unsafe fn GetIdentityInformation(&self) -> *mut IVssExamineWriterMetadata { ::core::mem::transmute((::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self))) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetWriterFailureEx<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, hr: ::windows::core::HRESULT, hrapplication: ::windows::core::HRESULT, wszapplicationmessage: Param2) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), ::core::mem::transmute(hr), ::core::mem::transmute(hrapplication), wszapplicationmessage.into_param().abi()).ok() } pub unsafe fn GetSessionId(&self) -> ::windows::core::Result<::windows::core::GUID> { let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).23)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::GUID>(result__) } pub unsafe fn IsWriterShuttingDown(&self) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).24)(::core::mem::transmute_copy(self))) } } unsafe impl ::windows::core::Interface for IVssWriterImpl { type Vtable = IVssWriterImpl_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IVssWriterImpl> for ::windows::core::IUnknown { fn from(value: IVssWriterImpl) -> Self { value.0 } } impl ::core::convert::From<&IVssWriterImpl> for ::windows::core::IUnknown { fn from(value: &IVssWriterImpl) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVssWriterImpl { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVssWriterImpl { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVssWriterImpl_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, writerid: ::windows::core::GUID, wszwritername: super::super::Foundation::PWSTR, wszwriterinstancename: super::super::Foundation::PWSTR, dwmajorversion: u32, dwminorversion: u32, ut: VSS_USAGE_TYPE, st: VSS_SOURCE_TYPE, nlevel: VSS_APPLICATION_LEVEL, dwtimeout: u32, aws: VSS_ALTERNATE_WRITER_STATE, biothrottlingonly: u8) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwsubscribetimeout: u32, dweventflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr), #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> *mut super::super::Foundation::PWSTR, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszoriginalvolume: super::super::Foundation::PWSTR, ppwszsnapshotdevice: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID), pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> i32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> VSS_APPLICATION_LEVEL, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, wszpath: super::super::Foundation::PWSTR) -> bool, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> VSS_BACKUP_TYPE, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> VSS_RESTORE_TYPE, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hr: ::windows::core::HRESULT) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, idwriter: ::windows::core::GUID, clsid: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> *mut IVssExamineWriterMetadata, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hr: ::windows::core::HRESULT, hrapplication: ::windows::core::HRESULT, wszapplicationmessage: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, idsession: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> bool, ); pub const VSSCoordinator: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe579ab5f_1cc4_44b4_bed9_de0991ff0623); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_ALTERNATE_WRITER_STATE(pub i32); pub const VSS_AWS_UNDEFINED: VSS_ALTERNATE_WRITER_STATE = VSS_ALTERNATE_WRITER_STATE(0i32); pub const VSS_AWS_NO_ALTERNATE_WRITER: VSS_ALTERNATE_WRITER_STATE = VSS_ALTERNATE_WRITER_STATE(1i32); pub const VSS_AWS_ALTERNATE_WRITER_EXISTS: VSS_ALTERNATE_WRITER_STATE = VSS_ALTERNATE_WRITER_STATE(2i32); pub const VSS_AWS_THIS_IS_ALTERNATE_WRITER: VSS_ALTERNATE_WRITER_STATE = VSS_ALTERNATE_WRITER_STATE(3i32); impl ::core::convert::From<i32> for VSS_ALTERNATE_WRITER_STATE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_ALTERNATE_WRITER_STATE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_APPLICATION_LEVEL(pub i32); pub const VSS_APP_UNKNOWN: VSS_APPLICATION_LEVEL = VSS_APPLICATION_LEVEL(0i32); pub const VSS_APP_SYSTEM: VSS_APPLICATION_LEVEL = VSS_APPLICATION_LEVEL(1i32); pub const VSS_APP_BACK_END: VSS_APPLICATION_LEVEL = VSS_APPLICATION_LEVEL(2i32); pub const VSS_APP_FRONT_END: VSS_APPLICATION_LEVEL = VSS_APPLICATION_LEVEL(3i32); pub const VSS_APP_SYSTEM_RM: VSS_APPLICATION_LEVEL = VSS_APPLICATION_LEVEL(4i32); pub const VSS_APP_AUTO: VSS_APPLICATION_LEVEL = VSS_APPLICATION_LEVEL(-1i32); impl ::core::convert::From<i32> for VSS_APPLICATION_LEVEL { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_APPLICATION_LEVEL { type Abi = Self; } pub const VSS_ASSOC_NO_MAX_SPACE: i32 = -1i32; pub const VSS_ASSOC_REMOVE: u32 = 0u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_BACKUP_SCHEMA(pub i32); pub const VSS_BS_UNDEFINED: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(0i32); pub const VSS_BS_DIFFERENTIAL: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(1i32); pub const VSS_BS_INCREMENTAL: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(2i32); pub const VSS_BS_EXCLUSIVE_INCREMENTAL_DIFFERENTIAL: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(4i32); pub const VSS_BS_LOG: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(8i32); pub const VSS_BS_COPY: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(16i32); pub const VSS_BS_TIMESTAMPED: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(32i32); pub const VSS_BS_LAST_MODIFY: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(64i32); pub const VSS_BS_LSN: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(128i32); pub const VSS_BS_WRITER_SUPPORTS_NEW_TARGET: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(256i32); pub const VSS_BS_WRITER_SUPPORTS_RESTORE_WITH_MOVE: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(512i32); pub const VSS_BS_INDEPENDENT_SYSTEM_STATE: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(1024i32); pub const VSS_BS_ROLLFORWARD_RESTORE: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(4096i32); pub const VSS_BS_RESTORE_RENAME: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(8192i32); pub const VSS_BS_AUTHORITATIVE_RESTORE: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(16384i32); pub const VSS_BS_WRITER_SUPPORTS_PARALLEL_RESTORES: VSS_BACKUP_SCHEMA = VSS_BACKUP_SCHEMA(32768i32); impl ::core::convert::From<i32> for VSS_BACKUP_SCHEMA { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_BACKUP_SCHEMA { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_BACKUP_TYPE(pub i32); pub const VSS_BT_UNDEFINED: VSS_BACKUP_TYPE = VSS_BACKUP_TYPE(0i32); pub const VSS_BT_FULL: VSS_BACKUP_TYPE = VSS_BACKUP_TYPE(1i32); pub const VSS_BT_INCREMENTAL: VSS_BACKUP_TYPE = VSS_BACKUP_TYPE(2i32); pub const VSS_BT_DIFFERENTIAL: VSS_BACKUP_TYPE = VSS_BACKUP_TYPE(3i32); pub const VSS_BT_LOG: VSS_BACKUP_TYPE = VSS_BACKUP_TYPE(4i32); pub const VSS_BT_COPY: VSS_BACKUP_TYPE = VSS_BACKUP_TYPE(5i32); pub const VSS_BT_OTHER: VSS_BACKUP_TYPE = VSS_BACKUP_TYPE(6i32); impl ::core::convert::From<i32> for VSS_BACKUP_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_BACKUP_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_COMPONENT_FLAGS(pub i32); pub const VSS_CF_BACKUP_RECOVERY: VSS_COMPONENT_FLAGS = VSS_COMPONENT_FLAGS(1i32); pub const VSS_CF_APP_ROLLBACK_RECOVERY: VSS_COMPONENT_FLAGS = VSS_COMPONENT_FLAGS(2i32); pub const VSS_CF_NOT_SYSTEM_STATE: VSS_COMPONENT_FLAGS = VSS_COMPONENT_FLAGS(4i32); impl ::core::convert::From<i32> for VSS_COMPONENT_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_COMPONENT_FLAGS { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_COMPONENT_TYPE(pub i32); pub const VSS_CT_UNDEFINED: VSS_COMPONENT_TYPE = VSS_COMPONENT_TYPE(0i32); pub const VSS_CT_DATABASE: VSS_COMPONENT_TYPE = VSS_COMPONENT_TYPE(1i32); pub const VSS_CT_FILEGROUP: VSS_COMPONENT_TYPE = VSS_COMPONENT_TYPE(2i32); impl ::core::convert::From<i32> for VSS_COMPONENT_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_COMPONENT_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VSS_DIFF_AREA_PROP { pub m_pwszVolumeName: *mut u16, pub m_pwszDiffAreaVolumeName: *mut u16, pub m_llMaximumDiffSpace: i64, pub m_llAllocatedDiffSpace: i64, pub m_llUsedDiffSpace: i64, } impl VSS_DIFF_AREA_PROP {} impl ::core::default::Default for VSS_DIFF_AREA_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VSS_DIFF_AREA_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VSS_DIFF_AREA_PROP") .field("m_pwszVolumeName", &self.m_pwszVolumeName) .field("m_pwszDiffAreaVolumeName", &self.m_pwszDiffAreaVolumeName) .field("m_llMaximumDiffSpace", &self.m_llMaximumDiffSpace) .field("m_llAllocatedDiffSpace", &self.m_llAllocatedDiffSpace) .field("m_llUsedDiffSpace", &self.m_llUsedDiffSpace) .finish() } } impl ::core::cmp::PartialEq for VSS_DIFF_AREA_PROP { fn eq(&self, other: &Self) -> bool { self.m_pwszVolumeName == other.m_pwszVolumeName && self.m_pwszDiffAreaVolumeName == other.m_pwszDiffAreaVolumeName && self.m_llMaximumDiffSpace == other.m_llMaximumDiffSpace && self.m_llAllocatedDiffSpace == other.m_llAllocatedDiffSpace && self.m_llUsedDiffSpace == other.m_llUsedDiffSpace } } impl ::core::cmp::Eq for VSS_DIFF_AREA_PROP {} unsafe impl ::windows::core::Abi for VSS_DIFF_AREA_PROP { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VSS_DIFF_VOLUME_PROP { pub m_pwszVolumeName: *mut u16, pub m_pwszVolumeDisplayName: *mut u16, pub m_llVolumeFreeSpace: i64, pub m_llVolumeTotalSpace: i64, } impl VSS_DIFF_VOLUME_PROP {} impl ::core::default::Default for VSS_DIFF_VOLUME_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VSS_DIFF_VOLUME_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VSS_DIFF_VOLUME_PROP").field("m_pwszVolumeName", &self.m_pwszVolumeName).field("m_pwszVolumeDisplayName", &self.m_pwszVolumeDisplayName).field("m_llVolumeFreeSpace", &self.m_llVolumeFreeSpace).field("m_llVolumeTotalSpace", &self.m_llVolumeTotalSpace).finish() } } impl ::core::cmp::PartialEq for VSS_DIFF_VOLUME_PROP { fn eq(&self, other: &Self) -> bool { self.m_pwszVolumeName == other.m_pwszVolumeName && self.m_pwszVolumeDisplayName == other.m_pwszVolumeDisplayName && self.m_llVolumeFreeSpace == other.m_llVolumeFreeSpace && self.m_llVolumeTotalSpace == other.m_llVolumeTotalSpace } } impl ::core::cmp::Eq for VSS_DIFF_VOLUME_PROP {} unsafe impl ::windows::core::Abi for VSS_DIFF_VOLUME_PROP { type Abi = Self; } pub const VSS_E_ASRERROR_CRITICAL_DISKS_TOO_SMALL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212280i32 as _); pub const VSS_E_ASRERROR_CRITICAL_DISK_CANNOT_BE_EXCLUDED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212267i32 as _); pub const VSS_E_ASRERROR_DATADISK_RDISK0: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212282i32 as _); pub const VSS_E_ASRERROR_DISK_ASSIGNMENT_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212287i32 as _); pub const VSS_E_ASRERROR_DISK_RECREATION_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212286i32 as _); pub const VSS_E_ASRERROR_DYNAMIC_VHD_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212278i32 as _); pub const VSS_E_ASRERROR_FIXED_PHYSICAL_DISK_AVAILABLE_AFTER_DISK_EXCLUSION: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212268i32 as _); pub const VSS_E_ASRERROR_MISSING_DYNDISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212284i32 as _); pub const VSS_E_ASRERROR_NO_ARCPATH: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212285i32 as _); pub const VSS_E_ASRERROR_NO_PHYSICAL_DISK_AVAILABLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212269i32 as _); pub const VSS_E_ASRERROR_RDISK0_TOOSMALL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212281i32 as _); pub const VSS_E_ASRERROR_RDISK_FOR_SYSTEM_DISK_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212270i32 as _); pub const VSS_E_ASRERROR_SHARED_CRIDISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212283i32 as _); pub const VSS_E_ASRERROR_SYSTEM_PARTITION_HIDDEN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212266i32 as _); pub const VSS_E_AUTORECOVERY_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212293i32 as _); pub const VSS_E_BAD_STATE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212543i32 as _); pub const VSS_E_BREAK_REVERT_ID_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212298i32 as _); pub const VSS_E_CANNOT_REVERT_DISKID: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212290i32 as _); pub const VSS_E_CLUSTER_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212288i32 as _); pub const VSS_E_CLUSTER_TIMEOUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212498i32 as _); pub const VSS_E_CORRUPT_XML_DOCUMENT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212528i32 as _); pub const VSS_E_CRITICAL_VOLUME_ON_INVALID_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212271i32 as _); pub const VSS_E_DYNAMIC_DISK_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212292i32 as _); pub const VSS_E_FLUSH_WRITES_TIMEOUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212525i32 as _); pub const VSS_E_FSS_TIMEOUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212265i32 as _); pub const VSS_E_HOLD_WRITES_TIMEOUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212524i32 as _); pub const VSS_E_INSUFFICIENT_STORAGE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212513i32 as _); pub const VSS_E_INVALID_XML_DOCUMENT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212527i32 as _); pub const VSS_E_LEGACY_PROVIDER: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212297i32 as _); pub const VSS_E_MAXIMUM_DIFFAREA_ASSOCIATIONS_REACHED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212514i32 as _); pub const VSS_E_MAXIMUM_NUMBER_OF_REMOTE_MACHINES_REACHED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212510i32 as _); pub const VSS_E_MAXIMUM_NUMBER_OF_SNAPSHOTS_REACHED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212521i32 as _); pub const VSS_E_MAXIMUM_NUMBER_OF_VOLUMES_REACHED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212526i32 as _); pub const VSS_E_MISSING_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212296i32 as _); pub const VSS_E_MISSING_HIDDEN_VOLUME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212295i32 as _); pub const VSS_E_MISSING_VOLUME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212294i32 as _); pub const VSS_E_NESTED_VOLUME_LIMIT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212500i32 as _); pub const VSS_E_NONTRANSPORTABLE_BCD: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212291i32 as _); pub const VSS_E_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212497i32 as _); pub const VSS_E_NO_SNAPSHOTS_IMPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212512i32 as _); pub const VSS_E_OBJECT_ALREADY_EXISTS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212531i32 as _); pub const VSS_E_OBJECT_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212536i32 as _); pub const VSS_E_PROVIDER_ALREADY_REGISTERED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212541i32 as _); pub const VSS_E_PROVIDER_IN_USE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212537i32 as _); pub const VSS_E_PROVIDER_NOT_REGISTERED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212540i32 as _); pub const VSS_E_PROVIDER_VETO: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212538i32 as _); pub const VSS_E_REBOOT_REQUIRED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212505i32 as _); pub const VSS_E_REMOTE_SERVER_UNAVAILABLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212509i32 as _); pub const VSS_E_REMOTE_SERVER_UNSUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212508i32 as _); pub const VSS_E_RESYNC_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212289i32 as _); pub const VSS_E_REVERT_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212507i32 as _); pub const VSS_E_REVERT_VOLUME_LOST: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212506i32 as _); pub const VSS_E_SNAPSHOT_NOT_IN_SET: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212501i32 as _); pub const VSS_E_SNAPSHOT_SET_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212522i32 as _); pub const VSS_E_SOME_SNAPSHOTS_NOT_IMPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212511i32 as _); pub const VSS_E_TRANSACTION_FREEZE_TIMEOUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212504i32 as _); pub const VSS_E_TRANSACTION_THAW_TIMEOUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212503i32 as _); pub const VSS_E_UNEXPECTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212542i32 as _); pub const VSS_E_UNEXPECTED_PROVIDER_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212529i32 as _); pub const VSS_E_UNEXPECTED_WRITER_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212523i32 as _); pub const VSS_E_UNSELECTED_VOLUME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212502i32 as _); pub const VSS_E_UNSUPPORTED_CONTEXT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212517i32 as _); pub const VSS_E_VOLUME_IN_USE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212515i32 as _); pub const VSS_E_VOLUME_NOT_LOCAL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212499i32 as _); pub const VSS_E_VOLUME_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212532i32 as _); pub const VSS_E_VOLUME_NOT_SUPPORTED_BY_PROVIDER: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212530i32 as _); pub const VSS_E_WRITERERROR_INCONSISTENTSNAPSHOT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212304i32 as _); pub const VSS_E_WRITERERROR_NONRETRYABLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212300i32 as _); pub const VSS_E_WRITERERROR_OUTOFRESOURCES: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212303i32 as _); pub const VSS_E_WRITERERROR_PARTIAL_FAILURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212490i32 as _); pub const VSS_E_WRITERERROR_RECOVERY_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212299i32 as _); pub const VSS_E_WRITERERROR_RETRYABLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212301i32 as _); pub const VSS_E_WRITERERROR_TIMEOUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212302i32 as _); pub const VSS_E_WRITER_ALREADY_SUBSCRIBED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212518i32 as _); pub const VSS_E_WRITER_INFRASTRUCTURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212520i32 as _); pub const VSS_E_WRITER_NOT_RESPONDING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212519i32 as _); pub const VSS_E_WRITER_STATUS_NOT_AVAILABLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212279i32 as _); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_FILE_RESTORE_STATUS(pub i32); pub const VSS_RS_UNDEFINED: VSS_FILE_RESTORE_STATUS = VSS_FILE_RESTORE_STATUS(0i32); pub const VSS_RS_NONE: VSS_FILE_RESTORE_STATUS = VSS_FILE_RESTORE_STATUS(1i32); pub const VSS_RS_ALL: VSS_FILE_RESTORE_STATUS = VSS_FILE_RESTORE_STATUS(2i32); pub const VSS_RS_FAILED: VSS_FILE_RESTORE_STATUS = VSS_FILE_RESTORE_STATUS(3i32); impl ::core::convert::From<i32> for VSS_FILE_RESTORE_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_FILE_RESTORE_STATUS { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_FILE_SPEC_BACKUP_TYPE(pub i32); pub const VSS_FSBT_FULL_BACKUP_REQUIRED: VSS_FILE_SPEC_BACKUP_TYPE = VSS_FILE_SPEC_BACKUP_TYPE(1i32); pub const VSS_FSBT_DIFFERENTIAL_BACKUP_REQUIRED: VSS_FILE_SPEC_BACKUP_TYPE = VSS_FILE_SPEC_BACKUP_TYPE(2i32); pub const VSS_FSBT_INCREMENTAL_BACKUP_REQUIRED: VSS_FILE_SPEC_BACKUP_TYPE = VSS_FILE_SPEC_BACKUP_TYPE(4i32); pub const VSS_FSBT_LOG_BACKUP_REQUIRED: VSS_FILE_SPEC_BACKUP_TYPE = VSS_FILE_SPEC_BACKUP_TYPE(8i32); pub const VSS_FSBT_FULL_SNAPSHOT_REQUIRED: VSS_FILE_SPEC_BACKUP_TYPE = VSS_FILE_SPEC_BACKUP_TYPE(256i32); pub const VSS_FSBT_DIFFERENTIAL_SNAPSHOT_REQUIRED: VSS_FILE_SPEC_BACKUP_TYPE = VSS_FILE_SPEC_BACKUP_TYPE(512i32); pub const VSS_FSBT_INCREMENTAL_SNAPSHOT_REQUIRED: VSS_FILE_SPEC_BACKUP_TYPE = VSS_FILE_SPEC_BACKUP_TYPE(1024i32); pub const VSS_FSBT_LOG_SNAPSHOT_REQUIRED: VSS_FILE_SPEC_BACKUP_TYPE = VSS_FILE_SPEC_BACKUP_TYPE(2048i32); pub const VSS_FSBT_CREATED_DURING_BACKUP: VSS_FILE_SPEC_BACKUP_TYPE = VSS_FILE_SPEC_BACKUP_TYPE(65536i32); pub const VSS_FSBT_ALL_BACKUP_REQUIRED: VSS_FILE_SPEC_BACKUP_TYPE = VSS_FILE_SPEC_BACKUP_TYPE(15i32); pub const VSS_FSBT_ALL_SNAPSHOT_REQUIRED: VSS_FILE_SPEC_BACKUP_TYPE = VSS_FILE_SPEC_BACKUP_TYPE(3840i32); impl ::core::convert::From<i32> for VSS_FILE_SPEC_BACKUP_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_FILE_SPEC_BACKUP_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_HARDWARE_OPTIONS(pub i32); pub const VSS_BREAKEX_FLAG_MASK_LUNS: VSS_HARDWARE_OPTIONS = VSS_HARDWARE_OPTIONS(1i32); pub const VSS_BREAKEX_FLAG_MAKE_READ_WRITE: VSS_HARDWARE_OPTIONS = VSS_HARDWARE_OPTIONS(2i32); pub const VSS_BREAKEX_FLAG_REVERT_IDENTITY_ALL: VSS_HARDWARE_OPTIONS = VSS_HARDWARE_OPTIONS(4i32); pub const VSS_BREAKEX_FLAG_REVERT_IDENTITY_NONE: VSS_HARDWARE_OPTIONS = VSS_HARDWARE_OPTIONS(8i32); pub const VSS_ONLUNSTATECHANGE_NOTIFY_READ_WRITE: VSS_HARDWARE_OPTIONS = VSS_HARDWARE_OPTIONS(256i32); pub const VSS_ONLUNSTATECHANGE_NOTIFY_LUN_PRE_RECOVERY: VSS_HARDWARE_OPTIONS = VSS_HARDWARE_OPTIONS(512i32); pub const VSS_ONLUNSTATECHANGE_NOTIFY_LUN_POST_RECOVERY: VSS_HARDWARE_OPTIONS = VSS_HARDWARE_OPTIONS(1024i32); pub const VSS_ONLUNSTATECHANGE_DO_MASK_LUNS: VSS_HARDWARE_OPTIONS = VSS_HARDWARE_OPTIONS(2048i32); impl ::core::convert::From<i32> for VSS_HARDWARE_OPTIONS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_HARDWARE_OPTIONS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VSS_MGMT_OBJECT_PROP { pub Type: VSS_MGMT_OBJECT_TYPE, pub Obj: VSS_MGMT_OBJECT_UNION, } impl VSS_MGMT_OBJECT_PROP {} impl ::core::default::Default for VSS_MGMT_OBJECT_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VSS_MGMT_OBJECT_PROP { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VSS_MGMT_OBJECT_PROP {} unsafe impl ::windows::core::Abi for VSS_MGMT_OBJECT_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_MGMT_OBJECT_TYPE(pub i32); pub const VSS_MGMT_OBJECT_UNKNOWN: VSS_MGMT_OBJECT_TYPE = VSS_MGMT_OBJECT_TYPE(0i32); pub const VSS_MGMT_OBJECT_VOLUME: VSS_MGMT_OBJECT_TYPE = VSS_MGMT_OBJECT_TYPE(1i32); pub const VSS_MGMT_OBJECT_DIFF_VOLUME: VSS_MGMT_OBJECT_TYPE = VSS_MGMT_OBJECT_TYPE(2i32); pub const VSS_MGMT_OBJECT_DIFF_AREA: VSS_MGMT_OBJECT_TYPE = VSS_MGMT_OBJECT_TYPE(3i32); impl ::core::convert::From<i32> for VSS_MGMT_OBJECT_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_MGMT_OBJECT_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub union VSS_MGMT_OBJECT_UNION { pub Vol: VSS_VOLUME_PROP, pub DiffVol: VSS_DIFF_VOLUME_PROP, pub DiffArea: VSS_DIFF_AREA_PROP, } impl VSS_MGMT_OBJECT_UNION {} impl ::core::default::Default for VSS_MGMT_OBJECT_UNION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VSS_MGMT_OBJECT_UNION { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VSS_MGMT_OBJECT_UNION {} unsafe impl ::windows::core::Abi for VSS_MGMT_OBJECT_UNION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VSS_OBJECT_PROP { pub Type: VSS_OBJECT_TYPE, pub Obj: VSS_OBJECT_UNION, } impl VSS_OBJECT_PROP {} impl ::core::default::Default for VSS_OBJECT_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VSS_OBJECT_PROP { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VSS_OBJECT_PROP {} unsafe impl ::windows::core::Abi for VSS_OBJECT_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_OBJECT_TYPE(pub i32); pub const VSS_OBJECT_UNKNOWN: VSS_OBJECT_TYPE = VSS_OBJECT_TYPE(0i32); pub const VSS_OBJECT_NONE: VSS_OBJECT_TYPE = VSS_OBJECT_TYPE(1i32); pub const VSS_OBJECT_SNAPSHOT_SET: VSS_OBJECT_TYPE = VSS_OBJECT_TYPE(2i32); pub const VSS_OBJECT_SNAPSHOT: VSS_OBJECT_TYPE = VSS_OBJECT_TYPE(3i32); pub const VSS_OBJECT_PROVIDER: VSS_OBJECT_TYPE = VSS_OBJECT_TYPE(4i32); pub const VSS_OBJECT_TYPE_COUNT: VSS_OBJECT_TYPE = VSS_OBJECT_TYPE(5i32); impl ::core::convert::From<i32> for VSS_OBJECT_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_OBJECT_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub union VSS_OBJECT_UNION { pub Snap: VSS_SNAPSHOT_PROP, pub Prov: VSS_PROVIDER_PROP, } impl VSS_OBJECT_UNION {} impl ::core::default::Default for VSS_OBJECT_UNION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VSS_OBJECT_UNION { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VSS_OBJECT_UNION {} unsafe impl ::windows::core::Abi for VSS_OBJECT_UNION { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_PROTECTION_FAULT(pub i32); pub const VSS_PROTECTION_FAULT_NONE: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(0i32); pub const VSS_PROTECTION_FAULT_DIFF_AREA_MISSING: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(1i32); pub const VSS_PROTECTION_FAULT_IO_FAILURE_DURING_ONLINE: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(2i32); pub const VSS_PROTECTION_FAULT_META_DATA_CORRUPTION: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(3i32); pub const VSS_PROTECTION_FAULT_MEMORY_ALLOCATION_FAILURE: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(4i32); pub const VSS_PROTECTION_FAULT_MAPPED_MEMORY_FAILURE: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(5i32); pub const VSS_PROTECTION_FAULT_COW_READ_FAILURE: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(6i32); pub const VSS_PROTECTION_FAULT_COW_WRITE_FAILURE: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(7i32); pub const VSS_PROTECTION_FAULT_DIFF_AREA_FULL: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(8i32); pub const VSS_PROTECTION_FAULT_GROW_TOO_SLOW: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(9i32); pub const VSS_PROTECTION_FAULT_GROW_FAILED: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(10i32); pub const VSS_PROTECTION_FAULT_DESTROY_ALL_SNAPSHOTS: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(11i32); pub const VSS_PROTECTION_FAULT_FILE_SYSTEM_FAILURE: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(12i32); pub const VSS_PROTECTION_FAULT_IO_FAILURE: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(13i32); pub const VSS_PROTECTION_FAULT_DIFF_AREA_REMOVED: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(14i32); pub const VSS_PROTECTION_FAULT_EXTERNAL_WRITER_TO_DIFF_AREA: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(15i32); pub const VSS_PROTECTION_FAULT_MOUNT_DURING_CLUSTER_OFFLINE: VSS_PROTECTION_FAULT = VSS_PROTECTION_FAULT(16i32); impl ::core::convert::From<i32> for VSS_PROTECTION_FAULT { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_PROTECTION_FAULT { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_PROTECTION_LEVEL(pub i32); pub const VSS_PROTECTION_LEVEL_ORIGINAL_VOLUME: VSS_PROTECTION_LEVEL = VSS_PROTECTION_LEVEL(0i32); pub const VSS_PROTECTION_LEVEL_SNAPSHOT: VSS_PROTECTION_LEVEL = VSS_PROTECTION_LEVEL(1i32); impl ::core::convert::From<i32> for VSS_PROTECTION_LEVEL { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_PROTECTION_LEVEL { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_PROVIDER_CAPABILITIES(pub i32); pub const VSS_PRV_CAPABILITY_LEGACY: VSS_PROVIDER_CAPABILITIES = VSS_PROVIDER_CAPABILITIES(1i32); pub const VSS_PRV_CAPABILITY_COMPLIANT: VSS_PROVIDER_CAPABILITIES = VSS_PROVIDER_CAPABILITIES(2i32); pub const VSS_PRV_CAPABILITY_LUN_REPOINT: VSS_PROVIDER_CAPABILITIES = VSS_PROVIDER_CAPABILITIES(4i32); pub const VSS_PRV_CAPABILITY_LUN_RESYNC: VSS_PROVIDER_CAPABILITIES = VSS_PROVIDER_CAPABILITIES(8i32); pub const VSS_PRV_CAPABILITY_OFFLINE_CREATION: VSS_PROVIDER_CAPABILITIES = VSS_PROVIDER_CAPABILITIES(16i32); pub const VSS_PRV_CAPABILITY_MULTIPLE_IMPORT: VSS_PROVIDER_CAPABILITIES = VSS_PROVIDER_CAPABILITIES(32i32); pub const VSS_PRV_CAPABILITY_RECYCLING: VSS_PROVIDER_CAPABILITIES = VSS_PROVIDER_CAPABILITIES(64i32); pub const VSS_PRV_CAPABILITY_PLEX: VSS_PROVIDER_CAPABILITIES = VSS_PROVIDER_CAPABILITIES(128i32); pub const VSS_PRV_CAPABILITY_DIFFERENTIAL: VSS_PROVIDER_CAPABILITIES = VSS_PROVIDER_CAPABILITIES(256i32); pub const VSS_PRV_CAPABILITY_CLUSTERED: VSS_PROVIDER_CAPABILITIES = VSS_PROVIDER_CAPABILITIES(512i32); impl ::core::convert::From<i32> for VSS_PROVIDER_CAPABILITIES { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_PROVIDER_CAPABILITIES { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VSS_PROVIDER_PROP { pub m_ProviderId: ::windows::core::GUID, pub m_pwszProviderName: *mut u16, pub m_eProviderType: VSS_PROVIDER_TYPE, pub m_pwszProviderVersion: *mut u16, pub m_ProviderVersionId: ::windows::core::GUID, pub m_ClassId: ::windows::core::GUID, } impl VSS_PROVIDER_PROP {} impl ::core::default::Default for VSS_PROVIDER_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VSS_PROVIDER_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VSS_PROVIDER_PROP") .field("m_ProviderId", &self.m_ProviderId) .field("m_pwszProviderName", &self.m_pwszProviderName) .field("m_eProviderType", &self.m_eProviderType) .field("m_pwszProviderVersion", &self.m_pwszProviderVersion) .field("m_ProviderVersionId", &self.m_ProviderVersionId) .field("m_ClassId", &self.m_ClassId) .finish() } } impl ::core::cmp::PartialEq for VSS_PROVIDER_PROP { fn eq(&self, other: &Self) -> bool { self.m_ProviderId == other.m_ProviderId && self.m_pwszProviderName == other.m_pwszProviderName && self.m_eProviderType == other.m_eProviderType && self.m_pwszProviderVersion == other.m_pwszProviderVersion && self.m_ProviderVersionId == other.m_ProviderVersionId && self.m_ClassId == other.m_ClassId } } impl ::core::cmp::Eq for VSS_PROVIDER_PROP {} unsafe impl ::windows::core::Abi for VSS_PROVIDER_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_PROVIDER_TYPE(pub i32); pub const VSS_PROV_UNKNOWN: VSS_PROVIDER_TYPE = VSS_PROVIDER_TYPE(0i32); pub const VSS_PROV_SYSTEM: VSS_PROVIDER_TYPE = VSS_PROVIDER_TYPE(1i32); pub const VSS_PROV_SOFTWARE: VSS_PROVIDER_TYPE = VSS_PROVIDER_TYPE(2i32); pub const VSS_PROV_HARDWARE: VSS_PROVIDER_TYPE = VSS_PROVIDER_TYPE(3i32); pub const VSS_PROV_FILESHARE: VSS_PROVIDER_TYPE = VSS_PROVIDER_TYPE(4i32); impl ::core::convert::From<i32> for VSS_PROVIDER_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_PROVIDER_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_RECOVERY_OPTIONS(pub i32); pub const VSS_RECOVERY_REVERT_IDENTITY_ALL: VSS_RECOVERY_OPTIONS = VSS_RECOVERY_OPTIONS(256i32); pub const VSS_RECOVERY_NO_VOLUME_CHECK: VSS_RECOVERY_OPTIONS = VSS_RECOVERY_OPTIONS(512i32); impl ::core::convert::From<i32> for VSS_RECOVERY_OPTIONS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_RECOVERY_OPTIONS { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_RESTOREMETHOD_ENUM(pub i32); pub const VSS_RME_UNDEFINED: VSS_RESTOREMETHOD_ENUM = VSS_RESTOREMETHOD_ENUM(0i32); pub const VSS_RME_RESTORE_IF_NOT_THERE: VSS_RESTOREMETHOD_ENUM = VSS_RESTOREMETHOD_ENUM(1i32); pub const VSS_RME_RESTORE_IF_CAN_REPLACE: VSS_RESTOREMETHOD_ENUM = VSS_RESTOREMETHOD_ENUM(2i32); pub const VSS_RME_STOP_RESTORE_START: VSS_RESTOREMETHOD_ENUM = VSS_RESTOREMETHOD_ENUM(3i32); pub const VSS_RME_RESTORE_TO_ALTERNATE_LOCATION: VSS_RESTOREMETHOD_ENUM = VSS_RESTOREMETHOD_ENUM(4i32); pub const VSS_RME_RESTORE_AT_REBOOT: VSS_RESTOREMETHOD_ENUM = VSS_RESTOREMETHOD_ENUM(5i32); pub const VSS_RME_RESTORE_AT_REBOOT_IF_CANNOT_REPLACE: VSS_RESTOREMETHOD_ENUM = VSS_RESTOREMETHOD_ENUM(6i32); pub const VSS_RME_CUSTOM: VSS_RESTOREMETHOD_ENUM = VSS_RESTOREMETHOD_ENUM(7i32); pub const VSS_RME_RESTORE_STOP_START: VSS_RESTOREMETHOD_ENUM = VSS_RESTOREMETHOD_ENUM(8i32); impl ::core::convert::From<i32> for VSS_RESTOREMETHOD_ENUM { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_RESTOREMETHOD_ENUM { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_RESTORE_TARGET(pub i32); pub const VSS_RT_UNDEFINED: VSS_RESTORE_TARGET = VSS_RESTORE_TARGET(0i32); pub const VSS_RT_ORIGINAL: VSS_RESTORE_TARGET = VSS_RESTORE_TARGET(1i32); pub const VSS_RT_ALTERNATE: VSS_RESTORE_TARGET = VSS_RESTORE_TARGET(2i32); pub const VSS_RT_DIRECTED: VSS_RESTORE_TARGET = VSS_RESTORE_TARGET(3i32); pub const VSS_RT_ORIGINAL_LOCATION: VSS_RESTORE_TARGET = VSS_RESTORE_TARGET(4i32); impl ::core::convert::From<i32> for VSS_RESTORE_TARGET { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_RESTORE_TARGET { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_RESTORE_TYPE(pub i32); pub const VSS_RTYPE_UNDEFINED: VSS_RESTORE_TYPE = VSS_RESTORE_TYPE(0i32); pub const VSS_RTYPE_BY_COPY: VSS_RESTORE_TYPE = VSS_RESTORE_TYPE(1i32); pub const VSS_RTYPE_IMPORT: VSS_RESTORE_TYPE = VSS_RESTORE_TYPE(2i32); pub const VSS_RTYPE_OTHER: VSS_RESTORE_TYPE = VSS_RESTORE_TYPE(3i32); impl ::core::convert::From<i32> for VSS_RESTORE_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_RESTORE_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_ROLLFORWARD_TYPE(pub i32); pub const VSS_RF_UNDEFINED: VSS_ROLLFORWARD_TYPE = VSS_ROLLFORWARD_TYPE(0i32); pub const VSS_RF_NONE: VSS_ROLLFORWARD_TYPE = VSS_ROLLFORWARD_TYPE(1i32); pub const VSS_RF_ALL: VSS_ROLLFORWARD_TYPE = VSS_ROLLFORWARD_TYPE(2i32); pub const VSS_RF_PARTIAL: VSS_ROLLFORWARD_TYPE = VSS_ROLLFORWARD_TYPE(3i32); impl ::core::convert::From<i32> for VSS_ROLLFORWARD_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_ROLLFORWARD_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_SNAPSHOT_COMPATIBILITY(pub i32); pub const VSS_SC_DISABLE_DEFRAG: VSS_SNAPSHOT_COMPATIBILITY = VSS_SNAPSHOT_COMPATIBILITY(1i32); pub const VSS_SC_DISABLE_CONTENTINDEX: VSS_SNAPSHOT_COMPATIBILITY = VSS_SNAPSHOT_COMPATIBILITY(2i32); impl ::core::convert::From<i32> for VSS_SNAPSHOT_COMPATIBILITY { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_SNAPSHOT_COMPATIBILITY { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_SNAPSHOT_CONTEXT(pub i32); pub const VSS_CTX_BACKUP: VSS_SNAPSHOT_CONTEXT = VSS_SNAPSHOT_CONTEXT(0i32); pub const VSS_CTX_FILE_SHARE_BACKUP: VSS_SNAPSHOT_CONTEXT = VSS_SNAPSHOT_CONTEXT(16i32); pub const VSS_CTX_NAS_ROLLBACK: VSS_SNAPSHOT_CONTEXT = VSS_SNAPSHOT_CONTEXT(25i32); pub const VSS_CTX_APP_ROLLBACK: VSS_SNAPSHOT_CONTEXT = VSS_SNAPSHOT_CONTEXT(9i32); pub const VSS_CTX_CLIENT_ACCESSIBLE: VSS_SNAPSHOT_CONTEXT = VSS_SNAPSHOT_CONTEXT(29i32); pub const VSS_CTX_CLIENT_ACCESSIBLE_WRITERS: VSS_SNAPSHOT_CONTEXT = VSS_SNAPSHOT_CONTEXT(13i32); pub const VSS_CTX_ALL: VSS_SNAPSHOT_CONTEXT = VSS_SNAPSHOT_CONTEXT(-1i32); impl ::core::convert::From<i32> for VSS_SNAPSHOT_CONTEXT { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_SNAPSHOT_CONTEXT { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VSS_SNAPSHOT_PROP { pub m_SnapshotId: ::windows::core::GUID, pub m_SnapshotSetId: ::windows::core::GUID, pub m_lSnapshotsCount: i32, pub m_pwszSnapshotDeviceObject: *mut u16, pub m_pwszOriginalVolumeName: *mut u16, pub m_pwszOriginatingMachine: *mut u16, pub m_pwszServiceMachine: *mut u16, pub m_pwszExposedName: *mut u16, pub m_pwszExposedPath: *mut u16, pub m_ProviderId: ::windows::core::GUID, pub m_lSnapshotAttributes: i32, pub m_tsCreationTimestamp: i64, pub m_eStatus: VSS_SNAPSHOT_STATE, } impl VSS_SNAPSHOT_PROP {} impl ::core::default::Default for VSS_SNAPSHOT_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VSS_SNAPSHOT_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VSS_SNAPSHOT_PROP") .field("m_SnapshotId", &self.m_SnapshotId) .field("m_SnapshotSetId", &self.m_SnapshotSetId) .field("m_lSnapshotsCount", &self.m_lSnapshotsCount) .field("m_pwszSnapshotDeviceObject", &self.m_pwszSnapshotDeviceObject) .field("m_pwszOriginalVolumeName", &self.m_pwszOriginalVolumeName) .field("m_pwszOriginatingMachine", &self.m_pwszOriginatingMachine) .field("m_pwszServiceMachine", &self.m_pwszServiceMachine) .field("m_pwszExposedName", &self.m_pwszExposedName) .field("m_pwszExposedPath", &self.m_pwszExposedPath) .field("m_ProviderId", &self.m_ProviderId) .field("m_lSnapshotAttributes", &self.m_lSnapshotAttributes) .field("m_tsCreationTimestamp", &self.m_tsCreationTimestamp) .field("m_eStatus", &self.m_eStatus) .finish() } } impl ::core::cmp::PartialEq for VSS_SNAPSHOT_PROP { fn eq(&self, other: &Self) -> bool { self.m_SnapshotId == other.m_SnapshotId && self.m_SnapshotSetId == other.m_SnapshotSetId && self.m_lSnapshotsCount == other.m_lSnapshotsCount && self.m_pwszSnapshotDeviceObject == other.m_pwszSnapshotDeviceObject && self.m_pwszOriginalVolumeName == other.m_pwszOriginalVolumeName && self.m_pwszOriginatingMachine == other.m_pwszOriginatingMachine && self.m_pwszServiceMachine == other.m_pwszServiceMachine && self.m_pwszExposedName == other.m_pwszExposedName && self.m_pwszExposedPath == other.m_pwszExposedPath && self.m_ProviderId == other.m_ProviderId && self.m_lSnapshotAttributes == other.m_lSnapshotAttributes && self.m_tsCreationTimestamp == other.m_tsCreationTimestamp && self.m_eStatus == other.m_eStatus } } impl ::core::cmp::Eq for VSS_SNAPSHOT_PROP {} unsafe impl ::windows::core::Abi for VSS_SNAPSHOT_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_SNAPSHOT_PROPERTY_ID(pub i32); pub const VSS_SPROPID_UNKNOWN: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(0i32); pub const VSS_SPROPID_SNAPSHOT_ID: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(1i32); pub const VSS_SPROPID_SNAPSHOT_SET_ID: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(2i32); pub const VSS_SPROPID_SNAPSHOTS_COUNT: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(3i32); pub const VSS_SPROPID_SNAPSHOT_DEVICE: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(4i32); pub const VSS_SPROPID_ORIGINAL_VOLUME: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(5i32); pub const VSS_SPROPID_ORIGINATING_MACHINE: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(6i32); pub const VSS_SPROPID_SERVICE_MACHINE: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(7i32); pub const VSS_SPROPID_EXPOSED_NAME: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(8i32); pub const VSS_SPROPID_EXPOSED_PATH: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(9i32); pub const VSS_SPROPID_PROVIDER_ID: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(10i32); pub const VSS_SPROPID_SNAPSHOT_ATTRIBUTES: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(11i32); pub const VSS_SPROPID_CREATION_TIMESTAMP: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(12i32); pub const VSS_SPROPID_STATUS: VSS_SNAPSHOT_PROPERTY_ID = VSS_SNAPSHOT_PROPERTY_ID(13i32); impl ::core::convert::From<i32> for VSS_SNAPSHOT_PROPERTY_ID { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_SNAPSHOT_PROPERTY_ID { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_SNAPSHOT_STATE(pub i32); pub const VSS_SS_UNKNOWN: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(0i32); pub const VSS_SS_PREPARING: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(1i32); pub const VSS_SS_PROCESSING_PREPARE: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(2i32); pub const VSS_SS_PREPARED: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(3i32); pub const VSS_SS_PROCESSING_PRECOMMIT: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(4i32); pub const VSS_SS_PRECOMMITTED: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(5i32); pub const VSS_SS_PROCESSING_COMMIT: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(6i32); pub const VSS_SS_COMMITTED: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(7i32); pub const VSS_SS_PROCESSING_POSTCOMMIT: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(8i32); pub const VSS_SS_PROCESSING_PREFINALCOMMIT: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(9i32); pub const VSS_SS_PREFINALCOMMITTED: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(10i32); pub const VSS_SS_PROCESSING_POSTFINALCOMMIT: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(11i32); pub const VSS_SS_CREATED: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(12i32); pub const VSS_SS_ABORTED: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(13i32); pub const VSS_SS_DELETED: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(14i32); pub const VSS_SS_POSTCOMMITTED: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(15i32); pub const VSS_SS_COUNT: VSS_SNAPSHOT_STATE = VSS_SNAPSHOT_STATE(16i32); impl ::core::convert::From<i32> for VSS_SNAPSHOT_STATE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_SNAPSHOT_STATE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_SOURCE_TYPE(pub i32); pub const VSS_ST_UNDEFINED: VSS_SOURCE_TYPE = VSS_SOURCE_TYPE(0i32); pub const VSS_ST_TRANSACTEDDB: VSS_SOURCE_TYPE = VSS_SOURCE_TYPE(1i32); pub const VSS_ST_NONTRANSACTEDDB: VSS_SOURCE_TYPE = VSS_SOURCE_TYPE(2i32); pub const VSS_ST_OTHER: VSS_SOURCE_TYPE = VSS_SOURCE_TYPE(3i32); impl ::core::convert::From<i32> for VSS_SOURCE_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_SOURCE_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_SUBSCRIBE_MASK(pub i32); pub const VSS_SM_POST_SNAPSHOT_FLAG: VSS_SUBSCRIBE_MASK = VSS_SUBSCRIBE_MASK(1i32); pub const VSS_SM_BACKUP_EVENTS_FLAG: VSS_SUBSCRIBE_MASK = VSS_SUBSCRIBE_MASK(2i32); pub const VSS_SM_RESTORE_EVENTS_FLAG: VSS_SUBSCRIBE_MASK = VSS_SUBSCRIBE_MASK(4i32); pub const VSS_SM_IO_THROTTLING_FLAG: VSS_SUBSCRIBE_MASK = VSS_SUBSCRIBE_MASK(8i32); pub const VSS_SM_ALL_FLAGS: VSS_SUBSCRIBE_MASK = VSS_SUBSCRIBE_MASK(-1i32); impl ::core::convert::From<i32> for VSS_SUBSCRIBE_MASK { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_SUBSCRIBE_MASK { type Abi = Self; } pub const VSS_S_ASYNC_CANCELLED: ::windows::core::HRESULT = ::windows::core::HRESULT(271115i32 as _); pub const VSS_S_ASYNC_FINISHED: ::windows::core::HRESULT = ::windows::core::HRESULT(271114i32 as _); pub const VSS_S_ASYNC_PENDING: ::windows::core::HRESULT = ::windows::core::HRESULT(271113i32 as _); pub const VSS_S_SOME_SNAPSHOTS_NOT_IMPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(271137i32 as _); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_USAGE_TYPE(pub i32); pub const VSS_UT_UNDEFINED: VSS_USAGE_TYPE = VSS_USAGE_TYPE(0i32); pub const VSS_UT_BOOTABLESYSTEMSTATE: VSS_USAGE_TYPE = VSS_USAGE_TYPE(1i32); pub const VSS_UT_SYSTEMSERVICE: VSS_USAGE_TYPE = VSS_USAGE_TYPE(2i32); pub const VSS_UT_USERDATA: VSS_USAGE_TYPE = VSS_USAGE_TYPE(3i32); pub const VSS_UT_OTHER: VSS_USAGE_TYPE = VSS_USAGE_TYPE(4i32); impl ::core::convert::From<i32> for VSS_USAGE_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_USAGE_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VSS_VOLUME_PROP { pub m_pwszVolumeName: *mut u16, pub m_pwszVolumeDisplayName: *mut u16, } impl VSS_VOLUME_PROP {} impl ::core::default::Default for VSS_VOLUME_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VSS_VOLUME_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VSS_VOLUME_PROP").field("m_pwszVolumeName", &self.m_pwszVolumeName).field("m_pwszVolumeDisplayName", &self.m_pwszVolumeDisplayName).finish() } } impl ::core::cmp::PartialEq for VSS_VOLUME_PROP { fn eq(&self, other: &Self) -> bool { self.m_pwszVolumeName == other.m_pwszVolumeName && self.m_pwszVolumeDisplayName == other.m_pwszVolumeDisplayName } } impl ::core::cmp::Eq for VSS_VOLUME_PROP {} unsafe impl ::windows::core::Abi for VSS_VOLUME_PROP { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VSS_VOLUME_PROTECTION_INFO { pub m_protectionLevel: VSS_PROTECTION_LEVEL, pub m_volumeIsOfflineForProtection: super::super::Foundation::BOOL, pub m_protectionFault: VSS_PROTECTION_FAULT, pub m_failureStatus: i32, pub m_volumeHasUnusedDiffArea: super::super::Foundation::BOOL, pub m_reserved: u32, } #[cfg(feature = "Win32_Foundation")] impl VSS_VOLUME_PROTECTION_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VSS_VOLUME_PROTECTION_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VSS_VOLUME_PROTECTION_INFO { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VSS_VOLUME_PROTECTION_INFO") .field("m_protectionLevel", &self.m_protectionLevel) .field("m_volumeIsOfflineForProtection", &self.m_volumeIsOfflineForProtection) .field("m_protectionFault", &self.m_protectionFault) .field("m_failureStatus", &self.m_failureStatus) .field("m_volumeHasUnusedDiffArea", &self.m_volumeHasUnusedDiffArea) .field("m_reserved", &self.m_reserved) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VSS_VOLUME_PROTECTION_INFO { fn eq(&self, other: &Self) -> bool { self.m_protectionLevel == other.m_protectionLevel && self.m_volumeIsOfflineForProtection == other.m_volumeIsOfflineForProtection && self.m_protectionFault == other.m_protectionFault && self.m_failureStatus == other.m_failureStatus && self.m_volumeHasUnusedDiffArea == other.m_volumeHasUnusedDiffArea && self.m_reserved == other.m_reserved } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VSS_VOLUME_PROTECTION_INFO {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VSS_VOLUME_PROTECTION_INFO { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_VOLUME_SNAPSHOT_ATTRIBUTES(pub i32); pub const VSS_VOLSNAP_ATTR_PERSISTENT: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(1i32); pub const VSS_VOLSNAP_ATTR_NO_AUTORECOVERY: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(2i32); pub const VSS_VOLSNAP_ATTR_CLIENT_ACCESSIBLE: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(4i32); pub const VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(8i32); pub const VSS_VOLSNAP_ATTR_NO_WRITERS: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(16i32); pub const VSS_VOLSNAP_ATTR_TRANSPORTABLE: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(32i32); pub const VSS_VOLSNAP_ATTR_NOT_SURFACED: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(64i32); pub const VSS_VOLSNAP_ATTR_NOT_TRANSACTED: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(128i32); pub const VSS_VOLSNAP_ATTR_HARDWARE_ASSISTED: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(65536i32); pub const VSS_VOLSNAP_ATTR_DIFFERENTIAL: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(131072i32); pub const VSS_VOLSNAP_ATTR_PLEX: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(262144i32); pub const VSS_VOLSNAP_ATTR_IMPORTED: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(524288i32); pub const VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(1048576i32); pub const VSS_VOLSNAP_ATTR_EXPOSED_REMOTELY: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(2097152i32); pub const VSS_VOLSNAP_ATTR_AUTORECOVER: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(4194304i32); pub const VSS_VOLSNAP_ATTR_ROLLBACK_RECOVERY: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(8388608i32); pub const VSS_VOLSNAP_ATTR_DELAYED_POSTSNAPSHOT: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(16777216i32); pub const VSS_VOLSNAP_ATTR_TXF_RECOVERY: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(33554432i32); pub const VSS_VOLSNAP_ATTR_FILE_SHARE: VSS_VOLUME_SNAPSHOT_ATTRIBUTES = VSS_VOLUME_SNAPSHOT_ATTRIBUTES(67108864i32); impl ::core::convert::From<i32> for VSS_VOLUME_SNAPSHOT_ATTRIBUTES { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_VOLUME_SNAPSHOT_ATTRIBUTES { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_WRITERRESTORE_ENUM(pub i32); pub const VSS_WRE_UNDEFINED: VSS_WRITERRESTORE_ENUM = VSS_WRITERRESTORE_ENUM(0i32); pub const VSS_WRE_NEVER: VSS_WRITERRESTORE_ENUM = VSS_WRITERRESTORE_ENUM(1i32); pub const VSS_WRE_IF_REPLACE_FAILS: VSS_WRITERRESTORE_ENUM = VSS_WRITERRESTORE_ENUM(2i32); pub const VSS_WRE_ALWAYS: VSS_WRITERRESTORE_ENUM = VSS_WRITERRESTORE_ENUM(3i32); impl ::core::convert::From<i32> for VSS_WRITERRESTORE_ENUM { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_WRITERRESTORE_ENUM { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VSS_WRITER_STATE(pub i32); pub const VSS_WS_UNKNOWN: VSS_WRITER_STATE = VSS_WRITER_STATE(0i32); pub const VSS_WS_STABLE: VSS_WRITER_STATE = VSS_WRITER_STATE(1i32); pub const VSS_WS_WAITING_FOR_FREEZE: VSS_WRITER_STATE = VSS_WRITER_STATE(2i32); pub const VSS_WS_WAITING_FOR_THAW: VSS_WRITER_STATE = VSS_WRITER_STATE(3i32); pub const VSS_WS_WAITING_FOR_POST_SNAPSHOT: VSS_WRITER_STATE = VSS_WRITER_STATE(4i32); pub const VSS_WS_WAITING_FOR_BACKUP_COMPLETE: VSS_WRITER_STATE = VSS_WRITER_STATE(5i32); pub const VSS_WS_FAILED_AT_IDENTIFY: VSS_WRITER_STATE = VSS_WRITER_STATE(6i32); pub const VSS_WS_FAILED_AT_PREPARE_BACKUP: VSS_WRITER_STATE = VSS_WRITER_STATE(7i32); pub const VSS_WS_FAILED_AT_PREPARE_SNAPSHOT: VSS_WRITER_STATE = VSS_WRITER_STATE(8i32); pub const VSS_WS_FAILED_AT_FREEZE: VSS_WRITER_STATE = VSS_WRITER_STATE(9i32); pub const VSS_WS_FAILED_AT_THAW: VSS_WRITER_STATE = VSS_WRITER_STATE(10i32); pub const VSS_WS_FAILED_AT_POST_SNAPSHOT: VSS_WRITER_STATE = VSS_WRITER_STATE(11i32); pub const VSS_WS_FAILED_AT_BACKUP_COMPLETE: VSS_WRITER_STATE = VSS_WRITER_STATE(12i32); pub const VSS_WS_FAILED_AT_PRE_RESTORE: VSS_WRITER_STATE = VSS_WRITER_STATE(13i32); pub const VSS_WS_FAILED_AT_POST_RESTORE: VSS_WRITER_STATE = VSS_WRITER_STATE(14i32); pub const VSS_WS_FAILED_AT_BACKUPSHUTDOWN: VSS_WRITER_STATE = VSS_WRITER_STATE(15i32); pub const VSS_WS_COUNT: VSS_WRITER_STATE = VSS_WRITER_STATE(16i32); impl ::core::convert::From<i32> for VSS_WRITER_STATE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VSS_WRITER_STATE { type Abi = Self; } pub const VssSnapshotMgmt: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0b5a2c52_3eb9_470a_96e2_6c6d4570e40f);
#![allow(dead_code)] use crate::{aocbail, utils}; use utils::{AOCError, AOCResult}; pub struct SeatRange { min: usize, max: usize, } impl SeatRange { pub fn narrow(&mut self, take_upper: bool) -> Option<usize> { let delta = (self.max - self.min + 1) / 2; if take_upper { self.min += delta; } else { self.max -= delta; } if self.min == self.max { Some(self.min) } else { None } } } pub fn day5() { let input = utils::get_input("day5"); println!( "binary_boarding part 1: {}", find_hipri_seat(input).unwrap() ); let input = utils::get_input("day5"); println!( "binary_boarding part 2: {}", find_your_seat(input).unwrap() ); } pub fn find_your_seat(input: impl Iterator<Item=String>) -> AOCResult<usize> { const SEAT_COUNT: usize = 8*128; let mut seats: [u8; SEAT_COUNT] = [0; SEAT_COUNT]; let mut min: usize = SEAT_COUNT-1; for line in input { let seat = find_seat(&line)?; min = std::cmp::min(min, seat); seats[seat] = 1; } for i in (min+1)..seats.len() { if seats[i] == 0 { return Ok(i); } } aocbail!("Unable to find seat!"); } pub fn find_hipri_seat(input: impl Iterator<Item=String>) -> AOCResult<usize> { let mut hipri_seat = 0; for line in input { hipri_seat = std::cmp::max(hipri_seat, find_seat(&line)?); } Ok(hipri_seat) } pub fn find_seat(boarding_pass: &str) -> AOCResult<usize> { let mut row_range = SeatRange{min: 0, max: 127}; let mut column_range = SeatRange{min: 0, max: 7}; let mut row: Option<usize> = None; let mut column: Option<usize> = None; for position in boarding_pass.chars() { match position { 'F' => { row = row_range.narrow(false); }, 'B' => { row = row_range.narrow(true); }, 'L' => { column = column_range.narrow(false); }, 'R' => { column = column_range.narrow(true); }, _ => { aocbail!("Illegal character"); } } } Ok(row? * 8 + column?) } #[test] pub fn basic_binary_boarding() { assert_eq!(find_seat("BFFFBBFRRR").unwrap(), 567); assert_eq!(find_seat("FFFBBBFRRR").unwrap(), 119); assert_eq!(find_seat("BBFFBBFRLL").unwrap(), 820); }
use std::path::PathBuf; use structopt::StructOpt; use self::build::Build; use self::completion::{Completion, AFTER_HELP as COMPLETION_AFTER_HELP}; use self::install::{Install, AFTER_HELP as INSTALL_AFTER_HELP}; use self::list::{List, AFTER_HELP as LIST_AFTER_HELP}; use self::log::{Log, AFTER_HELP as LOG_AFTER_HELP}; use self::package::{Package, AFTER_HELP as PACKAGE_AFTER_HELP}; use self::profile::{Profile, AFTER_HELP as PROFILE_AFTER_HELP}; use self::remove::{Remove, AFTER_HELP as REMOVE_AFTER_HELP}; use self::revert::{Revert, AFTER_HELP as REVERT_AFTER_HELP}; use self::search::{Search, AFTER_HELP as SEARCH_AFTER_HELP}; use self::update::{Update, AFTER_HELP as UPDATE_AFTER_HELP}; use self::upgrade::{Upgrade, AFTER_HELP as UPGRADE_AFTER_HELP}; use self::verify::{Verify, AFTER_HELP as VERIFY_AFTER_HELP}; mod build; mod completion; mod install; mod list; mod log; mod package; mod profile; mod remove; mod revert; mod search; mod update; mod upgrade; mod verify; /// Trait implemented by all subcommands. trait CliCommand: StructOpt { /// Execute the command with the given global flags. fn run(self, flags: GlobalFlags) -> Result<(), String>; } /// Global command-line flags. #[derive(Debug, StructOpt)] pub struct GlobalFlags { /// Simulate an action without doing anything #[structopt(global = true, long = "dry-run")] dry_run: bool, /// No output printed to stdout #[structopt( global = true, short = "q", long = "quiet", conflicts_with = "verbosity" )] quiet: bool, #[structopt( global = true, long = "store-dir", env = "DECK_STORE_PATH", empty_values = false, value_name = "PATH", default_value = "/deck/store", hide_default_value = true, hide_env_values = true, parse(from_os_str) )] /// Path to the store directory store_path: PathBuf, /// Increase verbosity level of output #[structopt(global = true, short = "v", long = "verbose", parse(from_occurrences))] verbosity: u8, } /// Built-in Deck client subcommands. #[derive(Debug, StructOpt)] pub enum Subcommand { /// Compile a package from source #[structopt(name = "build")] Build(Build), /// Print shell completions to stdout #[structopt(name = "completion", raw(after_help = "COMPLETION_AFTER_HELP"))] Completion(Completion), /// Display build logs for packages #[structopt(name = "log", raw(after_help = "LOG_AFTER_HELP"))] Log(Log), /// List installed packages #[structopt(name = "list", raw(after_help = "LIST_AFTER_HELP"))] List(List), /// Install new packages #[structopt(name = "install", raw(after_help = "INSTALL_AFTER_HELP"))] Install(Install), /// Export packages in a portable format #[structopt(name = "package", raw(after_help = "PACKAGE_AFTER_HELP"))] Package(Package), /// Perform a package transaction on a profile #[structopt(name = "profile", raw(after_help = "PROFILE_AFTER_HELP"))] Profile(Profile), /// Uninstall existing packages #[structopt(name = "remove", raw(after_help = "REMOVE_AFTER_HELP"))] Remove(Remove), /// Roll back one or more package transactions #[structopt(name = "revert", raw(after_help = "REVERT_AFTER_HELP"))] Revert(Revert), /// Search repositories for packages #[structopt(name = "search", raw(after_help = "SEARCH_AFTER_HELP"))] Search(Search), /// Synchronize updates from upstream repositories #[structopt(name = "update", raw(after_help = "UPDATE_AFTER_HELP"))] Update(Update), /// Upgrade existing packages in your environment #[structopt(name = "upgrade", raw(after_help = "UPGRADE_AFTER_HELP"))] Upgrade(Upgrade), /// Verify the integrity of store contents #[structopt(name = "verify", raw(after_help = "VERIFY_AFTER_HELP"))] Verify(Verify), } impl Subcommand { /// Executes the active subcommand with the given arguments. pub fn run(self, flags: GlobalFlags) -> Result<(), String> { println!("{:?}", flags); println!("{:?}", self); match self { Subcommand::Build(cmd) => cmd.run(flags), Subcommand::Completion(cmd) => cmd.run(flags), Subcommand::List(cmd) => cmd.run(flags), Subcommand::Log(cmd) => cmd.run(flags), Subcommand::Install(cmd) => cmd.run(flags), Subcommand::Package(cmd) => cmd.run(flags), Subcommand::Profile(cmd) => cmd.run(flags), Subcommand::Remove(cmd) => cmd.run(flags), Subcommand::Revert(cmd) => cmd.run(flags), Subcommand::Search(cmd) => cmd.run(flags), Subcommand::Update(cmd) => cmd.run(flags), Subcommand::Upgrade(cmd) => cmd.run(flags), Subcommand::Verify(cmd) => cmd.run(flags), } } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::string::String; use alloc::string::ToString; use alloc::sync::Arc; use spin::Mutex; use core::ops::Deref; use super::super::qlib::auth::userns::*; #[derive(Default)] pub struct UTSNamespaceInternal { pub hostName: String, pub domainName: String, pub userns: UserNameSpace, } #[derive(Clone, Default)] pub struct UTSNamespace(Arc<Mutex<UTSNamespaceInternal>>); impl Deref for UTSNamespace { type Target = Arc<Mutex<UTSNamespaceInternal>>; fn deref(&self) -> &Arc<Mutex<UTSNamespaceInternal>> { &self.0 } } impl UTSNamespace { pub fn New(hostName: String, domainName: String, userns: UserNameSpace) -> Self { let internal = UTSNamespaceInternal { hostName: hostName, domainName: domainName, userns: userns }; return Self(Arc::new(Mutex::new(internal))) } pub fn HostName(&self) -> String { return self.lock().hostName.to_string(); } pub fn SetHostName(&self, host: String) { self.lock().hostName = host; } pub fn DomainName(&self) -> String { return self.lock().domainName.to_string(); } pub fn SetDomainName(&self, domain: String) { self.lock().domainName = domain; } pub fn UserNamespace(&self) -> UserNameSpace { return self.lock().userns.clone(); } pub fn Fork(&self, userns: &UserNameSpace) -> Self { let me = self.lock(); let internal = UTSNamespaceInternal { hostName: me.hostName.to_string(), domainName: me.domainName.to_string(), userns: userns.clone(), }; return Self(Arc::new(Mutex::new(internal))) } }
use std::fmt::{Formatter, Result, Display}; use syntax::ast::op::UnaryOp::*; use syntax::ast::op::*; use syntax::ast::expr::ExprDef::*; use syntax::ast::constant::Const; use syntax::ast::pos::Position; use std::collections::btree_map::BTreeMap; #[derive(Clone, PartialEq)] /// A Javascript expression, including its position pub struct Expr { /// The expression definition pub def : ExprDef, /// The starting position pub start : Position, /// The ending position pub end : Position } impl Expr { /// Create a new expression with a starting and ending position pub fn new(def: ExprDef, start:Position, end:Position) -> Expr { Expr{def: def, start: start, end: end} } } impl Display for Expr { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}", self.def) } } #[derive(Clone, PartialEq)] /// A Javascript expression pub enum ExprDef { /// Run a operation between 2 expressions BinOpExpr(BinOp, Box<Expr>, Box<Expr>), /// Run an operation on a value UnaryOpExpr(UnaryOp, Box<Expr>), /// Make a constant value ConstExpr(Const), /// Run several expressions from top-to-bottom BlockExpr(Vec<Expr>), /// Load a reference to a value LocalExpr(String), /// Gets the constant field of a value GetConstFieldExpr(Box<Expr>, String), /// Gets the field of a value GetFieldExpr(Box<Expr>, Box<Expr>), /// Call a function with some values CallExpr(Box<Expr>, Vec<Expr>), /// Repeatedly run an expression while the conditional expression resolves to true WhileLoopExpr(Box<Expr>, Box<Expr>), /// Check if a conditional expression is true and run an expression if it is and another expression if it isn't IfExpr(Box<Expr>, Box<Expr>, Option<Box<Expr>>), /// Run blocks whose cases match the expression SwitchExpr(Box<Expr>, Vec<(Expr, Vec<Expr>)>, Option<Box<Expr>>), /// Create an object out of the binary tree given ObjectDeclExpr(Box<BTreeMap<String, Expr>>), /// Create an array with items inside ArrayDeclExpr(Vec<Expr>), /// Create a function with the given name, arguments, and expression FunctionDeclExpr(Option<String>, Vec<String>, Box<Expr>), /// Create an arrow function with the given arguments and expression ArrowFunctionDeclExpr(Vec<String>, Box<Expr>), /// Construct an object from the function and arguments given ConstructExpr(Box<Expr>, Vec<Expr>), /// Return the expression from a function ReturnExpr(Option<Box<Expr>>), /// Throw a value ThrowExpr(Box<Expr>), /// Assign an expression to a value AssignExpr(Box<Expr>, Box<Expr>), /// A variable declaration VarDeclExpr(Vec<(String, Option<Expr>)>), /// Return a string representing the type of the given expression TypeOfExpr(Box<Expr>) } impl Operator for ExprDef { fn get_assoc(&self) -> bool { match *self { ConstructExpr(_, _) | UnaryOpExpr(_, _) | TypeOfExpr(_) | IfExpr(_, _, _) | AssignExpr(_, _) => false, _ => true } } fn get_precedence(&self) -> u64 { match *self { GetFieldExpr(_, _) | GetConstFieldExpr(_, _) => 1, CallExpr(_, _) | ConstructExpr(_, _) => 2, UnaryOpExpr(UnaryIncrementPost, _) | UnaryOpExpr(UnaryIncrementPre, _) | UnaryOpExpr(UnaryDecrementPost, _) | UnaryOpExpr(UnaryDecrementPre, _) => 3, UnaryOpExpr(UnaryNot, _) | UnaryOpExpr(UnaryMinus, _) | TypeOfExpr(_) => 4, BinOpExpr(op, _, _) => op.get_precedence(), IfExpr(_, _, _) => 15, // 16 should be yield AssignExpr(_, _) => 17, _ => 19 } } } impl Display for ExprDef { fn fmt(&self, f: &mut Formatter) -> Result { return match *self { ConstExpr(ref c) => write!(f, "{}", c), BlockExpr(ref block) => { try!(write!(f, "{}", "{")); for expr in block.iter() { try!(write!(f, "{};", expr)); } write!(f, "{}", "}") }, LocalExpr(ref s) => write!(f, "{}", s), GetConstFieldExpr(ref ex, ref field) => write!(f, "{}.{}", ex, field), GetFieldExpr(ref ex, ref field) => write!(f, "{}[{}]", ex, field), CallExpr(ref ex, ref args) => { try!(write!(f, "{}(", ex)); let arg_strs:Vec<String> = args.iter().map(|arg| arg.to_string()).collect(); write!(f, "{})", arg_strs.connect(",")) }, ConstructExpr(ref func, ref args) => write!(f, "new {}({})", func, args), WhileLoopExpr(ref cond, ref expr) => write!(f, "while({}) {}", cond, expr), IfExpr(ref cond, ref expr, None) => write!(f, "if({}) {}", cond, expr), IfExpr(ref cond, ref expr, Some(ref else_e)) => write!(f, "if({}) {} else {}", cond, expr, else_e), SwitchExpr(ref val, ref vals, None) => write!(f, "switch({}){}", val, vals), SwitchExpr(ref val, ref vals, Some(ref def)) => write!(f, "switch({}){}default:{}", val, vals, def), ObjectDeclExpr(ref map) => write!(f, "{}", map), ArrayDeclExpr(ref arr) => write!(f, "{}", arr), FunctionDeclExpr(ref name, ref args, ref expr) => write!(f, "function {}({}){}", name, args.connect(", "), expr), ArrowFunctionDeclExpr(ref args, ref expr) => write!(f, "({}) => {}", args.connect(", "), expr), BinOpExpr(ref op, ref a, ref b) => write!(f, "{} {} {}", a, op, b), UnaryOpExpr(ref op, ref a) => write!(f, "{}{}", op, a), ReturnExpr(Some(ref ex)) => write!(f, "return {}", ex), ReturnExpr(None) => write!(f, "{}", "return"), ThrowExpr(ref ex) => write!(f, "throw {}", ex), AssignExpr(ref ref_e, ref val) => write!(f, "{} = {}", ref_e, val), VarDeclExpr(ref vars) => write!(f, "var {}", vars), TypeOfExpr(ref e) => write!(f, "typeof {}", e), } } }
#![warn(clippy::all)] #![warn(clippy::pedantic)] fn main() { run(); } fn run() { let start = std::time::Instant::now(); // code goes here let res = (2 * 2 * 2 * 2) * (3 * 3) * 5 * 7 * 11 * 13 * 17 * 19; let span = start.elapsed().as_nanos(); println!("{} {}", res, span); }
extern crate env_logger; extern crate samotop; extern crate tokio; #[macro_use] extern crate structopt; use structopt::StructOpt; fn main() { env_logger::init(); let opt = Opt::from_args(); tokio::run( samotop::START //.with(samotop::service::echo::EchoService) .with(samotop::service::mail::MailService::new("wooohoo")) .on_all(opt.ports) .as_task(), ); } #[derive(StructOpt, Debug)] #[structopt(name = "samotop")] struct Opt { /// SMTP server address:port #[structopt(short = "p", long = "port")] ports: Vec<String>, }
use rand::random; use crate::color::Color; use crate::geometry::Ray; use crate::{ geometry::{near_zero, random_in_unit_sphere, random_unit_vec, reflect, refract, unit, v3}, hittable::HitRecord, }; pub type Scatter = (Color, Ray); pub trait Material: Send + Sync { fn scatter(&self, ray: &Ray, rec: &HitRecord) -> Option<Scatter>; } pub struct Lambertian { pub albedo: Color, } pub struct Metal { pub albedo: Color, pub fuzz: f64, } pub struct Dielectric { pub ir: f64, } impl Material for Lambertian { fn scatter(&self, _ray: &Ray, rec: &HitRecord) -> Option<Scatter> { let mut scatter_dir = rec.normal + random_unit_vec(); if near_zero(&scatter_dir) { scatter_dir = rec.normal; } let scattered = Ray { orig: rec.point, dir: scatter_dir, }; let color = self.albedo; Some((color, scattered)) } } impl Material for Metal { fn scatter(&self, ray: &Ray, rec: &HitRecord) -> Option<Scatter> { let reflected = reflect(&unit(&ray.direction()), &rec.normal); let scattered = Ray { orig: rec.point, dir: reflected + self.fuzz * random_in_unit_sphere(), }; let color = self.albedo; if scattered.direction().dot(&rec.normal) > 0. { Some((color, scattered)) } else { None } } } impl Dielectric { fn reflectance(cosine: f64, ref_idx: f64) -> f64 { let r0 = ((1. - ref_idx) / (1. + ref_idx)).powf(2.); r0 + (1. - r0) * (1. - cosine).powf(5.) } } impl Material for Dielectric { fn scatter(&self, ray: &Ray, rec: &HitRecord) -> Option<Scatter> { let attenuation = Color(v3(1.0, 1.0, 1.0)); let refraction_ratio = if rec.front_face { 1.0 / self.ir } else { self.ir }; let unit_dir = unit(&ray.direction()); let cos_theta = unit_dir.dot(&rec.normal).min(1.0); let sin_theta = (1. - cos_theta * cos_theta).sqrt(); let cannot_refract = refraction_ratio * sin_theta > 1.0; let should_reflect = Dielectric::reflectance(cos_theta, refraction_ratio) > random(); let direction = if cannot_refract || should_reflect { reflect(&unit_dir, &rec.normal) } else { refract(&unit_dir, &rec.normal, refraction_ratio) }; Some(( attenuation, Ray { orig: rec.point, dir: direction, }, )) } }
use crate::assets::shader::ShaderManager; use crate::assets::Handle; use crate::core::colors::RgbaColor; use crate::core::transform::Transform; use luminance::blending::{Blending, Equation, Factor}; use luminance::context::GraphicsContext; use luminance::pipeline::{Pipeline, PipelineError, TextureBinding}; use luminance::pixel::NormUnsigned; use luminance::render_state::RenderState; use luminance::shader::Uniform; use luminance::shading_gate::ShadingGate; use luminance::tess::{Mode, Tess}; use luminance::texture::Dim2; use luminance_derive::{Semantics, UniformInterface, Vertex}; use luminance_gl::GL33; use std::time::Instant; // Vertex definition // ----------------- // Just position, texture coordinates and color for 2D. No need // for normal, tangent... // ----------------------------------------------------- #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Semantics)] pub enum VertexSemantics { #[sem(name = "position", repr = "[f32; 2]", wrapper = "VertexPosition")] Position, #[sem(name = "uv", repr = "[f32; 2]", wrapper = "TextureCoord")] TextureCoord, #[sem(name = "color", repr = "[f32; 4]", wrapper = "VertexColor")] Color, } #[allow(dead_code)] #[repr(C)] #[derive(Vertex, Copy, Debug, Clone)] #[vertex(sem = "VertexSemantics")] pub struct Vertex { /// Position of the vertex in 2D. position: VertexPosition, /// Texture coordinates for the vertex. uv: TextureCoord, /// Color for the vertex. color: VertexColor, } // Uniform definition // ------------------ // Matrices to translate to view space, other useful uniforms such as timestamp, delta, // and so on... // -------------------------------------------------------------------------------------- #[allow(dead_code)] #[derive(UniformInterface)] pub struct ShaderUniform { /// PROJECTION matrix in MVP #[uniform(unbound, name = "u_projection")] projection: Uniform<[[f32; 4]; 4]>, /// VIEW matrix in MVP #[uniform(unbound, name = "u_view")] view: Uniform<[[f32; 4]; 4]>, /// MODEL matrix in MVP #[uniform(unbound, name = "u_model")] model: Uniform<[[f32; 4]; 4]>, /// Texture for the sprite. #[uniform(unbound, name = "u_tex_1")] tex_1: Uniform<TextureBinding<Dim2, NormUnsigned>>, /// true if should blink. #[uniform(unbound, name = "u_time")] time: Uniform<f32>, } pub enum Material { /// Will use the given vertex and fragment shaders for the mesh. Shader { vertex_shader_id: String, fragment_shader_id: String, }, Texture { sprite_id: String, }, } /// Render meshes with materials. pub struct MeshRenderer<S> where S: GraphicsContext<Backend = GL33>, { tess: Tess<S::Backend, Vertex, u32>, /// used to send elapsed time to shader. creation_time: Instant, } pub struct MeshRender { pub enabled: bool, pub material: Material, } impl<S> MeshRenderer<S> where S: GraphicsContext<Backend = GL33>, { pub fn new(surface: &mut S) -> Self { let color = RgbaColor::new(255, 0, 0, 255).to_normalized(); let (vertices, indices) = ( vec![ Vertex { position: VertexPosition::new([-1.0, -1.0]), uv: TextureCoord::new([0.0, 0.0]), color: VertexColor::new(color), }, Vertex { position: VertexPosition::new([-1.0, 1.0]), uv: TextureCoord::new([0.0, 1.0]), color: VertexColor::new(color), }, Vertex { position: VertexPosition::new([1.0, 1.0]), uv: TextureCoord::new([1.0, 1.0]), color: VertexColor::new(color), }, Vertex { position: VertexPosition::new([1.0, -1.0]), uv: TextureCoord::new([1.0, 0.0]), color: VertexColor::new(color), }, ], vec![0, 1, 2, 0, 2, 3], ); let tess = surface .new_tess() .set_mode(Mode::Triangle) .set_indices(indices) .set_vertices(vertices) .build() .unwrap(); Self { tess, creation_time: Instant::now(), } } pub fn render( &mut self, _pipeline: &Pipeline<S::Backend>, shd_gate: &mut ShadingGate<S::Backend>, proj_matrix: &glam::Mat4, view: &glam::Mat4, world: &hecs::World, shader_manager: &mut ShaderManager<S>, ) -> Result<(), PipelineError> { // let handle = Handle(("simple-vs.glsl".to_string(), "simple-fs.glsl".to_string())); let render_st = RenderState::default() .set_depth_test(None) .set_blending_separate( Blending { equation: Equation::Additive, src: Factor::SrcAlpha, dst: Factor::SrcAlphaComplement, }, Blending { equation: Equation::Additive, src: Factor::One, dst: Factor::Zero, }, ); let elapsed = self.creation_time.elapsed().as_secs_f32(); for (_, (t, render)) in world.query::<(&Transform, &MeshRender)>().iter() { if !render.enabled { continue; } if let Material::Shader { ref vertex_shader_id, ref fragment_shader_id, } = render.material { let model = t.to_model(); let handle = Handle((vertex_shader_id.clone(), fragment_shader_id.clone())); if let Some(shader) = shader_manager.get_mut(&handle) { if let Some(ret) = shader.execute_mut(|shader_asset| { if let Some(ref mut shader) = shader_asset.shader { shd_gate.shade(shader, |mut iface, uni, mut rdr_gate| { iface.set(&uni.time, elapsed); iface.set(&uni.projection, proj_matrix.to_cols_array_2d()); iface.set(&uni.view, view.to_cols_array_2d()); iface.set(&uni.model, model.to_cols_array_2d()); rdr_gate.render(&render_st, |mut tess_gate| { tess_gate.render(&self.tess) }) }) } else { Ok(()) } }) { ret?; } } else { shader_manager.load(handle.0); } } } Ok(()) } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IRfcommDeviceService(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRfcommDeviceService { type Vtable = IRfcommDeviceService_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xae81ff1f_c5a1_4c40_8c28_f3efd69062f3); } #[repr(C)] #[doc(hidden)] pub struct IRfcommDeviceService_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 = "Networking")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Networking"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Networking_Sockets")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Networking::Sockets::SocketProtectionLevel) -> ::windows::core::HRESULT, #[cfg(not(feature = "Networking_Sockets"))] usize, #[cfg(feature = "Networking_Sockets")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Networking::Sockets::SocketProtectionLevel) -> ::windows::core::HRESULT, #[cfg(not(feature = "Networking_Sockets"))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams"))] 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", feature = "Storage_Streams")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cachemode: super::BluetoothCacheMode, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IRfcommDeviceService2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRfcommDeviceService2 { type Vtable = IRfcommDeviceService2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x536ced14_ebcd_49fe_bf9f_40efc689b20d); } #[repr(C)] #[doc(hidden)] pub struct IRfcommDeviceService2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IRfcommDeviceService3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRfcommDeviceService3 { type Vtable = IRfcommDeviceService3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1c22ace6_dd44_4d23_866d_8f3486ee6490); } #[repr(C)] #[doc(hidden)] pub struct IRfcommDeviceService3_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Devices_Enumeration")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Devices_Enumeration"))] usize, #[cfg(all(feature = "Devices_Enumeration", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Devices_Enumeration", feature = "Foundation")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IRfcommDeviceServiceStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRfcommDeviceServiceStatics { type Vtable = IRfcommDeviceServiceStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa4a149ef_626d_41ac_b253_87ac5c27e28a); } #[repr(C)] #[doc(hidden)] pub struct IRfcommDeviceServiceStatics_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, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, serviceid: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IRfcommDeviceServiceStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRfcommDeviceServiceStatics2 { type Vtable = IRfcommDeviceServiceStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaa8cb1c9_e78d_4be4_8076_0a3d87a0a05f); } #[repr(C)] #[doc(hidden)] pub struct IRfcommDeviceServiceStatics2_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, bluetoothdevice: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bluetoothdevice: ::windows::core::RawPtr, cachemode: super::BluetoothCacheMode, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bluetoothdevice: ::windows::core::RawPtr, serviceid: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bluetoothdevice: ::windows::core::RawPtr, serviceid: ::windows::core::RawPtr, cachemode: super::BluetoothCacheMode, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IRfcommDeviceServicesResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRfcommDeviceServicesResult { type Vtable = IRfcommDeviceServicesResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3b48388c_7ccf_488e_9625_d259a5732d55); } #[repr(C)] #[doc(hidden)] pub struct IRfcommDeviceServicesResult_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 super::BluetoothError) -> ::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 IRfcommServiceId(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRfcommServiceId { type Vtable = IRfcommServiceId_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x22629204_7e02_4017_8136_da1b6a1b9bbf); } #[repr(C)] #[doc(hidden)] pub struct IRfcommServiceId_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IRfcommServiceIdStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRfcommServiceIdStatics { type Vtable = IRfcommServiceIdStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2a179eba_a975_46e3_b56b_08ffd783a5fe); } #[repr(C)] #[doc(hidden)] pub struct IRfcommServiceIdStatics_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, uuid: ::windows::core::GUID, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, shortid: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IRfcommServiceProvider(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRfcommServiceProvider { type Vtable = IRfcommServiceProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xeadbfdc4_b1f6_44ff_9f7c_e7a82ab86821); } #[repr(C)] #[doc(hidden)] pub struct IRfcommServiceProvider_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation_Collections", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation_Collections", feature = "Storage_Streams")))] usize, #[cfg(feature = "Networking_Sockets")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, listener: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Networking_Sockets"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IRfcommServiceProvider2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRfcommServiceProvider2 { type Vtable = IRfcommServiceProvider2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x736bdfc6_3c81_4d1e_baf2_ddbb81284512); } #[repr(C)] #[doc(hidden)] pub struct IRfcommServiceProvider2_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 = "Networking_Sockets")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, listener: ::windows::core::RawPtr, radiodiscoverable: bool) -> ::windows::core::HRESULT, #[cfg(not(feature = "Networking_Sockets"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IRfcommServiceProviderStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRfcommServiceProviderStatics { type Vtable = IRfcommServiceProviderStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x98888303_69ca_413a_84f7_4344c7292997); } #[repr(C)] #[doc(hidden)] pub struct IRfcommServiceProviderStatics_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, serviceid: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct RfcommDeviceService(pub ::windows::core::IInspectable); impl RfcommDeviceService { #[cfg(feature = "Networking")] pub fn ConnectionHostName(&self) -> ::windows::core::Result<super::super::super::Networking::HostName> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Networking::HostName>(result__) } } pub fn ConnectionServiceName(&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 ServiceId(&self) -> ::windows::core::Result<RfcommServiceId> { 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::<RfcommServiceId>(result__) } } #[cfg(feature = "Networking_Sockets")] pub fn ProtectionLevel(&self) -> ::windows::core::Result<super::super::super::Networking::Sockets::SocketProtectionLevel> { let this = self; unsafe { let mut result__: super::super::super::Networking::Sockets::SocketProtectionLevel = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Networking::Sockets::SocketProtectionLevel>(result__) } } #[cfg(feature = "Networking_Sockets")] pub fn MaxProtectionLevel(&self) -> ::windows::core::Result<super::super::super::Networking::Sockets::SocketProtectionLevel> { let this = self; unsafe { let mut result__: super::super::super::Networking::Sockets::SocketProtectionLevel = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Networking::Sockets::SocketProtectionLevel>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams"))] pub fn GetSdpRawAttributesAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<super::super::super::Foundation::Collections::IMapView<u32, super::super::super::Storage::Streams::IBuffer>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<super::super::super::Foundation::Collections::IMapView<u32, super::super::super::Storage::Streams::IBuffer>>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams"))] pub fn GetSdpRawAttributesWithCacheModeAsync(&self, cachemode: super::BluetoothCacheMode) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<super::super::super::Foundation::Collections::IMapView<u32, super::super::super::Storage::Streams::IBuffer>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), cachemode, &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<super::super::super::Foundation::Collections::IMapView<u32, super::super::super::Storage::Streams::IBuffer>>>(result__) } } pub fn Device(&self) -> ::windows::core::Result<super::BluetoothDevice> { let this = &::windows::core::Interface::cast::<IRfcommDeviceService2>(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::BluetoothDevice>(result__) } } #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "Foundation")] pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(deviceid: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<RfcommDeviceService>> { Self::IRfcommDeviceServiceStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<RfcommDeviceService>>(result__) }) } pub fn GetDeviceSelector<'a, Param0: ::windows::core::IntoParam<'a, RfcommServiceId>>(serviceid: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IRfcommDeviceServiceStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), serviceid.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } #[cfg(feature = "Devices_Enumeration")] pub fn DeviceAccessInformation(&self) -> ::windows::core::Result<super::super::Enumeration::DeviceAccessInformation> { let this = &::windows::core::Interface::cast::<IRfcommDeviceService3>(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::Enumeration::DeviceAccessInformation>(result__) } } #[cfg(all(feature = "Devices_Enumeration", feature = "Foundation"))] pub fn RequestAccessAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<super::super::Enumeration::DeviceAccessStatus>> { let this = &::windows::core::Interface::cast::<IRfcommDeviceService3>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<super::super::Enumeration::DeviceAccessStatus>>(result__) } } pub fn GetDeviceSelectorForBluetoothDevice<'a, Param0: ::windows::core::IntoParam<'a, super::BluetoothDevice>>(bluetoothdevice: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IRfcommDeviceServiceStatics2(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), bluetoothdevice.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn GetDeviceSelectorForBluetoothDeviceWithCacheMode<'a, Param0: ::windows::core::IntoParam<'a, super::BluetoothDevice>>(bluetoothdevice: Param0, cachemode: super::BluetoothCacheMode) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IRfcommDeviceServiceStatics2(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), bluetoothdevice.into_param().abi(), cachemode, &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn GetDeviceSelectorForBluetoothDeviceAndServiceId<'a, Param0: ::windows::core::IntoParam<'a, super::BluetoothDevice>, Param1: ::windows::core::IntoParam<'a, RfcommServiceId>>(bluetoothdevice: Param0, serviceid: Param1) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IRfcommDeviceServiceStatics2(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), bluetoothdevice.into_param().abi(), serviceid.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn GetDeviceSelectorForBluetoothDeviceAndServiceIdWithCacheMode<'a, Param0: ::windows::core::IntoParam<'a, super::BluetoothDevice>, Param1: ::windows::core::IntoParam<'a, RfcommServiceId>>(bluetoothdevice: Param0, serviceid: Param1, cachemode: super::BluetoothCacheMode) -> ::windows::core::Result<::windows::core::HSTRING> { Self::IRfcommDeviceServiceStatics2(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), bluetoothdevice.into_param().abi(), serviceid.into_param().abi(), cachemode, &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn IRfcommDeviceServiceStatics<R, F: FnOnce(&IRfcommDeviceServiceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<RfcommDeviceService, IRfcommDeviceServiceStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IRfcommDeviceServiceStatics2<R, F: FnOnce(&IRfcommDeviceServiceStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<RfcommDeviceService, IRfcommDeviceServiceStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for RfcommDeviceService { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService;{ae81ff1f-c5a1-4c40-8c28-f3efd69062f3})"); } unsafe impl ::windows::core::Interface for RfcommDeviceService { type Vtable = IRfcommDeviceService_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xae81ff1f_c5a1_4c40_8c28_f3efd69062f3); } impl ::windows::core::RuntimeName for RfcommDeviceService { const NAME: &'static str = "Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService"; } impl ::core::convert::From<RfcommDeviceService> for ::windows::core::IUnknown { fn from(value: RfcommDeviceService) -> Self { value.0 .0 } } impl ::core::convert::From<&RfcommDeviceService> for ::windows::core::IUnknown { fn from(value: &RfcommDeviceService) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for RfcommDeviceService { 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 RfcommDeviceService { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<RfcommDeviceService> for ::windows::core::IInspectable { fn from(value: RfcommDeviceService) -> Self { value.0 } } impl ::core::convert::From<&RfcommDeviceService> for ::windows::core::IInspectable { fn from(value: &RfcommDeviceService) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for RfcommDeviceService { 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 RfcommDeviceService { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<RfcommDeviceService> for super::super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: RfcommDeviceService) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&RfcommDeviceService> for super::super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &RfcommDeviceService) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::IClosable> for RfcommDeviceService { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::IClosable> for &RfcommDeviceService { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for RfcommDeviceService {} unsafe impl ::core::marker::Sync for RfcommDeviceService {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct RfcommDeviceServicesResult(pub ::windows::core::IInspectable); impl RfcommDeviceServicesResult { pub fn Error(&self) -> ::windows::core::Result<super::BluetoothError> { let this = self; unsafe { let mut result__: super::BluetoothError = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::BluetoothError>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Services(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<RfcommDeviceService>> { 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::super::Foundation::Collections::IVectorView<RfcommDeviceService>>(result__) } } } unsafe impl ::windows::core::RuntimeType for RfcommDeviceServicesResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceServicesResult;{3b48388c-7ccf-488e-9625-d259a5732d55})"); } unsafe impl ::windows::core::Interface for RfcommDeviceServicesResult { type Vtable = IRfcommDeviceServicesResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3b48388c_7ccf_488e_9625_d259a5732d55); } impl ::windows::core::RuntimeName for RfcommDeviceServicesResult { const NAME: &'static str = "Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceServicesResult"; } impl ::core::convert::From<RfcommDeviceServicesResult> for ::windows::core::IUnknown { fn from(value: RfcommDeviceServicesResult) -> Self { value.0 .0 } } impl ::core::convert::From<&RfcommDeviceServicesResult> for ::windows::core::IUnknown { fn from(value: &RfcommDeviceServicesResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for RfcommDeviceServicesResult { 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 RfcommDeviceServicesResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<RfcommDeviceServicesResult> for ::windows::core::IInspectable { fn from(value: RfcommDeviceServicesResult) -> Self { value.0 } } impl ::core::convert::From<&RfcommDeviceServicesResult> for ::windows::core::IInspectable { fn from(value: &RfcommDeviceServicesResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for RfcommDeviceServicesResult { 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 RfcommDeviceServicesResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for RfcommDeviceServicesResult {} unsafe impl ::core::marker::Sync for RfcommDeviceServicesResult {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct RfcommServiceId(pub ::windows::core::IInspectable); impl RfcommServiceId { pub fn Uuid(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn AsShortId(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn AsString(&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 FromUuid<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(uuid: Param0) -> ::windows::core::Result<RfcommServiceId> { Self::IRfcommServiceIdStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uuid.into_param().abi(), &mut result__).from_abi::<RfcommServiceId>(result__) }) } pub fn FromShortId(shortid: u32) -> ::windows::core::Result<RfcommServiceId> { Self::IRfcommServiceIdStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), shortid, &mut result__).from_abi::<RfcommServiceId>(result__) }) } pub fn SerialPort() -> ::windows::core::Result<RfcommServiceId> { Self::IRfcommServiceIdStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RfcommServiceId>(result__) }) } pub fn ObexObjectPush() -> ::windows::core::Result<RfcommServiceId> { Self::IRfcommServiceIdStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RfcommServiceId>(result__) }) } pub fn ObexFileTransfer() -> ::windows::core::Result<RfcommServiceId> { Self::IRfcommServiceIdStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RfcommServiceId>(result__) }) } pub fn PhoneBookAccessPce() -> ::windows::core::Result<RfcommServiceId> { Self::IRfcommServiceIdStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RfcommServiceId>(result__) }) } pub fn PhoneBookAccessPse() -> ::windows::core::Result<RfcommServiceId> { Self::IRfcommServiceIdStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RfcommServiceId>(result__) }) } pub fn GenericFileTransfer() -> ::windows::core::Result<RfcommServiceId> { Self::IRfcommServiceIdStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RfcommServiceId>(result__) }) } pub fn IRfcommServiceIdStatics<R, F: FnOnce(&IRfcommServiceIdStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<RfcommServiceId, IRfcommServiceIdStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for RfcommServiceId { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Rfcomm.RfcommServiceId;{22629204-7e02-4017-8136-da1b6a1b9bbf})"); } unsafe impl ::windows::core::Interface for RfcommServiceId { type Vtable = IRfcommServiceId_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x22629204_7e02_4017_8136_da1b6a1b9bbf); } impl ::windows::core::RuntimeName for RfcommServiceId { const NAME: &'static str = "Windows.Devices.Bluetooth.Rfcomm.RfcommServiceId"; } impl ::core::convert::From<RfcommServiceId> for ::windows::core::IUnknown { fn from(value: RfcommServiceId) -> Self { value.0 .0 } } impl ::core::convert::From<&RfcommServiceId> for ::windows::core::IUnknown { fn from(value: &RfcommServiceId) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for RfcommServiceId { 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 RfcommServiceId { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<RfcommServiceId> for ::windows::core::IInspectable { fn from(value: RfcommServiceId) -> Self { value.0 } } impl ::core::convert::From<&RfcommServiceId> for ::windows::core::IInspectable { fn from(value: &RfcommServiceId) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for RfcommServiceId { 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 RfcommServiceId { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for RfcommServiceId {} unsafe impl ::core::marker::Sync for RfcommServiceId {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct RfcommServiceProvider(pub ::windows::core::IInspectable); impl RfcommServiceProvider { pub fn ServiceId(&self) -> ::windows::core::Result<RfcommServiceId> { 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::<RfcommServiceId>(result__) } } #[cfg(all(feature = "Foundation_Collections", feature = "Storage_Streams"))] pub fn SdpRawAttributes(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IMap<u32, super::super::super::Storage::Streams::IBuffer>> { 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::super::Foundation::Collections::IMap<u32, super::super::super::Storage::Streams::IBuffer>>(result__) } } #[cfg(feature = "Networking_Sockets")] pub fn StartAdvertising<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Networking::Sockets::StreamSocketListener>>(&self, listener: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), listener.into_param().abi()).ok() } } pub fn StopAdvertising(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "Foundation")] pub fn CreateAsync<'a, Param0: ::windows::core::IntoParam<'a, RfcommServiceId>>(serviceid: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<RfcommServiceProvider>> { Self::IRfcommServiceProviderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), serviceid.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<RfcommServiceProvider>>(result__) }) } #[cfg(feature = "Networking_Sockets")] pub fn StartAdvertisingWithRadioDiscoverability<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Networking::Sockets::StreamSocketListener>>(&self, listener: Param0, radiodiscoverable: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IRfcommServiceProvider2>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), listener.into_param().abi(), radiodiscoverable).ok() } } pub fn IRfcommServiceProviderStatics<R, F: FnOnce(&IRfcommServiceProviderStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<RfcommServiceProvider, IRfcommServiceProviderStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for RfcommServiceProvider { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Rfcomm.RfcommServiceProvider;{eadbfdc4-b1f6-44ff-9f7c-e7a82ab86821})"); } unsafe impl ::windows::core::Interface for RfcommServiceProvider { type Vtable = IRfcommServiceProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xeadbfdc4_b1f6_44ff_9f7c_e7a82ab86821); } impl ::windows::core::RuntimeName for RfcommServiceProvider { const NAME: &'static str = "Windows.Devices.Bluetooth.Rfcomm.RfcommServiceProvider"; } impl ::core::convert::From<RfcommServiceProvider> for ::windows::core::IUnknown { fn from(value: RfcommServiceProvider) -> Self { value.0 .0 } } impl ::core::convert::From<&RfcommServiceProvider> for ::windows::core::IUnknown { fn from(value: &RfcommServiceProvider) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for RfcommServiceProvider { 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 RfcommServiceProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<RfcommServiceProvider> for ::windows::core::IInspectable { fn from(value: RfcommServiceProvider) -> Self { value.0 } } impl ::core::convert::From<&RfcommServiceProvider> for ::windows::core::IInspectable { fn from(value: &RfcommServiceProvider) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for RfcommServiceProvider { 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 RfcommServiceProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for RfcommServiceProvider {} unsafe impl ::core::marker::Sync for RfcommServiceProvider {}
//! //! A descriptor is an opaque data structure representing a shader resource. //! For more info see Vulkan docs: (https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#descriptorsets) //! //! With `layout` user can define descriptors as fields for structures that represent descriptor sets. //! use device::Device; use resource::image; use std::ops::Range; /// Type of the descriptor. /// Every descriptor has a type. /// Type must be specified during both layout creation and descriptor writing. #[repr(u32)] #[derive(Clone, Copy, Debug)] pub enum DescriptorType { /// Sampler descriptor. Sampler = 0, /// Image view combined with sampler. CombinedImageSampler = 1, /// Image view to use with sampler. SampledImage = 2, /// Image view for per-pixel access. StorageImage = 3, /// Buffer range with dynamic array of read-only texels. UniformTexelBuffer = 4, /// Buffer range with dynamic array of read-write texels. StorageTexelBuffer = 5, /// Buffer range with read-only uniform structure. UniformBuffer = 6, /// Buffer range with read-write uniform structure. StorageBuffer = 7, #[doc(hidden)] UniformBufferDynamic = 8, #[doc(hidden)] StorageBufferDynamic = 9, #[doc(hidden)] InputAttachment = 10, } #[doc(hidden)] #[derive(Clone, Debug)] pub enum RawDescriptorWrite<'a, D: Device> { Sampler(&'a D::Sampler), CombinedImageSampler(&'a D::Sampler, &'a D::ImageView, image::Layout), SampledImage(&'a D::ImageView, image::Layout), StorageImage(&'a D::ImageView, image::Layout), InputAttachment(&'a D::ImageView, image::Layout), UniformTexelBuffer(&'a D::BufferView), StorageTexelBuffer(&'a D::BufferView), UniformBuffer(&'a D::Buffer, Range<u64>), StorageBuffer(&'a D::Buffer, Range<u64>), UniformBufferDynamic(&'a D::Buffer, Range<u64>), StorageBufferDynamic(&'a D::Buffer, Range<u64>), } #[doc(hidden)] pub trait Descriptor<D: Device, T> { fn descriptor_type() -> DescriptorType; fn write(&self) -> RawDescriptorWrite<'_, D>; } #[doc(hidden)] #[derive(Clone, Copy, Debug)] pub struct SamplerDescriptor; impl<D> Descriptor<D, SamplerDescriptor> for D::Sampler where D: Device, { fn descriptor_type() -> DescriptorType { DescriptorType::Sampler } fn write(&self) -> RawDescriptorWrite<'_, D> { RawDescriptorWrite::Sampler(self) } } #[doc(hidden)] #[derive(Clone, Copy, Debug)] pub struct CombinedImageSamplerDescriptor; impl<D> Descriptor<D, CombinedImageSamplerDescriptor> for (D::Sampler, D::ImageView, image::Layout) where D: Device, { fn descriptor_type() -> DescriptorType { DescriptorType::CombinedImageSampler } fn write(&self) -> RawDescriptorWrite<'_, D> { RawDescriptorWrite::CombinedImageSampler(&self.0, &self.1, self.2) } } #[doc(hidden)] #[derive(Clone, Copy, Debug)] pub struct SampledImageDescriptor; impl<D> Descriptor<D, SampledImageDescriptor> for (D::ImageView, image::Layout) where D: Device, { fn descriptor_type() -> DescriptorType { DescriptorType::SampledImage } fn write(&self) -> RawDescriptorWrite<'_, D> { RawDescriptorWrite::SampledImage(&self.0, self.1) } } #[doc(hidden)] #[derive(Clone, Copy, Debug)] pub struct StorageImageDescriptor; impl<D> Descriptor<D, StorageImageDescriptor> for (D::ImageView, image::Layout) where D: Device, { fn descriptor_type() -> DescriptorType { DescriptorType::StorageImage } fn write(&self) -> RawDescriptorWrite<'_, D> { RawDescriptorWrite::StorageImage(&self.0, self.1) } } #[doc(hidden)] #[derive(Clone, Copy, Debug)] pub struct UniformTexelBufferDescriptor; impl<D> Descriptor<D, UniformTexelBufferDescriptor> for D::BufferView where D: Device, { fn descriptor_type() -> DescriptorType { DescriptorType::UniformTexelBuffer } fn write(&self) -> RawDescriptorWrite<'_, D> { RawDescriptorWrite::UniformTexelBuffer(self) } } #[doc(hidden)] #[derive(Clone, Copy, Debug)] pub struct StorageTexelBufferDescriptor; impl<D> Descriptor<D, StorageTexelBufferDescriptor> for D::BufferView where D: Device, { fn descriptor_type() -> DescriptorType { DescriptorType::StorageTexelBuffer } fn write(&self) -> RawDescriptorWrite<'_, D> { RawDescriptorWrite::StorageTexelBuffer(self) } } #[doc(hidden)] #[derive(Clone, Copy, Debug)] pub struct UniformBufferDescriptor; impl<D> Descriptor<D, UniformBufferDescriptor> for (D::Buffer, Range<u64>) where D: Device, { fn descriptor_type() -> DescriptorType { DescriptorType::UniformBuffer } fn write(&self) -> RawDescriptorWrite<'_, D> { RawDescriptorWrite::UniformBuffer(&self.0, self.1.clone()) } } #[doc(hidden)] #[derive(Clone, Copy, Debug)] pub struct StorageBufferDescriptor; impl<D> Descriptor<D, StorageBufferDescriptor> for (D::Buffer, Range<u64>) where D: Device, { fn descriptor_type() -> DescriptorType { DescriptorType::StorageBuffer } fn write(&self) -> RawDescriptorWrite<'_, D> { RawDescriptorWrite::StorageBuffer(&self.0, self.1.clone()) } } #[doc(hidden)] #[derive(Clone, Copy, Debug)] pub struct UniformBufferDynamicDescriptor; impl<D> Descriptor<D, UniformBufferDynamicDescriptor> for (D::Buffer, Range<u64>) where D: Device, { fn descriptor_type() -> DescriptorType { DescriptorType::UniformBufferDynamic } fn write(&self) -> RawDescriptorWrite<'_, D> { RawDescriptorWrite::UniformBufferDynamic(&self.0, self.1.clone()) } } #[doc(hidden)] #[derive(Clone, Copy, Debug)] pub struct StorageBufferDynamicDescriptor; impl<D> Descriptor<D, StorageBufferDynamicDescriptor> for (D::Buffer, Range<u64>) where D: Device, { fn descriptor_type() -> DescriptorType { DescriptorType::StorageBufferDynamic } fn write(&self) -> RawDescriptorWrite<'_, D> { RawDescriptorWrite::StorageBufferDynamic(&self.0, self.1.clone()) } } #[doc(hidden)] #[derive(Clone, Copy, Debug)] pub struct InputAttachmentDescriptor; impl<D> Descriptor<D, InputAttachmentDescriptor> for (D::ImageView, image::Layout) where D: Device, { fn descriptor_type() -> DescriptorType { DescriptorType::InputAttachment } fn write(&self) -> RawDescriptorWrite<'_, D> { RawDescriptorWrite::InputAttachment(&self.0, self.1) } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use std::sync::Mutex; use std::time::Duration; use std::time::Instant; use common_base::runtime::Runtime; use common_base::runtime::TrySpawn; use common_exception::Result; use once_cell::sync::Lazy; use rand::distributions::Distribution; use rand::distributions::Uniform; use tokio::sync::Semaphore; use tokio::time::sleep; #[tokio::test(flavor = "multi_thread", worker_threads = 8)] async fn test_runtime() -> Result<()> { let counter = Arc::new(Mutex::new(0)); let runtime = Runtime::with_default_worker_threads()?; let runtime_counter = Arc::clone(&counter); let runtime_header = runtime.spawn(async move { let rt1 = Runtime::with_default_worker_threads().unwrap(); let rt1_counter = Arc::clone(&runtime_counter); let rt1_header = rt1.spawn(async move { let rt2 = Runtime::with_worker_threads(1, None).unwrap(); let rt2_counter = Arc::clone(&rt1_counter); let rt2_header = rt2.spawn(async move { let rt3 = Runtime::with_default_worker_threads().unwrap(); let rt3_counter = Arc::clone(&rt2_counter); let rt3_header = rt3.spawn(async move { let mut num = rt3_counter.lock().unwrap(); *num += 1; }); rt3_header.await.unwrap(); let mut num = rt2_counter.lock().unwrap(); *num += 1; }); rt2_header.await.unwrap(); let mut num = rt1_counter.lock().unwrap(); *num += 1; }); rt1_header.await.unwrap(); let mut num = runtime_counter.lock().unwrap(); *num += 1; }); runtime_header.await.unwrap(); let result = *counter.lock().unwrap(); assert_eq!(result, 4); Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_shutdown_long_run_runtime() -> Result<()> { let runtime = Runtime::with_default_worker_threads()?; runtime.spawn(async move { std::thread::sleep(Duration::from_secs(6)); }); let instant = Instant::now(); drop(runtime); assert!(instant.elapsed() >= Duration::from_secs(3)); assert!(instant.elapsed() < Duration::from_secs(4)); Ok(()) } static START_TIME: Lazy<Instant> = Lazy::new(Instant::now); // println can more clearly know if they are parallel async fn mock_get_page(i: usize) -> Vec<usize> { let millis = Uniform::from(0..10).sample(&mut rand::thread_rng()); println!( "[{}] > get_page({}) will complete in {} ms, {:?}", START_TIME.elapsed().as_millis(), i, millis, std::thread::current().id(), ); sleep(Duration::from_millis(millis)).await; println!( "[{}] < get_page({}) completed", START_TIME.elapsed().as_millis(), i ); (i..(i + 1)).collect() } #[tokio::test(flavor = "multi_thread", worker_threads = 8)] async fn test_runtime_try_spawn_batch() -> Result<()> { let runtime = Runtime::with_default_worker_threads()?; let mut futs = vec![]; for i in 0..20 { futs.push(mock_get_page(i)); } let max_concurrency = Semaphore::new(3); let handlers = runtime.try_spawn_batch(max_concurrency, futs).await?; let result = futures::future::try_join_all(handlers).await.unwrap(); assert_eq!(result.len(), 20); Ok(()) }
enum Mode { Char, Tag, Whitespace, } pub fn split(s: &str) -> Vec<&str> { let mut words = vec![]; let mut start = 0; let mut mode = Mode::Char; for (i, c) in s.char_indices() { match mode { Mode::Char if is_start_of_tag(c) => { if start != i { unsafe { words.push(s.get_unchecked(start..i)); } } start = i; mode = Mode::Tag; } Mode::Char if is_whitespace(c) => { if start != i { unsafe { words.push(s.get_unchecked(start..i)); } } start = i; mode = Mode::Whitespace; } Mode::Char => { /* continue */ } Mode::Tag if is_end_of_tag(c) => { unsafe { words.push(s.get_unchecked(start..=i)); } start = i + 1; mode = Mode::Char; } Mode::Tag => { /* continue */ } Mode::Whitespace if is_start_of_tag(c) => { if start != i { unsafe { words.push(s.get_unchecked(start..i)); } } start = i; mode = Mode::Tag; } Mode::Whitespace if is_whitespace(c) => { /* continue */ } Mode::Whitespace => { if start != i { unsafe { words.push(s.get_unchecked(start..i)); } } start = i; mode = Mode::Char; } } } if start < s.len() { words.push(&s[start..]); } words } fn is_end_of_tag(c: char) -> bool { c == '>' } fn is_start_of_tag(c: char) -> bool { c == '<' } fn is_whitespace(c: char) -> bool { c.is_ascii_whitespace() } #[cfg(test)] mod tests { use super::*; #[test] fn test_split_html() { let actual = split("<p>Hello, world!</p>"); let expected = vec!["<p>", "Hello,", " ", "world!", "</p>"]; assert_eq!(actual, expected); } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_base::base::GlobalInstance; use common_catalog::catalog::Catalog; pub use common_catalog::catalog::CatalogManager; use common_catalog::catalog_kind::CATALOG_DEFAULT; use common_config::CatalogConfig; use common_config::InnerConfig; use common_exception::ErrorCode; use common_exception::Result; use common_meta_app::schema::CatalogOption; use common_meta_app::schema::CreateCatalogReq; use common_meta_app::schema::DropCatalogReq; use common_meta_app::schema::IcebergCatalogOption; use common_storage::DataOperator; #[cfg(feature = "hive")] use common_storages_hive::HiveCatalog; use common_storages_iceberg::IcebergCatalog; use dashmap::DashMap; use crate::catalogs::DatabaseCatalog; #[async_trait::async_trait] pub trait CatalogManagerHelper { async fn init(conf: &InnerConfig) -> Result<()>; async fn try_create(conf: &InnerConfig) -> Result<Arc<CatalogManager>>; async fn register_build_in_catalogs(&self, conf: &InnerConfig) -> Result<()>; fn register_external_catalogs(&self, conf: &InnerConfig) -> Result<()>; /// build catalog from sql async fn create_user_defined_catalog(&self, req: CreateCatalogReq) -> Result<()>; fn drop_user_defined_catalog(&self, req: DropCatalogReq) -> Result<()>; } #[async_trait::async_trait] impl CatalogManagerHelper for CatalogManager { async fn init(conf: &InnerConfig) -> Result<()> { GlobalInstance::set(Self::try_create(conf).await?); Ok(()) } async fn try_create(conf: &InnerConfig) -> Result<Arc<CatalogManager>> { let catalog_manager = CatalogManager { catalogs: DashMap::new(), }; catalog_manager.register_build_in_catalogs(conf).await?; #[cfg(feature = "hive")] { catalog_manager.register_external_catalogs(conf)?; } Ok(Arc::new(catalog_manager)) } async fn register_build_in_catalogs(&self, conf: &InnerConfig) -> Result<()> { let default_catalog: Arc<dyn Catalog> = Arc::new(DatabaseCatalog::try_create_with_config(conf.clone()).await?); self.catalogs .insert(CATALOG_DEFAULT.to_owned(), default_catalog); Ok(()) } fn register_external_catalogs(&self, conf: &InnerConfig) -> Result<()> { // currently, if the `hive` feature is not enabled // the loop will quit after the first iteration. // this is expected. #[allow(clippy::never_loop)] for (name, ctl) in conf.catalogs.iter() { match ctl { CatalogConfig::Hive(ctl) => { // register hive catalog #[cfg(not(feature = "hive"))] { return Err(ErrorCode::CatalogNotSupported(format!( "Failed to create catalog {} to {}: Hive catalog is not enabled, please recompile with --features hive", name, ctl.address ))); } #[cfg(feature = "hive")] { let hms_address = ctl.address.clone(); let hive_catalog = Arc::new(HiveCatalog::try_create(hms_address)?); self.catalogs.insert(name.to_string(), hive_catalog); } } } } Ok(()) } async fn create_user_defined_catalog(&self, req: CreateCatalogReq) -> Result<()> { let catalog_option = req.meta.catalog_option; // create catalog first match catalog_option { // NOTE: // when compiling without `hive` feature enabled // `address` will be seem as unused, which is not intentional #[allow(unused)] CatalogOption::Hive(address) => { #[cfg(not(feature = "hive"))] { Err(ErrorCode::CatalogNotSupported( "Hive catalog is not enabled, please recompile with --features hive", )) } #[cfg(feature = "hive")] { let catalog: Arc<dyn Catalog> = Arc::new(HiveCatalog::try_create(address)?); let ctl_name = &req.name_ident.catalog_name; let if_not_exists = req.if_not_exists; self.insert_catalog(ctl_name, catalog, if_not_exists) } } CatalogOption::Iceberg(opt) => { let IcebergCatalogOption { storage_params: sp, flatten, } = opt; let data_operator = DataOperator::try_create(&sp).await?; let ctl_name = &req.name_ident.catalog_name; let catalog: Arc<dyn Catalog> = Arc::new(IcebergCatalog::try_create( ctl_name, flatten, data_operator, )?); let if_not_exists = req.if_not_exists; self.insert_catalog(ctl_name, catalog, if_not_exists) } } } fn drop_user_defined_catalog(&self, req: DropCatalogReq) -> Result<()> { let name = req.name_ident.catalog_name; if name == CATALOG_DEFAULT { return Err(ErrorCode::CatalogNotSupported( "Dropping the DEFAULT catalog is not allowed", )); } match self.catalogs.remove(&name) { Some(_) => Ok(()), None if req.if_exists => Ok(()), None => Err(ErrorCode::CatalogNotFound(format!( "Catalog {} has to be exists", name ))), } } }
use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use std::fmt; use std::ops::Add; #[derive(Debug)] pub struct Money { pub symbol: String, pub value: f64, } impl Add for Money { type Output = Self; fn add(self, other: Self) -> Self { Self { symbol: self.symbol, value: self.value + other.value, } } } impl PartialOrd for Money { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for Money { fn eq(&self, other: &Self) -> bool { self.value == other.value } } impl Ord for Money { fn cmp(&self, other: &Self) -> Ordering { match self.value { v if v == other.value => Ordering::Equal, v if v >= other.value => Ordering::Greater, v if v <= other.value => Ordering::Less, _ => panic!("Invalid value"), } } } impl Eq for Money {} #[derive(PartialEq)] pub struct User { pub name: String, pub age: usize, } impl Add for User { type Output = Self; fn add(self, other: Self) -> Self { Self { name: self.name.add(" ").add(&other.name), age: self.age + other.age, } } } impl fmt::Debug for User { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Name: {}, Age: {}", self.name, self.age) } } #[test] fn money_add_test() { let money1 = Money { symbol: "€".to_string(), value: 10.5, }; let money2 = Money { symbol: "€".to_string(), value: 9.0, }; assert_eq!( money1 + money2, Money { symbol: "€".to_string(), value: 19.5 } ); let money3 = Money { symbol: "€".to_string(), value: 20.5, }; let money4 = Money { symbol: "€".to_string(), value: 10.0, }; let mut moneyvec = vec![money3, money4]; moneyvec.sort(); assert_eq!( moneyvec, vec![ Money { symbol: "€".to_string(), value: 10.0 }, Money { symbol: "€".to_string(), value: 20.5 } ] ); } #[test] fn user_add_test() { let user1 = User { name: "Carlos".to_string(), age: 34, }; let user2 = User { name: "Pedro".to_string(), age: 20, }; let user_sum = user1 + user2; assert_eq!(user_sum.name, "Carlos Pedro".to_string()); assert_eq!(user_sum.age, 54); } #[test] fn user_eq_test() { let user3 = User { name: "Pedro".to_string(), age: 20, }; let user4 = User { name: "Pedro".to_string(), age: 20, }; //This works because User implements Debug trait assert_eq!(user3, user4); }
//! Hardware Abstraction Layer #![no_std] #![feature(linkage)] #![deny(warnings)] extern crate alloc; pub mod defs { use bitflags::bitflags; bitflags! { pub struct MMUFlags: usize { #[allow(clippy::identity_op)] const READ = 1 << 0; const WRITE = 1 << 1; const EXECUTE = 1 << 2; const USER = 1 << 3; } } pub type PhysAddr = usize; pub type VirtAddr = usize; pub const PAGE_SIZE: usize = 0x1000; } mod dummy; mod future; pub mod user; pub mod vdso; pub use self::defs::*; pub use self::dummy::*; pub use self::future::*; pub use trapframe::{GeneralRegs, UserContext, VectorRegs};
//! Web3 Error use derive_more::{Display, From}; use serde_json::Error as SerdeError; use std::io::Error as IoError; /// Errors which can occur when attempting to generate resource uri. #[derive(Debug, Display, From)] pub enum Error { /// server is unreachable #[display(fmt = "Server is unreachable")] Unreachable, /// decoder error #[display(fmt = "Decoder error: {}", _0)] Decoder(String), /// invalid response #[display(fmt = "Got invalid response: {}", _0)] #[from(ignore)] InvalidResponse(String), /// transport error #[display(fmt = "Transport error: {}", _0)] #[from(ignore)] Transport(String), /// io error #[display(fmt = "IO error: {}", _0)] Io(IoError), /// web3 internal error #[display(fmt = "Internal Web3 error")] Internal, #[display(fmt = "other lib: {}", _0)] #[from(ignore)] Other(String), #[display(fmt = "secp256k1 error: {}", _0)] Secp256k1(secp256k1::Error), } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { use self::Error::*; match *self { Unreachable | Decoder(_) | InvalidResponse(_) | Transport(_) | Internal | Other(_) => None, Io(ref e) => Some(e), Secp256k1(ref e) => Some(e), } } } impl From<SerdeError> for Error { fn from(err: SerdeError) -> Self { Error::Decoder(format!("{:?}", err)) } } impl From<ethabi::Error> for Error { fn from(err: ethabi::Error) -> Self { Error::Decoder(format!("{:?}", err)) } } impl From<hex::FromHexError> for Error { fn from(err: hex::FromHexError) -> Self { Error::Decoder(format!("{:?}", err)) } } impl From<std::string::FromUtf8Error> for Error { fn from(err: std::string::FromUtf8Error) -> Self { Error::Decoder(format!("{:?}", err)) } } impl From<tiny_hderive::Error> for Error { fn from(err: tiny_hderive::Error) -> Self { Error::Other(format!("{:?}", err)) } } impl From<failure::Error> for Error { fn from(err: failure::Error) -> Self { Error::Other(format!("{:?}", err)) } } impl Clone for Error { fn clone(&self) -> Self { use self::Error::*; match self { Unreachable => Unreachable, Decoder(s) => Decoder(s.clone()), InvalidResponse(s) => InvalidResponse(s.clone()), Transport(s) => Transport(s.clone()), Io(e) => Io(IoError::from(e.kind())), Secp256k1(e) => Secp256k1(*e), Internal => Internal, Other(s) => Other(s.clone()), } } } impl PartialEq for Error { fn eq(&self, other: &Self) -> bool { use self::Error::*; match (self, other) { (Unreachable, Unreachable) | (Internal, Internal) => true, (Decoder(a), Decoder(b)) | (InvalidResponse(a), InvalidResponse(b)) | (Transport(a), Transport(b)) => { a == b } (Io(a), Io(b)) => a.kind() == b.kind(), _ => false, } } }
use client_util::connection::GrpcConnection; use self::generated_types::{table_service_client::TableServiceClient, *}; use crate::connection::Connection; use crate::error::Error; use ::generated_types::google::OptionalField; /// Re-export generated_types pub mod generated_types { pub use generated_types::influxdata::iox::{ partition_template::v1::{template_part::*, *}, table::v1::*, }; } /// A basic client for working with Tables. #[derive(Debug, Clone)] pub struct Client { inner: TableServiceClient<GrpcConnection>, } impl Client { /// Creates a new client with the provided connection pub fn new(connection: Connection) -> Self { Self { inner: TableServiceClient::new(connection.into_grpc_connection()), } } /// Create a table pub async fn create_table( &mut self, namespace: &str, table: &str, partition_template: Option<PartitionTemplate>, ) -> Result<Table, Error> { let response = self .inner .create_table(CreateTableRequest { name: table.to_string(), namespace: namespace.to_string(), partition_template, }) .await?; Ok(response.into_inner().table.unwrap_field("table")?) } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use fidl_fuchsia_ledger_cloud_test::{ CloudControllerFactoryRequest, CloudControllerFactoryRequestStream, CloudControllerRequest, CloudControllerRequestStream, NetworkState, }; use futures::future::LocalFutureObj; use futures::prelude::*; use futures::select; use futures::stream::FuturesUnordered; use std::cell::RefCell; use std::rc::Rc; use crate::filter; use crate::session::{CloudSession, CloudSessionFuture, CloudSessionShared}; use crate::state::Cloud; fn filter_for_network_state(s: NetworkState) -> Box<dyn filter::RequestFilter> { match s { NetworkState::Connected => Box::new(filter::Always::new(filter::Status::Ok)), NetworkState::Disconnected => Box::new(filter::Always::new(filter::Status::NetworkError)), NetworkState::InjectNetworkErrors => Box::new(filter::Flaky::new(2)), } } pub struct CloudControllerFactory { storage: Rc<RefCell<Cloud>>, controllers: FuturesUnordered<CloudControllerFuture>, requests: stream::Fuse<CloudControllerFactoryRequestStream>, } type CloudControllerFactoryFuture = LocalFutureObj<'static, ()>; impl CloudControllerFactory { pub fn new(requests: CloudControllerFactoryRequestStream) -> CloudControllerFactory { CloudControllerFactory { storage: Rc::new(RefCell::new(Cloud::new())), controllers: FuturesUnordered::new(), requests: requests.fuse(), } } async fn handle_requests(mut self) -> Result<(), fidl::Error> { loop { select! { _ = self.controllers.next() => { // One of the controller futures completed. We // don't need to do anything. }, req = self.requests.try_next() => match req? { None => return Ok(()), Some(CloudControllerFactoryRequest::Build {controller, ..}) => { let controller = controller.into_stream()?; self.controllers.push(CloudController::new(self.storage.clone(), controller).run()) } } } } } pub fn run(self) -> CloudControllerFactoryFuture { LocalFutureObj::new(Box::new(self.handle_requests().map(|_| ()))) } } struct CloudController { cloud_futures: FuturesUnordered<CloudSessionFuture>, controller_requests: stream::Fuse<CloudControllerRequestStream>, cloud_state: Rc<CloudSessionShared>, } type CloudControllerFuture = LocalFutureObj<'static, ()>; impl CloudController { fn new( storage: Rc<RefCell<Cloud>>, controller: CloudControllerRequestStream, ) -> CloudController { let state = Rc::new(CloudSessionShared::new(storage)); CloudController { controller_requests: controller.fuse(), cloud_state: state, cloud_futures: FuturesUnordered::new(), } } async fn handle_requests(mut self) -> Result<(), fidl::Error> { loop { select! { _ = self.cloud_futures.next() => { // One of the cloud provider futures completed. We // don't need to do anything. }, req = self.controller_requests.try_next() => match req? { None => return Ok(()), Some(CloudControllerRequest::SetNetworkState {state, responder}) => { self.cloud_state.set_filter(filter_for_network_state(state)); responder.send()? }, Some(CloudControllerRequest::Connect {provider, ..}) => { let provider = provider.into_stream()?; self.cloud_futures.push(CloudSession::new(Rc::clone(&self.cloud_state), provider).run()) } } } } } fn run(self) -> CloudControllerFuture { LocalFutureObj::new(Box::new(self.handle_requests().map(|_| ()))) } } #[cfg(test)] mod tests { use fidl::endpoints::create_endpoints; use fidl_fuchsia_ledger_cloud::{ CloudProviderMarker, CloudProviderProxy, DeviceSetMarker, DeviceSetProxy, Status, }; use fidl_fuchsia_ledger_cloud_test::{ CloudControllerFactoryMarker, CloudControllerFactoryProxy, CloudControllerMarker, CloudControllerProxy, NetworkState, }; use fuchsia_async as fasync; use pin_utils::pin_mut; use super::*; struct DeviceSetConnection { cloud_controller: CloudControllerProxy, #[allow(unused)] cloud_provider: CloudProviderProxy, device_set: DeviceSetProxy, } async fn connect_device_set( factory: &CloudControllerFactoryProxy, ) -> Result<DeviceSetConnection, fidl::Error> { let (cloud_controller, cloud_controller_request) = create_endpoints::<CloudControllerMarker>()?; factory.build(cloud_controller_request)?; let cloud_controller = cloud_controller.into_proxy()?; let (cloud_provider, cloud_provider_request) = create_endpoints::<CloudProviderMarker>()?; cloud_controller.connect(cloud_provider_request)?; let cloud_provider = cloud_provider.into_proxy()?; let (device_set, device_set_request) = create_endpoints::<DeviceSetMarker>()?; assert_eq!(cloud_provider.get_device_set(device_set_request).await?, Status::Ok); let device_set = device_set.into_proxy()?; Ok(DeviceSetConnection { cloud_controller, cloud_provider, device_set }) } #[test] /// Checks that instances from a cloud controller factory share /// their cloud state. fn cloud_controller_factory_cloud_shared() { let mut exec = fasync::Executor::new().unwrap(); let (client, server) = create_endpoints::<CloudControllerFactoryMarker>().unwrap(); let stream = server.into_stream().unwrap(); let server_fut = CloudControllerFactory::new(stream).run(); fasync::spawn_local(server_fut); let proxy = client.into_proxy().unwrap(); let client_fut = async move { let client0 = connect_device_set(&proxy).await.unwrap(); let client1 = connect_device_set(&proxy).await.unwrap(); let fingerprint = || vec![1, 2, 3].into_iter(); assert_eq!( client0.device_set.set_fingerprint(&mut fingerprint()).await.unwrap(), Status::Ok ); assert_eq!( client1.device_set.check_fingerprint(&mut fingerprint()).await.unwrap(), Status::Ok ); }; pin_mut!(client_fut); assert!(exec.run_until_stalled(&mut client_fut).is_ready()); } #[test] /// Checks that instances from a cloud controller factory do not /// share their network state. fn cloud_controller_factory_network_unshared() { let mut exec = fasync::Executor::new().unwrap(); let (client, server) = create_endpoints::<CloudControllerFactoryMarker>().unwrap(); let stream = server.into_stream().unwrap(); let server_fut = CloudControllerFactory::new(stream).run(); fasync::spawn_local(server_fut); let proxy = client.into_proxy().unwrap(); let client_fut = async move { let client0 = connect_device_set(&proxy).await.unwrap(); let client1 = connect_device_set(&proxy).await.unwrap(); let fingerprint = || vec![1, 2, 3].into_iter(); // Disconnect the first provider. client0.cloud_controller.set_network_state(NetworkState::Disconnected).await.unwrap(); assert_eq!( client0.device_set.check_fingerprint(&mut fingerprint()).await.unwrap(), Status::NetworkError ); assert_eq!( client1.device_set.check_fingerprint(&mut fingerprint()).await.unwrap(), Status::NotFound ); }; pin_mut!(client_fut); assert!(exec.run_until_stalled(&mut client_fut).is_ready()); } }
struct ImportantExcerpt<'a> { part: &'a str, } fn main() { let novel = String::from("Call me RbertKo. Some years ago..."); let first_sentence = novel.split('.') .next() .expect("could not find a '.'"); let i = ImportantExcerpt { part: first_sentence }; let s: &'static str = "I have a static lifetime."; } ///////////////////// // 라이프타임 생략 규칙 (lifetime elision rules) fn first_word<'a>(s: &'a str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] }
extern crate failure; use rust_bert::gpt2::{Gpt2ConfigResources, Gpt2VocabResources, Gpt2MergesResources, Gpt2ModelResources}; use rust_bert::distilbert::{DistilBertModelResources, DistilBertConfigResources, DistilBertVocabResources}; use rust_bert::openai_gpt::{OpenAiGptConfigResources, OpenAiGptVocabResources, OpenAiGptMergesResources, OpenAiGptModelResources}; use rust_bert::roberta::{RobertaConfigResources, RobertaVocabResources, RobertaMergesResources, RobertaModelResources}; use rust_bert::bert::{BertConfigResources, BertVocabResources, BertModelResources}; use rust_bert::bart::{BartConfigResources, BartVocabResources, BartMergesResources, BartModelResources}; use rust_bert::resources::{Resource, download_resource, RemoteResource}; use rust_bert::electra::{ElectraConfigResources, ElectraVocabResources, ElectraModelResources}; /// This example downloads and caches all dependencies used in model tests. This allows for safe /// multi threaded testing (two test using the same resource would otherwise download the file to /// the same location). fn download_distil_gpt2() -> failure::Fallible<()> { // Shared under Apache 2.0 license by the HuggingFace Inc. team at https://huggingface.co/models. Modified with conversion to C-array format. let config_resource = Resource::Remote(RemoteResource::from_pretrained(Gpt2ConfigResources::DISTIL_GPT2)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(Gpt2VocabResources::DISTIL_GPT2)); let merges_resource = Resource::Remote(RemoteResource::from_pretrained(Gpt2MergesResources::DISTIL_GPT2)); let weights_resource = Resource::Remote(RemoteResource::from_pretrained(Gpt2ModelResources::DISTIL_GPT2)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&merges_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn download_distilbert_sst2() -> failure::Fallible<()> { // Shared under Apache 2.0 license by the HuggingFace Inc. team at https://huggingface.co/models. Modified with conversion to C-array format. let weights_resource = Resource::Remote(RemoteResource::from_pretrained(DistilBertModelResources::DISTIL_BERT_SST2)); let config_resource = Resource::Remote(RemoteResource::from_pretrained(DistilBertConfigResources::DISTIL_BERT_SST2)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(DistilBertVocabResources::DISTIL_BERT_SST2)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn download_distilbert_qa() -> failure::Fallible<()> { // Shared under Apache 2.0 license by the HuggingFace Inc. team at https://huggingface.co/models. Modified with conversion to C-array format. let weights_resource = Resource::Remote(RemoteResource::from_pretrained(DistilBertModelResources::DISTIL_BERT_SQUAD)); let config_resource = Resource::Remote(RemoteResource::from_pretrained(DistilBertConfigResources::DISTIL_BERT_SQUAD)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(DistilBertVocabResources::DISTIL_BERT_SQUAD)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn download_distilbert() -> failure::Fallible<()> { // Shared under Apache 2.0 license by the HuggingFace Inc. team at https://huggingface.co/models. Modified with conversion to C-array format. let weights_resource = Resource::Remote(RemoteResource::from_pretrained(DistilBertModelResources::DISTIL_BERT)); let config_resource = Resource::Remote(RemoteResource::from_pretrained(DistilBertConfigResources::DISTIL_BERT)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(DistilBertVocabResources::DISTIL_BERT)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn download_gpt2() -> failure::Fallible<()> { // Shared under Modified MIT license by the OpenAI team at https://github.com/openai/gpt-2. Modified with conversion to C-array format. let config_resource = Resource::Remote(RemoteResource::from_pretrained(Gpt2ConfigResources::GPT2)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(Gpt2VocabResources::GPT2)); let merges_resource = Resource::Remote(RemoteResource::from_pretrained(Gpt2MergesResources::GPT2)); let weights_resource = Resource::Remote(RemoteResource::from_pretrained(Gpt2ModelResources::GPT2)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&merges_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn download_gpt() -> failure::Fallible<()> { // Shared under MIT license by the OpenAI team at https://github.com/openai/finetune-transformer-lm. Modified with conversion to C-array format. let config_resource = Resource::Remote(RemoteResource::from_pretrained(OpenAiGptConfigResources::GPT)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(OpenAiGptVocabResources::GPT)); let merges_resource = Resource::Remote(RemoteResource::from_pretrained(OpenAiGptMergesResources::GPT)); let weights_resource = Resource::Remote(RemoteResource::from_pretrained(OpenAiGptModelResources::GPT)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&merges_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn download_roberta() -> failure::Fallible<()> { // Shared under MIT license by the Facebook AI Research Fairseq team at https://github.com/pytorch/fairseq. Modified with conversion to C-array format. let config_resource = Resource::Remote(RemoteResource::from_pretrained(RobertaConfigResources::ROBERTA)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(RobertaVocabResources::ROBERTA)); let merges_resource = Resource::Remote(RemoteResource::from_pretrained(RobertaMergesResources::ROBERTA)); let weights_resource = Resource::Remote(RemoteResource::from_pretrained(RobertaModelResources::ROBERTA)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&merges_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn download_bert() -> failure::Fallible<()> { // Shared under Apache 2.0 license by the Google team at https://github.com/google-research/bert. Modified with conversion to C-array format. let config_resource = Resource::Remote(RemoteResource::from_pretrained(BertConfigResources::BERT)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(BertVocabResources::BERT)); let weights_resource = Resource::Remote(RemoteResource::from_pretrained(BertModelResources::BERT)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn download_bert_ner() -> failure::Fallible<()> { // Shared under MIT license by the MDZ Digital Library team at the Bavarian State Library at https://github.com/dbmdz/berts. Modified with conversion to C-array format. let config_resource = Resource::Remote(RemoteResource::from_pretrained(BertConfigResources::BERT_NER)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(BertVocabResources::BERT_NER)); let weights_resource = Resource::Remote(RemoteResource::from_pretrained(BertModelResources::BERT_NER)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn download_bart() -> failure::Fallible<()> { // Shared under MIT license by the Facebook AI Research Fairseq team at https://github.com/pytorch/fairseq. Modified with conversion to C-array format. let config_resource = Resource::Remote(RemoteResource::from_pretrained(BartConfigResources::BART)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(BartVocabResources::BART)); let merges_resource = Resource::Remote(RemoteResource::from_pretrained(BartMergesResources::BART)); let weights_resource = Resource::Remote(RemoteResource::from_pretrained(BartModelResources::BART)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&merges_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn download_bart_cnn() -> failure::Fallible<()> { // Shared under MIT license by the Facebook AI Research Fairseq team at https://github.com/pytorch/fairseq. Modified with conversion to C-array format. let config_resource = Resource::Remote(RemoteResource::from_pretrained(BartConfigResources::BART_CNN)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(BartVocabResources::BART_CNN)); let merges_resource = Resource::Remote(RemoteResource::from_pretrained(BartMergesResources::BART_CNN)); let weights_resource = Resource::Remote(RemoteResource::from_pretrained(BartModelResources::BART_CNN)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&merges_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn download_electra_generator() -> failure::Fallible<()> { // Shared under Apache 2.0 license by the Google team at https://github.com/google-research/electra. Modified with conversion to C-array format. let config_resource = Resource::Remote(RemoteResource::from_pretrained(ElectraConfigResources::BASE_GENERATOR)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(ElectraVocabResources::BASE_GENERATOR)); let weights_resource = Resource::Remote(RemoteResource::from_pretrained(ElectraModelResources::BASE_GENERATOR)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn download_electra_discriminator() -> failure::Fallible<()> { // Shared under Apache 2.0 license by the Google team at https://github.com/google-research/electra. Modified with conversion to C-array format. let config_resource = Resource::Remote(RemoteResource::from_pretrained(ElectraConfigResources::BASE_DISCRIMINATOR)); let vocab_resource = Resource::Remote(RemoteResource::from_pretrained(ElectraVocabResources::BASE_DISCRIMINATOR)); let weights_resource = Resource::Remote(RemoteResource::from_pretrained(ElectraModelResources::BASE_DISCRIMINATOR)); let _ = download_resource(&config_resource)?; let _ = download_resource(&vocab_resource)?; let _ = download_resource(&weights_resource)?; Ok(()) } fn main() -> failure::Fallible<()> { let _ = download_distil_gpt2(); let _ = download_distilbert_sst2(); let _ = download_distilbert_qa(); let _ = download_distilbert(); let _ = download_gpt2(); let _ = download_gpt(); let _ = download_roberta(); let _ = download_bert(); let _ = download_bert_ner(); let _ = download_bart(); let _ = download_bart_cnn(); let _ = download_electra_generator(); let _ = download_electra_discriminator(); Ok(()) }
#![allow(unused_attributes)] #![allow(clippy::type_complexity)] #![feature(no_coverage)] #![feature(bench_black_box)] use std::fmt::Debug; use fuzzcheck::mutators::boxed::BoxMutator; use fuzzcheck::mutators::integer::U8Mutator; use fuzzcheck::mutators::option::OptionMutator; use fuzzcheck::mutators::recursive::RecurToMutator; use fuzzcheck::mutators::testing_utilities::test_mutator; use fuzzcheck::mutators::tuples::{Tuple2, Tuple2Mutator, TupleMutatorWrapper}; use fuzzcheck::mutators::vector::VecMutator; use fuzzcheck::{make_mutator, DefaultMutator, Mutator}; #[derive(Clone, Debug, PartialEq, Eq, Hash)] struct SampleStruct<T, U> { w: Option<Box<SampleStruct<T, U>>>, x: T, y: U, z: Vec<(u8, SampleStruct<T, U>)>, } make_mutator! { name: SampleStructMutator, recursive: true, default: true, type: struct SampleStruct<T, U> { #[field_mutator( OptionMutator<Box<SampleStruct<T, U>>, BoxMutator<RecurToMutator<SampleStructMutator<T, U, M1, M2>>>> = { OptionMutator::new(BoxMutator::new(self_.into())) } )] w: Option<Box<SampleStruct<T, U>>>, x: T, y: U, #[field_mutator( VecMutator< (u8, SampleStruct<T, U>), TupleMutatorWrapper< Tuple2Mutator< U8Mutator, RecurToMutator< SampleStructMutator<T, U, M1, M2> > >, Tuple2<u8, SampleStruct<T, U>> > > = { VecMutator::new( TupleMutatorWrapper::new( Tuple2Mutator::new( u8::default_mutator(), self_.into() ) ), 0..=usize::MAX ) } )] z: Vec<(u8, SampleStruct<T, U>)>, } } #[allow(clippy::vec_box)] #[derive(Clone, Debug, PartialEq, Eq, Hash)] struct SampleStruct2 { w: Vec<Box<SampleStruct2>>, } make_mutator! { name: SampleStruct2Mutator, recursive: true, default: true, type: struct SampleStruct2 { #[field_mutator( VecMutator<Box<SampleStruct2>, BoxMutator<RecurToMutator<SampleStruct2Mutator>>> = { VecMutator::new(BoxMutator::new(self_.into()), 0..=10) } )] w: Vec<Box<SampleStruct2>>, } } #[test] fn test_derived_struct() { let mutator = SampleStruct2::default_mutator(); // test_mutator(mutator, 100., 100., false, true, 50, 50); for _ in 0..1 { assert!(mutator.validate_value(&SampleStruct2 { w: vec![] }).is_some()); } std::hint::black_box(mutator); let mutator = <Vec<SampleStruct<u8, u8>>>::default_mutator(); test_mutator(mutator, 500., 500., false, true, 50, 100); }
#[doc = "Reader of register PLLFREQ0"] pub type R = crate::R<u32, super::PLLFREQ0>; #[doc = "Writer for register PLLFREQ0"] pub type W = crate::W<u32, super::PLLFREQ0>; #[doc = "Register PLLFREQ0 `reset()`'s with value 0"] impl crate::ResetValue for super::PLLFREQ0 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `MINT`"] pub type MINT_R = crate::R<u16, u16>; #[doc = "Write proxy for field `MINT`"] pub struct MINT_W<'a> { w: &'a mut W, } impl<'a> MINT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0x03ff) | ((value as u32) & 0x03ff); self.w } } #[doc = "Reader of field `MFRAC`"] pub type MFRAC_R = crate::R<u16, u16>; #[doc = "Write proxy for field `MFRAC`"] pub struct MFRAC_W<'a> { w: &'a mut W, } impl<'a> MFRAC_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03ff << 10)) | (((value as u32) & 0x03ff) << 10); self.w } } impl R { #[doc = "Bits 0:9 - PLL M Integer Value"] #[inline(always)] pub fn mint(&self) -> MINT_R { MINT_R::new((self.bits & 0x03ff) as u16) } #[doc = "Bits 10:19 - PLL M Fractional Value"] #[inline(always)] pub fn mfrac(&self) -> MFRAC_R { MFRAC_R::new(((self.bits >> 10) & 0x03ff) as u16) } } impl W { #[doc = "Bits 0:9 - PLL M Integer Value"] #[inline(always)] pub fn mint(&mut self) -> MINT_W { MINT_W { w: self } } #[doc = "Bits 10:19 - PLL M Fractional Value"] #[inline(always)] pub fn mfrac(&mut self) -> MFRAC_W { MFRAC_W { w: self } } }
extern crate day06; use std::env; use std::io; use std::io::BufRead; use day06::reallocate; fn main() { let input: String = match env::args().nth(1) { None => { eprintln!("Usage: {} [input_string | -]", env::args().nth(0).unwrap()); eprintln!("If - is given as argument, read from stdin."); std::process::exit(0); }, Some(input) => input, }; if "-".eq(&input) { let stdin = io::stdin(); let handle = stdin.lock(); handle.lines().for_each(|line_res| { match line_res { Ok(line) => run_compute(&line), Err(err) => eprintln!("Could not read input: {}", err), } }); } else { run_compute(&input) } } fn run_compute(line: &str) { let mut banks: Vec<u32> = vec![]; for bank in line.split_whitespace() { match u32::from_str_radix(bank, 10) { Ok(bank) => banks.push(bank), Err(err) => { eprintln!("Not a number: {} ({})", bank, err); return; }, } } let result = reallocate(&mut banks); println!("{}", result); }
mod day01; mod day02; mod day03; fn main() { //day01::sol(); //day02::sol(); day03::sol(); }
#![cfg(all(feature = "os-poll", feature = "tcp"))] use mio::net::TcpListener; use mio::{Events, Interest, Poll, Token}; use std::time::Duration; mod util; use util::init; // // There's a race condition if this test run in parallel with other tests. // Right after fd is closed below, anyone can open a new file/socket and system // might allocate the same fd for him. In such case test fails because it // receives an event generated by another test running at the same time since // it monitors fd owned by someone else. // // The test is alone in this source file on purpose to run single threaded and // avoid above race condition. // #[test] fn listen_then_close() { init(); let mut poll = Poll::new().unwrap(); let mut l = TcpListener::bind("127.0.0.1:0".parse().unwrap()).unwrap(); poll.registry() .register(&mut l, Token(1), Interest::READABLE) .unwrap(); drop(l); let mut events = Events::with_capacity(128); poll.poll(&mut events, Some(Duration::from_millis(100))) .unwrap(); for event in &events { if event.token() == Token(1) { panic!("received ready() on a closed TcpListener") } } }
//! ECS Component declarations for data structures in the crate, this needs to be here and not in //! rhusics-ecs because of the orphan rule. use cgmath::prelude::*; use cgmath::BaseFloat; use collision::prelude::*; use specs::prelude::{Component, DenseVecStorage, FlaggedStorage}; use collide::CollisionShape; use physics::{ForceAccumulator, Mass, PhysicalEntity, Velocity}; use {BodyPose, NextFrame}; impl<P, R> Component for BodyPose<P, R> where P: EuclideanSpace + Send + Sync + 'static, P::Scalar: BaseFloat, R: Rotation<P> + Send + Sync + 'static, { type Storage = FlaggedStorage<Self, DenseVecStorage<Self>>; } impl<T> Component for NextFrame<T> where T: Send + Sync + 'static, { type Storage = FlaggedStorage<Self, DenseVecStorage<Self>>; } impl<P, T, B, Y> Component for CollisionShape<P, T, B, Y> where T: Send + Sync + 'static, Y: Send + Sync + 'static, P: Primitive + Send + Sync + 'static, B: Bound + Send + Sync + 'static, { type Storage = DenseVecStorage<CollisionShape<P, T, B, Y>>; } impl<V, A> Component for Velocity<V, A> where V: Send + Sync + 'static + Clone, A: Send + Sync + 'static + Clone, { type Storage = DenseVecStorage<Self>; } impl<S, I> Component for Mass<S, I> where S: Send + Sync + 'static, I: Send + Sync + 'static, { type Storage = DenseVecStorage<Self>; } impl<S> Component for PhysicalEntity<S> where S: Send + Sync + 'static, { type Storage = DenseVecStorage<Self>; } impl<F, A> Component for ForceAccumulator<F, A> where F: Send + Sync + 'static, A: Send + Sync + 'static, { type Storage = DenseVecStorage<Self>; }
extern crate visitor; use visitor::expr::*; /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // struct Harvest<'a> { pub acc: Vec<&'a Term>, } fn harvest(t: &Term) -> Vec<&Term> { Harvest::new(&t).acc } impl<'a> Harvest<'a> { fn new(t: &'a Term) -> Harvest<'a> { let mut h = Harvest { acc: Vec::new() }; t.accept(&mut h); h } } impl<'a> Visitor<'a> for Harvest<'a> { fn object(&mut self) -> &mut dyn Visitor<'a> { self } fn visit_term(&mut self, t: &'a Term) { self.acc.push(t); t.recurse(self.object()) } } pub fn main() { println!("{:?}", harvest(&(parse("1 + 2 + (3 +(-8))").unwrap()))) }
//! Integration test for zkSync Rust SDK. //! //! In order to pass these tests, there must be a running //! instance of zkSync server and prover: //! //! ```bash //! zksync server &! //! zksync dummy-prover &! //! zksync sdk-test //! ``` use futures::compat::Future01CompatExt; use std::time::{Duration, Instant}; use zksync::{ web3::types::{H160, H256, U256}, zksync_models::node::tx::PackedEthSignature, EthereumProvider, Network, Provider, Wallet, WalletCredentials, }; const ETH_ADDR: &str = "36615Cf349d7F6344891B1e7CA7C72883F5dc049"; const ETH_PRIVATE_KEY: &str = "7726827caac94a7f9e1b160f7ea819f172f7b6f9d2a97f992c38edeab82d4110"; const LOCALHOST_WEB3_ADDR: &str = "http://127.0.0.1:8545"; fn eth_main_account_credentials() -> (H160, H256) { let addr = ETH_ADDR.parse().unwrap(); let eth_private_key = ETH_PRIVATE_KEY.parse().unwrap(); (addr, eth_private_key) } fn eth_random_account_credentials() -> (H160, H256) { // let addr = ETH_ADDR.parse().unwrap(); let mut eth_private_key = H256::default(); eth_private_key.randomize(); let address_from_pk = PackedEthSignature::address_from_private_key(&eth_private_key).unwrap(); (address_from_pk, eth_private_key) } fn one_ether() -> U256 { U256::from(10).pow(18.into()) } async fn wait_for_eth_tx(ethereum: &EthereumProvider, hash: H256) { let timeout = Duration::from_secs(10); let mut poller = tokio::time::interval(std::time::Duration::from_millis(100)); let web3 = ethereum.web3(); let start = Instant::now(); while web3 .eth() .transaction_receipt(hash) .compat() .await .unwrap() .is_none() { if start.elapsed() > timeout { panic!("Timeout elapsed while waiting for Ethereum transaction"); } poller.tick().await; } } async fn wait_for_deposit_and_update_account_id(wallet: &mut Wallet) { let timeout = Duration::from_secs(60); let mut poller = tokio::time::interval(std::time::Duration::from_millis(100)); let start = Instant::now(); while wallet .provider .account_info(wallet.address()) .await .unwrap() .id .is_none() { if start.elapsed() > timeout { panic!("Timeout elapsed while waiting for Ethereum transaction"); } poller.tick().await; } wallet.update_account_id().await.unwrap(); assert!(wallet.account_id().is_some(), "Account ID was not set"); } async fn transfer_eth_to(to: H160) { let (main_eth_address, main_eth_private_key) = eth_main_account_credentials(); let provider = Provider::new(Network::Localhost); let credentials = WalletCredentials::from_eth_pk(main_eth_address, main_eth_private_key, Network::Localhost) .unwrap(); let wallet = Wallet::new(provider, credentials).await.unwrap(); let ethereum = wallet.ethereum(LOCALHOST_WEB3_ADDR).await.unwrap(); let hash = ethereum.transfer("ETH", one_ether(), to).await.unwrap(); wait_for_eth_tx(&ethereum, hash).await; } #[tokio::test] #[cfg_attr(not(feature = "integration-tests"), ignore)] async fn simple_workflow() -> Result<(), anyhow::Error> { let (eth_address, eth_private_key) = eth_random_account_credentials(); // Transfer funds from "rich" account to a randomly created one (so we won't reuse the same // account in subsequent test runs). transfer_eth_to(eth_address).await; let provider = Provider::new(Network::Localhost); let credentials = WalletCredentials::from_eth_pk(eth_address, eth_private_key, Network::Localhost).unwrap(); let mut wallet = Wallet::new(provider, credentials).await.unwrap(); let ethereum = wallet.ethereum(LOCALHOST_WEB3_ADDR).await.unwrap(); let deposit_tx_hash = ethereum .deposit("ETH", one_ether() / 2, wallet.address()) .await .unwrap(); wait_for_eth_tx(&ethereum, deposit_tx_hash).await; // Update stored wallet ID after we initialized a wallet via deposit. wait_for_deposit_and_update_account_id(&mut wallet).await; if !wallet.is_signing_key_set().await.unwrap() { let handle = wallet.start_change_pubkey().send().await.unwrap(); handle .commit_timeout(Duration::from_secs(60)) .wait_for_commit() .await .unwrap(); } // Perform transfer to self. let handle = wallet .start_transfer() .to(wallet.address()) .token("ETH") .unwrap() .amount(1_000_000u64) .send() .await .unwrap(); handle .verify_timeout(Duration::from_secs(180)) .wait_for_verify() .await .unwrap(); Ok(()) }
#[macro_use] extern crate log; extern crate pretty_env_logger; use glyph_bbox::dataset; use metal_lion; use std::net::SocketAddr; #[tokio::main] async fn main() { pretty_env_logger::init_custom_env("METAL_LION_LOG_LEVEL"); let rt = metal_lion::cli::entrypoint().get_matches(); match rt.subcommand_name() { Some(v) => { let args = rt.subcommand_matches(v).unwrap(); match v { "server" => { let bind_addr: SocketAddr = args .value_of("bind") .unwrap() .parse() .expect("Failed to parse bind address"); let host: String; match args.value_of("host") { Some(v) => host = v.to_owned(), None => { host = format!("http://{}", args.value_of("bind").unwrap().to_owned()) } } let factory = metal_lion::badges::Factory::new(metal_lion::badges::FactoryOptions { host, render_dataset: dataset::DataSet::from_file(dataset::ReadOptions { filename: args.value_of("bbox_dataset_path").unwrap().into(), format: dataset::Format::JSON, }), }); metal_lion::web::listen(bind_addr, factory).await; } _ => error!("unrecognized subcommand"), } } None => error!("no subcommand specified"), } }
use ggez::graphics as ggraphics; use super::numeric; use crate::graphics::drawable::*; pub struct ShadowShape { shadow: ggraphics::Mesh, draw_param: ggraphics::DrawParam, drwob_essential: DrawableObjectEssential, } impl ShadowShape { pub fn new( ctx: &mut ggez::Context, width: f32, bounds: numeric::Rect, color: ggraphics::Color, depth: i8, ) -> ShadowShape { let mesh = ggraphics::MeshBuilder::new() .rectangle(ggraphics::DrawMode::stroke(width), bounds, color) .build(ctx) .unwrap(); let mut dparam = ggraphics::DrawParam::default(); dparam.dest.x = 0.0; dparam.dest.y = 0.0; dparam.color = ggraphics::WHITE; dparam.rotation = 0.0; ShadowShape { shadow: mesh, draw_param: dparam, drwob_essential: DrawableObjectEssential::new(true, depth), } } } impl DrawableComponent for ShadowShape { fn draw(&mut self, ctx: &mut ggez::Context) -> ggez::GameResult<()> { if self.drwob_essential.visible { ggraphics::draw(ctx, &self.shadow, self.draw_param)?; } Ok(()) } fn hide(&mut self) { self.drwob_essential.visible = false; } fn appear(&mut self) { self.drwob_essential.visible = true; } fn is_visible(&self) -> bool { self.drwob_essential.visible } fn set_drawing_depth(&mut self, depth: i8) { self.drwob_essential.drawing_depth = depth; } fn get_drawing_depth(&self) -> i8 { self.drwob_essential.drawing_depth } }
use io::{BufRead, Write}; use std::io; fn find(element: i32, parents: &mut Vec<i32>) -> i32 { if element == parents[element as usize] { return element; } let p = find(parents[element as usize], parents); parents[element as usize] = p; p } fn union(element_a: i32, element_b: i32, parents: &mut Vec<i32>) { let parents_a = find(element_a, parents) as usize; let parents_b = find(element_b, parents) as usize; if parents_a == parents_b { return; } parents[parents_a] = parents_b as i32; } fn main() { let stdin = io::stdin(); let mut stdin = stdin.lock(); let mut input = String::new(); stdin.read_line(&mut input).unwrap(); let mut input = input.trim().split_whitespace(); let n: i32 = input.next().unwrap().parse().unwrap(); let m: i32 = input.next().unwrap().parse().unwrap(); let mut parents: Vec<i32> = (0..n + 2).collect(); let stdout = io::stdout(); let mut out_stream = io::BufWriter::new(stdout.lock()); for _ in 0..m { let mut input = String::new(); stdin.read_line(&mut input).unwrap(); let input: Vec<i32> = input .trim() .split_whitespace() .map(|x| x.parse().unwrap()) .collect(); if input[0] == 0 { union(input[1], input[2], &mut parents); } else { let a = find(input[1], &mut parents); let b = find(input[2], &mut parents); if a != b { writeln!(out_stream, "{}", "NO").unwrap(); } else { writeln!(out_stream, "{}", "YES").unwrap(); } } } }
//! Arbitrary signal debouncing logic. //! //! Call [`Debounce::signal`] multiple times within the debounce time window, //! and the [`Debounce::debounced`] will be resolved only once. use std::time::Duration; use tokio::time::{delay_until, Instant}; /// Provides an arbitrary signal debouncing. pub struct Debounce { sequence_start: Option<Instant>, time: Duration, } impl Debounce { /// Create a new [`Debounce`]. pub fn new(time: Duration) -> Self { Self { sequence_start: None, time, } } /// Trigger a signal to debounce. pub fn signal(&mut self) { if self.sequence_start.is_none() { self.sequence_start = Some(Instant::now() + self.time); } } /// Debounced signal. /// /// This function resolves after a debounce timeout since the first signal /// in sequence expires. /// If there hasn't been a signal, or the debounce timeout isn't yet /// exausted - the future will be in a pending state. pub async fn debounced(&mut self) { let sequence_start = match self.sequence_start { Some(val) => val, None => futures::future::pending().await, }; delay_until(sequence_start).await; self.sequence_start = None; } /// This function exposes the state of the debounce logic. /// If this returns `false`, you shouldn't `poll` on [`debounced`], as it's /// pending indefinitely. pub fn is_debouncing(&self) -> bool { self.sequence_start.is_some() } } #[cfg(test)] mod tests { use super::*; use futures::{pin_mut, poll}; const TEST_DELAY_FRACTION: Duration = Duration::from_secs(60 * 60); // one hour const TEST_DELAY: Duration = Duration::from_secs(24 * 60 * 60); // one day #[tokio::test] async fn one_signal() { tokio::time::pause(); let mut debounce = Debounce::new(TEST_DELAY); assert!(debounce.sequence_start.is_none()); // Issue a signal. debounce.signal(); assert!(debounce.sequence_start.is_some()); { // Request debounced signal. let fut = debounce.debounced(); pin_mut!(fut); // Shouldn't be available immediately. assert!(poll!(&mut fut).is_pending()); // Simulate that we waited for some time, but no long enouh for the // debounce to happen. tokio::time::advance(TEST_DELAY_FRACTION).await; // Still shouldn't be available. assert!(poll!(&mut fut).is_pending()); // Then wait long enough for debounce timeout to pass. tokio::time::advance(TEST_DELAY * 2).await; // Should finally be available. assert!(poll!(&mut fut).is_ready()); } assert!(debounce.sequence_start.is_none()); tokio::time::resume(); } #[tokio::test] async fn late_request() { tokio::time::pause(); let mut debounce = Debounce::new(TEST_DELAY); assert!(debounce.sequence_start.is_none()); // Issue a signal. debounce.signal(); assert!(debounce.sequence_start.is_some()); // Simulate that we waited long enough. tokio::time::advance(TEST_DELAY * 2).await; assert!(debounce.sequence_start.is_some()); { // Request a debounced signal. let fut = debounce.debounced(); pin_mut!(fut); // Should be available immediately. assert!(poll!(&mut fut).is_ready()); } assert!(debounce.sequence_start.is_none()); tokio::time::resume(); } #[tokio::test] async fn multiple_signals() { tokio::time::pause(); let mut debounce = Debounce::new(TEST_DELAY); assert!(debounce.sequence_start.is_none()); debounce.signal(); let first_signal_timestamp = debounce.sequence_start; assert!(first_signal_timestamp.is_some()); debounce.signal(); assert_eq!(debounce.sequence_start, first_signal_timestamp); tokio::time::advance(TEST_DELAY_FRACTION).await; debounce.signal(); assert_eq!(debounce.sequence_start, first_signal_timestamp); { let fut = debounce.debounced(); pin_mut!(fut); assert!(poll!(&mut fut).is_pending()); tokio::time::advance(TEST_DELAY_FRACTION).await; assert!(poll!(&mut fut).is_pending()); tokio::time::advance(TEST_DELAY * 2).await; assert!(poll!(&mut fut).is_ready()); } assert!(debounce.sequence_start.is_none()); tokio::time::resume(); } #[tokio::test] async fn sequence() { tokio::time::pause(); let mut debounce = Debounce::new(TEST_DELAY); assert!(debounce.sequence_start.is_none()); debounce.signal(); let first_signal_timestamp = debounce.sequence_start; assert!(first_signal_timestamp.is_some()); debounce.signal(); assert_eq!(debounce.sequence_start, first_signal_timestamp); tokio::time::advance(TEST_DELAY_FRACTION).await; debounce.signal(); assert_eq!(debounce.sequence_start, first_signal_timestamp); { let fut = debounce.debounced(); pin_mut!(fut); assert!(poll!(&mut fut).is_pending()); tokio::time::advance(TEST_DELAY * 2).await; assert!(poll!(&mut fut).is_ready()); } assert!(debounce.sequence_start.is_none()); debounce.signal(); let second_signal_timestamp = debounce.sequence_start; assert!(second_signal_timestamp.is_some()); assert_ne!(second_signal_timestamp, first_signal_timestamp); { let fut = debounce.debounced(); pin_mut!(fut); assert!(poll!(&mut fut).is_pending()); tokio::time::advance(TEST_DELAY * 2).await; assert!(poll!(&mut fut).is_ready()); } assert!(debounce.sequence_start.is_none()); tokio::time::resume(); } #[tokio::test] async fn is_debouncing() { tokio::time::pause(); let mut debounce = Debounce::new(TEST_DELAY); assert_eq!(debounce.is_debouncing(), false); debounce.signal(); assert_eq!(debounce.is_debouncing(), true); tokio::time::advance(TEST_DELAY * 2).await; assert_eq!(debounce.is_debouncing(), true); debounce.debounced().await; assert_eq!(debounce.is_debouncing(), false); tokio::time::resume(); } }
use naia_shared::{Actor, ActorType, LocalActorKey, StateMask}; use std::{cell::RefCell, rc::Rc}; use super::actor_key::actor_key::ActorKey; #[derive(Debug)] pub enum ServerActorMessage<T: ActorType> { CreateActor(ActorKey, LocalActorKey, Rc<RefCell<dyn Actor<T>>>), UpdateActor( ActorKey, LocalActorKey, Rc<RefCell<StateMask>>, Rc<RefCell<dyn Actor<T>>>, ), DeleteActor(ActorKey, LocalActorKey), AssignPawn(ActorKey, LocalActorKey), UnassignPawn(ActorKey, LocalActorKey), UpdatePawn( ActorKey, LocalActorKey, Rc<RefCell<StateMask>>, Rc<RefCell<dyn Actor<T>>>, ), } impl<T: ActorType> ServerActorMessage<T> { pub fn write_message_type(&self) -> u8 { match self { ServerActorMessage::CreateActor(_, _, _) => 0, ServerActorMessage::DeleteActor(_, _) => 1, ServerActorMessage::UpdateActor(_, _, _, _) => 2, ServerActorMessage::AssignPawn(_, _) => 3, ServerActorMessage::UnassignPawn(_, _) => 4, ServerActorMessage::UpdatePawn(_, _, _, _) => 5, } } } impl<T: ActorType> Clone for ServerActorMessage<T> { fn clone(&self) -> Self { match self { ServerActorMessage::CreateActor(gk, lk, e) => { ServerActorMessage::CreateActor(gk.clone(), lk.clone(), e.clone()) } ServerActorMessage::DeleteActor(gk, lk) => { ServerActorMessage::DeleteActor(gk.clone(), lk.clone()) } ServerActorMessage::UpdateActor(gk, lk, sm, e) => { ServerActorMessage::UpdateActor(gk.clone(), lk.clone(), sm.clone(), e.clone()) } ServerActorMessage::AssignPawn(gk, lk) => { ServerActorMessage::AssignPawn(gk.clone(), lk.clone()) } ServerActorMessage::UnassignPawn(gk, lk) => { ServerActorMessage::UnassignPawn(gk.clone(), lk.clone()) } ServerActorMessage::UpdatePawn(gk, lk, sm, e) => { ServerActorMessage::UpdatePawn(gk.clone(), lk.clone(), sm.clone(), e.clone()) } } } }
mod app_config; mod handler; mod common; mod services; use actix_web::{App, HttpServer, web}; use dotenv::dotenv; use tokio_postgres::NoTls; use crate::handler::product; use crate::app_config::Configuration; #[actix_web::main] async fn main() -> std::io::Result<()> { dotenv().ok().expect("Failed to read .env file"); let config = Configuration::from_env().unwrap(); let pool = config.pg.create_pool(NoTls).unwrap(); println!("Starting server at {}:{}", config.server.host, config.server.port); HttpServer::new(move || { App::new() .data(pool.clone()) .route("/", web::get().to(product::hello)) .route("/echo", web::get().to(product::echo)) .route("/getall", web::get().to(product::get_all)) .route("/add", web::post().to(product::add)) .route("/update", web::post().to(product::update)) .route("/product/{product_id}/delete", web::delete().to(product::delete)) //.service(web::resource("/add-product").route(web::post().to(home::add_product))) }) .bind(format!("{}:{}", config.server.host, config.server.port))? .run() .await }
use crate::types::{Vector3f}; #[derive(Copy, Clone)] pub struct Viewport { width: i32, height: i32, } impl Viewport { /// maps pixel x from (0, image_height) to (0.5, -0.5) pub fn to_image_v(&self, image_y: f32) -> f32 { (image_y as f32 / self.image_height() as f32 - 0.5) * -1.0 } /// maps pixel x from (0, image_width) to (-0.5, 0.5) pub fn to_image_u(&self, image_x: f32) -> f32 { image_x as f32 / self.image_width() as f32 - 0.5 } pub fn image_width(&self) -> i32 { self.width } pub fn image_height(&self) -> i32 { self.height } pub fn aspect_ratio(&self) -> f32 { self.width as f32 / self.height as f32 } pub fn viewport_height(&self) -> f32 { 1.0 } pub fn viewport_width(&self) -> f32 { self.aspect_ratio() * self.viewport_height() } pub fn horizontal(&self) -> Vector3f { Vector3f::new(self.viewport_width(), 0f32, 0f32) } pub fn vertical(&self) -> Vector3f { Vector3f::new(0f32, self.viewport_height(), 0f32) } pub fn new_by_width(aspect_ratio: f32, width: i32) -> Viewport { let image_width = width; let image_height = (image_width as f32 / aspect_ratio) as i32; Viewport { width: image_width, height: image_height, } } }
mod pong; mod systems; extern crate amethyst; use crate::pong::Pong; use amethyst::{ core::TransformBundle, prelude::*, input::{ InputBundle, StringBindings }, renderer::{ plugins::{RenderFlat2D, RenderToWindow}, types::DefaultBackend, RenderingBundle, }, utils::application_root_dir, }; fn main() -> amethyst::Result<()> { amethyst::start_logger(Default::default()); let config_dir = "./config/display.ron"; let binding_dir = "./config/bindings.ron"; let assets_dir = "./assets"; let input_bundle = InputBundle::<StringBindings>::new() .with_bindings_from_file(binding_dir)?; let game_data = GameDataBuilder::default() .with_bundle(TransformBundle::new())? .with_bundle(input_bundle)? .with_bundle( RenderingBundle::<DefaultBackend>::new() // The RenderToWindow plugin provides all the scaffolding for opening a window and drawing on it .with_plugin( RenderToWindow::from_config_path(config_dir)? .with_clear([0.0, 0.0, 0.0, 1.0]), ) // RenderFlat2D plugin is used to render entities with a `SpriteRender` component. .with_plugin(RenderFlat2D::default()), )? .with(systems::PaddleSystem, "paddle_system", &["input_system"]) .with(systems::MoveBallsSystem, "ball_system", &[]) .with(systems::BounceSystem, "collision_system", &["paddle_system", "ball_system"]) .with() let mut world = World::new(); let mut game = Application::new(assets_dir, pong::Pong, game_data)?; game.run(); Ok(()) }
pub trait VecPushFastExt<T> { fn push_fast(&mut self, value: T); fn extend_from_slice_fast(&mut self, v: &[T]) where T: Clone; } impl<T> VecPushFastExt<T> for Vec<T> { #[inline(always)] fn push_fast(&mut self, v: T) { let n = self.len(); if n >= self.capacity() { unreachable!(); } unsafe { self.as_mut_ptr().add(n).write(v); self.set_len(n + 1); } } #[inline(always)] fn extend_from_slice_fast(&mut self, v: &[T]) where T: Clone, { let n = self.len(); if self.capacity() < v.len() || self.capacity() - v.len() < n { unreachable!(); } unsafe { let mut out = self.as_mut_ptr().add(n); for v in v { out.write(v.clone()); out = out.add(1); } self.set_len(n + v.len()); } } }
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::HashSet; use common_base::base::tokio; use common_exception::Result; use common_expression::types::Float64Type; use common_expression::types::Int32Type; use common_expression::types::NumberDataType; use common_expression::types::UInt64Type; use common_expression::Column; use common_expression::ColumnId; use common_expression::DataBlock; use common_expression::FromData; use common_expression::Scalar; use common_expression::TableDataType; use common_expression::TableField; use common_expression::TableSchemaRefExt; use common_sql::plans::AddTableColumnPlan; use common_sql::plans::DropTableColumnPlan; use common_sql::Planner; use common_storages_fuse::io::MetaReaders; use common_storages_fuse::FuseTable; use common_storages_fuse::TableContext; use databend_query::interpreters::AddTableColumnInterpreter; use databend_query::interpreters::DropTableColumnInterpreter; use databend_query::interpreters::Interpreter; use databend_query::interpreters::InterpreterFactory; use futures_util::TryStreamExt; use ordered_float::OrderedFloat; use storages_common_cache::LoadParams; use storages_common_table_meta::meta::SegmentInfo; use storages_common_table_meta::meta::TableSnapshot; use storages_common_table_meta::meta::Versioned; use storages_common_table_meta::table::OPT_KEY_SNAPSHOT_LOCATION; use crate::storages::fuse::table_test_fixture::TestFixture; async fn check_segment_column_ids( fixture: &TestFixture, expected_column_ids: Option<Vec<ColumnId>>, expected_column_min_max: Option<Vec<(ColumnId, (Scalar, Scalar))>>, ) -> Result<()> { let catalog = fixture.ctx().get_catalog("default")?; // get the latest tbl let table = catalog .get_table( fixture.default_tenant().as_str(), fixture.default_db_name().as_str(), fixture.default_table_name().as_str(), ) .await?; let snapshot_loc = table .get_table_info() .options() .get(OPT_KEY_SNAPSHOT_LOCATION) .unwrap(); let fuse_table = FuseTable::try_from_table(table.as_ref())?; let snapshot_reader = MetaReaders::table_snapshot_reader(fuse_table.get_operator()); let params = LoadParams { location: snapshot_loc.clone(), len_hint: None, ver: TableSnapshot::VERSION, put_cache: false, }; let snapshot = snapshot_reader.read(&params).await?; if let Some(expected_column_min_max) = expected_column_min_max { for (column_id, (min, max)) in expected_column_min_max { if let Some(stat) = snapshot.summary.col_stats.get(&column_id) { assert_eq!(min, stat.min); assert_eq!(max, stat.max); } } } if let Some(expected_column_ids) = expected_column_ids { let expected_column_ids = HashSet::<ColumnId>::from_iter(expected_column_ids.clone().iter().cloned()); for (seg_loc, _) in &snapshot.segments { let segment_reader = MetaReaders::segment_info_reader( fuse_table.get_operator(), TestFixture::default_table_schema(), ); let params = LoadParams { location: seg_loc.clone(), len_hint: None, ver: SegmentInfo::VERSION, put_cache: false, }; let segment_info = segment_reader.read(&params).await?; segment_info.blocks.iter().for_each(|block_meta| { assert_eq!( HashSet::from_iter( block_meta .col_stats .keys() .cloned() .collect::<Vec<ColumnId>>() .iter() .cloned() ), expected_column_ids, ); }); } } Ok(()) } #[tokio::test(flavor = "multi_thread")] async fn test_fuse_table_optimize_alter_table() -> Result<()> { let fixture = TestFixture::new().await; let ctx = fixture.ctx(); let tbl_name = fixture.default_table_name(); let db_name = fixture.default_db_name(); let catalog_name = fixture.default_catalog_name(); fixture.create_normal_table().await?; // insert values let table = fixture.latest_default_table().await?; let num_blocks = 1; let stream = TestFixture::gen_sample_blocks_stream(num_blocks, 1); let blocks = stream.try_collect().await?; fixture .append_commit_blocks(table.clone(), blocks, false, true) .await?; // check column ids // the table contains two fields: id int32, t tuple(int32, int32) let expected_leaf_column_ids = vec![0, 1, 2]; check_segment_column_ids(&fixture, Some(expected_leaf_column_ids), None).await?; // drop a column let drop_table_column_plan = DropTableColumnPlan { catalog: fixture.default_catalog_name(), database: fixture.default_db_name(), table: fixture.default_table_name(), column: "t".to_string(), }; let interpreter = DropTableColumnInterpreter::try_create(ctx.clone(), drop_table_column_plan)?; interpreter.execute(ctx.clone()).await?; // add a column of uint64 with default value `(1,15.0)` let fields = vec![ TableField::new("b", TableDataType::Tuple { fields_name: vec!["b1".to_string(), "b2".to_string()], fields_type: vec![ TableDataType::Number(NumberDataType::UInt64), TableDataType::Number(NumberDataType::Float64), ], }) .with_default_expr(Some("(1,15.0)".to_string())), ]; let schema = TableSchemaRefExt::create(fields); let add_table_column_plan = AddTableColumnPlan { catalog: fixture.default_catalog_name(), database: fixture.default_db_name(), table: fixture.default_table_name(), schema, field_default_exprs: vec![], field_comments: vec![], }; let interpreter = AddTableColumnInterpreter::try_create(ctx.clone(), add_table_column_plan)?; interpreter.execute(ctx.clone()).await?; // insert values for new schema let block = { let column0 = Int32Type::from_data(vec![1, 2]); let column3 = UInt64Type::from_data(vec![3, 4]); let column4 = Float64Type::from_data(vec![13.0, 14.0]); let tuple_column = Column::Tuple(vec![column3, column4]); DataBlock::new_from_columns(vec![column0, tuple_column]) }; // get the latest tbl let table = fixture .ctx() .get_catalog(&catalog_name)? .get_table( fixture.default_tenant().as_str(), fixture.default_db_name().as_str(), fixture.default_table_name().as_str(), ) .await?; fixture .append_commit_blocks(table.clone(), vec![block], false, true) .await?; // verify statistics min and max value check_segment_column_ids( &fixture, None, Some(vec![ ( 3, ( Scalar::Number(common_expression::types::number::NumberScalar::UInt64(1)), Scalar::Number(common_expression::types::number::NumberScalar::UInt64(4)), ), ), ( 4, ( Scalar::Number(common_expression::types::number::NumberScalar::Float64( OrderedFloat(13.0), )), Scalar::Number(common_expression::types::number::NumberScalar::Float64( OrderedFloat(15.0), )), ), ), ]), ) .await?; // do compact let query = format!("optimize table {db_name}.{tbl_name} compact"); let mut planner = Planner::new(ctx.clone()); let (plan, _) = planner.plan_sql(&query).await?; let interpreter = InterpreterFactory::get(ctx.clone(), &plan).await?; ctx.get_settings().set_max_threads(1)?; let data_stream = interpreter.execute(ctx.clone()).await?; let _ = data_stream.try_collect::<Vec<_>>().await; // verify statistics and min\max values let expected_column_ids = vec![0, 3, 4]; check_segment_column_ids( &fixture, Some(expected_column_ids), Some(vec![ ( 3, ( Scalar::Number(common_expression::types::number::NumberScalar::UInt64(1)), Scalar::Number(common_expression::types::number::NumberScalar::UInt64(4)), ), ), ( 4, ( Scalar::Number(common_expression::types::number::NumberScalar::Float64( OrderedFloat(13.0), )), Scalar::Number(common_expression::types::number::NumberScalar::Float64( OrderedFloat(15.0), )), ), ), ]), ) .await?; Ok(()) }
#[doc = "Reader of register FPR1"] pub type R = crate::R<u32, super::FPR1>; #[doc = "Writer for register FPR1"] pub type W = crate::W<u32, super::FPR1>; #[doc = "Register FPR1 `reset()`'s with value 0"] impl crate::ResetValue for super::FPR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "configurable event inputs x falling edge pending bit.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FPIF0_A { #[doc = "0: No trigger request occurred"] NOTPENDING = 0, #[doc = "1: Selected trigger request occurred"] PENDING = 1, } impl From<FPIF0_A> for bool { #[inline(always)] fn from(variant: FPIF0_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `FPIF0`"] pub type FPIF0_R = crate::R<bool, FPIF0_A>; impl FPIF0_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FPIF0_A { match self.bits { false => FPIF0_A::NOTPENDING, true => FPIF0_A::PENDING, } } #[doc = "Checks if the value of the field is `NOTPENDING`"] #[inline(always)] pub fn is_not_pending(&self) -> bool { *self == FPIF0_A::NOTPENDING } #[doc = "Checks if the value of the field is `PENDING`"] #[inline(always)] pub fn is_pending(&self) -> bool { *self == FPIF0_A::PENDING } } #[doc = "configurable event inputs x falling edge pending bit.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FPIF0_AW { #[doc = "1: Clears pending bit"] CLEAR = 1, } impl From<FPIF0_AW> for bool { #[inline(always)] fn from(variant: FPIF0_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `FPIF0`"] pub struct FPIF0_W<'a> { w: &'a mut W, } impl<'a> FPIF0_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF0_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[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 = "configurable event inputs x falling edge pending bit."] pub type FPIF1_A = FPIF0_A; #[doc = "Reader of field `FPIF1`"] pub type FPIF1_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF1_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF1`"] pub struct FPIF1_W<'a> { w: &'a mut W, } impl<'a> FPIF1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF1_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[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 = "configurable event inputs x falling edge pending bit."] pub type FPIF2_A = FPIF0_A; #[doc = "Reader of field `FPIF2`"] pub type FPIF2_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF2_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF2`"] pub struct FPIF2_W<'a> { w: &'a mut W, } impl<'a> FPIF2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF2_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[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 = "configurable event inputs x falling edge pending bit."] pub type FPIF3_A = FPIF0_A; #[doc = "Reader of field `FPIF3`"] pub type FPIF3_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF3_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF3`"] pub struct FPIF3_W<'a> { w: &'a mut W, } impl<'a> FPIF3_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF3_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[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 = "configurable event inputs x falling edge pending bit."] pub type FPIF4_A = FPIF0_A; #[doc = "Reader of field `FPIF4`"] pub type FPIF4_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF4_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF4`"] pub struct FPIF4_W<'a> { w: &'a mut W, } impl<'a> FPIF4_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF4_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF5_A = FPIF0_A; #[doc = "Reader of field `FPIF5`"] pub type FPIF5_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF5_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF5`"] pub struct FPIF5_W<'a> { w: &'a mut W, } impl<'a> FPIF5_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF5_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF6_A = FPIF0_A; #[doc = "Reader of field `FPIF6`"] pub type FPIF6_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF6_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF6`"] pub struct FPIF6_W<'a> { w: &'a mut W, } impl<'a> FPIF6_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF6_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF7_A = FPIF0_A; #[doc = "Reader of field `FPIF7`"] pub type FPIF7_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF7_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF7`"] pub struct FPIF7_W<'a> { w: &'a mut W, } impl<'a> FPIF7_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF7_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF8_A = FPIF0_A; #[doc = "Reader of field `FPIF8`"] pub type FPIF8_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF8_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF8`"] pub struct FPIF8_W<'a> { w: &'a mut W, } impl<'a> FPIF8_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF8_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF9_A = FPIF0_A; #[doc = "Reader of field `FPIF9`"] pub type FPIF9_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF9_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF9`"] pub struct FPIF9_W<'a> { w: &'a mut W, } impl<'a> FPIF9_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF9_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF10_A = FPIF0_A; #[doc = "Reader of field `FPIF10`"] pub type FPIF10_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF10_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF10`"] pub struct FPIF10_W<'a> { w: &'a mut W, } impl<'a> FPIF10_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF10_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF11_A = FPIF0_A; #[doc = "Reader of field `FPIF11`"] pub type FPIF11_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF11_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF11`"] pub struct FPIF11_W<'a> { w: &'a mut W, } impl<'a> FPIF11_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF11_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF12_A = FPIF0_A; #[doc = "Reader of field `FPIF12`"] pub type FPIF12_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF12_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF12`"] pub struct FPIF12_W<'a> { w: &'a mut W, } impl<'a> FPIF12_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF12_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF13_A = FPIF0_A; #[doc = "Reader of field `FPIF13`"] pub type FPIF13_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF13_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF13`"] pub struct FPIF13_W<'a> { w: &'a mut W, } impl<'a> FPIF13_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF13_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF14_A = FPIF0_A; #[doc = "Reader of field `FPIF14`"] pub type FPIF14_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF14_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF14`"] pub struct FPIF14_W<'a> { w: &'a mut W, } impl<'a> FPIF14_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF14_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF15_A = FPIF0_A; #[doc = "Reader of field `FPIF15`"] pub type FPIF15_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF15_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF15`"] pub struct FPIF15_W<'a> { w: &'a mut W, } impl<'a> FPIF15_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF15_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF16_A = FPIF0_A; #[doc = "Reader of field `FPIF16`"] pub type FPIF16_R = crate::R<bool, FPIF0_A>; #[doc = "configurable event inputs x falling edge pending bit."] pub type FPIF16_AW = FPIF0_AW; #[doc = "Write proxy for field `FPIF16`"] pub struct FPIF16_W<'a> { w: &'a mut W, } impl<'a> FPIF16_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPIF16_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears pending bit"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(FPIF0_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } impl R { #[doc = "Bit 0 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif0(&self) -> FPIF0_R { FPIF0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif1(&self) -> FPIF1_R { FPIF1_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif2(&self) -> FPIF2_R { FPIF2_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif3(&self) -> FPIF3_R { FPIF3_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif4(&self) -> FPIF4_R { FPIF4_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif5(&self) -> FPIF5_R { FPIF5_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif6(&self) -> FPIF6_R { FPIF6_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif7(&self) -> FPIF7_R { FPIF7_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif8(&self) -> FPIF8_R { FPIF8_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif9(&self) -> FPIF9_R { FPIF9_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif10(&self) -> FPIF10_R { FPIF10_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif11(&self) -> FPIF11_R { FPIF11_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif12(&self) -> FPIF12_R { FPIF12_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif13(&self) -> FPIF13_R { FPIF13_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif14(&self) -> FPIF14_R { FPIF14_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif15(&self) -> FPIF15_R { FPIF15_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif16(&self) -> FPIF16_R { FPIF16_R::new(((self.bits >> 16) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif0(&mut self) -> FPIF0_W { FPIF0_W { w: self } } #[doc = "Bit 1 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif1(&mut self) -> FPIF1_W { FPIF1_W { w: self } } #[doc = "Bit 2 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif2(&mut self) -> FPIF2_W { FPIF2_W { w: self } } #[doc = "Bit 3 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif3(&mut self) -> FPIF3_W { FPIF3_W { w: self } } #[doc = "Bit 4 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif4(&mut self) -> FPIF4_W { FPIF4_W { w: self } } #[doc = "Bit 5 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif5(&mut self) -> FPIF5_W { FPIF5_W { w: self } } #[doc = "Bit 6 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif6(&mut self) -> FPIF6_W { FPIF6_W { w: self } } #[doc = "Bit 7 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif7(&mut self) -> FPIF7_W { FPIF7_W { w: self } } #[doc = "Bit 8 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif8(&mut self) -> FPIF8_W { FPIF8_W { w: self } } #[doc = "Bit 9 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif9(&mut self) -> FPIF9_W { FPIF9_W { w: self } } #[doc = "Bit 10 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif10(&mut self) -> FPIF10_W { FPIF10_W { w: self } } #[doc = "Bit 11 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif11(&mut self) -> FPIF11_W { FPIF11_W { w: self } } #[doc = "Bit 12 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif12(&mut self) -> FPIF12_W { FPIF12_W { w: self } } #[doc = "Bit 13 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif13(&mut self) -> FPIF13_W { FPIF13_W { w: self } } #[doc = "Bit 14 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif14(&mut self) -> FPIF14_W { FPIF14_W { w: self } } #[doc = "Bit 15 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif15(&mut self) -> FPIF15_W { FPIF15_W { w: self } } #[doc = "Bit 16 - configurable event inputs x falling edge pending bit."] #[inline(always)] pub fn fpif16(&mut self) -> FPIF16_W { FPIF16_W { w: self } } }
// Copyright 2020-2021, The Tremor Team // // 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 crate::prelude::*; use crate::tremor_fn; use crate::{registry::Registry, TRUE}; pub fn load(registry: &mut Registry) { registry.insert(tremor_fn! (test|assert(ctx, desc, expected, got) { if expected == got { Ok(TRUE) } else if ctx.panic_on_assert { Err(to_runtime_error(format!(r#" Assertion for {} failed: expected: {} got: {} "#, desc, expected.encode(), got.encode()))) } else { Ok(Value::from(vec![(*expected).clone(), (*got).clone()])) } })); }
use std::time::Duration; // Calculate performance statistics. // ============================================================================================ fn as_nanos(duration: Duration) -> u64 { duration.as_secs() * 1_000_000_000 + duration.subsec_nanos() as u64 } fn from_nanos(nanos: u64) -> Duration { let secs = nanos / 1_000_000_000; let subsec_nanos = nanos % 1_000_000_000; Duration::new(secs, subsec_nanos as u32) } #[derive(Debug, Clone, Copy)] pub struct Statistics { pub min: Duration, pub max: Duration, pub mean: Duration, pub std: Duration, pub long_frames: usize, pub long_frame_ratio: f64, } pub fn analyze(frame_times: &[Duration], target_frame_time: Duration) -> Statistics { let mut min = frame_times[0]; let mut max = frame_times[0]; let mut total = Duration::new(0, 0); let mut long_frames = 0; for time in frame_times.iter().cloned() { total += time; if time < min { min = time; } if time > max { max = time; } if time > target_frame_time { long_frames += 1; } } let mean = total / frame_times.len() as u32; let total_sqr_deviation = frame_times.iter().cloned().fold(0, |total, time| { let diff = if time < mean { mean - time } else { time - mean }; // Convert to nanos so that we can square and hope we don't overflow ¯\_(ツ)_/¯. let nanos = as_nanos(diff); let diff_sqr = nanos * nanos; total + diff_sqr }); let std_dev = from_nanos(f64::sqrt(total_sqr_deviation as f64 / frame_times.len() as f64) as u64); let long_frame_ratio = long_frames as f64 / frame_times.len() as f64; Statistics { min: min, max: max, mean: mean, std: std_dev, long_frames: long_frames, long_frame_ratio: long_frame_ratio, } }
// https://github.com/garrynewman/bootil/blob/beb4cec8ad29533965491b767b177dc549e62d23/src/3rdParty/globber.cpp // https://github.com/Facepunch/gmad/blob/master/include/AddonWhiteList.h macro_rules! nul_str { ( $str:literal ) => { concat!($str, "\0") }; } pub const DEFAULT_IGNORE: &'static [&'static str] = &[ nul_str!(".git/*"), nul_str!("*.psd"), nul_str!("*.pdn"), nul_str!("*.xcf"), nul_str!("*.svn"), nul_str!(".gitignore"), nul_str!(".vscode/*"), nul_str!(".github/*"), nul_str!(".editorconfig"), nul_str!("README.md"), nul_str!("README.txt"), nul_str!("readme.txt"), nul_str!("addon.json"), nul_str!("addon.txt"), nul_str!("addon.jpg"), ]; const ADDON_WHITELIST: &'static [&'static str] = &[ nul_str!("lua/*.lua"), nul_str!("scenes/*.vcd"), nul_str!("particles/*.pcf"), nul_str!("resource/fonts/*.ttf"), nul_str!("scripts/vehicles/*.txt"), nul_str!("resource/localization/*/*.properties"), nul_str!("maps/*.bsp"), nul_str!("maps/*.nav"), nul_str!("maps/*.ain"), nul_str!("maps/thumb/*.png"), nul_str!("sound/*.wav"), nul_str!("sound/*.mp3"), nul_str!("sound/*.ogg"), nul_str!("materials/*.vmt"), nul_str!("materials/*.vtf"), nul_str!("materials/*.png"), nul_str!("materials/*.jpg"), nul_str!("materials/*.jpeg"), nul_str!("models/*.mdl"), nul_str!("models/*.vtx"), nul_str!("models/*.phy"), nul_str!("models/*.ani"), nul_str!("models/*.vvd"), nul_str!("gamemodes/*/*.txt"), nul_str!("gamemodes/*/*.fgd"), nul_str!("gamemodes/*/logo.png"), nul_str!("gamemodes/*/icon24.png"), nul_str!("gamemodes/*/gamemode/*.lua"), nul_str!("gamemodes/*/entities/effects/*.lua"), nul_str!("gamemodes/*/entities/weapons/*.lua"), nul_str!("gamemodes/*/entities/entities/*.lua"), nul_str!("gamemodes/*/backgrounds/*.png"), nul_str!("gamemodes/*/backgrounds/*.jpg"), nul_str!("gamemodes/*/backgrounds/*.jpeg"), nul_str!("gamemodes/*/content/models/*.mdl"), nul_str!("gamemodes/*/content/models/*.vtx"), nul_str!("gamemodes/*/content/models/*.phy"), nul_str!("gamemodes/*/content/models/*.ani"), nul_str!("gamemodes/*/content/models/*.vvd"), nul_str!("gamemodes/*/content/materials/*.vmt"), nul_str!("gamemodes/*/content/materials/*.vtf"), nul_str!("gamemodes/*/content/materials/*.png"), nul_str!("gamemodes/*/content/materials/*.jpg"), nul_str!("gamemodes/*/content/materials/*.jpeg"), nul_str!("gamemodes/*/content/scenes/*.vcd"), nul_str!("gamemodes/*/content/particles/*.pcf"), nul_str!("gamemodes/*/content/resource/fonts/*.ttf"), nul_str!("gamemodes/*/content/scripts/vehicles/*.txt"), nul_str!("gamemodes/*/content/resource/localization/*/*.properties"), nul_str!("gamemodes/*/content/maps/*.bsp"), nul_str!("gamemodes/*/content/maps/*.nav"), nul_str!("gamemodes/*/content/maps/*.ain"), nul_str!("gamemodes/*/content/maps/thumb/*.png"), nul_str!("gamemodes/*/content/sound/*.wav"), nul_str!("gamemodes/*/content/sound/*.mp3"), nul_str!("gamemodes/*/content/sound/*.ogg"), ]; const WILD_BYTE: u8 = '*' as u8; const QUESTION_BYTE: u8 = '?' as u8; pub unsafe fn globber(_wild: &str, _str: &str) -> bool { let mut cp: *const u8 = 0 as u8 as *const u8; let mut mp: *const u8 = 0 as u8 as *const u8; let mut wild = _wild.as_ptr(); let mut str = _str.as_ptr(); while *str != 0 && *wild != WILD_BYTE { if *wild != *str && *wild != QUESTION_BYTE { return false; } wild = wild.add(1); str = str.add(1); } while *str != 0 { if *wild == WILD_BYTE { wild = wild.add(1); if *wild == 0 { return true; } mp = wild; cp = str.add(1); } else if *wild == *str || *wild == QUESTION_BYTE { wild = wild.add(1); str = str.add(1); } else { wild = mp; cp = cp.add(1); str = cp; } } while *wild == WILD_BYTE { wild = wild.add(1); } *wild == 0 } pub fn check<S: Into<String> + Clone>(str: &S) -> bool { let mut string = str.clone().into(); string.push('\0'); let str = string.as_str(); for glob in ADDON_WHITELIST { if unsafe { globber(glob, str) } { return true; } } false } pub fn filter_default_ignored<S: Into<String> + Clone>(str: &S) -> bool { let mut string = str.clone().into(); string.push('\0'); let str = string.as_str(); for glob in DEFAULT_IGNORE { if unsafe { globber(glob, str) } { return false; } } true } pub fn is_ignored<S: Into<String> + Clone>(str: &S, ignore: &[String]) -> bool { if ignore.is_empty() { return false; } let mut string = str.clone().into(); string.push('\0'); let str = string.as_str(); for glob in ignore { debug_assert!(glob.ends_with('\0')); if unsafe { globber(glob, str) } { return true; } } false } #[test] pub fn test_whitelist() { let good: &'static [&'static str] = &[ "lua/test.lua", "lua/lol/test.lua", "lua/lua/testing.lua", "gamemodes/test/something.txt", "gamemodes/test/content/sound/lol.wav", "materials/lol.jpeg", ]; let bad: &'static [&'static str] = &[ "test.lua", "lua/test.exe", "lua/lol/test.exe", "gamemodes/test", "gamemodes/test/something", "gamemodes/test/something/something.exe", "gamemodes/test/content/sound/lol.vvv", "materials/lol.vvv", ]; for good in good { assert!(check(&*good)); } for good in ADDON_WHITELIST { assert!(check(&good.replace('*', "test"))); } for bad in bad { assert!(!check(&*bad)); } } #[test] pub fn test_ignore() { let ignored: &'static [&'static str] = &[ ".git/index", ".git/info/exclude", ".git/logs/head", ".git/logs/refs/heads/4.0.0", ".git/logs/refs/heads/master", ".git/logs/refs/remotes/origin/4.0.0", ".git/logs/refs/remotes/origin/cracker", ".git/logs/refs/remotes/origin/cracker-no-minigames", ".git/logs/refs/remotes/origin/master", ".git/objects/00/007c75922055623f4177467fd50a7d573c2c86", "blah.psd", "some/location/blah.psd", "some/blah/blah.pdn", "hi.xcf", "addon.jpg", "addon.json" ]; for ignored in ignored { assert!(!filter_default_ignored(&*ignored)); } let default_ignore: Vec<String> = DEFAULT_IGNORE.iter().cloned().map(|x| x.to_string()).collect(); for ignored in ignored { assert!(is_ignored(&*ignored, &default_ignore)); } assert!(is_ignored(&"lol.txt".to_string(), &["lol.txt\0".to_string()])); assert!(!is_ignored(&"lol.txt".to_string(), &[])); }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use failure::{bail, format_err}; use fidl_fuchsia_wlan_mlme::BssDescription; use fidl_fuchsia_wlan_sme as fidl_sme; use wlan_common::bss::BssDescriptionExt; use wlan_common::ie::rsn::{akm, cipher}; use wlan_common::ie::wpa::WpaIe; use wlan_common::organization::Oui; use wlan_rsn::{self, nonce::NonceReader, NegotiatedProtection, ProtectionInfo}; use super::rsn::{compute_psk, Rsna}; use crate::{client::state::Protection, DeviceInfo}; /// According to the WiFi Alliance WPA standard (2004), only TKIP support is required. We allow /// CCMP if the AP requests it. /// Only supported AKM is PSK pub fn is_legacy_wpa_compatible(a_wpa: &WpaIe) -> bool { let multicast_supported = a_wpa.multicast_cipher.has_known_usage() && (a_wpa.multicast_cipher.suite_type == cipher::TKIP || a_wpa.multicast_cipher.suite_type == cipher::CCMP_128); let unicast_supported = a_wpa.unicast_cipher_list.iter().any(|c| { c.has_known_usage() && (c.suite_type == cipher::TKIP || c.suite_type == cipher::CCMP_128) }); let akm_supported = a_wpa.akm_list.iter().any(|a| a.has_known_algorithm() && a.suite_type == akm::PSK); multicast_supported && unicast_supported && akm_supported } /// Builds a supplicant for establishing a WPA1 association. WPA Assocation is not an official term, /// but is used here to refer to the modified RSNA used by WPA1. pub fn get_legacy_wpa_association( device_info: &DeviceInfo, credential: &fidl_sme::Credential, bss: &BssDescription, ) -> Result<Protection, failure::Error> { let a_wpa = bss.get_wpa_ie()?; if !is_legacy_wpa_compatible(&a_wpa) { bail!("incompatible legacy WPA {:?}", a_wpa); } let s_wpa = construct_s_wpa(&a_wpa); let negotiated_protection = NegotiatedProtection::from_legacy_wpa(&s_wpa)?; let psk = compute_psk(credential, &bss.ssid[..])?; let supplicant = wlan_rsn::Supplicant::new_wpa_personal( // Note: There should be one Reader per device, not per SME. // Follow-up with improving on this. NonceReader::new(&device_info.addr[..])?, psk, device_info.addr, ProtectionInfo::LegacyWpa(s_wpa), bss.bssid, ProtectionInfo::LegacyWpa(a_wpa), ) .map_err(|e| format_err!("failed to create ESS-SA: {:?}", e))?; Ok(Protection::LegacyWpa(Rsna { negotiated_protection, supplicant: Box::new(supplicant) })) } /// Construct a supplicant WPA1 IE with: /// The same multicast and unicast ciphers as the AP WPA1 IE /// PSK as the AKM fn construct_s_wpa(a_wpa: &WpaIe) -> WpaIe { // Use CCMP if supported, otherwise default to TKIP. let unicast_cipher = if a_wpa .unicast_cipher_list .iter() .any(|c| c.has_known_usage() && c.suite_type == cipher::CCMP_128) { cipher::Cipher { oui: Oui::MSFT, suite_type: cipher::CCMP_128 } } else { cipher::Cipher { oui: Oui::MSFT, suite_type: cipher::TKIP } }; WpaIe { multicast_cipher: a_wpa.multicast_cipher.clone(), unicast_cipher_list: vec![unicast_cipher], akm_list: vec![akm::Akm { oui: Oui::MSFT, suite_type: akm::PSK }], } } #[cfg(test)] mod tests { use super::*; use crate::{ client::test_utils::{ fake_protected_bss_description, fake_unprotected_bss_description, fake_wpa1_bss_description, }, test_utils::{fake_device_info, make_wpa1_ie}, }; const CLIENT_ADDR: [u8; 6] = [0x7A, 0xE7, 0x76, 0xD9, 0xF2, 0x67]; #[test] fn test_incompatible_multicast_cipher() { let mut a_wpa = make_wpa1_ie(); a_wpa.multicast_cipher = cipher::Cipher { oui: Oui::MSFT, suite_type: cipher::WEP_40 }; assert_eq!(is_legacy_wpa_compatible(&a_wpa), false); } #[test] fn test_incompatible_unicast_cipher() { let mut a_wpa = make_wpa1_ie(); a_wpa.unicast_cipher_list = vec![cipher::Cipher { oui: Oui::DOT11, suite_type: cipher::WEP_40 }]; assert_eq!(is_legacy_wpa_compatible(&a_wpa), false); } #[test] fn test_incompatible_akm() { let mut a_wpa = make_wpa1_ie(); a_wpa.akm_list = vec![akm::Akm { oui: Oui::DOT11, suite_type: akm::EAP }]; assert_eq!(is_legacy_wpa_compatible(&a_wpa), false); } #[test] fn get_supplicant_ie_tkip() { let mut a_wpa = make_wpa1_ie(); a_wpa.unicast_cipher_list = vec![cipher::Cipher { oui: Oui::MSFT, suite_type: cipher::TKIP }]; let s_wpa = construct_s_wpa(&a_wpa); assert_eq!( s_wpa.unicast_cipher_list, vec![cipher::Cipher { oui: Oui::MSFT, suite_type: cipher::TKIP }] ); } #[test] fn get_supplicant_ie_ccmp() { let mut a_wpa = make_wpa1_ie(); a_wpa.unicast_cipher_list = vec![ cipher::Cipher { oui: Oui::MSFT, suite_type: cipher::TKIP }, cipher::Cipher { oui: Oui::MSFT, suite_type: cipher::CCMP_128 }, ]; let s_wpa = construct_s_wpa(&a_wpa); assert_eq!( s_wpa.unicast_cipher_list, vec![cipher::Cipher { oui: Oui::MSFT, suite_type: cipher::CCMP_128 }] ); } #[test] fn test_no_unicast_cipher() { let mut a_wpa = make_wpa1_ie(); a_wpa.unicast_cipher_list = vec![]; assert_eq!(is_legacy_wpa_compatible(&a_wpa), false); } #[test] fn test_no_akm() { let mut a_wpa = make_wpa1_ie(); a_wpa.akm_list = vec![]; assert_eq!(is_legacy_wpa_compatible(&a_wpa), false); } #[test] fn test_get_wpa_password_for_unprotected_network() { let bss = fake_unprotected_bss_description(b"foo_bss".to_vec()); let credential = fidl_sme::Credential::Password("somepass".as_bytes().to_vec()); get_legacy_wpa_association(&fake_device_info(CLIENT_ADDR), &credential, &bss) .expect_err("expect error when password is supplied for unprotected network"); } #[test] fn test_get_wpa_no_password_for_protected_network() { let bss = fake_wpa1_bss_description(b"foo_bss".to_vec()); let credential = fidl_sme::Credential::None(fidl_sme::Empty); get_legacy_wpa_association(&fake_device_info(CLIENT_ADDR), &credential, &bss) .expect_err("expect error when no password is supplied for protected network"); } #[test] fn test_get_wpa_for_rsna_protected_network() { let bss = fake_protected_bss_description(b"foo_bss".to_vec()); let credential = fidl_sme::Credential::None(fidl_sme::Empty); get_legacy_wpa_association(&fake_device_info(CLIENT_ADDR), &credential, &bss) .expect_err("expect error when treating RSNA as WPA association"); } #[test] fn test_get_wpa_psk() { let bss = fake_wpa1_bss_description(b"foo_bss".to_vec()); let credential = fidl_sme::Credential::Psk(vec![0xAA; 32]); get_legacy_wpa_association(&fake_device_info(CLIENT_ADDR), &credential, &bss) .expect("expected successful RSNA with valid PSK"); } #[test] fn test_get_wpa_invalid_psk() { let bss = fake_wpa1_bss_description(b"foo_bss".to_vec()); // PSK too short let credential = fidl_sme::Credential::Psk(vec![0xAA; 31]); get_legacy_wpa_association(&fake_device_info(CLIENT_ADDR), &credential, &bss) .expect_err("expected RSNA failure with invalid PSK"); } }
use crate::v0_2::CloudEventV0_2; use crate::v1_0::CloudEventV1_0; use serde_derive::{Deserialize, Serialize}; /// Generic CloudEvent wrapping all spec versions #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(untagged)] pub enum CloudEvent { V1_0(CloudEventV1_0), V0_2(CloudEventV0_2), }
use super::util::*; use crate::{V, ValueBaseOrdered, ValueBase}; fun!(add(x, y) { let x = as_float(x)?; let y = as_float(y)?; Ok(V::float(x + y)) }); fun!(sub(x, y) { let x = as_float(x)?; let y = as_float(y)?; Ok(V::float(x - y)) }); fun!(mul(x, y) { let x = as_float(x)?; let y = as_float(y)?; Ok(V::float(x * y)) }); fun!(div(x, y) { let x = as_float(x)?; let y = as_float(y)?; Ok(V::float(x / y)) }); fun!(mul_add(x, y, z) { let x = as_float(x)?; let y = as_float(y)?; let z = as_float(z)?; Ok(V::float(x.mul_add(y, z))) }); fun!(neg(x) { let x = as_float(x)?; Ok(V::float(-x)) }); fun!(floor(x) { let x = as_float(x)?; Ok(V::float(x.floor())) }); fun!(ceil(x) { let x = as_float(x)?; Ok(V::float(x.ceil())) }); fun!(round(x) { let x = as_float(x)?; Ok(V::float(x.round())) }); fun!(trunc(x) { let x = as_float(x)?; Ok(V::float(x.trunc())) }); fun!(fract(x) { let x = as_float(x)?; Ok(V::float(x.fract())) }); fun!(abs(x) { let x = as_float(x)?; Ok(V::float(x.abs())) }); fun!(signum(x) { let x = as_float(x)?; Ok(V::float(x.signum())) }); fun!(pow(x, y) { let x = as_float(x)?; let y = as_float(y)?; Ok(V::float(x.powf(y))) }); fun!(sqrt(x) { let x = as_float(x)?; Ok(V::float(x.sqrt())) }); fun!(exp(x) { let x = as_float(x)?; Ok(V::float(x.exp())) }); fun!(exp2(x) { let x = as_float(x)?; Ok(V::float(x.exp2())) }); fun!(ln(x) { let x = as_float(x)?; Ok(V::float(x.ln())) }); fun!(log2(x) { let x = as_float(x)?; Ok(V::float(x.log2())) }); fun!(log10(x) { let x = as_float(x)?; Ok(V::float(x.log10())) }); fun!(hypot(x, y) { let x = as_float(x)?; let y = as_float(y)?; Ok(V::float(x.hypot(y))) }); fun!(sin(x) { let x = as_float(x)?; Ok(V::float(x.sin())) }); fun!(cos(x) { let x = as_float(x)?; Ok(V::float(x.cos())) }); fun!(tan(x) { let x = as_float(x)?; Ok(V::float(x.tan())) }); fun!(asin(x) { let x = as_float(x)?; Ok(V::float(x.asin())) }); fun!(acos(x) { let x = as_float(x)?; Ok(V::float(x.acos())) }); fun!(atan(x) { let x = as_float(x)?; Ok(V::float(x.atan())) }); fun!(atan2(x, y) { let x = as_float(x)?; let y = as_float(y)?; Ok(V::float(x.atan2(y))) }); fun!(exp_m1(x) { let x = as_float(x)?; Ok(V::float(x.exp_m1())) }); fun!(ln_1p(x) { let x = as_float(x)?; Ok(V::float(x.ln_1p())) }); fun!(sinh(x) { let x = as_float(x)?; Ok(V::float(x.sinh())) }); fun!(cosh(x) { let x = as_float(x)?; Ok(V::float(x.cosh())) }); fun!(tanh(x) { let x = as_float(x)?; Ok(V::float(x.tanh())) }); fun!(asinh(x) { let x = as_float(x)?; Ok(V::float(x.asinh())) }); fun!(acosh(x) { let x = as_float(x)?; Ok(V::float(x.acosh())) }); fun!(atanh(x) { let x = as_float(x)?; Ok(V::float(x.atanh())) }); fun!(is_normal(x) { let x = as_float(x)?; Ok(V::boo(x.is_normal())) }); fun!(to_degrees(x) { let x = as_float(x)?; Ok(V::float(x.to_degrees())) }); fun!(to_radians(x) { let x = as_float(x)?; Ok(V::float(x.to_radians())) }); fun!(to_int(xf) { let x = as_float(xf)?; if x >= (std::i64::MAX as f64) || x <= (std::i64::MIN as f64) || x.is_nan() { Ok(V::err(xf.clone())) } else { return Ok(V::int(x as i64)); } }); fun!(from_int(n) { let n = as_int(n)?; Ok(V::float(n as f64)) }); fun!(to_bits(x) { let x = as_float(x)?; if x.is_nan() { Ok(V::int(-1)) } else { Ok(V::int(x.to_bits() as i64)) } }); fun!(from_bits(n) { let n = as_int(n)?; Ok(V::float(f64::from_bits(n as u64))) });
// Creating mock runtime here use crate::{Module, Trait}; use sp_core::H256; use frame_support::{impl_outer_origin, parameter_types, weights::Weight, impl_outer_event}; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, testing::Header, Perbill, }; use frame_system as system; use sp_io::TestExternalities; impl_outer_origin! { pub enum Origin for Test {} } // For testing the pallet, we construct most of a mock runtime. This means // first constructing a configuration type (`Test`) which `impl`s each of the // configuration traits of pallets we want to use. #[derive(Clone, Eq, PartialEq)] pub struct Test; parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); } impl system::Trait for Test { //noinspection RsUnresolvedReference type Origin = Origin; type Call = (); type Index = u64; type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = TestEvent; type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; type DbWeight = (); type BlockExecutionWeight = (); type ExtrinsicBaseWeight = (); type MaximumExtrinsicWeight = MaximumBlockWeight; type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); type ModuleToIndex = (); type AccountData = balances::AccountData<u64>; type OnNewAccount = (); type OnKilledAccount = (); } mod trade_event { pub use crate::Event; } impl_outer_event! { pub enum TestEvent for Test { trade_event<T>, balances<T>, system<T>, } } parameter_types! { pub const ExistentialDeposit: u64 = 1; } impl balances::Trait for Test { type Balance = u64; type DustRemoval = (); type Event = TestEvent; type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; } parameter_types! { pub const MaxClaimLength: u32 = 6; } impl Trait for Test { type Event = TestEvent; type Currency = Balances; } //noinspection RsUnresolvedReference pub type TradeModule = Module<Test>; pub type System = system::Module<Test>; pub type Balances = balances::Module<Test>; pub struct ExtBuilder; impl ExtBuilder { pub fn build() -> TestExternalities { let mut storage = system::GenesisConfig::default() .build_storage::<Test>() .unwrap(); balances::GenesisConfig::<Test> { balances: vec![(1, 4000), (2, 4000), (3, 4000), (4, 4000)], } .assimilate_storage(&mut storage).unwrap(); let mut ext = TestExternalities::from(storage); ext.execute_with(|| System::set_block_number(1)); ext } }
// 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::futex::*; use alloc::collections::btree_map::BTreeMap; use lazy_static::lazy_static; lazy_static! { pub static ref INIT_RLIMITS : BTreeMap<i32, RLimit> = [ (RLIMIT_CPU, RLimit {Cur: RLIM_INFINITY, Max: RLIM_INFINITY}), (RLIMIT_FSIZE, RLimit {Cur: RLIM_INFINITY, Max: RLIM_INFINITY}), (RLIMIT_DATA, RLimit {Cur: RLIM_INFINITY, Max: RLIM_INFINITY}), (RLIMIT_STACK, RLimit {Cur: DEFAULT_STACK_SOFT_LIMIT, Max: RLIM_INFINITY}), (RLIMIT_CORE, RLimit {Cur: 0, Max: RLIM_INFINITY}), (RLIMIT_RSS, RLimit {Cur: RLIM_INFINITY, Max: RLIM_INFINITY}), (RLIMIT_NPROC, RLimit {Cur: DEFAULT_NPROC_LIMIT, Max: DEFAULT_NPROC_LIMIT}), (RLIMIT_NOFILE, RLimit {Cur: DEFAULT_NOFILE_SOFT_LIMIT, Max: DEFAULT_NOFILE_HARD_LIMIT}), (RLIMIT_MEMLOCK, RLimit {Cur: DEFAULT_MEMLOCK_LIMIT, Max: DEFAULT_MEMLOCK_LIMIT}), (RLIMIT_AS, RLimit {Cur: RLIM_INFINITY, Max: RLIM_INFINITY}), (RLIMIT_LOCKS, RLimit {Cur: RLIM_INFINITY, Max: RLIM_INFINITY}), (RLIMIT_SIGPENDING, RLimit {Cur: 0, Max: 0}), (RLIMIT_MSGQUEUE, RLimit {Cur: DEFAULT_MSGQUEUE_LIMIT, Max: DEFAULT_MSGQUEUE_LIMIT}), (RLIMIT_NICE, RLimit {Cur: 0, Max: 0}), (RLIMIT_RTPRIO, RLimit {Cur: 0, Max: 0}), (RLIMIT_RTTIME, RLimit {Cur: RLIM_INFINITY, Max: RLIM_INFINITY}), ].iter().cloned().collect(); } // RLimit corresponds to Linux's struct rlimit. #[derive(Clone, Copy, Debug)] pub struct RLimit { // Cur specifies the soft limit. pub Cur: u64, // Max specifies the hard limit. pub Max: u64, } pub const RLIMIT_CPU: i32 = 0; pub const RLIMIT_FSIZE: i32 = 1; pub const RLIMIT_DATA: i32 = 2; pub const RLIMIT_STACK: i32 = 3; pub const RLIMIT_CORE: i32 = 4; pub const RLIMIT_RSS: i32 = 5; pub const RLIMIT_NPROC: i32 = 6; pub const RLIMIT_NOFILE: i32 = 7; pub const RLIMIT_MEMLOCK: i32 = 8; pub const RLIMIT_AS: i32 = 9; pub const RLIMIT_LOCKS: i32 = 10; pub const RLIMIT_SIGPENDING: i32 = 11; pub const RLIMIT_MSGQUEUE: i32 = 12; pub const RLIMIT_NICE: i32 = 13; pub const RLIMIT_RTPRIO: i32 = 14; pub const RLIMIT_RTTIME: i32 = 15; // RLimInfinity is RLIM_INFINITY on Linux. pub const RLIM_INFINITY: u64 = !0; // DefaultStackSoftLimit is called _STK_LIM in Linux. pub const DEFAULT_STACK_SOFT_LIMIT: u64 = 8 * 1024 * 1024; // DefaultNprocLimit is defined in kernel/fork.c:set_max_threads, and // called MAX_THREADS / 2 in Linux. pub const DEFAULT_NPROC_LIMIT: u64 = FUTEX_TID_MASK as u64 / 2; // DefaultNofileSoftLimit is called INR_OPEN_CUR in Linux. pub const DEFAULT_NOFILE_SOFT_LIMIT: u64 = 1024; // DefaultNofileHardLimit is called INR_OPEN_MAX in Linux. pub const DEFAULT_NOFILE_HARD_LIMIT: u64 = 4096; // DefaultMemlockLimit is called MLOCK_LIMIT in Linux. pub const DEFAULT_MEMLOCK_LIMIT: u64 = 64 * 1024; // DefaultMsgqueueLimit is called MQ_BYTES_MAX in Linux. pub const DEFAULT_MSGQUEUE_LIMIT: u64 = 819200;
pub mod vector; pub mod string; pub mod map;
//! Pull expression plan, but without nesting. use std::collections::HashMap; use timely::dataflow::scopes::child::Iterative; use timely::dataflow::{Scope, Stream}; use timely::order::Product; use timely::progress::Timestamp; use differential_dataflow::lattice::Lattice; use crate::binding::AsBinding; use crate::domain::Domain; use crate::plan::{Dependencies, Implementable, Plan}; use crate::timestamp::Rewind; use crate::{AsAid, Value, Var}; use crate::{Relation, ShutdownHandle, VariableMap}; /// A sequence of attributes that uniquely identify a nesting level in /// a Pull query. pub type PathId<A> = Vec<A>; /// A plan stage for extracting all matching [e a v] tuples for a /// given set of attributes and an input relation specifying entities. #[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)] pub struct PullLevel<P: Implementable> { /// Plan for the input relation. pub plan: Box<P>, /// Eid variable. pub pull_variable: Var, /// Attributes to pull for the input entities. pub pull_attributes: Vec<P::A>, /// Attribute names to distinguish plans of the same /// length. Useful to feed into a nested hash-map directly. pub path_attributes: Vec<P::A>, /// @TODO pub cardinality_many: bool, } impl<P: Implementable> PullLevel<P> { /// See Implementable::dependencies, as PullLevel v2 can't /// implement Implementable directly. fn dependencies(&self) -> Dependencies<P::A> { let attribute_dependencies = self .pull_attributes .iter() .cloned() .map(Dependencies::attribute) .sum(); self.plan.dependencies() + attribute_dependencies } /// See Implementable::implement, as PullLevel v2 can't implement /// Implementable directly. fn implement<'b, S>( &self, nested: &mut Iterative<'b, S, u64>, domain: &mut Domain<P::A, S::Timestamp>, local_arrangements: &VariableMap<P::A, Iterative<'b, S, u64>>, ) -> ( HashMap<PathId<P::A>, Stream<S, (Vec<Value>, S::Timestamp, isize)>>, ShutdownHandle, ) where S: Scope, S::Timestamp: Timestamp + Lattice + Rewind, { use differential_dataflow::operators::arrange::{Arrange, Arranged, TraceAgent}; use differential_dataflow::operators::JoinCore; use differential_dataflow::trace::implementations::ord::OrdValSpine; use differential_dataflow::trace::TraceReader; assert_eq!(self.pull_attributes.is_empty(), false); let (input, mut shutdown_handle) = self.plan.implement(nested, domain, local_arrangements); // Arrange input entities by eid. let e_offset = input .binds(self.pull_variable) .expect("input relation doesn't bind pull_variable"); let paths = { let (tuples, shutdown) = input.tuples(nested, domain); shutdown_handle.merge_with(shutdown); tuples }; let e_path: Arranged< Iterative<S, u64>, TraceAgent<OrdValSpine<Value, Vec<Value>, Product<S::Timestamp, u64>, isize>>, > = paths.map(move |t| (t[e_offset].clone(), t)).arrange(); let mut shutdown_handle = shutdown_handle; let path_streams = self .pull_attributes .iter() .map(|a| { let e_v = match domain.forward_propose(a) { None => panic!("attribute {:?} does not exist", a), Some(propose_trace) => { let frontier: Vec<S::Timestamp> = propose_trace.advance_frontier().to_vec(); let (arranged, shutdown_propose) = propose_trace .import_frontier(&nested.parent, &format!("Propose({:?})", a)); let e_v = arranged.enter_at(nested, move |_, _, time| { let mut forwarded = time.clone(); forwarded.advance_by(&frontier); Product::new(forwarded, 0) }); shutdown_handle.add_button(shutdown_propose); e_v } }; let path_id: Vec<P::A> = { assert_eq!(self.path_attributes.is_empty(), false); let mut path_attributes = self.path_attributes.clone(); path_attributes.push(a.clone()); path_attributes }; let path_stream = e_path .join_core(&e_v, move |_e, path: &Vec<Value>, v: &Value| { let mut result = path.clone(); result.push(v.clone()); Some(result) }) .leave() .inner; (path_id, path_stream) }) .collect::<HashMap<_, _>>(); (path_streams, shutdown_handle) } } /// A plan stage for extracting all tuples for a given set of /// attributes. #[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)] pub struct PullAll<A> { /// Attributes to pull for the input entities. pub pull_attributes: Vec<A>, } impl<A: AsAid> PullAll<A> { /// See Implementable::dependencies, as PullAll v2 can't implement /// Implementable directly. fn dependencies(&self) -> Dependencies<A> { self.pull_attributes .iter() .cloned() .map(Dependencies::attribute) .sum() } /// See Implementable::implement, as PullAll v2 can't implement /// Implementable directly. fn implement<'b, S>( &self, nested: &mut Iterative<'b, S, u64>, domain: &mut Domain<A, S::Timestamp>, _local_arrangements: &VariableMap<A, Iterative<'b, S, u64>>, ) -> ( HashMap<PathId<A>, Stream<S, (Vec<Value>, S::Timestamp, isize)>>, ShutdownHandle, ) where S: Scope, S::Timestamp: Timestamp + Lattice + Rewind, { use differential_dataflow::trace::TraceReader; assert!(!self.pull_attributes.is_empty()); let mut shutdown_handle = ShutdownHandle::empty(); let path_streams = self .pull_attributes .iter() .map(|a| { let e_v = match domain.forward_propose(a) { None => panic!("attribute {:?} does not exist", a), Some(propose_trace) => { let frontier: Vec<S::Timestamp> = propose_trace.advance_frontier().to_vec(); let (arranged, shutdown_propose) = propose_trace .import_frontier(&nested.parent, &format!("Propose({:?})", a)); let e_v = arranged.enter_at(nested, move |_, _, time| { let mut forwarded = time.clone(); forwarded.advance_by(&frontier); Product::new(forwarded, 0) }); shutdown_handle.add_button(shutdown_propose); e_v } }; let path_stream = e_v .as_collection(|e, v| vec![e.clone(), v.clone()]) .leave() .inner; (vec![a.clone()], path_stream) }) .collect::<HashMap<_, _>>(); (path_streams, shutdown_handle) } } /// @TODO #[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)] pub enum Pull<A: AsAid> { /// @TODO All(PullAll<A>), /// @TODO Level(PullLevel<Plan<A>>), } impl<A> Pull<A> where A: AsAid + timely::ExchangeData, { /// See Implementable::dependencies, as Pull v2 can't implement /// Implementable directly. pub fn dependencies(&self) -> Dependencies<A> { match self { Pull::All(ref pull) => pull.dependencies(), Pull::Level(ref pull) => pull.dependencies(), } } /// See Implementable::implement, as Pull v2 can't implement /// Implementable directly. pub fn implement<'b, S>( &self, nested: &mut Iterative<'b, S, u64>, domain: &mut Domain<A, S::Timestamp>, local_arrangements: &VariableMap<A, Iterative<'b, S, u64>>, ) -> ( HashMap<PathId<A>, Stream<S, (Vec<Value>, S::Timestamp, isize)>>, ShutdownHandle, ) where S: Scope, S::Timestamp: Timestamp + Lattice + Rewind, { match self { Pull::All(ref pull) => pull.implement(nested, domain, local_arrangements), Pull::Level(ref pull) => pull.implement(nested, domain, local_arrangements), } } }
use super::*; pub fn gen_pwstr() -> TokenStream { quote! { #[derive(::core::clone::Clone, ::core::marker::Copy, ::core::fmt::Debug, ::core::cmp::PartialEq, ::core::cmp::Eq)] #[repr(transparent)] pub struct PWSTR(pub *mut u16); impl PWSTR { pub fn is_null(&self) -> bool { self.0.is_null() } } impl ::core::default::Default for PWSTR { fn default() -> Self { Self(::core::ptr::null_mut()) } } unsafe impl ::windows::core::Abi for PWSTR { type Abi = Self; #[cfg(feature = "alloc")] unsafe fn drop_param(param: &mut ::windows::core::Param<'_, Self>) { if let ::windows::core::Param::Boxed(value) = param { if !value.is_null() { unsafe { ::windows::core::alloc::boxed::Box::from_raw(value.0); } } } } } #[cfg(feature = "alloc")] impl<'a> ::windows::core::IntoParam<'a, PWSTR> for &str { fn into_param(self) -> ::windows::core::Param<'a, PWSTR> { ::windows::core::Param::Boxed(PWSTR(::windows::core::alloc::boxed::Box::<[u16]>::into_raw(self.encode_utf16().chain(::core::iter::once(0)).collect::<::windows::core::alloc::vec::Vec<u16>>().into_boxed_slice()) as _)) } } #[cfg(feature = "alloc")] impl<'a> ::windows::core::IntoParam<'a, PWSTR> for ::windows::core::alloc::string::String { fn into_param(self) -> ::windows::core::Param<'a, PWSTR> { ::windows::core::IntoParam::into_param(self.as_str()) } } #[cfg(feature = "std")] impl<'a> ::windows::core::IntoParam<'a, PWSTR> for &::std::ffi::OsStr { fn into_param(self) -> ::windows::core::Param<'a, PWSTR> { use ::std::os::windows::ffi::OsStrExt; ::windows::core::Param::Boxed(PWSTR(::windows::core::alloc::boxed::Box::<[u16]>::into_raw(self.encode_wide().chain(::core::iter::once(0)).collect::<::windows::core::alloc::vec::Vec<u16>>().into_boxed_slice()) as _)) } } #[cfg(feature = "std")] impl<'a> ::windows::core::IntoParam<'a, PWSTR> for ::std::ffi::OsString { fn into_param(self) -> ::windows::core::Param<'a, PWSTR> { ::windows::core::IntoParam::into_param(self.as_os_str()) } } } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::alloc::Allocator; use std::borrow::Borrow; use std::intrinsics::assume; use std::mem::MaybeUninit; use super::container::Container; use super::traits::EntryMutRefLike; use super::traits::EntryRefLike; use super::traits::Keyable; pub struct Entry<K, V> { pub(crate) _alignment: [u64; 0], pub(crate) key: MaybeUninit<K>, pub(crate) val: MaybeUninit<V>, } impl<K: Keyable, V> Entry<K, V> { #[inline(always)] pub(crate) fn is_zero(&self) -> bool { K::is_zero(&self.key) } // this function can only be used in external crates #[inline(always)] pub fn key(&self) -> &K { unsafe { self.key.assume_init_ref() } } // this function can only be used in external crates /// # Safety /// /// The new key should be equals the old key. #[inline(always)] pub unsafe fn set_key(&mut self, key: K) { self.key.write(key); } // this function can only be used in external crates #[inline(always)] pub fn get(&self) -> &V { unsafe { self.val.assume_init_ref() } } // this function can only be used in external crates #[inline(always)] pub fn get_mut(&mut self) -> &mut V { unsafe { self.val.assume_init_mut() } } // this function can only be used in external crates #[inline(always)] pub fn write(&mut self, val: V) { self.val.write(val); } } pub struct Table0<K, V, C, A> where K: Keyable, C: Container<T = Entry<K, V>, A = A>, A: Allocator + Clone, { pub(crate) len: usize, #[allow(dead_code)] pub(crate) allocator: A, pub(crate) entries: C, pub(crate) dropped: bool, } impl<K, V, C, A> Table0<K, V, C, A> where K: Keyable, C: Container<T = Entry<K, V>, A = A>, A: Allocator + Clone, { pub fn with_capacity_in(capacity: usize, allocator: A) -> Self { Self { entries: unsafe { C::new_zeroed( std::cmp::max(8, capacity.next_power_of_two()), allocator.clone(), ) }, len: 0, allocator, dropped: false, } } #[inline(always)] pub fn len(&self) -> usize { self.len } #[inline(always)] pub fn heap_bytes(&self) -> usize { self.entries.heap_bytes() } #[inline(always)] pub fn capacity(&self) -> usize { self.entries.len() } /// # Safety /// /// `key` doesn't equal to zero. #[inline(always)] pub unsafe fn get(&self, key: &K) -> Option<&Entry<K, V>> { self.get_with_hash(key, key.hash()) } /// # Safety /// /// `key` doesn't equal to zero. /// Provided hash is correct. #[inline(always)] pub unsafe fn get_with_hash(&self, key: &K, hash: u64) -> Option<&Entry<K, V>> { assume(!K::equals_zero(key)); let index = (hash as usize) & (self.entries.len() - 1); for i in (index..self.entries.len()).chain(0..index) { assume(i < self.entries.len()); if self.entries[i].is_zero() { return None; } if self.entries[i].key.assume_init_ref().borrow() == key { return Some(&self.entries[i]); } } None } /// # Safety /// /// `key` doesn't equal to zero. #[inline(always)] pub unsafe fn get_mut(&mut self, key: &K) -> Option<&mut Entry<K, V>> { self.get_with_hash_mut(key, key.hash()) } /// # Safety /// /// `key` doesn't equal to zero. /// Provided hash is correct. #[inline(always)] pub unsafe fn get_with_hash_mut(&mut self, key: &K, hash: u64) -> Option<&mut Entry<K, V>> { assume(!K::equals_zero(key)); let index = (hash as usize) & (self.entries.len() - 1); for i in (index..self.entries.len()).chain(0..index) { assume(i < self.entries.len()); if self.entries[i].is_zero() { return None; } if self.entries[i].key.assume_init_ref().borrow() == key { return Some(&mut self.entries[i]); } } None } /// # Safety /// /// `key` doesn't equal to zero. /// The resulted `MaybeUninit` should be initialized immedidately. /// /// # Panics /// /// Panics if the hash table overflows. #[inline(always)] pub unsafe fn insert(&mut self, key: K) -> Result<&mut Entry<K, V>, &mut Entry<K, V>> { self.insert_with_hash(key, key.hash()) } /// # Safety /// /// `key` doesn't equal to zero. /// The resulted `MaybeUninit` should be initialized immedidately. /// Provided hash is correct. /// /// # Panics /// The hashtable is full. #[inline(always)] pub unsafe fn insert_with_hash( &mut self, key: K, hash: u64, ) -> Result<&mut Entry<K, V>, &mut Entry<K, V>> { assume(!K::equals_zero(&key)); let index = (hash as usize) & (self.entries.len() - 1); for i in (index..self.entries.len()).chain(0..index) { assume(i < self.entries.len()); if self.entries[i].is_zero() { self.len += 1; self.entries[i].key.write(key); return Ok(&mut self.entries[i]); } if self.entries[i].key.assume_init_ref() == &key { return Err(&mut self.entries[i]); } } panic!("the hash table overflows") } pub fn iter(&self) -> Table0Iter<'_, K, V> { Table0Iter { slice: self.entries.as_ref(), i: 0, } } pub fn clear(&mut self) { unsafe { self.len = 0; if std::mem::needs_drop::<V>() { for entry in self.entries.as_mut() { if !entry.is_zero() { std::ptr::drop_in_place(entry.get_mut()); } } } self.entries = C::new_zeroed(0, self.allocator.clone()); } } #[inline] pub fn check_grow(&mut self) { if std::intrinsics::unlikely((self.len() + 1) * 2 > self.capacity()) { if (self.entries.len() >> 22) == 0 { self.grow(2); } else { self.grow(1); } } } pub fn grow(&mut self, shift: u8) { let old_capacity = self.entries.len(); let new_capacity = self.entries.len() << shift; unsafe { self.entries.grow_zeroed(new_capacity); } for i in 0..old_capacity { unsafe { assume(i < self.entries.len()); } if K::is_zero(&self.entries[i].key) { continue; } let key = unsafe { self.entries[i].key.assume_init_ref() }; let hash = K::hash(key); let index = (hash as usize) & (self.entries.len() - 1); for j in (index..self.entries.len()).chain(0..index) { unsafe { assume(j < self.entries.len()); } if j == i { break; } if self.entries[j].is_zero() { unsafe { self.entries[j] = std::ptr::read(&self.entries[i]); self.entries[i].key = MaybeUninit::zeroed(); } break; } } } for i in old_capacity..new_capacity { unsafe { assume(i < self.entries.len()); } if K::is_zero(&self.entries[i].key) { break; } let key = unsafe { self.entries[i].key.assume_init_ref() }; let hash = K::hash(key); let index = (hash as usize) & (self.entries.len() - 1); for j in (index..self.entries.len()).chain(0..index) { unsafe { assume(j < self.entries.len()); } if j == i { break; } if self.entries[j].is_zero() { unsafe { self.entries[j] = std::ptr::read(&self.entries[i]); self.entries[i].key = MaybeUninit::zeroed(); } break; } } } } } impl<K, C, A> Table0<K, (), C, A> where K: Keyable, C: Container<T = Entry<K, ()>, A = A>, A: Allocator + Clone, { pub unsafe fn set_merge(&mut self, other: &Self) { while (self.len() + other.len()) * 2 > self.capacity() { if (self.entries.len() >> 22) == 0 { self.grow(2); } else { self.grow(1); } } for entry in other.iter() { let key = entry.key.assume_init(); let _ = self.insert(key); } } } impl<K, V, C, A> Drop for Table0<K, V, C, A> where K: Keyable, C: Container<T = Entry<K, V>, A = A>, A: Allocator + Clone, { fn drop(&mut self) { if std::mem::needs_drop::<V>() && !self.dropped { unsafe { for entry in self.entries.as_mut() { if !entry.is_zero() { std::ptr::drop_in_place(entry.get_mut()); } } } } } } pub struct Table0Iter<'a, K, V> { slice: &'a [Entry<K, V>], i: usize, } impl<'a, K, V> Iterator for Table0Iter<'a, K, V> where K: Keyable { type Item = &'a Entry<K, V>; fn next(&mut self) -> Option<Self::Item> { while self.i < self.slice.len() && self.slice[self.i].is_zero() { self.i += 1; } if self.i == self.slice.len() { None } else { let res = unsafe { &*(self.slice.as_ptr().add(self.i) as *const _) }; self.i += 1; Some(res) } } fn size_hint(&self) -> (usize, Option<usize>) { let remain = self.slice.len() - self.i; (remain, Some(remain)) } } pub struct Table0IterMut<'a, K, V> { slice: &'a mut [Entry<K, V>], i: usize, } impl<'a, K, V> Iterator for Table0IterMut<'a, K, V> where K: Keyable { type Item = &'a mut Entry<K, V>; fn next(&mut self) -> Option<Self::Item> { while self.i < self.slice.len() && self.slice[self.i].is_zero() { self.i += 1; } if self.i == self.slice.len() { None } else { let res = unsafe { &mut *(self.slice.as_ptr().add(self.i) as *mut _) }; self.i += 1; Some(res) } } } impl<'a, K: Keyable, V: 'a> EntryRefLike for &'a Entry<K, V> { type KeyRef = &'a K; type ValueRef = &'a V; fn key(&self) -> Self::KeyRef { unsafe { self.key.assume_init_ref() } } fn get(&self) -> Self::ValueRef { (*self).get() } } impl<'a, K: Keyable, V> EntryMutRefLike for &'a mut Entry<K, V> { type Key = K; type Value = V; fn key(&self) -> &Self::Key { unsafe { self.key.assume_init_ref() } } fn get(&self) -> &Self::Value { unsafe { self.val.assume_init_ref() } } fn get_mut(&mut self) -> &mut Self::Value { unsafe { self.val.assume_init_mut() } } fn write(&mut self, value: Self::Value) { self.val.write(value); } }
/* * Copyright © 2019 Peter M. Stahl pemistahl@gmail.com * * 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 expressed or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::collections::BTreeSet; use itertools::EitherOrBoth::Both; use itertools::Itertools; use unicode_segmentation::UnicodeSegmentation; #[derive(Clone, Eq, PartialEq)] pub(crate) enum Expression { Alternation(Vec<Expression>), CharacterClass(BTreeSet<char>), Concatenation(Box<Expression>, Box<Expression>), Literal(Vec<String>), Repetition(Box<Expression>, Quantifier), } #[derive(Clone, Eq, PartialEq)] pub(crate) enum Quantifier { KleeneStar, QuestionMark, } pub(crate) enum Substring { Prefix, Suffix, } impl Expression { pub(crate) fn new_alternation(expr1: Expression, expr2: Expression) -> Self { let mut options: Vec<Expression> = vec![]; flatten_alternations(&mut options, vec![expr1, expr2]); options.sort_by(|a, b| b.len().cmp(&a.len())); Expression::Alternation(options) } fn new_character_class( first_char_set: BTreeSet<char>, second_char_set: BTreeSet<char>, ) -> Self { let union_set = first_char_set.union(&second_char_set).copied().collect(); Expression::CharacterClass(union_set) } pub(crate) fn new_concatenation(expr1: Expression, expr2: Expression) -> Self { Expression::Concatenation(Box::from(expr1), Box::from(expr2)) } pub(crate) fn new_literal(value: &str) -> Self { Expression::Literal( UnicodeSegmentation::graphemes(value, true) .map(|it| it.to_string()) .collect_vec(), ) } pub(crate) fn new_repetition(expr: Expression, quantifier: Quantifier) -> Self { Expression::Repetition(Box::from(expr), quantifier) } fn is_empty(&self) -> bool { match self { Expression::Literal(graphemes) => graphemes.is_empty(), _ => false, } } pub(crate) fn is_single_codepoint(&self) -> bool { match self { Expression::CharacterClass(_) => true, Expression::Literal(graphemes) => { graphemes.len() == 1 && graphemes.first().unwrap().chars().count() == 1 } _ => false, } } fn len(&self) -> usize { match self { Expression::Alternation(options) => options.first().unwrap().len(), Expression::CharacterClass(_) => 1, Expression::Concatenation(expr1, expr2) => expr1.len() + expr2.len(), Expression::Literal(graphemes) => graphemes.len(), Expression::Repetition(expr, _) => expr.len(), } } pub(crate) fn precedence(&self) -> u8 { match self { Expression::Alternation(_) | Expression::CharacterClass(_) => 1, Expression::Concatenation(_, _) | Expression::Literal(_) => 2, Expression::Repetition(_, _) => 3, } } pub(crate) fn remove_substring(&mut self, substring: &Substring, length: usize) { match self { Expression::Concatenation(expr1, expr2) => match substring { Substring::Prefix => { if let Expression::Literal(_) = **expr1 { expr1.remove_substring(substring, length) } } Substring::Suffix => { if let Expression::Literal(_) = **expr2 { expr2.remove_substring(substring, length) } } }, Expression::Literal(graphemes) => match substring { Substring::Prefix => { graphemes.drain(..length); } Substring::Suffix => { graphemes.drain(graphemes.len() - length..); } }, _ => (), } } pub(crate) fn value(&self, substring: Option<&Substring>) -> Option<Vec<&str>> { match self { Expression::Concatenation(expr1, expr2) => match substring { Some(value) => match value { Substring::Prefix => expr1.value(None), Substring::Suffix => expr2.value(None), }, None => None, }, Expression::Literal(graphemes) => { let mut v = vec![]; for grapheme in graphemes { v.push(grapheme.as_str()); } Some(v) } _ => None, } } } fn flatten_alternations(flattened_options: &mut Vec<Expression>, current_options: Vec<Expression>) { for option in current_options { if let Expression::Alternation(expr_options) = option { flatten_alternations(flattened_options, expr_options); } else { flattened_options.push(option); } } } pub(crate) fn repeat_zero_or_more_times(expr: &Option<Expression>) -> Option<Expression> { if let Some(value) = expr { Some(Expression::new_repetition( value.clone(), Quantifier::KleeneStar, )) } else { None } } pub(crate) fn concatenate(a: &Option<Expression>, b: &Option<Expression>) -> Option<Expression> { if a.is_none() || b.is_none() { return None; } let expr1 = a.as_ref().unwrap(); let expr2 = b.as_ref().unwrap(); if expr1.is_empty() { return b.clone(); } if expr2.is_empty() { return a.clone(); } if let (Expression::Literal(graphemes_a), Expression::Literal(graphemes_b)) = (&expr1, &expr2) { return Some(Expression::new_literal( format!("{}{}", graphemes_a.join(""), graphemes_b.join("")).as_str(), )); } if let (Expression::Literal(graphemes_a), Expression::Concatenation(first, second)) = (&expr1, &expr2) { if let Expression::Literal(graphemes_first) = &**first { let literal = Expression::new_literal( format!("{}{}", graphemes_a.join(""), graphemes_first.join("")).as_str(), ); return Some(Expression::new_concatenation(literal, *second.clone())); } } if let (Expression::Literal(graphemes_b), Expression::Concatenation(first, second)) = (&expr2, &expr1) { if let Expression::Literal(graphemes_second) = &**second { let literal = Expression::new_literal( format!("{}{}", graphemes_second.join(""), graphemes_b.join("")).as_str(), ); return Some(Expression::new_concatenation(*first.clone(), literal)); } } Some(Expression::new_concatenation(expr1.clone(), expr2.clone())) } pub(crate) fn union(a: &Option<Expression>, b: &Option<Expression>) -> Option<Expression> { if let (Some(mut expr1), Some(mut expr2)) = (a.clone(), b.clone()) { if expr1 != expr2 { let common_prefix = remove_common_substring(&mut expr1, &mut expr2, Substring::Prefix); let common_suffix = remove_common_substring(&mut expr1, &mut expr2, Substring::Suffix); let mut result = if expr1.is_empty() { Some(Expression::new_repetition( expr2.clone(), Quantifier::QuestionMark, )) } else if expr2.is_empty() { Some(Expression::new_repetition( expr1.clone(), Quantifier::QuestionMark, )) } else { None }; if result.is_none() { if let Expression::Repetition(expr, quantifier) = expr1.clone() { if quantifier == Quantifier::QuestionMark { let alternation = Expression::new_alternation(*expr, expr2.clone()); result = Some(Expression::new_repetition( alternation, Quantifier::QuestionMark, )); } } } if result.is_none() { if let Expression::Repetition(expr, quantifier) = expr2.clone() { if quantifier == Quantifier::QuestionMark { let alternation = Expression::new_alternation(expr1.clone(), *expr); result = Some(Expression::new_repetition( alternation, Quantifier::QuestionMark, )); } } } if result.is_none() && expr1.is_single_codepoint() && expr2.is_single_codepoint() { let first_char_set = extract_character_set(expr1.clone()); let second_char_set = extract_character_set(expr2.clone()); result = Some(Expression::new_character_class( first_char_set, second_char_set, )); } if result.is_none() { result = Some(Expression::new_alternation(expr1.clone(), expr2.clone())); } if let Some(prefix) = common_prefix { result = Some(Expression::new_concatenation( Expression::new_literal(&prefix), result.unwrap(), )); } if let Some(suffix) = common_suffix { result = Some(Expression::new_concatenation( result.unwrap(), Expression::new_literal(&suffix), )); } result } else if a.is_some() { a.clone() } else if b.is_some() { b.clone() } else { None } } else if a.is_some() { a.clone() } else if b.is_some() { b.clone() } else { None } } fn extract_character_set(expr: Expression) -> BTreeSet<char> { match expr { Expression::Literal(graphemes) => { let single_char = graphemes.first().unwrap().chars().next().unwrap(); btree_set![single_char] } Expression::CharacterClass(char_set) => char_set, _ => BTreeSet::new(), } } fn remove_common_substring( a: &mut Expression, b: &mut Expression, substring: Substring, ) -> Option<String> { let common_substring = find_common_substring(a, b, &substring); if let Some(value) = &common_substring { a.remove_substring(&substring, value.len()); b.remove_substring(&substring, value.len()); } common_substring } fn find_common_substring(a: &Expression, b: &Expression, substring: &Substring) -> Option<String> { let mut graphemes_a = a.value(Some(substring)).unwrap_or_else(|| vec![]); let mut graphemes_b = b.value(Some(substring)).unwrap_or_else(|| vec![]); let mut common_graphemes = vec![]; if let Substring::Suffix = substring { graphemes_a.reverse(); graphemes_b.reverse(); } for pair in graphemes_a.iter().zip_longest(graphemes_b.iter()) { match pair { Both(grapheme_a, grapheme_b) => { if grapheme_a == grapheme_b { common_graphemes.push(*grapheme_a); } else { break; } } _ => break, } } if let Substring::Suffix = substring { common_graphemes.reverse(); } if common_graphemes.is_empty() { None } else { Some(common_graphemes.join("")) } }
use crate::ray::Ray; use crate::vec3::{Vec3, Point3}; use crate::material::Material; pub struct HitRecord{ pub t: f32, pub hit_point: Point3, pub normal: Vec3, pub front_face: bool, pub material: Material, } pub trait Hittable { fn hit(&self, r: &Ray, t_min: f32, t_max: f32) -> Option<HitRecord>; } impl HitRecord { pub fn set_face_normal(&mut self, r: &Ray, outward_normal: &Vec3) { self.front_face = r.direction().dot(*outward_normal) < 0.0; self.normal = if self.front_face { *outward_normal } else { -*outward_normal }; } }
// dari Book.rb // 08/12/2019 04:54 // struct Book { title: String, author: String, } impl Book { fn get_info(&self) { println!("Title: {}, Author: {}", self.title, self.author); } } fn main() { let book = Book{ title: String::from("Halaqoh Cinta"), author: String::from("@teladanrasul") }; book.get_info(); }
// This file is part of ICU4X. For terms of use, please see the file // called LICENSE at the top level of the ICU4X source tree // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). use crate::Calendar; use std::fmt; use std::marker::PhantomData; #[derive(Copy, Clone, Eq, PartialEq)] /// A duration between two dates pub struct DateDuration<C: Calendar + ?Sized> { pub years: i32, pub months: i32, pub weeks: i32, pub days: i32, pub marker: PhantomData<C>, } #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum DurationUnit { Years, Months, Weeks, Days, } impl<C: Calendar + ?Sized> Default for DateDuration<C> { fn default() -> Self { Self { years: 0, months: 0, weeks: 0, days: 0, marker: PhantomData, } } } impl<C: Calendar + ?Sized> DateDuration<C> { pub fn new(years: i32, months: i32, weeks: i32, days: i32) -> Self { DateDuration { years, months, weeks, days, marker: PhantomData, } } } impl<C: Calendar> fmt::Debug for DateDuration<C> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { f.debug_struct("DateDuration") .field("years", &self.years) .field("months", &self.months) .field("weeks", &self.weeks) .field("days", &self.days) .finish() } }
use std::fmt; use rumqtt::Error as RumqttError; use std::io::Error as IOError; use std::env::VarError; use rusqlite::Error as RusqliteError; use hyper::Error as HyperError; use std::option::NoneError; use std::num::ParseIntError; use std::num::ParseFloatError; use std::string::FromUtf8Error; pub enum Error { Io(IOError), Rumqtt(RumqttError), Var(VarError), Rusqlite(RusqliteError), Hyper(HyperError), None(NoneError), ParseInt(ParseIntError), ParseFloat(ParseFloatError), FromUtf8(FromUtf8Error), } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use Error::*; use std::error::Error; write!(f, "{}", match *self { Io(ref err) => err.description(), Rumqtt(ref err) => err.description(), Var(ref err) => err.description(), Rusqlite(ref err) => err.description(), Hyper(ref err) => err.description(), None(_) => "std::option::Option value not present", ParseInt(ref err) => err.description(), ParseFloat(ref err) => err.description(), FromUtf8(ref err) => err.description(), }) } } impl From<IOError> for Error { fn from(err: IOError) -> Self { Error::Io(err) } } impl From<RumqttError> for Error { fn from(err: RumqttError) -> Self { Error::Rumqtt(err) } } impl From<VarError> for Error { fn from(err: VarError) -> Self { Error::Var(err) } } impl From<RusqliteError> for Error { fn from(err: RusqliteError) -> Self { Error::Rusqlite(err) } } impl From<HyperError> for Error { fn from(err: HyperError) -> Self { Error::Hyper(err) } } impl From<NoneError> for Error { fn from(err: NoneError) -> Self { Error::None(err) } } impl From<ParseIntError> for Error { fn from(err: ParseIntError) -> Self { Error::ParseInt(err) } } impl From<ParseFloatError> for Error { fn from(err: ParseFloatError) -> Self { Error::ParseFloat(err) } } impl From<FromUtf8Error> for Error { fn from(err: FromUtf8Error) -> Self { Error::FromUtf8(err) } }
//! # OpenEXR //! //! The openexr crate provides high-level bindings for the [ASWF OpenEXR library](https://github.com/AcademySoftwareFoundation/openexr), //! which allows reading and writing files in the OpenEXR format (EXR standing //! for **EX**tended **R**ange). The OpenEXR format is the de-facto standard //! image storage format of the motion-picture industry. //! //! The purpose of EXR format is to accurately and efficiently represent high-dynamic-range scene-linear image data and associated metadata, with strong support for multi-part, multi-channel use cases. //! //! OpenEXR is widely used in host application software where accuracy is critical, such as photorealistic rendering, texture access, image compositing, deep compositing, and DI. //! OpenEXR is a project of the [Academy Software Foundation](https://www.aswf.io/). The format and library were originally developed by Industrial Light & Magic and first released in 2003. Weta Digital, Walt Disney Animation Studios, Sony Pictures Imageworks, Pixar Animation Studios, DreamWorks, and other studios, companies, and individuals have made contributions to the code base. //! //! OpenEXR is included in the [VFX Reference Platform](https://vfxplatform.com/). //! //! The openexr crate is maintained by [the vfx-rs project](https://github.com/vfx-rs). //! //! # Quick Start //! //! To use the included C++ OpenEXR source: //! //! ```bash //! cargo add openexr //! cargo build //! ``` //! //! If you have an existing installation of OpenEXR that you would like to use //! instead: //! //! ```bash //! cargo add openexr //! CMAKE_PREFIX_PATH=/path/to/cmake/configs cargo build //! ``` //! //! Note that you must take care to ensure that the version of OpenEXR you are //! pointing it to is the same as that for this version of the crate, otherwise //! you will encounter linker errors since all OpenEXR symbols are versioned. //! //! The [`prelude`](crate::prelude) pulls in the set of types that you //! need for basic file I/O of RGBA and arbitrary channel images: //! //! ```no_run //! use openexr::prelude::*; //! //! fn write_rgba1(filename: &str, pixels: &[Rgba], width: i32, height: i32) //! -> Result<(), Box<dyn std::error::Error>> { //! let header = Header::from_dimensions(width, height); //! let mut file = RgbaOutputFile::new( //! filename, //! &header, //! RgbaChannels::WriteRgba, //! 1, //! )?; //! //! file.set_frame_buffer(&pixels, 1, width as usize)?; //! file.write_pixels(height)?; //! //! Ok(()) //! } //! //! fn read_rgba1(path: &str) -> Result<(), Box<dyn std::error::Error>> { //! use imath_traits::Zero; //! //! let mut file = RgbaInputFile::new(path, 1).unwrap(); //! // Note that windows in OpenEXR are ***inclusive*** bounds, so a //! // 1920x1080 image has window [0, 0, 1919, 1079]. //! let data_window: [i32; 4] = *file.header().data_window(); //! let width = data_window.width() + 1; //! let height = data_window.height() + 1; //! //! let mut pixels = vec![Rgba::zero(); (width * height) as usize]; //! file.set_frame_buffer(&mut pixels, 1, width as usize)?; //! file.read_pixels(0, height - 1)?; //! //! Ok(()) //! } //! ``` //! //! Beyond that, types related to deep images are in the [`deep`](crate::deep) //! module, and tiled images are in the [`tiled`](crate::tiled) module. //! //! The [Reading and Writing OpenEXR Image Files](crate::doc::reading_and_writing_image_files) //! document is a great place to start to explore the full functionality of the //! crate. It contains example usage for nearly everything. //! //! # Math Crate Interoperability //! OpenEXR (and much of the rest of the VFX ecosystem) relies on Imath for basic //! math primitives like vectors and bounding boxes. //! //! Rust already has several mature crates for linear algebra targetting graphics //! such as [cgmath](https://crates.io/crates/cgmath), [nalgebra](https://crates.io/crates/nalgebra), [nalgebra-glm](https://crates.io/crates/nalgebra-glm) and [glam](https://crates.io/crates/glam). Rather than adding yet another //! contender to this crowded field, we instead provide a set of traits that allow //! any of these crates to be used with openexr in the form of [imath-traits](https://crates.io/crates/imath-traits). By default, these traits are implemented for arrays and slices, so you will find that the examples in this documentation will tend to use e.g. `[i32; 4]` for bounding boxes: //! //! ```no_run //! # use openexr::prelude::*; //! # fn read_rgba1(path: &str) -> Result<(), Box<dyn std::error::Error>> { //! # use imath_traits::Zero; //! let mut file = RgbaInputFile::new(path, 1).unwrap(); //! let data_window = file.header().data_window::<[i32; 4]>().clone(); //! let width = data_window.width() + 1; //! let height = data_window.height() + 1; //! # Ok(()) //! # } //! ``` //! //! To use your preffered math crate instead, simply enable the corresponding feature on openexr, //! which will be `imath_<name>`, for example: //! //! ```bash //! cargo build --features=imath_cgmath //! ``` //! //! Now you can use types from that crate together with openexr seamlessly. In //! the case that the math crate does not provide a bounding box type, one will //! be available as `imath_traits::Box2i` and `imath_traits::Box3i`. //! //! ```no_run //! # use openexr::prelude::*; //! #[cfg(feature = "imath_cgmath")] //! # fn read_rgba1(path: &str) -> Result<(), Box<dyn std::error::Error>> { //! # use imath_traits::Zero; //! use imath_traits::Box2i; //! //! let mut file = RgbaInputFile::new(path, 1).unwrap(); //! let data_window: Box2i = *file.header().data_window(); //! let width = data_window.width() + 1; //! let height = data_window.height() + 1; //! # Ok(()) //! # } //! ``` //! //! # Features //! * High dynamic range and color precision. //! * Support for 16-bit floating-point, 32-bit floating-point, and 32-bit integer pixels. //! * Multiple image compression algorithms, both lossless and lossy. Some of the included codecs can achieve 2:1 lossless compression ratios on images with film grain. The lossy codecs have been tuned for visual quality and decoding performance. //! * Extensibility. New image attributes (strings, vectors, integers, etc.) can be added to OpenEXR image headers without affecting backward compatibility with existing OpenEXR applications. //! * Support for stereoscopic image workflows and a generalization to multi-views. //! * Flexible support for deep data: pixels can store a variable-length list of samples and, thus, it is possible to store multiple values at different depths for each pixel. Hard surfaces and volumetric data representations are accommodated. //! * Multipart: ability to encode separate, but related, images in one file. This allows for access to individual parts without the need to read other parts in the file. //! //! # Long-Form Documentation //! //! The following documents give a more in-depth view of different parts of the //! openexr crate: //! //! * [Reading and Writing Image Files](crate::doc::reading_and_writing_image_files) - A //! tutorial-style guide to the main image reading and writing interfaces. //! * [Technical Introduction](crate::doc::technical_introduction) - A technical overview of the //! OpenEXR format and its related concepts. //! * [Interpreting Deep Pixels](crate::doc::interpreting_deep_pixels) - An in-depth look at how //! deep pixels are stored and how to manipulate their samples. //! * [Multi-View OpenEXR](crate::doc::multi_view_open_exr) - Representation of multi-view images //! in OpenEXR files. //! //! # Building the documentation //! //! To build the full documentation including long-form docs and KaTeX equations, use the following //! command: //! //! ```bash //! cargo +nightly doc --no-deps --features=long-form-docs //! ``` //! Note this is done automatically for docs.rs when publishing. //! //! To run the doctests in the long-form docs (i.e. make sure the code examples //! compile correctly) run: //! ```bash //! cargo +nightly test --features=long-form-docs //! ``` //! //! This should no longer be necessary once Rust 1.54 is released. //! #![allow(dead_code)] pub mod core; pub mod deep; pub mod doc; pub mod flat; pub mod multi_part; pub mod prelude; pub mod rgba; pub mod tiled; pub mod util; // Re-export Error type so we can always unambiguously refer to it pub use crate::core::error::Error; #[cfg(test)] mod tests { use crate::prelude::*; use std::path::PathBuf; use half::f16; pub(crate) fn deep_testpattern( width: i32, height: i32, ) -> (Vec<Vec<f32>>, Vec<Vec<f16>>) { let mut z_pixels = Vec::<Vec<f32>>::new(); let mut a_pixels = Vec::<Vec<f16>>::new(); for y in 0..height { let v = y as f32 / height as f32 * 8.0; for x in 0..width { let u = (x as f32) / (width as f32) * 8.0; let z_v = vec![((u.sin() * v.sin()) + 1.0)]; let a_v = vec![f16::from_f32(1.0f32)]; z_pixels.push(z_v); a_pixels.push(a_v); } } (z_pixels, a_pixels) } pub(crate) fn load_ferris() -> (Vec<Rgba>, i32, i32) { let path = PathBuf::from( std::env::var("CARGO_MANIFEST_DIR") .expect("CARGO_MANIFEST_DIR not set"), ) .join("images") .join("ferris.png"); let mut decoder = png::Decoder::new( std::fs::File::open(&path).expect("Couldn't open file"), ); decoder.set_transformations(png::Transformations::EXPAND); let (info, mut reader) = decoder.read_info().expect("Couldn't read info from file"); let mut buf = vec![0u8; info.buffer_size()]; reader.next_frame(&mut buf).expect("Coulnd't read frame"); let pixels: Vec<Rgba> = buf .chunks_exact(4) .map(|p| { Rgba::from_f32( p[0] as f32 / 255.0f32, p[1] as f32 / 255.0f32, p[2] as f32 / 255.0f32, p[3] as f32 / 255.0f32, ) }) .collect(); (pixels, info.width as i32, info.height as i32) } type Result<T, E = crate::Error> = std::result::Result<T, E>; fn write_rgba( filename: &str, pixels: &[Rgba], width: i32, height: i32, ) -> Result<()> { let header = Header::from_dimensions(width, height); let mut file = RgbaOutputFile::new(filename, &header, RgbaChannels::WriteRgba, 4)?; file.set_frame_buffer(&pixels, 1, width as usize)?; file.write_pixels(height)?; Ok(()) } #[test] fn write_rgba1() -> Result<(), Box<dyn std::error::Error>> { let (pixels, width, height) = load_ferris(); let header = Header::from_dimensions(width, height); let mut file = RgbaOutputFile::new( "write_rgba1.exr", &header, RgbaChannels::WriteRgba, 1, )?; file.set_frame_buffer(&pixels, 1, width as usize)?; file.write_pixels(height)?; Ok(()) } #[test] fn write_rgba3() -> Result<(), Box<dyn std::error::Error>> { use crate::core::attribute::{CppStringAttribute, M44fAttribute}; let (pixels, width, height) = load_ferris(); let comments = "this is an awesome image of Ferris"; let xform = [0.0f32; 16]; let mut header = Header::from_dimensions(width, height); header.insert("comments", &CppStringAttribute::from_value(comments))?; header.insert("cameraTransform", &M44fAttribute::from_value(&xform))?; let mut file = RgbaOutputFile::new( "write_rgba3.exr", &header, RgbaChannels::WriteRgba, 1, )?; file.set_frame_buffer(&pixels, 1, width as usize)?; file.write_pixels(height)?; Ok(()) } #[test] fn read_rgba1() -> Result<(), Box<dyn std::error::Error>> { use imath_traits::Zero; let path = PathBuf::from( std::env::var("CARGO_MANIFEST_DIR") .expect("CARGO_MANIFEST_DIR not set"), ) .join("images") .join("ferris.exr"); let mut file = RgbaInputFile::new(&path, 1)?; let data_window = file.header().data_window::<[i32; 4]>().clone(); let width = data_window[2] - data_window[0] + 1; let height = data_window[3] - data_window[1] + 1; let mut pixels = vec![Rgba::zero(); (width * height) as usize]; file.set_frame_buffer(&mut pixels, 1, width as usize)?; file.read_pixels(0, height - 1)?; let mut ofile = RgbaOutputFile::with_dimensions( "read_rgba1.exr", width, height, RgbaChannels::WriteRgba, 1.0f32, [0.0f32, 0.0f32], 1.0f32, LineOrder::IncreasingY, Compression::Piz, 1, )?; ofile.set_frame_buffer(&pixels, 1, width as usize)?; ofile.write_pixels(height)?; Ok(()) } #[test] fn read_header() -> Result<(), Box<dyn std::error::Error>> { let path = PathBuf::from( std::env::var("CARGO_MANIFEST_DIR") .expect("CARGO_MANIFEST_DIR not set"), ) .join("images") .join("custom_attributes.exr"); let file = RgbaInputFile::new(&path, 1)?; if let Some(attr) = file.header().find_typed_attribute_string("comments") { assert_eq!(attr.value(), "this is an awesome image of Ferris"); } else { } match file.header().find_typed_attribute_string("comments") { Some(attr) if attr.value() == "this is an awesome image of Ferris" => { () } _ => panic!("bad string attr"), }; match file.header().find_typed_attribute_m44f("cameraTransform") { Some(_) => (), _ => panic!("bad matrix attr"), }; Ok(()) } }
//! Various utilities for working with files use crate::errors::{bail, err_msg, format_err, Result, ResultExt}; use log::trace; use std::ffi::{OsStr, OsString}; use std::fs; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Read, Write}; use std::path::{Path, PathBuf}; /// Move file or directory `src` to `dst` recursively, /// overwriting previous contents of `dst`. If corresponding /// old file has the same content as the new file, timestamps /// of the old file are preserved. pub fn move_files(src: &Path, dst: &Path) -> Result<()> { let inner = || -> Result<()> { if src.is_dir() { if !dst.is_dir() { trace!("[DebugMoveFiles] New dir created: {}", dst.display()); create_dir(dst)?; } for item in read_dir(dst)? { let item = item?; if !src.join(item.file_name()).as_path().exists() { let path = item.path(); if path.as_path().is_dir() { trace!("[DebugMoveFiles] Old dir removed: {}", path.display()); remove_dir_all(&path)?; } else { trace!("[DebugMoveFiles] Old file removed: {}", path.display()); remove_file(&path)?; } } } for item in read_dir(src)? { let item = item?; let from = item.path().to_path_buf(); let to = dst.join(item.file_name()); move_files(&from, &to)?; } remove_dir_all(src)?; } else { move_one_file(src, dst)?; } Ok(()) }; inner().with_context(|_| format!("failed: move_files({:?}, {:?})", src, dst))?; Ok(()) } /// Copy file or directory `src` to `dst` recursively pub fn copy_recursively(src: &Path, dst: &Path) -> Result<()> { let inner = || -> Result<()> { if src.is_dir() { if !dst.is_dir() { create_dir(&dst)?; } for item in read_dir(src)? { let item = item?; let from = item.path().to_path_buf(); let to = dst.join(item.file_name()); copy_recursively(&from, &to)?; } } else { copy_file(src, dst)?; } Ok(()) }; inner().with_context(|_| format!("failed: copy_recursively({:?}, {:?})", src, dst))?; Ok(()) } /// Move file `old_path` to `new_path`. If contents of files are the same, /// timestamps of the old file are preserved. fn move_one_file(old_path: &Path, new_path: &Path) -> Result<()> { let inner = || -> Result<()> { let is_changed = if new_path.is_file() { let string1 = file_to_string(old_path)?; let string2 = file_to_string(new_path)?; string1 != string2 } else { true }; if is_changed { if new_path.exists() { remove_file(&new_path)?; } rename_file(&old_path, &new_path)?; trace!("[DebugMoveFiles] File changed: {}", new_path.display()); } else { remove_file(&old_path)?; trace!("[DebugMoveFiles] File not changed: {}", new_path.display()); } Ok(()) }; inner().with_context(|_| format!("failed: move_one_file({:?}, {:?})", old_path, new_path))?; Ok(()) } /// A wrapper over a buffered `std::fs::File` containing this file's path. pub struct File<F> { file: F, path: PathBuf, } /// A wrapper over `std::fs::File::open` with better error reporting. pub fn open_file<P: AsRef<Path>>(path: P) -> Result<File<BufReader<fs::File>>> { let file = fs::File::open(path.as_ref()) .with_context(|_| format!("Failed to open file for reading: {:?}", path.as_ref()))?; Ok(File { file: BufReader::new(file), path: path.as_ref().to_path_buf(), }) } /// Returns content of the file `path` as a string. pub fn file_to_string<P: AsRef<Path>>(path: P) -> Result<String> { let mut f = open_file(path)?; f.read_all() } /// A wrapper over `std::fs::File::create` with better error reporting. pub fn create_file<P: AsRef<Path>>(path: P) -> Result<File<BufWriter<fs::File>>> { let file = fs::File::create(path.as_ref()) .with_context(|_| format!("Failed to create file: {:?}", path.as_ref()))?; Ok(File { file: BufWriter::new(file), path: path.as_ref().to_path_buf(), }) } pub fn create_file_for_append<P: AsRef<Path>>(path: P) -> Result<File<BufWriter<fs::File>>> { let file = fs::OpenOptions::new() .append(true) .open(path.as_ref()) .with_context(|_| format!("Failed to open file: {:?}", path.as_ref()))?; Ok(File { file: BufWriter::new(file), path: path.as_ref().to_path_buf(), }) } impl<F> File<F> { pub fn path(&self) -> &Path { &self.path } /// Returns underlying `std::fs::File` pub fn into_inner(self) -> F { self.file } } impl<F: Read> File<F> { /// Read content of the file to a string pub fn read_all(&mut self) -> Result<String> { let mut r = String::new(); self.file .read_to_string(&mut r) .with_context(|_| format!("Failed to read from file: {:?}", self.path))?; Ok(r) } } impl<F: BufRead> File<F> { pub fn lines(self) -> Lines<F> where F: Sized, { self.file.lines() } } impl<F: Write> Write for File<F> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.file.write(buf).map_err(|err| { io::Error::new( io::ErrorKind::Other, format!("Failed to write to file: {:?}: {}", self.path, err), ) }) } fn flush(&mut self) -> io::Result<()> { self.file.flush().map_err(|err| { io::Error::new( io::ErrorKind::Other, format!("Failed to flush file: {:?}: {}", self.path, err), ) }) } } /// Deserialize value from JSON file `path`. pub fn load_json<P: AsRef<Path>, T: serde::de::DeserializeOwned>(path: P) -> Result<T> { let file = open_file(path.as_ref())?; Ok(::serde_json::from_reader(file.into_inner()) .with_context(|_| format!("failed to parse file as JSON: {}", path.as_ref().display()))?) } /// Serialize `value` into JSON file `path`. pub fn save_json<P: AsRef<Path>, T: ::serde::Serialize>( path: P, value: &T, backup_path: Option<&Path>, ) -> Result<()> { let tmp_path = { let mut buf = path.as_ref().to_path_buf(); let tmp_file_name = format!("{}.new", os_str_to_str(&buf.file_name().unwrap())?); buf.set_file_name(tmp_file_name); buf }; { let file = create_file(&tmp_path)?; ::serde_json::to_writer(&mut file.into_inner(), value).with_context(|_| { format!( "failed to serialize to JSON file: {}", path.as_ref().display() ) })?; } if path.as_ref().exists() { if let Some(backup_path) = backup_path { rename_file(path.as_ref(), backup_path)?; } else { remove_file(path.as_ref())?; } } rename_file(&tmp_path, path.as_ref())?; Ok(()) } /// Deserialize value from binary file `path`. pub fn load_bincode<P: AsRef<Path>, T: serde::de::DeserializeOwned>(path: P) -> Result<T> { let mut file = open_file(path.as_ref())?.into_inner(); Ok(bincode::deserialize_from(&mut file) .with_context(|_| format!("load_bincode failed: {}", path.as_ref().display()))?) } /// Serialize `value` into binary file `path`. pub fn save_bincode<P: AsRef<Path>, T: ::serde::Serialize>(path: P, value: &T) -> Result<()> { let mut file = create_file(path.as_ref())?.into_inner(); bincode::serialize_into(&mut file, value) .with_context(|_| format!("save_bincode failed: {}", path.as_ref().display()))?; Ok(()) } /// Load data from a TOML file pub fn load_toml_table<P: AsRef<Path>>(path: P) -> Result<toml::value::Table> { let data = file_to_string(path.as_ref())?; let value = data .parse::<toml::Value>() .with_context(|_| format!("failed to parse TOML file: {}", path.as_ref().display()))?; if let toml::value::Value::Table(table) = value { Ok(table) } else { bail!("TOML is not a table"); } } pub fn crate_version(path: impl AsRef<Path>) -> Result<String> { let cargo_toml_path = path.as_ref().join("Cargo.toml"); let table = load_toml_table(cargo_toml_path)?; let package = table .get("package") .ok_or_else(|| err_msg("Cargo.toml doesn't contain package field"))?; let package = package .as_table() .ok_or_else(|| err_msg("invalid Cargo.toml: package is not a table"))?; let version = package .get("version") .ok_or_else(|| err_msg("Cargo.toml doesn't contain package.version field"))?; let version = version .as_str() .ok_or_else(|| err_msg("invalid Cargo.toml: package.version is not a string"))?; Ok(version.into()) } /// Save `data` to a TOML file pub fn save_toml_table<P: AsRef<Path>>(path: P, data: &toml::Value) -> Result<()> { let mut file = create_file(path.as_ref())?; write!(file, "{}", data) .with_context(|_| format!("failed to write to TOML file: {}", path.as_ref().display()))?; Ok(()) } /// A wrapper over `std::fs::create_dir` with better error reporting pub fn create_dir<P: AsRef<Path>>(path: P) -> Result<()> { fs::create_dir(path.as_ref()) .with_context(|_| format!("Failed to create dir: {:?}", path.as_ref()))?; Ok(()) } /// A wrapper over `std::fs::create_dir_all` with better error reporting pub fn create_dir_all<P: AsRef<Path>>(path: P) -> Result<()> { fs::create_dir_all(path.as_ref()).with_context(|_| { format!( "Failed to create dirs (with parent components): {:?}", path.as_ref() ) })?; Ok(()) } /// A wrapper over `std::fs::remove_dir` with better error reporting pub fn remove_dir<P: AsRef<Path>>(path: P) -> Result<()> { fs::remove_dir(path.as_ref()) .with_context(|_| format!("Failed to remove dir: {:?}", path.as_ref()))?; Ok(()) } /// A wrapper over `std::fs::remove_dir_all` with better error reporting pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> Result<()> { fs::remove_dir_all(path.as_ref()) .with_context(|_| format!("Failed to remove dir (recursively): {:?}", path.as_ref()))?; Ok(()) } /// A wrapper over `std::fs::remove_file` with better error reporting pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()> { fs::remove_file(path.as_ref()) .with_context(|_| format!("Failed to remove file: {:?}", path.as_ref()))?; Ok(()) } /// A wrapper over `std::fs::rename` with better error reporting pub fn rename_file<P: AsRef<Path>, P2: AsRef<Path>>(path1: P, path2: P2) -> Result<()> { fs::rename(path1.as_ref(), path2.as_ref()).with_context(|_| { format!( "Failed to rename file from {:?} to {:?}", path1.as_ref(), path2.as_ref() ) })?; Ok(()) } /// A wrapper over `std::fs::copy` with better error reporting pub fn copy_file<P: AsRef<Path>, P2: AsRef<Path>>(path1: P, path2: P2) -> Result<()> { fs::copy(path1.as_ref(), path2.as_ref()) .map(|_| ()) .with_context(|_| { format!( "Failed to copy file from {:?} to {:?}", path1.as_ref(), path2.as_ref() ) })?; Ok(()) } /// A wrapper over `std::fs::DirEntry` iterator with better error reporting pub struct ReadDir { read_dir: fs::ReadDir, path: PathBuf, } /// A wrapper over `std::fs::read_dir` with better error reporting pub fn read_dir<P: AsRef<Path>>(path: P) -> Result<ReadDir> { Ok(ReadDir { read_dir: fs::read_dir(path.as_ref()) .with_context(|_| format!("Failed to read dir: {:?}", path.as_ref()))?, path: path.as_ref().to_path_buf(), }) } impl Iterator for ReadDir { type Item = Result<fs::DirEntry>; fn next(&mut self) -> Option<Result<fs::DirEntry>> { self.read_dir.next().map(|value| { Ok(value.with_context(|_| format!("Failed to read dir (in item): {:?}", self.path))?) }) } } /// Canonicalize `path`. Similar to `std::fs::canonicalize`, but /// `\\?\` prefix is removed. Windows implementation of `std::fs::canonicalize` /// adds this prefix, but many tools don't process it correctly, including /// CMake and compilers. pub fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf> { Ok(dunce::canonicalize(path.as_ref()) .with_context(|_| format!("failed to canonicalize {}", path.as_ref().display()))?) } /// A wrapper over `Path::to_str` with better error reporting pub fn path_to_str(path: &Path) -> Result<&str> { path.to_str() .ok_or_else(|| err_msg(format!("Path is not valid unicode: {}", path.display()))) } /// A wrapper over `OsStr::to_str` with better error reporting pub fn os_str_to_str(os_str: &OsStr) -> Result<&str> { os_str.to_str().ok_or_else(|| { err_msg(format!( "String is not valid unicode: {}", os_str.to_string_lossy() )) }) } /// A wrapper over `OsString::into_string` with better error reporting pub fn os_string_into_string(s: OsString) -> Result<String> { s.into_string().map_err(|s| { err_msg(format!( "String is not valid unicode: {}", s.to_string_lossy() )) }) } /// Returns current absolute path of `relative_path`. /// `relative_path` is relative to the repository root. pub fn repo_dir_path(relative_path: &str) -> Result<PathBuf> { let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let parent = path .parent() .ok_or_else(|| err_msg("failed to get parent directory"))?; let result = parent.join(relative_path); if !result.exists() { bail!("detected path does not exist: {}", result.display()); } Ok(result) } pub fn diff_paths(path: &Path, base: &Path) -> Result<PathBuf> { pathdiff::diff_paths(path, base) .ok_or_else(|| format_err!("failed to get relative path to {:?} from {:?}", path, base)) }
use crate::properties::WithRegionCore; use crate::{ChromName, ChromSet, ChromSetHandle}; pub use hts::vcf::VcfFile; use hts::vcf::{VcfReader, VcfRecord as Vcf}; use std::rc::Rc; #[derive(Clone)] pub struct VcfRecord<'a, C: ChromName> { chrom_name: C, record: Rc<Vcf<'a>>, } impl<'a, C: ChromName + 'a> VcfRecord<'a, C> { pub fn iter_of<S: ChromSet<RefType = C>>( file: &'a VcfFile, mut handle: S::Handle, ) -> impl Iterator<Item = VcfRecord<'a, C>> { let iter = file.vcf_iter(); iter.map(move |record| VcfRecord { chrom_name: handle.query_or_insert(record.chrom_name().unwrap()), record: Rc::new(record), }) } } impl<'a, C: ChromName> WithRegionCore<C> for VcfRecord<'a, C> { fn begin(&self) -> u32 { self.record.begin() as u32 - 1 } fn end(&self) -> u32 { self.record.end().unwrap_or_else(|| self.record.begin()) as u32 - 1 } fn chrom(&self) -> &C { &self.chrom_name } }
use chrono::{DateTime, Duration, Utc}; use rand::{self, seq::SliceRandom, Rng}; use std::cell::RefCell; use std::cmp; use std::env::args; use std::fmt::{self, Display}; use std::fs; use std::io::{self, prelude::*}; use std::str; use std::thread; use std::time; use std::usize; fn main() -> io::Result<()> { let args: Vec<String> = args().collect(); let words = read_words()?; let mut rng = rand::thread_rng(); let num_plants_arg = args.get(1).expect("First argument must be a valid whole number"); let num_plants = usize::from_str_radix(num_plants_arg, 10).expect("First argument must be a valid whole number"); let mut plants: Vec<Plant> = words .as_slice() .choose_multiple(&mut rng, num_plants) .map(|word| plant_from_word(&mut rng, word)) .collect(); let breeder = RandomBreeder::new(rand::thread_rng()); let grower = RandomGrower::new(rand::thread_rng()); while plants.len() > 1 { let now = Utc::now(); println!("{now:-^width$}", now = format!("{}", now), width = 70); for plant in plants.iter() { print!("{}", plant.expression); } println!(); let new_plants = rng.gen_range(0, num_plants / 2); for _ in 0..new_plants { let new_plant = if *[true, false].choose(&mut rng).unwrap() { let parents: Vec<&Plant> = plants.as_slice().choose_multiple(&mut rng, 2).collect(); breeder.breed(parents[0], parents[1]) } else { let mut children = grower.grow(plants.as_slice().choose(&mut rng).unwrap()); let child_idx = rng.gen_range(0, children.len()); children.remove(child_idx) }; plants.push(new_plant); } plants.retain(|plant| !plant.is_dead(&now)); thread::sleep(time::Duration::from_millis(500)); } Ok(()) } fn read_words() -> io::Result<Vec<String>> { let mut file = fs::File::open("/usr/share/dict/usa")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents.split("\n").map(|s| s.to_owned()).collect()) } fn plant_from_word<R: Rng>(rng: &mut R, word: &str) -> Plant { let dna = Dna(word.to_owned()); let expiration = random_date_after(rng, &Utc::now()); let expression = select_expression(rng, &dna); Plant::new(dna, expiration, expression) } struct Dna(String); impl Dna { fn combine(&self, other: &Self) -> Self { Dna(self.0.clone() + &other.0) } } impl Display for Dna { fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result { write!(fmtr, "{}", self.0) } } struct Plant { dna: Dna, expression: String, expiration: DateTime<Utc>, } impl Plant { fn new(dna: Dna, expiration: DateTime<Utc>, expression: String) -> Self { Plant { dna, expiration, expression, } } fn is_dead(&self, time: &DateTime<Utc>) -> bool { self.expiration <= *time } } impl Display for Plant { fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result { write!( fmtr, "<Plant phe={phe}, exp={exp}, dna={dna}>", dna = self.dna, phe = self.expression, exp = self.expiration ) } } trait Grower<T> { fn grow(&self, a: &T) -> Vec<T>; } struct RandomGrower<R> where R: Rng, { rng: RefCell<R>, } impl<R: Rng> RandomGrower<R> { fn new(rng: R) -> Self { Self { rng: RefCell::new(rng), } } } impl<R: Rng> Grower<Plant> for RandomGrower<R> { fn grow(&self, a: &Plant) -> Vec<Plant> { let mut rng = self.rng.borrow_mut(); (0..4) .map(|_| plant_from_word(&mut *rng, &*a.dna.0)) .collect() } } trait Breeder<T> { fn breed(&self, a: &T, b: &T) -> T; } struct RandomBreeder<R> where R: Rng, { rng: RefCell<R>, } impl<R: Rng> RandomBreeder<R> { fn new(rng: R) -> Self { Self { rng: RefCell::new(rng), } } } impl<R: Rng> Breeder<Plant> for RandomBreeder<R> { fn breed(&self, a: &Plant, b: &Plant) -> Plant { let dna = a.dna.combine(&b.dna); let mut rng = self.rng.borrow_mut(); let expression = select_expression(&mut *rng, &dna); let expiration = random_date_after(&mut *rng, cmp::min(&a.expiration, &b.expiration)); Plant::new(dna, expiration, expression) } } fn random_date_after<R: Rng>(rng: &mut R, dt: &DateTime<Utc>) -> DateTime<Utc> { let offset = rng.gen_range(1, 5000); let duration = Duration::milliseconds(offset); *dt + duration } fn select_expression<R: Rng>(rng: &mut R, dna: &Dna) -> String { let c = dna.0.as_bytes().choose(rng).unwrap(); String::from_utf8(vec![*c]).unwrap() }
use self::Rotation::*; use failure::Error; use rand::distributions::{IndependentSample, Normal}; use rand::{self, Rng}; use std::fmt; use std::fmt::Formatter; use std::str::FromStr; #[derive(Clone, Copy, Debug, PartialEq)] pub struct Point { pub x: u32, pub y: u32, } impl Point { pub fn new(x: u32, y: u32) -> Point { Point { x, y } } } #[derive(Clone, Copy, Debug, PartialEq, Serialize)] pub struct Rectangle { pub width: u32, pub height: u32, } impl Rectangle { fn split(self, sp: Cut) -> (Rectangle, Rectangle) { let Rectangle { width: w, height: h, .. } = self; match sp { Cut::Horizontal(y) => (Rectangle::new(w, h - y), Rectangle::new(w, y)), Cut::Vertical(x) => (Rectangle::new(w - x, h), Rectangle::new(x, h)), } } pub fn gen_with_area(area: u64) -> Rectangle { let divisors = (1..=(area as f64).sqrt() as u64) .into_iter() .filter(|i| area % i == 0) .collect::<Vec<u64>>(); let mut rng = rand::thread_rng(); let n = divisors.len() as f64; let normal = Normal::new(n / 2., n / 7.); let i = normal.ind_sample(&mut rng).max(0.).min(n - 1.) as usize; let (width, height) = if rng.gen() { let width = divisors[i]; (width, area / width) } else { let height = divisors[i]; (area / height, height) }; let width = width as u32; let height = height as u32; Rectangle { width, height } } pub fn simple_rsplit(self) -> (Rectangle, Rectangle) { let mut rng = rand::thread_rng(); let cut = match (self.width, self.height) { (1, 1) => panic!("{:?} cannot be split", self), (1, h) if h > 1 => { let y = rng.gen_range(1, h); Cut::Horizontal(y) } (w, 1) if w > 1 => { let x = rng.gen_range(1, w); Cut::Vertical(x) } (w, h) if w > 1 && h > 1 => { if rng.gen_range(0, w + h) < w { let x = rng.gen_range(1, w); Cut::Vertical(x) } else { let y = rng.gen_range(1, h); Cut::Horizontal(y) } } _ => panic!("Unexpected input: {:?}", self), }; self.split(cut) } pub fn area(&self) -> u64 { self.width as u64 * self.height as u64 } pub fn new(width: u32, height: u32) -> Rectangle { Rectangle { width, height } } } enum Cut { Horizontal(u32), Vertical(u32), } impl fmt::Display for Rectangle { //noinspection RsTypeCheck fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{w} {h}", w = self.width, h = self.height) } } impl FromStr for Rectangle { type Err = Error; fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { let result = match s.split_whitespace().collect::<Vec<&str>>().as_slice() { [width, height] => Rectangle::new(width.parse()?, height.parse()?), _ => bail!("Invalid format: {}", s), }; Ok(result) } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum Rotation { Normal, Rotated, } impl FromStr for Rotation { type Err = Error; fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { let result: Rotation = match s { "yes" => Rotation::Rotated, "no" => Rotation::Normal, _ => bail!("Unexpected token: {}", s), }; Ok(result) } } #[derive(Clone, Copy, Debug, PartialEq)] pub struct Placement { pub rectangle: Rectangle, pub rotation: Rotation, pub bottom_left: Point, pub top_right: Point, } impl Placement { pub fn new(r: Rectangle, rotation: Rotation, bottom_left: Point) -> Placement { let (width, height) = match rotation { Normal => (r.width, r.height), Rotated => (r.height, r.width), }; let x_max = bottom_left.x + width - 1; let y_max = bottom_left.y + height - 1; let top_right = Point::new(x_max, y_max); Placement { rectangle: r, rotation, bottom_left, top_right, } } pub fn overlaps(&self, rhs: &Placement) -> bool { rhs.bottom_left.y <= self.top_right.y && rhs.bottom_left.x <= self.top_right.x && self.bottom_left.y <= rhs.top_right.y && self.bottom_left.x <= rhs.top_right.x } } #[cfg(test)] mod test { use super::*; #[test] fn overlap_detection() { let p1 = Placement::new(Rectangle::new(5, 5), Rotation::Normal, Point::new(0, 0)); let p2 = Placement::new(Rectangle::new(5, 5), Rotation::Normal, Point::new(3, 3)); assert!(p1.overlaps(&p2)) } }
extern crate futures; extern crate stream_combinators; extern crate tokio; extern crate tokio_stdin; use futures::stream::{once, Stream}; use stream_combinators::FilterFoldStream; use tokio_stdin::spawn_stdin_stream_unbounded; fn main() { // Print stdin line-by-line let prog = spawn_stdin_stream_unbounded() // Include an extra newline in case the input is missing a trailing newline // Note: this will print a spurious blank line in the case the input has // a trailing newline; see `examples/fancier_stdin_into_lines.rs` // for a way to prevent that situation, if it matters. .chain(once(Ok('\n' as u8))) // Accumulate bytes into lines .filter_fold(vec![], |mut buf, byte| { if byte == ('\n' as u8) { let s = String::from_utf8(buf).unwrap(); Ok((vec![], Some(s))) } else { buf.push(byte); Ok((buf, None)) } }).for_each(|line| { println!("{}", line); Ok(()) }); tokio::run(prog) }
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // https://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Interface to the random number generator of the operating system. use std::fmt; use rand_core::{CryptoRng, RngCore, Error, impls}; /// A random number generator that retrieves randomness straight from the /// operating system. /// /// This is the preferred external source of entropy for most applications. /// Commonly it is used to initialize a user-space RNG, which can then be used /// to generate random values with much less overhead than `OsRng`. /// /// You may prefer to use [`EntropyRng`] instead of `OsRng`. It is unlikely, but /// not entirely theoretical, for `OsRng` to fail. In such cases [`EntropyRng`] /// falls back on a good alternative entropy source. /// /// `OsRng::new()` is guaranteed to be very cheap (after the first successful /// call), and will never consume more than one file handle per process. /// /// # Platform sources /// /// | OS | interface /// |------------------|--------------------------------------------------------- /// | Linux, Android | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after reading from `/dev/random` once /// | Windows | [`RtlGenRandom`][3] /// | macOS, iOS | [`SecRandomCopyBytes`][4] /// | FreeBSD | [`kern.arandom`][5] /// | OpenBSD, Bitrig | [`getentropy`][6] /// | NetBSD | [`/dev/urandom`][7] after reading from `/dev/random` once /// | Dragonfly BSD | [`/dev/random`][8] /// | Solaris, illumos | [`getrandom`][9] system call if available, otherwise [`/dev/random`][10] /// | Fuchsia OS | [`cprng_draw`][11] /// | Redox | [`rand:`][12] /// | CloudABI | [`random_get`][13] /// | Haiku | `/dev/random` (identical to `/dev/urandom`) /// | Web browsers | [`Crypto.getRandomValues`][14] (see [Support for WebAssembly and ams.js][14]) /// | Node.js | [`crypto.randomBytes`][15] (see [Support for WebAssembly and ams.js][16]) /// /// Rand doesn't have a blanket implementation for all Unix-like operating /// systems that reads from `/dev/urandom`. This ensures all supported operating /// systems are using the recommended interface and respect maximum buffer /// sizes. /// /// ## Support for WebAssembly and ams.js /// /// The three Emscripten targets `asmjs-unknown-emscripten`, /// `wasm32-unknown-emscripten` and `wasm32-experimental-emscripten` use /// Emscripten's emulation of `/dev/random` on web browsers and Node.js. /// Unfortunately it falls back to the insecure `Math.random()` if a browser /// doesn't support [`Crypto.getRandomValues`][12]. /// /// The bare Wasm target `wasm32-unknown-unknown` tries to call the javascript /// methods directly, using `stdweb` in combination with `cargo-web`. /// `wasm-bindgen` is not yet supported. /// /// ## Early boot /// /// It is possible that early in the boot process the OS hasn't had enough time /// yet to collect entropy to securely seed its RNG, especially on virtual /// machines. /// /// Some operating systems always block the thread until the RNG is securely /// seeded. This can take anywhere from a few seconds to more than a minute. /// Others make a best effort to use a seed from before the shutdown and don't /// document much. /// /// A few, Linux, NetBSD and Solaris, offer a choice between blocking, and /// getting an error. With `try_fill_bytes` we choose to get the error /// ([`ErrorKind::NotReady`]), while the other methods use a blocking interface. /// /// On Linux (when the `genrandom` system call is not available) and on NetBSD /// reading from `/dev/urandom` never blocks, even when the OS hasn't collected /// enough entropy yet. As a countermeasure we try to do a single read from /// `/dev/random` until we know the OS RNG is initialized (and store this in a /// global static). /// /// # Panics /// /// `OsRng` is extremely unlikely to fail if `OsRng::new()`, and one read from /// it, where succesfull. But in case it does fail, only [`try_fill_bytes`] is /// able to report the cause. Depending on the error the other [`RngCore`] /// methods will retry several times, and panic in case the error remains. /// /// [`EntropyRng`]: struct.EntropyRng.html /// [`RngCore`]: ../trait.RngCore.html /// [`try_fill_bytes`]: ../trait.RngCore.html#method.tymethod.try_fill_bytes /// [`ErrorKind::NotReady`]: ../enum.ErrorKind.html#variant.NotReady /// /// [1]: http://man7.org/linux/man-pages/man2/getrandom.2.html /// [2]: http://man7.org/linux/man-pages/man4/urandom.4.html /// [3]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx /// [4]: https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc /// [5]: https://www.freebsd.org/cgi/man.cgi?query=random&sektion=4 /// [6]: https://man.openbsd.org/getentropy.2 /// [7]: http://netbsd.gw.com/cgi-bin/man-cgi?random+4+NetBSD-current /// [8]: https://leaf.dragonflybsd.org/cgi/web-man?command=random&section=4 /// [9]: https://docs.oracle.com/cd/E88353_01/html/E37841/getrandom-2.html /// [10]: https://docs.oracle.com/cd/E86824_01/html/E54777/random-7d.html /// [11]: https://fuchsia.googlesource.com/zircon/+/HEAD/docs/syscalls/cprng_draw.md /// [12]: https://github.com/redox-os/randd/blob/master/src/main.rs /// [13]: https://github.com/NuxiNL/cloudabi/blob/v0.20/cloudabi.txt#L1826 /// [14]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues /// [15]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback /// [16]: #support-for-webassembly-and-amsjs #[derive(Clone)] pub struct OsRng(imp::OsRng); impl fmt::Debug for OsRng { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } impl OsRng { /// Create a new `OsRng`. pub fn new() -> Result<OsRng, Error> { imp::OsRng::new().map(OsRng) } } impl CryptoRng for OsRng {} impl RngCore for OsRng { fn next_u32(&mut self) -> u32 { impls::next_u32_via_fill(self) } fn next_u64(&mut self) -> u64 { impls::next_u64_via_fill(self) } fn fill_bytes(&mut self, dest: &mut [u8]) { use std::{time, thread}; // We cannot return Err(..), so we try to handle before panicking. const MAX_RETRY_PERIOD: u32 = 10; // max 10s const WAIT_DUR_MS: u32 = 100; // retry every 100ms let wait_dur = time::Duration::from_millis(WAIT_DUR_MS as u64); const RETRY_LIMIT: u32 = (MAX_RETRY_PERIOD * 1000) / WAIT_DUR_MS; const TRANSIENT_RETRIES: u32 = 8; let mut err_count = 0; let mut error_logged = false; // Maybe block until the OS RNG is initialized let mut read = 0; if let Ok(n) = self.0.test_initialized(dest, true) { read = n }; let dest = &mut dest[read..]; loop { if let Err(e) = self.try_fill_bytes(dest) { if err_count >= RETRY_LIMIT { error!("OsRng failed too many times; last error: {}", e); panic!("OsRng failed too many times; last error: {}", e); } if e.kind.should_wait() { if !error_logged { warn!("OsRng failed; waiting up to {}s and retrying. Error: {}", MAX_RETRY_PERIOD, e); error_logged = true; } err_count += 1; thread::sleep(wait_dur); continue; } else if e.kind.should_retry() { if !error_logged { warn!("OsRng failed; retrying up to {} times. Error: {}", TRANSIENT_RETRIES, e); error_logged = true; } err_count += (RETRY_LIMIT + TRANSIENT_RETRIES - 1) / TRANSIENT_RETRIES; // round up continue; } else { error!("OsRng failed: {}", e); panic!("OsRng fatal error: {}", e); } } break; } } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { // Some systems do not support reading 0 random bytes. // (And why waste a system call?) if dest.len() == 0 { return Ok(()); } let read = self.0.test_initialized(dest, false)?; let dest = &mut dest[read..]; let max = self.0.max_chunk_size(); if dest.len() <= max { trace!("OsRng: reading {} bytes via {}", dest.len(), self.0.method_str()); } else { trace!("OsRng: reading {} bytes via {} in {} chunks of {} bytes", dest.len(), self.0.method_str(), (dest.len() + max) / max, max); } for slice in dest.chunks_mut(max) { self.0.fill_chunk(slice)?; } Ok(()) } } trait OsRngImpl where Self: Sized { // Create a new `OsRng` platform interface. fn new() -> Result<Self, Error>; // Fill a chunk with random bytes. fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error>; // Test whether the OS RNG is initialized. This method may not be possible // to support cheaply (or at all) on all operating systems. // // If `blocking` is set, this will cause the OS the block execution until // its RNG is initialized. // // Random values that are read while this are stored in `dest`, the amount // of read bytes is returned. fn test_initialized(&mut self, _dest: &mut [u8], _blocking: bool) -> Result<usize, Error> { Ok(0) } // Maximum chunk size supported. fn max_chunk_size(&self) -> usize { ::core::usize::MAX } // Name of the OS interface (used for logging). fn method_str(&self) -> &'static str; } // Helper functions to read from a random device such as `/dev/urandom`. // // All instances use a single internal file handle, to prevent possible // exhaustion of file descriptors. #[cfg(any(target_os = "linux", target_os = "android", target_os = "netbsd", target_os = "dragonfly", target_os = "solaris", target_os = "redox", target_os = "haiku", target_os = "emscripten"))] mod random_device { use {Error, ErrorKind}; use std::fs::File; use std::io; use std::io::Read; use std::sync::{Once, Mutex, ONCE_INIT}; // TODO: remove outer Option when `Mutex::new(None)` is a constant expression static mut READ_RNG_FILE: Option<Mutex<Option<File>>> = None; static READ_RNG_ONCE: Once = ONCE_INIT; #[allow(unused)] pub fn open<F>(path: &'static str, open_fn: F) -> Result<(), Error> where F: Fn(&'static str) -> Result<File, io::Error> { READ_RNG_ONCE.call_once(|| { unsafe { READ_RNG_FILE = Some(Mutex::new(None)) } }); // We try opening the file outside the `call_once` fn because we cannot // clone the error, thus we must retry on failure. let mutex = unsafe { READ_RNG_FILE.as_ref().unwrap() }; let mut guard = mutex.lock().unwrap(); if (*guard).is_none() { info!("OsRng: opening random device {}", path); let file = open_fn(path).map_err(map_err)?; *guard = Some(file); }; Ok(()) } pub fn read(dest: &mut [u8]) -> Result<(), Error> { // We expect this function only to be used after `random_device::open` // was succesful. Therefore we can assume that our memory was set with a // valid object. let mutex = unsafe { READ_RNG_FILE.as_ref().unwrap() }; let mut guard = mutex.lock().unwrap(); let file = (*guard).as_mut().unwrap(); // Use `std::io::read_exact`, which retries on `ErrorKind::Interrupted`. file.read_exact(dest).map_err(|err| { Error::with_cause(ErrorKind::Unavailable, "error reading random device", err) }) } pub fn map_err(err: io::Error) -> Error { match err.kind() { io::ErrorKind::Interrupted => Error::new(ErrorKind::Transient, "interrupted"), io::ErrorKind::WouldBlock => Error::with_cause(ErrorKind::NotReady, "OS RNG not yet seeded", err), _ => Error::with_cause(ErrorKind::Unavailable, "error while opening random device", err) } } } #[cfg(any(target_os = "linux", target_os = "android"))] mod imp { extern crate libc; use {Error, ErrorKind}; use super::random_device; use super::OsRngImpl; use std::io; use std::io::Read; use std::fs::{File, OpenOptions}; use std::os::unix::fs::OpenOptionsExt; use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use std::sync::{Once, ONCE_INIT}; #[derive(Clone, Debug)] pub struct OsRng { method: OsRngMethod, initialized: bool, } #[derive(Clone, Debug)] enum OsRngMethod { GetRandom, RandomDevice, } impl OsRngImpl for OsRng { fn new() -> Result<OsRng, Error> { if is_getrandom_available() { return Ok(OsRng { method: OsRngMethod::GetRandom, initialized: false }); } random_device::open("/dev/urandom", &|p| File::open(p))?; Ok(OsRng { method: OsRngMethod::RandomDevice, initialized: false }) } fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { match self.method { OsRngMethod::GetRandom => getrandom_try_fill(dest, false), OsRngMethod::RandomDevice => random_device::read(dest), } } fn test_initialized(&mut self, dest: &mut [u8], blocking: bool) -> Result<usize, Error> { static OS_RNG_INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; if !self.initialized { self.initialized = OS_RNG_INITIALIZED.load(Ordering::Relaxed); } if self.initialized { return Ok(0); } let result = match self.method { OsRngMethod::GetRandom => { getrandom_try_fill(dest, blocking)?; Ok(dest.len()) } OsRngMethod::RandomDevice => { info!("OsRng: testing random device /dev/random"); let mut file = OpenOptions::new() .read(true) .custom_flags(if blocking { 0 } else { libc::O_NONBLOCK }) .open("/dev/random") .map_err(random_device::map_err)?; file.read(&mut dest[..1]).map_err(random_device::map_err)?; Ok(1) } }; OS_RNG_INITIALIZED.store(true, Ordering::Relaxed); self.initialized = true; result } fn method_str(&self) -> &'static str { match self.method { OsRngMethod::GetRandom => "getrandom", OsRngMethod::RandomDevice => "/dev/urandom", } } } #[cfg(target_arch = "x86_64")] const NR_GETRANDOM: libc::c_long = 318; #[cfg(target_arch = "x86")] const NR_GETRANDOM: libc::c_long = 355; #[cfg(target_arch = "arm")] const NR_GETRANDOM: libc::c_long = 384; #[cfg(target_arch = "aarch64")] const NR_GETRANDOM: libc::c_long = 278; #[cfg(target_arch = "s390x")] const NR_GETRANDOM: libc::c_long = 349; #[cfg(target_arch = "powerpc")] const NR_GETRANDOM: libc::c_long = 359; #[cfg(target_arch = "mips")] // old ABI const NR_GETRANDOM: libc::c_long = 4353; #[cfg(target_arch = "mips64")] const NR_GETRANDOM: libc::c_long = 5313; #[cfg(not(any(target_arch = "x86_64", target_arch = "x86", target_arch = "arm", target_arch = "aarch64", target_arch = "s390x", target_arch = "powerpc", target_arch = "mips", target_arch = "mips64")))] const NR_GETRANDOM: libc::c_long = 0; fn getrandom(buf: &mut [u8], blocking: bool) -> libc::c_long { extern "C" { fn syscall(number: libc::c_long, ...) -> libc::c_long; } const GRND_NONBLOCK: libc::c_uint = 0x0001; if NR_GETRANDOM == 0 { return -1 }; unsafe { syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), if blocking { 0 } else { GRND_NONBLOCK }) } } fn getrandom_try_fill(dest: &mut [u8], blocking: bool) -> Result<(), Error> { let mut read = 0; while read < dest.len() { let result = getrandom(&mut dest[read..], blocking); if result == -1 { let err = io::Error::last_os_error(); let kind = err.kind(); if kind == io::ErrorKind::Interrupted { continue; } else if kind == io::ErrorKind::WouldBlock { return Err(Error::with_cause( ErrorKind::NotReady, "getrandom not ready", err, )); } else { return Err(Error::with_cause( ErrorKind::Unavailable, "unexpected getrandom error", err, )); } } else { read += result as usize; } } Ok(()) } fn is_getrandom_available() -> bool { static CHECKER: Once = ONCE_INIT; static AVAILABLE: AtomicBool = ATOMIC_BOOL_INIT; if NR_GETRANDOM == 0 { return false }; CHECKER.call_once(|| { debug!("OsRng: testing getrandom"); let mut buf: [u8; 0] = []; let result = getrandom(&mut buf, false); let available = if result == -1 { let err = io::Error::last_os_error().raw_os_error(); err != Some(libc::ENOSYS) } else { true }; AVAILABLE.store(available, Ordering::Relaxed); info!("OsRng: using {}", if available { "getrandom" } else { "/dev/urandom" }); }); AVAILABLE.load(Ordering::Relaxed) } } #[cfg(target_os = "netbsd")] mod imp { use Error; use super::random_device; use super::OsRngImpl; use std::fs::File; use std::io::Read; use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; #[derive(Clone, Debug)] pub struct OsRng { initialized: bool } impl OsRngImpl for OsRng { fn new() -> Result<OsRng, Error> { random_device::open("/dev/urandom", &|p| File::open(p))?; Ok(OsRng { initialized: false }) } fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { random_device::read(dest) } // Read a single byte from `/dev/random` to determine if the OS RNG is // already seeded. NetBSD always blocks if not yet ready. fn test_initialized(&mut self, dest: &mut [u8], _blocking: bool) -> Result<usize, Error> { static OS_RNG_INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; if !self.initialized { self.initialized = OS_RNG_INITIALIZED.load(Ordering::Relaxed); } if self.initialized { return Ok(0); } info!("OsRng: testing random device /dev/random"); let mut file = File::open("/dev/random").map_err(random_device::map_err)?; file.read(&mut dest[..1]).map_err(random_device::map_err)?; OS_RNG_INITIALIZED.store(true, Ordering::Relaxed); self.initialized = true; Ok(1) } fn method_str(&self) -> &'static str { "/dev/urandom" } } } #[cfg(any(target_os = "dragonfly", target_os = "haiku", target_os = "emscripten"))] mod imp { use Error; use super::random_device; use super::OsRngImpl; use std::fs::File; #[derive(Clone, Debug)] pub struct OsRng(); impl OsRngImpl for OsRng { fn new() -> Result<OsRng, Error> { random_device::open("/dev/random", &|p| File::open(p))?; Ok(OsRng()) } fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { random_device::read(dest) } #[cfg(target_os = "emscripten")] fn max_chunk_size(&self) -> usize { // `Crypto.getRandomValues` documents `dest` should be at most 65536 // bytes. `crypto.randomBytes` documents: "To minimize threadpool // task length variation, partition large randomBytes requests when // doing so as part of fulfilling a client request. 65536 } fn method_str(&self) -> &'static str { "/dev/random" } } } // Read from `/dev/random`, with chunks of limited size (1040 bytes). // `/dev/random` uses the Hash_DRBG with SHA512 algorithm from NIST SP 800-90A. // `/dev/urandom` uses the FIPS 186-2 algorithm, which is considered less // secure. We choose to read from `/dev/random`. // // Since Solaris 11.3 the `getrandom` syscall is available. To make sure we can // compile on both Solaris and on OpenSolaris derivatives, that do not have the // function, we do a direct syscall instead of calling a library function. // // We have no way to differentiate between Solaris, illumos, SmartOS, etc. #[cfg(target_os = "solaris")] mod imp { extern crate libc; use {Error, ErrorKind}; use super::random_device; use super::OsRngImpl; use std::io; use std::io::Read; use std::fs::{File, OpenOptions}; use std::os::unix::fs::OpenOptionsExt; use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; #[derive(Clone, Debug)] pub struct OsRng { method: OsRngMethod, initialized: bool, } #[derive(Clone, Debug)] enum OsRngMethod { GetRandom, RandomDevice, } impl OsRngImpl for OsRng { fn new() -> Result<OsRng, Error> { if is_getrandom_available() { return Ok(OsRng { method: OsRngMethod::GetRandom, initialized: false }); } let open = |p| OpenOptions::new() .read(true) .custom_flags(libc::O_NONBLOCK) .open(p); random_device::open("/dev/random", &open)?; Ok(OsRng { method: OsRngMethod::RandomDevice, initialized: false }) } fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { match self.method { OsRngMethod::GetRandom => getrandom_try_fill(dest, false), OsRngMethod::RandomDevice => random_device::read(dest), } } fn test_initialized(&mut self, dest: &mut [u8], blocking: bool) -> Result<usize, Error> { static OS_RNG_INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; if !self.initialized { self.initialized = OS_RNG_INITIALIZED.load(Ordering::Relaxed); } if self.initialized { return Ok(0); } let chunk_len = ::core::cmp::min(1024, dest.len()); let dest = &mut dest[..chunk_len]; match self.method { OsRngMethod::GetRandom => getrandom_try_fill(dest, blocking)?, OsRngMethod::RandomDevice => { if blocking { info!("OsRng: testing random device /dev/random"); // We already have a non-blocking handle, but now need a // blocking one. Not much choice except opening it twice let mut file = File::open("/dev/random") .map_err(random_device::map_err)?; file.read(dest).map_err(random_device::map_err)?; } else { self.fill_chunk(dest)?; } } }; OS_RNG_INITIALIZED.store(true, Ordering::Relaxed); self.initialized = true; Ok(chunk_len) } fn max_chunk_size(&self) -> usize { // The documentation says 1024 is the maximum for getrandom, but // 1040 for /dev/random. 1024 } fn method_str(&self) -> &'static str { match self.method { OsRngMethod::GetRandom => "getrandom", OsRngMethod::RandomDevice => "/dev/random", } } } fn getrandom(buf: &mut [u8], blocking: bool) -> libc::c_long { extern "C" { fn syscall(number: libc::c_long, ...) -> libc::c_long; } const SYS_GETRANDOM: libc::c_long = 143; const GRND_NONBLOCK: libc::c_uint = 0x0001; const GRND_RANDOM: libc::c_uint = 0x0002; unsafe { syscall(SYS_GETRANDOM, buf.as_mut_ptr(), buf.len(), if blocking { 0 } else { GRND_NONBLOCK } | GRND_RANDOM) } } fn getrandom_try_fill(dest: &mut [u8], blocking: bool) -> Result<(), Error> { let result = getrandom(dest, blocking); if result == -1 || result == 0 { let err = io::Error::last_os_error(); let kind = err.kind(); if kind == io::ErrorKind::WouldBlock { return Err(Error::with_cause( ErrorKind::NotReady, "getrandom not ready", err, )); } else { return Err(Error::with_cause( ErrorKind::Unavailable, "unexpected getrandom error", err, )); } } else if result != dest.len() as i64 { return Err(Error::new(ErrorKind::Unavailable, "unexpected getrandom error")); } Ok(()) } fn is_getrandom_available() -> bool { use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use std::sync::{Once, ONCE_INIT}; static CHECKER: Once = ONCE_INIT; static AVAILABLE: AtomicBool = ATOMIC_BOOL_INIT; CHECKER.call_once(|| { debug!("OsRng: testing getrandom"); let mut buf: [u8; 0] = []; let result = getrandom(&mut buf, false); let available = if result == -1 { let err = io::Error::last_os_error().raw_os_error(); err != Some(libc::ENOSYS) } else { true }; AVAILABLE.store(available, Ordering::Relaxed); info!("OsRng: using {}", if available { "getrandom" } else { "/dev/random" }); }); AVAILABLE.load(Ordering::Relaxed) } } #[cfg(target_os = "cloudabi")] mod imp { extern crate cloudabi; use std::io; use {Error, ErrorKind}; use super::OsRngImpl; #[derive(Clone, Debug)] pub struct OsRng; impl OsRngImpl for OsRng { fn new() -> Result<OsRng, Error> { Ok(OsRng) } fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { let errno = unsafe { cloudabi::random_get(dest) }; if errno == cloudabi::errno::SUCCESS { Ok(()) } else { // Cloudlibc provides its own `strerror` implementation so we // can use `from_raw_os_error` here. Err(Error::with_cause( ErrorKind::Unavailable, "random_get() system call failed", io::Error::from_raw_os_error(errno as i32), )) } } fn method_str(&self) -> &'static str { "cloudabi::random_get" } } } #[cfg(any(target_os = "macos", target_os = "ios"))] mod imp { extern crate libc; use {Error, ErrorKind}; use super::OsRngImpl; use std::io; use self::libc::{c_int, size_t}; #[derive(Clone, Debug)] pub struct OsRng; enum SecRandom {} #[allow(non_upper_case_globals)] const kSecRandomDefault: *const SecRandom = 0 as *const SecRandom; #[link(name = "Security", kind = "framework")] extern { fn SecRandomCopyBytes(rnd: *const SecRandom, count: size_t, bytes: *mut u8) -> c_int; } impl OsRngImpl for OsRng { fn new() -> Result<OsRng, Error> { Ok(OsRng) } fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { let ret = unsafe { SecRandomCopyBytes(kSecRandomDefault, dest.len() as size_t, dest.as_mut_ptr()) }; if ret == -1 { Err(Error::with_cause( ErrorKind::Unavailable, "couldn't generate random bytes", io::Error::last_os_error())) } else { Ok(()) } } fn method_str(&self) -> &'static str { "SecRandomCopyBytes" } } } #[cfg(target_os = "freebsd")] mod imp { extern crate libc; use {Error, ErrorKind}; use super::OsRngImpl; use std::ptr; use std::io; #[derive(Clone, Debug)] pub struct OsRng; impl OsRngImpl for OsRng { fn new() -> Result<OsRng, Error> { Ok(OsRng) } fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { let mib = [libc::CTL_KERN, libc::KERN_ARND]; let mut len = dest.len(); let ret = unsafe { libc::sysctl(mib.as_ptr(), mib.len() as libc::c_uint, dest.as_mut_ptr() as *mut _, &mut len, ptr::null(), 0) }; if ret == -1 || len != dest.len() { return Err(Error::with_cause( ErrorKind::Unavailable, "kern.arandom sysctl failed", io::Error::last_os_error())); } Ok(()) } fn max_chunk_size(&self) -> usize { 256 } fn method_str(&self) -> &'static str { "kern.arandom" } } } #[cfg(any(target_os = "openbsd", target_os = "bitrig"))] mod imp { extern crate libc; use {Error, ErrorKind}; use super::OsRngImpl; use std::io; #[derive(Clone, Debug)] pub struct OsRng; impl OsRngImpl for OsRng { fn new() -> Result<OsRng, Error> { Ok(OsRng) } fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { let ret = unsafe { libc::getentropy(dest.as_mut_ptr() as *mut libc::c_void, dest.len()) }; if ret == -1 { return Err(Error::with_cause( ErrorKind::Unavailable, "getentropy failed", io::Error::last_os_error())); } Ok(()) } fn max_chunk_size(&self) -> usize { 256 } fn method_str(&self) -> &'static str { "getentropy" } } } #[cfg(target_os = "redox")] mod imp { use Error; use super::random_device; use super::OsRngImpl; use std::fs::File; #[derive(Clone, Debug)] pub struct OsRng(); impl OsRngImpl for OsRng { fn new() -> Result<OsRng, Error> { random_device::open("rand:", &|p| File::open(p))?; Ok(OsRng()) } fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { random_device::read(dest) } fn method_str(&self) -> &'static str { "'rand:'" } } } #[cfg(target_os = "fuchsia")] mod imp { extern crate fuchsia_cprng; use Error; use super::OsRngImpl; #[derive(Clone, Debug)] pub struct OsRng; impl OsRngImpl for OsRng { fn new() -> Result<OsRng, Error> { Ok(OsRng) } fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { fuchsia_cprng::cprng_draw(dest); Ok(()) } fn method_str(&self) -> &'static str { "cprng_draw" } } } #[cfg(windows)] mod imp { extern crate winapi; use {Error, ErrorKind}; use super::OsRngImpl; use std::io; use self::winapi::shared::minwindef::ULONG; use self::winapi::um::ntsecapi::RtlGenRandom; use self::winapi::um::winnt::PVOID; #[derive(Clone, Debug)] pub struct OsRng; impl OsRngImpl for OsRng { fn new() -> Result<OsRng, Error> { Ok(OsRng) } fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { let ret = unsafe { RtlGenRandom(dest.as_mut_ptr() as PVOID, dest.len() as ULONG) }; if ret == 0 { return Err(Error::with_cause( ErrorKind::Unavailable, "couldn't generate random bytes", io::Error::last_os_error())); } Ok(()) } fn max_chunk_size(&self) -> usize { <ULONG>::max_value() as usize } fn method_str(&self) -> &'static str { "RtlGenRandom" } } } #[cfg(all(target_arch = "wasm32", not(target_os = "emscripten"), feature = "stdweb"))] mod imp { use std::mem; use stdweb::unstable::TryInto; use stdweb::web::error::Error as WebError; use {Error, ErrorKind}; use super::OsRngImpl; #[derive(Clone, Debug)] enum OsRngMethod { Browser, Node } #[derive(Clone, Debug)] pub struct OsRng(OsRngMethod); impl OsRngImpl for OsRng { fn new() -> Result<OsRng, Error> { let result = js! { try { if ( typeof self === "object" && typeof self.crypto === "object" && typeof self.crypto.getRandomValues === "function" ) { return { success: true, ty: 1 }; } if (typeof require("crypto").randomBytes === "function") { return { success: true, ty: 2 }; } return { success: false, error: new Error("not supported") }; } catch(err) { return { success: false, error: err }; } }; if js!{ return @{ result.as_ref() }.success } == true { let ty = js!{ return @{ result }.ty }; if ty == 1 { Ok(OsRng(OsRngMethod::Browser)) } else if ty == 2 { Ok(OsRng(OsRngMethod::Node)) } else { unreachable!() } } else { let err: WebError = js!{ return @{ result }.error }.try_into().unwrap(); Err(Error::with_cause(ErrorKind::Unavailable, "WASM Error", err)) } } fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { assert_eq!(mem::size_of::<usize>(), 4); let len = dest.len() as u32; let ptr = dest.as_mut_ptr() as i32; let result = match self.0 { OsRngMethod::Browser => js! { try { let array = new Uint8Array(@{ len }); self.crypto.getRandomValues(array); HEAPU8.set(array, @{ ptr }); return { success: true }; } catch(err) { return { success: false, error: err }; } }, OsRngMethod::Node => js! { try { let bytes = require("crypto").randomBytes(@{ len }); HEAPU8.set(new Uint8Array(bytes), @{ ptr }); return { success: true }; } catch(err) { return { success: false, error: err }; } } }; if js!{ return @{ result.as_ref() }.success } == true { Ok(()) } else { let err: WebError = js!{ return @{ result }.error }.try_into().unwrap(); Err(Error::with_cause(ErrorKind::Unexpected, "WASM Error", err)) } } fn max_chunk_size(&self) -> usize { 65536 } fn method_str(&self) -> &'static str { match self.0 { OsRngMethod::Browser => "Crypto.getRandomValues", OsRngMethod::Node => "crypto.randomBytes", } } } } #[cfg(test)] mod test { use RngCore; use OsRng; #[test] fn test_os_rng() { let mut r = OsRng::new().unwrap(); r.next_u32(); r.next_u64(); let mut v1 = [0u8; 1000]; r.fill_bytes(&mut v1); let mut v2 = [0u8; 1000]; r.fill_bytes(&mut v2); let mut n_diff_bits = 0; for i in 0..v1.len() { n_diff_bits += (v1[i] ^ v2[i]).count_ones(); } // Check at least 1 bit per byte differs. p(failure) < 1e-1000 with random input. assert!(n_diff_bits >= v1.len() as u32); } #[test] fn test_os_rng_empty() { let mut r = OsRng::new().unwrap(); let mut empty = [0u8; 0]; r.fill_bytes(&mut empty); } #[test] fn test_os_rng_huge() { let mut r = OsRng::new().unwrap(); let mut huge = [0u8; 100_000]; r.fill_bytes(&mut huge); } #[cfg(not(any(target_arch = "wasm32", target_arch = "asmjs")))] #[test] fn test_os_rng_tasks() { use std::sync::mpsc::channel; use std::thread; let mut txs = vec!(); for _ in 0..20 { let (tx, rx) = channel(); txs.push(tx); thread::spawn(move|| { // wait until all the tasks are ready to go. rx.recv().unwrap(); // deschedule to attempt to interleave things as much // as possible (XXX: is this a good test?) let mut r = OsRng::new().unwrap(); thread::yield_now(); let mut v = [0u8; 1000]; for _ in 0..100 { r.next_u32(); thread::yield_now(); r.next_u64(); thread::yield_now(); r.fill_bytes(&mut v); thread::yield_now(); } }); } // start all the tasks for tx in txs.iter() { tx.send(()).unwrap(); } } }
#[derive(Default)] #[derive(Debug)] #[derive(RustcEncodable)] #[derive(RustcDecodable)] pub struct Config { pub roles: Vec<Role>, pub username: String, pub ssh_key_path: String } #[derive(Default)] #[derive(Debug)] #[derive(RustcEncodable)] #[derive(RustcDecodable)] pub struct Role { pub name: String, pub address: String } impl Config { pub fn new() -> Config { Default::default() } pub fn add_role(&mut self, role: String, address: String) { self.roles.push(Role{ name: role, address: address }); } pub fn is_role_unique(&self, role_name: &str) -> bool { !self.roles.iter().any(|ref role| role.name == role_name) } pub fn address_for_role_name(&self, role_name: &str) -> Option<String> { match self.roles.iter().find(|&r| r.name == role_name) { Some(role) => Some(role.address.clone()), None => None } } pub fn add_username(&mut self, username: String) { self.username = username; } pub fn add_ssh_key(&mut self, ssh_key_path: String) { self.ssh_key_path = ssh_key_path; } pub fn is_valid(&self) -> Result<(), Vec<String>> { let mut is_valid = true; let mut error_messages = vec!(); if self.username.len() == 0 { is_valid = false; error_messages.push("Username must be set".into()); } if self.ssh_key_path.len() == 0 { is_valid = false; error_messages.push("SSH Key path must be set".into()); } if is_valid { return Ok(()) } else { return Err(error_messages) } } }
// Copyright 2016-2018 Austin Bonander <austin.bonander@gmail.com> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Types which can be used to tune the behavior of `BufReader` and `BufWriter`. //! //! Some simple policies are provided for your convenience. You may prefer to create your own //! types and implement the traits for them instead. use super::Buffer; /// Flag for `ReaderPolicy` methods to signal whether or not `BufReader` should read into /// the buffer. /// /// See `do_read!()` for a shorthand. #[derive(Copy, Clone, Debug)] pub struct DoRead(pub bool); /// Shorthand for `return DoRead(bool)` or `return DoRead(true)` (empty invocation) #[macro_export] macro_rules! do_read ( ($val:expr) => ( return $crate::policy::DoRead($val); ); () => ( do_read!(true); ) ); /// Default policy for both `BufReader` and `BufWriter` that reproduces the behaviors of their /// `std::io` counterparts: /// /// * `BufReader`: only reads when the buffer is empty, does not resize or move data. /// * `BufWriter`: only flushes the buffer when there is not enough room for an incoming write. #[derive(Debug, Default)] pub struct StdPolicy; /// Trait that governs `BufReader`'s behavior. pub trait ReaderPolicy { /// Consulted before attempting to read into the buffer. /// /// Return `DoRead(true)` to issue a read into the buffer before reading data out of it, /// or `DoRead(false)` to read from the buffer as it is, even if it's empty. /// `do_read!()` is provided as a shorthand. /// /// If there is no room in the buffer after this method is called, /// the buffer will not be read into (so if the buffer is full but you want more data /// you should call `.make_room()` or reserve more space). If there *is* room, `BufReader` will /// attempt to read into the buffer. If successful (`Ok(x)` where `x > 0` is returned), this /// method will be consulted again for another read attempt. /// /// By default, this implements `std::io::BufReader`'s behavior: only read into the buffer if /// it is empty. /// /// ### Note /// If the read will ignore the buffer entirely (if the buffer is empty and the amount to be /// read matches or exceeds its capacity) or if `BufReader::read_into_buf()` was called to force /// a read into the buffer manually, this method will not be called. fn before_read(&mut self, buffer: &mut Buffer) -> DoRead { DoRead(buffer.len() == 0) } /// Called after bytes are consumed from the buffer. /// /// Supplies the true amount consumed if the amount passed to `BufReader::consume` /// was in excess. /// /// This is a no-op by default. fn after_consume(&mut self, _buffer: &mut Buffer, _amt: usize) {} } /// Behavior of `std::io::BufReader`: the buffer will only be read into if it is empty. impl ReaderPolicy for StdPolicy {} /// A policy for [`BufReader`](::BufReader) which ensures there is at least the given number of /// bytes in the buffer, failing this only if the reader is at EOF. /// /// If the minimum buffer length is greater than the buffer capacity, it will be resized. /// /// ### Example /// ```rust /// use buf_redux::BufReader; /// use buf_redux::policy::MinBuffered; /// use std::io::{BufRead, Cursor}; /// /// let data = (1 .. 16).collect::<Vec<u8>>(); /// /// // normally you should use `BufReader::new()` or give a capacity of several KiB or more /// let mut reader = BufReader::with_capacity(8, Cursor::new(data)) /// // always at least 4 bytes in the buffer (or until the source is empty) /// .set_policy(MinBuffered(4)); // always at least 4 bytes in the buffer /// /// // first buffer fill, same as `std::io::BufReader` /// assert_eq!(reader.fill_buf().unwrap(), &[1, 2, 3, 4, 5, 6, 7, 8]); /// reader.consume(3); /// /// // enough data in the buffer, another read isn't done yet /// assert_eq!(reader.fill_buf().unwrap(), &[4, 5, 6, 7, 8]); /// reader.consume(4); /// /// // `std::io::BufReader` would return `&[8]` /// assert_eq!(reader.fill_buf().unwrap(), &[8, 9, 10, 11, 12, 13, 14, 15]); /// reader.consume(5); /// /// // no data left in the reader /// assert_eq!(reader.fill_buf().unwrap(), &[13, 14, 15]); /// ``` #[derive(Debug)] pub struct MinBuffered(pub usize); impl MinBuffered { /// Set the number of bytes to ensure are in the buffer. pub fn set_min(&mut self, min: usize) { self.0 = min; } } impl ReaderPolicy for MinBuffered { fn before_read(&mut self, buffer: &mut Buffer) -> DoRead { // do nothing if we have enough data if buffer.len() >= self.0 { do_read!(false) } let cap = buffer.capacity(); // if there's enough room but some of it's stuck after the head if buffer.usable_space() < self.0 && buffer.free_space() >= self.0 { buffer.make_room(); } else if cap < self.0 { buffer.reserve(self.0 - cap); } DoRead(true) } } /// Flag for `WriterPolicy` methods to tell `BufWriter` how many bytes to flush to the /// underlying reader. /// /// See `flush_amt!()` for a shorthand. #[derive(Copy, Clone, Debug)] pub struct FlushAmt(pub usize); /// Shorthand for `return FlushAmt(n)` or `return FlushAmt(0)` (empty invocation) #[macro_export] macro_rules! flush_amt ( ($n:expr) => ( return $crate::policy::FlushAmt($n); ); () => ( flush_amt!(0); ) ); /// A trait which tells `BufWriter` when to flush. pub trait WriterPolicy { /// Return `FlushAmt(n > 0)` if the buffer should be flushed before reading into it. /// If the returned amount is 0 or greater than the amount of buffered data, no flush is /// performed. /// /// The buffer is provided, as well as `incoming` which is /// the size of the buffer that will be written to the `BufWriter`. /// /// By default, flushes the buffer if the usable space is smaller than the incoming write. fn before_write(&mut self, buf: &mut Buffer, incoming: usize) -> FlushAmt { FlushAmt(if incoming > buf.usable_space() { buf.len() } else { 0 }) } /// Return `true` if the buffer should be flushed after reading into it. /// /// `buf` references the updated buffer after the read. /// /// Default impl is a no-op. fn after_write(&mut self, _buf: &Buffer) -> FlushAmt { FlushAmt(0) } } /// Default behavior of `std::io::BufWriter`: flush before a read into the buffer /// only if the incoming data is larger than the buffer's writable space. impl WriterPolicy for StdPolicy {} /// Flush the buffer if it contains at least the given number of bytes. #[derive(Debug, Default)] pub struct FlushAtLeast(pub usize); impl WriterPolicy for FlushAtLeast { fn before_write(&mut self, buf: &mut Buffer, incoming: usize) -> FlushAmt { ensure_capacity(buf, self.0); FlushAmt(if incoming > buf.usable_space() { buf.len() } else { 0 }) } fn after_write(&mut self, buf: &Buffer) -> FlushAmt { FlushAmt(::std::cmp::max(buf.len(), self.0)) } } /// Only ever flush exactly the given number of bytes, until the writer is empty. #[derive(Debug, Default)] pub struct FlushExact(pub usize); impl WriterPolicy for FlushExact { /// Flushes the buffer if there is not enough room to fit `incoming` bytes, /// but only when the buffer contains at least `self.0` bytes. /// /// Otherwise, calls [`Buffer::make_room()`](::Buffer::make_room) fn before_write(&mut self, buf: &mut Buffer, incoming: usize) -> FlushAmt { ensure_capacity(buf, self.0); // don't have enough room to fit the additional bytes but we can't flush, // then make room for (at least some of) the incoming bytes. if incoming > buf.usable_space() && buf.len() < self.0 { buf.make_room(); } FlushAmt(self.0) } /// Flushes the given amount if possible, nothing otherwise. fn after_write(&mut self, _buf: &Buffer) -> FlushAmt { FlushAmt(self.0) } } /// Flush the buffer if it contains the given byte. /// /// Only scans the buffer after reading. Searches from the end first. #[derive(Debug, Default)] pub struct FlushOn(pub u8); impl WriterPolicy for FlushOn { fn after_write(&mut self, buf: &Buffer) -> FlushAmt { // include the delimiter in the flush FlushAmt(::memchr::memrchr(self.0, buf.buf()).map_or(0, |n| n + 1)) } } /// Flush the buffer if it contains a newline (`\n`). /// /// Equivalent to `FlushOn(b'\n')`. #[derive(Debug, Default)] pub struct FlushOnNewline; impl WriterPolicy for FlushOnNewline { fn after_write(&mut self, buf: &Buffer) -> FlushAmt { FlushAmt(::memchr::memrchr(b'\n', buf.buf()).map_or(0, |n| n + 1)) } } fn ensure_capacity(buf: &mut Buffer, min_cap: usize) { let cap = buf.capacity(); if cap < min_cap { buf.reserve(min_cap - cap); } } #[cfg(test)] mod test { use {BufReader, BufWriter}; use policy::*; use std::io::{BufRead, Cursor, Write}; #[test] fn test_min_buffered() { let min_buffered = 4; let data = (0 .. 20).collect::<Vec<u8>>(); // create a reader with 0 capacity let mut reader = BufReader::with_capacity(0, Cursor::new(data)) .set_policy(MinBuffered(min_buffered)); // policy reserves the required space in the buffer assert_eq!(reader.fill_buf().unwrap(), &[0, 1, 2, 3][..]); assert_eq!(reader.capacity(), min_buffered); // double the size now that the buffer's full reader.reserve(min_buffered); assert_eq!(reader.capacity(), min_buffered * 2); // we haven't consumed anything, the reader should have the same data assert_eq!(reader.fill_buf().unwrap(), &[0, 1, 2, 3]); reader.consume(2); // policy read more data, `std::io::BufReader` doesn't do that assert_eq!(reader.fill_buf().unwrap(), &[2, 3, 4, 5, 6, 7]); reader.consume(4); // policy made room and read more assert_eq!(reader.fill_buf().unwrap(), &[6, 7, 8, 9, 10, 11, 12, 13]); reader.consume(4); assert_eq!(reader.fill_buf().unwrap(), &[10, 11, 12, 13]); reader.consume(2); assert_eq!(reader.fill_buf().unwrap(), &[12, 13, 14, 15, 16, 17, 18, 19]); reader.consume(8); assert_eq!(reader.fill_buf().unwrap(), &[]) } #[test] fn test_flush_at_least() { let flush_min = 4; let mut writer = BufWriter::with_capacity(0, vec![]).set_policy(FlushAtLeast(flush_min)); assert_eq!(writer.capacity(), 0); assert_eq!(writer.write(&[1]).unwrap(), 1); // policy reserved space for writing assert_eq!(writer.capacity(), flush_min); // one byte in buffer, we want to double our capacity writer.reserve(flush_min * 2 - 1); assert_eq!(writer.capacity(), flush_min * 2); assert_eq!(writer.write(&[2, 3]).unwrap(), 2); // no flush yet, only 3 bytes in buffer assert_eq!(*writer.get_ref(), &[]); assert_eq!(writer.write(&[4, 5, 6]).unwrap(), 3); // flushed all assert_eq!(*writer.get_ref(), &[1, 2, 3, 4, 5, 6]); assert_eq!(writer.write(&[7, 8, 9]).unwrap(), 3); // `.into_inner()` should flush always assert_eq!(writer.into_inner().unwrap(), &[1, 2, 3, 4, 5, 6, 7, 8, 9]); } #[test] fn test_flush_exact() { let flush_exact = 4; let mut writer = BufWriter::with_capacity(0, vec![]).set_policy(FlushExact(flush_exact)); assert_eq!(writer.capacity(), 0); assert_eq!(writer.write(&[1]).unwrap(), 1); // policy reserved space for writing assert_eq!(writer.capacity(), flush_exact); // one byte in buffer, we want to double our capacity writer.reserve(flush_exact * 2 - 1); assert_eq!(writer.capacity(), flush_exact * 2); assert_eq!(writer.write(&[2, 3]).unwrap(), 2); // no flush yet, only 3 bytes in buffer assert_eq!(*writer.get_ref(), &[]); assert_eq!(writer.write(&[4, 5, 6]).unwrap(), 3); // flushed exactly 4 bytes assert_eq!(*writer.get_ref(), &[1, 2, 3, 4]); assert_eq!(writer.write(&[7, 8, 9, 10]).unwrap(), 4); // flushed another 4 bytes assert_eq!(*writer.get_ref(), &[1, 2, 3, 4, 5, 6, 7, 8]); // `.into_inner()` should flush always assert_eq!(writer.into_inner().unwrap(), &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); } #[test] fn test_flush_on() { let mut writer = BufWriter::with_capacity(8, vec![]).set_policy(FlushOn(0)); assert_eq!(writer.write(&[1, 2, 3]).unwrap(), 3); assert_eq!(*writer.get_ref(), &[]); assert_eq!(writer.write(&[0, 4, 5]).unwrap(), 3); assert_eq!(*writer.get_ref(), &[1, 2, 3, 0]); assert_eq!(writer.write(&[6, 7, 8, 9, 10, 11, 12]).unwrap(), 7); assert_eq!(*writer.get_ref(), &[1, 2, 3, 0, 4, 5]); assert_eq!(writer.write(&[0]).unwrap(), 1); assert_eq!(*writer.get_ref(), &[1, 2, 3, 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0]); } #[test] fn test_flush_on_newline() { let mut writer = BufWriter::with_capacity(8, vec![]).set_policy(FlushOnNewline); assert_eq!(writer.write(&[1, 2, 3]).unwrap(), 3); assert_eq!(*writer.get_ref(), &[]); assert_eq!(writer.write(&[b'\n', 4, 5]).unwrap(), 3); assert_eq!(*writer.get_ref(), &[1, 2, 3, b'\n']); assert_eq!(writer.write(&[6, 7, 8, 9, b'\n', 11, 12]).unwrap(), 7); assert_eq!(*writer.get_ref(), &[1, 2, 3, b'\n', 4, 5, 6, 7, 8, 9, b'\n']); assert_eq!(writer.write(&[b'\n']).unwrap(), 1); assert_eq!(*writer.get_ref(), &[1, 2, 3, b'\n', 4, 5, 6, 7, 8, 9, b'\n', 11, 12, b'\n']); } }
extern crate dredd_hooks; use dredd_hooks::{HooksServer}; fn main() { let mut hooks = HooksServer::new(); hooks.before("/message > GET", Box::new(|mut tr| { println!("It's me, File2"); tr })); HooksServer::start_from_env(hooks); }
use comrak::{markdown_to_html, ComrakExtensionOptions, ComrakOptions, ComrakRenderOptions}; use once_cell::sync::Lazy; use regex::Regex; use std::collections::HashMap; use syntect::{ easy::HighlightLines, highlighting::ThemeSet, html::{append_highlighted_html_for_styled_line, IncludeBackground}, parsing::SyntaxSet, util::LinesWithEndings, }; use crate::blog_clusters::BlogClusters; use crate::hlf_parser::{parse, HlfLhs, HlfRhs, Symbol}; use crate::shared::path_title; use crate::shared::HTMLTemplate; // 1. Retrieves the blogs into cluster // 2. Parse the template file into HLF // 3. Use the information in cluster to expand the HLF to get the webpage result // For each kind of webpages the expand rules are different and hard-coded. The // hard-coded rules could be wrote in files, which make this program data driven // (But it's difficult and not practical because requirements are always ugly // and hard to be described in a general way). // Use a bnf-like thing is a fancier expression of html snippet provider // while symbol in content means this symbol can be repeated const LATEX_MARK: &[u8; 9] = b"lAtExhERE"; const LATEX_MARK_LEN: usize = LATEX_MARK.len(); const LATEX_TAG_BEGIN: &[u8; 19] = br#"<div class="latex">"#; const LATEX_TAG_END: &[u8; 6] = b"</div>"; const ESCAPE_TABLE: [(&[u8], u8); 5] = [ (b"&quot;", b'"'), (b"&amp;", b'&'), (b"&#39;", b'\''), (b"&lt;", b'<'), (b"&gt;", b'>'), ]; // With markdown as input, this function returns content with latex replaced by // mark and array of latex extracted. Currently we don't need to distinguish // block latex and inline latex, the metadata is stored with the string, here we // kept the wrapping `$`, for inline latex number is `$` is 2, for block latex // it's 4. And the second problem is if we should use Vec<u8> rather than String // to represent each LaTeX part. The answer is no. We should use String to keep // the information that this LaTeX part is valid UTF-8. pub fn extract_latex(s: &str) -> (String, Vec<String>) { // Assume `$` pairs in a line as latex code fence. let s = s.as_bytes(); let mut new_s = Vec::with_capacity(s.len()); let mut latexes = Vec::new(); let mut state = 0; let mut ptr = 0; /* Here is a simple automaton for latex extraction * State Transition Graph: * L: Line break: `\r`, `\n` * $: Dollar sign * o: Other chars * If `o` is not set for specific state, we can ensure any other chars won't change this state. * ``` * +-+--$->+-+ +-+ * |2| |0|<-L--|5| * +-+--L->+-+ +-+ * A A|AA A * | //|| | * | // $\ o * o L/ \L | * | // \\ | * | // \\ | * | // \\ | * ||$ \\ | * ||| \\| * ||V ||| * +-+ +-+ +-+ * |1|--$->|3|--$->|4| * +-+ +-+ +-+ * ``` */ for (i, &byte) in s.iter().enumerate() { match state { 0 => match byte { b'$' => { state = 1; new_s.extend(&s[ptr..i]); ptr = i; } _ => (), }, 1 => match byte { b'$' => state = 3, b'\r' | b'\n' => state = 0, _ => state = 2, }, 2 => { match byte { b'$' => { state = 0; new_s.extend(LATEX_MARK); latexes.push(unsafe { String::from_utf8_unchecked(s[ptr..=i].to_vec()) }); ptr = i + 1; } // This is the error state, here we don't recover, instead // we only escape to next line. Why we need the `\r` check? // My special thank to Apple and Microsoft -_- b'\r' | b'\n' => state = 0, _ => (), } } 3 => match byte { b'$' => state = 4, _ => (), }, 4 => match byte { b'$' => { state = 0; new_s.extend(LATEX_MARK); latexes.push(unsafe { String::from_utf8_unchecked(s[ptr..=i].to_vec()) }); ptr = i + 1; } b'\r' | b'\n' => state = 0, _ => state = 5, }, // 5 is the error state, we only want to meet a line break then we will forget the error 5 => { match byte { // Here we recover from the error state b'\r' | b'\n' => state = 0, _ => (), } } _ => unreachable!(), } } new_s.extend(&s[ptr..]); (unsafe { String::from_utf8_unchecked(new_s) }, latexes) } // Replace marks in string given with latexes given. If latexes given more than // marks in string, this function returns None. pub fn insert_latex(s: &str, latexes: &Vec<String>) -> Option<String> { let s = s.as_bytes(); let mut latexes_iter = 0; let mut begin = 0; let mut result = Vec::with_capacity(s.len()); let mut i = 0; let i_max = s.len() - LATEX_MARK_LEN; while i < i_max { if &s[i..i + LATEX_MARK_LEN] == LATEX_MARK { result.extend(&s[begin..i]); result.extend(LATEX_TAG_BEGIN); result.extend(html_escape(&latexes[latexes_iter]).as_bytes()); result.extend(LATEX_TAG_END); latexes_iter += 1; begin = i + LATEX_MARK_LEN; i = begin; if latexes_iter >= latexes.len() { break; } } else { i += 1; } } if latexes_iter < latexes.len() { None } else { result.extend(&s[begin..]); Some(unsafe { String::from_utf8_unchecked(result) }) } } // This is used for unescape html pub fn html_unescape<T: AsRef<str>>(s: T) -> String { let s = s.as_ref().as_bytes(); let (begin, mut result) = (0..s.len()).fold( (0, Vec::with_capacity(s.len())), |(mut begin, mut result), i| { // unescape process ESCAPE_TABLE .iter() .find_map(|(before, after)| { s.get(i..i + before.len()).and_then(|range| { if &range == before { Some((before.len(), after)) } else { None } }) }) .map(|(offset, after)| { result.extend(&s[begin..i]); result.push(*after); begin = i + offset; }); (begin, result) }, ); // Append the tail result.extend(&s[begin..]); // The input is &str so we can ensure there is no surprise. unsafe { String::from_utf8_unchecked(result) } } pub fn html_escape<T: AsRef<str>>(s: T) -> String { let s = s.as_ref().as_bytes(); let (begin, mut result) = s.iter().enumerate().fold( (0, Vec::with_capacity(s.len())), |(mut begin, mut result), (i, byte)| { ESCAPE_TABLE .iter() .find_map( |(before, after)| { if byte == after { Some(before) } else { None } }, ) .map(|&before| { result.extend(&s[begin..i]); result.extend(before); begin = i + 1; }); (begin, result) }, ); result.extend(&s[begin..]); unsafe { String::from_utf8_unchecked(result) } } // Transform several frequently used markdown code annotation to file extension pub fn lang2ext(lang: &str) -> &str { match lang { // Syntect have no ebnf syntax highlighting support :-/ "cpp" | "c++" | "cxx" => "cpp", "rust" => "rs", "pascal" => "pas", "ebnf" | "" => "txt", _ => lang, } } pub fn highlight_code(lang: &str, code: &str) -> String { static SYNTAX_SET: Lazy<SyntaxSet> = Lazy::new(|| SyntaxSet::load_defaults_newlines()); static THEME_SET: Lazy<ThemeSet> = Lazy::new(|| ThemeSet::load_defaults()); let syntax = SYNTAX_SET .find_syntax_by_extension(lang2ext(lang)) .expect(&format!("Unknown language: {}!", lang)); let ref theme = THEME_SET.themes["base16-ocean.light"]; let mut highlighter = HighlightLines::new(syntax, theme); let code_unesc = html_unescape(&code); let mut code_highlight = String::with_capacity(code_unesc.len() * 2); for line in LinesWithEndings::from(&code_unesc) { let regions = highlighter.highlight(line, &SYNTAX_SET); append_highlighted_html_for_styled_line( &regions, IncludeBackground::No, &mut code_highlight, ); } code_highlight } pub struct BlogTemplate { hlfs: HashMap<HlfLhs, HlfRhs>, } impl HTMLTemplate for BlogTemplate { fn load(template_raw: &str) -> Result<Self, String> { let hlfs_vec = match parse(&template_raw) { Some(x) => x, None => return Err("template parse failed".to_string()), }; let mut hlfs = HashMap::new(); for i in hlfs_vec.iter() { hlfs.insert(i.lhs.clone(), i.rhs.clone()); } Ok(Self { hlfs: hlfs }) } fn fill(&self, cluster: &BlogClusters) -> Vec<(String, String)> { let mut results = Vec::new(); // We have the knowledge of blog template's structure let main_rhs = self .hlfs .get("main") .expect("there should be a main symbol in blog template."); let tags_rhs = match main_rhs.get(1).unwrap() { Symbol::N(x) => self .hlfs .get(x) .expect(&format!("\"{}\" symbol not found.", x)), _ => panic!(), }; let tag_rhs = match tags_rhs.get(1).unwrap() { Symbol::N(x) => self .hlfs .get(x) .expect(&format!("\"{}\" symbol not found.", x)), _ => panic!(), }; assert_eq!(main_rhs.len(), 3); assert_eq!(tags_rhs.len(), 3); assert_eq!(tag_rhs.len(), 1); let blogs = cluster.get_blogs(); for blog in blogs { let mut result = String::new(); match main_rhs.get(0).unwrap() { Symbol::T(x) => { // 1. Markdown to html // 2. Retrieve code blocks in html. // 3. Do syntax highlighting on unescaped code blocks // according to code annotation. (code may contains // some characters will be escaped to fit into html) // This solution is inspired by author of comrak: // https://github.com/kivikakk/comrak/issues/129. But // actually a better solution is extracting code blocks // before converting markdown to html and insert the // highlighted code after it. This is how we process latex // blocks, but I come up with it before I finish the code // highlighting part :-P. It works anyway.... let options = ComrakOptions { // Enable frequently used github markdown extensions extension: ComrakExtensionOptions { tasklist: true, table: true, strikethrough: true, ..Default::default() }, render: ComrakRenderOptions { github_pre_lang: true, ..Default::default() }, ..Default::default() }; let (content, latexes) = extract_latex(&blog.content); let content = markdown_to_html(&content, &options); let raw_html = x .replace("_slot_of_blog_title", &blog.title) .replace("_slot_of_blog_day", &blog.day.to_string()) .replace("_slot_of_blog_month", &blog.month.to_string()) .replace("_slot_of_blog_year", &blog.year.to_string()) .replace("_slot_of_blog_preview", &blog.preview) .replace("_slot_of_blog_content", &content); let raw_html = match insert_latex(&raw_html, &latexes) { Some(x) => x, None => panic!("LaTeX insertion error!"), }; // Assume latex never overlaps with or contained by code. static RE: Lazy<Regex> = Lazy::new(|| { Regex::new(r#"<pre lang="([^"]*)"><code>([^<]*)</code></pre>"#).unwrap() }); let mut begin = 0; for cap in RE.captures_iter(&raw_html) { let lang = cap.get(1).unwrap().as_str(); let code = cap.get(2).unwrap().as_str(); let ref code_highlight = highlight_code(lang, code); let range = cap.get(0).unwrap().range(); let end = range.start; result.push_str(&raw_html[begin..end]); result.push_str(r#"<pre lang=""#); result.push_str(lang); result.push_str(r#""><code>"#); result.push_str(code_highlight); result.push_str(r#"</code></pre>"#); begin = range.end; } result.push_str(&raw_html[begin..]); } _ => panic!(), }; match tags_rhs.get(0).unwrap() { Symbol::T(x) => result.push_str(x), _ => panic!(), }; // add multiple tag names for tag_handle in blog.tags.iter() { match tag_rhs.get(0).unwrap() { Symbol::T(x) => { let tag = cluster.get_tag(*tag_handle).unwrap(); result.push_str(&x.replace("_slot_of_tag_name", &tag.name)); } _ => panic!(), }; } match tags_rhs.get(2).unwrap() { Symbol::T(x) => result.push_str(x), _ => panic!(), }; match main_rhs.get(2).unwrap() { Symbol::T(x) => result.push_str(x), _ => panic!(), } results.push((format!("{}{}", &path_title(&blog.title), ".html"), result)); } results } } #[cfg(test)] mod template_tests { use super::*; #[test] fn test_html_unescape() { assert_eq!(html_unescape("emm"), "emm"); assert_eq!(html_unescape("&quot;"), "\""); assert_eq!(html_unescape("&amp;"), "&"); assert_eq!(html_unescape("&#39;"), "\'"); assert_eq!(html_unescape("&lt;"), "<"); assert_eq!(html_unescape("&gt;"), ">"); assert_eq!(html_unescape("&emm"), "&emm"); assert_eq!(html_unescape("&quot"), "&quot"); assert_eq!(html_unescape("&qu&lt;"), "&qu<"); assert_eq!(html_unescape("&qu&lt"), "&qu&lt"); assert_eq!(html_unescape("&quot;&lt;"), "\"<"); assert_eq!(html_unescape("&quot;&lt"), "\"&lt"); assert_eq!(html_unescape("&lt;&quot;&quot;&gt;"), "<\"\">"); } #[test] fn test_html_escape() { assert_eq!(html_escape("emm"), "emm"); assert_eq!("&quot;", html_escape("\"")); assert_eq!("&amp;", html_escape("&")); assert_eq!("&#39;", html_escape("\'")); assert_eq!("&lt;", html_escape("<")); assert_eq!("&gt;", html_escape(">")); assert_eq!("&amp;emm", html_escape("&emm")); assert_eq!("&amp;quot", html_escape("&quot")); assert_eq!("&amp;qu&lt;", html_escape("&qu<")); assert_eq!("&amp;qu&amp;lt", html_escape("&qu&lt")); assert_eq!("&quot;&lt;", html_escape("\"<")); assert_eq!("&quot;&amp;lt", html_escape("\"&lt")); assert_eq!("&lt;&quot;&quot;&gt;", html_escape("<\"\">")); } #[test] fn test_html_escape_and_unescape() { let chaos = r#" $%^Y&UIafjnh%^&*(OGFTY^&*IOL<KO{}?L:"KJYT<><<<>>"""KK''' 'L';'''"''"'""<><><>GFDER$%^&*()*&^%$%YH^T&*UIOJHVYFT^&Y *IOUYTE@#!@#$%^&*((~!@#$%^&*()(*^%~`1234567897^%$#@!@#$% ^&*148964865}"?>:{}"?><LP{}"?><KJHGBNL;oijk,./'][p;.,mnb vcxsrtyjkghmnabsdjf]))) "#; assert_eq!(html_unescape(&html_escape(&chaos)), chaos); } #[test] fn test_inline_latex_extraction() { let s = " hi $I'm latex0$ alice hi $I'm latex1$ bob hi $I'm not latex hi $I'm latex2$ $I'm not latex hi $I'm latex3$ alice hi $I'm latex4$ bob "; let (_, latexes) = extract_latex(s); assert_eq!( latexes, [ "$I'm latex0$", "$I'm latex1$", "$I'm latex2$", "$I'm latex3$", "$I'm latex4$", ] ); } #[test] fn test_block_latex_extraction() { let s = " hi $$I'm latex0$$ alice hi $$I'm latex1 bob hahah$$ hi $$I'm a failed latex$ hi $$I'm latex2$$ $I'm not latex hi $$I'm latex3$$ alice hi $$I'm latex4$$ bob "; let (_, latexes) = extract_latex(s); assert_eq!( latexes, [ "$$I'm latex0$$", "$$I'm latex1 bob hahah$$", "$$I'm latex2$$", "$$I'm latex3$$", "$$I'm latex4$$", ] ); } #[test] fn test_inline_latex_insertion() { let mark: &str = unsafe { &String::from_utf8_unchecked(LATEX_MARK.to_vec()) }; let begin: &str = unsafe { &String::from_utf8_unchecked(LATEX_TAG_BEGIN.to_vec()) }; let end: &str = unsafe { &String::from_utf8_unchecked(LATEX_TAG_END.to_vec()) }; let s = ["a", mark, "b", mark, "c"].join(""); let latexes = vec![String::from("$Alice$"), String::from("$Bob$")]; let s = insert_latex(&s, &latexes); assert_eq!( s, Some( [ "a", begin, &latexes[0], end, "b", begin, &latexes[1], end, "c" ] .join("") ) ); } #[test] fn test_block_latex_insertion() { let mark: &str = unsafe { &String::from_utf8_unchecked(LATEX_MARK.to_vec()) }; let begin: &str = unsafe { &String::from_utf8_unchecked(LATEX_TAG_BEGIN.to_vec()) }; let end: &str = unsafe { &String::from_utf8_unchecked(LATEX_TAG_END.to_vec()) }; let s = ["a", mark, "b", mark, "c"].join(""); let latexes = vec![String::from("$$Ali\nce$$"), String::from("$$Bob$$")]; let s = insert_latex(&s, &latexes); assert_eq!( s, Some( [ "a", begin, &latexes[0], end, "b", begin, &latexes[1], end, "c" ] .join("") ) ); } }
use crate::{Primitive, Renderer}; use iced_native::{ checkbox, Background, HorizontalAlignment, MouseCursor, Rectangle, VerticalAlignment, }; const SIZE: f32 = 28.0; impl checkbox::Renderer for Renderer { fn default_size(&self) -> u32 { SIZE as u32 } fn draw( &mut self, bounds: Rectangle, is_checked: bool, is_mouse_over: bool, (label, _): Self::Output, ) -> Self::Output { let (checkbox_border, checkbox_box) = ( Primitive::Quad { bounds, background: Background::Color([0.6, 0.6, 0.6].into()), border_radius: 6, }, Primitive::Quad { bounds: Rectangle { x: bounds.x + 1.0, y: bounds.y + 1.0, width: bounds.width - 2.0, height: bounds.height - 2.0, }, background: Background::Color( if is_mouse_over { [0.90, 0.90, 0.90] } else { [0.95, 0.95, 0.95] } .into(), ), border_radius: 5, }, ); ( Primitive::Group { primitives: if is_checked { let check = Primitive::Text { content: crate::text::CHECKMARK_ICON.to_string(), font: crate::text::BUILTIN_ICONS, size: bounds.height * 0.7, bounds: bounds, color: [0.3, 0.3, 0.3].into(), horizontal_alignment: HorizontalAlignment::Center, vertical_alignment: VerticalAlignment::Center, }; vec![checkbox_border, checkbox_box, check, label] } else { vec![checkbox_border, checkbox_box, label] }, }, if is_mouse_over { MouseCursor::Pointer } else { MouseCursor::OutOfBounds }, ) } }
use std::cmp::Ordering; use std::iter::Skip; use std::str::Chars; use unicode_width::UnicodeWidthChar; /// The action performed by [`StrShortener`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TextAction { /// Yield a spacer. Spacer, /// Terminate state reached. Terminate, /// Yield a shortener. Shortener, /// Yield a character. Char, } /// The direction which we should shorten. #[derive(Clone, Copy, PartialEq, Eq)] pub enum ShortenDirection { /// Shorten to the start of the string. Left, /// Shorten to the end of the string. Right, } /// Iterator that yield shortened version of the text. pub struct StrShortener<'a> { chars: Skip<Chars<'a>>, accumulted_len: usize, max_width: usize, direction: ShortenDirection, shortener: Option<char>, text_action: TextAction, } impl<'a> StrShortener<'a> { pub fn new( text: &'a str, max_width: usize, direction: ShortenDirection, mut shortener: Option<char>, ) -> Self { if text.is_empty() { // If we don't have any text don't produce a shortener for it. let _ = shortener.take(); } if direction == ShortenDirection::Right { return Self { chars: text.chars().skip(0), accumulted_len: 0, text_action: TextAction::Char, max_width, direction, shortener, }; } let mut offset = 0; let mut current_len = 0; let mut iter = text.chars().rev().enumerate(); while let Some((idx, ch)) = iter.next() { let ch_width = ch.width().unwrap_or(1); current_len += ch_width; match current_len.cmp(&max_width) { // We can only be here if we've faced wide character or we've already // handled equality situation. Anyway, break. Ordering::Greater => break, Ordering::Equal => { if shortener.is_some() && iter.clone().next().is_some() { // We have one more character after, shortener will accumulate for // the `current_len`. break; } else { // The match is exact, consume shortener. let _ = shortener.take(); } }, Ordering::Less => (), } offset = idx + 1; } // Consume the iterator to count the number of characters in it. let num_chars = iter.last().map_or(offset, |(idx, _)| idx + 1); let skip_chars = num_chars - offset; let text_action = if current_len < max_width || shortener.is_none() { TextAction::Char } else { TextAction::Shortener }; let chars = text.chars().skip(skip_chars); Self { chars, accumulted_len: 0, text_action, max_width, direction, shortener } } } impl<'a> Iterator for StrShortener<'a> { type Item = char; fn next(&mut self) -> Option<Self::Item> { match self.text_action { TextAction::Spacer => { self.text_action = TextAction::Char; Some(' ') }, TextAction::Terminate => { // We've reached the termination state. None }, TextAction::Shortener => { // When we shorten from the left we yield the shortener first and process the rest. self.text_action = if self.direction == ShortenDirection::Left { TextAction::Char } else { TextAction::Terminate }; // Consume the shortener to avoid yielding it later when shortening left. self.shortener.take() }, TextAction::Char => { let ch = self.chars.next()?; let ch_width = ch.width().unwrap_or(1); // Advance width. self.accumulted_len += ch_width; if self.accumulted_len > self.max_width { self.text_action = TextAction::Terminate; return self.shortener; } else if self.accumulted_len == self.max_width && self.shortener.is_some() { // Check if we have a next char. let has_next = self.chars.clone().next().is_some(); // We should terminate after that. self.text_action = TextAction::Terminate; return has_next.then(|| self.shortener.unwrap()).or(Some(ch)); } // Add a spacer for wide character. if ch_width == 2 { self.text_action = TextAction::Spacer; } Some(ch) }, } } } #[cfg(test)] mod tests { use super::*; #[test] fn into_shortened_with_shortener() { let s = "Hello"; let len = s.chars().count(); assert_eq!( "", StrShortener::new("", 1, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( ".", StrShortener::new(s, 1, ShortenDirection::Right, Some('.')).collect::<String>() ); assert_eq!( ".", StrShortener::new(s, 1, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( "H.", StrShortener::new(s, 2, ShortenDirection::Right, Some('.')).collect::<String>() ); assert_eq!( ".o", StrShortener::new(s, 2, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( s, &StrShortener::new(s, len * 2, ShortenDirection::Right, Some('.')).collect::<String>() ); assert_eq!( s, &StrShortener::new(s, len * 2, ShortenDirection::Left, Some('.')).collect::<String>() ); let s = "ちはP"; let len = 2 + 2 + 1; assert_eq!( ".", &StrShortener::new(s, 1, ShortenDirection::Right, Some('.')).collect::<String>() ); assert_eq!( &".", &StrShortener::new(s, 1, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( ".", &StrShortener::new(s, 2, ShortenDirection::Right, Some('.')).collect::<String>() ); assert_eq!( ".P", &StrShortener::new(s, 2, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( "ち .", &StrShortener::new(s, 3, ShortenDirection::Right, Some('.')).collect::<String>() ); assert_eq!( ".P", &StrShortener::new(s, 3, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( "ち は P", &StrShortener::new(s, len * 2, ShortenDirection::Left, Some('.')).collect::<String>() ); assert_eq!( "ち は P", &StrShortener::new(s, len * 2, ShortenDirection::Right, Some('.')).collect::<String>() ); } #[test] fn into_shortened_without_shortener() { let s = "Hello"; assert_eq!("", StrShortener::new("", 1, ShortenDirection::Left, None).collect::<String>()); assert_eq!( "H", &StrShortener::new(s, 1, ShortenDirection::Right, None).collect::<String>() ); assert_eq!("o", &StrShortener::new(s, 1, ShortenDirection::Left, None).collect::<String>()); assert_eq!( "He", &StrShortener::new(s, 2, ShortenDirection::Right, None).collect::<String>() ); assert_eq!( "lo", &StrShortener::new(s, 2, ShortenDirection::Left, None).collect::<String>() ); assert_eq!( &s, &StrShortener::new(s, s.len(), ShortenDirection::Right, None).collect::<String>() ); assert_eq!( &s, &StrShortener::new(s, s.len(), ShortenDirection::Left, None).collect::<String>() ); let s = "こJんにちはP"; let len = 2 + 1 + 2 + 2 + 2 + 2 + 1; assert_eq!("", &StrShortener::new(s, 1, ShortenDirection::Right, None).collect::<String>()); assert_eq!("P", &StrShortener::new(s, 1, ShortenDirection::Left, None).collect::<String>()); assert_eq!( "こ ", &StrShortener::new(s, 2, ShortenDirection::Right, None).collect::<String>() ); assert_eq!("P", &StrShortener::new(s, 2, ShortenDirection::Left, None).collect::<String>()); assert_eq!( "こ J", &StrShortener::new(s, 3, ShortenDirection::Right, None).collect::<String>() ); assert_eq!( "は P", &StrShortener::new(s, 3, ShortenDirection::Left, None).collect::<String>() ); assert_eq!( "こ Jん に ち は P", &StrShortener::new(s, len, ShortenDirection::Left, None).collect::<String>() ); assert_eq!( "こ Jん に ち は P", &StrShortener::new(s, len, ShortenDirection::Right, None).collect::<String>() ); } }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qtoolbar.h // dst-file: /src/widgets/qtoolbar.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::qwidget::*; // 773 use std::ops::Deref; use super::super::gui::qicon::*; // 771 use super::super::core::qstring::*; // 771 use super::super::core::qobject::*; // 771 use super::qaction::*; // 773 use super::super::core::qsize::*; // 771 use super::super::core::qrect::*; // 771 use super::super::core::qpoint::*; // 771 use super::super::core::qobjectdefs::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QToolBar_Class_Size() -> c_int; // proto: QAction * QToolBar::addAction(const QIcon & icon, const QString & text, const QObject * receiver, const char * member); fn C_ZN8QToolBar9addActionERK5QIconRK7QStringPK7QObjectPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void, arg3: *mut c_char) -> *mut c_void; // proto: bool QToolBar::isFloatable(); fn C_ZNK8QToolBar11isFloatableEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QSize QToolBar::iconSize(); fn C_ZNK8QToolBar8iconSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QRect QToolBar::actionGeometry(QAction * action); fn C_ZNK8QToolBar14actionGeometryEP7QAction(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QWidget * QToolBar::widgetForAction(QAction * action); fn C_ZNK8QToolBar15widgetForActionEP7QAction(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QToolBar::clear(); fn C_ZN8QToolBar5clearEv(qthis: u64 /* *mut c_void*/); // proto: void QToolBar::QToolBar(const QString & title, QWidget * parent); fn C_ZN8QToolBarC2ERK7QStringP7QWidget(arg0: *mut c_void, arg1: *mut c_void) -> u64; // proto: void QToolBar::setMovable(bool movable); fn C_ZN8QToolBar10setMovableEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: bool QToolBar::isMovable(); fn C_ZNK8QToolBar9isMovableEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QToolBar::setIconSize(const QSize & iconSize); fn C_ZN8QToolBar11setIconSizeERK5QSize(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QAction * QToolBar::addSeparator(); fn C_ZN8QToolBar12addSeparatorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QToolBar::setFloatable(bool floatable); fn C_ZN8QToolBar12setFloatableEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: QAction * QToolBar::addAction(const QString & text); fn C_ZN8QToolBar9addActionERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QAction * QToolBar::addAction(const QIcon & icon, const QString & text); fn C_ZN8QToolBar9addActionERK5QIconRK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void; // proto: void QToolBar::QToolBar(QWidget * parent); fn C_ZN8QToolBarC2EP7QWidget(arg0: *mut c_void) -> u64; // proto: QAction * QToolBar::actionAt(const QPoint & p); fn C_ZNK8QToolBar8actionAtERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QAction * QToolBar::actionAt(int x, int y); fn C_ZNK8QToolBar8actionAtEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int) -> *mut c_void; // proto: bool QToolBar::isFloating(); fn C_ZNK8QToolBar10isFloatingEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QAction * QToolBar::toggleViewAction(); fn C_ZNK8QToolBar16toggleViewActionEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QToolBar::~QToolBar(); fn C_ZN8QToolBarD2Ev(qthis: u64 /* *mut c_void*/); // proto: QAction * QToolBar::addAction(const QString & text, const QObject * receiver, const char * member); fn C_ZN8QToolBar9addActionERK7QStringPK7QObjectPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_char) -> *mut c_void; // proto: QAction * QToolBar::insertWidget(QAction * before, QWidget * widget); fn C_ZN8QToolBar12insertWidgetEP7QActionP7QWidget(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void; // proto: QAction * QToolBar::addWidget(QWidget * widget); fn C_ZN8QToolBar9addWidgetEP7QWidget(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: const QMetaObject * QToolBar::metaObject(); fn C_ZNK8QToolBar10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QAction * QToolBar::insertSeparator(QAction * before); fn C_ZN8QToolBar15insertSeparatorEP7QAction(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; fn QToolBar_SlotProxy_connect__ZN8QToolBar15actionTriggeredEP7QAction(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QToolBar_SlotProxy_connect__ZN8QToolBar14movableChangedEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QToolBar_SlotProxy_connect__ZN8QToolBar17visibilityChangedEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QToolBar_SlotProxy_connect__ZN8QToolBar15iconSizeChangedERK5QSize(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QToolBar_SlotProxy_connect__ZN8QToolBar15topLevelChangedEb(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QToolBar)=1 #[derive(Default)] pub struct QToolBar { qbase: QWidget, pub qclsinst: u64 /* *mut c_void*/, pub _iconSizeChanged: QToolBar_iconSizeChanged_signal, pub _allowedAreasChanged: QToolBar_allowedAreasChanged_signal, pub _movableChanged: QToolBar_movableChanged_signal, pub _toolButtonStyleChanged: QToolBar_toolButtonStyleChanged_signal, pub _topLevelChanged: QToolBar_topLevelChanged_signal, pub _actionTriggered: QToolBar_actionTriggered_signal, pub _orientationChanged: QToolBar_orientationChanged_signal, pub _visibilityChanged: QToolBar_visibilityChanged_signal, } impl /*struct*/ QToolBar { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QToolBar { return QToolBar{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QToolBar { type Target = QWidget; fn deref(&self) -> &QWidget { return & self.qbase; } } impl AsRef<QWidget> for QToolBar { fn as_ref(& self) -> & QWidget { return & self.qbase; } } // proto: QAction * QToolBar::addAction(const QIcon & icon, const QString & text, const QObject * receiver, const char * member); impl /*struct*/ QToolBar { pub fn addAction<RetType, T: QToolBar_addAction<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addAction(self); // return 1; } } pub trait QToolBar_addAction<RetType> { fn addAction(self , rsthis: & QToolBar) -> RetType; } // proto: QAction * QToolBar::addAction(const QIcon & icon, const QString & text, const QObject * receiver, const char * member); impl<'a> /*trait*/ QToolBar_addAction<QAction> for (&'a QIcon, &'a QString, &'a QObject, &'a String) { fn addAction(self , rsthis: & QToolBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBar9addActionERK5QIconRK7QStringPK7QObjectPKc()}; 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.as_ptr() as *mut c_char; let mut ret = unsafe {C_ZN8QToolBar9addActionERK5QIconRK7QStringPK7QObjectPKc(rsthis.qclsinst, arg0, arg1, arg2, arg3)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QToolBar::isFloatable(); impl /*struct*/ QToolBar { pub fn isFloatable<RetType, T: QToolBar_isFloatable<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isFloatable(self); // return 1; } } pub trait QToolBar_isFloatable<RetType> { fn isFloatable(self , rsthis: & QToolBar) -> RetType; } // proto: bool QToolBar::isFloatable(); impl<'a> /*trait*/ QToolBar_isFloatable<i8> for () { fn isFloatable(self , rsthis: & QToolBar) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QToolBar11isFloatableEv()}; let mut ret = unsafe {C_ZNK8QToolBar11isFloatableEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QSize QToolBar::iconSize(); impl /*struct*/ QToolBar { pub fn iconSize<RetType, T: QToolBar_iconSize<RetType>>(& self, overload_args: T) -> RetType { return overload_args.iconSize(self); // return 1; } } pub trait QToolBar_iconSize<RetType> { fn iconSize(self , rsthis: & QToolBar) -> RetType; } // proto: QSize QToolBar::iconSize(); impl<'a> /*trait*/ QToolBar_iconSize<QSize> for () { fn iconSize(self , rsthis: & QToolBar) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QToolBar8iconSizeEv()}; let mut ret = unsafe {C_ZNK8QToolBar8iconSizeEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QRect QToolBar::actionGeometry(QAction * action); impl /*struct*/ QToolBar { pub fn actionGeometry<RetType, T: QToolBar_actionGeometry<RetType>>(& self, overload_args: T) -> RetType { return overload_args.actionGeometry(self); // return 1; } } pub trait QToolBar_actionGeometry<RetType> { fn actionGeometry(self , rsthis: & QToolBar) -> RetType; } // proto: QRect QToolBar::actionGeometry(QAction * action); impl<'a> /*trait*/ QToolBar_actionGeometry<QRect> for (&'a QAction) { fn actionGeometry(self , rsthis: & QToolBar) -> QRect { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QToolBar14actionGeometryEP7QAction()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK8QToolBar14actionGeometryEP7QAction(rsthis.qclsinst, arg0)}; let mut ret1 = QRect::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QWidget * QToolBar::widgetForAction(QAction * action); impl /*struct*/ QToolBar { pub fn widgetForAction<RetType, T: QToolBar_widgetForAction<RetType>>(& self, overload_args: T) -> RetType { return overload_args.widgetForAction(self); // return 1; } } pub trait QToolBar_widgetForAction<RetType> { fn widgetForAction(self , rsthis: & QToolBar) -> RetType; } // proto: QWidget * QToolBar::widgetForAction(QAction * action); impl<'a> /*trait*/ QToolBar_widgetForAction<QWidget> for (&'a QAction) { fn widgetForAction(self , rsthis: & QToolBar) -> QWidget { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QToolBar15widgetForActionEP7QAction()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK8QToolBar15widgetForActionEP7QAction(rsthis.qclsinst, arg0)}; let mut ret1 = QWidget::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QToolBar::clear(); impl /*struct*/ QToolBar { pub fn clear<RetType, T: QToolBar_clear<RetType>>(& self, overload_args: T) -> RetType { return overload_args.clear(self); // return 1; } } pub trait QToolBar_clear<RetType> { fn clear(self , rsthis: & QToolBar) -> RetType; } // proto: void QToolBar::clear(); impl<'a> /*trait*/ QToolBar_clear<()> for () { fn clear(self , rsthis: & QToolBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBar5clearEv()}; unsafe {C_ZN8QToolBar5clearEv(rsthis.qclsinst)}; // return 1; } } // proto: void QToolBar::QToolBar(const QString & title, QWidget * parent); impl /*struct*/ QToolBar { pub fn new<T: QToolBar_new>(value: T) -> QToolBar { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QToolBar_new { fn new(self) -> QToolBar; } // proto: void QToolBar::QToolBar(const QString & title, QWidget * parent); impl<'a> /*trait*/ QToolBar_new for (&'a QString, Option<&'a QWidget>) { fn new(self) -> QToolBar { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBarC2ERK7QStringP7QWidget()}; let ctysz: c_int = unsafe{QToolBar_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = (if self.1.is_none() {0} else {self.1.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN8QToolBarC2ERK7QStringP7QWidget(arg0, arg1)}; let rsthis = QToolBar{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QToolBar::setMovable(bool movable); impl /*struct*/ QToolBar { pub fn setMovable<RetType, T: QToolBar_setMovable<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setMovable(self); // return 1; } } pub trait QToolBar_setMovable<RetType> { fn setMovable(self , rsthis: & QToolBar) -> RetType; } // proto: void QToolBar::setMovable(bool movable); impl<'a> /*trait*/ QToolBar_setMovable<()> for (i8) { fn setMovable(self , rsthis: & QToolBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBar10setMovableEb()}; let arg0 = self as c_char; unsafe {C_ZN8QToolBar10setMovableEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QToolBar::isMovable(); impl /*struct*/ QToolBar { pub fn isMovable<RetType, T: QToolBar_isMovable<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isMovable(self); // return 1; } } pub trait QToolBar_isMovable<RetType> { fn isMovable(self , rsthis: & QToolBar) -> RetType; } // proto: bool QToolBar::isMovable(); impl<'a> /*trait*/ QToolBar_isMovable<i8> for () { fn isMovable(self , rsthis: & QToolBar) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QToolBar9isMovableEv()}; let mut ret = unsafe {C_ZNK8QToolBar9isMovableEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QToolBar::setIconSize(const QSize & iconSize); impl /*struct*/ QToolBar { pub fn setIconSize<RetType, T: QToolBar_setIconSize<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setIconSize(self); // return 1; } } pub trait QToolBar_setIconSize<RetType> { fn setIconSize(self , rsthis: & QToolBar) -> RetType; } // proto: void QToolBar::setIconSize(const QSize & iconSize); impl<'a> /*trait*/ QToolBar_setIconSize<()> for (&'a QSize) { fn setIconSize(self , rsthis: & QToolBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBar11setIconSizeERK5QSize()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN8QToolBar11setIconSizeERK5QSize(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QAction * QToolBar::addSeparator(); impl /*struct*/ QToolBar { pub fn addSeparator<RetType, T: QToolBar_addSeparator<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addSeparator(self); // return 1; } } pub trait QToolBar_addSeparator<RetType> { fn addSeparator(self , rsthis: & QToolBar) -> RetType; } // proto: QAction * QToolBar::addSeparator(); impl<'a> /*trait*/ QToolBar_addSeparator<QAction> for () { fn addSeparator(self , rsthis: & QToolBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBar12addSeparatorEv()}; let mut ret = unsafe {C_ZN8QToolBar12addSeparatorEv(rsthis.qclsinst)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QToolBar::setFloatable(bool floatable); impl /*struct*/ QToolBar { pub fn setFloatable<RetType, T: QToolBar_setFloatable<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setFloatable(self); // return 1; } } pub trait QToolBar_setFloatable<RetType> { fn setFloatable(self , rsthis: & QToolBar) -> RetType; } // proto: void QToolBar::setFloatable(bool floatable); impl<'a> /*trait*/ QToolBar_setFloatable<()> for (i8) { fn setFloatable(self , rsthis: & QToolBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBar12setFloatableEb()}; let arg0 = self as c_char; unsafe {C_ZN8QToolBar12setFloatableEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QAction * QToolBar::addAction(const QString & text); impl<'a> /*trait*/ QToolBar_addAction<QAction> for (&'a QString) { fn addAction(self , rsthis: & QToolBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBar9addActionERK7QString()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN8QToolBar9addActionERK7QString(rsthis.qclsinst, arg0)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QAction * QToolBar::addAction(const QIcon & icon, const QString & text); impl<'a> /*trait*/ QToolBar_addAction<QAction> for (&'a QIcon, &'a QString) { fn addAction(self , rsthis: & QToolBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBar9addActionERK5QIconRK7QString()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN8QToolBar9addActionERK5QIconRK7QString(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QToolBar::QToolBar(QWidget * parent); impl<'a> /*trait*/ QToolBar_new for (Option<&'a QWidget>) { fn new(self) -> QToolBar { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBarC2EP7QWidget()}; let ctysz: c_int = unsafe{QToolBar_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_ZN8QToolBarC2EP7QWidget(arg0)}; let rsthis = QToolBar{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QAction * QToolBar::actionAt(const QPoint & p); impl /*struct*/ QToolBar { pub fn actionAt<RetType, T: QToolBar_actionAt<RetType>>(& self, overload_args: T) -> RetType { return overload_args.actionAt(self); // return 1; } } pub trait QToolBar_actionAt<RetType> { fn actionAt(self , rsthis: & QToolBar) -> RetType; } // proto: QAction * QToolBar::actionAt(const QPoint & p); impl<'a> /*trait*/ QToolBar_actionAt<QAction> for (&'a QPoint) { fn actionAt(self , rsthis: & QToolBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QToolBar8actionAtERK6QPoint()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK8QToolBar8actionAtERK6QPoint(rsthis.qclsinst, arg0)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QAction * QToolBar::actionAt(int x, int y); impl<'a> /*trait*/ QToolBar_actionAt<QAction> for (i32, i32) { fn actionAt(self , rsthis: & QToolBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QToolBar8actionAtEii()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; let mut ret = unsafe {C_ZNK8QToolBar8actionAtEii(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QToolBar::isFloating(); impl /*struct*/ QToolBar { pub fn isFloating<RetType, T: QToolBar_isFloating<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isFloating(self); // return 1; } } pub trait QToolBar_isFloating<RetType> { fn isFloating(self , rsthis: & QToolBar) -> RetType; } // proto: bool QToolBar::isFloating(); impl<'a> /*trait*/ QToolBar_isFloating<i8> for () { fn isFloating(self , rsthis: & QToolBar) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QToolBar10isFloatingEv()}; let mut ret = unsafe {C_ZNK8QToolBar10isFloatingEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QAction * QToolBar::toggleViewAction(); impl /*struct*/ QToolBar { pub fn toggleViewAction<RetType, T: QToolBar_toggleViewAction<RetType>>(& self, overload_args: T) -> RetType { return overload_args.toggleViewAction(self); // return 1; } } pub trait QToolBar_toggleViewAction<RetType> { fn toggleViewAction(self , rsthis: & QToolBar) -> RetType; } // proto: QAction * QToolBar::toggleViewAction(); impl<'a> /*trait*/ QToolBar_toggleViewAction<QAction> for () { fn toggleViewAction(self , rsthis: & QToolBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QToolBar16toggleViewActionEv()}; let mut ret = unsafe {C_ZNK8QToolBar16toggleViewActionEv(rsthis.qclsinst)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QToolBar::~QToolBar(); impl /*struct*/ QToolBar { pub fn free<RetType, T: QToolBar_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QToolBar_free<RetType> { fn free(self , rsthis: & QToolBar) -> RetType; } // proto: void QToolBar::~QToolBar(); impl<'a> /*trait*/ QToolBar_free<()> for () { fn free(self , rsthis: & QToolBar) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBarD2Ev()}; unsafe {C_ZN8QToolBarD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: QAction * QToolBar::addAction(const QString & text, const QObject * receiver, const char * member); impl<'a> /*trait*/ QToolBar_addAction<QAction> for (&'a QString, &'a QObject, &'a String) { fn addAction(self , rsthis: & QToolBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBar9addActionERK7QStringPK7QObjectPKc()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.as_ptr() as *mut c_char; let mut ret = unsafe {C_ZN8QToolBar9addActionERK7QStringPK7QObjectPKc(rsthis.qclsinst, arg0, arg1, arg2)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QAction * QToolBar::insertWidget(QAction * before, QWidget * widget); impl /*struct*/ QToolBar { pub fn insertWidget<RetType, T: QToolBar_insertWidget<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insertWidget(self); // return 1; } } pub trait QToolBar_insertWidget<RetType> { fn insertWidget(self , rsthis: & QToolBar) -> RetType; } // proto: QAction * QToolBar::insertWidget(QAction * before, QWidget * widget); impl<'a> /*trait*/ QToolBar_insertWidget<QAction> for (&'a QAction, &'a QWidget) { fn insertWidget(self , rsthis: & QToolBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBar12insertWidgetEP7QActionP7QWidget()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN8QToolBar12insertWidgetEP7QActionP7QWidget(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QAction * QToolBar::addWidget(QWidget * widget); impl /*struct*/ QToolBar { pub fn addWidget<RetType, T: QToolBar_addWidget<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addWidget(self); // return 1; } } pub trait QToolBar_addWidget<RetType> { fn addWidget(self , rsthis: & QToolBar) -> RetType; } // proto: QAction * QToolBar::addWidget(QWidget * widget); impl<'a> /*trait*/ QToolBar_addWidget<QAction> for (&'a QWidget) { fn addWidget(self , rsthis: & QToolBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBar9addWidgetEP7QWidget()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN8QToolBar9addWidgetEP7QWidget(rsthis.qclsinst, arg0)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: const QMetaObject * QToolBar::metaObject(); impl /*struct*/ QToolBar { pub fn metaObject<RetType, T: QToolBar_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QToolBar_metaObject<RetType> { fn metaObject(self , rsthis: & QToolBar) -> RetType; } // proto: const QMetaObject * QToolBar::metaObject(); impl<'a> /*trait*/ QToolBar_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QToolBar) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK8QToolBar10metaObjectEv()}; let mut ret = unsafe {C_ZNK8QToolBar10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QAction * QToolBar::insertSeparator(QAction * before); impl /*struct*/ QToolBar { pub fn insertSeparator<RetType, T: QToolBar_insertSeparator<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insertSeparator(self); // return 1; } } pub trait QToolBar_insertSeparator<RetType> { fn insertSeparator(self , rsthis: & QToolBar) -> RetType; } // proto: QAction * QToolBar::insertSeparator(QAction * before); impl<'a> /*trait*/ QToolBar_insertSeparator<QAction> for (&'a QAction) { fn insertSeparator(self , rsthis: & QToolBar) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN8QToolBar15insertSeparatorEP7QAction()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN8QToolBar15insertSeparatorEP7QAction(rsthis.qclsinst, arg0)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } #[derive(Default)] // for QToolBar_iconSizeChanged pub struct QToolBar_iconSizeChanged_signal{poi:u64} impl /* struct */ QToolBar { pub fn iconSizeChanged(&self) -> QToolBar_iconSizeChanged_signal { return QToolBar_iconSizeChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QToolBar_iconSizeChanged_signal { pub fn connect<T: QToolBar_iconSizeChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QToolBar_iconSizeChanged_signal_connect { fn connect(self, sigthis: QToolBar_iconSizeChanged_signal); } #[derive(Default)] // for QToolBar_allowedAreasChanged pub struct QToolBar_allowedAreasChanged_signal{poi:u64} impl /* struct */ QToolBar { pub fn allowedAreasChanged(&self) -> QToolBar_allowedAreasChanged_signal { return QToolBar_allowedAreasChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QToolBar_allowedAreasChanged_signal { pub fn connect<T: QToolBar_allowedAreasChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QToolBar_allowedAreasChanged_signal_connect { fn connect(self, sigthis: QToolBar_allowedAreasChanged_signal); } #[derive(Default)] // for QToolBar_movableChanged pub struct QToolBar_movableChanged_signal{poi:u64} impl /* struct */ QToolBar { pub fn movableChanged(&self) -> QToolBar_movableChanged_signal { return QToolBar_movableChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QToolBar_movableChanged_signal { pub fn connect<T: QToolBar_movableChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QToolBar_movableChanged_signal_connect { fn connect(self, sigthis: QToolBar_movableChanged_signal); } #[derive(Default)] // for QToolBar_toolButtonStyleChanged pub struct QToolBar_toolButtonStyleChanged_signal{poi:u64} impl /* struct */ QToolBar { pub fn toolButtonStyleChanged(&self) -> QToolBar_toolButtonStyleChanged_signal { return QToolBar_toolButtonStyleChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QToolBar_toolButtonStyleChanged_signal { pub fn connect<T: QToolBar_toolButtonStyleChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QToolBar_toolButtonStyleChanged_signal_connect { fn connect(self, sigthis: QToolBar_toolButtonStyleChanged_signal); } #[derive(Default)] // for QToolBar_topLevelChanged pub struct QToolBar_topLevelChanged_signal{poi:u64} impl /* struct */ QToolBar { pub fn topLevelChanged(&self) -> QToolBar_topLevelChanged_signal { return QToolBar_topLevelChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QToolBar_topLevelChanged_signal { pub fn connect<T: QToolBar_topLevelChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QToolBar_topLevelChanged_signal_connect { fn connect(self, sigthis: QToolBar_topLevelChanged_signal); } #[derive(Default)] // for QToolBar_actionTriggered pub struct QToolBar_actionTriggered_signal{poi:u64} impl /* struct */ QToolBar { pub fn actionTriggered(&self) -> QToolBar_actionTriggered_signal { return QToolBar_actionTriggered_signal{poi:self.qclsinst}; } } impl /* struct */ QToolBar_actionTriggered_signal { pub fn connect<T: QToolBar_actionTriggered_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QToolBar_actionTriggered_signal_connect { fn connect(self, sigthis: QToolBar_actionTriggered_signal); } #[derive(Default)] // for QToolBar_orientationChanged pub struct QToolBar_orientationChanged_signal{poi:u64} impl /* struct */ QToolBar { pub fn orientationChanged(&self) -> QToolBar_orientationChanged_signal { return QToolBar_orientationChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QToolBar_orientationChanged_signal { pub fn connect<T: QToolBar_orientationChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QToolBar_orientationChanged_signal_connect { fn connect(self, sigthis: QToolBar_orientationChanged_signal); } #[derive(Default)] // for QToolBar_visibilityChanged pub struct QToolBar_visibilityChanged_signal{poi:u64} impl /* struct */ QToolBar { pub fn visibilityChanged(&self) -> QToolBar_visibilityChanged_signal { return QToolBar_visibilityChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QToolBar_visibilityChanged_signal { pub fn connect<T: QToolBar_visibilityChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QToolBar_visibilityChanged_signal_connect { fn connect(self, sigthis: QToolBar_visibilityChanged_signal); } // actionTriggered(class QAction *) extern fn QToolBar_actionTriggered_signal_connect_cb_0(rsfptr:fn(QAction), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QAction::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QToolBar_actionTriggered_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QAction)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QAction::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QToolBar_actionTriggered_signal_connect for fn(QAction) { fn connect(self, sigthis: QToolBar_actionTriggered_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 = QToolBar_actionTriggered_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QToolBar_SlotProxy_connect__ZN8QToolBar15actionTriggeredEP7QAction(arg0, arg1, arg2)}; } } impl /* trait */ QToolBar_actionTriggered_signal_connect for Box<Fn(QAction)> { fn connect(self, sigthis: QToolBar_actionTriggered_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 = QToolBar_actionTriggered_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QToolBar_SlotProxy_connect__ZN8QToolBar15actionTriggeredEP7QAction(arg0, arg1, arg2)}; } } // movableChanged(_Bool) extern fn QToolBar_movableChanged_signal_connect_cb_1(rsfptr:fn(i8), arg0: c_char) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as i8; rsfptr(rsarg0); } extern fn QToolBar_movableChanged_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as i8; // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QToolBar_movableChanged_signal_connect for fn(i8) { fn connect(self, sigthis: QToolBar_movableChanged_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 = QToolBar_movableChanged_signal_connect_cb_1 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QToolBar_SlotProxy_connect__ZN8QToolBar14movableChangedEb(arg0, arg1, arg2)}; } } impl /* trait */ QToolBar_movableChanged_signal_connect for Box<Fn(i8)> { fn connect(self, sigthis: QToolBar_movableChanged_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 = QToolBar_movableChanged_signal_connect_cb_box_1 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QToolBar_SlotProxy_connect__ZN8QToolBar14movableChangedEb(arg0, arg1, arg2)}; } } // visibilityChanged(_Bool) extern fn QToolBar_visibilityChanged_signal_connect_cb_2(rsfptr:fn(i8), arg0: c_char) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as i8; rsfptr(rsarg0); } extern fn QToolBar_visibilityChanged_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as i8; // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QToolBar_visibilityChanged_signal_connect for fn(i8) { fn connect(self, sigthis: QToolBar_visibilityChanged_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 = QToolBar_visibilityChanged_signal_connect_cb_2 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QToolBar_SlotProxy_connect__ZN8QToolBar17visibilityChangedEb(arg0, arg1, arg2)}; } } impl /* trait */ QToolBar_visibilityChanged_signal_connect for Box<Fn(i8)> { fn connect(self, sigthis: QToolBar_visibilityChanged_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 = QToolBar_visibilityChanged_signal_connect_cb_box_2 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QToolBar_SlotProxy_connect__ZN8QToolBar17visibilityChangedEb(arg0, arg1, arg2)}; } } // iconSizeChanged(const class QSize &) extern fn QToolBar_iconSizeChanged_signal_connect_cb_3(rsfptr:fn(QSize), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QSize::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QToolBar_iconSizeChanged_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn(QSize)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QSize::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QToolBar_iconSizeChanged_signal_connect for fn(QSize) { fn connect(self, sigthis: QToolBar_iconSizeChanged_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 = QToolBar_iconSizeChanged_signal_connect_cb_3 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QToolBar_SlotProxy_connect__ZN8QToolBar15iconSizeChangedERK5QSize(arg0, arg1, arg2)}; } } impl /* trait */ QToolBar_iconSizeChanged_signal_connect for Box<Fn(QSize)> { fn connect(self, sigthis: QToolBar_iconSizeChanged_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 = QToolBar_iconSizeChanged_signal_connect_cb_box_3 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QToolBar_SlotProxy_connect__ZN8QToolBar15iconSizeChangedERK5QSize(arg0, arg1, arg2)}; } } // topLevelChanged(_Bool) extern fn QToolBar_topLevelChanged_signal_connect_cb_4(rsfptr:fn(i8), arg0: c_char) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as i8; rsfptr(rsarg0); } extern fn QToolBar_topLevelChanged_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn(i8)>, arg0: c_char) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as i8; // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QToolBar_topLevelChanged_signal_connect for fn(i8) { fn connect(self, sigthis: QToolBar_topLevelChanged_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 = QToolBar_topLevelChanged_signal_connect_cb_4 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QToolBar_SlotProxy_connect__ZN8QToolBar15topLevelChangedEb(arg0, arg1, arg2)}; } } impl /* trait */ QToolBar_topLevelChanged_signal_connect for Box<Fn(i8)> { fn connect(self, sigthis: QToolBar_topLevelChanged_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 = QToolBar_topLevelChanged_signal_connect_cb_box_4 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QToolBar_SlotProxy_connect__ZN8QToolBar15topLevelChangedEb(arg0, arg1, arg2)}; } } // <= body block end
use crate::v0::support::{with_ipfs, MaybeTimeoutExt, StringError, StringSerialized}; use ipfs::{Cid, Ipfs, IpfsTypes, PeerId}; use serde::{Deserialize, Serialize}; use warp::{query, Filter, Rejection, Reply}; #[derive(Debug, Serialize)] #[serde(rename_all = "PascalCase")] struct Response { // blank extra: String, // blank #[serde(rename = "ID")] id: String, // the actual response responses: Vec<ResponsesMember>, // TODO: what's this? r#type: usize, } #[derive(Debug, Serialize)] #[serde(rename_all = "PascalCase")] struct ResponsesMember { // Multiaddrs addrs: Vec<String>, // PeerId #[serde(rename = "ID")] id: String, } #[derive(Debug, Deserialize)] pub struct FindPeerQuery { arg: StringSerialized<PeerId>, #[allow(unused)] // TODO: client sends verbose: Option<bool>, timeout: Option<StringSerialized<humantime::Duration>>, } async fn find_peer_query<T: IpfsTypes>( ipfs: Ipfs<T>, query: FindPeerQuery, ) -> Result<impl Reply, Rejection> { let FindPeerQuery { arg, verbose: _, timeout, } = query; let peer_id = arg.into_inner(); let addrs = ipfs .find_peer(peer_id) .maybe_timeout(timeout.map(StringSerialized::into_inner)) .await .map_err(StringError::from)? .map_err(StringError::from)? .into_iter() .map(|addr| addr.to_string()) .collect(); let id = peer_id.to_string(); let response = Response { extra: Default::default(), id: Default::default(), responses: vec![ResponsesMember { addrs, id }], r#type: 2, }; Ok(warp::reply::json(&response)) } pub fn find_peer<T: IpfsTypes>( ipfs: &Ipfs<T>, ) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone { with_ipfs(ipfs) .and(query::<FindPeerQuery>()) .and_then(find_peer_query) } #[derive(Debug, Deserialize)] pub struct FindProvidersQuery { arg: StringSerialized<Cid>, // FIXME: in go-ipfs this returns a lot of logs #[allow(unused)] verbose: Option<bool>, #[serde(rename = "num-providers")] num_providers: Option<usize>, timeout: Option<StringSerialized<humantime::Duration>>, } async fn find_providers_query<T: IpfsTypes>( ipfs: Ipfs<T>, query: FindProvidersQuery, ) -> Result<impl Reply, Rejection> { let FindProvidersQuery { arg, verbose: _, num_providers, timeout, } = query; let cid = arg.into_inner(); let providers = ipfs .get_providers(cid) .maybe_timeout(timeout.map(StringSerialized::into_inner)) .await .map_err(StringError::from)? .map_err(StringError::from)? .into_iter() .take(if let Some(n) = num_providers { n } else { 20 }) .map(|peer_id| ResponsesMember { addrs: vec![], id: peer_id.to_string(), }) .collect(); // FIXME: go-ipfs returns just a list of PeerIds let response = Response { extra: Default::default(), id: Default::default(), responses: providers, r#type: 2, }; Ok(warp::reply::json(&response)) } pub fn find_providers<T: IpfsTypes>( ipfs: &Ipfs<T>, ) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone { with_ipfs(ipfs) .and(query::<FindProvidersQuery>()) .and_then(find_providers_query) } #[derive(Debug, Deserialize)] pub struct ProvideQuery { arg: StringSerialized<Cid>, // FIXME: in go-ipfs this returns a lot of logs #[allow(unused)] verbose: Option<bool>, timeout: Option<StringSerialized<humantime::Duration>>, } async fn provide_query<T: IpfsTypes>( ipfs: Ipfs<T>, query: ProvideQuery, ) -> Result<impl Reply, Rejection> { let ProvideQuery { arg, verbose: _, timeout, } = query; let cid = arg.into_inner(); ipfs.provide(cid.clone()) .maybe_timeout(timeout.map(StringSerialized::into_inner)) .await .map_err(StringError::from)? .map_err(StringError::from)?; let response = Response { extra: Default::default(), id: cid.to_string(), responses: vec![], r#type: 2, }; Ok(warp::reply::json(&response)) } pub fn provide<T: IpfsTypes>( ipfs: &Ipfs<T>, ) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone { with_ipfs(ipfs) .and(query::<ProvideQuery>()) .and_then(provide_query) } #[derive(Debug, Deserialize)] pub struct GetClosestPeersQuery { arg: StringSerialized<PeerId>, // FIXME: in go-ipfs this returns a lot of logs #[allow(unused)] verbose: Option<bool>, timeout: Option<StringSerialized<humantime::Duration>>, } async fn get_closest_peers_query<T: IpfsTypes>( ipfs: Ipfs<T>, query: GetClosestPeersQuery, ) -> Result<impl Reply, Rejection> { let GetClosestPeersQuery { arg, verbose: _, timeout, } = query; let peer_id = arg.into_inner(); let closest_peers = ipfs .get_closest_peers(peer_id) .maybe_timeout(timeout.map(StringSerialized::into_inner)) .await .map_err(StringError::from)? .map_err(StringError::from)? .into_iter() .map(|peer_id| ResponsesMember { addrs: vec![], id: peer_id.to_string(), }) .collect(); // FIXME: go-ipfs returns just a list of PeerIds let response = Response { extra: Default::default(), id: peer_id.to_string(), responses: closest_peers, r#type: 2, }; Ok(warp::reply::json(&response)) } pub fn get_closest_peers<T: IpfsTypes>( ipfs: &Ipfs<T>, ) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone { with_ipfs(ipfs) .and(query::<GetClosestPeersQuery>()) .and_then(get_closest_peers_query) }
fn main() { //基本类型有四种,整型,浮点型,布尔型,字符型 //整型 默认给的是i32 //有符号 i8,i16,i32,i64,isize //无符号 u8,u16,u32,u64,usize let x = 0b111_000;//二进制 println!("二进制表示 {}", x); let x = 0o77;//八进制 println!("八进制表示 {}", x); let x = 0xff;//十六进制 println!("十六进制表示 {}", x); //溢出的情况,在编译期就给你报错 // let x: i8 = 256; // println!(" {}", x); //浮点型 f32,f64,默认给的是f64 let y = 3.14159; println!("浮点型 {}", y); //布尔型 true,false let a = true; let b = false; println!("布尔型 {},{}", a, b); //字符型 let c = 'z'; println!("字符型 {}", c); //============================ //复合类型 元组、数组 let tup = ('c', 3.14, 3); println!("元组 {:?}", tup); let array = [34, 4, 2, 4, 5]; for value in array.iter() { println!("数组 value={}", value); } //两个数值交换 let (a, b) = (10, 20); let (b, a) = (a, b); println!("a={},b={}", a, b); }
#[macro_use] extern crate clap; extern crate colored; extern crate tdo_core; extern crate tdo_export; #[macro_use] mod macros; mod cli; mod filesystem; use std::env; use colored::*; use clap::Shell; mod subcommands; use std::process::exit; use tdo_core::{tdo, error}; static TDO_MIN_LEN: u32 = 5; #[allow(unused_variables)] fn main() { let app = cli::cli().get_matches(); let save_path = match env::home_dir() { Some(path) => path.join(".tdo/list.json"), None => { errorprint!("You seem to have no home directory. Unfortunately this is required \ in order to use tdo."); exit(1); } }; let mut tdo: tdo::Tdo = match tdo::Tdo::load(save_path.to_str().unwrap()) { Ok(loaded) => loaded, Err(error::Error(error::ErrorKind::StorageError( error::storage_error::ErrorKind::FileNotFound), _)) => tdo::Tdo::new(), Err(error::Error(error::ErrorKind::StorageError( error::storage_error::ErrorKind::FileCorrupted), _)) => { errorprint!("The saved JSON could not be parsed."); errorprint!("Please fix the saved json file manually or delete it to continue."); exit(1); } Err(error::Error(error::ErrorKind::StorageError( error::storage_error::ErrorKind::UnableToConvert), _)) => { errorprint!("The File could not be converted to the new version automatically."); errorprint!("Please fix the saved json file manually or delete it to continue."); exit(1); } Err(e) => { println!("{:?}", e); panic!(); } }; match app.subcommand { None => { match app.value_of("task") { Some(task_string) => { if task_string.len() >= TDO_MIN_LEN as usize { subcommands::add(&mut tdo, task_string, app.value_of("list")); } else { errorprint!(format!("The todo has to be at least {} characters long.", TDO_MIN_LEN)); println!("If you want to add a todo with less than {} characters use `tdo \ add` instead", TDO_MIN_LEN) } } None => subcommands::print_out(&tdo, false), } } Some(_) => { match app.subcommand() { ("all", Some(_)) => subcommands::print_out(&tdo, true), ("add", Some(sub_m)) => { let task_string = sub_m.value_of("task").unwrap(); subcommands::add(&mut tdo, task_string, sub_m.value_of("list")); } ("edit", Some(sub_m)) => { let id: u32 = match sub_m.value_of("id").unwrap().parse() { Ok(id) => id, Err(_) => { errorprint!("id must be va valid integer."); exit(1); } }; subcommands::edit(&mut tdo, id); } ("done", Some(sub_m)) => { let id: u32 = match sub_m.value_of("id").unwrap().parse() { Ok(id) => id, Err(_) => { errorprint!("id must be va valid integer."); exit(1); } }; subcommands::done(&mut tdo, id); } ("newlist", Some(sub_m)) => { let new_list = match sub_m.value_of("listname") { Some(name) => name, None => { errorprint!("listname could not be parsed."); exit(1); } }; subcommands::newlist(&mut tdo, new_list); } ("move", Some(sub_m)) => { let id: u32 = match sub_m.value_of("id").unwrap().parse() { Ok(id) => id, Err(_) => { errorprint!("id must be va valid integer."); exit(1); } }; subcommands::move_todo(&mut tdo, id, sub_m.value_of("listname").unwrap()); } ("remove", Some(sub_m)) => { let list_name = match sub_m.value_of("listname") { Some(name) => name, None => { errorprint!("listname could not be parsed."); exit(1); } }; subcommands::remove(&mut tdo, list_name); } ("completions", Some(sub_m)) => { if let Some(shell) = sub_m.value_of("shell") { cli::cli().gen_completions_to("tdo", shell.parse::<Shell>().unwrap(), &mut std::io::stdout()); } } ("github", Some(sub_m)) => { match sub_m.subcommand { None => { let repo = sub_m.value_of("repository").unwrap(); let title = sub_m.value_of("title").unwrap(); subcommands::github(&mut tdo, repo, title, sub_m.value_of("body")); } Some(_) => { match sub_m.subcommand() { ("set", Some(subs)) => { subcommands::github_set(&mut tdo, subs.value_of("token")) } ("update", _) => subcommands::github_update(&mut tdo), _ => println!("{:?}", sub_m), } } } } ("clean", Some(sub_m)) => subcommands::clean(&mut tdo, sub_m.value_of("listname")), ("lists", Some(_)) => subcommands::lists(&tdo), ("export", Some(sub_m)) => { let filepath = match sub_m.value_of("destination") { Some(path) => path, None => { errorprint!("destination could not be parsed"); exit(1); } }; subcommands::export(&tdo, filepath, sub_m.is_present("undone")); } ("reset", Some(_)) => { match subcommands::reset(&mut tdo) { Some(x) => tdo = x, None => {} } } _ => println!("{}", app.usage()), } } } let target = match filesystem::validate_target_file(save_path.to_str().unwrap()) { Ok(path) => path, Err(e) => { errorprint!(e); return; } }; match tdo.save(target.to_str().unwrap()) { Err(e) => errorprint!(e), _ => {} } }