text
stringlengths
8
4.13M
use {Request, Response}; use super::codec::{Codec, Encoder, Decode, Encode}; use {http, h2}; use futures::{Future, Stream, Poll, Async}; use tower::Service; use tower_h2::RecvBody; /// A bidirectional streaming gRPC service. #[derive(Debug, Clone)] pub struct Grpc<T, C> { inner: T, codec: C, } #[derive(Debug)] pub struct ResponseFuture<T, E> { inner: T, encoder: Option<E>, } // ===== impl Grpc ===== impl<T, C, S> Grpc<T, C> where T: Service<Request = Request<Decode<C::Decoder>>, Response = Response<S>, Error = ::Error>, C: Codec, S: Stream<Item = C::Encode>, { pub fn new(inner: T, codec: C) -> Self { Grpc { inner, codec, } } } impl<T, C, S> Service for Grpc<T, C> where T: Service<Request = Request<Decode<C::Decoder>>, Response = Response<S>, Error = ::Error>, C: Codec, S: Stream<Item = C::Encode>, { type Request = http::Request<RecvBody>; type Response = http::Response<Encode<S, C::Encoder>>; type Error = h2::Error; type Future = ResponseFuture<T::Future, C::Encoder>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.inner.poll_ready().map_err(|_| unimplemented!()) } fn call(&mut self, request: Self::Request) -> Self::Future { // Map the request body let (head, body) = request.into_parts(); // Wrap the body stream with a decoder let body = Decode::new(body, self.codec.decoder()); // Reconstruct the HTTP request let request = http::Request::from_parts(head, body); // Convert the HTTP request to a gRPC request let request = Request::from_http(request); // Send the request to the inner service let inner = self.inner.call(request); // Return the response ResponseFuture { inner, encoder: Some(self.codec.encoder()), } } } // ===== impl ResponseFuture ===== impl<T, E, S> Future for ResponseFuture<T, E> where T: Future<Item = Response<S>, Error = ::Error>, E: Encoder, S: Stream<Item = E::Item>, { type Item = http::Response<Encode<S, E>>; type Error = h2::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { // Get the gRPC response let response = match self.inner.poll() { Ok(Async::Ready(response)) => response, Ok(Async::NotReady) => return Ok(Async::NotReady), Err(e) => { match e { ::Error::Grpc(status) => { let response = Response::new(Encode::error(status)); return Ok(response.into_http().into()); } // TODO: Is this correct? _ => return Err(h2::Reason::INTERNAL_ERROR.into()), } } }; // Convert to an HTTP response let response = response.into_http(); // Map the response body let (head, body) = response.into_parts(); // Get the encoder let encoder = self.encoder.take().expect("encoder consumed"); // Encode the body let body = Encode::new(body, encoder); // Success Ok(http::Response::from_parts(head, body).into()) } }
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #![allow(non_snake_case)] extern crate astro; use astro::*; #[test] fn ecc_anom() { let ecc_anom = orbit::elliptic::ecc_anom(5_f64.to_radians(), 0.1, 0.0000001); assert_eq!(util::round_upto_digits(ecc_anom.to_degrees(), 6), 5.554589); } #[test] fn vel() { let a = 17.9400782; let e = 0.96727426; let (vel_p, vel_a) = (orbit::elliptic::perih_vel(a, e), orbit::elliptic::aph_vel(a, e)); assert_eq!(util::round_upto_digits(vel_p, 2), 54.52); assert_eq!(util::round_upto_digits(vel_a, 2), 0.91); let V = orbit::elliptic::vel(1.0, a); assert_eq!(util::round_upto_digits(V, 2), 41.53); } #[test] fn passage_through_nodes() { let T = time::julian_day ( &time::Date{ year : 1986, month : time::Month::Feb, decimal_day : 9.45891, cal_type : time::CalType::Gregorian } ); let w = 111.84644_f64.to_radians(); let e = 0.96727426; let n = 0.01297082_f64.to_radians(); let a = 17.9400782; let (ascen, r_a) = orbit::elliptic::passage_through_node ( w, n, a, e, T, &orbit::Node::Ascend ); assert_eq!(util::round_upto_digits((T - ascen), 4), 92.2998); assert_eq!(util::round_upto_digits(r_a, 4), 1.8045); let (descend, r_b) = orbit::elliptic::passage_through_node ( w, n, a, e, T, &orbit::Node::Descend ); assert_eq!(util::round_upto_digits((T - descend), 4), -28.9105); assert_eq!(util::round_upto_digits(r_b, 4), 0.8493); }
// Neg The unary negation operator -. use crate::integer::Integer; use core::ops::Neg; impl Neg for Integer { type Output = Integer; fn neg(self) -> Self::Output { self.negate() } } impl Neg for &Integer { type Output = Integer; fn neg(self) -> Self::Output { self.negate() } }
use super::*; use serde::Deserialize; #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] struct MyData { id: u32, data: u32, } impl Entity<u32> for MyData { fn get_id(&self) -> u32 { self.id } } #[test] fn should_be_able_to_save_and_read() { // given let mut storage = SqliteStorage::new(":memory:").unwrap(); let entity = MyData { id: 42, data: 24 }; // when storage.save(&entity).unwrap(); let read_entity = storage.find_by_id(&42).unwrap(); // then assert_eq!(entity, read_entity); } #[test] fn should_result_in_an_error_when_searching_for_unset_key() { // given let mut storage = SqliteStorage::new(":memory:").unwrap(); // when let result: Result<MyData> = storage.find_by_id(&42); // then match result { Err(Error::NotFound(id)) => assert_eq!("42", id), _ => assert!(false, "Invalid result!"), }; } #[test] fn should_overwrite_values_upon_save() { // given let mut storage = SqliteStorage::new(":memory:").unwrap(); let entity = MyData { id: 42, data: 24 }; storage.save(&entity).unwrap(); // when let updated_entity = MyData { id: 42, data: 100 }; storage.save(&updated_entity).unwrap(); // then let loaded = storage.find_by_id(&42).unwrap(); assert_eq!(updated_entity, loaded); } #[test] fn should_find_with_pagination() { // given let mut storage = SqliteStorage::new(":memory:").unwrap(); let a = MyData { id: 42, data: 24 }; let b = MyData { id: 53, data: 35 }; let c = MyData { id: 64, data: 46 }; storage.save(&a).unwrap(); storage.save(&b).unwrap(); storage.save(&c).unwrap(); // when let first = storage.find_all_with_page(&Page::new(0, 1)).unwrap(); let second = storage.find_all_with_page(&Page::new(1, 2)).unwrap(); let third = storage.find_all_with_page(&Page::new(0, 3)).unwrap(); // then assert_eq!(vec![a.clone()], first); assert_eq!(vec![c.clone()], second); assert_eq!(vec![a, b, c], third); } #[test] fn should_delete_entry_by_id() { // given a storage with one entity let mut storage = SqliteStorage::new(":memory:").unwrap(); let entity = MyData { id: 42, data: 24 }; storage.save(&entity).unwrap(); // when removing by id <SqliteStorage as Delete<u32, MyData>>::remove_by_id(&mut storage, &entity.id).unwrap(); // then entity should be removed match <SqliteStorage as Read<u32, MyData>>::find_by_id(&mut storage, &42u32) { Ok(_) => panic!("Entity shouldn't be in storage"), Err(_) => assert!(true), } }
use crate::widget::{soft_label, titled_panel}; use druid::{ widget::{CrossAxisAlignment, Flex, MainAxisAlignment, TextBox, Controller}, Data, Lens, Widget, WidgetExt, Env, EventCtx, Event, }; #[derive(Clone, Data, Lens, Default)] pub struct Base64State { plaintext: String, base64: String, mode: usize, } struct Base64Controller; impl<W: Widget<Base64State>> Controller<Base64State, W> for Base64Controller { fn event(&mut self, child: &mut W, ctx: &mut EventCtx, event: &Event, data: &mut Base64State, env: &Env) { let old_plain = data.plaintext.clone(); let old_base64 = data.base64.clone(); child.event(ctx, event, data, env); if data.plaintext != old_plain { data.base64 = base64::encode(&data.plaintext); return; } else if data.base64 != old_base64 { data.plaintext = base64::decode(&data.base64).ok().map(|vec| String::from_utf8(vec).ok()).flatten().unwrap_or_else(|| String::from("Invalid")); } } } pub fn build_base64_widget() -> impl Widget<Base64State> { let plaintext = Flex::column() .with_child(soft_label("PLAINTEXT")) .with_child(TextBox::new().lens(Base64State::plaintext).expand_width()); let base64 = Flex::column() .with_child(soft_label("BASE64")) .with_child(TextBox::new().lens(Base64State::base64).expand_width()); let column = Flex::column() .main_axis_alignment(MainAxisAlignment::Center) .cross_axis_alignment(CrossAxisAlignment::Center) .with_child(plaintext) .with_spacer(2.0) .with_child(base64) .expand_height(); titled_panel( "Base64", " - Transforms text into its Base64 representation.", column, ).controller(Base64Controller) }
pub mod config_define; pub use self::config_define::{Config, Metadata}; use serde_json; use serde_yaml; use std::fs::File; use std::io::BufReader; use std::io::Read; pub fn load(path: &str, op: &str) -> Config { assert!(!path.is_empty()); assert!(!op.is_empty()); let file = File::open(path).expect("Unable to open file"); let mut buf_reader = BufReader::new(file); let mut contents = String::new(); buf_reader .read_to_string(&mut contents) .expect("Unable to read file"); let v: Vec<&str> = path.split(".").collect(); let ext = v[v.len() - 1].to_string(); let mut config: Config = match ext.to_ascii_lowercase().as_str() { "json" => { let conf: Config = serde_json::from_str(&contents).unwrap(); conf } "yml" | "yaml" => { let conf: Config = serde_yaml::from_str(&contents).unwrap(); conf } _ => { panic!("cannot load {} file", path); } }; let mut meta = config.get_metadata(); meta.set_operation(op.to_ascii_lowercase()); config.muted_with_metadata(meta).validate(); config }
use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use syn::token::{Colon, Pub}; use syn::{ parenthesized, parse::{Parse, ParseStream, Result}, parse_quote, Expr, Field, Fields, Ident, ItemStruct, Token, Type, VisPublic, Visibility, }; #[derive(Clone, Debug, PartialEq)] pub(crate) struct MachineContext { context_type: Type, } impl Parse for MachineContext { /// example machine context: /// /// ```text /// Context = Machine; /// ``` fn parse(input: ParseStream<'_>) -> Result<Self> { /// Context = Machine; /// _______ let context_magic: Ident = Ident::parse(input)?; /// Context = Machine; /// _ let _: Token![=] = input.parse()?; /// Context = Machine; /// _______ let context_type: Type = Type::parse(input)?; /// Context = Machine; /// _ let _: Token![;] = input.parse()?; Ok(MachineContext { context_type }) } } impl MachineContext { pub fn context_type(&self) -> Type { self.context_type.clone() } } #[cfg(test)] mod tests { use super::*; use quote::quote; use syn::{parse2, parse_quote}; #[test] fn test_initial_state_parse() { let _: MachineContext = parse2(quote! { pub struct FSM { str: String } }) .unwrap(); } }
use cw::{Crosswords, Range}; use cw::PointIter; /// An iterator over the characters in a particular range in a crosswords grid. pub struct RangeIter<'a> { pi: PointIter, cw: &'a Crosswords, } impl<'a> RangeIter<'a> { /// Creates an iterator over the characters in the given range. pub fn new(range: Range, cw: &'a Crosswords) -> RangeIter<'a> { RangeIter { pi: range.points(), cw: cw, } } } impl<'a> Iterator for RangeIter<'a> { type Item = char; fn next(&mut self) -> Option<char> { self.pi.next().and_then(|point| self.cw.get_char(point)) } fn size_hint(&self) -> (usize, Option<usize>) { self.pi.size_hint() } }
extern crate ggez; extern crate rustic; extern crate tiled; use ggez::graphics::Rect; use rustic::application::*; use rustic::resources::*; use rustic::sop::*; use rustic::storyboard::*; fn main() { let mut builder = ApplicationBuilder::new("map", "rustic"); builder.stories(vec![ Story::Setup(Box::new(|ctx| { let state = &mut *ctx.state.borrow_mut(); let world = &mut state.world.specs_world; add_sprite_map_resource(world); add_camera_resource(world, Rect::new(0.0, 0.0, 800.0, 600.0)); add_map_resource(world); Story::Done("Setup".to_owned()) })), create_scene("/dungeon/map_jail.tmx"), move_camera_to_tile(43, 15, 3.0), quit_state(), ]); let app = builder.build(); app.run(); }
// Copyright 2019. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use crate::{chain_storage::BlockchainBackend, validation::error::ValidationError}; pub type Validator<T, B> = Box<dyn Validation<T, B>>; pub type StatelessValidator<T> = Box<dyn StatelessValidation<T>>; /// The core validation trait. Multiple `Validation` implementors can be chained together in a [ValidatorPipeline] to /// provide consensus validation for blocks, transactions, or DAN instructions. Implementors only need to implement /// the methods that are relevant for the pipeline, since the default implementation always passes. pub trait Validation<T, B>: Send + Sync where B: BlockchainBackend { /// General validation code that can run independent of external state fn validate(&self, item: &T, db: &B) -> Result<(), ValidationError>; } /// Stateless version of the core validation trait. pub trait StatelessValidation<T>: Send + Sync { /// General validation code that can run independent of external state fn validate(&self, item: &T) -> Result<(), ValidationError>; }
#![allow(clippy::comparison_chain)] #![allow(clippy::collapsible_if)] use std::borrow::Borrow; use std::cmp::Reverse; use std::cmp::{max, min}; use std::collections::{BTreeSet, HashMap, HashSet}; use itertools::Itertools; use whiteread::parse_line; const ten97: usize = 1000_000_007; /// 2の逆元 mod ten97.割りたいときに使う const inv2ten97: u128 = 500_000_004; fn main() { let (l, q): (isize, isize) = parse_line().unwrap(); let mut bts = BTreeSet::new(); bts.insert(0); bts.insert(l); for _ in 0..q { let (c, x): (usize, isize) = parse_line().unwrap(); if c == 1 { bts.insert(x); } else { let l = bts.range(..x).next_back().unwrap(); let r = bts.range(x..).next().unwrap(); println!("{}", r - l); } } }
//! Synchronization primitives and utilities based on intrusive collections. //! //! This crate provides a variety of `Futures`-based and `async/await` compatible //! types that are based on the idea of intrusive collections: //! - Channels in a variety of flavors: //! - Oneshot //! - Multi-Producer Multi-Consumer (MPMC) //! - State Broadcast //! - Synchronization Primitives: //! - Manual Reset Event //! - Mutex //! - Semaphore //! - A timer //! //! ## Intrusive collections? //! //! In an intrusive collection, the elements that want to get stored inside the //! collection are-providing the means to store themselves inside the collection. //! E.g. in an intrusive linked list, each element that gets stored inside the //! list contains pointer field that points to the next list element. E.g. //! //! ``` //! // The element which is intended to be stored inside an intrusive container //! struct ListElement { //! data: u32, //! next: *mut ListElement, //! } //! //! // The intrusive container //! struct List { //! head: *mut ListElement, //! } //! ``` //! //! The advantage here is that the intrusive collection (here: the list) requires //! only a fixed amount of memory. In this case it only needs a pointer to the //! first element. //! //! The list container itself has a fixed size of a single pointer, independent //! of the number of stored elements. //! //! Intrusive lists are often used low-level code like in operating system kernels. //! E.g. they can be used for storing elements that represent threads that are //! blocked and waiting on queue. //! In that case the stored elements can be on the call-stack of the //! caller of each blocked thread, since the call-stack won't change as long as //! the thread is blocked. //! //! ### Application in Futures //! //! This library brings this idea into the world of Rusts `Future`s. Due to the //! addition of `Pin`ning, the address of a certain `Future` is not allowed to //! change between the first call to `poll()` until the `Future` is dropped. //! This means the data inside the `Future` itself can be inserted into an //! intrusive container. If the the call to `Future::poll()` is not immedately //! ready, some parts of the `Future` itself are registered at the type which //! yielded the `Future`. Each `Future` can store a `Waker`. When the original //! type gets ready, it can iterate through the list of registered `Future`s, //! wakeup associated tasks, and potentially remove them from it's queue. //! //! The result is that the future-yielding type is not required to copy an //! arbitrary amount of `Waker` objects into itself, and thereby does not require //! dynamic memory for this task. //! //! When a `Future` gets destructed/dropped, it must make sure to remove itself //! from any collections that refer to it, to avoid invalid memory accesses. //! //! This library implements common synchronization primitives for the usage in //! asychronous code based on this concept. //! //! The implementation requires the usage of a fair chunk of of `unsafe` //! annotations. However the provided user-level API is intended to be fully safe. //! //! ## Features of this library //! //! The following types are currently implemented: //! - Channels (oneshot and multi-producer-multi-consumer) //! - Synchronization primitives (async mutexes and events) //! - Timers //! //! ## Design goals for the library //! //! - Providing implementations of common synchronization primitives in a //! platform independent fashion. //! - Support for `no-std` environments. As many types as possible are also //! provided for `no-std` environments. The library should boost the ability //! to use async Rust code in environments like //! - Microcontrollers (RTOS and bare-metal) //! - Kernels //! - Drivers //! - Avoidance of dynamic memory allocations during runtime. //! After objects from this library have been created, they should not require //! the allocation of any further memory during runtime. //! E.g. they should not require to allocate memory for each call to an //! asynchronous function, or each time a new task accesses the same object //! in parallel. //! - Familiar APIs. //! The library tries to mimic the APIs of existing Rust libraries like the //! standard library and and `futures-rs` as closely as possible. //! //! ## Non goals //! //! - Providing IO primitives (like) sockets, or platform specific implementations //! - Reaching the highest possible performance in terms of throughput and latency. //! While code inside this library is optimized for performance, portability //! and deterministic memory usage are more important goals. //! - Providing future wrappers for platform-specific APIs. //! //! ## Local, Non-local and shared flavors //! //! The library provides types in a variety of flavors: //! //! - A local flavor (e.g. [`channel::LocalChannel`]) //! - A non-local flavor (e.g. [`channel::Channel`]) //! - A shared flavor (e.g. [`channel::shared::Sender`]) //! - A generic flavor (e.g. [`channel::GenericChannel`] and //! [`channel::shared::GenericSender`]) //! //! The difference between the types lie in their thread-safety. The non-local //! flavors of types can be accessed from multiple threads (and thereby also //! futures tasks) concurrently. This means they implement the `Sync` trait in //! addition to the `Send` trait. //! The local flavors only implement the `Send` trait. //! //! ### Local flavor //! //! The local flavors will require no internal synchronization (e.g. internal //! Mutexes) and can therefore be provided for all platforms (including `no-std`). //! Due the lack of required synchronization, they are also very fast. //! //! It might seem counter-intuitive to provide synchronization primitives that //! only work within a single task. However there is a variety of applications //! where those can be used to coordinate sub-tasks (futures that are polled on //! a single task concurrently). //! //! The following example demonstrates this use-case: //! //! ``` //! # use futures::join; //! # use futures_intrusive::sync::LocalManualResetEvent; //! async fn async_fn() { //! let event = LocalManualResetEvent::new(false); //! let task_a = async { //! // Wait for the event //! event.wait().await; //! // Do something with the knowledge that task_b reached a certain state //! }; //! let task_b = async { //! // Some complex asynchronous workflow here //! // ... //! // Signal task_a //! event.set(); //! }; //! join!(task_a, task_b); //! } //! ``` //! //! ### Non-local flavor //! //! The non-local flavors can be used between arbitrary tasks and threads. //! They use internal synchronization for this in form of an embedded `Mutex` in //! the form of a [`parking_lot::Mutex`] type. //! //! The non-local flavors are only available in `std` environments. //! //! ### Shared flavor //! //! For some types also a shared flavor of the type is provided. Non-local //! flavors of types are `Sync`, but still can only be shared by reference //! between various tasks. //! Shared flavors are also `Sync`, but the types do also implement the `Clone` //! trait, which allows to duplicate the object, and pass the ownership of it //! to a different task. These types allow to avoid references (and thereby //! lifetimes) in some scenarios, which makes them more convenient to use. //! The types also return `Future`s which do not have an associated lifetime. //! This allows to use those types as implementations of traits, without the //! need for generic associated types (GATs). //! //! Due to the requirement of atomic reference counting, those types are //! currently only available for `std` environments. //! //! ### Generic flavor //! //! The generic flavors of provided types are parameterized around a //! [`lock_api::RawMutex`] type. The form the base for the non-local and shared //! flavors, which just parameterize the generic flavor in either a non //! thread-safe or thread-safe fashion. //! //! Users have the opportunity to directly make use generic flavors, in order to //! adapt the provided thread-safe types for the use in `no-std` environments. //! //! E.g. by providing a custom [`lock_api::RawMutex`] //! implementation, the following platforms can be supported: //! //! - For RTOS platform, RTOS-specific mutexes can be wrapped. //! - For Kernel development, spinlock based mutexes can be created. //! - For embedded development, mutexes which just disable interrupts can be //! utilized. //! //! //! ## Relation to types in other libraries //! //! Other libraries (e.g. `futures-rs` and `tokio`) are already providing //! a lot of primitives that are comparable feature-wise to the types in this //! library. //! //! The most important differences are: //! - This library has a bigger focus on `no-std` environments, and does not //! only try to provide an implementation for `std`. //! - The types in this library do not require dynamic memory allocation for //! waking up an arbitrary amount of tasks that are waiting on a particular //! `Future`. Other libraries typically require heap-allocated nodes for //! growing vectors for handling a varying amount of tasks. //! - The `Future`s produced by this library are all `!Unpin`, which might make //! them less ergonomic to use. //! #![cfg_attr(not(feature = "std"), no_std)] #![warn(missing_docs, missing_debug_implementations)] #![deny(bare_trait_objects)] mod noop_lock; use noop_lock::NoopLock; pub mod buffer; mod intrusive_singly_linked_list; #[allow(dead_code)] mod intrusive_double_linked_list; pub mod sync; pub mod channel; pub mod timer;
use crate::components; use crate::game::{MAP_HEIGHT, MAP_WIDTH}; pub fn create_entities_from_map( world: &mut legion::World, map: Vec<(components::Position, &str)>, ) -> ggez::GameResult { for (position, val) in map { if position.x >= MAP_WIDTH || position.y > MAP_HEIGHT { return Err(ggez::GameError::ResourceLoadError( "Could not load game map!".to_string(), )); } match val { // blue box "BB" => { create_floor(world, position); create_box(world, position, components::BoxColor::Blue); } // red box "RB" => { create_floor(world, position); create_box(world, position, components::BoxColor::Red); } // blue box destination "BS" => { create_floor(world, position); create_box_spot(world, position, components::BoxColor::Blue); } // red box destination "RS" => { create_floor(world, position); create_box_spot(world, position, components::BoxColor::Red); } // player initial position "P" => { create_floor(world, position); create_player(world, position); } // wall "W" => { create_wall(world, position); } // no item "." => { create_floor(world, position); } // empty space "N" => {} // unknown c => panic!("Invalid map item {}", c), } } Ok(()) } pub fn create_player(world: &mut legion::World, pos: components::Position) -> legion::Entity { world.push(( components::Player, components::Movable, components::Position { z: 10, ..pos }, components::Renderable::new_animated(vec![ "/images/player_1.png".to_string(), "/images/player_2.png".to_string(), "/images/player_3.png".to_string(), ]), )) } pub fn create_box( world: &mut legion::World, pos: components::Position, color: components::BoxColor, ) -> legion::Entity { let paths = match color { components::BoxColor::Red => vec![ "/images/box_red_1.png".to_string(), "/images/box_red_2.png".to_string(), ], components::BoxColor::Blue => vec![ "/images/box_blue_1.png".to_string(), "/images/box_blue_2.png".to_string(), ], }; world.push(( components::Box { color }, components::Movable, components::Position { z: 10, ..pos }, components::Renderable::new_animated(paths), )) } pub fn create_wall(world: &mut legion::World, pos: components::Position) -> legion::Entity { world.push(( components::Wall, components::Immovable, components::Position { z: 10, ..pos }, components::Renderable::new_static("/images/wall.png".to_string()), )) } pub fn create_box_spot( world: &mut legion::World, pos: components::Position, color: components::BoxColor, ) -> legion::Entity { let path = match color { components::BoxColor::Red => "/images/box_spot_red.png".to_string(), components::BoxColor::Blue => "/images/box_spot_blue.png".to_string(), }; world.push(( components::BoxSpot { color }, components::Position { z: 9, ..pos }, components::Renderable::new_static(path), )) } pub fn create_floor(world: &mut legion::World, floor_pos: components::Position) -> legion::Entity { world.push(( components::Position { z: 5, ..floor_pos }, components::Renderable::new_static("/images/floor.png".to_string()), )) }
//! A Quantity has a magnitude and a dimension. use super::*; use std::cmp::{Ordering, PartialOrd}; use std::fmt; use std::ops::{DivAssign, MulAssign}; #[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct Quantity<T> { /// The magnitude of this quantity (compared to the base units) magnitude: T, /// The dimension of this quantity dimension: Dimension, } impl<T> Quantity<T> { pub fn new(magnitude: T, dimension: Dimension) -> Self { Quantity { magnitude, dimension, } } #[inline] pub fn magnitude(&self) -> T where T: Clone, { self.magnitude.clone() } #[inline] pub fn borrow_magnitude(&self) -> &T { &self.magnitude } #[inline] pub fn dimension(&self) -> Dimension { self.dimension } pub fn cast<U>(self) -> Quantity<U> where U: From<T>, { Quantity { magnitude: self.magnitude.into(), dimension: self.dimension, } } pub fn raise(&mut self, power: i8) where T: Clone + Div<T, Output = T> + From<i32> + MulAssign, { self.dimension.raise(power); let mut tmp: T = 1.into(); if power < 0 { self.magnitude = tmp.clone() / self.magnitude.clone(); } std::mem::swap(&mut self.magnitude, &mut tmp); let mut i = power.abs(); while i > 0 { self.magnitude *= tmp.clone(); i -= 1; } } #[inline] pub fn raised(&self, power: i8) -> Quantity<T> where T: Clone + Div<T, Output = T> + From<i32> + MulAssign, { let mut r = self.clone(); r.raise(power); r } pub fn invert(&mut self) where T: Clone + Div<T, Output = T> + From<i32> + MulAssign, { self.raise(-1) } #[inline] pub fn inverted(&self) -> Quantity<T> where T: Clone + Div<T, Output = T> + From<i32> + MulAssign, { self.raised(-1) } #[inline] pub fn abs(&self) -> Quantity<T> where T: Clone + From<i32> + MulAssign + PartialOrd, { let mut r = self.clone(); if r.magnitude < 0.into() { r.magnitude *= (-1).into(); } r } } impl<T> Mul<Quantity<T>> for f64 where T: Clone + From<f64> + Mul<T, Output = T>, { type Output = Quantity<T>; fn mul(self, mut rhs: Quantity<T>) -> Quantity<T> { let lhs: T = self.into(); rhs.magnitude = lhs * rhs.magnitude.clone(); rhs } } impl<T> Mul<Quantity<T>> for i32 where T: Clone + From<i32> + Mul<T, Output = T>, { type Output = Quantity<T>; fn mul(self, mut rhs: Quantity<T>) -> Quantity<T> { let lhs: T = self.into(); rhs.magnitude = lhs * rhs.magnitude.clone(); rhs } } /// # Panic /// Both self and rhs must have a standard dimension, otherwise this operation will panic. impl<T> Mul<Quantity<T>> for Quantity<T> where T: Mul<T, Output = T>, { type Output = Quantity<T>; fn mul(self, rhs: Quantity<T>) -> Quantity<T> { Quantity { magnitude: self.magnitude * rhs.magnitude, dimension: self.dimension * rhs.dimension, } } } /// # Panic /// Both self and rhs must have a standard dimension, otherwise this operation will panic. impl<T> Mul<Dimension> for Quantity<T> { type Output = Quantity<T>; fn mul(self, rhs: Dimension) -> Quantity<T> { Quantity { magnitude: self.magnitude, dimension: self.dimension * rhs, } } } impl<T, U> MulAssign<U> for Quantity<T> where T: MulAssign<T> + From<U>, { fn mul_assign(&mut self, rhs: U) { self.magnitude *= rhs.into(); } } impl<T> Div<f64> for Quantity<T> where T: Clone + From<f64> + Div<T, Output = T>, { type Output = Quantity<T>; fn div(mut self, rhs: f64) -> Quantity<T> { let rhs: T = rhs.into(); self.magnitude = self.magnitude / rhs; self } } impl<T> Div<i32> for Quantity<T> where T: Clone + From<i32> + Div<T, Output = T>, { type Output = Quantity<T>; fn div(mut self, rhs: i32) -> Quantity<T> { let rhs: T = rhs.into(); self.magnitude = self.magnitude / rhs; self } } /// # Panic /// Both self and rhs must have a standard dimension, otherwise this operation will panic. impl<T> Div<Quantity<T>> for Quantity<T> where T: Div<T, Output = T>, { type Output = Quantity<T>; fn div(self, rhs: Quantity<T>) -> Quantity<T> { Quantity { magnitude: self.magnitude / rhs.magnitude, dimension: self.dimension / rhs.dimension, } } } /// # Panic /// Both self and rhs must have a standard dimension, otherwise this operation will panic. impl<T: fmt::Display> Div<Dimension> for Quantity<T> { type Output = Quantity<T>; fn div(self, rhs: Dimension) -> Quantity<T> { Quantity { magnitude: self.magnitude, dimension: self.dimension / rhs, } } } impl<T, U> DivAssign<U> for Quantity<T> where T: DivAssign<T> + From<U>, { fn div_assign(&mut self, rhs: U) { self.magnitude /= rhs.into(); } } impl<T> PartialOrd for Quantity<T> where T: PartialOrd, { fn partial_cmp(&self, other: &Quantity<T>) -> Option<Ordering> { if self.dimension == other.dimension { self.magnitude.partial_cmp(&other.magnitude) } else { None } } } /* impl<T> PartialOrd<f64> for Quantity<T> where T: PartialOrd<f64>, { fn partial_cmp(&self, other: &f64) -> Option<Ordering> { if self.dimension == DIMLESS { self.magnitude.partial_cmp(&other) } else { None } } } */ impl<T> fmt::Display for Quantity<T> where T: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}{}", self.magnitude, self.dimension)?; Ok(()) } }
fn print_border(size: usize, l: char, m: char, r: char) { print!("{}", l); for _ in 0..(size-1) { print!("────{}", m); } println!("────{}", r); } pub fn print_square(size: usize, data: &[i32]) { print_border(size, '┌', '┬', '┐'); for y in 0..size { for x in 0..size { let c = data[y*size + x]; if c == 0 { print!("│ "); } else { print!("│{:3} ", c); } } print!("│\n"); if y < size - 1 { print_border(size, '├', '┼', '┤'); } else { print_border(size, '└', '┴', '┘'); } } }
use crate::apis::api_caller::ApiCaller; use crate::apis::flight_provider::flight_provider_request::FlightProviderRequest; use crate::apis::flight_provider::raw_models::flight_raw::FlightRaw; pub struct FlightProvider {} impl FlightProvider { pub fn new() -> Self { FlightProvider {} } pub async fn get(&self, request: FlightProviderRequest) { let url = Self::generate_url(request); let api_caller = ApiCaller::new(url); let raw_response = api_caller.get().await.unwrap(); let response = Self::parse_response(raw_response); } fn generate_url(request: FlightProviderRequest) -> String { format!( "https://data-live.flightradar24.com/clickhandler/\ ?version=1.5&flight={flight_id}", flight_id = request.flight_id ) } fn parse_response(raw_response: String) -> Option<FlightRaw> { let response: Option<FlightRaw> = serde_json::from_str(raw_response.as_str()).ok(); println!("{:?}", response); response } } #[cfg(test)] mod FlightProviderTests { use crate::apis::flight_provider::flight_provider::FlightProvider; use crate::apis::flight_provider::flight_provider_request::FlightProviderRequest; use tokio_test::block_on; #[test] fn generate_url_works() { // 42.858110, 40.032470 // 38.202162, 51.214457 println!( "{}", FlightProvider::generate_url(FlightProviderRequest::new("25cd0734".into())) ); } #[test] fn get() { // 42.858110, 40.032470 // 38.202162, 51.214457 block_on(FlightProvider::new().get(FlightProviderRequest::new("25cd0734".into()))); } }
//https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/submissions/ use std::cmp::max; impl Solution { pub fn max_depth(s: String) -> i32 { let mut nesting_depth = 0; let mut tmp = 0; for c in s.chars() { match c { '(' => tmp += 1, ')' => tmp += -1, _ => () } nesting_depth = max(nesting_depth, tmp); } nesting_depth } }
// Copyright 2019 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT // http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD // https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied, // modified, or distributed except according to those terms. Please review the Licences for the // specific language governing permissions and limitations relating to use of the SAFE Network // Software. //! Helpers to work with extern "C" callbacks. use crate::result::FfiResult; use std::os::raw::c_void; use std::ptr; /// This trait allows us to treat callbacks with different number and type of arguments uniformly. pub trait Callback { /// Arguments for the callback. Should be a tuple. type Args: CallbackArgs; /// Call the callback, passing the user data pointer, error code and any additional arguments. fn call(&self, user_data: *mut c_void, error: *const FfiResult, args: Self::Args); } impl Callback for extern "C" fn(user_data: *mut c_void, result: *const FfiResult) { type Args = (); fn call(&self, user_data: *mut c_void, error: *const FfiResult, _args: Self::Args) { self(user_data, error) } } impl<T: CallbackArgs> Callback for extern "C" fn(user_data: *mut c_void, result: *const FfiResult, a: T) { type Args = T; fn call(&self, user_data: *mut c_void, error: *const FfiResult, args: Self::Args) { self(user_data, error, args) } } impl<T: CallbackArgs> Callback for unsafe extern "C" fn(user_data: *mut c_void, result: *const FfiResult, a: T) { type Args = T; fn call(&self, user_data: *mut c_void, error: *const FfiResult, args: Self::Args) { unsafe { self(user_data, error, args) } } } impl<T0: CallbackArgs, T1: CallbackArgs> Callback for extern "C" fn(user_data: *mut c_void, result: *const FfiResult, a0: T0, a1: T1) { type Args = (T0, T1); fn call(&self, user_data: *mut c_void, error: *const FfiResult, args: Self::Args) { self(user_data, error, args.0, args.1) } } impl<T0: CallbackArgs, T1: CallbackArgs, T2: CallbackArgs> Callback for extern "C" fn(user_data: *mut c_void, result: *const FfiResult, a0: T0, a1: T1, a2: T2) { type Args = (T0, T1, T2); fn call(&self, user_data: *mut c_void, error: *const FfiResult, args: Self::Args) { self(user_data, error, args.0, args.1, args.2) } } /// Trait for arguments to callbacks. This is similar to `Default`, but allows /// us to implement it for foreign types that don't already implement `Default`. pub trait CallbackArgs { /// Return default value for the type, used when calling the callback with error. fn default() -> Self; } impl CallbackArgs for () { fn default() -> Self {} } impl CallbackArgs for bool { fn default() -> Self { false } } impl CallbackArgs for u32 { fn default() -> Self { 0 } } impl CallbackArgs for i32 { fn default() -> Self { 0 } } impl CallbackArgs for i64 { fn default() -> Self { 0 } } impl CallbackArgs for u64 { fn default() -> Self { 0 } } impl CallbackArgs for usize { fn default() -> Self { 0 } } impl<T> CallbackArgs for *const T { fn default() -> Self { ptr::null() } } impl<T> CallbackArgs for *mut T { fn default() -> Self { ptr::null_mut() } } impl CallbackArgs for [u8; 32] { fn default() -> Self { [0; 32] } } impl<T0: CallbackArgs, T1: CallbackArgs> CallbackArgs for (T0, T1) { fn default() -> Self { (CallbackArgs::default(), CallbackArgs::default()) } } impl<T0: CallbackArgs, T1: CallbackArgs, T2: CallbackArgs> CallbackArgs for (T0, T1, T2) { fn default() -> Self { ( CallbackArgs::default(), CallbackArgs::default(), CallbackArgs::default(), ) } } impl<T0: CallbackArgs, T1: CallbackArgs, T2: CallbackArgs, T3: CallbackArgs> CallbackArgs for (T0, T1, T2, T3) { fn default() -> Self { ( CallbackArgs::default(), CallbackArgs::default(), CallbackArgs::default(), CallbackArgs::default(), ) } }
extern crate self as fuzzcheck; use std::ops::{Bound, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive}; use fuzzcheck_mutators_derive::make_mutator; use crate::mutators::map::MapMutator; use crate::mutators::tuples::{Tuple2, Tuple2Mutator, TupleMutatorWrapper}; use crate::mutators::Wrapper; use crate::{DefaultMutator, Mutator}; make_mutator! { name: RangeMutator, default: true, type: pub struct Range<Idx> { start: Idx, end: Idx, } } make_mutator! { name: RangeFromMutator, default: true, type: pub struct RangeFrom<Idx> { start: Idx, } } make_mutator! { name: RangeToMutator, default: true, type: pub struct RangeTo<Idx> { end: Idx, } } make_mutator! { name: RangeToInclusiveMutator, default: true, type: pub struct RangeToInclusive<Idx> { end: Idx, } } make_mutator! { name: RangeFullMutator, default: true, type: pub struct RangeFull; } make_mutator! { name: BoundMutator, default: true, type: pub enum Bound<T> { Included(T), Excluded(T), Unbounded, } } #[no_coverage] fn range_inclusive_from_tuple<T: Clone>(t: &(T, T)) -> RangeInclusive<T> { t.0.clone()..=t.1.clone() } #[no_coverage] fn tuple_from_range_inclusive<T: Clone>(r: &RangeInclusive<T>) -> Option<(T, T)> { Some((r.start().clone(), r.end().clone())) } #[no_coverage] fn range_cplx<T>(_r: &RangeInclusive<T>, orig_cplx: f64) -> f64 { orig_cplx } pub type RangeInclusiveMutator<T, M> = Wrapper< MapMutator< (T, T), RangeInclusive<T>, TupleMutatorWrapper<Tuple2Mutator<M, M>, Tuple2<T, T>>, fn(&RangeInclusive<T>) -> Option<(T, T)>, fn(&(T, T)) -> RangeInclusive<T>, fn(&RangeInclusive<T>, f64) -> f64, >, >; impl<T, M> RangeInclusiveMutator<T, M> where T: Clone, M: Mutator<T> + Clone, { #[no_coverage] pub fn new(m: M) -> Self { Wrapper(MapMutator::new( TupleMutatorWrapper::new(Tuple2Mutator::new(m.clone(), m)), tuple_from_range_inclusive, range_inclusive_from_tuple, range_cplx, )) } } impl<T> DefaultMutator for RangeInclusive<T> where T: 'static + Clone + DefaultMutator, T::Mutator: Clone, { type Mutator = RangeInclusiveMutator<T, T::Mutator>; #[no_coverage] fn default_mutator() -> Self::Mutator { Self::Mutator::new(T::default_mutator()) } }
/* Copyright ⓒ 2017 contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ extern crate build_helper; use build_helper::*; use build_helper::semver::Version; macro_rules! show { ($value:expr) => { println!(concat!("DEBUG: ", stringify!($value), ": {:?}"), $value); }; ($value:expr, |$i:ident| $map:expr) => { { let $i = $value; println!(concat!("DEBUG: ", stringify!($value), ": {:?}"), $map); } }; } fn main() { // For things which have a stable value, test for that value. For everything else, just ensure can read the value at all. let _ = bin::cargo(); let _ = bin::rustc(); let _ = bin::rustdoc(); assert_eq!(cargo::features::all().collect::<Vec<_>>().sorted(), vec!["a", "default"]); assert!(cargo::features::enabled("a")); assert!(!cargo::features::enabled("b")); assert!(cargo::features::enabled("default")); let _ = cargo::manifest::dir(); assert_eq!(cargo::manifest::links(), Some("awakening".into())); assert_eq!(cargo::pkg::authors().sorted(), vec!["Daniel Keep <daniel.keep@gmail.com>", "John Smith <null@null>"]); assert_eq!(cargo::pkg::description().unwrap_or("".into()), "A description of this crate."); assert_eq!(cargo::pkg::homepage().unwrap_or("".into()), "http://example.org/basic.rs"); assert_eq!(cargo::pkg::name(), "basic"); assert_eq!(cargo::pkg::version(), Version::parse("1.2.3-pre").unwrap()); let _ = debug(); let _ = host(); let _ = num_jobs(); let _ = opt_level(); let _ = out_dir(); let _ = profile(); let _ = target::endian(); let _ = target::pointer_width(); { let triple = target::triple(); let mut s = format!("{}-{}-{}", triple.arch(), triple.family(), triple.os()); if let Some(env) = triple.env() { s.push_str("-"); s.push_str(env); } assert_eq!(triple.as_str(), s); } let _ = unix(); let _ = windows(); // Emit whatever we can which *should* be inert. metadata::emit_raw("key", "value"); rustc::cfg("a_cfg_flag"); rustc::flags("-L ."); rustc::link_lib(None, "dummy"); rustc::link_search(None, "."); rerun_if_changed("dne.rs"); warning("not that big a deal"); } trait Sorted { fn sorted(self) -> Self; } impl<T: Ord> Sorted for Vec<T> { fn sorted(mut self) -> Self { self.sort(); self } }
use std::str::FromStr; use std::{error::Error, fmt}; /// Indicates if the concept is invalid. #[derive(Debug, PartialEq, Eq)] pub struct InvalidBoeConcept { concept: String, } impl InvalidBoeConcept { fn new(concept: &str) -> Self { InvalidBoeConcept { concept: concept.to_owned(), } } } impl fmt::Display for InvalidBoeConcept { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Unkown BOE concept: {}", &self.concept[..]) } } impl Error for InvalidBoeConcept {} macro_rules! boe_auction_concepts { ( $( $(#[$docs:meta])* ($konst:ident, $name:expr); )+ ) => { /// Type of BOE concepts #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub enum BoeConcept { $( $(#[$docs])* $konst, )+ } impl FromStr for BoeConcept { type Err = InvalidBoeConcept; #[inline] fn from_str(s: &str) -> Result<Self, Self::Err> { match &s.to_uppercase()[..] { $( $name => Ok(BoeConcept::$konst) , )+ "FORMA ADJUDICACIÓN" => Ok(BoeConcept::LotAuctionKind), "VALOR DE TASACIÓN" => Ok(BoeConcept::Appraisal), "FECHA DE ADQUISICIÓN" => Ok(BoeConcept::AcquisitionDate), "FECHA DE MATRICULACIÓN" => Ok(BoeConcept::LicensedDate), "REFERENCIA REGISTRAL" => Ok(BoeConcept::RegisterInscription), _ => Err(InvalidBoeConcept::new(s)), } } } #[cfg(test)] const TEST_BOE_CONCEPTS: &'static [(BoeConcept, &'static str)] = &[ $( (BoeConcept::$konst, $name), )+ ]; #[test] fn test_parse_boe_concepts() { for &(std, name) in TEST_BOE_CONCEPTS { // Test upper case assert_eq!(name.parse::<BoeConcept>().unwrap(), std); // Test lower case assert_eq!(name.to_lowercase().parse::<BoeConcept>().unwrap(), std); } } #[test] fn test_parse_invalid_boe_concept() { let invalid_concept = "non-sense"; assert_eq!(invalid_concept.parse::<BoeConcept>(), Err(InvalidBoeConcept::new(invalid_concept))); } } } boe_auction_concepts! { /// Acquisition date (AcquisitionDate, "FECHA ADQUISICIÓN"); /// Additional information (AdditionalInformation, "INFORMACIÓN ADICIONAL"); /// Specify physical address of the resource. (Address, "DIRECCIÓN"); /// Value of the asset according to official authorities. (Appraisal, "TASACIÓN"); /// Area of a property asset (Area, "SUPERFICIE"); /// Specify the kind of auction, so far: /// * AGENCIA TRIBUTARIA /// * RECAUDACIÓN TRIBUTARIA /// * NOTARIAL VOLUNTARIA /// * JUDICIAL VOLUNTARIA /// * JUDICIAL EN VIA DE APREMIO /// * JUDICIAL CONCURSAL /// * NOTARIAL EN VENTA EXTRAJUDICIAL /// * Desconocida, (AuctionKind, "TIPO DE SUBASTA"); /// Auction value (AuctionValue, "VALOR SUBASTA"); /// Steps between bids (BidStep, "TRAMOS ENTRE PUJAS"); /// Vehicle brand (Brand, "MARCA"); /// Charges (Charges, "CARGAS"); /// Catastro reference, we can go to the official catastro webpage to see /// everything related with the Residence. (CatastroReference, "REFERENCIA CATASTRAL"); /// City (City, "LOCALIDAD"); /// The quantity of the claim by the creditors. (ClaimQuantity, "CANTIDAD RECLAMADA"); /// Code of the auction (Code, "CÓDIGO"); /// Deposit amount to be able to make bids in the auction. (DepositAmount, "IMPORTE DEL DEPÓSITO"); /// Description of the concept. (Description, "DESCRIPCIÓN"); /// Email. (Email, "CORREO ELECTRÓNICO"); /// End date of the auction. (EndDate, "FECHA DE CONCLUSIÓN"); /// Fax. (Fax, "FAX"); /// Frame number. (FrameNumber, "NÚMERO DE BASTIDOR"); /// Header concept. (Header, "HEADER"); /// Identifier of the concept. (Identifier, "IDENTIFICADOR"); /// IDUFIR (Identificador único de finca registral) (Idufir, "IDUFIR"); /// Judicial title. (JudicialTitle, "TÍTULO JURÍDICO"); /// Licensed date. (LicensedDate, "FECHA MATRICULACIÓN"); /// License plate. (LicensePlate, "MATRÍCULA"); /// Asset localization. (Localization, "DEPÓSITO"); /// It specifies in this concept contains lots or not. (Lots, "LOTES"); /// Specify if the lots are joined or splitted. (LotAuctionKind, "FORMA DE ADJUDICACIÓN"); /// Minimum bid to be able to access the auction. (MinimumBid, "PUJA MÍNIMA"); /// Vehicle model. (Model, "MODELO"); /// BOE Notice. (Notice, "ANUNCIO BOE"); /// Owner status of the asset. (OwnerStatus, "SITUACIÓN POSESORIA"); /// Postal code. (PostalCode, "CÓDIGO POSTAL"); /// Province. (Province, "PROVINCIA"); /// Primary residence. (PrimaryResidence, "VIVIENDA HABITUAL"); /// Quota (Quota, "CUOTA"); /// Register inscription. (RegisterInscription, "INSCRIPCIÓN REGISTRAL"); /// Start date of the auction. (StartDate, "FECHA DE INICIO"); /// Telephone. (Telephone, "TELÉFONO"); /// If the asset can be viewed or not. (Visitable, "VISITABLE"); }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use actix::clock::Duration; use starcoin_config::NodeConfig; use starcoin_node::run_dev_node; use std::sync::Arc; use std::thread; #[stest::test] fn test_run_node() { let config = Arc::new(NodeConfig::random_for_test()); let handle = run_dev_node(config); thread::sleep(Duration::from_secs(10)); handle.stop().unwrap() }
use super::SkewTContext; use crate::{ analysis::{Analysis, PrecipTypeAlgorithm}, app::config::{self}, coords::{ScreenCoords, TPCoords, XYCoords}, gui::{ utility::{draw_filled_polygon, plot_curve_from_points}, Drawable, DrawingArgs, PlotContextExt, }, }; use itertools::izip; use log::warn; use metfor::{Celsius, Fahrenheit, HectoPascal, JpKg, Quantity}; use sounding_analysis::{self, Parcel, ParcelAscentAnalysis}; use std::iter::once; mod precip_type; #[derive(Clone, Copy, Debug)] enum TemperatureType { DryBulb, WetBulb, DewPoint, } impl SkewTContext { pub fn draw_temperature_profiles(args: DrawingArgs<'_, '_>) { let config = args.ac.config.borrow(); if config.show_wet_bulb { Self::draw_temperature_profile(TemperatureType::WetBulb, args); } if config.show_dew_point { Self::draw_temperature_profile(TemperatureType::DewPoint, args); } if config.show_temperature { Self::draw_temperature_profile(TemperatureType::DryBulb, args); } } fn draw_temperature_profile(t_type: TemperatureType, args: DrawingArgs<'_, '_>) { let (ac, cr) = (args.ac, args.cr); let config = ac.config.borrow(); let anal = if let Some(anal) = ac.get_sounding_for_display() { anal } else { return; }; let anal = anal.borrow(); let sndg = anal.sounding(); let pres_data = sndg.pressure_profile(); let temp_data = match t_type { TemperatureType::DryBulb => sndg.temperature_profile(), TemperatureType::WetBulb => sndg.wet_bulb_profile(), TemperatureType::DewPoint => sndg.dew_point_profile(), }; let line_width = match t_type { TemperatureType::DryBulb => config.temperature_line_width, TemperatureType::WetBulb => config.wet_bulb_line_width, TemperatureType::DewPoint => config.dew_point_line_width, }; let line_rgba = match t_type { TemperatureType::DryBulb => config.temperature_rgba, TemperatureType::WetBulb => config.wet_bulb_rgba, TemperatureType::DewPoint => config.dew_point_rgba, }; let profile_data = izip!(pres_data, temp_data).filter_map(|(pres, temp)| { if let (Some(pressure), Some(temperature)) = (pres.into(), temp.into()) { if pressure > config::MINP { let tp_coords = TPCoords { temperature, pressure, }; Some(ac.skew_t.convert_tp_to_screen(tp_coords)) } else { None } } else { None } }); plot_curve_from_points(cr, line_width, line_rgba, profile_data); } pub fn draw_data_overlays(args: DrawingArgs<'_, '_>) { use crate::app::config::ParcelType::*; let (ac, cr) = (args.ac, args.cr); let config = ac.config.borrow(); let anal = if let Some(anal) = ac.get_sounding_for_display() { anal } else { return; }; let anal = anal.borrow(); let sndg = anal.sounding(); if config.show_parcel_profile { match config.parcel_type { Surface => anal.surface_parcel_analysis(), MixedLayer => anal.mixed_layer_parcel_analysis(), MostUnstable => anal.most_unstable_parcel_analysis(), Convective => anal.convective_parcel_analysis(), Effective => anal.effective_parcel_analysis(), } .map(|p_analysis| { let color = config.parcel_rgba; let p_profile = p_analysis.profile(); Self::draw_parcel_profile(args, p_profile, color); if config.fill_parcel_areas { Self::draw_cape_cin_fill(args, p_analysis); } // Draw overlay tags if p_analysis .cape() .map(|cape| cape > JpKg(0.0)) .unwrap_or(false) { // LCL if let Some(pos) = p_analysis .lcl_pressure() .into_option() .and_then(|p| p_analysis.lcl_temperature().map(|t| (p, t))) .map(|(p, t)| { let vt = metfor::virtual_temperature(t, t, p) .map(Celsius::from) .unwrap_or(t); (p, vt) }) .map(|(p, t)| TPCoords { temperature: t, pressure: p, }) .map(|coords| { let mut coords = ac.skew_t.convert_tp_to_screen(coords); coords.x += 0.025; coords }) { ac.skew_t.draw_tag("LCL", pos, config.parcel_rgba, args); } // LFC if let Some(pos) = p_analysis .lfc_pressure() .into_option() .and_then(|p| p_analysis.lfc_virt_temperature().map(|t| (p, t))) .map(|(p, t)| TPCoords { temperature: t, pressure: p, }) .map(|coords| { let mut coords = ac.skew_t.convert_tp_to_screen(coords); coords.x += 0.025; coords }) { ac.skew_t.draw_tag("LFC", pos, config.parcel_rgba, args); } // EL if let Some(pos) = p_analysis .el_pressure() .into_option() .and_then(|p| p_analysis.el_temperature().map(|t| (p, t))) .map(|(p, t)| { let vt = metfor::virtual_temperature(t, t, p) .map(Celsius::from) .unwrap_or(t); (p, vt) }) .map(|(p, t)| TPCoords { temperature: t, pressure: p, }) .map(|coords| { let mut coords = ac.skew_t.convert_tp_to_screen(coords); coords.x += 0.025; coords }) { ac.skew_t.draw_tag("EL", pos, config.parcel_rgba, args); } } }) .or_else(|| { warn!("Parcel analysis returned None."); Some(()) }); } if config.show_downburst { Self::draw_downburst(args, &anal); } if config.show_inversion_mix_down { if let Some(parcel_profile) = sounding_analysis::sfc_based_inversion(sndg) .ok() .and_then(|lyr| lyr) // unwrap a layer of options .map(|lyr| lyr.top) .and_then(Parcel::from_datarow) .and_then(|parcel| sounding_analysis::mix_down(parcel, sndg).ok()) { let color = config.inversion_mix_down_rgba; Self::draw_parcel_profile(args, &parcel_profile, color); if let (Some(&pressure), Some(&temperature)) = ( parcel_profile.pressure.get(0), parcel_profile.parcel_t.get(0), ) { let pos = ac.skew_t.convert_tp_to_screen(TPCoords { temperature, pressure, }); let deg_f = format!( "{:.0}\u{00B0}F", Fahrenheit::from(temperature).unpack().round() ); ac.skew_t.draw_tag( &format!("{}/{:.0}\u{00B0}C", deg_f, temperature.unpack().round()), pos, color, args, ); } } } if config.show_inflow_layer { if let Some(lyr) = anal.effective_inflow_layer() { if let (Some(bottom_p), Some(top_p)) = ( lyr.bottom.pressure.into_option(), lyr.top.pressure.into_option(), ) { // Values from wind barbs, make this to the left of the wind barbs let (shaft_length, _) = cr .device_to_user_distance( config.wind_barb_shaft_length, -config.wind_barb_barb_length, ) .unwrap(); let padding = cr .device_to_user_distance(config.edge_padding, 0.0) .unwrap() .0; let screen_bounds = ac.skew_t.get_plot_area(); let XYCoords { x: mut xmax, .. } = ac.skew_t.convert_screen_to_xy(screen_bounds.upper_right); xmax = xmax.min(1.0); let ScreenCoords { x: xmax, .. } = ac.skew_t.convert_xy_to_screen(XYCoords { x: xmax, y: 0.0 }); let xcoord = xmax - 2.0 * padding - 2.0 * shaft_length; let yb = SkewTContext::get_wind_barb_center(bottom_p, xcoord, args); let yt = SkewTContext::get_wind_barb_center(top_p, xcoord, args); const WIDTH: f64 = 0.02; let rgba = config.inflow_layer_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); cr.set_line_width(cr.device_to_user_distance(4.0, 0.0).unwrap().0); cr.move_to(yt.x + WIDTH, yt.y); cr.line_to(yt.x - WIDTH, yt.y); cr.move_to(yt.x, yt.y); cr.line_to(yb.x, yb.y); cr.move_to(yb.x + WIDTH, yb.y); cr.line_to(yb.x - WIDTH, yb.y); cr.stroke().unwrap(); } } } if config.show_pft { Self::draw_pft_overlays(args, &anal); } } fn draw_pft_overlays(args: DrawingArgs<'_, '_>, sounding_anal: &Analysis) { let (ac, cr) = (args.ac, args.cr); let config = ac.config.borrow(); let sp_color = config.pft_sp_curve_color; let mean_q_color = config.pft_mean_q_color; let mean_theta_color = config.pft_mean_theta_color; let cloud_parcel_color = config.pft_cloud_parcel_color; let line_width = config.pft_line_width; // This plots an SP-curve and the cloud parcel above the LFC. let plot_single_sp_curve_cloud_parcel = |pft_anal: &sounding_analysis::PFTAnalysis| { let sp_curve = pft_anal.sp_curve.iter().map(|(p, t)| { let tp_coords = TPCoords { temperature: *t, pressure: *p, }; ac.skew_t.convert_tp_to_screen(tp_coords) }); plot_curve_from_points(cr, line_width, sp_color, sp_curve); let theta_e_pnts = (0..100) .map(|i| pft_anal.p_fc - HectoPascal((i * 10) as f64)) .take_while(|p| *p > HectoPascal(100.0)) .map(|p| { metfor::find_root( &|t| { Some( (metfor::equiv_pot_temperature(Celsius(t), Celsius(t), p)? - pft_anal.theta_e_fc) .unpack(), ) }, Celsius(-80.0).unpack(), Celsius(50.0).unpack(), ) .map(Celsius) .map(|t| (p, t)) }) .take_while(|opt| opt.is_some()) .flatten() .map(|(pressure, temperature)| { let pt_coords = TPCoords { temperature, pressure, }; ac.skew_t.convert_tp_to_screen(pt_coords) }); plot_curve_from_points(cr, line_width, cloud_parcel_color, theta_e_pnts); }; if let Some(pft_anal) = sounding_anal.pft() { plot_single_sp_curve_cloud_parcel(pft_anal); let sfc_p = match sounding_anal .sounding() .pressure_profile() .iter() .flat_map(|p| p.into_option()) .next() { Some(p) => p, None => return, }; let p_top = match pft_anal.sp_curve.first() { Some((p, _)) => *p, None => return, }; let q_iter = once(sfc_p) .chain(once(p_top)) .filter_map(|p| { metfor::dew_point_from_p_and_specific_humidity(p, pft_anal.q_ml) .map(|dp| (dp, p)) }) .map(|(temperature, pressure)| TPCoords { temperature, pressure, }) .map(|coords| ac.skew_t.convert_tp_to_screen(coords)); plot_curve_from_points(cr, line_width, mean_q_color, q_iter); let theta_iter = sounding_anal .sounding() .pressure_profile() .iter() .flat_map(|p| p.into_option()) .take_while(|p| *p > p_top) .chain(once(p_top)) .map(|p| (metfor::temperature_from_pot_temp(pft_anal.theta_ml, p), p)) .map(|(t, p)| (Celsius::from(t), p)) .map(|(temperature, pressure)| TPCoords { temperature, pressure, }) .map(|coords| ac.skew_t.convert_tp_to_screen(coords)); plot_curve_from_points(cr, line_width, mean_theta_color, theta_iter); } } fn draw_cape_cin_fill(args: DrawingArgs<'_, '_>, parcel_analysis: &ParcelAscentAnalysis) { let cape = match parcel_analysis.cape().into_option() { Some(cape) => cape, None => return, }; let cin = match parcel_analysis.cin().into_option() { Some(cin) => cin, None => return, }; if cape <= JpKg(0.0) { return; } if parcel_analysis.lcl_pressure().is_none() { // No moist convection. return; }; let lfc = match parcel_analysis.lfc_pressure().into_option() { Some(lfc) => lfc, None => return, }; let el = match parcel_analysis.el_pressure().into_option() { Some(el) => el, None => return, }; let (ac, cr) = (args.ac, args.cr); let config = ac.config.borrow(); let parcel_profile = parcel_analysis.profile(); let pres_data = &parcel_profile.pressure; let parcel_t = &parcel_profile.parcel_t; let env_t = &parcel_profile.environment_t; if cin < JpKg(0.0) { let bottom = izip!(pres_data, parcel_t, env_t) // Top down .rev() .skip_while(|&(&p, _, _)| p < lfc) .take_while(|&(_, &p_t, &e_t)| p_t <= e_t) .map(|(p, _, _)| p) .last(); if let Some(&bottom) = bottom { let up_side = izip!(pres_data, parcel_t, env_t) .skip_while(|&(&p, _, _)| p > bottom) .take_while(|&(&p, _, _)| p >= lfc) .map(|(p, _, e_t)| (*p, *e_t)); let down_side = izip!(pres_data, parcel_t, env_t) // Top down .rev() // Skip above top. .skip_while(|&(&p, _, _)| p < lfc) // Now we're in the CIN area! .take_while(|&(&p, _, _)| p < bottom) .map(|(p, p_t, _)| (*p, *p_t)); let negative_polygon = up_side.chain(down_side); let negative_polygon = negative_polygon.map(|(pressure, temperature)| { let tp_coords = TPCoords { temperature, pressure, }; ac.skew_t.convert_tp_to_screen(tp_coords) }); let negative_polygon_rgba = config.parcel_negative_rgba; draw_filled_polygon(cr, negative_polygon_rgba, negative_polygon); } } let up_side = izip!(pres_data, parcel_t, env_t) .skip_while(|&(p, _, _)| *p > lfc) .take_while(|&(p, _, _)| *p >= el) .map(|(p, _, e_t)| (*p, *e_t)); let down_side = izip!(pres_data, parcel_t, env_t) // Top down .rev() // Skip above top. .skip_while(|&(p, _, _)| *p < el) // Now we're in the CAPE area! .take_while(|&(p, _, _)| *p <= lfc) .map(|(p, p_t, _)| (*p, *p_t)); let polygon = up_side.chain(down_side); let polygon = polygon.map(|(pressure, temperature)| { let tp_coords = TPCoords { temperature, pressure, }; ac.skew_t.convert_tp_to_screen(tp_coords) }); let polygon_rgba = config.parcel_positive_rgba; draw_filled_polygon(cr, polygon_rgba, polygon); } fn draw_downburst(args: DrawingArgs<'_, '_>, sounding_analysis: &Analysis) { let (ac, cr) = (args.ac, args.cr); let config = ac.config.borrow(); let parcel_profile = if let Some(pp) = sounding_analysis.downburst_profile() { pp } else { return; }; let color = config.downburst_rgba; Self::draw_parcel_profile(args, parcel_profile, color); if config.fill_dcape_area { let pres_data = &parcel_profile.pressure; let parcel_t = &parcel_profile.parcel_t; let env_t = &parcel_profile.environment_t; let up_side = izip!(pres_data, env_t); let down_side = izip!(pres_data, parcel_t).rev(); let polygon = up_side.chain(down_side); let polygon = polygon.map(|(&pressure, &temperature)| { let tp_coords = TPCoords { temperature, pressure, }; ac.skew_t.convert_tp_to_screen(tp_coords) }); let polygon_rgba = config.dcape_area_color; draw_filled_polygon(cr, polygon_rgba, polygon); } } pub fn draw_precip_icons(&self, args: DrawingArgs<'_, '_>) { use PrecipTypeAlgorithm::*; // TODO add options for which boxes to show. self.draw_precip_icon(Model, 0, args); self.draw_precip_icon(Bourgouin, 1, args); self.draw_precip_icon(NSSL, 2, args); } }
fn main() { println!("I've been updated!"); }
use crate::checks::author_has_permission; use crate::checks::ParsedCommand; use crate::chess_game::render_board; use serenity::{model::channel::Message, prelude::*}; use std::collections::HashMap; use std::future::Future; use std::pin::Pin; pub fn get_commands() -> HashMap< String, fn(Context, Message, ParsedCommand) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>>, > { let mut functions: HashMap< String, fn( Context, Message, ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>>, > = HashMap::< String, fn( Context, Message, ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>>, >::new(); functions.insert("ping".into(), ping); functions.insert("dm_not_implemented".into(), dm_not_implemented); functions.insert("no command".into(), no_command); functions.insert("test".into(), test); // functions.insert("lyr".into(), lyr); // functions.insert("lyrics".into(), lyr); functions.insert("lol".into(), lol); functions.insert("xD".into(), xd); functions.insert("xd".into(), xd); functions.insert("XD".into(), xd); functions.insert("Sören".into(), soeren); functions.insert("Sö".into(), soeren); functions.insert("Söse".into(), soeren); functions.insert("admin".into(), admin); functions.insert("am_i_admin".into(), admin); functions.insert("Admin".into(), admin); functions.insert("Administrator".into(), admin); functions.insert("administrator".into(), admin); functions.insert("offline".into(), offline); functions.insert("online".into(), online); functions.insert("chess".into(), chess); functions.insert("def".into(), define); functions.insert("define".into(), define); // TODO: Maybe handle aliases in a better more efficient way return functions; } pub fn ping( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(ping_async(ctx, msg, args)) } async fn ping_async(ctx: Context, msg: Message, _args: ParsedCommand) { if let Err(why) = msg.channel_id.say(&ctx.http, "Pong!").await { println!("Error sending message: {:?}", why); } } pub fn dm_not_implemented( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(dm_not_implemented_async(ctx, msg, args)) } async fn dm_not_implemented_async(ctx: Context, msg: Message, _args: ParsedCommand) { if let Err(why) = msg .channel_id .say( &ctx.http, "Sorry, but I do not have any functions for DM's yet.", ) .await { println!("Error sending message: {:?}", why); } } pub fn no_command( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(no_command_async(ctx, msg, args)) } async fn no_command_async(ctx: Context, msg: Message, _args: ParsedCommand) { if let Err(why) = msg .channel_id .say( &ctx.http, "You need to specify a command after the prefix, otherwise I do not know what to do.", ) .await { println!("Error sending message: {:?}", why); } } pub fn test( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(test_async(ctx, msg, args)) } async fn test_async(ctx: Context, msg: Message, _args: ParsedCommand) { if let Err(why) = msg.channel_id.say(&ctx.http, "Hello, im online :)").await { println!("Error sending message: {:?}", why); } } pub fn _lyr( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(_lyr_async(ctx, msg, args)) } async fn _lyr_async(ctx: Context, msg: Message, args: ParsedCommand) { use std::process::Command; let song = match args.args { Some(args) => args.join(" "), _ => "".into(), }; let output = Command::new("sh") .arg("-c") .arg(format!("lyr-no-prompt query {}", song)) .output() .expect("Error using the lyr command"); let hello = String::from_utf8(output.stdout).expect("Error when converting command output to string"); if hello.chars().count() == 0 { if let Err(why) = msg .channel_id .say( &ctx.http, "You need to specify a song otherwise I do not know what to search for :(", ) .await { println!("Error sending message: {:?}", why); } } else { let paragraphs: Vec<&str> = hello.split("\n\n").collect(); for paragraph in paragraphs { if let Err(why) = msg .channel_id .say(&ctx.http, format!("{}", paragraph)) .await { println!("Error sending message: {:?}", why); } } } } pub fn lol( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(lol_async(ctx, msg, args)) } async fn lol_async(ctx: Context, msg: Message, _args: ParsedCommand) { if let Err(why) = msg .channel_id .say( &ctx.http, "When I was young we used to say ROFL instead of lol.", ) .await { println!("Error sending message: {:?}", why); } } pub fn xd( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(xd_async(ctx, msg, args)) } async fn xd_async(ctx: Context, msg: Message, _args: ParsedCommand) { if let Err(why) = msg .channel_id .say( &ctx.http, "You can also use emojis, they are better for showing your emotions", ) .await { println!("Error sending message: {:?}", why); } } pub fn soeren( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(soeren_async(ctx, msg, args)) } async fn soeren_async(ctx: Context, msg: Message, _args: ParsedCommand) { if let Err(why) = msg .channel_id .say(&ctx.http, "Scheel\nDer einzig Wahre...") .await { println!("Error sending message: {:?}", why); } } pub fn admin( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(admin_async(ctx, msg, args)) } async fn admin_async(ctx: Context, msg: Message, _args: ParsedCommand) { if author_has_permission( msg.clone(), serenity::model::permissions::Permissions::ADMINISTRATOR, &ctx.clone().cache, ctx.clone(), ) .await { if let Err(why) = msg .channel_id .say(&ctx.http, "Yes, you are the admin, my Lord") .await { println!("Error sending message: {:?}", why); } } else { if let Err(why) = msg .channel_id .say(&ctx.http, "No, you do not possess the power of god") .await { println!("Error sending message: {:?}", why); } } } pub fn offline( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(offline_async(ctx, msg, args)) } async fn offline_async(ctx: Context, msg: Message, _args: ParsedCommand) { if author_has_permission( msg.clone(), serenity::model::permissions::Permissions::ADMINISTRATOR, &ctx.clone().cache, ctx.clone(), ) .await { if let Err(why) = msg.channel_id.say(&ctx.http, "It's getting dark...").await { println!("Error sending message: {:?}", why); } ctx.clone().invisible().await; } else { if let Err(why) = msg .channel_id .say(&ctx.http, "Sorry, only for admins :(") .await { println!("Error sending message: {:?}", why); } } } pub fn online( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(online_async(ctx, msg, args)) } async fn online_async(ctx: Context, msg: Message, _args: ParsedCommand) { if author_has_permission( msg.clone(), serenity::model::permissions::Permissions::ADMINISTRATOR, &ctx.clone().cache, ctx.clone(), ) .await { if let Err(why) = msg .channel_id .say(&ctx.http, "Ahh, the sun is rising...") .await { println!("Error sending message: {:?}", why); } ctx.clone().online().await; } else { if let Err(why) = msg .channel_id .say(&ctx.http, "Sorry, only for admins :(") .await { println!("Error sending message: {:?}", why); } } } // TODO: add chessrs and implement displaying a board with figures && later also adding possibility to move pub fn chess( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(chess_async(ctx, msg, args)) } async fn chess_async(ctx: Context, msg: Message, args: ParsedCommand) { if match &args.args { Some(v) => v.len() == 0, _ => true, } { if let Err(why) = msg.channel_id.say(&ctx.http, "Ahh, you want to play chess...\nI need some more information to start a match:\nIf you want to play against a bot enter ```t chess bot```").await { println!("Error sending message: {:?}", why); } } else if match &args.args { Some(v) => v.len() > 2 && v[0] == "fen", _ => false, } { render_board( ctx, msg, &args .clone() .args .expect("Somehow logic does not work anymore")[1], &args.args.expect("There should be a third argument")[2], ) .await; } else if match &args.args { Some(v) => v.len() == 2 && v[0] == "fen", _ => false, } { render_board( ctx, msg, &args .clone() .args .expect("Somehow logic does not work anymore")[1], "", ) .await; } else { if let Err(why) = msg .channel_id .say( &ctx.http, "Sorry, I can only display FEN positions yet:\n``` t chess fen <position>```", ) .await { println!("Error sending message: {:?}", why); } } } pub fn define( ctx: Context, msg: Message, args: ParsedCommand, ) -> Pin<Box<dyn Future<Output = ()> + std::marker::Send>> { Box::pin(define_async(ctx, msg, args)) } async fn define_async(ctx: Context, msg: Message, args: ParsedCommand) { let search_word = match args.args { Some(x) => { if x.len() > 0 { x.join(" ") } else { if let Err(why) = msg .channel_id .say( &ctx.http, "I need a definition to search for:\n``` t define <word>```", ) .await { println!("Error sending message: {:?}", why); } return; } } _ => { if let Err(why) = msg .channel_id .say( &ctx.http, "I need a definition to search for:\n``` t define <word>```", ) .await { println!("Error sending message: {:?}", why); } return; } }; let response = match get_definition(&search_word).await { Ok(definition) => definition, Err(why) => { if let Err(why) = msg .channel_id .say(&ctx.http, format!("There has been an error:\n```{}```", why)) .await { println!("Error sending message: {:?}", why); } return; } }; if let Err(_) = msg .channel_id .send_message(&ctx.http, |m| { m.embed(|e| { e.title(format!("{}", response.word)); e.field("Description:".to_string(), response.description, false); e.field("Example:".to_string(), response.example, false); e.field("Author:".to_string(), response.author, false); return e; }); return m; }) .await { if let Err(why) = msg .channel_id .say( &ctx.http, "Sorry, there was an error printing the definition, it might have been to long :(", ) .await { println!("Error sending message: {:?}", why); } } } // TODO: add help command (maybe automatic implementation) use std::fmt; #[derive(Debug, Clone)] struct UrbanError; impl fmt::Display for UrbanError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Error when getting definition, probably it does not exist yet :(" ) } } async fn get_definition(search_word: &str) -> Result<Definition, UrbanError> { use serde_json::Value; let res = reqwest::get(&format!( "https://api.urbandictionary.com/v0/define?term={}", search_word )) .await .expect("Error connecting"); let body = res.text().await.expect("error getting body"); let value: Value = serde_json::from_str(&body).expect(""); Ok(Definition { word: match value["list"][0]["word"].as_str() { Some(x) => x, _ => return Err(UrbanError), } .to_string() .replace("[", "") .replace("]", ""), description: match value["list"][0]["definition"].as_str() { Some(x) => x, _ => return Err(UrbanError), } .to_string() .replace("[", "") .replace("]", ""), example: match value["list"][0]["example"].as_str() { Some(x) => x, _ => return Err(UrbanError), } .to_string() .replace("[", "") .replace("]", ""), author: match value["list"][0]["author"].as_str() { Some(x) => x, _ => return Err(UrbanError), } .to_string() .replace("[", "") .replace("]", ""), }) } #[derive(Debug)] struct Definition { word: String, description: String, example: String, author: String, }
/* * __ __ _ _ _ * | \/ | ___ ___ __ _| | (_)_ __ | | __ * | |\/| |/ _ \/ __|/ _` | | | | '_ \| |/ / * | | | | __/\__ \ (_| | |___| | | | | < * |_| |_|\___||___/\__,_|_____|_|_| |_|_|\_\ * * Copyright (c) 2017-2018, The MesaLink Authors. * All rights reserved. * * This work is licensed under the terms of the BSD 3-Clause License. * For a copy, see the LICENSE file. * */ use crate::libssl::err::{MesalinkBuiltinError, MesalinkInnerResult}; use crate::MesalinkOpaquePointerType; pub(crate) fn sanitize_const_ptr_for_ref<'a, T>(ptr: *const T) -> MesalinkInnerResult<&'a T> where T: MesalinkOpaquePointerType, { let ptr = ptr as *mut T; sanitize_ptr_for_mut_ref(ptr).map(|r| r as &'a T) } pub(crate) fn sanitize_ptr_for_ref<'a, T>(ptr: *mut T) -> MesalinkInnerResult<&'a T> where T: MesalinkOpaquePointerType, { sanitize_ptr_for_mut_ref(ptr).map(|r| r as &'a T) } pub(crate) fn sanitize_ptr_for_mut_ref<'a, T>(ptr: *mut T) -> MesalinkInnerResult<&'a mut T> where T: MesalinkOpaquePointerType, { if ptr.is_null() { return Err(error!(MesalinkBuiltinError::NullPointer.into())); } let obj_ref: &mut T = unsafe { &mut *ptr }; if obj_ref.check_magic() { Ok(obj_ref) } else { Err(error!(MesalinkBuiltinError::MalformedObject.into())) } }
use juniper::{ graphql_object, graphql_subscription, Context, EmptyMutation, GraphQLObject, RootNode, SubscriptionCoordinator, Variables, }; use juniper::futures::executor; use juniper::futures::stream::{self, Stream, StreamExt}; use juniper::http::GraphQLRequest; use juniper_subscriptions::{Connection, Coordinator}; use std::pin::Pin; #[derive(Debug, Clone, GraphQLObject)] struct Data { id: String, value: i32, } struct Store; impl Context for Store {} struct Query; #[graphql_object(context = Store)] impl Query { fn new() -> Self { Self } } type DataStream = Pin<Box<dyn Stream<Item = Data> + Send>>; struct Subscription; #[graphql_subscription(context = Store)] impl Subscription { async fn sample() -> DataStream { let data = Data { id: "sample-1".to_string(), value: 1, }; Box::pin(stream::once(async { data })) } } type Schema = RootNode<'static, Query, EmptyMutation<Store>, Subscription>; async fn run1() { let ctx = Store; let schema = Schema::new(Query, EmptyMutation::new(), Subscription); let q = r#"{ "query": "subscription { sample { id value } }" }"#; let req: GraphQLRequest = serde_json::from_str(q).unwrap(); let crd = Coordinator::new(schema); let con = crd.subscribe(&req, &ctx).await.unwrap(); let items = con.collect::<Vec<_>>().await; println!("{:?}", items); println!("{}", serde_json::to_string(&items).unwrap()); } async fn run2() { let ctx = Store; let schema = Schema::new(Query, EmptyMutation::new(), Subscription); let q = r#" subscription { sample { id value } } "#; let v = Variables::new(); let (s, e) = juniper::resolve_into_stream(q, None, &schema, &v, &ctx) .await .unwrap(); let con = Connection::from_stream(s, e); let items = con.collect::<Vec<_>>().await; println!("{:?}", items); println!("{}", serde_json::to_string(&items).unwrap()); } fn main() { executor::block_on(run1()); println!("-----"); executor::block_on(run2()); }
mod line_item; pub use line_item::LineItem; mod money; pub use money::Money; mod currency; pub use currency::Currency; mod billing_method; pub use billing_method::BillingMethod; mod foreign_key; pub use foreign_key::ForeignKey; trait HasVariants { fn variants() -> Vec<String>; }
// Copyright 2014 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 core::cell::UnsafeCell; use core::marker; use core::ops::{Deref, DerefMut}; use self::poison::{/*LockResult*/}; use super::sys::os as sys; pub mod poison { /*use core::marker::Reflect; use core::cell::UnsafeCell; use core::fmt; use std::thread; use std::error::{Error}; pub struct Flag { failed: UnsafeCell<bool> } // This flag is only ever accessed with a lock previously held. Note that this // a totally private structure. unsafe impl Send for Flag {} unsafe impl Sync for Flag {} pub const FLAG_INIT: Flag = Flag { failed: UnsafeCell { value: false } }; impl Flag { #[inline] pub fn borrow(&self) -> LockResult<Guard> { let ret = Guard { panicking: thread::panicking() }; if unsafe { *self.failed.get() } { Err(PoisonError::new(ret)) } else { Ok(ret) } } #[inline] pub fn done(&self, guard: &Guard) { if !guard.panicking && thread::panicking() { unsafe { *self.failed.get() = true; } } } #[inline] pub fn get(&self) -> bool { unsafe { *self.failed.get() } } } pub struct Guard { panicking: bool, } /// A type of error which can be returned whenever a lock is acquired. /// /// Both Mutexes and RwLocks are poisoned whenever a thread fails while the lock /// is held. The precise semantics for when a lock is poisoned is documented on /// each lock, but once a lock is poisoned then all future acquisitions will /// return this error. pub struct PoisonError<T> { guard: T, }*/ /*/// A type alias for the result of a lock method which can be poisoned. /// /// The `Ok` variant of this result indicates that the primitive was not /// poisoned, and the `Guard` is contained within. The `Err` variant indicates /// that the primitive was poisoned. Note that the `Err` variant *also* carries /// the associated guard, and it can be acquired through the `into_inner` /// method. pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;*/ /*impl<T> fmt::Debug for PoisonError<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "PoisonError { inner: .. }".fmt(f) } } impl<T> fmt::Display for PoisonError<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "poisoned lock: another task failed inside".fmt(f) } } impl<T: Send + Reflect> Error for PoisonError<T> { fn description(&self) -> &str { "poisoned lock: another task failed inside" } } impl<T> PoisonError<T> { /// Creates a `PoisonError`. pub fn new(guard: T) -> PoisonError<T> { PoisonError { guard: guard } } /// Consumes this error indicating that a lock is poisoned, returning the /// underlying guard to allow access regardless. pub fn into_inner(self) -> T { self.guard } /// Reaches into this error indicating that a lock is poisoned, returning a /// reference to the underlying guard to allow access regardless. pub fn get_ref(&self) -> &T { &self.guard } /// Reaches into this error indicating that a lock is poisoned, returning a /// mutable reference to the underlying guard to allow access regardless. pub fn get_mut(&mut self) -> &mut T { &mut self.guard } } impl<T> From<PoisonError<T>> for TryLockError<T> { fn from(err: PoisonError<T>) -> TryLockError<T> { TryLockError::Poisoned(err) } } impl<T> fmt::Debug for TryLockError<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f), TryLockError::WouldBlock => "WouldBlock".fmt(f) } } } impl<T: Send + Reflect> fmt::Display for TryLockError<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.description().fmt(f) } } impl<T: Send + Reflect> Error for TryLockError<T> { fn description(&self) -> &str { match *self { TryLockError::Poisoned(ref p) => p.description(), TryLockError::WouldBlock => "try_lock failed because the operation would block" } } fn cause(&self) -> Option<&Error> { match *self { TryLockError::Poisoned(ref p) => Some(p), _ => None } } } pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U> where F: FnOnce(T) -> U { match result { Ok(t) => Ok(f(t)), Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))) } }*/ } /// The static mutex type is provided to allow for static allocation of mutexes. /// /// Note that this is a separate type because using a Mutex correctly means that /// it needs to have a destructor run. In Rust, statics are not allowed to have /// destructors. As a result, a `StaticMutex` has one extra method when compared /// to a `Mutex`, a `destroy` method. This method is unsafe to call, and /// documentation can be found directly on the method. /// /// # Examples /// /// ``` /// # #![feature(std_misc)] /// use std::sync::{StaticMutex, MUTEX_INIT}; /// /// static LOCK: StaticMutex = MUTEX_INIT; /// /// { /// let _g = LOCK.lock().unwrap(); /// // do some productive work /// } /// // lock is unlocked here. /// ``` pub struct StaticMutex { lock: sys::Mutex, //poison: poison::Flag, } /// An RAII implementation of a "scoped lock" of a mutex. When this structure is /// dropped (falls out of scope), the lock will be unlocked. /// /// The data protected by the mutex can be access through this guard via its /// `Deref` and `DerefMut` implementations #[must_use] pub struct MutexGuard<'a, T: ?Sized + 'a> { // funny underscores due to how Deref/DerefMut currently work (they // disregard field privacy). __lock: &'a StaticMutex, __data: &'a UnsafeCell<T>, //__poison: poison::Guard, } impl<'a, T: ?Sized> !marker::Send for MutexGuard<'a, T> {} /// Static initialization of a mutex. This constant can be used to initialize /// other mutex constants. pub const MUTEX_INIT: StaticMutex = StaticMutex { lock: sys::MUTEX_INIT, //poison: poison::FLAG_INIT, }; impl StaticMutex { /// Acquires this lock, see `Mutex::lock` #[inline] pub fn lock(&'static self) -> /*LockResult<*/MutexGuard<()>/*>*/ { unsafe { self.lock.lock() } MutexGuard::new(self, &DUMMY.0) } } struct Dummy(UnsafeCell<()>); unsafe impl Sync for Dummy {} static DUMMY: Dummy = Dummy(UnsafeCell { value: () }); impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> { fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell<T>) -> /*LockResult<*/MutexGuard<'mutex, T>/*>*/ { //poison::map_result(lock.poison.borrow(), |guard| { MutexGuard { __lock: lock, __data: data, //__poison: guard, } //}) } } impl<'mutex, T: ?Sized> Deref for MutexGuard<'mutex, T> { type Target = T; fn deref<'a>(&'a self) -> &'a T { unsafe { &*self.__data.get() } } } impl<'mutex, T: ?Sized> DerefMut for MutexGuard<'mutex, T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *self.__data.get() } } } impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> { #[inline] fn drop(&mut self) { unsafe { //self.__lock.poison.done(&self.__poison); self.__lock.lock.unlock(); } } }
//! Contains many ffi-safe equivalents of standard library types. //! The vast majority of them can be converted to and from std equivalents. //! //! For ffi-safe equivalents/wrappers of types outside the standard library go to //! the [external_types module](../external_types/index.html) pub(crate) mod arc; pub(crate) mod boxed; pub(crate) mod cmp_ordering; pub mod cow; pub mod map; pub(crate) mod option; pub(crate) mod range; pub(crate) mod result; pub(crate) mod slice_mut; pub(crate) mod slices; pub(crate) mod std_error; pub(crate) mod std_io; pub(crate) mod str; pub mod string; pub(crate) mod time; pub(crate) mod tuple; pub mod utypeid; pub mod vec; /// Some types from the `std::sync` module have ffi-safe equivalents in /// `abi_stable::external_types`. /// /// The `sync::{Mutex,RwLock,Once}` equivalents are declared in /// `abi_stable::external_types::parking_lot` /// /// The `mpsc` equivalents are declared in /// `abi_stable::external_types::crossbeam_channel`, /// this is enabled by default with the `channels`/`crossbeam-channel` cargo feature. pub mod sync {} #[doc(inline)] pub use self::{ arc::RArc, boxed::RBox, cmp_ordering::RCmpOrdering, cow::{RCow, RCowSlice, RCowStr, RCowVal}, map::RHashMap, option::{RNone, ROption, RSome}, result::{RErr, ROk, RResult}, slice_mut::RSliceMut, slices::RSlice, std_error::{RBoxError, RBoxError_, SendRBoxError, UnsyncRBoxError}, std_io::{RIoError, RIoErrorKind, RSeekFrom}, str::RStr, string::RString, time::RDuration, tuple::{Tuple1, Tuple2, Tuple3, Tuple4}, utypeid::UTypeId, vec::RVec, };
use std::f32::consts::PI; use crate::{ angle::{DirectionX, DirectionY}, position::WorldCoords, ray::Ray, util::round, AngleRad, Grid, TilePosition, }; const RAY_PRECISION: usize = 8; pub fn rays_from(center: &TilePosition, grid: &Grid, width: f32, angle: &AngleRad) -> Vec<Ray> { debug_assert!(width > 0.0, "width needs to be > 0"); let center_wc = WorldCoords::from_tile_position(center, grid.tile_size); let left_rad: AngleRad = angle.perpendicular(); let (left_sin, left_cos) = ( round(left_rad.sin(), RAY_PRECISION), round(left_rad.cos(), RAY_PRECISION), ); // sections on each side let sections = (width.ceil() / grid.tile_size.floor()).max(1.0).ceil(); let section_width = (width / 2.0) / sections; #[allow( clippy::as_conversions, clippy::cast_sign_loss, clippy::clippy::cast_possible_truncation )] let sections = sections as i16; let (fx, fy) = { ( match DirectionX::from(&left_rad) { DirectionX::Left | DirectionX::Parallel => 1.0, DirectionX::Right => -1.0, }, match DirectionY::from(&left_rad) { DirectionY::Up | DirectionY::Parallel => { // Honestly I've got no idea why this is necessary :( if angle.0 > 1.5 * PI { -1.0 } else { 1.0 } } DirectionY::Down => -1.0, }, ) }; #[allow(clippy::integer_arithmetic)] (-sections..=sections) .filter_map(|idx| { let len = section_width * f32::from(idx); let dx = left_sin * len * fx; let dy = left_cos * len * fy; let tp = center_wc .translated(dx, dy) .bounds_checked(grid)? .to_tile_position() .ok()?; Some(Ray::new(grid.clone(), tp, angle.clone())) }) .collect() } #[cfg(test)] mod tests { use crate::util::round_tp; use super::*; fn rays_for_angle( center: &TilePosition, grid: &Grid, width: f32, angle: f32, ) -> Vec<TilePosition> { let rays = rays_from(center, grid, width, &angle.into()); #[cfg(feature = "plot")] { use crate::plot::{plot_rays_origins, PlotType}; let mut rays = rays_from(center, grid, width, &angle.into()); plot_rays_origins( &grid, center, width, &angle.into(), &mut rays, PlotType::File, ); } rays.iter().map(|ray| round_tp(&ray.tp)).collect() } #[test] fn rays_from_width_smaller_than_tile_isolate() { let center = TilePosition::new(1, 1, 0.5, 0.5); let grid = Grid::new(4, 4, 1.0); let width = grid.tile_size * 0.8; // Right/Down at 315 let angle = 315_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.217), (1, 0.217)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.783), (1, 0.783)).into() ] ); } #[test] fn rays_from_width_smaller_than_tile() { let center = TilePosition::new(1, 1, 0.5, 0.5); let grid = Grid::new(4, 4, 1.0); let width = grid.tile_size * 0.8; // To the right let angle = 0.0; assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.500), (1, 0.900)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.500), (1, 0.100)).into(), ], ); // // To the left let angle = 180_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.500), (1, 0.100)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.500), (1, 0.900)).into() ], ); // Up let angle = 90_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.100), (1, 0.500)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.900), (1, 0.500)).into(), ], ); // Down let angle = 270_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.900), (1, 0.500)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.100), (1, 0.500)).into() ], ); // Right/Up at 45 let angle = 45_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.217), (1, 0.783)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.783), (1, 0.217)).into() ] ); // Left/Up at 120 let angle = 120_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.154), (1, 0.300)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.846), (1, 0.700)).into() ] ); // Left/Down at 225 let angle = 225_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.783), (1, 0.217)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.217), (1, 0.783)).into() ] ); // Right/Down at 315 let angle = 315_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.217), (1, 0.217)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.783), (1, 0.783)).into() ] ); // // Checking edge cases regarding the oddity of angle > 1.5 * PI // // Left/Down let angle = 269_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.900), (1, 0.493)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.100), (1, 0.507)).into() ] ); let angle = 271_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.100), (1, 0.493)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.900), (1, 0.507)).into() ] ); let angle = 359_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.493), (1, 0.100)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.507), (1, 0.900)).into() ] ); let angle = 361_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.507), (1, 0.100)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.493), (1, 0.900)).into() ] ); } #[test] fn rays_from_width_same_as_tile() { let center = TilePosition::new(1, 1, 0.5, 0.5); let grid = Grid::new(4, 4, 1.0); let width = grid.tile_size; let angle = 0.0; assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.500), (2, 0.000)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.500), (1, 0.000)).into() ] ); let angle = 120_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.067), (1, 0.250)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.933), (1, 0.750)).into() ] ); } #[test] fn rays_from_width_larger_than_tile() { let center = TilePosition::new(1, 1, 0.5, 0.5); let grid = Grid::new(4, 4, 1.0); let width = grid.tile_size * 2.0; let angle = 0.0; assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.500), (2, 0.500)).into(), ((1, 0.500), (2, 0.000)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.500), (1, 0.000)).into(), ((1, 0.500), (0, 0.500)).into() ] ); let angle = 120_f32.to_radians(); assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((0, 0.634), (1, 0.000)).into(), ((1, 0.067), (1, 0.250)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.933), (1, 0.750)).into(), ((2, 0.366), (2, 0.000)).into() ] ); } #[test] fn rays_bounds() { let grid = Grid::new(4, 4, 1.0); let angle = 0.0; let center = TilePosition::new(0, 0, 0.0, 0.0); let width = grid.tile_size * 0.8; assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((0, 0.000), (0, 0.400)).into(), ((0, 0.000), (0, 0.000)).into(), ] ); let center = TilePosition::new(1, 1, 0.5, 0.5); let width = grid.tile_size * 10.0; assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((1, 0.500), (3, 0.500)).into(), ((1, 0.500), (3, 0.000)).into(), ((1, 0.500), (2, 0.500)).into(), ((1, 0.500), (2, 0.000)).into(), ((1, 0.500), (1, 0.500)).into(), ((1, 0.500), (1, 0.000)).into(), ((1, 0.500), (0, 0.500)).into(), ((1, 0.500), (0, 0.000)).into() ] ); let angle = 90_f32.to_radians(); let center = TilePosition::new(2, 2, 0.5, 0.5); let width = grid.tile_size * 10.0; assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((0, 0.000), (2, 0.500)).into(), ((0, 0.500), (2, 0.500)).into(), ((1, 0.000), (2, 0.500)).into(), ((1, 0.500), (2, 0.500)).into(), ((2, 0.000), (2, 0.500)).into(), ((2, 0.500), (2, 0.500)).into(), ((3, 0.000), (2, 0.500)).into(), ((3, 0.500), (2, 0.500)).into() ] ); let angle = 315_f32.to_radians(); let center = TilePosition::new(0, 2, 0.5, 0.5); let width = grid.tile_size * 10.0; assert_eq!( rays_for_angle(&center, &grid, width, angle), [ ((0, 0.146), (2, 0.146)).into(), ((0, 0.500), (2, 0.500)).into(), ((0, 0.854), (2, 0.854)).into(), ((1, 0.207), (3, 0.207)).into(), ((1, 0.561), (3, 0.561)).into(), ((1, 0.914), (3, 0.914)).into() ] ); } }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qboxlayout.h // dst-file: /src/widgets/qboxlayout.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::qboxlayout::QBoxLayout; // 773 use std::ops::Deref; use super::qwidget::*; // 773 use super::super::core::qobjectdefs::*; // 771 use super::qlayout::*; // 773 use super::qlayoutitem::*; // 773 use super::super::core::qsize::*; // 771 use super::super::core::qrect::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QHBoxLayout_Class_Size() -> c_int; // proto: void QHBoxLayout::QHBoxLayout(QWidget * parent); fn C_ZN11QHBoxLayoutC2EP7QWidget(arg0: *mut c_void) -> u64; // proto: const QMetaObject * QHBoxLayout::metaObject(); fn C_ZNK11QHBoxLayout10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QHBoxLayout::~QHBoxLayout(); fn C_ZN11QHBoxLayoutD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QHBoxLayout::QHBoxLayout(); fn C_ZN11QHBoxLayoutC2Ev() -> u64; fn QBoxLayout_Class_Size() -> c_int; // proto: int QBoxLayout::spacing(); fn C_ZNK10QBoxLayout7spacingEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: bool QBoxLayout::hasHeightForWidth(); fn C_ZNK10QBoxLayout17hasHeightForWidthEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QBoxLayout::addItem(QLayoutItem * ); fn C_ZN10QBoxLayout7addItemEP11QLayoutItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QSize QBoxLayout::sizeHint(); fn C_ZNK10QBoxLayout8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QBoxLayout::~QBoxLayout(); fn C_ZN10QBoxLayoutD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QBoxLayout::insertSpacing(int index, int size); fn C_ZN10QBoxLayout13insertSpacingEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int); // proto: void QBoxLayout::setStretch(int index, int stretch); fn C_ZN10QBoxLayout10setStretchEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int); // proto: void QBoxLayout::insertStretch(int index, int stretch); fn C_ZN10QBoxLayout13insertStretchEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int); // proto: void QBoxLayout::addLayout(QLayout * layout, int stretch); fn C_ZN10QBoxLayout9addLayoutEP7QLayouti(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int); // proto: bool QBoxLayout::setStretchFactor(QWidget * w, int stretch); fn C_ZN10QBoxLayout16setStretchFactorEP7QWidgeti(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int) -> c_char; // proto: void QBoxLayout::invalidate(); fn C_ZN10QBoxLayout10invalidateEv(qthis: u64 /* *mut c_void*/); // proto: void QBoxLayout::setGeometry(const QRect & ); fn C_ZN10QBoxLayout11setGeometryERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QBoxLayout::addStretch(int stretch); fn C_ZN10QBoxLayout10addStretchEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: void QBoxLayout::insertLayout(int index, QLayout * layout, int stretch); fn C_ZN10QBoxLayout12insertLayoutEiP7QLayouti(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void, arg2: c_int); // proto: bool QBoxLayout::setStretchFactor(QLayout * l, int stretch); fn C_ZN10QBoxLayout16setStretchFactorEP7QLayouti(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_int) -> c_char; // proto: int QBoxLayout::count(); fn C_ZNK10QBoxLayout5countEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: QLayoutItem * QBoxLayout::itemAt(int ); fn C_ZNK10QBoxLayout6itemAtEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void; // proto: const QMetaObject * QBoxLayout::metaObject(); fn C_ZNK10QBoxLayout10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QBoxLayout::insertSpacerItem(int index, QSpacerItem * spacerItem); fn C_ZN10QBoxLayout16insertSpacerItemEiP11QSpacerItem(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void); // proto: int QBoxLayout::heightForWidth(int ); fn C_ZNK10QBoxLayout14heightForWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int; // proto: void QBoxLayout::addStrut(int ); fn C_ZN10QBoxLayout8addStrutEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: QSize QBoxLayout::maximumSize(); fn C_ZNK10QBoxLayout11maximumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: int QBoxLayout::stretch(int index); fn C_ZNK10QBoxLayout7stretchEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int; // proto: void QBoxLayout::addSpacerItem(QSpacerItem * spacerItem); fn C_ZN10QBoxLayout13addSpacerItemEP11QSpacerItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: int QBoxLayout::minimumHeightForWidth(int ); fn C_ZNK10QBoxLayout21minimumHeightForWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int; // proto: QSize QBoxLayout::minimumSize(); fn C_ZNK10QBoxLayout11minimumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QBoxLayout::setSpacing(int spacing); fn C_ZN10QBoxLayout10setSpacingEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: QLayoutItem * QBoxLayout::takeAt(int ); fn C_ZN10QBoxLayout6takeAtEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void; // proto: void QBoxLayout::insertItem(int index, QLayoutItem * ); fn C_ZN10QBoxLayout10insertItemEiP11QLayoutItem(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void); // proto: void QBoxLayout::addSpacing(int size); fn C_ZN10QBoxLayout10addSpacingEi(qthis: u64 /* *mut c_void*/, arg0: c_int); fn QVBoxLayout_Class_Size() -> c_int; // proto: void QVBoxLayout::QVBoxLayout(); fn C_ZN11QVBoxLayoutC2Ev() -> u64; // proto: const QMetaObject * QVBoxLayout::metaObject(); fn C_ZNK11QVBoxLayout10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QVBoxLayout::QVBoxLayout(QWidget * parent); fn C_ZN11QVBoxLayoutC2EP7QWidget(arg0: *mut c_void) -> u64; // proto: void QVBoxLayout::~QVBoxLayout(); fn C_ZN11QVBoxLayoutD2Ev(qthis: u64 /* *mut c_void*/); } // <= ext block end // body block begin => // class sizeof(QHBoxLayout)=1 #[derive(Default)] pub struct QHBoxLayout { qbase: QBoxLayout, pub qclsinst: u64 /* *mut c_void*/, } // class sizeof(QBoxLayout)=1 #[derive(Default)] pub struct QBoxLayout { qbase: QLayout, pub qclsinst: u64 /* *mut c_void*/, } // class sizeof(QVBoxLayout)=1 #[derive(Default)] pub struct QVBoxLayout { qbase: QBoxLayout, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QHBoxLayout { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QHBoxLayout { return QHBoxLayout{qbase: QBoxLayout::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QHBoxLayout { type Target = QBoxLayout; fn deref(&self) -> &QBoxLayout { return & self.qbase; } } impl AsRef<QBoxLayout> for QHBoxLayout { fn as_ref(& self) -> & QBoxLayout { return & self.qbase; } } // proto: void QHBoxLayout::QHBoxLayout(QWidget * parent); impl /*struct*/ QHBoxLayout { pub fn new<T: QHBoxLayout_new>(value: T) -> QHBoxLayout { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QHBoxLayout_new { fn new(self) -> QHBoxLayout; } // proto: void QHBoxLayout::QHBoxLayout(QWidget * parent); impl<'a> /*trait*/ QHBoxLayout_new for (&'a QWidget) { fn new(self) -> QHBoxLayout { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QHBoxLayoutC2EP7QWidget()}; let ctysz: c_int = unsafe{QHBoxLayout_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN11QHBoxLayoutC2EP7QWidget(arg0)}; let rsthis = QHBoxLayout{qbase: QBoxLayout::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: const QMetaObject * QHBoxLayout::metaObject(); impl /*struct*/ QHBoxLayout { pub fn metaObject<RetType, T: QHBoxLayout_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QHBoxLayout_metaObject<RetType> { fn metaObject(self , rsthis: & QHBoxLayout) -> RetType; } // proto: const QMetaObject * QHBoxLayout::metaObject(); impl<'a> /*trait*/ QHBoxLayout_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QHBoxLayout) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QHBoxLayout10metaObjectEv()}; let mut ret = unsafe {C_ZNK11QHBoxLayout10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QHBoxLayout::~QHBoxLayout(); impl /*struct*/ QHBoxLayout { pub fn free<RetType, T: QHBoxLayout_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QHBoxLayout_free<RetType> { fn free(self , rsthis: & QHBoxLayout) -> RetType; } // proto: void QHBoxLayout::~QHBoxLayout(); impl<'a> /*trait*/ QHBoxLayout_free<()> for () { fn free(self , rsthis: & QHBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QHBoxLayoutD2Ev()}; unsafe {C_ZN11QHBoxLayoutD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QHBoxLayout::QHBoxLayout(); impl<'a> /*trait*/ QHBoxLayout_new for () { fn new(self) -> QHBoxLayout { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QHBoxLayoutC2Ev()}; let ctysz: c_int = unsafe{QHBoxLayout_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let qthis: u64 = unsafe {C_ZN11QHBoxLayoutC2Ev()}; let rsthis = QHBoxLayout{qbase: QBoxLayout::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } impl /*struct*/ QBoxLayout { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QBoxLayout { return QBoxLayout{qbase: QLayout::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QBoxLayout { type Target = QLayout; fn deref(&self) -> &QLayout { return & self.qbase; } } impl AsRef<QLayout> for QBoxLayout { fn as_ref(& self) -> & QLayout { return & self.qbase; } } // proto: int QBoxLayout::spacing(); impl /*struct*/ QBoxLayout { pub fn spacing<RetType, T: QBoxLayout_spacing<RetType>>(& self, overload_args: T) -> RetType { return overload_args.spacing(self); // return 1; } } pub trait QBoxLayout_spacing<RetType> { fn spacing(self , rsthis: & QBoxLayout) -> RetType; } // proto: int QBoxLayout::spacing(); impl<'a> /*trait*/ QBoxLayout_spacing<i32> for () { fn spacing(self , rsthis: & QBoxLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QBoxLayout7spacingEv()}; let mut ret = unsafe {C_ZNK10QBoxLayout7spacingEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: bool QBoxLayout::hasHeightForWidth(); impl /*struct*/ QBoxLayout { pub fn hasHeightForWidth<RetType, T: QBoxLayout_hasHeightForWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.hasHeightForWidth(self); // return 1; } } pub trait QBoxLayout_hasHeightForWidth<RetType> { fn hasHeightForWidth(self , rsthis: & QBoxLayout) -> RetType; } // proto: bool QBoxLayout::hasHeightForWidth(); impl<'a> /*trait*/ QBoxLayout_hasHeightForWidth<i8> for () { fn hasHeightForWidth(self , rsthis: & QBoxLayout) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QBoxLayout17hasHeightForWidthEv()}; let mut ret = unsafe {C_ZNK10QBoxLayout17hasHeightForWidthEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QBoxLayout::addItem(QLayoutItem * ); impl /*struct*/ QBoxLayout { pub fn addItem<RetType, T: QBoxLayout_addItem<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addItem(self); // return 1; } } pub trait QBoxLayout_addItem<RetType> { fn addItem(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::addItem(QLayoutItem * ); impl<'a> /*trait*/ QBoxLayout_addItem<()> for (&'a QLayoutItem) { fn addItem(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout7addItemEP11QLayoutItem()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN10QBoxLayout7addItemEP11QLayoutItem(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QSize QBoxLayout::sizeHint(); impl /*struct*/ QBoxLayout { pub fn sizeHint<RetType, T: QBoxLayout_sizeHint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.sizeHint(self); // return 1; } } pub trait QBoxLayout_sizeHint<RetType> { fn sizeHint(self , rsthis: & QBoxLayout) -> RetType; } // proto: QSize QBoxLayout::sizeHint(); impl<'a> /*trait*/ QBoxLayout_sizeHint<QSize> for () { fn sizeHint(self , rsthis: & QBoxLayout) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QBoxLayout8sizeHintEv()}; let mut ret = unsafe {C_ZNK10QBoxLayout8sizeHintEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QBoxLayout::~QBoxLayout(); impl /*struct*/ QBoxLayout { pub fn free<RetType, T: QBoxLayout_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QBoxLayout_free<RetType> { fn free(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::~QBoxLayout(); impl<'a> /*trait*/ QBoxLayout_free<()> for () { fn free(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayoutD2Ev()}; unsafe {C_ZN10QBoxLayoutD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QBoxLayout::insertSpacing(int index, int size); impl /*struct*/ QBoxLayout { pub fn insertSpacing<RetType, T: QBoxLayout_insertSpacing<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insertSpacing(self); // return 1; } } pub trait QBoxLayout_insertSpacing<RetType> { fn insertSpacing(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::insertSpacing(int index, int size); impl<'a> /*trait*/ QBoxLayout_insertSpacing<()> for (i32, i32) { fn insertSpacing(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout13insertSpacingEii()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; unsafe {C_ZN10QBoxLayout13insertSpacingEii(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QBoxLayout::setStretch(int index, int stretch); impl /*struct*/ QBoxLayout { pub fn setStretch<RetType, T: QBoxLayout_setStretch<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setStretch(self); // return 1; } } pub trait QBoxLayout_setStretch<RetType> { fn setStretch(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::setStretch(int index, int stretch); impl<'a> /*trait*/ QBoxLayout_setStretch<()> for (i32, i32) { fn setStretch(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout10setStretchEii()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; unsafe {C_ZN10QBoxLayout10setStretchEii(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QBoxLayout::insertStretch(int index, int stretch); impl /*struct*/ QBoxLayout { pub fn insertStretch<RetType, T: QBoxLayout_insertStretch<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insertStretch(self); // return 1; } } pub trait QBoxLayout_insertStretch<RetType> { fn insertStretch(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::insertStretch(int index, int stretch); impl<'a> /*trait*/ QBoxLayout_insertStretch<()> for (i32, Option<i32>) { fn insertStretch(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout13insertStretchEii()}; let arg0 = self.0 as c_int; let arg1 = (if self.1.is_none() {0} else {self.1.unwrap()}) as c_int; unsafe {C_ZN10QBoxLayout13insertStretchEii(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QBoxLayout::addLayout(QLayout * layout, int stretch); impl /*struct*/ QBoxLayout { pub fn addLayout<RetType, T: QBoxLayout_addLayout<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addLayout(self); // return 1; } } pub trait QBoxLayout_addLayout<RetType> { fn addLayout(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::addLayout(QLayout * layout, int stretch); impl<'a> /*trait*/ QBoxLayout_addLayout<()> for (&'a QLayout, Option<i32>) { fn addLayout(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout9addLayoutEP7QLayouti()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = (if self.1.is_none() {0} else {self.1.unwrap()}) as c_int; unsafe {C_ZN10QBoxLayout9addLayoutEP7QLayouti(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: bool QBoxLayout::setStretchFactor(QWidget * w, int stretch); impl /*struct*/ QBoxLayout { pub fn setStretchFactor<RetType, T: QBoxLayout_setStretchFactor<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setStretchFactor(self); // return 1; } } pub trait QBoxLayout_setStretchFactor<RetType> { fn setStretchFactor(self , rsthis: & QBoxLayout) -> RetType; } // proto: bool QBoxLayout::setStretchFactor(QWidget * w, int stretch); impl<'a> /*trait*/ QBoxLayout_setStretchFactor<i8> for (&'a QWidget, i32) { fn setStretchFactor(self , rsthis: & QBoxLayout) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout16setStretchFactorEP7QWidgeti()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1 as c_int; let mut ret = unsafe {C_ZN10QBoxLayout16setStretchFactorEP7QWidgeti(rsthis.qclsinst, arg0, arg1)}; return ret as i8; // 1 // return 1; } } // proto: void QBoxLayout::invalidate(); impl /*struct*/ QBoxLayout { pub fn invalidate<RetType, T: QBoxLayout_invalidate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.invalidate(self); // return 1; } } pub trait QBoxLayout_invalidate<RetType> { fn invalidate(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::invalidate(); impl<'a> /*trait*/ QBoxLayout_invalidate<()> for () { fn invalidate(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout10invalidateEv()}; unsafe {C_ZN10QBoxLayout10invalidateEv(rsthis.qclsinst)}; // return 1; } } // proto: void QBoxLayout::setGeometry(const QRect & ); impl /*struct*/ QBoxLayout { pub fn setGeometry<RetType, T: QBoxLayout_setGeometry<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setGeometry(self); // return 1; } } pub trait QBoxLayout_setGeometry<RetType> { fn setGeometry(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::setGeometry(const QRect & ); impl<'a> /*trait*/ QBoxLayout_setGeometry<()> for (&'a QRect) { fn setGeometry(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout11setGeometryERK5QRect()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN10QBoxLayout11setGeometryERK5QRect(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QBoxLayout::addStretch(int stretch); impl /*struct*/ QBoxLayout { pub fn addStretch<RetType, T: QBoxLayout_addStretch<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addStretch(self); // return 1; } } pub trait QBoxLayout_addStretch<RetType> { fn addStretch(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::addStretch(int stretch); impl<'a> /*trait*/ QBoxLayout_addStretch<()> for (Option<i32>) { fn addStretch(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout10addStretchEi()}; let arg0 = (if self.is_none() {0} else {self.unwrap()}) as c_int; unsafe {C_ZN10QBoxLayout10addStretchEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QBoxLayout::insertLayout(int index, QLayout * layout, int stretch); impl /*struct*/ QBoxLayout { pub fn insertLayout<RetType, T: QBoxLayout_insertLayout<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insertLayout(self); // return 1; } } pub trait QBoxLayout_insertLayout<RetType> { fn insertLayout(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::insertLayout(int index, QLayout * layout, int stretch); impl<'a> /*trait*/ QBoxLayout_insertLayout<()> for (i32, &'a QLayout, Option<i32>) { fn insertLayout(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout12insertLayoutEiP7QLayouti()}; let arg0 = self.0 as c_int; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = (if self.2.is_none() {0} else {self.2.unwrap()}) as c_int; unsafe {C_ZN10QBoxLayout12insertLayoutEiP7QLayouti(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: bool QBoxLayout::setStretchFactor(QLayout * l, int stretch); impl<'a> /*trait*/ QBoxLayout_setStretchFactor<i8> for (&'a QLayout, i32) { fn setStretchFactor(self , rsthis: & QBoxLayout) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout16setStretchFactorEP7QLayouti()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1 as c_int; let mut ret = unsafe {C_ZN10QBoxLayout16setStretchFactorEP7QLayouti(rsthis.qclsinst, arg0, arg1)}; return ret as i8; // 1 // return 1; } } // proto: int QBoxLayout::count(); impl /*struct*/ QBoxLayout { pub fn count<RetType, T: QBoxLayout_count<RetType>>(& self, overload_args: T) -> RetType { return overload_args.count(self); // return 1; } } pub trait QBoxLayout_count<RetType> { fn count(self , rsthis: & QBoxLayout) -> RetType; } // proto: int QBoxLayout::count(); impl<'a> /*trait*/ QBoxLayout_count<i32> for () { fn count(self , rsthis: & QBoxLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QBoxLayout5countEv()}; let mut ret = unsafe {C_ZNK10QBoxLayout5countEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: QLayoutItem * QBoxLayout::itemAt(int ); impl /*struct*/ QBoxLayout { pub fn itemAt<RetType, T: QBoxLayout_itemAt<RetType>>(& self, overload_args: T) -> RetType { return overload_args.itemAt(self); // return 1; } } pub trait QBoxLayout_itemAt<RetType> { fn itemAt(self , rsthis: & QBoxLayout) -> RetType; } // proto: QLayoutItem * QBoxLayout::itemAt(int ); impl<'a> /*trait*/ QBoxLayout_itemAt<QLayoutItem> for (i32) { fn itemAt(self , rsthis: & QBoxLayout) -> QLayoutItem { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QBoxLayout6itemAtEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK10QBoxLayout6itemAtEi(rsthis.qclsinst, arg0)}; let mut ret1 = QLayoutItem::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: const QMetaObject * QBoxLayout::metaObject(); impl /*struct*/ QBoxLayout { pub fn metaObject<RetType, T: QBoxLayout_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QBoxLayout_metaObject<RetType> { fn metaObject(self , rsthis: & QBoxLayout) -> RetType; } // proto: const QMetaObject * QBoxLayout::metaObject(); impl<'a> /*trait*/ QBoxLayout_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QBoxLayout) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QBoxLayout10metaObjectEv()}; let mut ret = unsafe {C_ZNK10QBoxLayout10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QBoxLayout::insertSpacerItem(int index, QSpacerItem * spacerItem); impl /*struct*/ QBoxLayout { pub fn insertSpacerItem<RetType, T: QBoxLayout_insertSpacerItem<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insertSpacerItem(self); // return 1; } } pub trait QBoxLayout_insertSpacerItem<RetType> { fn insertSpacerItem(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::insertSpacerItem(int index, QSpacerItem * spacerItem); impl<'a> /*trait*/ QBoxLayout_insertSpacerItem<()> for (i32, &'a QSpacerItem) { fn insertSpacerItem(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout16insertSpacerItemEiP11QSpacerItem()}; let arg0 = self.0 as c_int; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN10QBoxLayout16insertSpacerItemEiP11QSpacerItem(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: int QBoxLayout::heightForWidth(int ); impl /*struct*/ QBoxLayout { pub fn heightForWidth<RetType, T: QBoxLayout_heightForWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.heightForWidth(self); // return 1; } } pub trait QBoxLayout_heightForWidth<RetType> { fn heightForWidth(self , rsthis: & QBoxLayout) -> RetType; } // proto: int QBoxLayout::heightForWidth(int ); impl<'a> /*trait*/ QBoxLayout_heightForWidth<i32> for (i32) { fn heightForWidth(self , rsthis: & QBoxLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QBoxLayout14heightForWidthEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK10QBoxLayout14heightForWidthEi(rsthis.qclsinst, arg0)}; return ret as i32; // 1 // return 1; } } // proto: void QBoxLayout::addStrut(int ); impl /*struct*/ QBoxLayout { pub fn addStrut<RetType, T: QBoxLayout_addStrut<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addStrut(self); // return 1; } } pub trait QBoxLayout_addStrut<RetType> { fn addStrut(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::addStrut(int ); impl<'a> /*trait*/ QBoxLayout_addStrut<()> for (i32) { fn addStrut(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout8addStrutEi()}; let arg0 = self as c_int; unsafe {C_ZN10QBoxLayout8addStrutEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QSize QBoxLayout::maximumSize(); impl /*struct*/ QBoxLayout { pub fn maximumSize<RetType, T: QBoxLayout_maximumSize<RetType>>(& self, overload_args: T) -> RetType { return overload_args.maximumSize(self); // return 1; } } pub trait QBoxLayout_maximumSize<RetType> { fn maximumSize(self , rsthis: & QBoxLayout) -> RetType; } // proto: QSize QBoxLayout::maximumSize(); impl<'a> /*trait*/ QBoxLayout_maximumSize<QSize> for () { fn maximumSize(self , rsthis: & QBoxLayout) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QBoxLayout11maximumSizeEv()}; let mut ret = unsafe {C_ZNK10QBoxLayout11maximumSizeEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: int QBoxLayout::stretch(int index); impl /*struct*/ QBoxLayout { pub fn stretch<RetType, T: QBoxLayout_stretch<RetType>>(& self, overload_args: T) -> RetType { return overload_args.stretch(self); // return 1; } } pub trait QBoxLayout_stretch<RetType> { fn stretch(self , rsthis: & QBoxLayout) -> RetType; } // proto: int QBoxLayout::stretch(int index); impl<'a> /*trait*/ QBoxLayout_stretch<i32> for (i32) { fn stretch(self , rsthis: & QBoxLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QBoxLayout7stretchEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK10QBoxLayout7stretchEi(rsthis.qclsinst, arg0)}; return ret as i32; // 1 // return 1; } } // proto: void QBoxLayout::addSpacerItem(QSpacerItem * spacerItem); impl /*struct*/ QBoxLayout { pub fn addSpacerItem<RetType, T: QBoxLayout_addSpacerItem<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addSpacerItem(self); // return 1; } } pub trait QBoxLayout_addSpacerItem<RetType> { fn addSpacerItem(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::addSpacerItem(QSpacerItem * spacerItem); impl<'a> /*trait*/ QBoxLayout_addSpacerItem<()> for (&'a QSpacerItem) { fn addSpacerItem(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout13addSpacerItemEP11QSpacerItem()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN10QBoxLayout13addSpacerItemEP11QSpacerItem(rsthis.qclsinst, arg0)}; // return 1; } } // proto: int QBoxLayout::minimumHeightForWidth(int ); impl /*struct*/ QBoxLayout { pub fn minimumHeightForWidth<RetType, T: QBoxLayout_minimumHeightForWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.minimumHeightForWidth(self); // return 1; } } pub trait QBoxLayout_minimumHeightForWidth<RetType> { fn minimumHeightForWidth(self , rsthis: & QBoxLayout) -> RetType; } // proto: int QBoxLayout::minimumHeightForWidth(int ); impl<'a> /*trait*/ QBoxLayout_minimumHeightForWidth<i32> for (i32) { fn minimumHeightForWidth(self , rsthis: & QBoxLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QBoxLayout21minimumHeightForWidthEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK10QBoxLayout21minimumHeightForWidthEi(rsthis.qclsinst, arg0)}; return ret as i32; // 1 // return 1; } } // proto: QSize QBoxLayout::minimumSize(); impl /*struct*/ QBoxLayout { pub fn minimumSize<RetType, T: QBoxLayout_minimumSize<RetType>>(& self, overload_args: T) -> RetType { return overload_args.minimumSize(self); // return 1; } } pub trait QBoxLayout_minimumSize<RetType> { fn minimumSize(self , rsthis: & QBoxLayout) -> RetType; } // proto: QSize QBoxLayout::minimumSize(); impl<'a> /*trait*/ QBoxLayout_minimumSize<QSize> for () { fn minimumSize(self , rsthis: & QBoxLayout) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QBoxLayout11minimumSizeEv()}; let mut ret = unsafe {C_ZNK10QBoxLayout11minimumSizeEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QBoxLayout::setSpacing(int spacing); impl /*struct*/ QBoxLayout { pub fn setSpacing<RetType, T: QBoxLayout_setSpacing<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setSpacing(self); // return 1; } } pub trait QBoxLayout_setSpacing<RetType> { fn setSpacing(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::setSpacing(int spacing); impl<'a> /*trait*/ QBoxLayout_setSpacing<()> for (i32) { fn setSpacing(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout10setSpacingEi()}; let arg0 = self as c_int; unsafe {C_ZN10QBoxLayout10setSpacingEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QLayoutItem * QBoxLayout::takeAt(int ); impl /*struct*/ QBoxLayout { pub fn takeAt<RetType, T: QBoxLayout_takeAt<RetType>>(& self, overload_args: T) -> RetType { return overload_args.takeAt(self); // return 1; } } pub trait QBoxLayout_takeAt<RetType> { fn takeAt(self , rsthis: & QBoxLayout) -> RetType; } // proto: QLayoutItem * QBoxLayout::takeAt(int ); impl<'a> /*trait*/ QBoxLayout_takeAt<QLayoutItem> for (i32) { fn takeAt(self , rsthis: & QBoxLayout) -> QLayoutItem { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout6takeAtEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZN10QBoxLayout6takeAtEi(rsthis.qclsinst, arg0)}; let mut ret1 = QLayoutItem::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QBoxLayout::insertItem(int index, QLayoutItem * ); impl /*struct*/ QBoxLayout { pub fn insertItem<RetType, T: QBoxLayout_insertItem<RetType>>(& self, overload_args: T) -> RetType { return overload_args.insertItem(self); // return 1; } } pub trait QBoxLayout_insertItem<RetType> { fn insertItem(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::insertItem(int index, QLayoutItem * ); impl<'a> /*trait*/ QBoxLayout_insertItem<()> for (i32, &'a QLayoutItem) { fn insertItem(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout10insertItemEiP11QLayoutItem()}; let arg0 = self.0 as c_int; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN10QBoxLayout10insertItemEiP11QLayoutItem(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QBoxLayout::addSpacing(int size); impl /*struct*/ QBoxLayout { pub fn addSpacing<RetType, T: QBoxLayout_addSpacing<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addSpacing(self); // return 1; } } pub trait QBoxLayout_addSpacing<RetType> { fn addSpacing(self , rsthis: & QBoxLayout) -> RetType; } // proto: void QBoxLayout::addSpacing(int size); impl<'a> /*trait*/ QBoxLayout_addSpacing<()> for (i32) { fn addSpacing(self , rsthis: & QBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QBoxLayout10addSpacingEi()}; let arg0 = self as c_int; unsafe {C_ZN10QBoxLayout10addSpacingEi(rsthis.qclsinst, arg0)}; // return 1; } } impl /*struct*/ QVBoxLayout { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QVBoxLayout { return QVBoxLayout{qbase: QBoxLayout::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QVBoxLayout { type Target = QBoxLayout; fn deref(&self) -> &QBoxLayout { return & self.qbase; } } impl AsRef<QBoxLayout> for QVBoxLayout { fn as_ref(& self) -> & QBoxLayout { return & self.qbase; } } // proto: void QVBoxLayout::QVBoxLayout(); impl /*struct*/ QVBoxLayout { pub fn new<T: QVBoxLayout_new>(value: T) -> QVBoxLayout { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QVBoxLayout_new { fn new(self) -> QVBoxLayout; } // proto: void QVBoxLayout::QVBoxLayout(); impl<'a> /*trait*/ QVBoxLayout_new for () { fn new(self) -> QVBoxLayout { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QVBoxLayoutC2Ev()}; let ctysz: c_int = unsafe{QVBoxLayout_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let qthis: u64 = unsafe {C_ZN11QVBoxLayoutC2Ev()}; let rsthis = QVBoxLayout{qbase: QBoxLayout::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: const QMetaObject * QVBoxLayout::metaObject(); impl /*struct*/ QVBoxLayout { pub fn metaObject<RetType, T: QVBoxLayout_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QVBoxLayout_metaObject<RetType> { fn metaObject(self , rsthis: & QVBoxLayout) -> RetType; } // proto: const QMetaObject * QVBoxLayout::metaObject(); impl<'a> /*trait*/ QVBoxLayout_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QVBoxLayout) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QVBoxLayout10metaObjectEv()}; let mut ret = unsafe {C_ZNK11QVBoxLayout10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QVBoxLayout::QVBoxLayout(QWidget * parent); impl<'a> /*trait*/ QVBoxLayout_new for (&'a QWidget) { fn new(self) -> QVBoxLayout { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QVBoxLayoutC2EP7QWidget()}; let ctysz: c_int = unsafe{QVBoxLayout_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN11QVBoxLayoutC2EP7QWidget(arg0)}; let rsthis = QVBoxLayout{qbase: QBoxLayout::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QVBoxLayout::~QVBoxLayout(); impl /*struct*/ QVBoxLayout { pub fn free<RetType, T: QVBoxLayout_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QVBoxLayout_free<RetType> { fn free(self , rsthis: & QVBoxLayout) -> RetType; } // proto: void QVBoxLayout::~QVBoxLayout(); impl<'a> /*trait*/ QVBoxLayout_free<()> for () { fn free(self , rsthis: & QVBoxLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QVBoxLayoutD2Ev()}; unsafe {C_ZN11QVBoxLayoutD2Ev(rsthis.qclsinst)}; // return 1; } } // <= body block end
use serde::Deserialize; #[derive(Deserialize, Debug)] pub struct FlightTrailPositionRaw { pub lat: Option<f64>, pub lng: Option<f64>, pub alt: Option<f64>, pub spd: Option<f64>, pub ts: Option<i64>, pub hd: Option<i64>, }
use juniper::GraphQLEnum; #[derive(GraphQLEnum)] enum Test { Test, #[graphql(name = "TEST")] Test1, } fn main() {}
pub fn range(start: i32, end: i32) -> Vec<i32> { (start..end + 1).collect() } #[cfg(test)] mod tests { use super::*; #[test] fn test_range_4to9() { assert_eq!(range(4, 9), vec![4, 5, 6, 7, 8, 9]); } #[test] fn test_range_neg2to4() { assert_eq!(range(-2, 4), vec![-2, -1, 0, 1, 2, 3, 4]); } #[test] fn test_range_9to4() { assert_eq!(range(9, 4), vec![]); } }
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. /// A RSA public key in the format stated in RFC 3110, Section 2, used for DNS IPSECKEY and (formerly) KEY resource records. /// /// RFC 4025 Section 2.6 Final Paragraph increases the maximum size of `exponent` and `modulus` to 65,535 bytes (lifting the restrction of 4096 bits in RFC 3110 Section 2). #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct RsaPublicKey<'a> { /// An unsigned variable length integer. /// /// Must not start with leading zeros (`0x00`) but this is not validated or checked when data is received. /// /// Will never have a length of `0`. pub exponent: &'a [u8], /// An unsigned variable length integer. /// /// Must not start with leading zeros (`0x00`) but this is not validated or checked when data is received. /// /// Will never have a length of `0`. pub modulus: &'a [u8], }
use cargo::core::manifest::TargetSourcePath; use cargo::core::Edition; use failure::Fallible; use maplit::{btreeset, hashset}; use syn::visit::{self, Visit}; use syn::{Item, ItemMod, ItemUse, UseTree}; use std::collections::{BTreeSet, HashSet}; use std::path::Path; pub(crate) fn find_uses_lossy<'a>( src: &TargetSourcePath, extern_crates: &HashSet<&'a str>, edition: Edition, ) -> Fallible<HashSet<&'a str>> { match edition { Edition::Edition2015 => find_uses_lossy_2015(src, extern_crates), Edition::Edition2018 => find_uses_lossy_2018(src, extern_crates), } } fn find_uses_lossy_2015<'a>( src: &TargetSourcePath, extern_crates: &HashSet<&'a str>, ) -> Fallible<HashSet<&'a str>> { let root_path = match src.path() { None => return Ok(hashset!()), Some(path) => path, }; let file = crate::fs::read_src(root_path)?; if !file.attrs.is_empty() { return Ok(hashset!()); } Ok(file .items .into_iter() .flat_map(|item| match item { Item::ExternCrate(item) => Some(item), _ => None, }) .filter(|item| item.attrs.is_empty()) .flat_map(|item| extern_crates.get(&*item.ident.to_string()).cloned()) .collect()) } fn find_uses_lossy_2018<'a>( src: &TargetSourcePath, extern_crates: &HashSet<&'a str>, ) -> Fallible<HashSet<&'a str>> { struct Visitor<'a, 'b> { extern_crates: &'b HashSet<&'a str>, used: HashSet<&'a str>, mods: BTreeSet<String>, } impl<'a, 'b, 'ast> Visit<'ast> for Visitor<'a, 'b> { fn visit_item_mod(&mut self, item: &'ast ItemMod) { if item.attrs.is_empty() { if let Some((_, items)) = &item.content { let used = uses_of_extern_crates(items, self.extern_crates); self.used.extend(used); } else { self.mods.insert(item.ident.to_string()); } visit::visit_item_mod(self, item); } } fn visit_item_use(&mut self, item: &'ast ItemUse) { let used = use_of_extern_crate(item, self.extern_crates); self.used.extend(used); } } let root_path = match src.path() { None => return Ok(hashset!()), Some(path) => path.to_owned(), }; let (mut mods, mut used) = (btreeset!(vec![]), hashset!()); while !mods.is_empty() { let mut next_mods = btreeset!(); for mods in mods { let path = { let mut path = root_path.clone(); let mut mods = mods.iter().peekable(); if mods.peek().is_some() { path.pop(); } let mut another_path = None; while let Some(m) = mods.next() { if mods.peek().is_some() { path.push(m); } else { another_path = Some(path.join(m).join("mod.rs")); path.push(Path::new(m).with_extension("rs")); } } if path.exists() { path } else if let Some(another_path) = another_path { if another_path.exists() { another_path } else { return Err(failure::err_msg(format!( "No such file: {:?}", btreeset!(path, another_path), ))); } } else { return Err(failure::err_msg(format!("No such file: {:?}", path))); } }; let file = crate::fs::read_src(&path)?; let mut visitor = Visitor { extern_crates, used: uses_of_extern_crates(&file.items, extern_crates), mods: btreeset!(), }; visitor.visit_file(&file); for m in visitor.mods { let mut mods = mods.clone(); mods.push(m); next_mods.insert(mods); } used.extend(visitor.used); } mods = next_mods; } Ok(used) } fn use_of_extern_crate<'a>(item: &ItemUse, extern_crates: &HashSet<&'a str>) -> Option<&'a str> { if !item.attrs.is_empty() { return None; } let top = match &item.tree { UseTree::Path(path) => &path.ident, UseTree::Name(name) => &name.ident, UseTree::Rename(rename) => &rename.ident, _ => return None, }; extern_crates.get(&*top.to_string()).cloned() } fn uses_of_extern_crates<'a>(items: &[Item], extern_crates: &HashSet<&'a str>) -> HashSet<&'a str> { items .iter() .flat_map(|item| match item { Item::Use(item) => Some(item), _ => None, }) .flat_map(|item| use_of_extern_crate(item, extern_crates)) .collect() } #[cfg(test)] mod tests { use cargo::core::manifest::TargetSourcePath; use failure::Fallible; use maplit::hashset; use once_cell::sync::Lazy; use std::collections::HashSet; #[test] fn test_find_uses_lossy_2018() -> Fallible<()> { static PATH: Lazy<TargetSourcePath> = Lazy::new(|| TargetSourcePath::Path(file!().into())); static EXTERN_CRATES: Lazy<HashSet<&str>> = Lazy::new(|| hashset!("cargo", "failure", "maplit", "once_cell", "syn")); static EXPECTED: Lazy<HashSet<&str>> = Lazy::new(|| hashset!("cargo", "failure", "maplit", "syn")); let used = super::find_uses_lossy_2018(&PATH, &EXTERN_CRATES)?; assert_eq!(used, *EXPECTED); Ok(()) } }
mod gbc; mod gui; use gbc::Emu; use gui::{Gui}; use std::env; use anyhow::{Result, bail}; fn main() -> Result<()>{ if env::args().count() != 2 { bail!("Please enter the path to ROM.GB"); } let rom_name = env::args().nth(1).unwrap(); let emu = Emu::new(&rom_name)?; let mut gui = Gui::new(emu)?; gui.run(); Ok(()) }
extern crate rand; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; use rand::distributions::{IndependentSample, Range}; use rand::{thread_rng, Rng}; use std::path::Path; struct RandomLiner { reader: BufReader<File>, positions: Vec<usize>, } impl RandomLiner { fn new<P: AsRef<Path>>(path: P) -> RandomLiner { let mut reader = BufReader::new(File::open(path).unwrap()); let mut positions = vec![0]; let mut current_position = 0; let mut _buffer = Vec::new(); loop { let count = reader.read_until(b'\n', &mut _buffer).unwrap(); if count == 0 { positions.pop().unwrap(); break; } current_position += count; positions.push(current_position); } RandomLiner { reader: reader, positions: positions, } } fn get(&mut self, buf: &mut Vec<u8>) { if self.positions.is_empty() { panic!("no lines"); } let mut rng = rand::thread_rng(); let index = Range::new(0, self.positions.len()).ind_sample(&mut rng); self.reader.seek(SeekFrom::Start(self.positions[index] as u64)).unwrap(); self.reader.read_until(b'\n', buf).unwrap(); } } pub fn generate(s: &str) { let mut r = RandomLiner::new(s); let mut buf = Default::default(); r.get(&mut buf); buf.pop(); println!("{}-{:02x}", String::from_utf8(buf).unwrap(), thread_rng().gen::<u8>()); }
fn main() { println!("🔓 Challenge 28"); println!("Code in 'challenges/src/chal28.rs'"); }
use serde::Serialize; use std::error::Error as StdError; use thiserror::Error; use warp::http::StatusCode; use warp::{Rejection, Reply}; #[derive(Serialize)] struct ErrorMessage { code: u16, msg: String, } pub async fn recover(err: Rejection) -> Result<impl Reply, Rejection> { //api errors should be returned in json if let Some(ref err) = err.find::<Error>() { let error = match err { Error::InvalidDateFormat(_, _) | Error::PastDate(_) | Error::InvalidSymbol | Error::MissingDateBoundaries | Error::InvalidDateRange | Error::InvalidBase(_) => { log::trace!("api reject, {}", err); ErrorMessage { code: StatusCode::BAD_REQUEST.as_u16(), msg: err.to_string(), } } Error::DateNotFound(_) => { log::trace!("api reject, {}", err); ErrorMessage { code: StatusCode::NOT_FOUND.as_u16(), msg: "Not Found".into(), } } _ => { log::error!("unhandled error! {}", err); ErrorMessage { code: StatusCode::INTERNAL_SERVER_ERROR.as_u16(), msg: "Internal Server Error".into(), } } }; return Ok(warp::reply::with_status( warp::reply::json(&error), StatusCode::from_u16(error.code).unwrap(), )); }; Err(err) } #[derive(Error, Debug)] pub enum Error { #[error("no curencies found for date `{0}`")] DateNotFound(String), #[error("could not parse `{0}` as NaiveDate")] DateParse(String, #[source] chrono::ParseError), #[error("`{0}` is invalid, there are no currency rates for dates older then 1999-01-04.")] PastDate(&'static str), #[error("`{0}` is an invalid port")] InvalidPort(String, #[source] std::num::ParseIntError), #[error("start_at must be older than end_at")] InvalidDateRange, #[error("`{0}`: `{1}` is in an invalid date format, date must be in the format %Y-%m-%d")] InvalidDateFormat(&'static str, String), #[error("`{0}` is an invalid base currency")] InvalidBase(String), #[error("empty currency dataset, should have at least 1 element")] EmpyDataset, #[error("symbol list contains invalid symbols")] InvalidSymbol, #[error("both start_at and end_at parameters must be present")] MissingDateBoundaries, #[error("database error, `{0}`")] Database(String, #[source] Option<Box<dyn StdError + Sync + Send>>), #[error("error fetching currencies from ECB, `{0}`")] Fetcher(String), #[error("error rendering template, `{0}`")] Template(#[source] askama::Error), } impl warp::reject::Reject for Error {}
// 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::any::Any; use std::fmt::Debug; use std::fmt::Formatter; use common_expression::BlockMetaInfo; use common_expression::BlockMetaInfoPtr; use common_expression::Column; use common_expression::DataBlock; use crate::pipelines::processors::transforms::group_by::ArenaHolder; use crate::pipelines::processors::transforms::group_by::HashMethodBounds; use crate::pipelines::processors::transforms::HashTableCell; pub struct HashTablePayload<T: HashMethodBounds, V: Send + Sync + 'static> { pub bucket: isize, pub cell: HashTableCell<T, V>, pub arena_holder: ArenaHolder, } pub struct SerializedPayload { pub bucket: isize, pub data_block: DataBlock, } impl SerializedPayload { pub fn get_group_by_column(&self) -> &Column { let entry = self.data_block.columns().last().unwrap(); entry.value.as_column().unwrap() } } pub struct SpilledPayload { pub bucket: isize, pub location: String, pub columns_layout: Vec<usize>, } pub enum AggregateMeta<Method: HashMethodBounds, V: Send + Sync + 'static> { Serialized(SerializedPayload), HashTable(HashTablePayload<Method, V>), Spilling(HashTablePayload<Method, V>), Spilled(SpilledPayload), Partitioned { bucket: isize, data: Vec<Self> }, } impl<Method: HashMethodBounds, V: Send + Sync + 'static> AggregateMeta<Method, V> { pub fn create_hashtable(bucket: isize, cell: HashTableCell<Method, V>) -> BlockMetaInfoPtr { Box::new(AggregateMeta::<Method, V>::HashTable(HashTablePayload { cell, bucket, arena_holder: ArenaHolder::create(None), })) } pub fn create_serialized(bucket: isize, block: DataBlock) -> BlockMetaInfoPtr { Box::new(AggregateMeta::<Method, V>::Serialized(SerializedPayload { bucket, data_block: block, })) } pub fn create_spilling(bucket: isize, cell: HashTableCell<Method, V>) -> BlockMetaInfoPtr { Box::new(AggregateMeta::<Method, V>::Spilling(HashTablePayload { cell, bucket, arena_holder: ArenaHolder::create(None), })) } pub fn create_spilled( bucket: isize, location: String, columns_layout: Vec<usize>, ) -> BlockMetaInfoPtr { Box::new(AggregateMeta::<Method, V>::Spilled(SpilledPayload { bucket, location, columns_layout, })) } pub fn create_partitioned(bucket: isize, data: Vec<Self>) -> BlockMetaInfoPtr { Box::new(AggregateMeta::<Method, V>::Partitioned { data, bucket }) } } impl<Method: HashMethodBounds, V: Send + Sync + 'static> serde::Serialize for AggregateMeta<Method, V> { fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { unreachable!("AggregateMeta does not support exchanging between multiple nodes") } } impl<'de, Method: HashMethodBounds, V: Send + Sync + 'static> serde::Deserialize<'de> for AggregateMeta<Method, V> { fn deserialize<D>(_: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { unreachable!("AggregateMeta does not support exchanging between multiple nodes") } } impl<Method: HashMethodBounds, V: Send + Sync + 'static> Debug for AggregateMeta<Method, V> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { AggregateMeta::HashTable(_) => f.debug_struct("AggregateMeta::HashTable").finish(), AggregateMeta::Partitioned { .. } => { f.debug_struct("AggregateMeta::Partitioned").finish() } AggregateMeta::Serialized { .. } => { f.debug_struct("AggregateMeta::Serialized").finish() } AggregateMeta::Spilling(_) => f.debug_struct("Aggregate::Spilling").finish(), AggregateMeta::Spilled(_) => f.debug_struct("Aggregate::Spilled").finish(), } } } impl<Method: HashMethodBounds, V: Send + Sync + 'static> BlockMetaInfo for AggregateMeta<Method, V> { fn as_any(&self) -> &dyn Any { self } fn typetag_deserialize(&self) { unimplemented!("AggregateMeta does not support exchanging between multiple nodes") } fn typetag_name(&self) -> &'static str { unimplemented!("AggregateMeta does not support exchanging between multiple nodes") } fn equals(&self, _: &Box<dyn BlockMetaInfo>) -> bool { unimplemented!("Unimplemented equals for AggregateMeta") } fn clone_self(&self) -> Box<dyn BlockMetaInfo> { unimplemented!("Unimplemented clone for AggregateMeta") } }
use glutin::dpi::PhysicalSize; use math::{clamp_mut, Mat4, Vec2, Vec3, SAFE_HALF_PI_MAX, SAFE_HALF_PI_MIN}; pub struct Camera { pub f_width: f32, pub f_height: f32, mov: Vec2, pub position: Vec3, pub pointing: Vec3, pub right: Vec3, pub forward: Vec3, pub look_at: Vec3, up: Vec3, fov_y: f32, z_near: f32, z_far: f32, cached_view: Mat4, cached_projection: Mat4, pub speed: f32, enabled: bool, } impl Camera { pub fn new() -> Self { let mut state = Self { f_width: 500.0, f_height: 500.0, mov: Vec2::from_components(0.0, 0.0), position: Vec3::from_components(0.0, 0.0, 0.0), pointing: Vec3::from_components(1.0, 0.0, 0.0), right: Vec3::from_components(0.0, 0.0, 0.0), forward: Vec3::from_components(0.0, 0.0, 0.0), look_at: Vec3::from_components(0.0, 0.0, 0.0), up: Vec3::from_components(0.0, 1.0, 0.0), fov_y: std::f32::consts::FRAC_PI_2, z_near: 0.01, z_far: 1000.0, cached_view: Mat4::new(), cached_projection: Mat4::new(), speed: 4.0, enabled: false, }; state.make_valid(); state } pub fn make_valid(&mut self) { self.enabled = true; self.on_mouse_step(0.0, 0.0); self.enabled = false; self.look_at.add_vectors(&self.pointing, &self.position); } pub fn set_enabled(&mut self, enabled: bool) { self.enabled = enabled; } pub fn on_resize(&mut self, physical_size: PhysicalSize<u32>) { let (width, height) = physical_size.into(); self.f_width = width; self.f_height = height; } pub fn on_mouse_step(&mut self, x: f32, y: f32) { if !self.enabled { return; } self.mov.x += x / 1000.0; self.mov.y -= y / 1000.0; clamp_mut(&mut self.mov.y, SAFE_HALF_PI_MIN, SAFE_HALF_PI_MAX); self.pointing.to_sphere_coord(&self.mov); self.right.cross_vectors(&self.up, &self.pointing); self.right.normalize(); self.forward.cross_vectors(&self.up, &self.right); self.forward.normalize(); } pub fn get_matrix(&mut self) -> (&Mat4, &Mat4) { self.cached_view .look_at(&self.position, &self.look_at, &self.up); self.cached_projection.to_projection_matrix( self.z_near, self.z_far, self.fov_y, self.f_width / self.f_height, 1.0, ); (&self.cached_view, &self.cached_projection) } pub fn write_matrix(&self, cached_view: &mut Mat4, cached_projection: &mut Mat4) { cached_view.look_at(&self.position, &self.look_at, &self.up); cached_projection.to_projection_matrix( self.z_near, self.z_far, self.fov_y, self.f_width / self.f_height, 1.0, ); } }
use crate::ast; use crate::ast::expr::EagerBrace; use crate::{ParseError, Parser, Spanned, ToTokens}; use runestick::Span; use std::fmt; /// A unary expression. /// /// # Examples /// /// ```rust /// use rune::{testing, ast}; /// /// testing::roundtrip::<ast::ExprUnary>("!0"); /// testing::roundtrip::<ast::ExprUnary>("*foo"); /// testing::roundtrip::<ast::ExprUnary>("&foo"); /// testing::roundtrip::<ast::ExprUnary>("&Foo { /// a: 42, /// }"); /// ``` #[derive(Debug, Clone, PartialEq, Eq, ToTokens, Spanned)] pub struct ExprUnary { /// Attributes associated with expression. #[rune(iter)] pub attributes: Vec<ast::Attribute>, /// Token associated with operator. pub op_token: ast::Token, /// The expression of the operation. pub expr: ast::Expr, /// The operation to apply. #[rune(skip)] pub op: UnOp, } impl ExprUnary { /// Get the span of the op. pub fn op_span(&self) -> Span { self.op_token.span() } /// Parse the uniary expression with the given meta and configuration. pub(crate) fn parse_with_meta( parser: &mut Parser, attributes: Vec<ast::Attribute>, eager_brace: EagerBrace, ) -> Result<Self, ParseError> { let op_token = parser.next()?; let op = UnOp::from_token(op_token)?; Ok(Self { attributes, op_token, expr: ast::Expr::parse_with( parser, eager_brace, ast::expr::EagerBinary(false), ast::expr::Callable(true), )?, op, }) } } expr_parse!(Unary, ExprUnary, "try expression"); /// A unary operation. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum UnOp { /// Not `!<thing>`. Not, /// Negation `-<thing>`. Neg, /// Reference `&<thing>`. BorrowRef, /// Dereference `*<thing>`. Deref, } impl UnOp { /// Convert a unary operator from a token. pub fn from_token(t: ast::Token) -> Result<Self, ParseError> { match t.kind { K![!] => Ok(Self::Not), K![-] => Ok(Self::Neg), K![&] => Ok(Self::BorrowRef), K![*] => Ok(Self::Deref), _ => Err(ParseError::expected(&t, "unary operator, like `!` or `-`")), } } } impl fmt::Display for UnOp { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { Self::Not => write!(fmt, "!")?, Self::Neg => write!(fmt, "-")?, Self::BorrowRef => write!(fmt, "&")?, Self::Deref => write!(fmt, "*")?, } Ok(()) } }
extern crate nalgebra as na; extern crate nalgebra19 as na19; extern crate rand; extern crate tiled; mod assets; mod combat; mod enemies; mod physics; mod player; mod prelude; mod world; use amethyst::{ animation::AnimationBundle, assets::*, audio::{output::init_output, AudioBundle, SourceHandle, WavFormat}, core::transform::*, ecs::*, input::{is_close_requested, is_key_down}, prelude::*, renderer::{ bundle::RenderingBundle, camera::*, debug_drawing::DebugLines, palette::Srgba, plugins::{RenderDebugLines, RenderFlat2D, RenderToWindow}, sprite::SpriteSheetHandle, types::{DefaultBackend, Texture}, ImageFormat, SpriteRender, SpriteSheet, SpriteSheetFormat, }, tiles::{MortonEncoder, RenderTiles2D}, ui::{RenderUi, UiBundle, UiCreator, UiEventType, UiFinder}, utils::{ application_root_dir, fps_counter::{FpsCounter, FpsCounterBundle}, }, winit::VirtualKeyCode, }; use amethyst_imgui::RenderImgui; use assets::*; use combat::CombatBundle; use enemies::*; use imgui::*; use na::{Isometry2, Point2, Point3, RealField, UnitQuaternion, Vector2, Vector3}; use ncollide2d::shape::*; use nphysics2d::material::*; use nphysics2d::object::*; use physics::*; use player::*; use prelude::*; use std::f32::consts::PI; use world::*; #[derive(Default)] struct LoadingState { progress: Option<ProgressCounter>, assets: Option<(SpriteStorage, PrefabStorage, SoundStorage, MapStorage)>, } struct GameplayState { assets: (SpriteStorage, PrefabStorage, SoundStorage, MapStorage), } impl SimpleState for GameplayState { fn on_start(&mut self, mut data: StateData<'_, GameData<'_, '_>>) { data.world.delete_all(); data.world.insert(WaveState { idle_time: 0.0, wave_num: 0, }); data.world.insert(self.assets.0.clone()); data.world.insert(self.assets.1.clone()); data.world.insert(self.assets.2.clone()); data.world.insert(self.assets.3.clone()); initialize_tile_world(data.world); data.world.exec(|mut creator: UiCreator<'_>| { creator.create(get_resource("hud.ron"), ()); }); } fn update(&mut self, data: &mut StateData<'_, GameData<'_, '_>>) -> SimpleTrans { let (entities, names): (Entities<'_>, ReadStorage<'_, Named>) = data.world.system_data(); if get_named_entity(&entities, &names, "player").is_none() { return SimpleTrans::Switch(Box::new(MenuState { assets: self.assets.clone(), menu: "game_over.ron", })); } if get_named_entity(&entities, &names, "pylon").is_none() { return SimpleTrans::Switch(Box::new(MenuState { assets: self.assets.clone(), menu: "game_over.ron", })); } if data.world.read_resource::<WaveState>().wave_num == SPAWNS.len() { return SimpleTrans::Switch(Box::new(MenuState { assets: self.assets.clone(), menu: "game_over.ron", })); } SimpleTrans::None } } struct MenuState { assets: (SpriteStorage, PrefabStorage, SoundStorage, MapStorage), menu: &'static str, } impl SimpleState for MenuState { fn on_start(&mut self, mut data: StateData<'_, GameData<'_, '_>>) { data.world.delete_all(); data.world.exec(|mut creator: UiCreator<'_>| { creator.create(get_resource(self.menu), ()); }); } fn handle_event( &mut self, data: StateData<'_, GameData<'_, '_>>, event: StateEvent, ) -> SimpleTrans { match &event { StateEvent::Window(event) => { if is_close_requested(&event) { Trans::Quit } else { Trans::None } } StateEvent::Ui(ui_event) => data.world.exec(|finder: UiFinder<'_>| { if ui_event.event_type == UiEventType::Click { if let Some(start) = finder.find("play") { if start == ui_event.target { return Trans::Push(Box::new(GameplayState { assets: self.assets.clone(), })); } } if let Some(exit) = finder.find("exit") { if exit == ui_event.target { return Trans::Quit; } } } Trans::None }), _ => Trans::None, } } } impl SimpleState for LoadingState { fn on_start(&mut self, mut data: StateData<'_, GameData<'_, '_>>) { data.world.register::<PhysicsHandle>(); data.world.insert(AssetStorage::<TiledMap>::default()); init_output(data.world); let mut progress_counter = ProgressCounter::new(); let tile_spritesheet = load_spritesheet(data.world, get_resource("Tiles"), &mut progress_counter); let player_prefab = load_prefab( data.world, get_resource("Player.ron"), &mut progress_counter, ); let crab_prefab = load_prefab( data.world, get_resource("Enemies1.ron"), &mut progress_counter, ); let goblin_hit = load_sound_file( data.world, get_resource("Goblin_Hit.wav"), &mut progress_counter, ); let player_hit = load_sound_file( data.world, get_resource("Player_Hit.wav"), &mut progress_counter, ); let pylon_hit = load_sound_file( data.world, get_resource("Pylon_Hit.wav"), &mut progress_counter, ); let sword_slash = load_sound_file( data.world, get_resource("Sword_Slash.wav"), &mut progress_counter, ); let main_theme = load_sound_file( data.world, get_resource("MainTheme.wav"), &mut progress_counter, ); let village_map = load_map( data.world, get_resource("Village.tmx"), &mut progress_counter, ); self.progress = Some(progress_counter); self.assets = Some(( SpriteStorage { tile_spritesheet }, PrefabStorage { player: player_prefab, crab: crab_prefab, }, SoundStorage { goblin_hit, player_hit, pylon_hit, sword_slash, main_theme, }, MapStorage { village_map }, )); } fn update(&mut self, data: &mut StateData<GameData>) -> SimpleTrans { if let Some(progress) = &self.progress { println!("{:?}", progress); if progress.is_complete() { return SimpleTrans::Switch(Box::new(MenuState { assets: self.assets.clone().unwrap(), menu: "main_menu.ron", })); } } SimpleTrans::None } } struct ImguiDebugSystem { listbox_item_current: i32, box_current: i32, } impl Default for ImguiDebugSystem { fn default() -> Self { ImguiDebugSystem { listbox_item_current: 0, box_current: 0, } } } impl<'s> amethyst::ecs::System<'s> for ImguiDebugSystem { type SystemData = ( Read<'s, FpsCounter>, Option<Read<'s, SpriteStorage>>, Write<'s, Physics<f32>>, Entities<'s>, ReadStorage<'s, PhysicsHandle>, Read<'s, LazyUpdate>, ); fn run(&mut self, (fps, sprites, mut physics, entities, handles, update): Self::SystemData) { amethyst_imgui::with(|ui: &imgui::Ui| { let mut window = imgui::Window::new(im_str!("Test")); window.build(ui, || { ui.text(im_str!("This is a test!")); ui.text(im_str!("FPS: {}", fps.sampled_fps())); ui.separator(); let mut items = Vec::new(); let mut item_handles = Vec::new(); let mut idx = 0; for (entity, handle) in (&entities, &handles).join() { if let Some(body1) = physics.get_position(handle) { items.push(im_str!("Item: {}", idx,)); item_handles.push(handle); idx = idx + 1; } } let mut base = Vec::with_capacity(items.len()); for item in items.iter() { base.push(item); } let items = base.as_slice(); if ui.list_box( im_str!("Test"), &mut self.listbox_item_current, items.as_ref(), 15, ) { if let Some(handle) = item_handles.get(self.listbox_item_current as usize) { physics.apply_impulse(handle, Vector2::new(0.0, 100.0)); } } let mut drag = ui.drag_int(im_str!("Box"), &mut self.box_current); if drag.build() { for (handle) in (&handles).join() { physics.set_rotation( handle, self.box_current as f32 / 360.0 as f32 * std::f32::consts::FRAC_PI_2, ); } println!("{}", self.box_current); } }); }); } } fn main() -> amethyst::Result<()> { amethyst::start_logger(Default::default()); let display_config_path = get_resource("display_config.ron"); let input_path = get_resource("input.ron"); let game_data = GameDataBuilder::default() .with_system_desc( PrefabLoaderSystemDesc::<MyPrefabData>::default(), "scene_loader", &[], ) .with(DjSystem, "dj", &[]) .with(Processor::<TiledMap>::new(), "tiled_map_processor", &[]) .with_bundle(AnimationBundle::<AnimationId, SpriteRender>::new( "sprite_animation_control", "sprite_sampler_interpolation", ))? .with_bundle( TransformBundle::new() .with_dep(&["sprite_animation_control", "sprite_sampler_interpolation"]), )? .with_bundle( amethyst::input::InputBundle::<amethyst::input::StringBindings>::new() .with_bindings_from_file(input_path)?, )? .with_bundle( RenderingBundle::<DefaultBackend>::new() .with_plugin( RenderToWindow::from_config_path(display_config_path)? .with_clear([0.0, 0.0, 0.0, 1.0]), ) .with_plugin(RenderFlat2D::default()) .with_plugin(RenderTiles2D::<WorldTile, MortonEncoder>::default()) .with_plugin(RenderDebugLines::default()) .with_plugin(RenderUi::default()) .with_plugin(RenderImgui::<amethyst::input::StringBindings>::default()), )? .with_bundle(AudioBundle::default())? .with_bundle(PhysicsBundle)? .with_bundle(PlayerBundle)? .with_bundle(EnemiesBundle)? .with_bundle(CombatBundle)? .with_bundle(FpsCounterBundle)? .with_bundle(UiBundle::<amethyst::input::StringBindings>::new())?; let mut game = Application::new("", LoadingState::default(), game_data)?; game.run(); Ok(()) } pub trait IsoConvert { fn pos2(&self) -> Point2<f32>; fn pos3(&self) -> Point3<f32>; } impl IsoConvert for Isometry2<f32> { fn pos2(&self) -> Point2<f32> { [self.translation.x as f32, self.translation.y as f32].into() } fn pos3(&self) -> Point3<f32> { [self.translation.x as f32, self.translation.y as f32, 0.0].into() } } struct DebugDrawShapes; impl<'s> System<'s> for DebugDrawShapes { type SystemData = (Write<'s, DebugLines>, Read<'s, Physics<f32>>); fn run(&mut self, (mut debugLines, physics): Self::SystemData) { for (handle, collider) in physics.colliders.iter() { if let Some(circle) = collider.shape().as_shape::<Ball<f32>>() { debugLines.draw_circle( na19::geometry::Point3::<f32>::new( collider.position().pos3().x, collider.position().pos3().y, collider.position().pos3().z, ), circle.radius() as f32, 16, Srgba::new(1.0, 1.0, 1.0, 1.0), ); } else if let Some(cube) = collider.shape().as_shape::<Cuboid<f32>>() { let pos = collider.position().pos2(); let ext = cube.half_extents(); debugLines.draw_rotated_rectangle( [pos.x - ext.x as f32, pos.y - ext.y as f32].into(), [pos.x + ext.x as f32, pos.y + ext.y as f32].into(), 0.0, na19::UnitQuaternion::new(na19::Vector3::new( 0.0, 0.0, collider.position().rotation.angle() as f32, )), Srgba::new(1.0, 1.0, 1.0, 1.0), ); } } } }
//! Adaptive radix tree. #![warn(missing_docs)] #![warn(missing_debug_implementations)] #[macro_use] mod utils; mod bst; mod map; pub use bst::Bst; pub use map::{ConcurrentMap, SequentialMap};
use chrono::Local; use rand::{thread_rng, Rng}; #[derive(Eq, PartialEq, Clone, Debug)] pub struct TemporaryKey { unix_timestamp_secs: u64, unix_timestamp_millis: u16, random_part: u16, } impl TemporaryKey { /// generate a somewhat unique key for temporary tables /// /// The time when the key has been generated should be visible from the key itself. pub fn new() -> Self { let mut rng = thread_rng(); let ts_millis = Local::now().naive_utc().timestamp_millis().unsigned_abs(); Self { unix_timestamp_secs: ts_millis / 1000, unix_timestamp_millis: (ts_millis % 1000) as u16, random_part: rng.gen(), } } } impl ToString for TemporaryKey { fn to_string(&self) -> String { format!( "{}_{}_{}", self.unix_timestamp_secs, self.unix_timestamp_millis, self.random_part ) } } impl Default for TemporaryKey { fn default() -> Self { TemporaryKey::new() } } #[cfg(test)] mod tests { use super::TemporaryKey; #[test] fn temporary_key_is_unique() { dbg!(TemporaryKey::new()); assert_ne!( TemporaryKey::new().to_string(), TemporaryKey::new().to_string() ); } }
use async_trait::async_trait; use candy_frontend::{ ast_to_hir::{AstToHir, HirResult}, cst_to_ast::{AstResult, CstToAst}, hir_to_mir::{HirToMir, MirResult}, mir_optimize::{OptimizeMir, OptimizedMirResult}, mir_to_lir::{LirResult, MirToLir}, module::{Module, ModuleKind, PackagesPath}, position::{line_start_offsets_raw, Offset}, rich_ir::{ ReferenceCollection, ReferenceKey, RichIr, RichIrBuilder, ToRichIr, TokenModifier, TokenType, }, string_to_rcst::{ModuleError, RcstResult, StringToRcst}, TracingConfig, }; use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; use std::{fmt::Debug, hash::Hash, ops::Range, sync::Arc}; use strum::{EnumDiscriminants, EnumString, IntoStaticStr}; use tokio::sync::{Mutex, RwLock}; use tower_lsp::jsonrpc; use crate::{ database::Database, features::{LanguageFeatures, Reference}, semantic_tokens::{SemanticTokenModifier, SemanticTokenType, SemanticTokensBuilder}, server::Server, utils::{ lsp_position_to_offset_raw, module_from_url, module_to_url, range_to_lsp_range_raw, LspPositionConversion, }, }; use enumset::EnumSet; use extension_trait::extension_trait; use lsp_types::{ notification::Notification, FoldingRange, FoldingRangeKind, LocationLink, SemanticToken, }; use url::Url; #[derive(Debug, Eq, PartialEq, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ViewIrParams { pub uri: Url, } impl Server { pub async fn candy_view_ir(&self, params: ViewIrParams) -> jsonrpc::Result<String> { let state = self.state.read().await; let config = IrConfig::decode(&params.uri, &state.require_running().packages_path); let features = state.require_features(); features.ir.open(&self.db, config, params.uri.clone()).await; let open_irs = features.ir.open_irs.read().await; Ok(open_irs.get(&params.uri).unwrap().ir.text.to_owned()) } } #[derive(Debug, Default)] pub struct IrFeatures { open_irs: Arc<RwLock<FxHashMap<Url, OpenIr>>>, } impl IrFeatures { pub async fn generate_update_notifications( &self, module: &Module, ) -> Vec<UpdateIrNotification> { let open_irs = self.open_irs.read().await; open_irs .iter() .filter(|(_, open_ir)| &open_ir.config.module == module) .map(|(uri, _)| UpdateIrNotification { uri: uri.clone() }) .collect() } async fn ensure_is_open(&self, db: &Mutex<Database>, config: IrConfig) { let packages_path = { let db = db.lock().await; db.packages_path.to_owned() }; let uri = Url::from_config(&config, &packages_path); { let open_irs = self.open_irs.read().await; if open_irs.contains_key(&uri) { return; } } self.open(db, config, uri).await; } async fn open(&self, db: &Mutex<Database>, config: IrConfig, uri: Url) { let db = db.lock().await; let open_ir = self.create(&db, config); let mut open_irs = self.open_irs.write().await; open_irs.insert(uri, open_ir); } fn create(&self, db: &Database, config: IrConfig) -> OpenIr { let ir = match &config.ir { Ir::Rcst => Self::rich_ir_for_rcst(&config.module, db.rcst(config.module.clone())), Ir::Ast => Self::rich_ir_for_ast(&config.module, db.ast(config.module.clone())), Ir::Hir => Self::rich_ir_for_hir(&config.module, db.hir(config.module.clone())), Ir::Mir(tracing_config) => Self::rich_ir_for_mir( &config.module, db.mir(config.module.clone(), tracing_config.to_owned()), tracing_config, ), Ir::OptimizedMir(tracing_config) => Self::rich_ir_for_optimized_mir( &config.module, db.optimized_mir(config.module.clone(), tracing_config.to_owned()), tracing_config, ), Ir::Lir(tracing_config) => Self::rich_ir_for_lir( &config.module, &db.lir(config.module.clone(), tracing_config.to_owned()), tracing_config, ), Ir::VmByteCode(tracing_config) => Self::rich_ir_for_vm_byte_code( &config.module, &candy_vm::mir_to_lir::compile_lir( db, config.module.clone(), tracing_config.to_owned(), ) .0, tracing_config, ), }; let line_start_offsets = line_start_offsets_raw(&ir.text); OpenIr { config, ir, line_start_offsets, } } fn rich_ir_for_rcst(module: &Module, rcst: RcstResult) -> RichIr { Self::rich_ir_for("RCST", module, None, |builder| match rcst { Ok(rcst) => rcst.build_rich_ir(builder), Err(error) => Self::build_rich_ir_for_module_error(builder, module, &error), }) } fn rich_ir_for_ast(module: &Module, asts: AstResult) -> RichIr { Self::rich_ir_for("AST", module, None, |builder| match asts { Ok((asts, _)) => asts.build_rich_ir(builder), Err(error) => Self::build_rich_ir_for_module_error(builder, module, &error), }) } fn rich_ir_for_hir(module: &Module, hir: HirResult) -> RichIr { Self::rich_ir_for("HIR", module, None, |builder| match hir { Ok((hir, _)) => hir.build_rich_ir(builder), Err(error) => Self::build_rich_ir_for_module_error(builder, module, &error), }) } fn rich_ir_for_mir(module: &Module, mir: MirResult, tracing_config: &TracingConfig) -> RichIr { Self::rich_ir_for("MIR", module, tracing_config, |builder| match mir { Ok((mir, _)) => mir.build_rich_ir(builder), Err(error) => Self::build_rich_ir_for_module_error(builder, module, &error), }) } fn rich_ir_for_optimized_mir( module: &Module, mir: OptimizedMirResult, tracing_config: &TracingConfig, ) -> RichIr { Self::rich_ir_for( "Optimized MIR", module, tracing_config, |builder| match mir { Ok((mir, _, _)) => mir.build_rich_ir(builder), Err(error) => Self::build_rich_ir_for_module_error(builder, module, &error), }, ) } fn rich_ir_for_lir(module: &Module, lir: &LirResult, tracing_config: &TracingConfig) -> RichIr { Self::rich_ir_for("LIR", module, tracing_config, |builder| match lir { Ok((lir, _)) => lir.build_rich_ir(builder), Err(error) => Self::build_rich_ir_for_module_error(builder, module, error), }) } fn rich_ir_for_vm_byte_code( module: &Module, byte_code: &candy_vm::lir::Lir, tracing_config: &TracingConfig, ) -> RichIr { Self::rich_ir_for("VM Byte Code", module, tracing_config, |builder| { byte_code.build_rich_ir(builder) }) } fn rich_ir_for( ir_name: &str, module: &Module, tracing_config: impl Into<Option<&TracingConfig>>, build_rich_ir: impl FnOnce(&mut RichIrBuilder), ) -> RichIr { let mut builder = RichIrBuilder::default(); builder.push_comment_line(format!("{ir_name} for module {module}")); if let Some(tracing_config) = tracing_config.into() { builder.push_newline(); builder.push_tracing_config(tracing_config); } builder.push_newline(); build_rich_ir(&mut builder); builder.finish(true) } fn build_rich_ir_for_module_error( builder: &mut RichIrBuilder, module: &Module, module_error: &ModuleError, ) { match module_error { ModuleError::DoesNotExist => { builder.push( format!("# Module {module} does not exist"), TokenType::Comment, EnumSet::empty(), ); } ModuleError::InvalidUtf8 => { builder.push("# Invalid UTF-8", TokenType::Comment, EnumSet::empty()); } ModuleError::IsNotCandy => { builder.push("# Is not Candy code", TokenType::Comment, EnumSet::empty()); } ModuleError::IsToolingModule => { builder.push( "# Is a tooling module", TokenType::Comment, EnumSet::empty(), ); } } } } #[derive(Debug)] struct OpenIr { config: IrConfig, ir: RichIr, line_start_offsets: Vec<Offset>, } #[derive(Clone, Debug)] struct IrConfig { module: Module, ir: Ir, } impl IrConfig { fn decode(uri: &Url, packages_path: &PackagesPath) -> Self { let (path, ir) = uri.path().rsplit_once('.').unwrap(); let details = urlencoding::decode(uri.fragment().unwrap()).unwrap(); let mut details: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&details).unwrap(); let original_scheme = details.get("scheme").unwrap().as_str().unwrap(); let original_uri = format!("{original_scheme}:{path}").parse().unwrap(); let module_kind = match details.get("moduleKind").unwrap().as_str().unwrap() { "code" => ModuleKind::Code, "asset" => ModuleKind::Asset, module_kind => panic!("Unknown module kind: `{module_kind}`"), }; let tracing_config = details .remove("tracingConfig") .map(|it| serde_json::from_value(it).unwrap()); let ir = IrDiscriminants::try_from(ir).unwrap_or_else(|_| panic!("Unsupported IR: {ir}")); let ir = match ir { IrDiscriminants::Rcst => Ir::Rcst, IrDiscriminants::Ast => Ir::Ast, IrDiscriminants::Hir => Ir::Hir, IrDiscriminants::Mir => Ir::Mir(tracing_config.unwrap()), IrDiscriminants::OptimizedMir => Ir::OptimizedMir(tracing_config.unwrap()), IrDiscriminants::Lir => Ir::Lir(tracing_config.unwrap()), IrDiscriminants::VmByteCode => Ir::VmByteCode(tracing_config.unwrap()), }; IrConfig { module: module_from_url(&original_uri, module_kind, packages_path).unwrap(), ir, } } } #[extension_trait] impl UrlFromIrConfig for Url { fn from_config(config: &IrConfig, packages_path: &PackagesPath) -> Self { let ir: &'static str = IrDiscriminants::from(&config.ir).into(); let original_url = module_to_url(&config.module, packages_path).unwrap(); let mut details = serde_json::Map::new(); details.insert("scheme".to_string(), original_url.scheme().into()); match &config.ir { Ir::Mir(tracing_config) | Ir::OptimizedMir(tracing_config) | Ir::Lir(tracing_config) => { details.insert( "tracingConfig".to_string(), serde_json::to_value(tracing_config).unwrap(), ); } _ => {} } Url::parse( format!( "candy-ir:{}.{ir}#{}", original_url.path(), urlencoding::encode(serde_json::to_string(&details).unwrap().as_str()), ) .as_str(), ) .unwrap() } } #[derive(Clone, Debug, EnumDiscriminants, Eq, Hash, PartialEq)] #[strum_discriminants( derive(EnumString, Hash, IntoStaticStr), strum(serialize_all = "camelCase") )] pub enum Ir { Rcst, Ast, Hir, Mir(TracingConfig), OptimizedMir(TracingConfig), Lir(TracingConfig), VmByteCode(TracingConfig), } impl Ir { fn tracing_config(&self) -> Option<&TracingConfig> { match self { Ir::Rcst | Ir::Ast | Ir::Hir => None, Ir::Mir(tracing_config) | Ir::OptimizedMir(tracing_config) | Ir::Lir(tracing_config) | Ir::VmByteCode(tracing_config) => Some(tracing_config), } } } #[derive(Debug, Serialize, Deserialize)] pub struct UpdateIrNotification { pub uri: Url, } impl Notification for UpdateIrNotification { const METHOD: &'static str = "candy/updateIr"; type Params = Self; } #[async_trait] impl LanguageFeatures for IrFeatures { fn language_id(&self) -> Option<String> { None } fn supported_url_schemes(&self) -> Vec<&'static str> { vec!["candy-ir"] } fn supports_find_definition(&self) -> bool { true } async fn find_definition( &self, db: &Mutex<Database>, uri: Url, position: lsp_types::Position, ) -> Option<LocationLink> { let (origin_selection_range, key, config) = { let open_irs = self.open_irs.read().await; let open_ir = open_irs.get(&uri).unwrap(); let offset = open_ir.lsp_position_to_offset(position); let (key, result) = open_ir.find_references_entry(offset)?; let origin_selection_range = result .references .iter() .find(|it| it.contains(&offset)) .unwrap_or_else(|| result.definition.as_ref().unwrap()); let origin_selection_range = open_ir.range_to_lsp_range(origin_selection_range); if let Some(definition) = &result.definition { let target_range = open_ir.range_to_lsp_range(definition); return Some(LocationLink { origin_selection_range: Some(origin_selection_range), target_uri: uri, target_range, target_selection_range: target_range, }); } ( origin_selection_range, key.to_owned(), open_ir.config.to_owned(), ) }; let packages_path = { let db = db.lock().await; db.packages_path.to_owned() }; let packages_path_for_function = packages_path.clone(); let find_in_other_ir = async move |config: IrConfig, key: &ReferenceKey| { let uri = Url::from_config(&config, &packages_path_for_function); self.ensure_is_open(db, config).await; let rich_irs = self.open_irs.read().await; let other_ir = rich_irs.get(&uri).unwrap(); let result = other_ir.ir.references.get(key).unwrap(); let target_range = other_ir.range_to_lsp_range(result.definition.as_ref().unwrap()); (uri, target_range) }; let (uri, target_range) = match &key { ReferenceKey::Int(_) | ReferenceKey::Text(_) | ReferenceKey::Symbol(_) | ReferenceKey::BuiltinFunction(_) => { // These don't have a definition in Candy source code. return None; } ReferenceKey::Module(module) => ( module_to_url(module, &packages_path).unwrap(), lsp_types::Range::default(), ), ReferenceKey::ModuleWithSpan(module, span) => { let db = db.lock().await; let range = db.range_to_lsp_range(module.to_owned(), span.to_owned()); (module_to_url(module, &packages_path).unwrap(), range) } ReferenceKey::HirId(id) => { let config = IrConfig { module: id.module.to_owned(), ir: Ir::Hir, }; find_in_other_ir(config, &key).await } ReferenceKey::MirId(_) => { let config = IrConfig { module: config.module.to_owned(), ir: Ir::Mir( config .ir .tracing_config() .map(|it| it.to_owned()) .unwrap_or_else(TracingConfig::off), ), }; find_in_other_ir(config, &key).await } ReferenceKey::LirId(_) | ReferenceKey::LirConstantId(_) | ReferenceKey::LirBodyId(_) => { let config = IrConfig { module: config.module.to_owned(), ir: Ir::Lir( config .ir .tracing_config() .map(|it| it.to_owned()) .unwrap_or_else(TracingConfig::off), ), }; find_in_other_ir(config, &key).await } }; Some(LocationLink { origin_selection_range: Some(origin_selection_range), target_uri: uri, target_range, target_selection_range: target_range, }) } fn supports_folding_ranges(&self) -> bool { true } async fn folding_ranges(&self, _db: &Mutex<Database>, uri: Url) -> Vec<FoldingRange> { let open_irs = self.open_irs.read().await; dbg!(&uri); dbg!(&open_irs.keys()); let open_ir = open_irs.get(&uri).unwrap(); open_ir.folding_ranges() } fn supports_references(&self) -> bool { true } async fn references( &self, _db: &Mutex<Database>, uri: Url, position: lsp_types::Position, only_in_same_document: bool, include_declaration: bool, ) -> FxHashMap<Url, Vec<Reference>> { let open_irs = self.open_irs.read().await; let open_ir = open_irs.get(&uri).unwrap(); let offset = open_ir.lsp_position_to_offset(position); let Some((reference_key, _)) = open_ir.find_references_entry(offset) else { return FxHashMap::default(); }; if only_in_same_document { FxHashMap::from_iter([( uri, open_ir.find_references(reference_key, include_declaration), )]) } else { open_irs .iter() .map(|(uri, ir)| { ( uri.to_owned(), ir.find_references(reference_key, include_declaration), ) }) .filter(|(_, references)| !references.is_empty()) .collect() } } fn supports_semantic_tokens(&self) -> bool { true } async fn semantic_tokens(&self, _db: &Mutex<Database>, uri: Url) -> Vec<SemanticToken> { let open_irs = self.open_irs.read().await; let open_ir = open_irs.get(&uri).unwrap(); open_ir.semantic_tokens() } } impl OpenIr { fn folding_ranges(&self) -> Vec<FoldingRange> { self.ir .folding_ranges .iter() .map(|range| { let range = self.range_to_lsp_range(range); FoldingRange { start_line: range.start.line, start_character: Some(range.start.character), end_line: range.end.line, end_character: Some(range.end.character), kind: Some(FoldingRangeKind::Region), // TODO: Customize collapsed text collapsed_text: None, } }) .collect() } fn find_references( &self, reference_key: &ReferenceKey, include_declaration: bool, ) -> Vec<Reference> { let Some(result) = self.ir.references.get(reference_key) else { return vec![]; }; let mut references = vec![]; if include_declaration && let Some(definition) = &result.definition { references.push(Reference { range: self.range_to_lsp_range(definition), is_write: true, }) } for reference in &result.references { references.push(Reference { range: self.range_to_lsp_range(reference), is_write: true, }) } references } fn find_references_entry( &self, offset: Offset, ) -> Option<(&ReferenceKey, &ReferenceCollection)> { self.ir.references.iter().find(|(_, value)| { value .definition .as_ref() .map(|it| it.contains(&offset)) .unwrap_or_default() || value.references.iter().any(|it| it.contains(&offset)) }) } fn semantic_tokens(&self) -> Vec<SemanticToken> { let mut builder = SemanticTokensBuilder::new(&self.ir.text, &self.line_start_offsets); for annotation in &self.ir.annotations { let Some(token_type) = annotation.token_type else { continue; }; builder.add( annotation.range.clone(), token_type.to_semantic(), annotation .token_modifiers .iter() .map(|it| it.to_semantic()) .collect(), ); } builder.finish() } fn lsp_position_to_offset(&self, position: lsp_types::Position) -> Offset { lsp_position_to_offset_raw(&self.ir.text, &self.line_start_offsets, position) } fn range_to_lsp_range(&self, range: &Range<Offset>) -> lsp_types::Range { range_to_lsp_range_raw(&self.ir.text, &self.line_start_offsets, range) } } #[extension_trait] impl TokenTypeToSemantic for TokenType { fn to_semantic(&self) -> SemanticTokenType { match self { TokenType::Module => SemanticTokenType::Module, TokenType::Parameter => SemanticTokenType::Parameter, TokenType::Variable => SemanticTokenType::Variable, TokenType::Function => SemanticTokenType::Function, TokenType::Comment => SemanticTokenType::Comment, TokenType::Symbol => SemanticTokenType::Symbol, TokenType::Text => SemanticTokenType::Text, TokenType::Int => SemanticTokenType::Int, TokenType::Address => SemanticTokenType::Address, TokenType::Constant => SemanticTokenType::Constant, } } } #[extension_trait] impl TokenModifierToSemantic for TokenModifier { fn to_semantic(&self) -> SemanticTokenModifier { match self { TokenModifier::Builtin => SemanticTokenModifier::Builtin, } } }
use crate::{check_b64_arg, ok, Error, NsmDescription, NsmResponse, NsmResult}; use nsm_driver::nsm_process_request; use nsm_io::{Digest, ErrorCode, Request, Response}; pub fn nsm_get_attestation_doc( fd: i32, n: Option<String>, pk: Option<String>, ud: Option<String>, ) -> NsmResult<NsmResponse> { let mut nonce = None; check_b64_arg(&mut nonce, n, "nonce")?; let mut public_key = None; check_b64_arg(&mut public_key, pk, "public key")?; let mut user_data = None; check_b64_arg(&mut user_data, ud, "user data")?; let request = Request::Attestation { nonce, user_data, public_key, }; match nsm_process_request(fd, request) { Response::Attestation { document } => Ok(ok(base64_url::encode(document.as_slice()))), Response::Error(err) => Err(Error { msg: "Unable to generate attestation document".to_string(), code: err, }), _ => Err(Error { msg: "Unable to generate attestation document".to_string(), code: ErrorCode::InvalidResponse, }), } } pub fn nsm_get_random(fd: i32, number: u8) -> NsmResult<NsmResponse> { match nsm_process_request(fd, Request::GetRandom) { Response::GetRandom { random } => Ok(ok(base64_url::encode(&random[..(number as usize)]))), Response::Error(err) => Err(Error { msg: "Unable to read random bytes".to_string(), code: err, }), e => Err(Error { msg: format!("{:?}", e), code: ErrorCode::InvalidResponse, }), } } pub fn nsm_extend_pcr(fd: i32, index: u16, d: String) -> NsmResult<NsmResponse> { let mut data = vec![]; match base64_url::decode(&d) { Ok(v) => data.extend_from_slice(v.as_slice()), Err(_) => { return Err(Error { msg: "Invalid data supplied".to_string(), code: ErrorCode::InvalidArgument, }) } }; let request = Request::ExtendPCR { index, data }; match nsm_process_request(fd, request) { Response::ExtendPCR { data: pcr } => Ok(ok(base64_url::encode(pcr.as_slice()))), Response::Error(e) => Err(Error { msg: "Unable to extend pcr".to_string(), code: e, }), _ => Err(Error { msg: "Unable to extend pcr".to_string(), code: ErrorCode::InvalidResponse, }), } } pub fn nsm_lock_pcr(fd: i32, index: u16) -> NsmResult<NsmResponse> { let request = Request::LockPCR { index }; match nsm_process_request(fd, request) { Response::LockPCR => Ok(ok(String::new())), Response::Error(err) => Err(Error { code: err, msg: "Unable to lock pcr".to_string(), }), _ => Err(Error { code: ErrorCode::InvalidResponse, msg: "Unable to lock pcr".to_string(), }), } } pub fn nsm_lock_pcrs(fd: i32, range: u16) -> NsmResult<NsmResponse> { let request = Request::LockPCRs { range }; match nsm_process_request(fd, request) { Response::LockPCRs => Ok(ok(String::new())), Response::Error(err) => Err(Error { code: err, msg: "Unable to lock pcrs".to_string(), }), _ => Err(Error { code: ErrorCode::InvalidResponse, msg: "Unable to lock pcrs".to_string(), }), } } pub fn nsm_describe_pcr(fd: i32, index: u16) -> NsmResult<NsmResponse> { let request = Request::DescribePCR { index }; match nsm_process_request(fd, request) { Response::DescribePCR { lock, data } => { let msg = format!( r#"{{"lock":{},"data":"{}"}}"#, lock, base64_url::encode(data.as_slice()) ); Ok(ok(base64_url::encode(&msg.as_bytes()))) } Response::Error(err) => Err(Error { code: err, msg: "Unable to describe pcr".to_string(), }), _ => Err(Error { code: ErrorCode::InvalidResponse, msg: "Unable to describe pcr".to_string(), }), } } pub fn nsm_describe(fd: i32) -> NsmResult<NsmResponse> { let request = Request::DescribeNSM; match nsm_process_request(fd, request) { Response::DescribeNSM { version_major, version_minor, version_patch, module_id, max_pcrs, locked_pcrs, digest, } => { let mut nsm_description = NsmDescription::default(); nsm_description.version_major = version_major; nsm_description.version_minor = version_minor; nsm_description.version_patch = version_patch; nsm_description.max_pcrs = max_pcrs; match digest { Digest::SHA256 => { nsm_description.digest = Digest::SHA256; } Digest::SHA384 => { nsm_description.digest = Digest::SHA384; } Digest::SHA512 => { nsm_description.digest = Digest::SHA512; } } nsm_description.locked_pcrs_len = locked_pcrs.len() as u32; for (i, val) in locked_pcrs.iter().enumerate() { nsm_description.locked_pcrs[i] = *val; } let module_id_len = std::cmp::min(nsm_description.module_id.len() - 1, module_id.len()); nsm_description.module_id[0..module_id_len] .copy_from_slice(&module_id.as_bytes()[0..module_id_len]); nsm_description.module_id[module_id_len] = 0; nsm_description.module_id_len = module_id_len as u32; Ok(ok(serde_json::to_string(&nsm_description).unwrap())) } Response::Error(err) => Err(Error { code: err, msg: "Unable to describe nsm".to_string(), }), _ => Err(Error { code: ErrorCode::InvalidResponse, msg: "Unable to describe nsm".to_string(), }), } }
use object_chain::{Chain, ChainElement, Link}; use crate::{ geometry::{ measurement::{MeasureConstraint, MeasureSpec}, BoundingBox, Position, }, input::event::InputEvent, state::WidgetState, widgets::{ layouts::linear::{ private::{LayoutDirection, LinearLayoutChainElement}, Cell, NoWeight, Weight, }, Widget, }, Canvas, WidgetRenderer, }; /// Common implementation of linear layouts. /// /// ## Cell measurement /// /// The measurement process consists of two phases. At first, cells without weight are measured. /// Then, the rest of the available space is partitioned according to the weights of the remaining /// cells. The more weight a cell has, the more space it will take up. /// /// ### Example: /// /// We have a layout with three cells: /// - A cell with weight 1. /// - A cell without weight, which contains a widget that is 40 px high. /// - A cell with weight 2. /// /// The layout has 160 px height. /// /// 1. At first, the second cell is measured. It needs 40 px for its widget, which leaves 120 px of /// unused space. /// 2. Next, the remaining space is divided into 3 (the sum of weights), and assigned to the rest of /// the cells. Each cell receives space according to its weight. /// /// The final layout will look like this: /// - The first cell will take up 40 px because of weight 1. /// - The second cell will take up 40 px because it has a fixed height of 40. /// - The third cell will take up 80 px because of weight 2. /// pub struct LinearLayout<CE, L> { pub bounds: BoundingBox, pub widgets: CE, pub direction: L, } impl<CE, L> LinearLayout<CE, L> where CE: LinearLayoutChainElement + ChainElement, { /// Appends a cell to the end of the layout. /// /// Initially, a cell has no weight. Call `weight` to specify the weight of the most recently /// added cell. pub fn add<W>(self, widget: W) -> LinearLayout<Link<Cell<W, NoWeight>, CE>, L> where W: Widget, { LinearLayout { bounds: self.bounds, widgets: self.widgets.append(Cell::new(widget)), direction: self.direction, } } fn locate(&self, mut idx: usize) -> Option<(usize, usize)> { let children = self.widgets.len(); for i in 0..children { let child = self.widgets.at(i).widget(); let grandchildren = child.children(); if idx <= grandchildren { return Some((i, idx)); } idx -= grandchildren + 1; } None } } impl<W, CE, L> LinearLayout<Link<Cell<W, NoWeight>, CE>, L> where W: Widget, CE: LinearLayoutChainElement + ChainElement, { /// Sets the weight of the most recently appended cell. /// /// Weight specifies the relative size of the cell in the second phase of the layout process. /// See [`LinearLayout#cell-measurement`] for more information. pub fn weight(self, weight: u32) -> LinearLayout<Link<Cell<W, Weight>, CE>, L> { LinearLayout { bounds: self.bounds, widgets: Link { object: self.widgets.object.weight(weight), parent: self.widgets.parent, }, direction: self.direction, } } } impl<W, L> LinearLayout<Chain<Cell<W, NoWeight>>, L> where W: Widget, { /// Sets the weight of the most recently appended cell. /// /// Weight specifies the relative size of the cell in the second phase of the layout process. /// See [`LinearLayout#cell-measurement`] for more information. pub fn weight(self, weight: u32) -> LinearLayout<Chain<Cell<W, Weight>>, L> { LinearLayout { bounds: self.bounds, widgets: Chain { object: self.widgets.object.weight(weight), }, direction: self.direction, } } } impl<CE, L> Widget for LinearLayout<CE, L> where CE: LinearLayoutChainElement + ChainElement, L: LayoutDirection, { fn attach(&mut self, parent: usize, index: usize) { debug_assert!(index == 0 || parent != index); let mut children = index; for i in 0..self.widgets.len() { let widget = self.widgets.at_mut(i).widget_mut(); widget.attach(parent, children + i); children += widget.children(); } } fn bounding_box(&self) -> BoundingBox { self.bounds } fn bounding_box_mut(&mut self) -> &mut BoundingBox { &mut self.bounds } fn measure(&mut self, measure_spec: MeasureSpec) { let count = self.widgets.len(); let mut total_fixed_main_axis_size = 0; let mut max_cross = 0; let max_main_axis_size = match L::main_axis_measure_spec(measure_spec) { MeasureConstraint::AtMost(max) | MeasureConstraint::Exactly(max) => max, MeasureConstraint::Unspecified => { // Weight makes no sense here as we have "infinite" space. for i in 0..count { let widget = self.widgets.at_mut(i).widget_mut(); widget.measure(measure_spec); total_fixed_main_axis_size += L::main_axis_size(widget.bounding_box()); max_cross = max_cross.max(L::cross_axis_size(widget.bounding_box())); } total_fixed_main_axis_size += (count as u32 - 1) * self.direction.element_spacing(); // TODO this is almost the same as the bottom of the function. Should deduplicate. self.bounds.size = L::create_measured_size( total_fixed_main_axis_size, L::cross_axis_measure_spec(measure_spec).apply_to_measured(max_cross), ); return; } }; let mut total_weight = 0; // Count the height of the widgets that don't have a weight for i in 0..count { let cell = self.widgets.at_mut(i); let weight = cell.weight(); if weight == 0 { let spec = L::create_measure_spec( MeasureConstraint::AtMost(max_main_axis_size - total_fixed_main_axis_size), L::cross_axis_measure_spec(measure_spec), ); let widget = cell.widget_mut(); widget.measure(spec); total_fixed_main_axis_size += L::main_axis_size(widget.bounding_box()); max_cross = max_cross.max(L::cross_axis_size(widget.bounding_box())); } else { total_weight += weight; } } // We don't want to take space away from non-weighted widgets, // so add spacing after first pass. total_fixed_main_axis_size += (count as u32 - 1) * self.direction.element_spacing(); // Divide the rest of the space among the weighted widgets if total_weight != 0 { let remaining_space = max_main_axis_size - total_fixed_main_axis_size; let height_per_weight_unit = remaining_space / total_weight; // in case we have some stray pixels, divide them up evenly let mut remainder = remaining_space % total_weight; for i in 0..count { let cell = self.widgets.at_mut(i); let weight = cell.weight(); if weight != 0 { let rem = if remainder > 0 { remainder.min(weight) } else { 0 }; remainder -= rem; let spec = L::create_measure_spec( MeasureConstraint::Exactly(height_per_weight_unit * weight + rem), L::cross_axis_measure_spec(measure_spec), ); let widget = cell.widget_mut(); widget.measure(spec); max_cross = max_cross.max(L::cross_axis_size(widget.bounding_box())); } } } self.bounds.size = L::create_measured_size( if total_weight == 0 { total_fixed_main_axis_size } else { max_main_axis_size }, L::cross_axis_measure_spec(measure_spec).apply_to_measured(max_cross), ); } fn arrange(&mut self, position: Position) { self.bounds.position = position; self.widgets .arrange(position, self.direction, self.direction.element_spacing()); } fn children(&self) -> usize { self.widgets.count_widgets() } fn get_child(&self, idx: usize) -> &dyn Widget { let (child, grandchild) = self.locate(idx).unwrap(); let widget = self.widgets.at(child).widget(); if grandchild == 0 { widget } else { widget.get_child(grandchild - 1) } } fn get_mut_child(&mut self, idx: usize) -> &mut dyn Widget { let (child, grandchild) = self.locate(idx).unwrap(); let widget = self.widgets.at_mut(child).widget_mut(); if grandchild == 0 { widget } else { widget.get_mut_child(grandchild - 1) } } fn parent_index(&self) -> usize { self.widgets.at(0).widget().parent_index() } fn set_parent(&mut self, _index: usize) {} fn update(&mut self) { self.widgets.update(); } fn test_input(&mut self, event: InputEvent) -> Option<usize> { self.widgets.test_input(event).map(|idx| idx + 1) } fn on_state_changed(&mut self, state: WidgetState) { self.widgets.on_state_changed(state); } fn is_selectable(&self) -> bool { false } } impl<C, CE, L> WidgetRenderer<C> for LinearLayout<CE, L> where CE: LinearLayoutChainElement + ChainElement + WidgetRenderer<C>, C: Canvas, { fn draw(&mut self, canvas: &mut C) -> Result<(), C::Error> { self.widgets.draw(canvas) } }
extern crate limonite; use limonite::syntax::expr::{Expr, ExprWrapper}; use limonite::syntax::op::InfixOp::*; use limonite::syntax::literals::Literals::*; use limonite::semantic::type_checker::TypeChecker; use limonite::semantic::analyzer_trait::ASTAnalyzer; // Type Checker #[test] fn test_type_inference_builtin_type() { // var string = "RHS" // expands to // var string: str = "RHS" let mut input_ast = ExprWrapper::default( Expr::VarDecl( false, "string".into(), None, ExprWrapper::default(Expr::Literal(UTF8String("RHS".into()))) ) ); TypeChecker::new().analyze(&mut input_ast); let desired_ast = ExprWrapper::default( Expr::VarDecl( false, "string".into(), Some("str".into()), ExprWrapper::default(Expr::Literal(UTF8String("RHS".into()))) ) ); assert!(input_ast == desired_ast); } #[test] fn test_infix_op_valid() { // 'a' + 'b' // 5 - 1 let mut input_ast = ExprWrapper::default( Expr::InfixOp( Add, ExprWrapper::default(Expr::Literal(UTF8Char('a'))), ExprWrapper::default(Expr::Literal(UTF8Char('b'))), ) ); let mut input_ast2 = ExprWrapper::default( Expr::InfixOp( Sub, ExprWrapper::default(Expr::Literal(U32Num(5))), ExprWrapper::default(Expr::Literal(U32Num(1))), ) ); TypeChecker::new().analyze(&mut input_ast); TypeChecker::new().analyze(&mut input_ast2); } #[test] #[should_panic] // Won't panic when actually displaying errors correctly fn test_infix_op_invalid() { // 'a' + 5 let mut input_ast = ExprWrapper::default( Expr::InfixOp( Add, ExprWrapper::default(Expr::Literal(UTF8Char('a'))), ExprWrapper::default(Expr::Literal(U32Num(5))), ) ); TypeChecker::new().analyze(&mut input_ast); }
use crate::db::HashValueDb; use crate::errors::MerkleTreeError; use crate::hasher::{Arity2Hasher, Arity4Hasher}; use crate::types::LeafIndex; use std::marker::PhantomData; // TODO: Have prehashed versions of the methods below that do not call `hash_leaf_data` but assume // that leaf data being passed is already hashed. /// The types `D`, `H` and `MTH` correspond to the types of data, hash and merkle tree hasher #[derive(Clone, Debug, Serialize, Deserialize)] pub struct VanillaBinarySparseMerkleTree<D: Clone, H: Clone, MTH> where MTH: Arity2Hasher<D, H>, { pub depth: usize, pub root: H, pub hasher: MTH, pub phantom: PhantomData<D>, } impl<D: Clone, H: Clone + PartialEq, MTH> VanillaBinarySparseMerkleTree<D, H, MTH> where MTH: Arity2Hasher<D, H>, { /// Create a new tree. `empty_leaf_val` is the default value for leaf of empty tree. It could be zero. /// Requires a database to hold leaves and nodes. The db should implement the `HashValueDb` trait pub fn new( empty_leaf_val: D, hasher: MTH, depth: usize, hash_db: &mut dyn HashValueDb<H, (H, H)>, ) -> Result<VanillaBinarySparseMerkleTree<D, H, MTH>, MerkleTreeError> { assert!(depth > 0); let mut cur_hash = hasher.hash_leaf_data(empty_leaf_val)?; for _ in 0..depth { let val = (cur_hash.clone(), cur_hash.clone()); cur_hash = hasher.hash_tree_nodes(cur_hash.clone(), cur_hash.clone())?; hash_db.put(cur_hash.clone(), val)?; } Ok(Self { depth, root: cur_hash, hasher, phantom: PhantomData, }) } /// Create a new tree with a given root hash pub fn initialize_with_root_hash(hasher: MTH, depth: usize, root: H) -> Self { Self { depth, root, hasher, phantom: PhantomData, } } /// Set the given `val` at the given leaf index `idx` pub fn update( &mut self, idx: &dyn LeafIndex, val: D, hash_db: &mut dyn HashValueDb<H, (H, H)>, ) -> Result<(), MerkleTreeError> { // Find path to insert the new key let mut siblings_wrap = Some(Vec::<H>::new()); self.get(idx, &mut siblings_wrap, hash_db)?; let mut siblings = siblings_wrap.unwrap(); let mut path = idx.to_leaf_path(2, self.depth); // Reverse since path was from root to leaf but i am going leaf to root path.reverse(); let mut cur_hash = self.hasher.hash_leaf_data(val)?; // Iterate over the bits for d in path { let sibling = siblings.pop().unwrap(); let (l, r) = if d == 0 { // leaf falls on the left side (cur_hash, sibling) } else { // leaf falls on the right side (sibling, cur_hash) }; let val = (l.clone(), r.clone()); cur_hash = self.hasher.hash_tree_nodes(l, r)?; hash_db.put(cur_hash.clone(), val)?; } self.root = cur_hash; Ok(()) } /// Get value for a leaf. `proof` when not set to None will be set to the inclusion proof for that leaf. pub fn get( &self, idx: &dyn LeafIndex, proof: &mut Option<Vec<H>>, hash_db: &dyn HashValueDb<H, (H, H)>, ) -> Result<H, MerkleTreeError> { let path = idx.to_leaf_path(2, self.depth); let mut cur_node = &self.root; let need_proof = proof.is_some(); let mut proof_vec = Vec::<H>::new(); let mut children; for d in path { children = hash_db.get(cur_node)?; if d == 0 { // leaf falls on the left side cur_node = &children.0; if need_proof { proof_vec.push(children.1); } } else { // leaf falls on the right side cur_node = &children.1; if need_proof { proof_vec.push(children.0); } } } match proof { Some(v) => { v.append(&mut proof_vec); } None => (), } Ok(cur_node.clone()) } /// Verify a leaf inclusion proof, if `root` is None, use the current root else use given root pub fn verify_proof( &self, idx: &dyn LeafIndex, val: D, proof: Vec<H>, root: Option<&H>, ) -> Result<bool, MerkleTreeError> { let mut path = idx.to_leaf_path(2, self.depth); if path.len() != proof.len() { return Ok(false); } path.reverse(); let mut cur_hash = self.hasher.hash_leaf_data(val)?; for (i, sibling) in proof.into_iter().rev().enumerate() { let (l, r) = if path[i] == 0 { // leaf falls on the left side (cur_hash, sibling) } else { // leaf falls on the right side (sibling, cur_hash) }; cur_hash = self.hasher.hash_tree_nodes(l, r)?; } // Check if root is equal to cur_hash match root { Some(r) => Ok(cur_hash == *r), None => Ok(cur_hash == self.root), } } } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct VanillaArity4SparseMerkleTree<D: Clone, H: Clone, MTH> where MTH: Arity4Hasher<D, H>, { pub depth: usize, pub root: H, hasher: MTH, phantom: PhantomData<D>, } impl<D: Clone, H: Clone + PartialEq + Default, MTH> VanillaArity4SparseMerkleTree<D, H, MTH> where MTH: Arity4Hasher<D, H>, { /// Create a new tree. `empty_leaf_val` is the default value for leaf of empty tree. It could be zero. /// Requires a database to hold leaves and nodes. The db should implement the `HashValueDb` trait pub fn new( empty_leaf_val: D, hasher: MTH, depth: usize, hash_db: &mut dyn HashValueDb<H, [H; 4]>, ) -> Result<VanillaArity4SparseMerkleTree<D, H, MTH>, MerkleTreeError> { assert!(depth > 0); let mut cur_hash = hasher.hash_leaf_data(empty_leaf_val)?; for _ in 0..depth { let val = [ cur_hash.clone(), cur_hash.clone(), cur_hash.clone(), cur_hash.clone(), ]; cur_hash = hasher.hash_tree_nodes( cur_hash.clone(), cur_hash.clone(), cur_hash.clone(), cur_hash.clone(), )?; hash_db.put(cur_hash.clone(), val)?; } Ok(Self { depth, root: cur_hash, hasher, phantom: PhantomData, }) } /// Create a new tree with a given root hash pub fn initialize_with_root_hash(hasher: MTH, depth: usize, root: H) -> Self { Self { depth, root, hasher, phantom: PhantomData, } } /// Set the given `val` at the given leaf index `idx` pub fn update( &mut self, idx: &dyn LeafIndex, val: D, hash_db: &mut dyn HashValueDb<H, [H; 4]>, ) -> Result<(), MerkleTreeError> { // Find path to insert the new key let mut siblings_wrap = Some(Vec::<[H; 3]>::new()); self.get(idx, &mut siblings_wrap, hash_db)?; let mut siblings = siblings_wrap.unwrap(); let mut path = idx.to_leaf_path(4, self.depth); // Reverse since path was from root to leaf but i am going leaf to root path.reverse(); let mut cur_hash = self.hasher.hash_leaf_data(val)?; // Iterate over the base 4 digits for d in path { let (n_0, n_1, n_2, n_3) = Self::extract_from_siblings(d, siblings.pop().unwrap(), cur_hash); let val = [n_0.clone(), n_1.clone(), n_2.clone(), n_3.clone()]; cur_hash = self.hasher.hash_tree_nodes(n_0, n_1, n_2, n_3)?; hash_db.put(cur_hash.clone(), val)?; } self.root = cur_hash; Ok(()) } /// Get value for a leaf. `proof` when not set to None will be set to the inclusion proof for that leaf. pub fn get( &self, idx: &dyn LeafIndex, proof: &mut Option<Vec<[H; 3]>>, hash_db: &dyn HashValueDb<H, [H; 4]>, ) -> Result<H, MerkleTreeError> { let path = idx.to_leaf_path(4, self.depth); let mut cur_node = &self.root; let need_proof = proof.is_some(); let mut proof_vec = Vec::<[H; 3]>::new(); let mut children; for d in path { children = hash_db.get(cur_node)?; cur_node = &children[d as usize]; if need_proof { let mut proof_node: [H; 3] = [H::default(), H::default(), H::default()]; let mut j = 0; // XXX: to_vec will lead to copying the slice, can it be prevented without using unsafe? for (i, c) in children.to_vec().into_iter().enumerate() { if i != (d as usize) { proof_node[j] = c; j += 1; } } proof_vec.push(proof_node); } } match proof { Some(v) => { v.append(&mut proof_vec); } None => (), } Ok(cur_node.clone()) } /// Verify a merkle proof, if `root` is None, use the current root else use given root pub fn verify_proof( &self, idx: &dyn LeafIndex, val: D, proof: Vec<[H; 3]>, root: Option<&H>, ) -> Result<bool, MerkleTreeError> { let mut path = idx.to_leaf_path(4, self.depth); if path.len() != proof.len() { return Ok(false); } path.reverse(); let mut cur_hash = self.hasher.hash_leaf_data(val)?; for (i, sibling) in proof.into_iter().rev().enumerate() { let (n_0, n_1, n_2, n_3) = Self::extract_from_siblings(path[i], sibling, cur_hash); cur_hash = self.hasher.hash_tree_nodes(n_0, n_1, n_2, n_3)?; } // Check if root is equal to cur_hash match root { Some(r) => Ok(cur_hash == *r), None => Ok(cur_hash == self.root), } } /// Destructure the sibling array and return the cur_hash and siblings in the correct order. /// `d` is the index of `cur_hash` in the returned array fn extract_from_siblings(d: u8, sibling: [H; 3], cur_hash: H) -> (H, H, H, H) { let [s_0, s_1, s_2] = sibling; if d == 0 { (cur_hash, s_0, s_1, s_2) } else if d == 1 { (s_0, cur_hash, s_1, s_2) } else if d == 2 { (s_0, s_1, cur_hash, s_2) } else { (s_0, s_1, s_2, cur_hash) } } } #[allow(non_snake_case)] #[cfg(test)] mod tests { use super::*; extern crate rand; use self::rand::{thread_rng, Rng}; use crate::db::InMemoryHashValueDb; use crate::hasher::Sha256Hasher; use num_bigint::{BigUint, RandBigInt}; use std::collections::HashSet; use crate::db::rusqlite_db; use crate::errors::MerkleTreeErrorKind; use std::fs; extern crate rusqlite; use rusqlite::{params, Connection, NO_PARAMS}; fn check_binary_tree_update_get_and_proof<'a, T, I>( tree: &'a mut VanillaBinarySparseMerkleTree<&'a str, Vec<u8>, Sha256Hasher>, tree_depth: usize, hasher: Sha256Hasher, data: &'a Vec<(I, String, Vec<u8>)>, db: &mut T, ) where T: HashValueDb<Vec<u8>, (Vec<u8>, Vec<u8>)>, { for i in 0..(data.len() as u64) { // Update and check tree.update(&i, &data[i as usize].1, db).unwrap(); let mut proof_vec = Vec::<Vec<u8>>::new(); let mut proof = Some(proof_vec); assert_eq!(tree.get(&i, &mut proof, db).unwrap(), data[i as usize].2); proof_vec = proof.unwrap(); let verifier_tree = VanillaBinarySparseMerkleTree::initialize_with_root_hash( hasher.clone(), tree_depth, tree.root.clone(), ); assert!(verifier_tree .verify_proof(&i, &data[i as usize].1, proof_vec.clone(), None) .unwrap()); assert!(verifier_tree .verify_proof(&i, &data[i as usize].1, proof_vec.clone(), Some(&tree.root)) .unwrap()); } for i in 0..(data.len() as u64) { // Check after all updates done let mut proof_vec = Vec::<Vec<u8>>::new(); let mut proof = Some(proof_vec); assert_eq!(tree.get(&i, &mut proof, db).unwrap(), data[i as usize].2); proof_vec = proof.unwrap(); let verifier_tree = VanillaBinarySparseMerkleTree::initialize_with_root_hash( hasher.clone(), tree_depth, tree.root.clone(), ); assert!(verifier_tree .verify_proof(&i, &data[i as usize].1, proof_vec.clone(), None) .unwrap()); } } fn check_binary_tree_create_update_get_and_proof<T>( tree_depth: usize, empty_leaf_val: &str, db: &mut T, ) where T: HashValueDb<Vec<u8>, (Vec<u8>, Vec<u8>)>, { let max_leaves = 2u64.pow(tree_depth as u32); let hasher = Sha256Hasher { leaf_data_domain_separator: 0, node_domain_separator: 1, }; let mut tree = VanillaBinarySparseMerkleTree::new( empty_leaf_val.clone(), hasher.clone(), tree_depth, db, ) .unwrap(); let empty_leaf_hash = Arity2Hasher::hash_leaf_data(&hasher, empty_leaf_val).unwrap(); for i in 0..max_leaves { assert_eq!(tree.get(&i, &mut None, db).unwrap(), empty_leaf_hash); } let mut data = vec![]; for i in 0..max_leaves { let val = [String::from("val_"), i.to_string()].concat(); let hash = Arity2Hasher::hash_leaf_data(&hasher, &val).unwrap(); data.push((i, val, hash)); } check_binary_tree_update_get_and_proof(&mut tree, tree_depth, hasher, &data, db); } #[test] fn test_vanilla_binary_sparse_tree_sha256_string() { let mut db = InMemoryHashValueDb::<(Vec<u8>, Vec<u8>)>::new(); let tree_depth = 7; // Choice of `empty_leaf_val` is arbitrary let empty_leaf_val = ""; check_binary_tree_create_update_get_and_proof(tree_depth, empty_leaf_val, &mut db) } #[test] fn test_vanilla_sparse_4_ary_tree_sha256_string() { let mut db = InMemoryHashValueDb::<[Vec<u8>; 4]>::new(); let tree_depth = 5; let max_leaves = 4u64.pow(tree_depth as u32); let empty_leaf_val = ""; let hasher = Sha256Hasher { leaf_data_domain_separator: 0, node_domain_separator: 1, }; let mut tree = VanillaArity4SparseMerkleTree::new( empty_leaf_val.clone(), hasher.clone(), tree_depth, &mut db, ) .unwrap(); let empty_leaf_hash = Arity4Hasher::hash_leaf_data(&hasher, empty_leaf_val).unwrap(); for i in 0..max_leaves { assert_eq!(tree.get(&i, &mut None, &db).unwrap(), empty_leaf_hash); } let mut data = vec![]; for i in 0..max_leaves { let val = [String::from("val_"), i.to_string()].concat(); let hash = Arity2Hasher::hash_leaf_data(&hasher, &val).unwrap(); data.push((i, val, hash)); } for i in 0..max_leaves { // Update and check tree.update(&i, &data[i as usize].1, &mut db).unwrap(); let mut proof_vec = Vec::<[Vec<u8>; 3]>::new(); let mut proof = Some(proof_vec); assert_eq!(tree.get(&i, &mut proof, &db).unwrap(), data[i as usize].2); proof_vec = proof.unwrap(); let verifier_tree = VanillaArity4SparseMerkleTree::initialize_with_root_hash( hasher.clone(), tree_depth, tree.root.clone(), ); assert!(verifier_tree .verify_proof(&i, &data[i as usize].1, proof_vec.clone(), None) .unwrap()); assert!(verifier_tree .verify_proof(&i, &data[i as usize].1, proof_vec.clone(), Some(&tree.root)) .unwrap()); } for i in 0..max_leaves { // Check after all updates done assert_eq!(tree.get(&i, &mut None, &db).unwrap(), data[i as usize].2); let mut proof_vec = Vec::<[Vec<u8>; 3]>::new(); let mut proof = Some(proof_vec); assert_eq!(tree.get(&i, &mut proof, &db).unwrap(), data[i as usize].2); proof_vec = proof.unwrap(); let verifier_tree = VanillaArity4SparseMerkleTree::initialize_with_root_hash( hasher.clone(), tree_depth, tree.root.clone(), ); assert!(verifier_tree .verify_proof(&i, &data[i as usize].1, proof_vec.clone(), None) .unwrap()); } } #[test] fn test_vanilla_binary_sparse_tree_sha256_string_BigUint_index() { let mut db = InMemoryHashValueDb::<(Vec<u8>, Vec<u8>)>::new(); let tree_depth = 65; let empty_leaf_val = ""; let hasher = Sha256Hasher { leaf_data_domain_separator: 0, node_domain_separator: 1, }; let mut tree = VanillaBinarySparseMerkleTree::new( empty_leaf_val.clone(), hasher.clone(), tree_depth, &mut db, ) .unwrap(); let mut data = vec![]; let test_cases = 300; let mut rng = thread_rng(); let mut set = HashSet::new(); while data.len() < test_cases { let i: BigUint = rng.gen_biguint(160); if set.contains(&i) { continue; } else { set.insert(i.clone()); } let val = [String::from("val_"), i.clone().to_string()].concat(); let hash = Arity2Hasher::hash_leaf_data(&hasher, &val).unwrap(); data.push((i.clone(), val, hash)); } check_binary_tree_update_get_and_proof(&mut tree, tree_depth, hasher, &data, &mut db); } /// Testing implementation for using sqlite for storing tree data. No error handling. Purpose is /// to demonstrate how a persistent database can be used pub struct RusqliteSMTHashValueDb { db_path: String, pub table_name: String, pub db_conn: Connection, } impl RusqliteSMTHashValueDb { pub fn new(db_path: String, table_name: String) -> Self { let db_conn = Connection::open(&db_path).unwrap(); let sql = format!("create table if not exists {} (key string primary key, value1 blob not null, value2 blob not null)", table_name); db_conn.execute(&sql, NO_PARAMS).unwrap(); Self { db_path, table_name, db_conn, } } } impl HashValueDb<Vec<u8>, (Vec<u8>, Vec<u8>)> for RusqliteSMTHashValueDb { fn put(&mut self, hash: Vec<u8>, value: (Vec<u8>, Vec<u8>)) -> Result<(), MerkleTreeError> { let hash_hex = rusqlite_db::RusqliteHashValueDb::hash_to_hex(&hash); let sql = format!( "insert into {} (key, value1, value2) values (?1, ?2, ?3)", self.table_name ); let (v1, v2) = value; // XXX: A real implementation will have error handling here self.db_conn .execute(&sql, params![hash_hex, v1, v2]) .unwrap(); Ok(()) } fn get(&self, hash: &Vec<u8>) -> Result<(Vec<u8>, Vec<u8>), MerkleTreeError> { let sql = format!( "select value1, value2 from {} where key='{}'", self.table_name, rusqlite_db::RusqliteHashValueDb::hash_to_hex(hash) ); // XXX: A real implementation will have error handling here self.db_conn .query_row(&sql, NO_PARAMS, |row| { let v1 = row.get(0).unwrap(); let v2 = row.get(1).unwrap(); Ok((v1, v2)) }) .map_err(|_| { MerkleTreeError::from_kind(MerkleTreeErrorKind::HashNotFoundInDB { hash: hash.to_vec(), }) }) } } #[test] fn test_binary_tree_sha256_hash_sqlite_db() { // Test demonstrating the use of sqlite db for tree data let db_path = "./rusqlite_tree.db"; fs::remove_file(db_path); let mut db = RusqliteSMTHashValueDb::new(String::from(db_path), String::from("kv_table")); let tree_depth = 3; let empty_leaf_val = ""; check_binary_tree_create_update_get_and_proof(tree_depth, empty_leaf_val, &mut db) } }
extern crate clap; extern crate falcon; use falcon::analysis; use falcon::il; use falcon::loader::{Elf, Loader}; use std::path::Path; fn main () { let matches = clap::App::new("falcon-example-0") .version("0.2.1") .about("An example of Falcon usage") .arg(clap::Arg::with_name("program") .short("p") .long("program") .value_name("FILE") .help("Program to analyze with Falcon") .required(true)) .arg(clap::Arg::with_name("function") .short("f") .long("function") .value_name("FUNCTION_NAME") .help("Function to analyze with Falcon") .required(true)) .get_matches(); let program_filename = matches.value_of("program").unwrap(); let function_name = matches.value_of("function").unwrap(); // Load our Elf let elf = match Elf::from_file(Path::new(program_filename)) { Ok(elf) => elf, Err(_) => { panic!("Error loading elf"); } }; let program = elf.program().unwrap(); // If we have a main function, let's print that let function = match program.functions() .into_iter() .filter(|f| f.name() == function_name) .collect::<Vec<&il::Function>>() .first() { Some(function) => (*function).clone(), None => { panic!(format!("Could not find function {}", function_name)); } }; let ud = match analysis::use_def(&function) { Ok(ud) => ud, Err(e) => { panic!("Error calculating use def chains: {}", e); } }; for block in function.blocks() { for instruction in block.instructions() { println!("{}", instruction); let rfl = il::RefFunctionLocation::Instruction(block, instruction); let rpl = il::RefProgramLocation::new(&function, rfl); for location in ud[&rpl].locations() { println!(" {}", location); } } } }
#[cfg(not(target_arch = "wasm32"))] use glutin::MouseCursor as GlMouseCursor; /// Mouse cursor styles #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub enum MouseCursor { /// No cursor None, /// Default cursor Default, /// Crosshair cursor Crosshair, /// Hand cursor Hand, /// Arrow cursor Arrow, /// Move cursor Move, /// Text cursor Text, /// Wait cursor Wait, /// Help cursor Help, /// Progress cursor Progress, /// NotAllowed cursor NotAllowed, /// ContextMenu cursor ContextMenu, /// Cell cursor Cell, /// VerticalText cursor VerticalText, /// Alias cursor Alias, /// Copy cursor Copy, /// NoDrop cursor NoDrop, /// Grab cursor Grab, /// Grabbing cursor Grabbing, /// AllScroll cursor AllScroll, /// ZoomIn cursor ZoomIn, /// ZoomOut cursor ZoomOut, /// EResize cursor EResize, /// NResize cursor NResize, /// NeResize cursor NeResize, /// NwResize cursor NwResize, /// SResize cursor SResize, /// SeResize cursor SeResize, /// SwResize cursor SwResize, /// WResize cursor WResize, /// EwResize cursor EwResize, /// NsResize cursor NsResize, /// NeswResize cursor NeswResize, /// NwseResize cursor NwseResize, /// ColResize cursor ColResize, /// RowResize cursor RowResize, } impl MouseCursor { #[cfg(target_arch = "wasm32")] #[inline] pub(crate) fn into_css_style(self) -> &'static str { match self { MouseCursor::None => "none", MouseCursor::Default => "auto", MouseCursor::Crosshair => "crosshair", MouseCursor::Hand => "pointer", MouseCursor::Arrow => "default", MouseCursor::Move => "move", MouseCursor::Text => "text", MouseCursor::Wait => "wait", MouseCursor::Help => "help", MouseCursor::Progress => "progress", MouseCursor::NotAllowed => "not-allowed", MouseCursor::ContextMenu => "context-menu", MouseCursor::Cell => "cell", MouseCursor::VerticalText => "vertical-text", MouseCursor::Alias => "alias", MouseCursor::Copy => "copy", MouseCursor::NoDrop => "no-drop", MouseCursor::Grab => "grab", MouseCursor::Grabbing => "grabbing", MouseCursor::AllScroll => "all-scroll", MouseCursor::ZoomIn => "zoom-in", MouseCursor::ZoomOut => "zoom-out", MouseCursor::EResize => "e-resize", MouseCursor::NResize => "n-resize", MouseCursor::NeResize => "ne-resize", MouseCursor::NwResize => "nw-resize", MouseCursor::SResize => "s-resize", MouseCursor::SeResize => "se-resize", MouseCursor::SwResize => "sw-resize", MouseCursor::WResize => "w-resize", MouseCursor::EwResize => "ew-resize", MouseCursor::NsResize => "ns-resize", MouseCursor::NeswResize => "nesw-resize", MouseCursor::NwseResize => "nwse-resize", MouseCursor::ColResize => "col-resize", MouseCursor::RowResize => "row-resize", } } #[cfg(not(target_arch = "wasm32"))] #[inline] pub(crate) fn into_gl_cursor(self) -> Option<GlMouseCursor> { match self { MouseCursor::None => None, MouseCursor::Default => Some(GlMouseCursor::Default), MouseCursor::Crosshair => Some(GlMouseCursor::Crosshair), MouseCursor::Hand => Some(GlMouseCursor::Hand), MouseCursor::Arrow => Some(GlMouseCursor::Arrow), MouseCursor::Move => Some(GlMouseCursor::Move), MouseCursor::Text => Some(GlMouseCursor::Text), MouseCursor::Wait => Some(GlMouseCursor::Wait), MouseCursor::Help => Some(GlMouseCursor::Help), MouseCursor::Progress => Some(GlMouseCursor::Progress), MouseCursor::NotAllowed => Some(GlMouseCursor::NotAllowed), MouseCursor::ContextMenu => Some(GlMouseCursor::ContextMenu), MouseCursor::Cell => Some(GlMouseCursor::Cell), MouseCursor::VerticalText => Some(GlMouseCursor::VerticalText), MouseCursor::Alias => Some(GlMouseCursor::Alias), MouseCursor::Copy => Some(GlMouseCursor::Copy), MouseCursor::NoDrop => Some(GlMouseCursor::NoDrop), MouseCursor::Grab => Some(GlMouseCursor::Grab), MouseCursor::Grabbing => Some(GlMouseCursor::Grabbing), MouseCursor::AllScroll => Some(GlMouseCursor::AllScroll), MouseCursor::ZoomIn => Some(GlMouseCursor::ZoomIn), MouseCursor::ZoomOut => Some(GlMouseCursor::ZoomOut), MouseCursor::EResize => Some(GlMouseCursor::EResize), MouseCursor::NResize => Some(GlMouseCursor::NResize), MouseCursor::NeResize => Some(GlMouseCursor::NeResize), MouseCursor::NwResize => Some(GlMouseCursor::NwResize), MouseCursor::SResize => Some(GlMouseCursor::SResize), MouseCursor::SeResize => Some(GlMouseCursor::SeResize), MouseCursor::SwResize => Some(GlMouseCursor::SwResize), MouseCursor::WResize => Some(GlMouseCursor::WResize), MouseCursor::EwResize => Some(GlMouseCursor::EwResize), MouseCursor::NsResize => Some(GlMouseCursor::NsResize), MouseCursor::NeswResize => Some(GlMouseCursor::NeswResize), MouseCursor::NwseResize => Some(GlMouseCursor::NwseResize), MouseCursor::ColResize => Some(GlMouseCursor::ColResize), MouseCursor::RowResize => Some(GlMouseCursor::RowResize), } } } impl Default for MouseCursor { fn default() -> Self { MouseCursor::Default } }
use std::io::prelude::*; use std::fs::File; use std::str::from_utf8; enum Dir { N, E, S, W } enum Movement { Right(i32), Left(i32), } struct Map { x: i32, y: i32, dir: Dir } impl Map { fn new() -> Map { Map{x: 0, y: 0, dir: Dir::N} } fn move(&self, i: Movement) -> Map { let (dir, n) = match i { Movement::Right(n) => match self.dir { Dir::N => (Dir::E, n), Dir::E => (Dir::S, n), Dir::S => (Dir::W, n), Dir::W => (Dir::N, n) }, Movement::Left(n) => match self.dir { Dir::N => (Dir::W, n), Dir::W => (Dir::S, n), Dir::S => (Dir::E, n), Dir::E => (Dir::N, n), } }; let (delta_x, delta_y) = match dir { Dir::N => (0, n), Dir::W => (-n, 0), Dir::S => (0, -n), Dir::E => (n, 0) }; Map{x: self.x + delta_x, y: self.y + delta_y, dir: dir} } fn distance(&self) -> i32 { self.x.abs() + self.y.abs() } } fn main() { let mut f = File::open("data.txt").expect("unable to open file"); let mut data = String::new(); f.read_to_string(&mut data).expect("unable to read file"); let map = data .split(", ") .map(|s| s.trim()) .map(|m| { let bytes = m.as_bytes(); let (first, rest) = bytes.split_at(1); let n: i32 = from_utf8(rest).unwrap().parse().unwrap(); match first[0] as char { 'R' => Movement::Right(n), 'L' => Movement::Left(n), d => panic!("invalid instruction direction {}", d) } }) .fold(Map::new(), |map, mov| map.move(mov)); println!("{}", map.distance()); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "ApplicationModel_Appointments_AppointmentsProvider")] pub mod AppointmentsProvider; #[cfg(feature = "ApplicationModel_Appointments_DataProvider")] pub mod DataProvider; #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct Appointment(pub ::windows::core::IInspectable); impl Appointment { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<Appointment, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn StartTime(&self) -> ::windows::core::Result<super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::DateTime>(result__) } } #[cfg(feature = "Foundation")] pub fn SetStartTime<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn Duration(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Foundation")] pub fn SetDuration<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Location(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetLocation<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Subject(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetSubject<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Details(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetDetails<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn Reminder(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Foundation::TimeSpan>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::super::Foundation::TimeSpan>>(result__) } } #[cfg(feature = "Foundation")] pub fn SetReminder<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::IReference<super::super::Foundation::TimeSpan>>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Organizer(&self) -> ::windows::core::Result<AppointmentOrganizer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentOrganizer>(result__) } } pub fn SetOrganizer<'a, Param0: ::windows::core::IntoParam<'a, AppointmentOrganizer>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn Invitees(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<AppointmentInvitee>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<AppointmentInvitee>>(result__) } } pub fn Recurrence(&self) -> ::windows::core::Result<AppointmentRecurrence> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentRecurrence>(result__) } } pub fn SetRecurrence<'a, Param0: ::windows::core::IntoParam<'a, AppointmentRecurrence>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn BusyStatus(&self) -> ::windows::core::Result<AppointmentBusyStatus> { let this = self; unsafe { let mut result__: AppointmentBusyStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentBusyStatus>(result__) } } pub fn SetBusyStatus(&self, value: AppointmentBusyStatus) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), value).ok() } } pub fn AllDay(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetAllDay(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), value).ok() } } pub fn Sensitivity(&self) -> ::windows::core::Result<AppointmentSensitivity> { let this = self; unsafe { let mut result__: AppointmentSensitivity = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentSensitivity>(result__) } } pub fn SetSensitivity(&self, value: AppointmentSensitivity) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::Foundation::Uri> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn SetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn LocalId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn CalendarId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IAppointment2>(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 RoamingId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IAppointment2>(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 SetRoamingId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn OriginalStartTime(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Foundation::DateTime>> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::super::Foundation::DateTime>>(result__) } } pub fn IsResponseRequested(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetIsResponseRequested(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value).ok() } } pub fn AllowNewTimeProposal(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetAllowNewTimeProposal(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value).ok() } } pub fn OnlineMeetingLink(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetOnlineMeetingLink<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn ReplyTime(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Foundation::DateTime>> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::super::Foundation::DateTime>>(result__) } } #[cfg(feature = "Foundation")] pub fn SetReplyTime<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::IReference<super::super::Foundation::DateTime>>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn UserResponse(&self) -> ::windows::core::Result<AppointmentParticipantResponse> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { let mut result__: AppointmentParticipantResponse = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentParticipantResponse>(result__) } } pub fn SetUserResponse(&self, value: AppointmentParticipantResponse) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), value).ok() } } pub fn HasInvitees(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsCanceledMeeting(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetIsCanceledMeeting(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsOrganizedByUser(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetIsOrganizedByUser(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointment2>(self)?; unsafe { (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), value).ok() } } pub fn ChangeNumber(&self) -> ::windows::core::Result<u64> { let this = &::windows::core::Interface::cast::<IAppointment3>(self)?; unsafe { let mut result__: u64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__) } } pub fn RemoteChangeNumber(&self) -> ::windows::core::Result<u64> { let this = &::windows::core::Interface::cast::<IAppointment3>(self)?; unsafe { let mut result__: u64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__) } } pub fn SetRemoteChangeNumber(&self, value: u64) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointment3>(self)?; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() } } pub fn DetailsKind(&self) -> ::windows::core::Result<AppointmentDetailsKind> { let this = &::windows::core::Interface::cast::<IAppointment3>(self)?; unsafe { let mut result__: AppointmentDetailsKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentDetailsKind>(result__) } } pub fn SetDetailsKind(&self, value: AppointmentDetailsKind) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointment3>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value).ok() } } } unsafe impl ::windows::core::RuntimeType for Appointment { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.Appointment;{dd002f2f-2bdd-4076-90a3-22c275312965})"); } unsafe impl ::windows::core::Interface for Appointment { type Vtable = IAppointment_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdd002f2f_2bdd_4076_90a3_22c275312965); } impl ::windows::core::RuntimeName for Appointment { const NAME: &'static str = "Windows.ApplicationModel.Appointments.Appointment"; } impl ::core::convert::From<Appointment> for ::windows::core::IUnknown { fn from(value: Appointment) -> Self { value.0 .0 } } impl ::core::convert::From<&Appointment> for ::windows::core::IUnknown { fn from(value: &Appointment) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for Appointment { 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 Appointment { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<Appointment> for ::windows::core::IInspectable { fn from(value: Appointment) -> Self { value.0 } } impl ::core::convert::From<&Appointment> for ::windows::core::IInspectable { fn from(value: &Appointment) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for Appointment { 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 Appointment { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for Appointment {} unsafe impl ::core::marker::Sync for Appointment {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentBusyStatus(pub i32); impl AppointmentBusyStatus { pub const Busy: AppointmentBusyStatus = AppointmentBusyStatus(0i32); pub const Tentative: AppointmentBusyStatus = AppointmentBusyStatus(1i32); pub const Free: AppointmentBusyStatus = AppointmentBusyStatus(2i32); pub const OutOfOffice: AppointmentBusyStatus = AppointmentBusyStatus(3i32); pub const WorkingElsewhere: AppointmentBusyStatus = AppointmentBusyStatus(4i32); } impl ::core::convert::From<i32> for AppointmentBusyStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentBusyStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentBusyStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentBusyStatus;i4)"); } impl ::windows::core::DefaultType for AppointmentBusyStatus { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentCalendar(pub ::windows::core::IInspectable); impl AppointmentCalendar { #[cfg(feature = "UI")] pub fn DisplayColor(&self) -> ::windows::core::Result<super::super::UI::Color> { let this = self; unsafe { let mut result__: super::super::UI::Color = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::UI::Color>(result__) } } pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetDisplayName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn LocalId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn IsHidden(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn OtherAppReadAccess(&self) -> ::windows::core::Result<AppointmentCalendarOtherAppReadAccess> { let this = self; unsafe { let mut result__: AppointmentCalendarOtherAppReadAccess = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentCalendarOtherAppReadAccess>(result__) } } pub fn SetOtherAppReadAccess(&self, value: AppointmentCalendarOtherAppReadAccess) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value).ok() } } pub fn OtherAppWriteAccess(&self) -> ::windows::core::Result<AppointmentCalendarOtherAppWriteAccess> { let this = self; unsafe { let mut result__: AppointmentCalendarOtherAppWriteAccess = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentCalendarOtherAppWriteAccess>(result__) } } pub fn SetOtherAppWriteAccess(&self, value: AppointmentCalendarOtherAppWriteAccess) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value).ok() } } pub fn SourceDisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SummaryCardView(&self) -> ::windows::core::Result<AppointmentSummaryCardView> { let this = self; unsafe { let mut result__: AppointmentSummaryCardView = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentSummaryCardView>(result__) } } pub fn SetSummaryCardView(&self, value: AppointmentSummaryCardView) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn FindAppointmentsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>>(&self, rangestart: Param0, rangelength: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), rangestart.into_param().abi(), rangelength.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn FindAppointmentsAsyncWithOptions<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>, Param2: ::windows::core::IntoParam<'a, FindAppointmentsOptions>>(&self, rangestart: Param0, rangelength: Param1, options: Param2) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), rangestart.into_param().abi(), rangelength.into_param().abi(), options.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn FindExceptionsFromMasterAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, masterlocalid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<AppointmentException>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), masterlocalid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<AppointmentException>>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn FindAllInstancesAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>>(&self, masterlocalid: Param0, rangestart: Param1, rangelength: Param2) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), masterlocalid.into_param().abi(), rangestart.into_param().abi(), rangelength.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn FindAllInstancesAsyncWithOptions<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>, Param3: ::windows::core::IntoParam<'a, FindAppointmentsOptions>>( &self, masterlocalid: Param0, rangestart: Param1, rangelength: Param2, poptions: Param3, ) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), masterlocalid.into_param().abi(), rangestart.into_param().abi(), rangelength.into_param().abi(), poptions.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>>(result__) } } #[cfg(feature = "Foundation")] pub fn GetAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, localid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<Appointment>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), localid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<Appointment>>(result__) } } #[cfg(feature = "Foundation")] pub fn GetAppointmentInstanceAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(&self, localid: Param0, instancestarttime: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<Appointment>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), localid.into_param().abi(), instancestarttime.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<Appointment>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn FindUnexpandedAppointmentsAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn FindUnexpandedAppointmentsAsyncWithOptions<'a, Param0: ::windows::core::IntoParam<'a, FindAppointmentsOptions>>(&self, options: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), options.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>>(result__) } } #[cfg(feature = "Foundation")] pub fn DeleteAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "Foundation")] pub fn SaveAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "Foundation")] pub fn DeleteAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, localid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), localid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "Foundation")] pub fn DeleteAppointmentInstanceAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(&self, localid: Param0, instancestarttime: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), localid.into_param().abi(), instancestarttime.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "Foundation")] pub fn SaveAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>>(&self, pappointment: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), pappointment.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } pub fn SyncManager(&self) -> ::windows::core::Result<AppointmentCalendarSyncManager> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(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::<AppointmentCalendarSyncManager>(result__) } } pub fn RemoteId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(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 SetRemoteId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "UI")] pub fn SetDisplayColor<'a, Param0: ::windows::core::IntoParam<'a, super::super::UI::Color>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn SetIsHidden(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value).ok() } } pub fn UserDataAccountId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn CanCreateOrUpdateAppointments(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetCanCreateOrUpdateAppointments(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() } } pub fn CanCancelMeetings(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetCanCancelMeetings(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() } } pub fn CanForwardMeetings(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetCanForwardMeetings(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value).ok() } } pub fn CanProposeNewTimeForMeetings(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetCanProposeNewTimeForMeetings(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), value).ok() } } pub fn CanUpdateMeetingResponses(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetCanUpdateMeetingResponses(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), value).ok() } } pub fn CanNotifyInvitees(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetCanNotifyInvitees(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), value).ok() } } pub fn MustNofityInvitees(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetMustNofityInvitees(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation")] pub fn TryCreateOrUpdateAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>>(&self, appointment: Param0, notifyinvitees: bool) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), appointment.into_param().abi(), notifyinvitees, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryCancelMeetingAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, meeting: Param0, subject: Param1, comment: Param2, notifyinvitees: bool) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), meeting.into_param().abi(), subject.into_param().abi(), comment.into_param().abi(), notifyinvitees, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn TryForwardMeetingAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<AppointmentInvitee>>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param4: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( &self, meeting: Param0, invitees: Param1, subject: Param2, forwardheader: Param3, comment: Param4, ) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), meeting.into_param().abi(), invitees.into_param().abi(), subject.into_param().abi(), forwardheader.into_param().abi(), comment.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryProposeNewTimeForMeetingAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param4: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( &self, meeting: Param0, newstarttime: Param1, newduration: Param2, subject: Param3, comment: Param4, ) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), meeting.into_param().abi(), newstarttime.into_param().abi(), newduration.into_param().abi(), subject.into_param().abi(), comment.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn TryUpdateMeetingResponseAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, meeting: Param0, response: AppointmentParticipantResponse, subject: Param2, comment: Param3, sendupdate: bool) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), meeting.into_param().abi(), response, subject.into_param().abi(), comment.into_param().abi(), sendupdate, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn RegisterSyncManagerAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = &::windows::core::Interface::cast::<IAppointmentCalendar3>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } } unsafe impl ::windows::core::RuntimeType for AppointmentCalendar { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentCalendar;{5273819d-8339-3d4f-a02f-64084452bb5d})"); } unsafe impl ::windows::core::Interface for AppointmentCalendar { type Vtable = IAppointmentCalendar_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5273819d_8339_3d4f_a02f_64084452bb5d); } impl ::windows::core::RuntimeName for AppointmentCalendar { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentCalendar"; } impl ::core::convert::From<AppointmentCalendar> for ::windows::core::IUnknown { fn from(value: AppointmentCalendar) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentCalendar> for ::windows::core::IUnknown { fn from(value: &AppointmentCalendar) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendar { 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 AppointmentCalendar { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentCalendar> for ::windows::core::IInspectable { fn from(value: AppointmentCalendar) -> Self { value.0 } } impl ::core::convert::From<&AppointmentCalendar> for ::windows::core::IInspectable { fn from(value: &AppointmentCalendar) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendar { 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 AppointmentCalendar { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentCalendar {} unsafe impl ::core::marker::Sync for AppointmentCalendar {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentCalendarOtherAppReadAccess(pub i32); impl AppointmentCalendarOtherAppReadAccess { pub const SystemOnly: AppointmentCalendarOtherAppReadAccess = AppointmentCalendarOtherAppReadAccess(0i32); pub const Limited: AppointmentCalendarOtherAppReadAccess = AppointmentCalendarOtherAppReadAccess(1i32); pub const Full: AppointmentCalendarOtherAppReadAccess = AppointmentCalendarOtherAppReadAccess(2i32); pub const None: AppointmentCalendarOtherAppReadAccess = AppointmentCalendarOtherAppReadAccess(3i32); } impl ::core::convert::From<i32> for AppointmentCalendarOtherAppReadAccess { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentCalendarOtherAppReadAccess { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentCalendarOtherAppReadAccess { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentCalendarOtherAppReadAccess;i4)"); } impl ::windows::core::DefaultType for AppointmentCalendarOtherAppReadAccess { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentCalendarOtherAppWriteAccess(pub i32); impl AppointmentCalendarOtherAppWriteAccess { pub const None: AppointmentCalendarOtherAppWriteAccess = AppointmentCalendarOtherAppWriteAccess(0i32); pub const SystemOnly: AppointmentCalendarOtherAppWriteAccess = AppointmentCalendarOtherAppWriteAccess(1i32); pub const Limited: AppointmentCalendarOtherAppWriteAccess = AppointmentCalendarOtherAppWriteAccess(2i32); } impl ::core::convert::From<i32> for AppointmentCalendarOtherAppWriteAccess { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentCalendarOtherAppWriteAccess { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentCalendarOtherAppWriteAccess { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentCalendarOtherAppWriteAccess;i4)"); } impl ::windows::core::DefaultType for AppointmentCalendarOtherAppWriteAccess { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentCalendarSyncManager(pub ::windows::core::IInspectable); impl AppointmentCalendarSyncManager { pub fn Status(&self) -> ::windows::core::Result<AppointmentCalendarSyncStatus> { let this = self; unsafe { let mut result__: AppointmentCalendarSyncStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentCalendarSyncStatus>(result__) } } #[cfg(feature = "Foundation")] pub fn LastSuccessfulSyncTime(&self) -> ::windows::core::Result<super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::DateTime>(result__) } } #[cfg(feature = "Foundation")] pub fn LastAttemptedSyncTime(&self) -> ::windows::core::Result<super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::DateTime>(result__) } } #[cfg(feature = "Foundation")] pub fn SyncAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn SyncStatusChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AppointmentCalendarSyncManager, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveSyncStatusChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } pub fn SetStatus(&self, value: AppointmentCalendarSyncStatus) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendarSyncManager2>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation")] pub fn SetLastSuccessfulSyncTime<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendarSyncManager2>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn SetLastAttemptedSyncTime<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentCalendarSyncManager2>(self)?; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for AppointmentCalendarSyncManager { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentCalendarSyncManager;{2b21b3a0-4aff-4392-bc5f-5645ffcffb17})"); } unsafe impl ::windows::core::Interface for AppointmentCalendarSyncManager { type Vtable = IAppointmentCalendarSyncManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2b21b3a0_4aff_4392_bc5f_5645ffcffb17); } impl ::windows::core::RuntimeName for AppointmentCalendarSyncManager { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentCalendarSyncManager"; } impl ::core::convert::From<AppointmentCalendarSyncManager> for ::windows::core::IUnknown { fn from(value: AppointmentCalendarSyncManager) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentCalendarSyncManager> for ::windows::core::IUnknown { fn from(value: &AppointmentCalendarSyncManager) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarSyncManager { 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 AppointmentCalendarSyncManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentCalendarSyncManager> for ::windows::core::IInspectable { fn from(value: AppointmentCalendarSyncManager) -> Self { value.0 } } impl ::core::convert::From<&AppointmentCalendarSyncManager> for ::windows::core::IInspectable { fn from(value: &AppointmentCalendarSyncManager) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarSyncManager { 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 AppointmentCalendarSyncManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentCalendarSyncManager {} unsafe impl ::core::marker::Sync for AppointmentCalendarSyncManager {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentCalendarSyncStatus(pub i32); impl AppointmentCalendarSyncStatus { pub const Idle: AppointmentCalendarSyncStatus = AppointmentCalendarSyncStatus(0i32); pub const Syncing: AppointmentCalendarSyncStatus = AppointmentCalendarSyncStatus(1i32); pub const UpToDate: AppointmentCalendarSyncStatus = AppointmentCalendarSyncStatus(2i32); pub const AuthenticationError: AppointmentCalendarSyncStatus = AppointmentCalendarSyncStatus(3i32); pub const PolicyError: AppointmentCalendarSyncStatus = AppointmentCalendarSyncStatus(4i32); pub const UnknownError: AppointmentCalendarSyncStatus = AppointmentCalendarSyncStatus(5i32); pub const ManualAccountRemovalRequired: AppointmentCalendarSyncStatus = AppointmentCalendarSyncStatus(6i32); } impl ::core::convert::From<i32> for AppointmentCalendarSyncStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentCalendarSyncStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentCalendarSyncStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentCalendarSyncStatus;i4)"); } impl ::windows::core::DefaultType for AppointmentCalendarSyncStatus { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentConflictResult(pub ::windows::core::IInspectable); impl AppointmentConflictResult { pub fn Type(&self) -> ::windows::core::Result<AppointmentConflictType> { let this = self; unsafe { let mut result__: AppointmentConflictType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentConflictType>(result__) } } #[cfg(feature = "Foundation")] pub fn Date(&self) -> ::windows::core::Result<super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::DateTime>(result__) } } } unsafe impl ::windows::core::RuntimeType for AppointmentConflictResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentConflictResult;{d5cdf0be-2f2f-3b7d-af0a-a7e20f3a46e3})"); } unsafe impl ::windows::core::Interface for AppointmentConflictResult { type Vtable = IAppointmentConflictResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd5cdf0be_2f2f_3b7d_af0a_a7e20f3a46e3); } impl ::windows::core::RuntimeName for AppointmentConflictResult { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentConflictResult"; } impl ::core::convert::From<AppointmentConflictResult> for ::windows::core::IUnknown { fn from(value: AppointmentConflictResult) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentConflictResult> for ::windows::core::IUnknown { fn from(value: &AppointmentConflictResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentConflictResult { 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 AppointmentConflictResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentConflictResult> for ::windows::core::IInspectable { fn from(value: AppointmentConflictResult) -> Self { value.0 } } impl ::core::convert::From<&AppointmentConflictResult> for ::windows::core::IInspectable { fn from(value: &AppointmentConflictResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentConflictResult { 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 AppointmentConflictResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentConflictResult {} unsafe impl ::core::marker::Sync for AppointmentConflictResult {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentConflictType(pub i32); impl AppointmentConflictType { pub const None: AppointmentConflictType = AppointmentConflictType(0i32); pub const Adjacent: AppointmentConflictType = AppointmentConflictType(1i32); pub const Overlap: AppointmentConflictType = AppointmentConflictType(2i32); } impl ::core::convert::From<i32> for AppointmentConflictType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentConflictType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentConflictType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentConflictType;i4)"); } impl ::windows::core::DefaultType for AppointmentConflictType { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentDaysOfWeek(pub u32); impl AppointmentDaysOfWeek { pub const None: AppointmentDaysOfWeek = AppointmentDaysOfWeek(0u32); pub const Sunday: AppointmentDaysOfWeek = AppointmentDaysOfWeek(1u32); pub const Monday: AppointmentDaysOfWeek = AppointmentDaysOfWeek(2u32); pub const Tuesday: AppointmentDaysOfWeek = AppointmentDaysOfWeek(4u32); pub const Wednesday: AppointmentDaysOfWeek = AppointmentDaysOfWeek(8u32); pub const Thursday: AppointmentDaysOfWeek = AppointmentDaysOfWeek(16u32); pub const Friday: AppointmentDaysOfWeek = AppointmentDaysOfWeek(32u32); pub const Saturday: AppointmentDaysOfWeek = AppointmentDaysOfWeek(64u32); } impl ::core::convert::From<u32> for AppointmentDaysOfWeek { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentDaysOfWeek { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentDaysOfWeek { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentDaysOfWeek;u4)"); } impl ::windows::core::DefaultType for AppointmentDaysOfWeek { type DefaultType = Self; } impl ::core::ops::BitOr for AppointmentDaysOfWeek { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for AppointmentDaysOfWeek { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for AppointmentDaysOfWeek { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for AppointmentDaysOfWeek { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for AppointmentDaysOfWeek { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentDetailsKind(pub i32); impl AppointmentDetailsKind { pub const PlainText: AppointmentDetailsKind = AppointmentDetailsKind(0i32); pub const Html: AppointmentDetailsKind = AppointmentDetailsKind(1i32); } impl ::core::convert::From<i32> for AppointmentDetailsKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentDetailsKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentDetailsKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentDetailsKind;i4)"); } impl ::windows::core::DefaultType for AppointmentDetailsKind { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentException(pub ::windows::core::IInspectable); impl AppointmentException { pub fn Appointment(&self) -> ::windows::core::Result<Appointment> { 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::<Appointment>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn ExceptionProperties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } pub fn IsDeleted(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for AppointmentException { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentException;{a2076767-16f6-4bce-9f5a-8600b8019fcb})"); } unsafe impl ::windows::core::Interface for AppointmentException { type Vtable = IAppointmentException_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa2076767_16f6_4bce_9f5a_8600b8019fcb); } impl ::windows::core::RuntimeName for AppointmentException { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentException"; } impl ::core::convert::From<AppointmentException> for ::windows::core::IUnknown { fn from(value: AppointmentException) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentException> for ::windows::core::IUnknown { fn from(value: &AppointmentException) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentException { 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 AppointmentException { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentException> for ::windows::core::IInspectable { fn from(value: AppointmentException) -> Self { value.0 } } impl ::core::convert::From<&AppointmentException> for ::windows::core::IInspectable { fn from(value: &AppointmentException) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentException { 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 AppointmentException { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentException {} unsafe impl ::core::marker::Sync for AppointmentException {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentInvitee(pub ::windows::core::IInspectable); impl AppointmentInvitee { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AppointmentInvitee, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn Role(&self) -> ::windows::core::Result<AppointmentParticipantRole> { let this = self; unsafe { let mut result__: AppointmentParticipantRole = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentParticipantRole>(result__) } } pub fn SetRole(&self, value: AppointmentParticipantRole) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn Response(&self) -> ::windows::core::Result<AppointmentParticipantResponse> { let this = self; unsafe { let mut result__: AppointmentParticipantResponse = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentParticipantResponse>(result__) } } pub fn SetResponse(&self, value: AppointmentParticipantResponse) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() } } pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IAppointmentParticipant>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetDisplayName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentParticipant>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Address(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IAppointmentParticipant>(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 SetAddress<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentParticipant>(self)?; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for AppointmentInvitee { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentInvitee;{13bf0796-9842-495b-b0e7-ef8f79c0701d})"); } unsafe impl ::windows::core::Interface for AppointmentInvitee { type Vtable = IAppointmentInvitee_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x13bf0796_9842_495b_b0e7_ef8f79c0701d); } impl ::windows::core::RuntimeName for AppointmentInvitee { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentInvitee"; } impl ::core::convert::From<AppointmentInvitee> for ::windows::core::IUnknown { fn from(value: AppointmentInvitee) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentInvitee> for ::windows::core::IUnknown { fn from(value: &AppointmentInvitee) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentInvitee { 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 AppointmentInvitee { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentInvitee> for ::windows::core::IInspectable { fn from(value: AppointmentInvitee) -> Self { value.0 } } impl ::core::convert::From<&AppointmentInvitee> for ::windows::core::IInspectable { fn from(value: &AppointmentInvitee) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentInvitee { 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 AppointmentInvitee { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<AppointmentInvitee> for IAppointmentParticipant { type Error = ::windows::core::Error; fn try_from(value: AppointmentInvitee) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&AppointmentInvitee> for IAppointmentParticipant { type Error = ::windows::core::Error; fn try_from(value: &AppointmentInvitee) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IAppointmentParticipant> for AppointmentInvitee { fn into_param(self) -> ::windows::core::Param<'a, IAppointmentParticipant> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IAppointmentParticipant> for &AppointmentInvitee { fn into_param(self) -> ::windows::core::Param<'a, IAppointmentParticipant> { ::core::convert::TryInto::<IAppointmentParticipant>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for AppointmentInvitee {} unsafe impl ::core::marker::Sync for AppointmentInvitee {} pub struct AppointmentManager {} impl AppointmentManager { #[cfg(feature = "Foundation")] pub fn ShowAddAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(appointment: Param0, selection: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { Self::IAppointmentManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), appointment.into_param().abi(), selection.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowAddAppointmentWithPlacementAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(appointment: Param0, selection: Param1, preferredplacement: super::super::UI::Popups::Placement) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { Self::IAppointmentManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), appointment.into_param().abi(), selection.into_param().abi(), preferredplacement, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) }) } #[cfg(feature = "Foundation")] pub fn ShowReplaceAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, Appointment>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(appointmentid: Param0, appointment: Param1, selection: Param2) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { Self::IAppointmentManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), appointment.into_param().abi(), selection.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowReplaceAppointmentWithPlacementAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, Appointment>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(appointmentid: Param0, appointment: Param1, selection: Param2, preferredplacement: super::super::UI::Popups::Placement) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { Self::IAppointmentManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), appointment.into_param().abi(), selection.into_param().abi(), preferredplacement, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowReplaceAppointmentWithPlacementAndDateAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, Appointment>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>( appointmentid: Param0, appointment: Param1, selection: Param2, preferredplacement: super::super::UI::Popups::Placement, instancestartdate: Param4, ) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { Self::IAppointmentManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), appointment.into_param().abi(), selection.into_param().abi(), preferredplacement, instancestartdate.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) }) } #[cfg(feature = "Foundation")] pub fn ShowRemoveAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(appointmentid: Param0, selection: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { Self::IAppointmentManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), selection.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowRemoveAppointmentWithPlacementAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(appointmentid: Param0, selection: Param1, preferredplacement: super::super::UI::Popups::Placement) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { Self::IAppointmentManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), selection.into_param().abi(), preferredplacement, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowRemoveAppointmentWithPlacementAndDateAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(appointmentid: Param0, selection: Param1, preferredplacement: super::super::UI::Popups::Placement, instancestartdate: Param3) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { Self::IAppointmentManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), selection.into_param().abi(), preferredplacement, instancestartdate.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) }) } #[cfg(feature = "Foundation")] pub fn ShowTimeFrameAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>>(timetoshow: Param0, duration: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { Self::IAppointmentManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), timetoshow.into_param().abi(), duration.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) }) } #[cfg(feature = "Foundation")] pub fn ShowAppointmentDetailsAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(appointmentid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { Self::IAppointmentManagerStatics2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) }) } #[cfg(feature = "Foundation")] pub fn ShowAppointmentDetailsWithDateAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(appointmentid: Param0, instancestartdate: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { Self::IAppointmentManagerStatics2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), instancestartdate.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) }) } #[cfg(feature = "Foundation")] pub fn ShowEditNewAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>>(appointment: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { Self::IAppointmentManagerStatics2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), appointment.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) }) } #[cfg(feature = "Foundation")] pub fn RequestStoreAsync(options: AppointmentStoreAccessType) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AppointmentStore>> { Self::IAppointmentManagerStatics2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), options, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AppointmentStore>>(result__) }) } #[cfg(feature = "System")] pub fn GetForUser<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::User>>(user: Param0) -> ::windows::core::Result<AppointmentManagerForUser> { Self::IAppointmentManagerStatics3(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), user.into_param().abi(), &mut result__).from_abi::<AppointmentManagerForUser>(result__) }) } pub fn IAppointmentManagerStatics<R, F: FnOnce(&IAppointmentManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AppointmentManager, IAppointmentManagerStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAppointmentManagerStatics2<R, F: FnOnce(&IAppointmentManagerStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AppointmentManager, IAppointmentManagerStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAppointmentManagerStatics3<R, F: FnOnce(&IAppointmentManagerStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AppointmentManager, IAppointmentManagerStatics3> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for AppointmentManager { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentManager"; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentManagerForUser(pub ::windows::core::IInspectable); impl AppointmentManagerForUser { #[cfg(feature = "Foundation")] pub fn ShowAddAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, appointment: Param0, selection: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), appointment.into_param().abi(), selection.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) } } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowAddAppointmentWithPlacementAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, appointment: Param0, selection: Param1, preferredplacement: super::super::UI::Popups::Placement) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), appointment.into_param().abi(), selection.into_param().abi(), preferredplacement, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) } } #[cfg(feature = "Foundation")] pub fn ShowReplaceAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, Appointment>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, appointmentid: Param0, appointment: Param1, selection: Param2) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), appointment.into_param().abi(), selection.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) } } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowReplaceAppointmentWithPlacementAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, Appointment>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, appointmentid: Param0, appointment: Param1, selection: Param2, preferredplacement: super::super::UI::Popups::Placement) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), appointment.into_param().abi(), selection.into_param().abi(), preferredplacement, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) } } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowReplaceAppointmentWithPlacementAndDateAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, Appointment>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>( &self, appointmentid: Param0, appointment: Param1, selection: Param2, preferredplacement: super::super::UI::Popups::Placement, instancestartdate: Param4, ) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), appointment.into_param().abi(), selection.into_param().abi(), preferredplacement, instancestartdate.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) } } #[cfg(feature = "Foundation")] pub fn ShowRemoveAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, appointmentid: Param0, selection: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), selection.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowRemoveAppointmentWithPlacementAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, appointmentid: Param0, selection: Param1, preferredplacement: super::super::UI::Popups::Placement) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), selection.into_param().abi(), preferredplacement, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowRemoveAppointmentWithPlacementAndDateAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(&self, appointmentid: Param0, selection: Param1, preferredplacement: super::super::UI::Popups::Placement, instancestartdate: Param3) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), selection.into_param().abi(), preferredplacement, instancestartdate.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn ShowTimeFrameAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>>(&self, timetoshow: Param0, duration: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), timetoshow.into_param().abi(), duration.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "Foundation")] pub fn ShowAppointmentDetailsAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, appointmentid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "Foundation")] pub fn ShowAppointmentDetailsWithDateAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(&self, appointmentid: Param0, instancestartdate: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), appointmentid.into_param().abi(), instancestartdate.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "Foundation")] pub fn ShowEditNewAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>>(&self, appointment: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), appointment.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) } } #[cfg(feature = "Foundation")] pub fn RequestStoreAsync(&self, options: AppointmentStoreAccessType) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AppointmentStore>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), options, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AppointmentStore>>(result__) } } #[cfg(feature = "System")] pub fn User(&self) -> ::windows::core::Result<super::super::System::User> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::System::User>(result__) } } } unsafe impl ::windows::core::RuntimeType for AppointmentManagerForUser { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentManagerForUser;{70261423-73cc-4660-b318-b01365302a03})"); } unsafe impl ::windows::core::Interface for AppointmentManagerForUser { type Vtable = IAppointmentManagerForUser_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x70261423_73cc_4660_b318_b01365302a03); } impl ::windows::core::RuntimeName for AppointmentManagerForUser { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentManagerForUser"; } impl ::core::convert::From<AppointmentManagerForUser> for ::windows::core::IUnknown { fn from(value: AppointmentManagerForUser) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentManagerForUser> for ::windows::core::IUnknown { fn from(value: &AppointmentManagerForUser) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentManagerForUser { 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 AppointmentManagerForUser { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentManagerForUser> for ::windows::core::IInspectable { fn from(value: AppointmentManagerForUser) -> Self { value.0 } } impl ::core::convert::From<&AppointmentManagerForUser> for ::windows::core::IInspectable { fn from(value: &AppointmentManagerForUser) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentManagerForUser { 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 AppointmentManagerForUser { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentManagerForUser {} unsafe impl ::core::marker::Sync for AppointmentManagerForUser {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentOrganizer(pub ::windows::core::IInspectable); impl AppointmentOrganizer { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AppointmentOrganizer, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetDisplayName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Address(&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 SetAddress<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for AppointmentOrganizer { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentOrganizer;{615e2902-9718-467b-83fb-b293a19121de})"); } unsafe impl ::windows::core::Interface for AppointmentOrganizer { type Vtable = IAppointmentParticipant_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x615e2902_9718_467b_83fb_b293a19121de); } impl ::windows::core::RuntimeName for AppointmentOrganizer { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentOrganizer"; } impl ::core::convert::From<AppointmentOrganizer> for ::windows::core::IUnknown { fn from(value: AppointmentOrganizer) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentOrganizer> for ::windows::core::IUnknown { fn from(value: &AppointmentOrganizer) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentOrganizer { 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 AppointmentOrganizer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentOrganizer> for ::windows::core::IInspectable { fn from(value: AppointmentOrganizer) -> Self { value.0 } } impl ::core::convert::From<&AppointmentOrganizer> for ::windows::core::IInspectable { fn from(value: &AppointmentOrganizer) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentOrganizer { 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 AppointmentOrganizer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<AppointmentOrganizer> for IAppointmentParticipant { fn from(value: AppointmentOrganizer) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&AppointmentOrganizer> for IAppointmentParticipant { fn from(value: &AppointmentOrganizer) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IAppointmentParticipant> for AppointmentOrganizer { fn into_param(self) -> ::windows::core::Param<'a, IAppointmentParticipant> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IAppointmentParticipant> for &AppointmentOrganizer { fn into_param(self) -> ::windows::core::Param<'a, IAppointmentParticipant> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } unsafe impl ::core::marker::Send for AppointmentOrganizer {} unsafe impl ::core::marker::Sync for AppointmentOrganizer {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentParticipantResponse(pub i32); impl AppointmentParticipantResponse { pub const None: AppointmentParticipantResponse = AppointmentParticipantResponse(0i32); pub const Tentative: AppointmentParticipantResponse = AppointmentParticipantResponse(1i32); pub const Accepted: AppointmentParticipantResponse = AppointmentParticipantResponse(2i32); pub const Declined: AppointmentParticipantResponse = AppointmentParticipantResponse(3i32); pub const Unknown: AppointmentParticipantResponse = AppointmentParticipantResponse(4i32); } impl ::core::convert::From<i32> for AppointmentParticipantResponse { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentParticipantResponse { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentParticipantResponse { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentParticipantResponse;i4)"); } impl ::windows::core::DefaultType for AppointmentParticipantResponse { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentParticipantRole(pub i32); impl AppointmentParticipantRole { pub const RequiredAttendee: AppointmentParticipantRole = AppointmentParticipantRole(0i32); pub const OptionalAttendee: AppointmentParticipantRole = AppointmentParticipantRole(1i32); pub const Resource: AppointmentParticipantRole = AppointmentParticipantRole(2i32); } impl ::core::convert::From<i32> for AppointmentParticipantRole { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentParticipantRole { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentParticipantRole { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentParticipantRole;i4)"); } impl ::windows::core::DefaultType for AppointmentParticipantRole { type DefaultType = Self; } pub struct AppointmentProperties {} impl AppointmentProperties { pub fn Subject() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn Location() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn StartTime() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|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), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn Duration() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|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), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn Reminder() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn BusyStatus() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn Sensitivity() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn OriginalStartTime() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn IsResponseRequested() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn AllowNewTimeProposal() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn AllDay() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn Details() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn OnlineMeetingLink() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn ReplyTime() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn Organizer() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn UserResponse() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn HasInvitees() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn IsCanceledMeeting() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn IsOrganizedByUser() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn Recurrence() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn Uri() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn Invitees() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn DefaultProperties() -> ::windows::core::Result<super::super::Foundation::Collections::IVector<::windows::core::HSTRING>> { Self::IAppointmentPropertiesStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<::windows::core::HSTRING>>(result__) }) } pub fn ChangeNumber() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics2(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn RemoteChangeNumber() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics2(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn DetailsKind() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IAppointmentPropertiesStatics2(|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), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn IAppointmentPropertiesStatics<R, F: FnOnce(&IAppointmentPropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AppointmentProperties, IAppointmentPropertiesStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IAppointmentPropertiesStatics2<R, F: FnOnce(&IAppointmentPropertiesStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AppointmentProperties, IAppointmentPropertiesStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for AppointmentProperties { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentProperties"; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentRecurrence(pub ::windows::core::IInspectable); impl AppointmentRecurrence { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AppointmentRecurrence, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn Unit(&self) -> ::windows::core::Result<AppointmentRecurrenceUnit> { let this = self; unsafe { let mut result__: AppointmentRecurrenceUnit = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentRecurrenceUnit>(result__) } } pub fn SetUnit(&self, value: AppointmentRecurrenceUnit) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation")] pub fn Occurrences(&self) -> ::windows::core::Result<super::super::Foundation::IReference<u32>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<u32>>(result__) } } #[cfg(feature = "Foundation")] pub fn SetOccurrences<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::IReference<u32>>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn Until(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Foundation::DateTime>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::super::Foundation::DateTime>>(result__) } } #[cfg(feature = "Foundation")] pub fn SetUntil<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::IReference<super::super::Foundation::DateTime>>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Interval(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetInterval(&self, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() } } pub fn DaysOfWeek(&self) -> ::windows::core::Result<AppointmentDaysOfWeek> { let this = self; unsafe { let mut result__: AppointmentDaysOfWeek = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentDaysOfWeek>(result__) } } pub fn SetDaysOfWeek(&self, value: AppointmentDaysOfWeek) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() } } pub fn WeekOfMonth(&self) -> ::windows::core::Result<AppointmentWeekOfMonth> { let this = self; unsafe { let mut result__: AppointmentWeekOfMonth = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentWeekOfMonth>(result__) } } pub fn SetWeekOfMonth(&self, value: AppointmentWeekOfMonth) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value).ok() } } pub fn Month(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetMonth(&self, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), value).ok() } } pub fn Day(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetDay(&self, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), value).ok() } } pub fn RecurrenceType(&self) -> ::windows::core::Result<RecurrenceType> { let this = &::windows::core::Interface::cast::<IAppointmentRecurrence2>(self)?; unsafe { let mut result__: RecurrenceType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RecurrenceType>(result__) } } pub fn TimeZone(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IAppointmentRecurrence2>(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 SetTimeZone<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentRecurrence2>(self)?; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn CalendarIdentifier(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IAppointmentRecurrence3>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for AppointmentRecurrence { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentRecurrence;{d87b3e83-15a6-487b-b959-0c361e60e954})"); } unsafe impl ::windows::core::Interface for AppointmentRecurrence { type Vtable = IAppointmentRecurrence_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd87b3e83_15a6_487b_b959_0c361e60e954); } impl ::windows::core::RuntimeName for AppointmentRecurrence { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentRecurrence"; } impl ::core::convert::From<AppointmentRecurrence> for ::windows::core::IUnknown { fn from(value: AppointmentRecurrence) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentRecurrence> for ::windows::core::IUnknown { fn from(value: &AppointmentRecurrence) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentRecurrence { 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 AppointmentRecurrence { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentRecurrence> for ::windows::core::IInspectable { fn from(value: AppointmentRecurrence) -> Self { value.0 } } impl ::core::convert::From<&AppointmentRecurrence> for ::windows::core::IInspectable { fn from(value: &AppointmentRecurrence) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentRecurrence { 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 AppointmentRecurrence { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentRecurrence {} unsafe impl ::core::marker::Sync for AppointmentRecurrence {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentRecurrenceUnit(pub i32); impl AppointmentRecurrenceUnit { pub const Daily: AppointmentRecurrenceUnit = AppointmentRecurrenceUnit(0i32); pub const Weekly: AppointmentRecurrenceUnit = AppointmentRecurrenceUnit(1i32); pub const Monthly: AppointmentRecurrenceUnit = AppointmentRecurrenceUnit(2i32); pub const MonthlyOnDay: AppointmentRecurrenceUnit = AppointmentRecurrenceUnit(3i32); pub const Yearly: AppointmentRecurrenceUnit = AppointmentRecurrenceUnit(4i32); pub const YearlyOnDay: AppointmentRecurrenceUnit = AppointmentRecurrenceUnit(5i32); } impl ::core::convert::From<i32> for AppointmentRecurrenceUnit { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentRecurrenceUnit { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentRecurrenceUnit { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentRecurrenceUnit;i4)"); } impl ::windows::core::DefaultType for AppointmentRecurrenceUnit { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentSensitivity(pub i32); impl AppointmentSensitivity { pub const Public: AppointmentSensitivity = AppointmentSensitivity(0i32); pub const Private: AppointmentSensitivity = AppointmentSensitivity(1i32); } impl ::core::convert::From<i32> for AppointmentSensitivity { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentSensitivity { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentSensitivity { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentSensitivity;i4)"); } impl ::windows::core::DefaultType for AppointmentSensitivity { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentStore(pub ::windows::core::IInspectable); impl AppointmentStore { pub fn ChangeTracker(&self) -> ::windows::core::Result<AppointmentStoreChangeTracker> { 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::<AppointmentStoreChangeTracker>(result__) } } #[cfg(feature = "Foundation")] pub fn CreateAppointmentCalendarAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, name: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AppointmentCalendar>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), name.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AppointmentCalendar>>(result__) } } #[cfg(feature = "Foundation")] pub fn GetAppointmentCalendarAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, calendarid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AppointmentCalendar>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), calendarid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AppointmentCalendar>>(result__) } } #[cfg(feature = "Foundation")] pub fn GetAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, localid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<Appointment>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), localid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<Appointment>>(result__) } } #[cfg(feature = "Foundation")] pub fn GetAppointmentInstanceAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(&self, localid: Param0, instancestarttime: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<Appointment>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), localid.into_param().abi(), instancestarttime.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<Appointment>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn FindAppointmentCalendarsAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<AppointmentCalendar>>> { 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::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<AppointmentCalendar>>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn FindAppointmentCalendarsAsyncWithOptions(&self, options: FindAppointmentCalendarsOptions) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<AppointmentCalendar>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), options, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<AppointmentCalendar>>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn FindAppointmentsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>>(&self, rangestart: Param0, rangelength: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), rangestart.into_param().abi(), rangelength.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn FindAppointmentsAsyncWithOptions<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>, Param2: ::windows::core::IntoParam<'a, FindAppointmentsOptions>>(&self, rangestart: Param0, rangelength: Param1, options: Param2) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), rangestart.into_param().abi(), rangelength.into_param().abi(), options.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Appointment>>>(result__) } } #[cfg(feature = "Foundation")] pub fn FindConflictAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>>(&self, appointment: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AppointmentConflictResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), appointment.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AppointmentConflictResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn FindConflictAsyncWithInstanceStart<'a, Param0: ::windows::core::IntoParam<'a, Appointment>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(&self, appointment: Param0, instancestarttime: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AppointmentConflictResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), appointment.into_param().abi(), instancestarttime.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AppointmentConflictResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn MoveAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>, Param1: ::windows::core::IntoParam<'a, AppointmentCalendar>>(&self, appointment: Param0, destinationcalendar: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), appointment.into_param().abi(), destinationcalendar.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "Foundation")] pub fn ShowAddAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, appointment: Param0, selection: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), appointment.into_param().abi(), selection.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) } } #[cfg(feature = "Foundation")] pub fn ShowReplaceAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, Appointment>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, localid: Param0, appointment: Param1, selection: Param2) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), localid.into_param().abi(), appointment.into_param().abi(), selection.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) } } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowReplaceAppointmentWithPlacementAndDateAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, Appointment>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>( &self, localid: Param0, appointment: Param1, selection: Param2, preferredplacement: super::super::UI::Popups::Placement, instancestartdate: Param4, ) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), localid.into_param().abi(), appointment.into_param().abi(), selection.into_param().abi(), preferredplacement, instancestartdate.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) } } #[cfg(feature = "Foundation")] pub fn ShowRemoveAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, localid: Param0, selection: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), localid.into_param().abi(), selection.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub fn ShowRemoveAppointmentWithPlacementAndDateAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(&self, localid: Param0, selection: Param1, preferredplacement: super::super::UI::Popups::Placement, instancestartdate: Param3) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), localid.into_param().abi(), selection.into_param().abi(), preferredplacement, instancestartdate.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn ShowAppointmentDetailsAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, localid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), localid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "Foundation")] pub fn ShowAppointmentDetailsWithDateAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>>(&self, localid: Param0, instancestartdate: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), localid.into_param().abi(), instancestartdate.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "Foundation")] pub fn ShowEditNewAppointmentAsync<'a, Param0: ::windows::core::IntoParam<'a, Appointment>>(&self, appointment: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), appointment.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<::windows::core::HSTRING>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn FindLocalIdsFromRoamingIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, roamingid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), roamingid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>>(result__) } } #[cfg(feature = "Foundation")] pub fn StoreChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AppointmentStore, AppointmentStoreChangedEventArgs>>>(&self, phandler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = &::windows::core::Interface::cast::<IAppointmentStore2>(self)?; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), phandler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveStoreChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IAppointmentStore2>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn CreateAppointmentCalendarInAccountAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, name: Param0, userdataaccountid: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AppointmentCalendar>> { let this = &::windows::core::Interface::cast::<IAppointmentStore2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), name.into_param().abi(), userdataaccountid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AppointmentCalendar>>(result__) } } pub fn GetChangeTracker<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, identity: Param0) -> ::windows::core::Result<AppointmentStoreChangeTracker> { let this = &::windows::core::Interface::cast::<IAppointmentStore3>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), identity.into_param().abi(), &mut result__).from_abi::<AppointmentStoreChangeTracker>(result__) } } } unsafe impl ::windows::core::RuntimeType for AppointmentStore { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentStore;{a461918c-7a47-4d96-96c9-15cd8a05a735})"); } unsafe impl ::windows::core::Interface for AppointmentStore { type Vtable = IAppointmentStore_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa461918c_7a47_4d96_96c9_15cd8a05a735); } impl ::windows::core::RuntimeName for AppointmentStore { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentStore"; } impl ::core::convert::From<AppointmentStore> for ::windows::core::IUnknown { fn from(value: AppointmentStore) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentStore> for ::windows::core::IUnknown { fn from(value: &AppointmentStore) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentStore { 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 AppointmentStore { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentStore> for ::windows::core::IInspectable { fn from(value: AppointmentStore) -> Self { value.0 } } impl ::core::convert::From<&AppointmentStore> for ::windows::core::IInspectable { fn from(value: &AppointmentStore) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentStore { 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 AppointmentStore { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentStore {} unsafe impl ::core::marker::Sync for AppointmentStore {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentStoreAccessType(pub i32); impl AppointmentStoreAccessType { pub const AppCalendarsReadWrite: AppointmentStoreAccessType = AppointmentStoreAccessType(0i32); pub const AllCalendarsReadOnly: AppointmentStoreAccessType = AppointmentStoreAccessType(1i32); pub const AllCalendarsReadWrite: AppointmentStoreAccessType = AppointmentStoreAccessType(2i32); } impl ::core::convert::From<i32> for AppointmentStoreAccessType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentStoreAccessType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentStoreAccessType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentStoreAccessType;i4)"); } impl ::windows::core::DefaultType for AppointmentStoreAccessType { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentStoreChange(pub ::windows::core::IInspectable); impl AppointmentStoreChange { pub fn Appointment(&self) -> ::windows::core::Result<Appointment> { 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::<Appointment>(result__) } } pub fn ChangeType(&self) -> ::windows::core::Result<AppointmentStoreChangeType> { let this = self; unsafe { let mut result__: AppointmentStoreChangeType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentStoreChangeType>(result__) } } pub fn AppointmentCalendar(&self) -> ::windows::core::Result<AppointmentCalendar> { let this = &::windows::core::Interface::cast::<IAppointmentStoreChange2>(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::<AppointmentCalendar>(result__) } } } unsafe impl ::windows::core::RuntimeType for AppointmentStoreChange { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentStoreChange;{a5a6e035-0a33-3654-8463-b543e90c3b79})"); } unsafe impl ::windows::core::Interface for AppointmentStoreChange { type Vtable = IAppointmentStoreChange_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa5a6e035_0a33_3654_8463_b543e90c3b79); } impl ::windows::core::RuntimeName for AppointmentStoreChange { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentStoreChange"; } impl ::core::convert::From<AppointmentStoreChange> for ::windows::core::IUnknown { fn from(value: AppointmentStoreChange) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentStoreChange> for ::windows::core::IUnknown { fn from(value: &AppointmentStoreChange) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentStoreChange { 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 AppointmentStoreChange { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentStoreChange> for ::windows::core::IInspectable { fn from(value: AppointmentStoreChange) -> Self { value.0 } } impl ::core::convert::From<&AppointmentStoreChange> for ::windows::core::IInspectable { fn from(value: &AppointmentStoreChange) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentStoreChange { 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 AppointmentStoreChange { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentStoreChange {} unsafe impl ::core::marker::Sync for AppointmentStoreChange {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentStoreChangeReader(pub ::windows::core::IInspectable); impl AppointmentStoreChangeReader { #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn ReadBatchAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<AppointmentStoreChange>>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<AppointmentStoreChange>>>(result__) } } pub fn AcceptChanges(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() } } pub fn AcceptChangesThrough<'a, Param0: ::windows::core::IntoParam<'a, AppointmentStoreChange>>(&self, lastchangetoaccept: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), lastchangetoaccept.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for AppointmentStoreChangeReader { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentStoreChangeReader;{8b2409f1-65f3-42a0-961d-4c209bf30370})"); } unsafe impl ::windows::core::Interface for AppointmentStoreChangeReader { type Vtable = IAppointmentStoreChangeReader_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8b2409f1_65f3_42a0_961d_4c209bf30370); } impl ::windows::core::RuntimeName for AppointmentStoreChangeReader { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentStoreChangeReader"; } impl ::core::convert::From<AppointmentStoreChangeReader> for ::windows::core::IUnknown { fn from(value: AppointmentStoreChangeReader) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentStoreChangeReader> for ::windows::core::IUnknown { fn from(value: &AppointmentStoreChangeReader) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentStoreChangeReader { 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 AppointmentStoreChangeReader { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentStoreChangeReader> for ::windows::core::IInspectable { fn from(value: AppointmentStoreChangeReader) -> Self { value.0 } } impl ::core::convert::From<&AppointmentStoreChangeReader> for ::windows::core::IInspectable { fn from(value: &AppointmentStoreChangeReader) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentStoreChangeReader { 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 AppointmentStoreChangeReader { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentStoreChangeReader {} unsafe impl ::core::marker::Sync for AppointmentStoreChangeReader {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentStoreChangeTracker(pub ::windows::core::IInspectable); impl AppointmentStoreChangeTracker { pub fn GetChangeReader(&self) -> ::windows::core::Result<AppointmentStoreChangeReader> { 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::<AppointmentStoreChangeReader>(result__) } } pub fn Enable(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() } } pub fn Reset(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() } } pub fn IsTracking(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IAppointmentStoreChangeTracker2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for AppointmentStoreChangeTracker { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentStoreChangeTracker;{1b25f4b1-8ece-4f17-93c8-e6412458fd5c})"); } unsafe impl ::windows::core::Interface for AppointmentStoreChangeTracker { type Vtable = IAppointmentStoreChangeTracker_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1b25f4b1_8ece_4f17_93c8_e6412458fd5c); } impl ::windows::core::RuntimeName for AppointmentStoreChangeTracker { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentStoreChangeTracker"; } impl ::core::convert::From<AppointmentStoreChangeTracker> for ::windows::core::IUnknown { fn from(value: AppointmentStoreChangeTracker) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentStoreChangeTracker> for ::windows::core::IUnknown { fn from(value: &AppointmentStoreChangeTracker) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentStoreChangeTracker { 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 AppointmentStoreChangeTracker { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentStoreChangeTracker> for ::windows::core::IInspectable { fn from(value: AppointmentStoreChangeTracker) -> Self { value.0 } } impl ::core::convert::From<&AppointmentStoreChangeTracker> for ::windows::core::IInspectable { fn from(value: &AppointmentStoreChangeTracker) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentStoreChangeTracker { 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 AppointmentStoreChangeTracker { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentStoreChangeTracker {} unsafe impl ::core::marker::Sync for AppointmentStoreChangeTracker {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentStoreChangeType(pub i32); impl AppointmentStoreChangeType { pub const AppointmentCreated: AppointmentStoreChangeType = AppointmentStoreChangeType(0i32); pub const AppointmentModified: AppointmentStoreChangeType = AppointmentStoreChangeType(1i32); pub const AppointmentDeleted: AppointmentStoreChangeType = AppointmentStoreChangeType(2i32); pub const ChangeTrackingLost: AppointmentStoreChangeType = AppointmentStoreChangeType(3i32); pub const CalendarCreated: AppointmentStoreChangeType = AppointmentStoreChangeType(4i32); pub const CalendarModified: AppointmentStoreChangeType = AppointmentStoreChangeType(5i32); pub const CalendarDeleted: AppointmentStoreChangeType = AppointmentStoreChangeType(6i32); } impl ::core::convert::From<i32> for AppointmentStoreChangeType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentStoreChangeType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentStoreChangeType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentStoreChangeType;i4)"); } impl ::windows::core::DefaultType for AppointmentStoreChangeType { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentStoreChangedDeferral(pub ::windows::core::IInspectable); impl AppointmentStoreChangedDeferral { pub fn Complete(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } } unsafe impl ::windows::core::RuntimeType for AppointmentStoreChangedDeferral { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentStoreChangedDeferral;{4cb82026-fedb-4bc3-9662-95a9befdf4df})"); } unsafe impl ::windows::core::Interface for AppointmentStoreChangedDeferral { type Vtable = IAppointmentStoreChangedDeferral_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4cb82026_fedb_4bc3_9662_95a9befdf4df); } impl ::windows::core::RuntimeName for AppointmentStoreChangedDeferral { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentStoreChangedDeferral"; } impl ::core::convert::From<AppointmentStoreChangedDeferral> for ::windows::core::IUnknown { fn from(value: AppointmentStoreChangedDeferral) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentStoreChangedDeferral> for ::windows::core::IUnknown { fn from(value: &AppointmentStoreChangedDeferral) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentStoreChangedDeferral { 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 AppointmentStoreChangedDeferral { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentStoreChangedDeferral> for ::windows::core::IInspectable { fn from(value: AppointmentStoreChangedDeferral) -> Self { value.0 } } impl ::core::convert::From<&AppointmentStoreChangedDeferral> for ::windows::core::IInspectable { fn from(value: &AppointmentStoreChangedDeferral) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentStoreChangedDeferral { 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 AppointmentStoreChangedDeferral { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentStoreChangedDeferral {} unsafe impl ::core::marker::Sync for AppointmentStoreChangedDeferral {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentStoreChangedEventArgs(pub ::windows::core::IInspectable); impl AppointmentStoreChangedEventArgs { pub fn GetDeferral(&self) -> ::windows::core::Result<AppointmentStoreChangedDeferral> { 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::<AppointmentStoreChangedDeferral>(result__) } } } unsafe impl ::windows::core::RuntimeType for AppointmentStoreChangedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentStoreChangedEventArgs;{2285f8b9-0791-417e-bfea-cc6d41636c8c})"); } unsafe impl ::windows::core::Interface for AppointmentStoreChangedEventArgs { type Vtable = IAppointmentStoreChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2285f8b9_0791_417e_bfea_cc6d41636c8c); } impl ::windows::core::RuntimeName for AppointmentStoreChangedEventArgs { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentStoreChangedEventArgs"; } impl ::core::convert::From<AppointmentStoreChangedEventArgs> for ::windows::core::IUnknown { fn from(value: AppointmentStoreChangedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentStoreChangedEventArgs> for ::windows::core::IUnknown { fn from(value: &AppointmentStoreChangedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentStoreChangedEventArgs { 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 AppointmentStoreChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentStoreChangedEventArgs> for ::windows::core::IInspectable { fn from(value: AppointmentStoreChangedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&AppointmentStoreChangedEventArgs> for ::windows::core::IInspectable { fn from(value: &AppointmentStoreChangedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentStoreChangedEventArgs { 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 AppointmentStoreChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentStoreChangedEventArgs {} unsafe impl ::core::marker::Sync for AppointmentStoreChangedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AppointmentStoreNotificationTriggerDetails(pub ::windows::core::IInspectable); impl AppointmentStoreNotificationTriggerDetails {} unsafe impl ::windows::core::RuntimeType for AppointmentStoreNotificationTriggerDetails { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.AppointmentStoreNotificationTriggerDetails;{9b33cb11-c301-421e-afef-047ecfa76adb})"); } unsafe impl ::windows::core::Interface for AppointmentStoreNotificationTriggerDetails { type Vtable = IAppointmentStoreNotificationTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9b33cb11_c301_421e_afef_047ecfa76adb); } impl ::windows::core::RuntimeName for AppointmentStoreNotificationTriggerDetails { const NAME: &'static str = "Windows.ApplicationModel.Appointments.AppointmentStoreNotificationTriggerDetails"; } impl ::core::convert::From<AppointmentStoreNotificationTriggerDetails> for ::windows::core::IUnknown { fn from(value: AppointmentStoreNotificationTriggerDetails) -> Self { value.0 .0 } } impl ::core::convert::From<&AppointmentStoreNotificationTriggerDetails> for ::windows::core::IUnknown { fn from(value: &AppointmentStoreNotificationTriggerDetails) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentStoreNotificationTriggerDetails { 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 AppointmentStoreNotificationTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AppointmentStoreNotificationTriggerDetails> for ::windows::core::IInspectable { fn from(value: AppointmentStoreNotificationTriggerDetails) -> Self { value.0 } } impl ::core::convert::From<&AppointmentStoreNotificationTriggerDetails> for ::windows::core::IInspectable { fn from(value: &AppointmentStoreNotificationTriggerDetails) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentStoreNotificationTriggerDetails { 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 AppointmentStoreNotificationTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AppointmentStoreNotificationTriggerDetails {} unsafe impl ::core::marker::Sync for AppointmentStoreNotificationTriggerDetails {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentSummaryCardView(pub i32); impl AppointmentSummaryCardView { pub const System: AppointmentSummaryCardView = AppointmentSummaryCardView(0i32); pub const App: AppointmentSummaryCardView = AppointmentSummaryCardView(1i32); } impl ::core::convert::From<i32> for AppointmentSummaryCardView { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentSummaryCardView { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentSummaryCardView { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentSummaryCardView;i4)"); } impl ::windows::core::DefaultType for AppointmentSummaryCardView { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AppointmentWeekOfMonth(pub i32); impl AppointmentWeekOfMonth { pub const First: AppointmentWeekOfMonth = AppointmentWeekOfMonth(0i32); pub const Second: AppointmentWeekOfMonth = AppointmentWeekOfMonth(1i32); pub const Third: AppointmentWeekOfMonth = AppointmentWeekOfMonth(2i32); pub const Fourth: AppointmentWeekOfMonth = AppointmentWeekOfMonth(3i32); pub const Last: AppointmentWeekOfMonth = AppointmentWeekOfMonth(4i32); } impl ::core::convert::From<i32> for AppointmentWeekOfMonth { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AppointmentWeekOfMonth { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AppointmentWeekOfMonth { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.AppointmentWeekOfMonth;i4)"); } impl ::windows::core::DefaultType for AppointmentWeekOfMonth { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct FindAppointmentCalendarsOptions(pub u32); impl FindAppointmentCalendarsOptions { pub const None: FindAppointmentCalendarsOptions = FindAppointmentCalendarsOptions(0u32); pub const IncludeHidden: FindAppointmentCalendarsOptions = FindAppointmentCalendarsOptions(1u32); } impl ::core::convert::From<u32> for FindAppointmentCalendarsOptions { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for FindAppointmentCalendarsOptions { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for FindAppointmentCalendarsOptions { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.FindAppointmentCalendarsOptions;u4)"); } impl ::windows::core::DefaultType for FindAppointmentCalendarsOptions { type DefaultType = Self; } impl ::core::ops::BitOr for FindAppointmentCalendarsOptions { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for FindAppointmentCalendarsOptions { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for FindAppointmentCalendarsOptions { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for FindAppointmentCalendarsOptions { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for FindAppointmentCalendarsOptions { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct FindAppointmentsOptions(pub ::windows::core::IInspectable); impl FindAppointmentsOptions { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<FindAppointmentsOptions, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation_Collections")] pub fn CalendarIds(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<::windows::core::HSTRING>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn FetchProperties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<::windows::core::HSTRING>>(result__) } } pub fn IncludeHidden(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetIncludeHidden(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() } } pub fn MaxCount(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetMaxCount(&self, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } } unsafe impl ::windows::core::RuntimeType for FindAppointmentsOptions { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.FindAppointmentsOptions;{55f7dc55-9942-3086-82b5-2cb29f64d5f5})"); } unsafe impl ::windows::core::Interface for FindAppointmentsOptions { type Vtable = IFindAppointmentsOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x55f7dc55_9942_3086_82b5_2cb29f64d5f5); } impl ::windows::core::RuntimeName for FindAppointmentsOptions { const NAME: &'static str = "Windows.ApplicationModel.Appointments.FindAppointmentsOptions"; } impl ::core::convert::From<FindAppointmentsOptions> for ::windows::core::IUnknown { fn from(value: FindAppointmentsOptions) -> Self { value.0 .0 } } impl ::core::convert::From<&FindAppointmentsOptions> for ::windows::core::IUnknown { fn from(value: &FindAppointmentsOptions) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for FindAppointmentsOptions { 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 FindAppointmentsOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<FindAppointmentsOptions> for ::windows::core::IInspectable { fn from(value: FindAppointmentsOptions) -> Self { value.0 } } impl ::core::convert::From<&FindAppointmentsOptions> for ::windows::core::IInspectable { fn from(value: &FindAppointmentsOptions) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for FindAppointmentsOptions { 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 FindAppointmentsOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for FindAppointmentsOptions {} unsafe impl ::core::marker::Sync for FindAppointmentsOptions {} #[repr(transparent)] #[doc(hidden)] pub struct IAppointment(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointment { type Vtable = IAppointment_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdd002f2f_2bdd_4076_90a3_22c275312965); } #[repr(C)] #[doc(hidden)] pub struct IAppointment_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut AppointmentBusyStatus) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentBusyStatus) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut AppointmentSensitivity) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentSensitivity) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointment2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointment2 { type Vtable = IAppointment2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5e85983c_540f_3452_9b5c_0dd7ad4c65a2); } #[repr(C)] #[doc(hidden)] pub struct IAppointment2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut AppointmentParticipantResponse) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentParticipantResponse) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointment3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointment3 { type Vtable = IAppointment3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbfcc45a9_8961_4991_934b_c48768e5a96c); } #[repr(C)] #[doc(hidden)] pub struct IAppointment3_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 u64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut AppointmentDetailsKind) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentDetailsKind) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentCalendar(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentCalendar { type Vtable = IAppointmentCalendar_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5273819d_8339_3d4f_a02f_64084452bb5d); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentCalendar_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 = "UI")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::UI::Color) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut AppointmentCalendarOtherAppReadAccess) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentCalendarOtherAppReadAccess) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut AppointmentCalendarOtherAppWriteAccess) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentCalendarOtherAppWriteAccess) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut AppointmentSummaryCardView) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentSummaryCardView) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, rangestart: super::super::Foundation::DateTime, rangelength: super::super::Foundation::TimeSpan, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, rangestart: super::super::Foundation::DateTime, rangelength: super::super::Foundation::TimeSpan, options: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, masterlocalid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, masterlocalid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, rangestart: super::super::Foundation::DateTime, rangelength: super::super::Foundation::TimeSpan, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, masterlocalid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, rangestart: super::super::Foundation::DateTime, rangelength: super::super::Foundation::TimeSpan, poptions: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, instancestarttime: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, options: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, instancestarttime: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pappointment: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentCalendar2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentCalendar2 { type Vtable = IAppointmentCalendar2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x18e7e422_2467_4e1c_a459_d8a29303d092); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentCalendar2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "UI")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::UI::Color) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointment: ::windows::core::RawPtr, notifyinvitees: bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, meeting: ::windows::core::RawPtr, subject: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, comment: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, notifyinvitees: bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, meeting: ::windows::core::RawPtr, invitees: ::windows::core::RawPtr, subject: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, forwardheader: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, comment: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, meeting: ::windows::core::RawPtr, newstarttime: super::super::Foundation::DateTime, newduration: super::super::Foundation::TimeSpan, subject: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, comment: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, meeting: ::windows::core::RawPtr, response: AppointmentParticipantResponse, subject: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, comment: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sendupdate: bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentCalendar3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentCalendar3 { type Vtable = IAppointmentCalendar3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xeb23d22b_a685_42ae_8495_b3119adb4167); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentCalendar3_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentCalendarSyncManager(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentCalendarSyncManager { type Vtable = IAppointmentCalendarSyncManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2b21b3a0_4aff_4392_bc5f_5645ffcffb17); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentCalendarSyncManager_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 AppointmentCalendarSyncStatus) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentCalendarSyncManager2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentCalendarSyncManager2 { type Vtable = IAppointmentCalendarSyncManager2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x647528ad_0d29_4c7c_aaa7_bf996805537c); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentCalendarSyncManager2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentCalendarSyncStatus) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentConflictResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentConflictResult { type Vtable = IAppointmentConflictResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd5cdf0be_2f2f_3b7d_af0a_a7e20f3a46e3); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentConflictResult_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 AppointmentConflictType) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentException(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentException { type Vtable = IAppointmentException_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa2076767_16f6_4bce_9f5a_8600b8019fcb); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentException_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentInvitee(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentInvitee { type Vtable = IAppointmentInvitee_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x13bf0796_9842_495b_b0e7_ef8f79c0701d); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentInvitee_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 AppointmentParticipantRole) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentParticipantRole) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut AppointmentParticipantResponse) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentParticipantResponse) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentManagerForUser(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentManagerForUser { type Vtable = IAppointmentManagerForUser_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x70261423_73cc_4660_b318_b01365302a03); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentManagerForUser_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, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement, instancestartdate: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, selection: super::super::Foundation::Rect, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement, instancestartdate: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, timetoshow: super::super::Foundation::DateTime, duration: super::super::Foundation::TimeSpan, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, instancestartdate: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointment: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, options: AppointmentStoreAccessType, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "System")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "System"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentManagerStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentManagerStatics { type Vtable = IAppointmentManagerStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3a30fa01_5c40_499d_b33f_a43050f74fc4); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentManagerStatics_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, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement, instancestartdate: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, selection: super::super::Foundation::Rect, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement, instancestartdate: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, timetoshow: super::super::Foundation::DateTime, duration: super::super::Foundation::TimeSpan, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentManagerStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentManagerStatics2 { type Vtable = IAppointmentManagerStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0a81f60d_d04f_4034_af72_a36573b45ff0); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentManagerStatics2_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, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointmentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, instancestartdate: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointment: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, options: AppointmentStoreAccessType, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentManagerStatics3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentManagerStatics3 { type Vtable = IAppointmentManagerStatics3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2f9ae09c_b34c_4dc7_a35d_cafd88ae3ec6); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentManagerStatics3_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 = "System")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, user: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "System"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IAppointmentParticipant(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentParticipant { type Vtable = IAppointmentParticipant_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x615e2902_9718_467b_83fb_b293a19121de); } impl IAppointmentParticipant { pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetDisplayName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Address(&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 SetAddress<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for IAppointmentParticipant { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{615e2902-9718-467b-83fb-b293a19121de}"); } impl ::core::convert::From<IAppointmentParticipant> for ::windows::core::IUnknown { fn from(value: IAppointmentParticipant) -> Self { value.0 .0 } } impl ::core::convert::From<&IAppointmentParticipant> for ::windows::core::IUnknown { fn from(value: &IAppointmentParticipant) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAppointmentParticipant { 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 IAppointmentParticipant { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IAppointmentParticipant> for ::windows::core::IInspectable { fn from(value: IAppointmentParticipant) -> Self { value.0 } } impl ::core::convert::From<&IAppointmentParticipant> for ::windows::core::IInspectable { fn from(value: &IAppointmentParticipant) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IAppointmentParticipant { 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 IAppointmentParticipant { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IAppointmentParticipant_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentPropertiesStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentPropertiesStatics { type Vtable = IAppointmentPropertiesStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x25141fe9_68ae_3aae_855f_bc4441caa234); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentPropertiesStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[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 IAppointmentPropertiesStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentPropertiesStatics2 { type Vtable = IAppointmentPropertiesStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdffc434b_b017_45dd_8af5_d163d10801bb); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentPropertiesStatics2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentRecurrence(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentRecurrence { type Vtable = IAppointmentRecurrence_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd87b3e83_15a6_487b_b959_0c361e60e954); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentRecurrence_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 AppointmentRecurrenceUnit) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentRecurrenceUnit) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut AppointmentDaysOfWeek) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentDaysOfWeek) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut AppointmentWeekOfMonth) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: AppointmentWeekOfMonth) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentRecurrence2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentRecurrence2 { type Vtable = IAppointmentRecurrence2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3df3a2e0_05a7_4f50_9f86_b03f9436254d); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentRecurrence2_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 RecurrenceType) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentRecurrence3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentRecurrence3 { type Vtable = IAppointmentRecurrence3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x89ff96d9_da4d_4a17_8dd2_1cebc2b5ff9d); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentRecurrence3_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentStore(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentStore { type Vtable = IAppointmentStore_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa461918c_7a47_4d96_96c9_15cd8a05a735); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentStore_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, calendarid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, instancestarttime: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, options: FindAppointmentCalendarsOptions, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, rangestart: super::super::Foundation::DateTime, rangelength: super::super::Foundation::TimeSpan, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, rangestart: super::super::Foundation::DateTime, rangelength: super::super::Foundation::TimeSpan, options: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointment: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointment: ::windows::core::RawPtr, instancestarttime: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointment: ::windows::core::RawPtr, destinationcalendar: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, appointment: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement, instancestartdate: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, selection: super::super::Foundation::Rect, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, selection: super::super::Foundation::Rect, preferredplacement: super::super::UI::Popups::Placement, instancestartdate: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, localid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, instancestartdate: super::super::Foundation::DateTime, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appointment: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, roamingid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentStore2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentStore2 { type Vtable = IAppointmentStore2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x25c48c20_1c41_424f_8084_67c1cfe0a854); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentStore2_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, phandler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, userdataaccountid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentStore3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentStore3 { type Vtable = IAppointmentStore3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4251940b_b078_470a_9a40_c2e01761f72f); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentStore3_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, identity: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentStoreChange(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentStoreChange { type Vtable = IAppointmentStoreChange_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa5a6e035_0a33_3654_8463_b543e90c3b79); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentStoreChange_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut AppointmentStoreChangeType) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentStoreChange2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentStoreChange2 { type Vtable = IAppointmentStoreChange2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb37d0dce_5211_4402_a608_a96fe70b8ee2); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentStoreChange2_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 IAppointmentStoreChangeReader(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentStoreChangeReader { type Vtable = IAppointmentStoreChangeReader_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8b2409f1_65f3_42a0_961d_4c209bf30370); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentStoreChangeReader_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lastchangetoaccept: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentStoreChangeTracker(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentStoreChangeTracker { type Vtable = IAppointmentStoreChangeTracker_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1b25f4b1_8ece_4f17_93c8_e6412458fd5c); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentStoreChangeTracker_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentStoreChangeTracker2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentStoreChangeTracker2 { type Vtable = IAppointmentStoreChangeTracker2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb66aaf45_9542_4cf7_8550_eb370e0c08d3); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentStoreChangeTracker2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentStoreChangedDeferral(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentStoreChangedDeferral { type Vtable = IAppointmentStoreChangedDeferral_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4cb82026_fedb_4bc3_9662_95a9befdf4df); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentStoreChangedDeferral_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAppointmentStoreChangedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentStoreChangedEventArgs { type Vtable = IAppointmentStoreChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2285f8b9_0791_417e_bfea_cc6d41636c8c); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentStoreChangedEventArgs_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 IAppointmentStoreNotificationTriggerDetails(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAppointmentStoreNotificationTriggerDetails { type Vtable = IAppointmentStoreNotificationTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9b33cb11_c301_421e_afef_047ecfa76adb); } #[repr(C)] #[doc(hidden)] pub struct IAppointmentStoreNotificationTriggerDetails_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IFindAppointmentsOptions(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IFindAppointmentsOptions { type Vtable = IFindAppointmentsOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x55f7dc55_9942_3086_82b5_2cb29f64d5f5); } #[repr(C)] #[doc(hidden)] pub struct IFindAppointmentsOptions_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::windows::core::HRESULT, ); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RecurrenceType(pub i32); impl RecurrenceType { pub const Master: RecurrenceType = RecurrenceType(0i32); pub const Instance: RecurrenceType = RecurrenceType(1i32); pub const ExceptionInstance: RecurrenceType = RecurrenceType(2i32); } impl ::core::convert::From<i32> for RecurrenceType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RecurrenceType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for RecurrenceType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.Appointments.RecurrenceType;i4)"); } impl ::windows::core::DefaultType for RecurrenceType { type DefaultType = Self; }
use image::ImageBuffer; use rand::rngs::SmallRng; use rand::{Rng, SeedableRng}; // assuming 0.0 <= value <= 1.0 fn brightness(value: f64) -> u8 { (value * 255f64) as u8 } fn rnd(func: fn(i64, i64) -> i64, x: i64, y: i64) -> u8 { brightness(SmallRng::seed_from_u64(func(x, y) as u64).gen()) } fn main() { // change these lines to play around with patterns let func = |x: i64, y: i64| -> i64 { x ^ y }; let zoom: u32 = 2; let size: u32 = 512; ImageBuffer::from_fn(size, size, |x, y| { image::Luma([rnd( func, (((x / zoom) as i64) - (size as i64 / 2)).abs(), (((y / zoom) as i64) - (size as i64 / 2)).abs(), )]) }) .save("out.png") .unwrap(); }
mod world; mod mouse; mod dot; mod line; pub use self::mouse::Mouse; pub use self::dot::Dot; pub use self::world::World; pub use self::line::Line;
#[doc = "Reader of register CHMAP3"] pub type R = crate::R<u32, super::CHMAP3>; #[doc = "Writer for register CHMAP3"] pub type W = crate::W<u32, super::CHMAP3>; #[doc = "Register CHMAP3 `reset()`'s with value 0"] impl crate::ResetValue for super::CHMAP3 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `CH24SEL`"] pub type CH24SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH24SEL`"] pub struct CH24SEL_W<'a> { w: &'a mut W, } impl<'a> CH24SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `CH25SEL`"] pub type CH25SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH25SEL`"] pub struct CH25SEL_W<'a> { w: &'a mut W, } impl<'a> CH25SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Reader of field `CH26SEL`"] pub type CH26SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH26SEL`"] pub struct CH26SEL_W<'a> { w: &'a mut W, } impl<'a> CH26SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `CH27SEL`"] pub type CH27SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH27SEL`"] pub struct CH27SEL_W<'a> { w: &'a mut W, } impl<'a> CH27SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12); self.w } } #[doc = "Reader of field `CH28SEL`"] pub type CH28SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH28SEL`"] pub struct CH28SEL_W<'a> { w: &'a mut W, } impl<'a> CH28SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16); self.w } } #[doc = "Reader of field `CH29SEL`"] pub type CH29SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH29SEL`"] pub struct CH29SEL_W<'a> { w: &'a mut W, } impl<'a> CH29SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 20)) | (((value as u32) & 0x0f) << 20); self.w } } #[doc = "Reader of field `CH30SEL`"] pub type CH30SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH30SEL`"] pub struct CH30SEL_W<'a> { w: &'a mut W, } impl<'a> CH30SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 24)) | (((value as u32) & 0x0f) << 24); self.w } } #[doc = "Reader of field `CH31SEL`"] pub type CH31SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CH31SEL`"] pub struct CH31SEL_W<'a> { w: &'a mut W, } impl<'a> CH31SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 28)) | (((value as u32) & 0x0f) << 28); self.w } } impl R { #[doc = "Bits 0:3 - uDMA Channel 24 Source Select"] #[inline(always)] pub fn ch24sel(&self) -> CH24SEL_R { CH24SEL_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - uDMA Channel 25 Source Select"] #[inline(always)] pub fn ch25sel(&self) -> CH25SEL_R { CH25SEL_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:11 - uDMA Channel 26 Source Select"] #[inline(always)] pub fn ch26sel(&self) -> CH26SEL_R { CH26SEL_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:15 - uDMA Channel 27 Source Select"] #[inline(always)] pub fn ch27sel(&self) -> CH27SEL_R { CH27SEL_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 16:19 - uDMA Channel 28 Source Select"] #[inline(always)] pub fn ch28sel(&self) -> CH28SEL_R { CH28SEL_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 20:23 - uDMA Channel 29 Source Select"] #[inline(always)] pub fn ch29sel(&self) -> CH29SEL_R { CH29SEL_R::new(((self.bits >> 20) & 0x0f) as u8) } #[doc = "Bits 24:27 - uDMA Channel 30 Source Select"] #[inline(always)] pub fn ch30sel(&self) -> CH30SEL_R { CH30SEL_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 28:31 - uDMA Channel 31 Source Select"] #[inline(always)] pub fn ch31sel(&self) -> CH31SEL_R { CH31SEL_R::new(((self.bits >> 28) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - uDMA Channel 24 Source Select"] #[inline(always)] pub fn ch24sel(&mut self) -> CH24SEL_W { CH24SEL_W { w: self } } #[doc = "Bits 4:7 - uDMA Channel 25 Source Select"] #[inline(always)] pub fn ch25sel(&mut self) -> CH25SEL_W { CH25SEL_W { w: self } } #[doc = "Bits 8:11 - uDMA Channel 26 Source Select"] #[inline(always)] pub fn ch26sel(&mut self) -> CH26SEL_W { CH26SEL_W { w: self } } #[doc = "Bits 12:15 - uDMA Channel 27 Source Select"] #[inline(always)] pub fn ch27sel(&mut self) -> CH27SEL_W { CH27SEL_W { w: self } } #[doc = "Bits 16:19 - uDMA Channel 28 Source Select"] #[inline(always)] pub fn ch28sel(&mut self) -> CH28SEL_W { CH28SEL_W { w: self } } #[doc = "Bits 20:23 - uDMA Channel 29 Source Select"] #[inline(always)] pub fn ch29sel(&mut self) -> CH29SEL_W { CH29SEL_W { w: self } } #[doc = "Bits 24:27 - uDMA Channel 30 Source Select"] #[inline(always)] pub fn ch30sel(&mut self) -> CH30SEL_W { CH30SEL_W { w: self } } #[doc = "Bits 28:31 - uDMA Channel 31 Source Select"] #[inline(always)] pub fn ch31sel(&mut self) -> CH31SEL_W { CH31SEL_W { w: self } } }
mod handle; mod table; // objects mod thread; mod process; mod code; mod mono_copy; mod event; mod channel; pub use self::handle::{Handle, HandleOffset}; pub use self::table::HandleTable; pub use nabi::HandleRights; pub use self::thread::ThreadRef; pub use self::process::ProcessRef; pub use self::code::CodeRef; pub use self::mono_copy::MonoCopyRef; pub use self::event::EventRef; pub use self::channel::{ChannelRef, Message};
pub fn set_cursor_visibility(_visible: bool) {} pub fn set_cursor_bounds(_top: i32, _left: i32, _bottom: i32, _right: i32) {} pub fn clear_cursor_bounds() { }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPrintManagerInterop(pub ::windows::core::IUnknown); impl IPrintManagerInterop { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetForWindow<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::HWND>, T: ::windows::core::Interface>(&self, appwindow: Param0) -> ::windows::core::Result<T> { let mut result__ = ::core::option::Option::None; (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), appwindow.into_param().abi(), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn ShowPrintUIForWindowAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::HWND>, T: ::windows::core::Interface>(&self, appwindow: Param0) -> ::windows::core::Result<T> { let mut result__ = ::core::option::Option::None; (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), appwindow.into_param().abi(), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__) } } unsafe impl ::windows::core::Interface for IPrintManagerInterop { type Vtable = IPrintManagerInterop_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc5435a42_8d43_4e7b_a68a_ef311e392087); } impl ::core::convert::From<IPrintManagerInterop> for ::windows::core::IUnknown { fn from(value: IPrintManagerInterop) -> Self { value.0 } } impl ::core::convert::From<&IPrintManagerInterop> for ::windows::core::IUnknown { fn from(value: &IPrintManagerInterop) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPrintManagerInterop { 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 IPrintManagerInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IPrintManagerInterop_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 = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appwindow: super::super::super::Foundation::HWND, riid: *const ::windows::core::GUID, printmanager: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appwindow: super::super::super::Foundation::HWND, riid: *const ::windows::core::GUID, asyncoperation: *mut *mut ::core::ffi::c_void) -> ::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 IPrintWorkflowConfigurationNative(pub ::windows::core::IUnknown); impl IPrintWorkflowConfigurationNative { #[cfg(feature = "Win32_Graphics_Printing")] pub unsafe fn PrinterQueue(&self) -> ::windows::core::Result<super::super::super::Graphics::Printing::IPrinterQueue> { let mut result__: <super::super::super::Graphics::Printing::IPrinterQueue 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::super::Graphics::Printing::IPrinterQueue>(result__) } #[cfg(feature = "Win32_Graphics_Printing")] pub unsafe fn DriverProperties(&self) -> ::windows::core::Result<super::super::super::Graphics::Printing::IPrinterPropertyBag> { let mut result__: <super::super::super::Graphics::Printing::IPrinterPropertyBag 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::super::Graphics::Printing::IPrinterPropertyBag>(result__) } #[cfg(feature = "Win32_Graphics_Printing")] pub unsafe fn UserProperties(&self) -> ::windows::core::Result<super::super::super::Graphics::Printing::IPrinterPropertyBag> { let mut result__: <super::super::super::Graphics::Printing::IPrinterPropertyBag as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Graphics::Printing::IPrinterPropertyBag>(result__) } } unsafe impl ::windows::core::Interface for IPrintWorkflowConfigurationNative { type Vtable = IPrintWorkflowConfigurationNative_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc056be0a_9ee2_450a_9823_964f0006f2bb); } impl ::core::convert::From<IPrintWorkflowConfigurationNative> for ::windows::core::IUnknown { fn from(value: IPrintWorkflowConfigurationNative) -> Self { value.0 } } impl ::core::convert::From<&IPrintWorkflowConfigurationNative> for ::windows::core::IUnknown { fn from(value: &IPrintWorkflowConfigurationNative) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPrintWorkflowConfigurationNative { 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 IPrintWorkflowConfigurationNative { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IPrintWorkflowConfigurationNative_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_Graphics_Printing")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Graphics_Printing"))] usize, #[cfg(feature = "Win32_Graphics_Printing")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Graphics_Printing"))] usize, #[cfg(feature = "Win32_Graphics_Printing")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Graphics_Printing"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPrintWorkflowObjectModelSourceFileContentNative(pub ::windows::core::IUnknown); impl IPrintWorkflowObjectModelSourceFileContentNative { pub unsafe fn StartXpsOMGeneration<'a, Param0: ::windows::core::IntoParam<'a, IPrintWorkflowXpsReceiver>>(&self, receiver: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), receiver.into_param().abi()).ok() } #[cfg(feature = "Win32_Storage_Xps")] pub unsafe fn ObjectFactory(&self) -> ::windows::core::Result<super::super::super::Storage::Xps::IXpsOMObjectFactory1> { let mut result__: <super::super::super::Storage::Xps::IXpsOMObjectFactory1 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::super::Storage::Xps::IXpsOMObjectFactory1>(result__) } } unsafe impl ::windows::core::Interface for IPrintWorkflowObjectModelSourceFileContentNative { type Vtable = IPrintWorkflowObjectModelSourceFileContentNative_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x68c9e477_993e_4052_8ac6_454eff58db9d); } impl ::core::convert::From<IPrintWorkflowObjectModelSourceFileContentNative> for ::windows::core::IUnknown { fn from(value: IPrintWorkflowObjectModelSourceFileContentNative) -> Self { value.0 } } impl ::core::convert::From<&IPrintWorkflowObjectModelSourceFileContentNative> for ::windows::core::IUnknown { fn from(value: &IPrintWorkflowObjectModelSourceFileContentNative) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPrintWorkflowObjectModelSourceFileContentNative { 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 IPrintWorkflowObjectModelSourceFileContentNative { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IPrintWorkflowObjectModelSourceFileContentNative_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, receiver: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Storage_Xps")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Storage_Xps"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPrintWorkflowXpsObjectModelTargetPackageNative(pub ::windows::core::IUnknown); impl IPrintWorkflowXpsObjectModelTargetPackageNative { #[cfg(feature = "Win32_Storage_Xps")] pub unsafe fn DocumentPackageTarget(&self) -> ::windows::core::Result<super::super::super::Storage::Xps::IXpsDocumentPackageTarget> { let mut result__: <super::super::super::Storage::Xps::IXpsDocumentPackageTarget 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::super::Storage::Xps::IXpsDocumentPackageTarget>(result__) } } unsafe impl ::windows::core::Interface for IPrintWorkflowXpsObjectModelTargetPackageNative { type Vtable = IPrintWorkflowXpsObjectModelTargetPackageNative_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7d96bc74_9b54_4ca1_ad3a_979c3d44ddac); } impl ::core::convert::From<IPrintWorkflowXpsObjectModelTargetPackageNative> for ::windows::core::IUnknown { fn from(value: IPrintWorkflowXpsObjectModelTargetPackageNative) -> Self { value.0 } } impl ::core::convert::From<&IPrintWorkflowXpsObjectModelTargetPackageNative> for ::windows::core::IUnknown { fn from(value: &IPrintWorkflowXpsObjectModelTargetPackageNative) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPrintWorkflowXpsObjectModelTargetPackageNative { 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 IPrintWorkflowXpsObjectModelTargetPackageNative { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IPrintWorkflowXpsObjectModelTargetPackageNative_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_Storage_Xps")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Storage_Xps"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPrintWorkflowXpsReceiver(pub ::windows::core::IUnknown); impl IPrintWorkflowXpsReceiver { #[cfg(feature = "Win32_System_Com")] pub unsafe fn SetDocumentSequencePrintTicket<'a, Param0: ::windows::core::IntoParam<'a, super::super::Com::IStream>>(&self, documentsequenceprintticket: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), documentsequenceprintticket.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetDocumentSequenceUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>>(&self, documentsequenceuri: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), documentsequenceuri.into_param().abi()).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn AddDocumentData<'a, Param1: ::windows::core::IntoParam<'a, super::super::Com::IStream>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>>(&self, documentid: u32, documentprintticket: Param1, documenturi: Param2) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(documentid), documentprintticket.into_param().abi(), documenturi.into_param().abi()).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_Xps"))] pub unsafe fn AddPage<'a, Param2: ::windows::core::IntoParam<'a, super::super::super::Storage::Xps::IXpsOMPageReference>, Param3: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>>(&self, documentid: u32, pageid: u32, pagereference: Param2, pageuri: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(documentid), ::core::mem::transmute(pageid), pagereference.into_param().abi(), pageuri.into_param().abi()).ok() } pub unsafe fn Close(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self)).ok() } } unsafe impl ::windows::core::Interface for IPrintWorkflowXpsReceiver { type Vtable = IPrintWorkflowXpsReceiver_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x04097374_77b8_47f6_8167_aae29d4cf84b); } impl ::core::convert::From<IPrintWorkflowXpsReceiver> for ::windows::core::IUnknown { fn from(value: IPrintWorkflowXpsReceiver) -> Self { value.0 } } impl ::core::convert::From<&IPrintWorkflowXpsReceiver> for ::windows::core::IUnknown { fn from(value: &IPrintWorkflowXpsReceiver) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPrintWorkflowXpsReceiver { 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 IPrintWorkflowXpsReceiver { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IPrintWorkflowXpsReceiver_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_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, documentsequenceprintticket: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_System_Com"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, documentsequenceuri: super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, documentid: u32, documentprintticket: ::windows::core::RawPtr, documenturi: super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_Xps"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, documentid: u32, pageid: u32, pagereference: ::windows::core::RawPtr, pageuri: super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_Xps")))] usize, 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 IPrintWorkflowXpsReceiver2(pub ::windows::core::IUnknown); impl IPrintWorkflowXpsReceiver2 { #[cfg(feature = "Win32_System_Com")] pub unsafe fn SetDocumentSequencePrintTicket<'a, Param0: ::windows::core::IntoParam<'a, super::super::Com::IStream>>(&self, documentsequenceprintticket: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), documentsequenceprintticket.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetDocumentSequenceUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>>(&self, documentsequenceuri: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), documentsequenceuri.into_param().abi()).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn AddDocumentData<'a, Param1: ::windows::core::IntoParam<'a, super::super::Com::IStream>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>>(&self, documentid: u32, documentprintticket: Param1, documenturi: Param2) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(documentid), documentprintticket.into_param().abi(), documenturi.into_param().abi()).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_Xps"))] pub unsafe fn AddPage<'a, Param2: ::windows::core::IntoParam<'a, super::super::super::Storage::Xps::IXpsOMPageReference>, Param3: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>>(&self, documentid: u32, pageid: u32, pagereference: Param2, pageuri: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(documentid), ::core::mem::transmute(pageid), pagereference.into_param().abi(), pageuri.into_param().abi()).ok() } pub unsafe fn Close(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Failed(&self, xpserror: ::windows::core::HRESULT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(xpserror)).ok() } } unsafe impl ::windows::core::Interface for IPrintWorkflowXpsReceiver2 { type Vtable = IPrintWorkflowXpsReceiver2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x023bcc0c_dfab_4a61_b074_490c6995580d); } impl ::core::convert::From<IPrintWorkflowXpsReceiver2> for ::windows::core::IUnknown { fn from(value: IPrintWorkflowXpsReceiver2) -> Self { value.0 } } impl ::core::convert::From<&IPrintWorkflowXpsReceiver2> for ::windows::core::IUnknown { fn from(value: &IPrintWorkflowXpsReceiver2) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPrintWorkflowXpsReceiver2 { 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 IPrintWorkflowXpsReceiver2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IPrintWorkflowXpsReceiver2> for IPrintWorkflowXpsReceiver { fn from(value: IPrintWorkflowXpsReceiver2) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IPrintWorkflowXpsReceiver2> for IPrintWorkflowXpsReceiver { fn from(value: &IPrintWorkflowXpsReceiver2) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IPrintWorkflowXpsReceiver> for IPrintWorkflowXpsReceiver2 { fn into_param(self) -> ::windows::core::Param<'a, IPrintWorkflowXpsReceiver> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IPrintWorkflowXpsReceiver> for &IPrintWorkflowXpsReceiver2 { fn into_param(self) -> ::windows::core::Param<'a, IPrintWorkflowXpsReceiver> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IPrintWorkflowXpsReceiver2_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_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, documentsequenceprintticket: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_System_Com"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, documentsequenceuri: super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, documentid: u32, documentprintticket: ::windows::core::RawPtr, documenturi: super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_Xps"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, documentid: u32, pageid: u32, pagereference: ::windows::core::RawPtr, pageuri: super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Storage_Xps")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xpserror: ::windows::core::HRESULT) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPrinting3DManagerInterop(pub ::windows::core::IUnknown); impl IPrinting3DManagerInterop { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetForWindow<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::HWND>, T: ::windows::core::Interface>(&self, appwindow: Param0) -> ::windows::core::Result<T> { let mut result__ = ::core::option::Option::None; (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), appwindow.into_param().abi(), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn ShowPrintUIForWindowAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::HWND>, T: ::windows::core::Interface>(&self, appwindow: Param0) -> ::windows::core::Result<T> { let mut result__ = ::core::option::Option::None; (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), appwindow.into_param().abi(), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__) } } unsafe impl ::windows::core::Interface for IPrinting3DManagerInterop { type Vtable = IPrinting3DManagerInterop_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9ca31010_1484_4587_b26b_dddf9f9caecd); } impl ::core::convert::From<IPrinting3DManagerInterop> for ::windows::core::IUnknown { fn from(value: IPrinting3DManagerInterop) -> Self { value.0 } } impl ::core::convert::From<&IPrinting3DManagerInterop> for ::windows::core::IUnknown { fn from(value: &IPrinting3DManagerInterop) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPrinting3DManagerInterop { 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 IPrinting3DManagerInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IPrinting3DManagerInterop_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 = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appwindow: super::super::super::Foundation::HWND, riid: *const ::windows::core::GUID, printmanager: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appwindow: super::super::super::Foundation::HWND, riid: *const ::windows::core::GUID, asyncoperation: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, );
use nalgebra::Vector4; use crate::{LumpData, LumpType, PrimitiveRead}; use std::io::{Read, Result as IOResult}; bitflags! { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)] pub struct SurfaceFlags: i32 { const LIGHT = 0x1; const SKY2D = 0x2; const SKY = 0x4; const WARP = 0x8; const TRANS = 0x10; const NOPORTAL = 0x20; const TRIGGER = 0x40; const NODRAW = 0x80; const HINT = 0x100; const SKIP = 0x200; const NOLIGHT = 0x400; const BUMPLIGHT = 0x800; const NOSHADOWS = 0x1000; const NODECALS = 0x2000; const NOCHOP = 0x4000; const HITBOX = 0x8000; } } pub struct TextureInfo { pub texture_vecs_s: Vector4<f32>, pub texture_vecs_t: Vector4<f32>, pub lightmap_vecs_s: Vector4<f32>, pub lightmap_vecs_t: Vector4<f32>, pub flags: SurfaceFlags, pub texture_data: i32 } impl LumpData for TextureInfo { fn lump_type() -> LumpType { LumpType::TextureInfo } fn lump_type_hdr() -> Option<LumpType> { None } fn element_size(_version: i32) -> usize { 72 } fn read(reader: &mut dyn Read, _version: i32) -> IOResult<Self> { let texture_vecs_s = Vector4::new(reader.read_f32()?, reader.read_f32()?, reader.read_f32()?, reader.read_f32()?); let texture_vecs_t = Vector4::new(reader.read_f32()?, reader.read_f32()?, reader.read_f32()?, reader.read_f32()?); let lightmap_vecs_s = Vector4::new(reader.read_f32()?, reader.read_f32()?, reader.read_f32()?, reader.read_f32()?); let lightmap_vecs_t = Vector4::new(reader.read_f32()?, reader.read_f32()?, reader.read_f32()?, reader.read_f32()?); let flags_bits = reader.read_i32()?; let flags = SurfaceFlags::from_bits(flags_bits).unwrap(); let texture_data = reader.read_i32()?; Ok(Self { texture_vecs_s, texture_vecs_t, lightmap_vecs_s, lightmap_vecs_t, flags, texture_data }) } }
impl Solution { pub fn is_anagram(s: String, t: String) -> bool { if s.len() != t.len() { return false; } let mut db = std::collections::HashMap::<char, i32>::with_capacity(26); for (x, y) in s.chars().zip(t.chars()) { *db.entry(x).or_default() += 1; *db.entry(y).or_default() -= 1; } db.into_values().all(|count| count == 0) } }
//! Стены use crate::sig::rab_e::openings::*; use crate::sig::rab_e::*; use crate::sig::HasWrite; use nom::{ bytes::complete::take, multi::count, number::complete::{le_f32, le_i16, le_u16, le_u32, le_u8}, IResult, }; use std::fmt; #[derive(Debug)] pub struct Wall { p1: Point, //1-я точка стены p2: Point, //2-я точка стены agt: u8, //Генерировать АЖТ. 0=нет, 128=да flag: u8, //Битовый флаг опирания + bF b: f32, //Толщина стены, см force_from: i16, //Номер первой вертикальной нагрузки, -1=нет force_to: i16, //Номер последней вертикальной нагрузки, -1=нет force_num: u16, //Количество вертикальных нагрузок diagram_from: i16, //Номер первого фрагмента схемы вертикальных нагрузок на стену, -1=нет diagram_to: i16, //Номер последнего фрагмента схемы вертикальных нагрузок на стену, -1=нет diagram_num: u16, //Количество фрагментов схемы вертикальных нагрузок на стену //4b WS found_from: i16, //Фундамент под стену 1 значение, -1=нет found_to: i16, //Фундамент под стену 2 значение, -2=нет op_num: u16, //Количество отверстий в стене area: f32, //Площадь стены, (b*h) mu: f32, //Процент армирования стены //2b WS r_ver_3: u16, //Зависит от расчета. 1=без, 0=расчет, МКЭ r_ver_4: u32, //Зависит от расчета. 1=без, 0=расчет, МКЭ r_ver_5: u16, //Зависит от расчета. 1=без, 0=расчет, МКЭ r_ver_6: u16, //Зависит от расчета. 1=без, 0=расчет, МКЭ cons_1: u32, //Всегда 1 diagram_fwall_from: u16, //Номер первого фрагмента схемы напряжений на фундамент под стеной. Начало с 1 для 1-го этажа, с 0 выше diagram_fwall_to: u16, //Номер последнего фрагмента схемы напряжений на фундамент под стеной diagram_fwall_num: u16, //Количество фрагментов схемы напряжений на фундамент под стеной r_ver_9: u16, //Зависит от расчета. 1=без, 0=расчет, МКЭ diagram_horizontal_from: u16, //Первый участок схемы горизонтальных нагрузок diagram_horizontal_to: u16, //Последний участок схемы горизонтальных нагрузок diagram_horizontal_num: u16, //Количество участков схемы горизонтальных нагрузок k: f32, //Коэффициент жескости на действие горизонтальных нагрузок cons_3: u32, //Всегда 1 //1b WS reinforcement_wall: f32, //Армирование стены, кг reinforcement_fwall: f32, //Армирование фундамента под стеной, кг //1b WS r_ver_12: u16, //Зависит от расчета. 1=без, 0=расчет, МКЭ r_ver_13: u16, //Зависит от расчета. 1=без, 0=расчет, МКЭ flag_hinge: u8, //Шарнир с плитами. 0=нет, 1=низ, 2=верх, 3=низ и верх dz1: f32, //Переменная dz1 mat: u16, //Номер материала стены //9b WS op: Vec<Opening>, //Вектор отверстий ws: Vec<u8>, //17b } impl HasWrite for Wall { fn write(&self) -> Vec<u8> { let mut out: Vec<u8> = vec![]; out.extend(&self.p1.write()); out.extend(&self.p2.write()); out.extend(&self.agt.to_le_bytes()); out.extend(&self.flag.to_le_bytes()); out.extend(&self.b.to_le_bytes()); out.extend(&self.force_from.to_le_bytes()); out.extend(&self.force_to.to_le_bytes()); out.extend(&self.force_num.to_le_bytes()); out.extend(&self.diagram_from.to_le_bytes()); out.extend(&self.diagram_to.to_le_bytes()); out.extend(&self.diagram_num.to_le_bytes()); out.extend(&self.ws[0..4]); out.extend(&self.found_from.to_le_bytes()); out.extend(&self.found_to.to_le_bytes()); out.extend(&self.op_num.to_le_bytes()); out.extend(&self.area.to_le_bytes()); out.extend(&self.mu.to_le_bytes()); out.extend(&self.ws[4..6]); out.extend(&self.r_ver_3.to_le_bytes()); out.extend(&self.r_ver_4.to_le_bytes()); out.extend(&self.r_ver_5.to_le_bytes()); out.extend(&self.r_ver_6.to_le_bytes()); out.extend(&self.cons_1.to_le_bytes()); out.extend(&self.diagram_fwall_from.to_le_bytes()); out.extend(&self.diagram_fwall_to.to_le_bytes()); out.extend(&self.diagram_fwall_num.to_le_bytes()); out.extend(&self.r_ver_9.to_le_bytes()); out.extend(&self.diagram_horizontal_from.to_le_bytes()); out.extend(&self.diagram_horizontal_to.to_le_bytes()); out.extend(&self.diagram_horizontal_num.to_le_bytes()); out.extend(&self.k.to_le_bytes()); out.extend(&self.cons_3.to_le_bytes()); out.extend(&self.ws[6..7]); out.extend(&self.reinforcement_wall.to_le_bytes()); out.extend(&self.reinforcement_fwall.to_le_bytes()); out.extend(&self.ws[7..8]); out.extend(&self.r_ver_12.to_le_bytes()); out.extend(&self.r_ver_13.to_le_bytes()); out.extend(&self.flag_hinge.to_le_bytes()); out.extend(&self.dz1.to_le_bytes()); out.extend(&self.mat.to_le_bytes()); out.extend(&self.ws[8..17]); for i in &self.op { out.extend(&i.write()); } out } fn name(&self) -> &str { "" } } impl fmt::Display for Wall { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "p1 |{}|, p2 |{}|, agt: {}, flag: {}, b: {}, k: {}, openings: {}", &self.p1, &self.p2, &self.agt, &self.flag, &self.b, &self.k, &self.op_num )?; let vec = &self.op; for (count, v) in vec.iter().enumerate() { write!(f, "\n opening №{}: {}", count, v)?; } write!(f, "") } } impl Wall { pub fn get_start_point(&self) -> &Point { &self.p1 } pub fn get_end_point(&self) -> &Point { &self.p2 } } pub fn read_wall(i: &[u8]) -> IResult<&[u8], Wall> { let (i, p1) = read_point(i)?; let (i, p2) = read_point(i)?; let (i, agt) = le_u8(i)?; let (i, flag) = le_u8(i)?; let (i, b) = le_f32(i)?; let (i, force_from) = le_i16(i)?; let (i, force_to) = le_i16(i)?; let (i, force_num) = le_u16(i)?; let (i, diagram_from) = le_i16(i)?; let (i, diagram_to) = le_i16(i)?; let (i, diagram_num) = le_u16(i)?; let (i, ws2) = take(4u8)(i)?; //4b WS let (i, found_from) = le_i16(i)?; let (i, found_to) = le_i16(i)?; let (i, op_num) = le_u16(i)?; let (i, area) = le_f32(i)?; let (i, mu) = le_f32(i)?; let (i, ws3) = take(2u8)(i)?; //2b WS let (i, r_ver_3) = le_u16(i)?; let (i, r_ver_4) = le_u32(i)?; let (i, r_ver_5) = le_u16(i)?; let (i, r_ver_6) = le_u16(i)?; let (i, cons_1) = le_u32(i)?; let (i, diagram_fwall_from) = le_u16(i)?; let (i, diagram_fwall_to) = le_u16(i)?; let (i, diagram_fwall_num) = le_u16(i)?; let (i, r_ver_9) = le_u16(i)?; let (i, diagram_horizontal_from) = le_u16(i)?; let (i, diagram_horizontal_to) = le_u16(i)?; let (i, diagram_horizontal_num) = le_u16(i)?; let (i, k) = le_f32(i)?; let (i, cons_3) = le_u32(i)?; let (i, ws4) = take(1u8)(i)?; //1b WS let (i, reinforcement_wall) = le_f32(i)?; let (i, reinforcement_fwall) = le_f32(i)?; let (i, ws5) = take(1u8)(i)?; //1b WS let (i, r_ver_12) = le_u16(i)?; let (i, r_ver_13) = le_u16(i)?; let (i, flag_hinge) = le_u8(i)?; let (i, dz1) = le_f32(i)?; let (i, mat) = le_u16(i)?; let (i, ws6) = take(9u8)(i)?; //9b WS let (i, op) = count(read_op, op_num as usize)(i)?; let mut ws = ws2.to_vec(); ws.extend_from_slice(ws3); ws.extend_from_slice(ws4); ws.extend_from_slice(ws5); ws.extend_from_slice(ws6); Ok(( i, Wall { p1, p2, agt, flag, b, force_from, force_to, force_num, diagram_from, diagram_to, diagram_num, found_from, found_to, op_num, area, mu, r_ver_3, r_ver_4, r_ver_5, r_ver_6, cons_1, diagram_fwall_from, diagram_fwall_to, diagram_fwall_num, r_ver_9, diagram_horizontal_from, diagram_horizontal_to, diagram_horizontal_num, k, cons_3, reinforcement_wall, reinforcement_fwall, r_ver_12, r_ver_13, flag_hinge, dz1, mat, op, ws, }, )) } #[cfg(test)] fn test_wall(path_str: &str) { use crate::tests::rab_e_sig_test::read_test_sig; let original_in = read_test_sig(path_str); let (_, wall) = read_wall(&original_in).expect("couldn't read_wall"); assert_eq!(original_in, wall.write()); } #[test] fn wall_test() { test_wall("test_sig/walls/wall.test"); } #[test] fn wall_2mat_test() { test_wall("test_sig/walls/wall_2mat.test"); } #[test] fn wall_agt_test() { test_wall("test_sig/walls/wall_agt.test"); } #[test] fn wall_down_test() { test_wall("test_sig/walls/wall_down.test"); } #[test] fn wall_dz_test() { test_wall("test_sig/walls/wall_dz.test"); } #[test] fn wall_found_test() { test_wall("test_sig/walls/wall_found.test"); } #[test] fn wall_found_f_test() { test_wall("test_sig/walls/wall_found_f.test"); } #[test] fn wall_found_f_slab_test() { test_wall("test_sig/walls/wall_found_f_slab.test"); } #[test] fn wall_found_slab_test() { test_wall("test_sig/walls/wall_found_slab.test"); } #[test] fn wall_k_test() { test_wall("test_sig/walls/wall_k.test"); } #[test] fn wall_nf_test() { test_wall("test_sig/walls/wall_nf.test"); } #[test] fn wall_nf_found_f_test() { test_wall("test_sig/walls/wall_nf_found_f.test"); } #[test] fn wall_nf_found_f_slab_test() { test_wall("test_sig/walls/wall_nf_found_f_slab.test"); } #[test] fn wall_nf_slab_test() { test_wall("test_sig/walls/wall_nf_slab.test"); } #[test] fn wall_opening_1_test() { test_wall("test_sig/walls/wall_opening_1.test"); } #[test] fn wall_opening_2_test() { test_wall("test_sig/walls/wall_opening_2.test"); } #[test] fn wall_opening_3_test() { test_wall("test_sig/walls/wall_opening_3.test"); } #[test] fn wall_opening_4_test() { test_wall("test_sig/walls/wall_opening_4.test"); } #[test] fn wall_slab_test() { test_wall("test_sig/walls/wall_slab.test"); } #[test] fn wall_up_test() { test_wall("test_sig/walls/wall_up.test"); } #[test] fn wall_up_down_test() { test_wall("test_sig/walls/wall_up_down.test"); } #[test] fn p_wall_test() { test_wall("test_sig/walls/P_wall.test"); } #[test] fn r_wall_found_f_test() { test_wall("test_sig/walls/R_wall_found_f.test"); } #[test] fn p_wall_nf_test() { test_wall("test_sig/walls/P_wall_nf.test"); } #[test] fn p_wall_opening_1_test() { test_wall("test_sig/walls/P_wall_opening_1.test"); } #[test] fn s_wall_test() { test_wall("test_sig/walls/S_wall.test"); } #[test] fn s_wall_full_value_test() { use crate::tests::rab_e_sig_test::read_test_sig; let original_in = read_test_sig("test_sig/walls/S_wall.test"); let (_, wall) = read_wall(&original_in).expect("couldn't read_wall"); let c_wall = Wall { p1: Point { x: 0.2f32, y: 0.3f32, }, p2: Point { x: 1.7f32, y: 2.3f32, }, agt: 0u8, flag: 8u8, b: 22f32, force_from: 2i16, force_to: 2i16, force_num: 1u16, diagram_from: 2i16, diagram_to: 2i16, diagram_num: 1u16, found_from: 10i16, found_to: 11i16, op_num: 1u16, area: 7.5f32, mu: 0.001f32, r_ver_3: 0u16, r_ver_4: 0u32, r_ver_5: 0u16, r_ver_6: 0u16, cons_1: 1u32, diagram_fwall_from: 17u16, diagram_fwall_to: 21u16, diagram_fwall_num: 5u16, r_ver_9: 0u16, diagram_horizontal_from: 0u16, diagram_horizontal_to: 0u16, diagram_horizontal_num: 0u16, k: 1f32, cons_3: 1u32, reinforcement_wall: 16.2f32, reinforcement_fwall: 19.89f32, r_ver_12: 0u16, r_ver_13: 0u16, flag_hinge: 0u8, dz1: 0f32, mat: 1u16, ws: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17u8], op: vec![Opening { num_points: 5, x_vec: vec![1.12, 1.12, 4.73, 4.73, 1.12f32], y_vec: vec![0.16, 1.73, 1.73, 0.16, 0.16f32], }], }; assert_eq!(wall.write(), c_wall.write()) }
// 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::net::SocketAddr; use std::sync::Arc; use std::time::Duration; use common_catalog::table::Table; use common_catalog::table_context::TableContext; use common_exception::Result; use common_expression::types::number::Int64Type; use common_expression::types::number::UInt32Type; use common_expression::types::number::UInt64Type; use common_expression::types::NumberDataType; use common_expression::types::StringType; use common_expression::utils::FromData; use common_expression::DataBlock; use common_expression::FromOptData; use common_expression::TableDataType; use common_expression::TableField; use common_expression::TableSchemaRefExt; use common_meta_app::schema::TableIdent; use common_meta_app::schema::TableInfo; use common_meta_app::schema::TableMeta; use crate::SyncOneBlockSystemTable; use crate::SyncSystemTable; pub struct ProcessesTable { table_info: TableInfo, } #[async_trait::async_trait] impl SyncSystemTable for ProcessesTable { const NAME: &'static str = "system.processes"; fn get_table_info(&self) -> &TableInfo { &self.table_info } fn get_full_data(&self, ctx: Arc<dyn TableContext>) -> Result<DataBlock> { let processes_info = ctx.get_processes_info(); let mut processes_id = Vec::with_capacity(processes_info.len()); let mut processes_type = Vec::with_capacity(processes_info.len()); let mut processes_host = Vec::with_capacity(processes_info.len()); let mut processes_user = Vec::with_capacity(processes_info.len()); let mut processes_state = Vec::with_capacity(processes_info.len()); let mut processes_database = Vec::with_capacity(processes_info.len()); let mut processes_extra_info = Vec::with_capacity(processes_info.len()); let mut processes_memory_usage = Vec::with_capacity(processes_info.len()); let mut processes_data_read_bytes = Vec::with_capacity(processes_info.len()); let mut processes_data_write_bytes = Vec::with_capacity(processes_info.len()); let mut processes_scan_progress_read_rows = Vec::with_capacity(processes_info.len()); let mut processes_scan_progress_read_bytes = Vec::with_capacity(processes_info.len()); let mut processes_mysql_connection_id = Vec::with_capacity(processes_info.len()); let mut processes_time = Vec::with_capacity(processes_info.len()); let mut processes_status = Vec::with_capacity(processes_info.len()); for process_info in &processes_info { let data_metrics = &process_info.data_metrics; let scan_progress = process_info.scan_progress_value.clone().unwrap_or_default(); let time = process_info .created_time .elapsed() .unwrap_or(Duration::from_secs(0)) .as_secs(); processes_id.push(process_info.id.clone().into_bytes()); processes_type.push(process_info.typ.clone().into_bytes()); processes_state.push(process_info.state.clone().into_bytes()); processes_database.push(process_info.database.clone().into_bytes()); processes_host.push(ProcessesTable::process_host(&process_info.client_address)); processes_user.push( ProcessesTable::process_option_value(process_info.user.clone()) .name .into_bytes(), ); processes_extra_info.push( ProcessesTable::process_option_value(process_info.session_extra_info.clone()) .into_bytes(), ); processes_memory_usage.push(process_info.memory_usage); processes_scan_progress_read_rows.push(scan_progress.rows as u64); processes_scan_progress_read_bytes.push(scan_progress.bytes as u64); processes_mysql_connection_id.push(process_info.mysql_connection_id); processes_time.push(time); if let Some(data_metrics) = data_metrics { processes_data_read_bytes.push(data_metrics.get_read_bytes() as u64); processes_data_write_bytes.push(data_metrics.get_write_bytes() as u64); } else { processes_data_read_bytes.push(0); processes_data_write_bytes.push(0); } // Status info. processes_status.push( process_info .status_info .clone() .unwrap_or("".to_owned()) .into_bytes(), ); } Ok(DataBlock::new_from_columns(vec![ StringType::from_data(processes_id), StringType::from_data(processes_type), StringType::from_opt_data(processes_host), StringType::from_data(processes_user), StringType::from_data(processes_state), StringType::from_data(processes_database), StringType::from_data(processes_extra_info), Int64Type::from_data(processes_memory_usage), UInt64Type::from_data(processes_data_read_bytes), UInt64Type::from_data(processes_data_write_bytes), UInt64Type::from_data(processes_scan_progress_read_rows), UInt64Type::from_data(processes_scan_progress_read_bytes), UInt32Type::from_opt_data(processes_mysql_connection_id), UInt64Type::from_data(processes_time), StringType::from_data(processes_status), ])) } } impl ProcessesTable { pub fn create(table_id: u64) -> Arc<dyn Table> { let schema = TableSchemaRefExt::create(vec![ TableField::new("id", TableDataType::String), TableField::new("type", TableDataType::String), TableField::new( "host", TableDataType::Nullable(Box::new(TableDataType::String)), ), TableField::new("user", TableDataType::String), TableField::new("command", TableDataType::String), TableField::new("database", TableDataType::String), TableField::new("extra_info", TableDataType::String), TableField::new("memory_usage", TableDataType::Number(NumberDataType::Int64)), TableField::new( "data_read_bytes", TableDataType::Number(NumberDataType::UInt64), ), TableField::new( "data_write_bytes", TableDataType::Number(NumberDataType::UInt64), ), TableField::new( "scan_progress_read_rows", TableDataType::Number(NumberDataType::UInt64), ), TableField::new( "scan_progress_read_bytes", TableDataType::Number(NumberDataType::UInt64), ), TableField::new( "mysql_connection_id", TableDataType::Nullable(Box::new(TableDataType::Number(NumberDataType::UInt32))), ), TableField::new("time", TableDataType::Number(NumberDataType::UInt64)), TableField::new("status", TableDataType::String), ]); let table_info = TableInfo { desc: "'system'.'processes'".to_string(), name: "processes".to_string(), ident: TableIdent::new(table_id, 0), meta: TableMeta { schema, engine: "SystemProcesses".to_string(), ..Default::default() }, ..Default::default() }; SyncOneBlockSystemTable::create(ProcessesTable { table_info }) } fn process_host(client_address: &Option<SocketAddr>) -> Option<Vec<u8>> { client_address.as_ref().map(|s| s.to_string().into_bytes()) } fn process_option_value<T>(opt: Option<T>) -> T where T: Default { opt.unwrap_or_default() } }
#[cfg(all(feature = "handlebars", feature = "rustc_version"))] extern crate rustc_version; #[cfg(feature = "handlebars")] extern crate handlebars; #[cfg(feature = "reqwest")] extern crate reqwest; #[macro_use] extern crate serde_derive; #[allow(unused_extern_crates)] extern crate serde; #[macro_use] extern crate quick_error; extern crate toml; extern crate tar; extern crate libflate; #[cfg(test)] extern crate tempdir; use std::env::var_os; use std::ffi::{OsStr, OsString}; mod depot; mod recipients; mod manifest; #[cfg(feature = "handlebars")] mod template; pub use recipients::{Recipients, RecipientsError}; pub use manifest::{Manifest, Packages, ManifestCreationError, ManifestInspectionError}; pub use depot::{Depot, DepotError}; quick_error! { #[derive(Debug)] pub enum Error { RecipientsError(err: RecipientsError) { from() description("recipients error") display("failed to find recipients: {}", err) cause(err) } ManifestCreationError(err: ManifestCreationError) { from() description("manifest creation error") display("failed to create manifest: {}", err) cause(err) } ManifestInspectionError(err: ManifestInspectionError) { from() description("manifest load error") display("failed to inspect manifest: {}", err) cause(err) } DepotError(err: DepotError) { from() description("depot error") display("failed to deliver packages: {}", err) cause(err) } } } fn var_os_or<K: AsRef<OsStr>, E, F: FnOnce(K) -> E>(key: K, f: F) -> Result<OsString, E> { var_os(key.as_ref()).ok_or_else(|| f(key)) } pub fn simply_deliver() -> Result<(), Error> { let depot = Depot::new(); let manifest = Manifest::produce()?; let recipients = Recipients::new()?; let packages = manifest.inspect()?; depot.deliver(&recipients, packages)?; Ok(()) }
use crate::FileHandle; use std::path::Path; use std::path::PathBuf; #[cfg(feature = "parent")] use raw_window_handle::{HasRawWindowHandle, RawWindowHandle}; pub(crate) struct Filter { pub name: String, pub extensions: Vec<String>, } /// ## Synchronous File Dialog /// #### Supported Platforms: /// - Linux /// - Windows /// - Mac #[derive(Default)] pub struct FileDialog { pub(crate) filters: Vec<Filter>, pub(crate) starting_directory: Option<PathBuf>, pub(crate) file_name: Option<String>, #[cfg(feature = "parent")] pub(crate) parent: Option<RawWindowHandle>, } // Oh god, I don't like sending RawWindowHandle between threads but here we go anyways... // fingers crossed unsafe impl Send for FileDialog {} impl FileDialog { /// New file dialog builder pub fn new() -> Self { Default::default() } /// Add file extension filter. /// /// Takes in the name of the filter, and list of extensions /// /// #### Name of the filter will be displayed on supported platforms /// - Windows /// - Linux /// /// On platforms that don't support filter names, all filters will be merged into one filter pub fn add_filter(mut self, name: &str, extensions: &[&str]) -> Self { self.filters.push(Filter { name: name.into(), extensions: extensions.iter().map(|e| e.to_string()).collect(), }); self } /// Set starting directory of the dialog. /// #### Supported Platforms: /// - Linux /// - Windows /// - Mac pub fn set_directory<P: AsRef<Path>>(mut self, path: P) -> Self { self.starting_directory = Some(path.as_ref().into()); self } /// Set starting file name of the dialog. /// #### Supported Platforms: /// - Windows /// - Linux /// - Mac pub fn set_file_name(mut self, file_name: &str) -> Self { self.file_name = Some(file_name.into()); self } #[cfg(feature = "parent")] fn set_parent<W: HasRawWindowHandle>(mut self, parent: &W) -> Self { self.parent = Some(parent.raw_window_handle()); self } } use crate::backend::{FilePickerDialogImpl, FileSaveDialogImpl, FolderPickerDialogImpl}; #[cfg(not(target_arch = "wasm32"))] impl FileDialog { /// Pick one file pub fn pick_file(self) -> Option<PathBuf> { FilePickerDialogImpl::pick_file(self) } /// Pick multiple files pub fn pick_files(self) -> Option<Vec<PathBuf>> { FilePickerDialogImpl::pick_files(self) } /// Pick one folder pub fn pick_folder(self) -> Option<PathBuf> { FolderPickerDialogImpl::pick_folder(self) } /// Opens save file dialog /// /// #### Platform specific notes regarding save dialog filters: /// - On MacOs /// - If filter is set, all files will be grayed out (no matter the extension sadly) /// - If user does not type an extension MacOs will append first available extension from filters list /// - If user types in filename with extension MacOs will check if it exists in filters list, if not it will display appropriate message /// - On GTK /// - It only filters which already existing files get shown to the user /// - It does not append extensions automatically /// - It does not prevent users from adding any unsupported extension /// - On Win: /// - If no extension was provided it will just add currently selected one /// - If selected extension was typed in by the user it will just return /// - If unselected extension was provided it will append selected one at the end, example: `test.png.txt` pub fn save_file(self) -> Option<PathBuf> { FileSaveDialogImpl::save_file(self) } } /// ## Asynchronous File Dialog /// #### Supported Platforms: /// - Linux /// - Windows /// - Mac /// - WASM32 #[derive(Default)] pub struct AsyncFileDialog { file_dialog: FileDialog, } impl AsyncFileDialog { /// New file dialog builder pub fn new() -> Self { Default::default() } /// Add file extension filter. /// /// Takes in the name of the filter, and list of extensions /// /// #### Name of the filter will be displayed on supported platforms /// - Windows /// - Linux /// /// On platforms that don't support filter names, all filters will be merged into one filter pub fn add_filter(mut self, name: &str, extensions: &[&str]) -> Self { self.file_dialog = self.file_dialog.add_filter(name, extensions); self } /// Set starting directory of the dialog. /// #### Supported Platforms: /// - Linux /// - Windows /// - Mac pub fn set_directory<P: AsRef<Path>>(mut self, path: P) -> Self { self.file_dialog = self.file_dialog.set_directory(path); self } /// Set starting file name of the dialog. /// #### Supported Platforms: /// - Windows /// - Linux /// - Mac pub fn set_file_name(mut self, file_name: &str) -> Self { self.file_dialog = self.file_dialog.set_file_name(file_name); self } #[cfg(feature = "parent")] /// Set parent windows explicitly (optional) /// Suported in: `macos` pub fn set_parent<W: HasRawWindowHandle>(mut self, parent: &W) -> Self { self.file_dialog = self.file_dialog.set_parent(parent); self } } use crate::backend::{ AsyncFilePickerDialogImpl, AsyncFileSaveDialogImpl, AsyncFolderPickerDialogImpl, }; use std::future::Future; impl AsyncFileDialog { /// Pick one file pub fn pick_file(self) -> impl Future<Output = Option<FileHandle>> { AsyncFilePickerDialogImpl::pick_file_async(self.file_dialog) } /// Pick multiple files pub fn pick_files(self) -> impl Future<Output = Option<Vec<FileHandle>>> { AsyncFilePickerDialogImpl::pick_files_async(self.file_dialog) } #[cfg(not(target_arch = "wasm32"))] /// Pick one folder /// /// Does not exist in `WASM32` pub fn pick_folder(self) -> impl Future<Output = Option<FileHandle>> { AsyncFolderPickerDialogImpl::pick_folder_async(self.file_dialog) } #[cfg(not(target_arch = "wasm32"))] /// Opens save file dialog /// /// Does not exist in `WASM32` /// /// /// #### Platform specific notes regarding save dialog filters: /// - On MacOs /// - If filter is set, all files will be grayed out (no matter the extension sadly) /// - If user does not type an extension MacOs will append first available extension from filters list /// - If user types in filename with extension MacOs will check if it exists in filters list, if not it will display appropriate message /// - On GTK /// - It only filters which already existing files get shown to the user /// - It does not append extensions automatically /// - It does not prevent users from adding any unsupported extension /// - On Win: /// - If no extension was provided it will just add currently selected one /// - If selected extension was typed in by the user it will just return /// - If unselected extension was provided it will append selected one at the end, example: `test.png.txt` pub fn save_file(self) -> impl Future<Output = Option<FileHandle>> { AsyncFileSaveDialogImpl::save_file_async(self.file_dialog) } } use crate::backend::AsyncMessageDialogImpl; use crate::backend::MessageDialogImpl; /// ## Synchronous Message Dialog #[derive(Default)] pub struct MessageDialog { pub(crate) title: String, pub(crate) description: String, pub(crate) level: MessageLevel, pub(crate) buttons: MessageButtons, #[cfg(feature = "parent")] pub(crate) parent: Option<RawWindowHandle>, } // Oh god, I don't like sending RawWindowHandle between threads but here we go anyways... // fingers crossed unsafe impl Send for MessageDialog {} impl MessageDialog { pub fn new() -> Self { Default::default() } pub fn set_level(mut self, level: MessageLevel) -> Self { self.level = level; self } pub fn set_title(mut self, text: &str) -> Self { self.title = text.into(); self } pub fn set_description(mut self, text: &str) -> Self { self.description = text.into(); self } pub fn set_buttons(mut self, btn: MessageButtons) -> Self { self.buttons = btn; self } #[cfg(feature = "parent")] fn set_parent<W: HasRawWindowHandle>(mut self, parent: &W) -> Self { self.parent = Some(parent.raw_window_handle()); self } pub fn show(self) -> bool { MessageDialogImpl::show(self) } } /// ## Asynchronous Message Dialog #[derive(Default)] pub struct AsyncMessageDialog(MessageDialog); impl AsyncMessageDialog { pub fn new() -> Self { Default::default() } pub fn set_level(mut self, level: MessageLevel) -> Self { self.0 = self.0.set_level(level); self } pub fn set_title(mut self, text: &str) -> Self { self.0 = self.0.set_title(text); self } pub fn set_description(mut self, text: &str) -> Self { self.0 = self.0.set_description(text); self } pub fn set_buttons(mut self, btn: MessageButtons) -> Self { self.0 = self.0.set_buttons(btn); self } #[cfg(feature = "parent")] /// Set parent windows explicitly (optional) /// Suported in: `macos` pub fn set_parent<W: HasRawWindowHandle>(mut self, parent: &W) -> Self { self.0 = self.0.set_parent(parent); self } pub fn show(self) -> impl Future<Output = bool> { AsyncMessageDialogImpl::show_async(self.0) } } pub enum MessageLevel { Info, Warning, Error, } impl Default for MessageLevel { fn default() -> Self { Self::Info } } pub enum MessageButtons { Ok, OkCancle, YesNo, } impl Default for MessageButtons { fn default() -> Self { Self::Ok } }
extern crate ingredients_bot; use ingredients_bot::*; fn main() { let food = get_food().unwrap(); println!("{}", food.to_tweets().join("\n---\n")); }
//! linux_raw syscalls supporting `rustix::fs`. //! //! # Safety //! //! See the `rustix::backend` module documentation for details. #![allow(unsafe_code)] #![allow(clippy::undocumented_unsafe_blocks)] use crate::backend::c; use crate::backend::conv::fs::oflags_for_open_how; use crate::backend::conv::{ by_ref, c_int, c_uint, dev_t, opt_mut, pass_usize, raw_fd, ret, ret_c_int, ret_c_uint, ret_infallible, ret_owned_fd, ret_usize, size_of, slice, slice_mut, zero, }; #[cfg(target_pointer_width = "64")] use crate::backend::conv::{loff_t, loff_t_from_u64, ret_u64}; #[cfg(any( target_arch = "aarch64", target_arch = "riscv64", target_arch = "mips64", target_arch = "mips64r6", target_pointer_width = "32", ))] use crate::fd::AsFd; use crate::fd::{BorrowedFd, OwnedFd}; use crate::ffi::CStr; #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] use crate::fs::CWD; use crate::fs::{ inotify, Access, Advice, AtFlags, FallocateFlags, FileType, FlockOperation, Gid, MemfdFlags, Mode, OFlags, RenameFlags, ResolveFlags, SealFlags, SeekFrom, Stat, StatFs, StatVfs, StatVfsMountFlags, StatxFlags, Timestamps, Uid, XattrFlags, }; use crate::io; use core::mem::{transmute, zeroed, MaybeUninit}; #[cfg(any(target_arch = "mips64", target_arch = "mips64r6"))] use linux_raw_sys::general::stat as linux_stat64; use linux_raw_sys::general::{ __kernel_fsid_t, __kernel_timespec, open_how, statx, AT_EACCESS, AT_FDCWD, AT_REMOVEDIR, AT_SYMLINK_NOFOLLOW, F_ADD_SEALS, F_GETFL, F_GET_SEALS, F_SETFL, SEEK_CUR, SEEK_DATA, SEEK_END, SEEK_HOLE, SEEK_SET, STATX__RESERVED, }; use linux_raw_sys::ioctl::{BLKPBSZGET, BLKSSZGET, EXT4_IOC_RESIZE_FS, FICLONE}; #[cfg(target_pointer_width = "32")] use { crate::backend::conv::{hi, lo, slice_just_addr}, linux_raw_sys::general::stat64 as linux_stat64, linux_raw_sys::general::timespec as __kernel_old_timespec, }; #[inline] pub(crate) fn open(path: &CStr, flags: OFlags, mode: Mode) -> io::Result<OwnedFd> { // Always enable support for large files. let flags = flags | OFlags::from_bits_retain(c::O_LARGEFILE); #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] { openat(CWD.as_fd(), path, flags, mode) } #[cfg(not(any(target_arch = "aarch64", target_arch = "riscv64")))] unsafe { ret_owned_fd(syscall_readonly!(__NR_open, path, flags, mode)) } } #[inline] pub(crate) fn openat( dirfd: BorrowedFd<'_>, path: &CStr, flags: OFlags, mode: Mode, ) -> io::Result<OwnedFd> { // Always enable support for large files. let flags = flags | OFlags::from_bits_retain(c::O_LARGEFILE); unsafe { ret_owned_fd(syscall_readonly!(__NR_openat, dirfd, path, flags, mode)) } } #[inline] pub(crate) fn openat2( dirfd: BorrowedFd<'_>, path: &CStr, mut flags: OFlags, mode: Mode, resolve: ResolveFlags, ) -> io::Result<OwnedFd> { // Enable support for large files, but not with `O_PATH` because // `openat2` doesn't like those flags together. if !flags.contains(OFlags::PATH) { flags |= OFlags::from_bits_retain(c::O_LARGEFILE); } unsafe { ret_owned_fd(syscall_readonly!( __NR_openat2, dirfd, path, by_ref(&open_how { flags: oflags_for_open_how(flags), mode: u64::from(mode.bits()), resolve: resolve.bits(), }), size_of::<open_how, _>() )) } } #[inline] pub(crate) fn chmod(path: &CStr, mode: Mode) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_fchmodat, raw_fd(AT_FDCWD), path, mode )) } } #[inline] pub(crate) fn chmodat( dirfd: BorrowedFd<'_>, path: &CStr, mode: Mode, flags: AtFlags, ) -> io::Result<()> { if flags == AtFlags::SYMLINK_NOFOLLOW { return Err(io::Errno::OPNOTSUPP); } if !flags.is_empty() { return Err(io::Errno::INVAL); } unsafe { ret(syscall_readonly!(__NR_fchmodat, dirfd, path, mode)) } } #[inline] pub(crate) fn fchmod(fd: BorrowedFd<'_>, mode: Mode) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_fchmod, fd, mode)) } } #[inline] pub(crate) fn chownat( dirfd: BorrowedFd<'_>, path: &CStr, owner: Option<Uid>, group: Option<Gid>, flags: AtFlags, ) -> io::Result<()> { unsafe { let (ow, gr) = crate::ugid::translate_fchown_args(owner, group); ret(syscall_readonly!( __NR_fchownat, dirfd, path, c_uint(ow), c_uint(gr), flags )) } } #[inline] pub(crate) fn fchown(fd: BorrowedFd<'_>, owner: Option<Uid>, group: Option<Gid>) -> io::Result<()> { unsafe { let (ow, gr) = crate::ugid::translate_fchown_args(owner, group); ret(syscall_readonly!(__NR_fchown, fd, c_uint(ow), c_uint(gr))) } } #[inline] pub(crate) fn mknodat( dirfd: BorrowedFd<'_>, path: &CStr, file_type: FileType, mode: Mode, dev: u64, ) -> io::Result<()> { #[cfg(target_pointer_width = "32")] unsafe { ret(syscall_readonly!( __NR_mknodat, dirfd, path, (mode, file_type), dev_t(dev)? )) } #[cfg(target_pointer_width = "64")] unsafe { ret(syscall_readonly!( __NR_mknodat, dirfd, path, (mode, file_type), dev_t(dev) )) } } #[inline] pub(crate) fn seek(fd: BorrowedFd<'_>, pos: SeekFrom) -> io::Result<u64> { let (whence, offset) = match pos { SeekFrom::Start(pos) => { let pos: u64 = pos; // Silently cast; we'll get `EINVAL` if the value is negative. (SEEK_SET, pos as i64) } SeekFrom::End(offset) => (SEEK_END, offset), SeekFrom::Current(offset) => (SEEK_CUR, offset), #[cfg(target_os = "linux")] SeekFrom::Data(offset) => (SEEK_DATA, offset), #[cfg(target_os = "linux")] SeekFrom::Hole(offset) => (SEEK_HOLE, offset), }; _seek(fd, offset, whence) } #[inline] pub(crate) fn _seek(fd: BorrowedFd<'_>, offset: i64, whence: c::c_uint) -> io::Result<u64> { #[cfg(target_pointer_width = "32")] unsafe { let mut result = MaybeUninit::<u64>::uninit(); ret(syscall!( __NR__llseek, fd, // Don't use the hi/lo functions here because Linux's llseek // takes its 64-bit argument differently from everything else. pass_usize((offset >> 32) as usize), pass_usize(offset as usize), &mut result, c_uint(whence) ))?; Ok(result.assume_init()) } #[cfg(target_pointer_width = "64")] unsafe { ret_u64(syscall_readonly!( __NR_lseek, fd, loff_t(offset), c_uint(whence) )) } } #[inline] pub(crate) fn tell(fd: BorrowedFd<'_>) -> io::Result<u64> { _seek(fd, 0, SEEK_CUR).map(|x| x as u64) } #[inline] pub(crate) fn ftruncate(fd: BorrowedFd<'_>, length: u64) -> io::Result<()> { // <https://github.com/torvalds/linux/blob/fcadab740480e0e0e9fa9bd272acd409884d431a/arch/arm64/kernel/sys32.c#L81-L83> #[cfg(all( target_pointer_width = "32", any( target_arch = "arm", target_arch = "mips", target_arch = "mips32r6", target_arch = "powerpc" ), ))] unsafe { ret(syscall_readonly!( __NR_ftruncate64, fd, zero(), hi(length), lo(length) )) } #[cfg(all( target_pointer_width = "32", not(any( target_arch = "arm", target_arch = "mips", target_arch = "mips32r6", target_arch = "powerpc" )), ))] unsafe { ret(syscall_readonly!( __NR_ftruncate64, fd, hi(length), lo(length) )) } #[cfg(target_pointer_width = "64")] unsafe { ret(syscall_readonly!( __NR_ftruncate, fd, loff_t_from_u64(length) )) } } #[inline] pub(crate) fn fallocate( fd: BorrowedFd<'_>, mode: FallocateFlags, offset: u64, len: u64, ) -> io::Result<()> { #[cfg(target_pointer_width = "32")] unsafe { ret(syscall_readonly!( __NR_fallocate, fd, mode, hi(offset), lo(offset), hi(len), lo(len) )) } #[cfg(target_pointer_width = "64")] unsafe { ret(syscall_readonly!( __NR_fallocate, fd, mode, loff_t_from_u64(offset), loff_t_from_u64(len) )) } } #[inline] pub(crate) fn fadvise(fd: BorrowedFd<'_>, pos: u64, len: u64, advice: Advice) -> io::Result<()> { // On ARM, the arguments are reordered so that the len and pos argument // pairs are aligned. And ARM has a custom syscall code for this. #[cfg(target_arch = "arm")] unsafe { ret(syscall_readonly!( __NR_arm_fadvise64_64, fd, advice, hi(pos), lo(pos), hi(len), lo(len) )) } // On powerpc, the arguments are reordered as on ARM. #[cfg(target_arch = "powerpc")] unsafe { ret(syscall_readonly!( __NR_fadvise64_64, fd, advice, hi(pos), lo(pos), hi(len), lo(len) )) } // On mips, the arguments are not reordered, and padding is inserted // instead to ensure alignment. #[cfg(any(target_arch = "mips", target_arch = "mips32r6"))] unsafe { ret(syscall_readonly!( __NR_fadvise64, fd, zero(), hi(pos), lo(pos), hi(len), lo(len), advice )) } #[cfg(all( target_pointer_width = "32", not(any( target_arch = "arm", target_arch = "mips", target_arch = "mips32r6", target_arch = "powerpc" )), ))] unsafe { ret(syscall_readonly!( __NR_fadvise64_64, fd, hi(pos), lo(pos), hi(len), lo(len), advice )) } #[cfg(target_pointer_width = "64")] unsafe { ret(syscall_readonly!( __NR_fadvise64, fd, loff_t_from_u64(pos), loff_t_from_u64(len), advice )) } } #[inline] pub(crate) fn fsync(fd: BorrowedFd<'_>) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_fsync, fd)) } } #[inline] pub(crate) fn fdatasync(fd: BorrowedFd<'_>) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_fdatasync, fd)) } } #[inline] pub(crate) fn flock(fd: BorrowedFd<'_>, operation: FlockOperation) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_flock, fd, c_uint(operation as c::c_uint) )) } } #[inline] pub(crate) fn syncfs(fd: BorrowedFd<'_>) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_syncfs, fd)) } } #[inline] pub(crate) fn sync() { unsafe { ret_infallible(syscall_readonly!(__NR_sync)) } } #[inline] pub(crate) fn fstat(fd: BorrowedFd<'_>) -> io::Result<Stat> { // 32-bit and mips64 Linux: `struct stat64` is not y2038 compatible; use // `statx`. // // And, some old platforms don't support `statx`, and some fail with a // confusing error code, so we call `crate::fs::statx` to handle that. If // `statx` isn't available, fall back to the buggy system call. #[cfg(any( target_pointer_width = "32", target_arch = "mips64", target_arch = "mips64r6" ))] { match crate::fs::statx(fd, cstr!(""), AtFlags::EMPTY_PATH, StatxFlags::BASIC_STATS) { Ok(x) => statx_to_stat(x), Err(io::Errno::NOSYS) => fstat_old(fd), Err(err) => Err(err), } } #[cfg(all( target_pointer_width = "64", not(target_arch = "mips64"), not(target_arch = "mips64r6") ))] unsafe { let mut result = MaybeUninit::<Stat>::uninit(); ret(syscall!(__NR_fstat, fd, &mut result))?; Ok(result.assume_init()) } } #[cfg(any( target_pointer_width = "32", target_arch = "mips64", target_arch = "mips64r6", ))] fn fstat_old(fd: BorrowedFd<'_>) -> io::Result<Stat> { let mut result = MaybeUninit::<linux_stat64>::uninit(); #[cfg(any(target_arch = "mips64", target_arch = "mips64r6"))] unsafe { ret(syscall!(__NR_fstat, fd, &mut result))?; stat_to_stat(result.assume_init()) } #[cfg(target_pointer_width = "32")] unsafe { ret(syscall!(__NR_fstat64, fd, &mut result))?; stat_to_stat(result.assume_init()) } } #[inline] pub(crate) fn stat(path: &CStr) -> io::Result<Stat> { // See the comments in `fstat` about using `crate::fs::statx` here. #[cfg(any( target_pointer_width = "32", target_arch = "mips64", target_arch = "mips64r6" ))] { match crate::fs::statx( crate::fs::CWD.as_fd(), path, AtFlags::empty(), StatxFlags::BASIC_STATS, ) { Ok(x) => statx_to_stat(x), Err(io::Errno::NOSYS) => stat_old(path), Err(err) => Err(err), } } #[cfg(all( target_pointer_width = "64", not(target_arch = "mips64"), not(target_arch = "mips64r6"), ))] unsafe { let mut result = MaybeUninit::<Stat>::uninit(); ret(syscall!( __NR_newfstatat, raw_fd(AT_FDCWD), path, &mut result, c_uint(0) ))?; Ok(result.assume_init()) } } #[cfg(any( target_pointer_width = "32", target_arch = "mips64", target_arch = "mips64r6" ))] fn stat_old(path: &CStr) -> io::Result<Stat> { let mut result = MaybeUninit::<linux_stat64>::uninit(); #[cfg(any(target_arch = "mips64", target_arch = "mips64r6"))] unsafe { ret(syscall!( __NR_newfstatat, raw_fd(AT_FDCWD), path, &mut result, c_uint(0) ))?; stat_to_stat(result.assume_init()) } #[cfg(target_pointer_width = "32")] unsafe { ret(syscall!( __NR_fstatat64, raw_fd(AT_FDCWD), path, &mut result, c_uint(0) ))?; stat_to_stat(result.assume_init()) } } #[inline] pub(crate) fn statat(dirfd: BorrowedFd<'_>, path: &CStr, flags: AtFlags) -> io::Result<Stat> { // See the comments in `fstat` about using `crate::fs::statx` here. #[cfg(any( target_pointer_width = "32", target_arch = "mips64", target_arch = "mips64r6" ))] { match crate::fs::statx(dirfd, path, flags, StatxFlags::BASIC_STATS) { Ok(x) => statx_to_stat(x), Err(io::Errno::NOSYS) => statat_old(dirfd, path, flags), Err(err) => Err(err), } } #[cfg(all( target_pointer_width = "64", not(target_arch = "mips64"), not(target_arch = "mips64r6"), ))] unsafe { let mut result = MaybeUninit::<Stat>::uninit(); ret(syscall!(__NR_newfstatat, dirfd, path, &mut result, flags))?; Ok(result.assume_init()) } } #[cfg(any( target_pointer_width = "32", target_arch = "mips64", target_arch = "mips64r6" ))] fn statat_old(dirfd: BorrowedFd<'_>, path: &CStr, flags: AtFlags) -> io::Result<Stat> { let mut result = MaybeUninit::<linux_stat64>::uninit(); #[cfg(any(target_arch = "mips64", target_arch = "mips64r6"))] unsafe { ret(syscall!(__NR_newfstatat, dirfd, path, &mut result, flags))?; stat_to_stat(result.assume_init()) } #[cfg(target_pointer_width = "32")] unsafe { ret(syscall!(__NR_fstatat64, dirfd, path, &mut result, flags))?; stat_to_stat(result.assume_init()) } } #[inline] pub(crate) fn lstat(path: &CStr) -> io::Result<Stat> { // See the comments in `fstat` about using `crate::fs::statx` here. #[cfg(any(target_pointer_width = "32", target_arch = "mips64"))] { match crate::fs::statx( crate::fs::CWD.as_fd(), path, AtFlags::SYMLINK_NOFOLLOW, StatxFlags::BASIC_STATS, ) { Ok(x) => statx_to_stat(x), Err(io::Errno::NOSYS) => lstat_old(path), Err(err) => Err(err), } } #[cfg(all(target_pointer_width = "64", not(target_arch = "mips64")))] unsafe { let mut result = MaybeUninit::<Stat>::uninit(); ret(syscall!( __NR_newfstatat, raw_fd(AT_FDCWD), path, &mut result, c_uint(AT_SYMLINK_NOFOLLOW) ))?; Ok(result.assume_init()) } } #[cfg(any(target_pointer_width = "32", target_arch = "mips64"))] fn lstat_old(path: &CStr) -> io::Result<Stat> { let mut result = MaybeUninit::<linux_stat64>::uninit(); #[cfg(any(target_arch = "mips64", target_arch = "mips64r6"))] unsafe { ret(syscall!( __NR_newfstatat, raw_fd(AT_FDCWD), path, &mut result, c_uint(AT_SYMLINK_NOFOLLOW) ))?; stat_to_stat(result.assume_init()) } #[cfg(target_pointer_width = "32")] unsafe { ret(syscall!( __NR_fstatat64, raw_fd(AT_FDCWD), path, &mut result, c_uint(AT_SYMLINK_NOFOLLOW) ))?; stat_to_stat(result.assume_init()) } } /// Convert from a Linux `statx` value to rustix's `Stat`. #[cfg(any( target_pointer_width = "32", target_arch = "mips64", target_arch = "mips64r6" ))] fn statx_to_stat(x: crate::fs::Statx) -> io::Result<Stat> { Ok(Stat { st_dev: crate::fs::makedev(x.stx_dev_major, x.stx_dev_minor), st_mode: x.stx_mode.into(), st_nlink: x.stx_nlink.into(), st_uid: x.stx_uid.into(), st_gid: x.stx_gid.into(), st_rdev: crate::fs::makedev(x.stx_rdev_major, x.stx_rdev_minor), st_size: x.stx_size.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_blksize: x.stx_blksize.into(), st_blocks: x.stx_blocks.into(), st_atime: x .stx_atime .tv_sec .try_into() .map_err(|_| io::Errno::OVERFLOW)?, st_atime_nsec: x.stx_atime.tv_nsec.into(), st_mtime: x .stx_mtime .tv_sec .try_into() .map_err(|_| io::Errno::OVERFLOW)?, st_mtime_nsec: x.stx_mtime.tv_nsec.into(), st_ctime: x .stx_ctime .tv_sec .try_into() .map_err(|_| io::Errno::OVERFLOW)?, st_ctime_nsec: x.stx_ctime.tv_nsec.into(), st_ino: x.stx_ino.into(), }) } /// Convert from a Linux `stat64` value to rustix's `Stat`. #[cfg(target_pointer_width = "32")] fn stat_to_stat(s64: linux_raw_sys::general::stat64) -> io::Result<Stat> { Ok(Stat { st_dev: s64.st_dev.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_mode: s64.st_mode.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_nlink: s64.st_nlink.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_uid: s64.st_uid.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_gid: s64.st_gid.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_rdev: s64.st_rdev.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_size: s64.st_size.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_blksize: s64.st_blksize.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_blocks: s64.st_blocks.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_atime: s64.st_atime.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_atime_nsec: s64 .st_atime_nsec .try_into() .map_err(|_| io::Errno::OVERFLOW)?, st_mtime: s64.st_mtime.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_mtime_nsec: s64 .st_mtime_nsec .try_into() .map_err(|_| io::Errno::OVERFLOW)?, st_ctime: s64.st_ctime.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_ctime_nsec: s64 .st_ctime_nsec .try_into() .map_err(|_| io::Errno::OVERFLOW)?, st_ino: s64.st_ino.try_into().map_err(|_| io::Errno::OVERFLOW)?, }) } /// Convert from a Linux `stat` value to rustix's `Stat`. #[cfg(any(target_arch = "mips64", target_arch = "mips64r6"))] fn stat_to_stat(s: linux_raw_sys::general::stat) -> io::Result<Stat> { Ok(Stat { st_dev: s.st_dev.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_mode: s.st_mode.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_nlink: s.st_nlink.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_uid: s.st_uid.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_gid: s.st_gid.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_rdev: s.st_rdev.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_size: s.st_size.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_blksize: s.st_blksize.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_blocks: s.st_blocks.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_atime: s.st_atime.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_atime_nsec: s .st_atime_nsec .try_into() .map_err(|_| io::Errno::OVERFLOW)?, st_mtime: s.st_mtime.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_mtime_nsec: s .st_mtime_nsec .try_into() .map_err(|_| io::Errno::OVERFLOW)?, st_ctime: s.st_ctime.try_into().map_err(|_| io::Errno::OVERFLOW)?, st_ctime_nsec: s .st_ctime_nsec .try_into() .map_err(|_| io::Errno::OVERFLOW)?, st_ino: s.st_ino.try_into().map_err(|_| io::Errno::OVERFLOW)?, }) } #[inline] pub(crate) fn statx( dirfd: BorrowedFd<'_>, path: &CStr, flags: AtFlags, mask: StatxFlags, ) -> io::Result<statx> { // If a future Linux kernel adds more fields to `struct statx` and users // passing flags unknown to rustix in `StatxFlags`, we could end up // writing outside of the buffer. To prevent this possibility, we mask off // any flags that we don't know about. // // This includes `STATX__RESERVED`, which has a value that we know, but // which could take on arbitrary new meaning in the future. Linux currently // rejects this flag with `EINVAL`, so we do the same. // // This doesn't rely on `STATX_ALL` because [it's deprecated] and already // doesn't represent all the known flags. // // [it's deprecated]: https://patchwork.kernel.org/project/linux-fsdevel/patch/20200505095915.11275-7-mszeredi@redhat.com/ if (mask.bits() & STATX__RESERVED) == STATX__RESERVED { return Err(io::Errno::INVAL); } let mask = mask & StatxFlags::all(); unsafe { let mut statx_buf = MaybeUninit::<statx>::uninit(); ret(syscall!( __NR_statx, dirfd, path, flags, mask, &mut statx_buf ))?; Ok(statx_buf.assume_init()) } } #[inline] pub(crate) fn is_statx_available() -> bool { unsafe { // Call `statx` with null pointers so that if it fails for any reason // other than `EFAULT`, we know it's not supported. matches!( ret(syscall!( __NR_statx, raw_fd(AT_FDCWD), zero(), zero(), zero(), zero() )), Err(io::Errno::FAULT) ) } } #[inline] pub(crate) fn fstatfs(fd: BorrowedFd<'_>) -> io::Result<StatFs> { #[cfg(target_pointer_width = "32")] unsafe { let mut result = MaybeUninit::<StatFs>::uninit(); ret(syscall!( __NR_fstatfs64, fd, size_of::<StatFs, _>(), &mut result ))?; Ok(result.assume_init()) } #[cfg(target_pointer_width = "64")] unsafe { let mut result = MaybeUninit::<StatFs>::uninit(); ret(syscall!(__NR_fstatfs, fd, &mut result))?; Ok(result.assume_init()) } } #[inline] pub(crate) fn fstatvfs(fd: BorrowedFd<'_>) -> io::Result<StatVfs> { // Linux doesn't have an `fstatvfs` syscall; we have to do `fstatfs` and // translate the fields as best we can. let statfs = fstatfs(fd)?; Ok(statfs_to_statvfs(statfs)) } #[inline] pub(crate) fn statfs(path: &CStr) -> io::Result<StatFs> { #[cfg(target_pointer_width = "32")] unsafe { let mut result = MaybeUninit::<StatFs>::uninit(); ret(syscall!( __NR_statfs64, path, size_of::<StatFs, _>(), &mut result ))?; Ok(result.assume_init()) } #[cfg(target_pointer_width = "64")] unsafe { let mut result = MaybeUninit::<StatFs>::uninit(); ret(syscall!(__NR_statfs, path, &mut result))?; Ok(result.assume_init()) } } #[inline] pub(crate) fn statvfs(path: &CStr) -> io::Result<StatVfs> { // Linux doesn't have a `statvfs` syscall; we have to do `statfs` and // translate the fields as best we can. let statfs = statfs(path)?; Ok(statfs_to_statvfs(statfs)) } fn statfs_to_statvfs(statfs: StatFs) -> StatVfs { let __kernel_fsid_t { val } = statfs.f_fsid; let [f_fsid_val0, f_fsid_val1]: [i32; 2] = val; StatVfs { f_bsize: statfs.f_bsize as u64, f_frsize: if statfs.f_frsize != 0 { statfs.f_frsize } else { statfs.f_bsize } as u64, f_blocks: statfs.f_blocks as u64, f_bfree: statfs.f_bfree as u64, f_bavail: statfs.f_bavail as u64, f_files: statfs.f_files as u64, f_ffree: statfs.f_ffree as u64, f_favail: statfs.f_ffree as u64, f_fsid: u64::from(f_fsid_val0 as u32) | u64::from(f_fsid_val1 as u32) << 32, f_flag: StatVfsMountFlags::from_bits_retain(statfs.f_flags as u64), f_namemax: statfs.f_namelen as u64, } } #[inline] pub(crate) fn readlink(path: &CStr, buf: &mut [u8]) -> io::Result<usize> { let (buf_addr_mut, buf_len) = slice_mut(buf); unsafe { ret_usize(syscall!( __NR_readlinkat, raw_fd(AT_FDCWD), path, buf_addr_mut, buf_len )) } } #[inline] pub(crate) fn readlinkat( dirfd: BorrowedFd<'_>, path: &CStr, buf: &mut [MaybeUninit<u8>], ) -> io::Result<usize> { let (buf_addr_mut, buf_len) = slice_mut(buf); unsafe { ret_usize(syscall!( __NR_readlinkat, dirfd, path, buf_addr_mut, buf_len )) } } #[inline] pub(crate) fn fcntl_getfl(fd: BorrowedFd<'_>) -> io::Result<OFlags> { #[cfg(target_pointer_width = "32")] unsafe { ret_c_uint(syscall_readonly!(__NR_fcntl64, fd, c_uint(F_GETFL))) .map(OFlags::from_bits_retain) } #[cfg(target_pointer_width = "64")] unsafe { ret_c_uint(syscall_readonly!(__NR_fcntl, fd, c_uint(F_GETFL))).map(OFlags::from_bits_retain) } } #[inline] pub(crate) fn fcntl_setfl(fd: BorrowedFd<'_>, flags: OFlags) -> io::Result<()> { // Always enable support for large files. let flags = flags | OFlags::from_bits_retain(c::O_LARGEFILE); #[cfg(target_pointer_width = "32")] unsafe { ret(syscall_readonly!(__NR_fcntl64, fd, c_uint(F_SETFL), flags)) } #[cfg(target_pointer_width = "64")] unsafe { ret(syscall_readonly!(__NR_fcntl, fd, c_uint(F_SETFL), flags)) } } #[inline] pub(crate) fn fcntl_get_seals(fd: BorrowedFd<'_>) -> io::Result<SealFlags> { #[cfg(target_pointer_width = "32")] unsafe { ret_c_int(syscall_readonly!(__NR_fcntl64, fd, c_uint(F_GET_SEALS))) .map(|seals| SealFlags::from_bits_retain(seals as u32)) } #[cfg(target_pointer_width = "64")] unsafe { ret_c_int(syscall_readonly!(__NR_fcntl, fd, c_uint(F_GET_SEALS))) .map(|seals| SealFlags::from_bits_retain(seals as u32)) } } #[inline] pub(crate) fn fcntl_add_seals(fd: BorrowedFd<'_>, seals: SealFlags) -> io::Result<()> { #[cfg(target_pointer_width = "32")] unsafe { ret(syscall_readonly!( __NR_fcntl64, fd, c_uint(F_ADD_SEALS), seals )) } #[cfg(target_pointer_width = "64")] unsafe { ret(syscall_readonly!( __NR_fcntl, fd, c_uint(F_ADD_SEALS), seals )) } } #[inline] pub(crate) fn fcntl_lock(fd: BorrowedFd<'_>, operation: FlockOperation) -> io::Result<()> { #[cfg(target_pointer_width = "64")] use linux_raw_sys::general::{flock, F_SETLK, F_SETLKW}; #[cfg(target_pointer_width = "32")] use linux_raw_sys::general::{flock64 as flock, F_SETLK64 as F_SETLK, F_SETLKW64 as F_SETLKW}; use linux_raw_sys::general::{F_RDLCK, F_UNLCK, F_WRLCK}; let (cmd, l_type) = match operation { FlockOperation::LockShared => (F_SETLKW, F_RDLCK), FlockOperation::LockExclusive => (F_SETLKW, F_WRLCK), FlockOperation::Unlock => (F_SETLKW, F_UNLCK), FlockOperation::NonBlockingLockShared => (F_SETLK, F_RDLCK), FlockOperation::NonBlockingLockExclusive => (F_SETLK, F_WRLCK), FlockOperation::NonBlockingUnlock => (F_SETLK, F_UNLCK), }; unsafe { let lock = flock { l_type: l_type as _, // When `l_len` is zero, this locks all the bytes from // `l_whence`/`l_start` to the end of the file, even as the // file grows dynamically. l_whence: SEEK_SET as _, l_start: 0, l_len: 0, ..zeroed() }; #[cfg(target_pointer_width = "32")] { ret(syscall_readonly!( __NR_fcntl64, fd, c_uint(cmd), by_ref(&lock) )) } #[cfg(target_pointer_width = "64")] { ret(syscall_readonly!( __NR_fcntl, fd, c_uint(cmd), by_ref(&lock) )) } } } #[inline] pub(crate) fn rename(old_path: &CStr, new_path: &CStr) -> io::Result<()> { #[cfg(target_arch = "riscv64")] unsafe { ret(syscall_readonly!( __NR_renameat2, raw_fd(AT_FDCWD), old_path, raw_fd(AT_FDCWD), new_path, c_uint(0) )) } #[cfg(not(target_arch = "riscv64"))] unsafe { ret(syscall_readonly!( __NR_renameat, raw_fd(AT_FDCWD), old_path, raw_fd(AT_FDCWD), new_path )) } } #[inline] pub(crate) fn renameat( old_dirfd: BorrowedFd<'_>, old_path: &CStr, new_dirfd: BorrowedFd<'_>, new_path: &CStr, ) -> io::Result<()> { #[cfg(target_arch = "riscv64")] unsafe { ret(syscall_readonly!( __NR_renameat2, old_dirfd, old_path, new_dirfd, new_path, c_uint(0) )) } #[cfg(not(target_arch = "riscv64"))] unsafe { ret(syscall_readonly!( __NR_renameat, old_dirfd, old_path, new_dirfd, new_path )) } } #[inline] pub(crate) fn renameat2( old_dirfd: BorrowedFd<'_>, old_path: &CStr, new_dirfd: BorrowedFd<'_>, new_path: &CStr, flags: RenameFlags, ) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_renameat2, old_dirfd, old_path, new_dirfd, new_path, flags )) } } #[inline] pub(crate) fn unlink(path: &CStr) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_unlinkat, raw_fd(AT_FDCWD), path, c_uint(0) )) } } #[inline] pub(crate) fn unlinkat(dirfd: BorrowedFd<'_>, path: &CStr, flags: AtFlags) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_unlinkat, dirfd, path, flags)) } } #[inline] pub(crate) fn rmdir(path: &CStr) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_unlinkat, raw_fd(AT_FDCWD), path, c_uint(AT_REMOVEDIR) )) } } #[inline] pub(crate) fn link(old_path: &CStr, new_path: &CStr) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_linkat, raw_fd(AT_FDCWD), old_path, raw_fd(AT_FDCWD), new_path, c_uint(0) )) } } #[inline] pub(crate) fn linkat( old_dirfd: BorrowedFd<'_>, old_path: &CStr, new_dirfd: BorrowedFd<'_>, new_path: &CStr, flags: AtFlags, ) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_linkat, old_dirfd, old_path, new_dirfd, new_path, flags )) } } #[inline] pub(crate) fn symlink(old_path: &CStr, new_path: &CStr) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_symlinkat, old_path, raw_fd(AT_FDCWD), new_path )) } } #[inline] pub(crate) fn symlinkat(old_path: &CStr, dirfd: BorrowedFd<'_>, new_path: &CStr) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_symlinkat, old_path, dirfd, new_path)) } } #[inline] pub(crate) fn mkdir(path: &CStr, mode: Mode) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_mkdirat, raw_fd(AT_FDCWD), path, mode )) } } #[inline] pub(crate) fn mkdirat(dirfd: BorrowedFd<'_>, path: &CStr, mode: Mode) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_mkdirat, dirfd, path, mode)) } } #[inline] pub(crate) fn getdents(fd: BorrowedFd<'_>, dirent: &mut [u8]) -> io::Result<usize> { let (dirent_addr_mut, dirent_len) = slice_mut(dirent); unsafe { ret_usize(syscall!(__NR_getdents64, fd, dirent_addr_mut, dirent_len)) } } #[inline] pub(crate) fn getdents_uninit( fd: BorrowedFd<'_>, dirent: &mut [MaybeUninit<u8>], ) -> io::Result<usize> { let (dirent_addr_mut, dirent_len) = slice_mut(dirent); unsafe { ret_usize(syscall!(__NR_getdents64, fd, dirent_addr_mut, dirent_len)) } } #[inline] pub(crate) fn utimensat( dirfd: BorrowedFd<'_>, path: &CStr, times: &Timestamps, flags: AtFlags, ) -> io::Result<()> { _utimensat(dirfd, Some(path), times, flags) } #[inline] fn _utimensat( dirfd: BorrowedFd<'_>, path: Option<&CStr>, times: &Timestamps, flags: AtFlags, ) -> io::Result<()> { // Assert that `Timestamps` has the expected layout. let _ = unsafe { transmute::<Timestamps, [__kernel_timespec; 2]>(times.clone()) }; // `utimensat_time64` was introduced in Linux 5.1. The old `utimensat` // syscall is not y2038-compatible on 32-bit architectures. #[cfg(target_pointer_width = "32")] unsafe { match ret(syscall_readonly!( __NR_utimensat_time64, dirfd, path, by_ref(times), flags )) { Err(io::Errno::NOSYS) => _utimensat_old(dirfd, path, times, flags), otherwise => otherwise, } } #[cfg(target_pointer_width = "64")] unsafe { ret(syscall_readonly!( __NR_utimensat, dirfd, path, by_ref(times), flags )) } } #[cfg(target_pointer_width = "32")] unsafe fn _utimensat_old( dirfd: BorrowedFd<'_>, path: Option<&CStr>, times: &Timestamps, flags: AtFlags, ) -> io::Result<()> { // See the comments in `rustix_clock_gettime_via_syscall` about // emulation. let old_times = [ __kernel_old_timespec { tv_sec: times .last_access .tv_sec .try_into() .map_err(|_| io::Errno::OVERFLOW)?, tv_nsec: times .last_access .tv_nsec .try_into() .map_err(|_| io::Errno::INVAL)?, }, __kernel_old_timespec { tv_sec: times .last_modification .tv_sec .try_into() .map_err(|_| io::Errno::OVERFLOW)?, tv_nsec: times .last_modification .tv_nsec .try_into() .map_err(|_| io::Errno::INVAL)?, }, ]; // The length of the array is fixed and not passed into the syscall. let old_times_addr = slice_just_addr(&old_times); ret(syscall_readonly!( __NR_utimensat, dirfd, path, old_times_addr, flags )) } #[inline] pub(crate) fn futimens(fd: BorrowedFd<'_>, times: &Timestamps) -> io::Result<()> { _utimensat(fd, None, times, AtFlags::empty()) } #[inline] pub(crate) fn access(path: &CStr, access: Access) -> io::Result<()> { #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] { accessat_noflags(CWD.as_fd(), path, access) } #[cfg(not(any(target_arch = "aarch64", target_arch = "riscv64")))] unsafe { ret(syscall_readonly!(__NR_access, path, access)) } } pub(crate) fn accessat( dirfd: BorrowedFd<'_>, path: &CStr, access: Access, flags: AtFlags, ) -> io::Result<()> { if !flags .difference(AtFlags::EACCESS | AtFlags::SYMLINK_NOFOLLOW) .is_empty() { return Err(io::Errno::INVAL); } // Linux's `faccessat` syscall doesn't have a flags argument, so if we have // any flags, use the newer `faccessat2` introduced in Linux 5.8 which // does. Unless we're on Android where using newer system calls can cause // seccomp to abort the process. #[cfg(not(target_os = "android"))] if !flags.is_empty() { unsafe { match ret(syscall_readonly!( __NR_faccessat2, dirfd, path, access, flags )) { Ok(()) => return Ok(()), Err(io::Errno::NOSYS) => {} Err(other) => return Err(other), } } } // Linux's `faccessat` doesn't have a flags parameter. If we have // `AT_EACCESS` and we're not setuid or setgid, we can emulate it. if flags.is_empty() || (flags.bits() == AT_EACCESS && crate::backend::ugid::syscalls::getuid() == crate::backend::ugid::syscalls::geteuid() && crate::backend::ugid::syscalls::getgid() == crate::backend::ugid::syscalls::getegid()) { return accessat_noflags(dirfd, path, access); } Err(io::Errno::NOSYS) } #[inline] fn accessat_noflags(dirfd: BorrowedFd<'_>, path: &CStr, access: Access) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_faccessat, dirfd, path, access)) } } #[inline] pub(crate) fn copy_file_range( fd_in: BorrowedFd<'_>, off_in: Option<&mut u64>, fd_out: BorrowedFd<'_>, off_out: Option<&mut u64>, len: usize, ) -> io::Result<usize> { unsafe { ret_usize(syscall!( __NR_copy_file_range, fd_in, opt_mut(off_in), fd_out, opt_mut(off_out), pass_usize(len), c_uint(0) )) } } #[inline] pub(crate) fn memfd_create(name: &CStr, flags: MemfdFlags) -> io::Result<OwnedFd> { unsafe { ret_owned_fd(syscall_readonly!(__NR_memfd_create, name, flags)) } } #[inline] pub(crate) fn sendfile( out_fd: BorrowedFd<'_>, in_fd: BorrowedFd<'_>, offset: Option<&mut u64>, count: usize, ) -> io::Result<usize> { #[cfg(target_pointer_width = "32")] unsafe { ret_usize(syscall!( __NR_sendfile64, out_fd, in_fd, opt_mut(offset), pass_usize(count) )) } #[cfg(target_pointer_width = "64")] unsafe { ret_usize(syscall!( __NR_sendfile, out_fd, in_fd, opt_mut(offset), pass_usize(count) )) } } #[inline] pub(crate) fn inotify_init1(flags: inotify::CreateFlags) -> io::Result<OwnedFd> { unsafe { ret_owned_fd(syscall_readonly!(__NR_inotify_init1, flags)) } } #[inline] pub(crate) fn inotify_add_watch( infd: BorrowedFd<'_>, path: &CStr, flags: inotify::WatchFlags, ) -> io::Result<i32> { unsafe { ret_c_int(syscall_readonly!(__NR_inotify_add_watch, infd, path, flags)) } } #[inline] pub(crate) fn inotify_rm_watch(infd: BorrowedFd<'_>, wfd: i32) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_inotify_rm_watch, infd, c_int(wfd))) } } #[inline] pub(crate) fn getxattr(path: &CStr, name: &CStr, value: &mut [u8]) -> io::Result<usize> { let (value_addr_mut, value_len) = slice_mut(value); unsafe { ret_usize(syscall!( __NR_getxattr, path, name, value_addr_mut, value_len )) } } #[inline] pub(crate) fn lgetxattr(path: &CStr, name: &CStr, value: &mut [u8]) -> io::Result<usize> { let (value_addr_mut, value_len) = slice_mut(value); unsafe { ret_usize(syscall!( __NR_lgetxattr, path, name, value_addr_mut, value_len )) } } #[inline] pub(crate) fn fgetxattr(fd: BorrowedFd<'_>, name: &CStr, value: &mut [u8]) -> io::Result<usize> { let (value_addr_mut, value_len) = slice_mut(value); unsafe { ret_usize(syscall!( __NR_fgetxattr, fd, name, value_addr_mut, value_len )) } } #[inline] pub(crate) fn setxattr( path: &CStr, name: &CStr, value: &[u8], flags: XattrFlags, ) -> io::Result<()> { let (value_addr, value_len) = slice(value); unsafe { ret(syscall_readonly!( __NR_setxattr, path, name, value_addr, value_len, flags )) } } #[inline] pub(crate) fn lsetxattr( path: &CStr, name: &CStr, value: &[u8], flags: XattrFlags, ) -> io::Result<()> { let (value_addr, value_len) = slice(value); unsafe { ret(syscall_readonly!( __NR_lsetxattr, path, name, value_addr, value_len, flags )) } } #[inline] pub(crate) fn fsetxattr( fd: BorrowedFd<'_>, name: &CStr, value: &[u8], flags: XattrFlags, ) -> io::Result<()> { let (value_addr, value_len) = slice(value); unsafe { ret(syscall_readonly!( __NR_fsetxattr, fd, name, value_addr, value_len, flags )) } } #[inline] pub(crate) fn listxattr(path: &CStr, list: &mut [c::c_char]) -> io::Result<usize> { let (list_addr_mut, list_len) = slice_mut(list); unsafe { ret_usize(syscall!(__NR_listxattr, path, list_addr_mut, list_len)) } } #[inline] pub(crate) fn llistxattr(path: &CStr, list: &mut [c::c_char]) -> io::Result<usize> { let (list_addr_mut, list_len) = slice_mut(list); unsafe { ret_usize(syscall!(__NR_llistxattr, path, list_addr_mut, list_len)) } } #[inline] pub(crate) fn flistxattr(fd: BorrowedFd<'_>, list: &mut [c::c_char]) -> io::Result<usize> { let (list_addr_mut, list_len) = slice_mut(list); unsafe { ret_usize(syscall!(__NR_flistxattr, fd, list_addr_mut, list_len)) } } #[inline] pub(crate) fn removexattr(path: &CStr, name: &CStr) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_removexattr, path, name)) } } #[inline] pub(crate) fn lremovexattr(path: &CStr, name: &CStr) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_lremovexattr, path, name)) } } #[inline] pub(crate) fn fremovexattr(fd: BorrowedFd<'_>, name: &CStr) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_fremovexattr, fd, name)) } } #[inline] pub(crate) fn ioctl_blksszget(fd: BorrowedFd) -> io::Result<u32> { let mut result = MaybeUninit::<c::c_uint>::uninit(); unsafe { ret(syscall!(__NR_ioctl, fd, c_uint(BLKSSZGET), &mut result))?; Ok(result.assume_init() as u32) } } #[inline] pub(crate) fn ioctl_blkpbszget(fd: BorrowedFd) -> io::Result<u32> { let mut result = MaybeUninit::<c::c_uint>::uninit(); unsafe { ret(syscall!(__NR_ioctl, fd, c_uint(BLKPBSZGET), &mut result))?; Ok(result.assume_init() as u32) } } #[inline] pub(crate) fn ioctl_ficlone(fd: BorrowedFd<'_>, src_fd: BorrowedFd<'_>) -> io::Result<()> { unsafe { ret(syscall_readonly!(__NR_ioctl, fd, c_uint(FICLONE), src_fd)) } } #[inline] pub(crate) fn ext4_ioc_resize_fs(fd: BorrowedFd<'_>, blocks: u64) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_ioctl, fd, c_uint(EXT4_IOC_RESIZE_FS), by_ref(&blocks) )) } }
use matrix_sdk::{ events::{ room::{ member::MemberEventContent, message::{MessageEventContent, TextMessageEventContent}, }, AnyMessageEventContent, StrippedStateEvent, SyncMessageEvent, }, Client, EventHandler, RoomState, }; use crate::cfg::BotConfig; use tokio::time::{sleep, Duration}; use tracing::{error, info}; pub struct MyEventHandler { pub client: Client, pub config: BotConfig, } impl MyEventHandler { pub fn new(client: Client, config: BotConfig) -> Self { Self { client, config } } } impl MyEventHandler { async fn handle_message( &self, state: RoomState, event: &SyncMessageEvent<MessageEventContent>, ) -> anyhow::Result<()> { if let Some(room) = state.joined() { let msg_body = if let SyncMessageEvent { content: MessageEventContent::Text(TextMessageEventContent { body: msg_body, .. }), .. } = event { msg_body.clone() } else { String::new() }; match msg_body.to_ascii_lowercase().as_str() { "ping" => { let content = AnyMessageEventContent::RoomMessage( MessageEventContent::text_plain("pong"), ); self.client.room_send(room.room_id(), content, None).await?; } _ => {} } } Ok(()) } } #[async_trait::async_trait] impl EventHandler for MyEventHandler { async fn on_room_message( &self, state: RoomState, event: &SyncMessageEvent<MessageEventContent>, ) { if let Err(err) = self.handle_message(state, event).await { error!("Error handling message {}", err); } } async fn on_stripped_state_member( &self, room: RoomState, room_member: &StrippedStateEvent<MemberEventContent>, _: Option<MemberEventContent>, ) { if room_member.state_key != self.client.user_id().await.unwrap() { return; } if let RoomState::Invited(room) = room { info!("Autojoining room {}", room.room_id()); let mut delay = 2; while let Err(err) = self.client.join_room_by_id(room.room_id()).await { error!( "Failed to join room {} ({:?}), retrying in {}s", room.room_id(), err, delay ); sleep(Duration::from_secs(delay)).await; delay *= 2; if delay > 3600 { error!("Can't join room {} ({:?})", room.room_id(), err); break; } } info!("Successfully joined room {}", room.room_id()); } } }
//! Handle damages use amethyst::{ ecs::{ReadStorage, System, WriteStorage, Component, DenseVecStorage, Entities, Write}, }; use specs_physics::events::{ProximityEvent, ProximityEvents}; use amethyst::core::shrev::{ReaderId}; /// Destroys entities which are destroyable. pub struct Destroyer { pub damage: f32 } impl Component for Destroyer { type Storage = DenseVecStorage<Self>; } /// Will be destroyed if collides with a Destroyer. pub struct Destroyable { pub health: f32 } impl Component for Destroyable { type Storage = DenseVecStorage<Self>; } // pub struct DestroySystem { reader: Option<ReaderId<ProximityEvent>> } impl Default for DestroySystem { fn default() -> Self { DestroySystem { reader: None } } } impl<'s> System<'s> for DestroySystem { type SystemData = ( ReadStorage<'s, Destroyer>, WriteStorage<'s, Destroyable>, Entities<'s>, Write<'s, ProximityEvents>, ); fn run(&mut self, (destroyers, mut destroyables, entities, mut channel): Self::SystemData) { if let None = self.reader { self.reader = Some(channel.register_reader()); } if let Some(reader) = &mut self.reader { for collision in channel.read(reader) { if let (Some(destroyable), Some(destroyer)) = (destroyables.get_mut(collision.collider1), destroyers.get(collision.collider2)) { let collider = collision.collider1.clone(); destroyable.health -= destroyer.damage; if destroyable.health < 0.0 { if let Err(error) = entities.delete(collider) { warn!("Couldn't remove entity {} with zero health: {}", collider.id(), error); } } } if let (Some(destroyable), Some(destroyer)) = (destroyables.get_mut(collision.collider2), destroyers.get(collision.collider1)) { info!("Damage Collision"); let collider = collision.collider2.clone(); destroyable.health -= destroyer.damage; if destroyable.health < 0.0 { if let Err(error) = entities.delete(collider) { warn!("Couldn't remove entity {} with zero health: {}", collider.id(), error); } } } } } } }
use std::time::Duration; pub const TRAIN_ACCELERATION: u32 = 2; pub trait CurrentMovable { fn accelerate(&mut self, t: Duration) -> i32; fn decelerate(&mut self, t: Duration) -> i32; fn print(&self); } #[derive(Debug)] pub struct CurrentTrain { current_v: i32, } impl CurrentTrain { pub fn new(v: i32) -> CurrentTrain { CurrentTrain { current_v: v } } } impl CurrentMovable for CurrentTrain { fn print(&self) { println!("Current ride {:?}", self); } fn accelerate(&mut self, t: Duration) -> i32 { self.current_v = self.current_v + (TRAIN_ACCELERATION * t.as_secs() as u32) as i32; self.current_v } fn decelerate(&mut self, t: Duration) -> i32 { self.current_v = self.current_v - (TRAIN_ACCELERATION * t.as_secs() as u32) as i32; self.current_v } } pub fn current_use() { println!("-------------------- {} --------------------", file!()); let mut c = CurrentTrain::new(12); c.print(); let d1 = Duration::new(5, 0); let d2 = Duration::new(12, 0); c.accelerate(d1); c.print(); c.decelerate(d1); c.print(); c.decelerate(d1); c.print(); c.decelerate(d2); c.print(); c.accelerate(d1); c.print(); }
mod adventofcode; use adventofcode::load_file; #[cfg(test)] mod tests { use spreadsheet_sum; #[test] fn test1() { let input = r#"5 1 9 5 7 5 3 2 4 6 8"#; assert_eq!(spreadsheet_sum(&input), 18); } } fn spreadsheet_sum(input: &str) -> i32 { let mut sum = 0; for line in input.lines() { let values: Vec<_> = line.split_whitespace() .map(|s| s.parse::<i32>().unwrap()) .collect(); let min = values.iter().min().unwrap(); let max = values.iter().max().unwrap(); let diff = max - min; sum += diff; } sum } fn main() { let input = load_file("inputs/02-1.txt").unwrap(); let sum = spreadsheet_sum(&input); println!("{}", sum); }
use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::{d5_2_hashmap_from_scratch, d7_44_blob_data_file::BlobError}; use std::io; pub fn read_value<V: DeserializeOwned, R: io::Read>(r: &mut R) -> Result<V, BlobError> { let result = bincode::deserialize_from(r)?; Ok(result) } pub fn write_value<V: Serialize, W: io::Write>(w: &mut W, v: V) -> Result<(), BlobError> { bincode::serialize_into(w, &v)?; Ok(()) } pub struct Blob { k: Vec<u8>, v: Vec<u8>, } impl Blob { pub fn from<K: Serialize, V: Serialize>(k: &K, v: &V) -> Result<Blob, BlobError> { let k = bincode::serialize(k)?; let v = bincode::serialize(v)?; Ok(Blob { k, v }) } pub fn write<W: io::Write>(&self, w: &mut W) -> Result<(), BlobError> { write_value(w, self.k.len())?; write_value(w, self.v.len())?; w.write_all(&self.k)?; w.write_all(&self.v)?; Ok(()) } pub fn read<R: io::Read>(r: &mut R) -> Result<Blob, failure::Error> { let k_len: usize = read_value(r)?; let v_len: usize = read_value(r)?; let mut k = vec![0_u8; k_len]; let mut v = vec![0_u8; v_len]; r.read_exact(&mut k)?; r.read_exact(&mut v)?; Ok(Blob { k, v }) } pub fn get_v<V: DeserializeOwned>(&self) -> Result<V, BlobError> { let result = bincode::deserialize(&self.v)?; Ok(result) } // Borrowed version of get_v(). // pub fn get_v_brw<'d, V: Deserialize<'d>>(&'d self) -> Result<V, BlobError> { let result = bincode::deserialize(&self.v)?; Ok(result) } pub fn deserialize<V: DeserializeOwned>(bindata: &[u8]) -> Result<V, bincode::Error> { bincode::deserialize(bindata) } pub fn deserialize_b<'d, V: Deserialize<'d>>(bindata: &'d [u8]) -> Result<V, bincode::Error> { bincode::deserialize(bindata) } pub fn len(&self) -> usize { 8 + 8 + self.k.len() + self.v.len() } pub fn k_hash(&self, seed: u64) -> u64 { d5_2_hashmap_from_scratch::hash(seed, &self.k) } pub fn key_match(&self, rhs: &Self) -> bool { self.k == rhs.k } } #[cfg(test)] mod test { use super::*; use serde_derive::*; #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct Point<T> { x: T, y: T, } #[test] fn test_read_write_string() { let k: i32 = 87; let v = "hello world"; let blob = Blob::from(&k, &v).unwrap(); { let mut fout = std::fs::OpenOptions::new() .write(true) .create(true) .open("/tmp/t_rblob.dat") .unwrap(); blob.write(&mut fout).unwrap(); } let mut fin = std::fs::File::open("/tmp/t_rblob.dat").unwrap(); let b2 = Blob::read(&mut fin).unwrap(); let v2: String = b2.get_v().unwrap(); assert_eq!(&v2, "hello world"); //It's just Bytes let p: Point<i32> = b2.get_v().unwrap(); assert_eq!(p, Point { x: 11, y: 0 }); } #[test] pub fn test_ser64() { let ndat = bincode::serialize(&0u64).unwrap(); assert_eq!(ndat.len(), 8); } }
use pattern::*; use haystack::Span; use memchr::{memchr, memrchr}; use std::ops::Range; #[derive(Debug, Clone)] pub struct CharSearcher { // safety invariant: `utf8_size` must be less than 5 utf8_size: usize, /// A utf8 encoded copy of the `needle` utf8_encoded: [u8; 4], } #[derive(Debug, Clone)] pub struct CharChecker(char); impl CharSearcher { #[inline] fn as_bytes(&self) -> &[u8] { &self.utf8_encoded[..self.utf8_size] } #[inline] fn last_byte(&self) -> u8 { self.utf8_encoded[self.utf8_size - 1] } #[inline] fn new(c: char) -> Self { let mut utf8_encoded = [0u8; 4]; let utf8_size = c.encode_utf8(&mut utf8_encoded).len(); CharSearcher { utf8_size, utf8_encoded, } } } unsafe impl Searcher<str> for CharSearcher { #[inline] fn search(&mut self, span: Span<&str>) -> Option<Range<usize>> { let (hay, range) = span.into_parts(); let mut finger = range.start; let bytes = hay.as_bytes(); loop { let index = memchr(self.last_byte(), &bytes[finger..range.end])?; finger += index + 1; if finger >= self.utf8_size { let found = &bytes[(finger - self.utf8_size)..finger]; if found == self.as_bytes() { return Some((finger - self.utf8_size)..finger); } } } } } unsafe impl Consumer<str> for CharChecker { #[inline] fn consume(&mut self, span: Span<&str>) -> Option<usize> { let (hay, range) = span.into_parts(); let mut utf8_encoded = [0u8; 4]; let encoded = self.0.encode_utf8(&mut utf8_encoded); let check_end = range.start + encoded.len(); if range.end < check_end { return None; } if unsafe { hay.as_bytes().get_unchecked(range.start..check_end) } == encoded.as_bytes() { Some(check_end) } else { None } } #[inline] fn trim_start(&mut self, hay: &str) -> usize { let mut checker = Pattern::<&str>::into_consumer(|c: char| c == self.0); checker.trim_start(hay) } } unsafe impl ReverseSearcher<str> for CharSearcher { #[inline] fn rsearch(&mut self, span: Span<&str>) -> Option<Range<usize>> { let (hay, range) = span.into_parts(); let start = range.start; let mut bytes = hay[range].as_bytes(); loop { let index = memrchr(self.last_byte(), bytes)? + 1; if index >= self.utf8_size { let found = &bytes[(index - self.utf8_size)..index]; if found == self.as_bytes() { let index = index + start; return Some((index - self.utf8_size)..index); } } bytes = &bytes[..(index - 1)]; } } } unsafe impl ReverseConsumer<str> for CharChecker { #[inline] fn rconsume(&mut self, span: Span<&str>) -> Option<usize> { // let (hay, range) = span.into_parts(); // let mut utf8_encoded = [0u8; 4]; // let encoded_len = self.0.encode_utf8(&mut utf8_encoded).len(); // let index = range.end.wrapping_sub(encoded_len); // if hay.as_bytes().get(range.start..index) == Some(&utf8_encoded[..encoded_len]) { // Some(index) // } else { // None // } let (hay, range) = span.into_parts(); let mut utf8_encoded = [0u8; 4]; let encoded = self.0.encode_utf8(&mut utf8_encoded); if range.start + encoded.len() > range.end { return None; } let check_start = range.end - encoded.len(); if unsafe { hay.as_bytes().get_unchecked(check_start..range.end) } == encoded.as_bytes() { Some(check_start) } else { None } } #[inline] fn trim_end(&mut self, haystack: &str) -> usize { let mut checker = Pattern::<&str>::into_consumer(|c: char| c == self.0); checker.trim_end(haystack) } } unsafe impl DoubleEndedSearcher<str> for CharSearcher {} unsafe impl DoubleEndedConsumer<str> for CharChecker {} macro_rules! impl_pattern { ($ty:ty) => { impl<'h> Pattern<$ty> for char { type Searcher = CharSearcher; type Consumer = CharChecker; #[inline] fn into_searcher(self) -> Self::Searcher { CharSearcher::new(self) } #[inline] fn into_consumer(self) -> Self::Consumer { CharChecker(self) } } } } impl_pattern!(&'h str); impl_pattern!(&'h mut str);
extern crate tuix; use tuix::*; //static THEME: &'static str = include_str!("themes/basic_theme.css"); fn main() { // Create the app let mut app = Application::new(|win_desc, state, window| { match state.insert_stylesheet("examples/themes/basic_theme.css") { Ok(_) => {}, Err(e) => println!("Error loading stylesheet: {}", e) } window.set_background_color(state, Color::rgb(255,255,255)); let one = Element::new().build(state, window, |builder| builder .class("one") .set_box_shadow_h_offset(Length::Pixels(2.5)) .set_box_shadow_v_offset(Length::Pixels(2.5)) .set_box_shadow_blur(Length::Pixels(10.0)) .set_box_shadow_color(Color::rgba(0,0,0,128)) ); //let two = Element::new().build(state, one, |builder| builder.class("two")); //let three = Element::new().build(state, two, |builder| builder.class("three")); // let four = Element::new().build(state, three, |builder| builder.class("four")); //let five = Element::new().build(state, four, |builder| builder.class("five")); //let outer = ScrollContainer::new().build(state, window, |builder| builder.class("container")); //outer = Element::new().build(state, window, |builder| builder.class("outer").set_scaley(1.0)); // let row = HBox::new().build(state, outer, |builder| { // builder // }); // Label::new("Button").build(state, row, |builder| builder); // Button::with_label("Press Me").build(state, row, |builder| builder); //let inner = Element::new().build(state, outer, |builder| builder.class("inner").set_clip_widget(outer)); //let inner = Element::new().build(state, outer, |builder| builder.class("inner2")); // let _innerinner = Element::new().build(state, outer, |builder| builder.class("inner2")); win_desc.with_title("basic") }); app.run(); }
use main_error::MainResult; // You can use plain strings (owned or not) as the error type. // NOTE: Uses the `MainResult` type as a shorthand for `Result<(), MainError>`. fn main() -> MainResult { // NOTE: The try-operator `?` is necessary for implicit conversion to `MainError`. Err("strings can be used as errors")?; Ok(()) }
// MinIO Rust Library for Amazon S3 Compatible Cloud Storage // Copyright 2022 MinIO, Inc. // // 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::s3::utils; use std::any::Any; pub trait Sse: std::fmt::Debug { fn headers(&self) -> utils::Multimap; fn copy_headers(&self) -> utils::Multimap; fn tls_required(&self) -> bool; fn as_any(&self) -> &dyn Any; } #[derive(Clone, Debug)] pub struct SseCustomerKey { headers: utils::Multimap, copy_headers: utils::Multimap, } impl SseCustomerKey { pub fn new(key: &str) -> SseCustomerKey { let b64key = utils::b64encode(key); let md5key = utils::md5sum_hash(key.as_bytes()); let mut headers = utils::Multimap::new(); headers.insert( String::from("X-Amz-Server-Side-Encryption-Customer-Algorithm"), String::from("AES256"), ); headers.insert( String::from("X-Amz-Server-Side-Encryption-Customer-Key"), b64key.clone(), ); headers.insert( String::from("X-Amz-Server-Side-Encryption-Customer-Key-MD5"), md5key.clone(), ); let mut copy_headers = utils::Multimap::new(); copy_headers.insert( String::from("X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm"), String::from("AES256"), ); copy_headers.insert( String::from("X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key"), b64key.clone(), ); copy_headers.insert( String::from("X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-MD5"), md5key.clone(), ); SseCustomerKey { headers: headers, copy_headers: copy_headers, } } } impl Sse for SseCustomerKey { fn headers(&self) -> utils::Multimap { self.headers.clone() } fn copy_headers(&self) -> utils::Multimap { self.copy_headers.clone() } fn tls_required(&self) -> bool { true } fn as_any(&self) -> &dyn Any { self } } #[derive(Clone, Debug)] pub struct SseKms { headers: utils::Multimap, } impl SseKms { pub fn new(key: &str, context: Option<&str>) -> SseKms { let mut headers = utils::Multimap::new(); headers.insert( String::from("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id"), key.to_string(), ); headers.insert( String::from("X-Amz-Server-Side-Encryption"), String::from("aws:kms"), ); if let Some(v) = context { headers.insert( String::from("X-Amz-Server-Side-Encryption-Context"), utils::b64encode(v), ); } SseKms { headers: headers } } } impl Sse for SseKms { fn headers(&self) -> utils::Multimap { self.headers.clone() } fn copy_headers(&self) -> utils::Multimap { utils::Multimap::new() } fn tls_required(&self) -> bool { true } fn as_any(&self) -> &dyn Any { self } } #[derive(Clone, Debug)] pub struct SseS3 { headers: utils::Multimap, } impl SseS3 { pub fn new() -> SseS3 { let mut headers = utils::Multimap::new(); headers.insert( String::from("X-Amz-Server-Side-Encryption"), String::from("AES256"), ); SseS3 { headers: headers } } } impl Sse for SseS3 { fn headers(&self) -> utils::Multimap { self.headers.clone() } fn copy_headers(&self) -> utils::Multimap { utils::Multimap::new() } fn tls_required(&self) -> bool { false } fn as_any(&self) -> &dyn Any { self } }
#[derive(Debug, Default, Clone)] struct Data { id: String, value: i32, } fn main() { let ds1 = vec![ Data { id: "d1".to_string(), value: 1}, Data { id: "d2".to_string(), value: 2}, ]; let ds2 = [ ds1.clone(), vec![Data { id: "d3".to_string(), value: 3 }] ].concat(); println!("{:?}", ds2); let ds3 = ds2.iter().cloned().chain( std::iter::once(Data { id: "d4".to_string(), value: 4 }) ).collect::<Vec<_>>(); println!("{:?}", ds3); }
use std::ffi::CString; #[cfg(feature = "img")] use image::DynamicImage; use libwebp_sys::*; #[cfg(feature = "img")] use image::*; use crate::{shared::*, Encoder}; pub struct AnimFrame<'a> { image: &'a [u8], layout: PixelLayout, width: u32, height: u32, timestamp: i32, config: Option<&'a WebPConfig>, } impl<'a> AnimFrame<'a> { pub fn new( image: &'a [u8], layout: PixelLayout, width: u32, height: u32, timestamp: i32, config: Option<&'a WebPConfig>, ) -> Self { Self { image, layout, width, height, timestamp, config, } } #[cfg(feature = "img")] pub fn from_image(image: &'a DynamicImage, timestamp: i32) -> Result<Self, &str> { match image { DynamicImage::ImageLuma8(_) => Err("Unimplemented"), DynamicImage::ImageLumaA8(_) => Err("Unimplemented"), DynamicImage::ImageRgb8(image) => Ok(Self::from_rgb( image.as_ref(), image.width(), image.height(), timestamp, )), DynamicImage::ImageRgba8(image) => Ok(Self::from_rgba( image.as_ref(), image.width(), image.height(), timestamp, )), _ => Err("Unimplemented"), } } /// Creates a new encoder from the given image data in the RGB pixel layout. pub fn from_rgb(image: &'a [u8], width: u32, height: u32, timestamp: i32) -> Self { Self::new(image, PixelLayout::Rgb, width, height, timestamp, None) } /// Creates a new encoder from the given image data in the RGBA pixel layout. pub fn from_rgba(image: &'a [u8], width: u32, height: u32, timestamp: i32) -> Self { Self::new(image, PixelLayout::Rgba, width, height, timestamp, None) } pub fn get_image(&self) -> &[u8] { &self.image } pub fn get_layout(&self) -> PixelLayout { self.layout } pub fn get_time_ms(&self) -> i32 { self.timestamp } pub fn width(&self) -> u32 { self.width } pub fn height(&self) -> u32 { self.height } } impl<'a> From<&'a AnimFrame<'a>> for Encoder<'a> { fn from(f: &'a AnimFrame) -> Self { Encoder::new(f.get_image(), f.layout, f.width, f.height) } } #[cfg(feature = "img")] impl Into<DynamicImage> for &AnimFrame<'_> { fn into(self) -> DynamicImage { if self.layout.is_alpha() { let image = ImageBuffer::from_raw(self.width(), self.height(), self.get_image().to_owned()) .expect("ImageBuffer couldn't be created"); DynamicImage::ImageRgba8(image) } else { let image = ImageBuffer::from_raw(self.width(), self.height(), self.get_image().to_owned()) .expect("ImageBuffer couldn't be created"); DynamicImage::ImageRgb8(image) } } } pub struct AnimEncoder<'a> { frames: Vec<AnimFrame<'a>>, width: u32, height: u32, config: &'a WebPConfig, muxparams: WebPMuxAnimParams, } impl<'a> AnimEncoder<'a> { pub fn new(width: u32, height: u32, config: &'a WebPConfig) -> Self { Self { frames: vec![], width, height, config, muxparams: WebPMuxAnimParams { bgcolor: 0, loop_count: 0, }, } } pub fn set_bgcolor(&mut self, rgba: [u8; 4]) { let bgcolor = (u32::from(rgba[3]) << 24) + (u32::from(rgba[2]) << 16) + (u32::from(rgba[1]) << 8) + (u32::from(rgba[0])); self.muxparams.bgcolor = bgcolor; } pub fn set_loop_count(&mut self, loop_count: i32) { self.muxparams.loop_count = loop_count; } pub fn add_frame(&mut self, frame: AnimFrame<'a>) { self.frames.push(frame); } pub fn encode(&self) -> WebPMemory { self.try_encode().unwrap() } pub fn try_encode(&self) -> Result<WebPMemory, AnimEncodeError> { unsafe { anim_encode(&self) } } } #[derive(Debug)] pub enum AnimEncodeError { WebPEncodingError(WebPEncodingError), WebPMuxError(WebPMuxError), WebPAnimEncoderGetError(String), } unsafe fn anim_encode(all_frame: &AnimEncoder) -> Result<WebPMemory, AnimEncodeError> { let width = all_frame.width; let height = all_frame.height; let mut uninit = std::mem::MaybeUninit::<WebPAnimEncoderOptions>::uninit(); let mux_abi_version = WebPGetMuxABIVersion(); WebPAnimEncoderOptionsInitInternal(uninit.as_mut_ptr(), mux_abi_version); let encoder = WebPAnimEncoderNewInternal( width as i32, height as i32, uninit.as_ptr(), mux_abi_version, ); let mut frame_pictures = vec![]; for frame in all_frame.frames.iter() { let mut pic = crate::new_picture(frame.image, frame.layout, width, height); let config = frame.config.unwrap_or(all_frame.config); let ok = WebPAnimEncoderAdd( encoder, &mut *pic as *mut _, frame.timestamp as std::os::raw::c_int, config, ); if ok == 0 { //ok == false WebPAnimEncoderDelete(encoder); return Err(AnimEncodeError::WebPEncodingError(pic.error_code)); } frame_pictures.push(pic); } WebPAnimEncoderAdd(encoder, std::ptr::null_mut(), 0, std::ptr::null()); let mut webp_data = std::mem::MaybeUninit::<WebPData>::uninit(); let ok = WebPAnimEncoderAssemble(encoder, webp_data.as_mut_ptr()); if ok == 0 { //ok == false let cstring = WebPAnimEncoderGetError(encoder); let cstring = CString::from_raw(cstring as *mut _); let string = cstring.to_string_lossy().to_string(); WebPAnimEncoderDelete(encoder); return Err(AnimEncodeError::WebPAnimEncoderGetError(string)); } WebPAnimEncoderDelete(encoder); let mux = WebPMuxCreateInternal(webp_data.as_ptr(), 1, mux_abi_version); let mux_error = WebPMuxSetAnimationParams(mux, &all_frame.muxparams); if mux_error != WebPMuxError::WEBP_MUX_OK { return Err(AnimEncodeError::WebPMuxError(mux_error)); } let mut raw_data: WebPData = webp_data.assume_init(); WebPDataClear(&mut raw_data); let mut webp_data = std::mem::MaybeUninit::<WebPData>::uninit(); WebPMuxAssemble(mux, webp_data.as_mut_ptr()); WebPMuxDelete(mux); let raw_data: WebPData = webp_data.assume_init(); Ok(WebPMemory(raw_data.bytes as *mut u8, raw_data.size)) }
//! Implementations related to single rules. use crate::types::*; use crate::{ filter::{Filter, Filterable}, tokenizer::{finalize, Tokenizer}, utils, }; use itertools::Itertools; use log::{error, info, warn}; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use std::fmt; pub(crate) mod disambiguation; pub(crate) mod engine; pub(crate) mod grammar; use engine::Engine; pub(crate) use engine::composition::MatchGraph; pub use grammar::Example; use self::{ disambiguation::POSFilter, engine::{composition::GraphId, EngineMatches}, }; /// A *Unification* makes an otherwise matching pattern invalid if no combination of its filters /// matches all tokens marked with "unify". /// Can also be negated. #[derive(Serialize, Deserialize, Debug)] pub(crate) struct Unification { pub(crate) mask: Vec<Option<bool>>, pub(crate) filters: Vec<Vec<POSFilter>>, } impl Unification { pub fn keep(&self, graph: &MatchGraph, tokens: &[Token]) -> bool { let filters: Vec<_> = self.filters.iter().multi_cartesian_product().collect(); let mut filter_mask: Vec<_> = filters.iter().map(|_| true).collect(); let negate = self.mask.iter().all(|x| x.map_or(true, |x| !x)); for (group, maybe_mask_val) in graph.groups()[1..].iter().zip(self.mask.iter()) { if maybe_mask_val.is_some() { for token in group.tokens(tokens) { for (mask_val, filter) in filter_mask.iter_mut().zip(filters.iter()) { *mask_val = *mask_val && POSFilter::and(filter, &token.word); } } } } let result = filter_mask.iter().any(|x| *x); if negate { !result } else { result } } } /// A disambiguation rule. /// Changes the information associcated with one or more tokens if it matches. /// Sourced from LanguageTool. An example of how a simple rule might look in the original XML format: /// /// ```xml /// <rule id="NODT_HAVE" name="no determiner + have as verb/noun ->have/verb"> /// <pattern> /// <token> /// <exception postag="PRP$"></exception> /// <exception regexp="yes">the|a</exception> /// </token> /// <marker> /// <token case_sensitive="yes" regexp="yes">[Hh]ave|HAVE</token> /// </marker> /// </pattern> /// <disambig action="replace"><wd lemma="have" pos="VB"></wd></disambig> /// </rule> /// ``` #[derive(Serialize, Deserialize)] pub struct DisambiguationRule { pub(crate) id: String, pub(crate) engine: Engine, pub(crate) disambiguations: disambiguation::Disambiguation, pub(crate) filter: Option<Filter>, pub(crate) start: GraphId, pub(crate) end: GraphId, pub(crate) examples: Vec<disambiguation::DisambiguationExample>, pub(crate) unification: Option<Unification>, } #[derive(Default)] pub(crate) struct Changes(Vec<Vec<HashSet<(usize, usize)>>>); impl Changes { pub fn is_empty(&self) -> bool { self.0.is_empty() } } impl DisambiguationRule { /// Get a unique identifier of this rule. pub fn id(&self) -> &str { self.id.as_str() } pub(crate) fn apply<'t>(&'t self, tokens: &[Token<'t>], tokenizer: &Tokenizer) -> Changes { if matches!(self.disambiguations, disambiguation::Disambiguation::Nop) { return Changes::default(); } let mut all_byte_spans = Vec::new(); for graph in self.engine.get_matches(tokens, self.start, self.end) { if let Some(unification) = &self.unification { if !unification.keep(&graph, tokens) { continue; } } if let Some(filter) = &self.filter { if !filter.keep(&graph, tokenizer) { continue; } } let mut byte_spans = Vec::new(); for group_idx in GraphId::range(&self.start, &self.end) { let group = graph.by_id(group_idx); let group_byte_spans: HashSet<_> = group.tokens(graph.tokens()).map(|x| x.byte_span).collect(); byte_spans.push(group_byte_spans); } all_byte_spans.push(byte_spans); } Changes(all_byte_spans) } pub(crate) fn change<'t>( &'t self, tokens: &mut Vec<IncompleteToken<'t>>, tokenizer: &Tokenizer, changes: Changes, ) { log::info!("applying {}", self.id); for byte_spans in changes.0 { let mut groups = Vec::new(); let mut refs = tokens.iter_mut().collect::<Vec<_>>(); for group_byte_spans in byte_spans { let mut group = Vec::new(); while let Some(i) = refs .iter() .position(|x| group_byte_spans.contains(&x.byte_span)) { group.push(refs.remove(i)); } groups.push(group); } self.disambiguations .apply(groups, tokenizer.options().retain_last); } } /// Often there are examples associated with a rule. /// This method checks whether the correct action is taken in the examples. pub fn test(&self, tokenizer: &Tokenizer) -> bool { let mut passes = Vec::new(); for (i, test) in self.examples.iter().enumerate() { let text = match test { disambiguation::DisambiguationExample::Unchanged(x) => x.as_str(), disambiguation::DisambiguationExample::Changed(x) => x.text.as_str(), }; // by convention examples are always considered as one sentence even if the sentencizer would split let tokens_before = tokenizer.disambiguate_up_to_id(tokenizer.tokenize(text), Some(&self.id)); let finalized = finalize(tokens_before.clone()); let changes = self.apply(&finalized, tokenizer); let tokens_before: Vec<_> = tokens_before.into_iter().map(|x| x.0).collect(); let mut tokens_after: Vec<_> = tokens_before.clone(); if !changes.is_empty() { self.change(&mut tokens_after, tokenizer, changes); } info!("Tokens: {:#?}", tokens_before); let pass = match test { disambiguation::DisambiguationExample::Unchanged(_) => { tokens_before == tokens_after } disambiguation::DisambiguationExample::Changed(change) => { let _before = tokens_before .iter() .find(|x| x.char_span == change.char_span) .unwrap(); let after = tokens_after .iter() .find(|x| x.char_span == change.char_span) .unwrap(); let unordered_tags = after .word .tags .iter() .map(|x| x.to_owned_word_data()) .collect::<HashSet<owned::WordData>>(); // need references to compare let unordered_tags: HashSet<_> = unordered_tags.iter().collect(); let unordered_tags_change = change .after .tags .iter() .collect::<HashSet<&owned::WordData>>(); after.word.text == change.after.text.as_ref_id() && unordered_tags == unordered_tags_change } }; if !pass { let error_str = format!( "Rule {}: Test \"{:#?}\" failed. Before: {:#?}. After: {:#?}.", self.id, test, tokens_before.into_iter().collect::<Vec<_>>(), tokens_after.into_iter().collect::<Vec<_>>(), ); if tokenizer .options() .known_failures .contains(&format!("{}:{}", self.id, i)) { warn!("{}", error_str) } else { error!("{}", error_str) } } passes.push(pass); } passes.iter().all(|x| *x) } } pub struct Suggestions<'a, 't> { rule: &'a Rule, tokenizer: &'a Tokenizer, matches: EngineMatches<'a, 't>, tokens: &'t [Token<'t>], } impl<'a, 't> Iterator for Suggestions<'a, 't> { type Item = Suggestion; fn next(&mut self) -> Option<Self::Item> { let rule = self.rule; let tokenizer = self.tokenizer; let tokens = self.tokens; let (start, end) = (self.rule.start, self.rule.end); self.matches.find_map(|graph| { if let Some(unification) = &rule.unification { if !unification.keep(&graph, tokens) { return None; } } let start_group = graph.by_id(start); let end_group = graph.by_id(end); let replacements: Vec<String> = rule .suggesters .iter() .filter_map(|x| x.apply(&graph, tokenizer, start, end)) .collect(); let start = if replacements .iter() .all(|x| utils::no_space_chars().chars().any(|c| x.starts_with(c))) { let first_token = graph.groups()[graph.get_index(start)..] .iter() .find_map(|x| x.tokens(graph.tokens()).next()) .unwrap(); let idx = tokens .iter() .position(|x| std::ptr::eq(x, first_token)) .unwrap_or(0); if idx > 0 { tokens[idx - 1].char_span.1 } else { start_group.char_span.0 } } else { start_group.char_span.0 }; let end = end_group.char_span.1; // fix e. g. "Super , dass" let replacements: Vec<String> = replacements .into_iter() .map(|x| utils::fix_nospace_chars(&x)) .collect(); if !replacements.is_empty() { Some(Suggestion { message: rule .message .apply(&graph, tokenizer, rule.start, rule.end) .expect("Rules must have a message."), source: rule.id.to_string(), start, end, replacements, }) } else { None } }) } } /// A grammar rule. /// Returns a [Suggestion][crate::types::Suggestion] for change if it matches. /// Sourced from LanguageTool. An example of how a simple rule might look in the original XML format: /// /// ```xml /// <rule id="DOSNT" name="he dosn't (doesn't)"> /// <pattern> /// <token regexp="yes">do[se]n|does|dosan|doasn|dosen</token> /// <token regexp="yes">['’`´‘]</token> /// <token>t</token> /// </pattern> /// <message>Did you mean <suggestion>doesn\2t</suggestion>?</message> /// <example correction="doesn't">He <marker>dosn't</marker> know about it.</example> /// </rule> /// ``` #[derive(Serialize, Deserialize, Debug)] pub struct Rule { pub(crate) id: String, pub(crate) engine: Engine, pub(crate) examples: Vec<Example>, pub(crate) suggesters: Vec<grammar::Synthesizer>, pub(crate) message: grammar::Synthesizer, pub(crate) start: GraphId, pub(crate) end: GraphId, pub(crate) on: bool, pub(crate) url: Option<String>, pub(crate) short: Option<String>, pub(crate) name: String, pub(crate) category_id: String, pub(crate) category_name: String, pub(crate) category_type: Option<String>, pub(crate) unification: Option<Unification>, } impl fmt::Display for Rule { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}/{}", self.id.as_str(), self.name.as_str()) } } impl Rule { /// Get a unique identifier of this rule. pub fn id(&self) -> &str { self.id.as_str() } /// Get whether this rule is "turned on" i. e. whether it should be used by the rule set. pub fn on(&self) -> bool { self.on } /// Gets a short text describing this rule e.g. "Possible typo" if there is one. pub fn short(&self) -> Option<&str> { self.short.as_deref() } /// Gets an url with more information about this rule if there is one. pub fn url(&self) -> Option<&str> { self.url.as_deref() } /// Gets the examples associated with this rule. pub fn examples(&self) -> &[Example] { &self.examples } /// Turn this rule on. pub fn set_on(&mut self, on: bool) { self.on = on; } /// Gets a human-readable name of this rule. pub fn name(&self) -> &str { &self.name } /// Gets the ID of the category this rule is in. pub fn category_id(&self) -> &str { &self.category_id } /// Gets a human-readable name of the category this rule is in. pub fn category_name(&self) -> &str { &self.category_name } /// Gets the type of the category this rule is in e. g. "style" or "grammar". pub fn category_type(&self) -> Option<&str> { self.category_type.as_deref() } pub(crate) fn apply<'a, 't>( &'a self, tokens: &'t [Token<'t>], tokenizer: &'a Tokenizer, ) -> Suggestions<'a, 't> { Suggestions { matches: self.engine.get_matches(tokens, self.start, self.end), rule: &self, tokenizer, tokens, } } /// Grammar rules always have at least one example associated with them. /// This method checks whether the correct action is taken in the examples. pub fn test(&self, tokenizer: &Tokenizer) -> bool { let mut passes = Vec::new(); for test in self.examples.iter() { // by convention examples are always considered as one sentence even if the sentencizer would split let tokens = finalize(tokenizer.disambiguate(tokenizer.tokenize(&test.text()))); info!("Tokens: {:#?}", tokens); let suggestions: Vec<_> = self.apply(&tokens, tokenizer).collect(); let pass = if suggestions.len() > 1 { false } else { match test.suggestion() { Some(correct_suggestion) => { suggestions.len() == 1 && correct_suggestion == &suggestions[0] } None => suggestions.is_empty(), } }; if !pass { warn!( "Rule {}: test \"{}\" failed. Expected: {:#?}. Found: {:#?}.", self.id, test.text(), test.suggestion(), suggestions ); } passes.push(pass); } passes.iter().all(|x| *x) } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Fairly minimal recursive-descent parser helper functions and types. use std::fmt; #[derive(Clone, Debug)] pub struct Location { pub line: usize, pub col: usize, pub file: String, } impl Location { fn new(file: String) -> Self { Location { line: 0, col: 0, file, } } pub fn is_null(&self) -> bool { self.line == 0 } } #[derive(Clone, Debug)] pub struct Span { pub start: Location, pub end: Location, } impl Span { pub fn new(file: String) -> Self { Span { start: Location::new(file.clone()), end: Location::new(file), } } pub fn is_null(&self) -> bool { self.start.is_null() && self.end.is_null() } } #[derive(Clone, Debug)] pub struct Spanned<T> { pub data: T, pub span: Span, } impl<T> Spanned<T> { pub fn new(span: Span, data: T) -> Self { Spanned { data, span } } } /// Every bit set but the high bit in usize. const OFF_MASK: usize = <usize>::max_value() / 2; /// Only the high bit in usize. const FATAL_MASK: usize = !OFF_MASK; /// An error produced by pipdl pub struct ParserError { message: String, fatal: bool, span: Span, } impl ParserError { pub(crate) fn is_fatal(&self) -> bool { self.fatal } pub(crate) fn make_fatal(mut self) -> Self { self.fatal = true; self } pub(crate) fn span(&self) -> Span { self.span.clone() } pub(crate) fn message(&self) -> &str { &self.message } } impl fmt::Debug for ParserError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Error") .field("file", &self.span.start.file) .field("start_line", &self.span.start.line) .field("start_column", &self.span.start.col) .field("end_line", &self.span.end.line) .field("end_column", &self.span.end.col) .finish() } } /// Attempts to run each expression in order, recovering from any non-fatal /// errors and attempting the next option. macro_rules! any { ($i:ident, $expected:expr, $($e:expr => |$x:ident| $f:expr),+ $(,)*) => { // NOTE: We have to do this sorcery for early returns. Using a loop with breaks makes clippy // mad because the loop never loops and we can't desable the lint because we're not in a function. // Also, we don't directly call the closure otherwise clippy would also complain about that. Yeah. { let mut my_closure = || { $(match $e { Ok((i, $x)) => return Ok((i, $f)), Err(e) => { // This assignment is used to help out with type inference. let e: $crate::util::ParserError = e; if e.is_fatal() { return Err(e); } } })+ return $i.expected($expected); }; my_closure() } }; ($i:ident, $expected:expr, $($e:expr => $f:expr),+ $(,)*) => { any!($i, $expected, $($e => |_x| $f),+); } } /// Attempts to repeatedly run the expression, stopping on a non-fatal error, /// and directly returning any fatal error. macro_rules! drive { ($i:ident, $e:expr) => { let mut $i = $i; loop { match $e { Ok((j, _)) => $i = j, Err(e) => if e.is_fatal() { return Err(e); } else { break; }, } } }; } /// The type of error used by internal parsers pub(crate) type PResult<'src, T> = Result<(In<'src>, T), ParserError>; /// Specify that after this point, errors produced while parsing which are not /// handled should instead be treated as fatal parsing errors. macro_rules! commit { ($($e:tt)*) => { // Evaluate the inner expression, transforming errors into fatal errors. let eval = || { $($e)* }; eval().map_err($crate::util::ParserError::make_fatal) } } /// This datastructure is used as the cursor type into the input source data. It /// holds the full source string, and the current offset. #[derive(Clone, Debug)] pub(crate) struct In<'src> { src: &'src str, byte_offset: usize, loc: Location, } impl<'src> In<'src> { pub(crate) fn new(s: &'src str, file: String) -> Self { In { src: s, byte_offset: 0, loc: Location { line: 1, col: 0, file, }, } } /// The remaining string in the source file. pub(crate) fn rest(&self) -> &'src str { &self.src[self.byte_offset..] } /// Move the cursor forward by `n` characters. pub(crate) fn advance(&self, n_chars: usize) -> Self { let mut loc = self.loc.clone(); let (n_bytes, last_c) = self .rest() .char_indices() .take(n_chars) .inspect(|&(_, character)| { if character == '\n' { loc.line += 1; loc.col = 0; } else { loc.col += 1; } }) .last() .expect("No characters remaining in advance"); let byte_offset = self .byte_offset .checked_add(n_bytes + last_c.len_utf8()) .expect("Failed checked add"); assert!(byte_offset <= self.src.len()); In { src: self.src, byte_offset, loc, } } /// Produce a new non-fatal error result with the given expected value. pub(crate) fn expected<T>(&self, expected: &'static str) -> Result<T, ParserError> { assert!((self.byte_offset & FATAL_MASK) == 0, "Offset is too large!"); // Get the line where the error occurred. let text = self.src.lines().nth(self.loc.line - 1).unwrap_or(""); // Usually happens when the error occurs on the last, empty line // Format the final error message. let message = format!( "{}\n\ | {}\n{:~>off$}^\n", format!("Expected {}", expected), text, "", off = self.loc.col + 2 ); Err(ParserError { message, fatal: false, span: Span { start: self.loc.clone(), end: self.loc.clone(), }, }) } pub(crate) fn loc(&self) -> Location { self.loc.clone() } } /// Repeatedly run f, collecting results into a vec. Returns an error if a fatal /// error is produced while parsing. pub(crate) fn many<'src, F, R>(i: In<'src>, mut f: F) -> PResult<'src, Vec<R>> where F: FnMut(In<'src>) -> PResult<'src, R>, { let mut v = Vec::new(); drive!( i, match f(i.clone()) { Ok((i, x)) => { v.push(x); Ok((i, ())) } Err(e) => Err(e), } ); Ok((i, v)) } /// Repeatedly run f, followed by parsing the seperator sep. Returns an error if /// a fatal error is produced while parsing. pub(crate) fn sep<'src, Parser, Ret>( i: In<'src>, mut parser: Parser, sep: &'static str, ) -> PResult<'src, Vec<Ret>> where Parser: FnMut(In<'src>) -> PResult<'src, Ret>, { let mut return_vector = Vec::new(); drive!( i, match parser(i.clone()) { Ok((i, result)) => { return_vector.push(result); match punct(i.clone(), sep) { Ok(o) => Ok(o), Err(_) => return Ok((i, return_vector)), } } Err(e) => Err(e), } ); Ok((i, return_vector)) } /// Skip any leading whitespace, including comments pub(crate) fn skip_ws(mut i: In) -> Result<In, ParserError> { loop { if i.rest().is_empty() { break; } let c = i .rest() .chars() .next() .expect("No characters remaining when skipping ws"); if c.is_whitespace() { i = i.advance(1); continue; } // Line comments if i.rest().starts_with("//") { while !i.rest().starts_with('\n') { i = i.advance(1); if i.rest().is_empty() { break; } } continue; } // Block comments if i.rest().starts_with("/*") { while !i.rest().starts_with("*/") { i = i.advance(1); if i.rest().is_empty() { return i.expected("end of block comment (`*/`)"); } } i = i.advance(2); continue; } break; } Ok(i) } /// Read an identifier as a string. pub(crate) fn ident(i: In) -> PResult<Spanned<String>> { let i = skip_ws(i)?; let start = i.loc(); let (end_char, end_byte) = i .rest() .char_indices() .enumerate() .skip_while(|&(_, (b_idx, c))| match c { '_' | 'a'...'z' | 'A'...'Z' => true, '0'...'9' if b_idx != 0 => true, _ => false, }) .next() .map(|(c_idx, (b_idx, _))| (c_idx, b_idx)) .unwrap_or((i.rest().chars().count(), i.rest().len())); if end_byte == 0 { return i.expected("identifier"); } let j = i.advance(end_char); let end = j.loc(); Ok(( j, Spanned::new(Span { start, end }, i.rest()[..end_byte].to_owned()), )) } /// Parse a specific keyword. pub(crate) fn kw<'src>(i: In<'src>, kw: &'static str) -> PResult<'src, Spanned<()>> { let error_message = i.expected(kw); let (i, id) = ident(i)?; if id.data == kw { Ok((i, Spanned::new(id.span, ()))) } else { error_message } } /// Parse punctuation. pub(crate) fn punct<'src>(i: In<'src>, p: &'static str) -> PResult<'src, Spanned<()>> { let i = skip_ws(i)?; let start = i.loc(); if i.rest().starts_with(p) { let i = i.advance(p.chars().count()); let end = i.loc(); Ok((i, Spanned::new(Span { start, end }, ()))) } else { i.expected(p) } } /// Try to parse the inner value, and return Some() if it succeeded, None if it /// failed non-fatally, and an error if it failed fatally. pub(crate) fn maybe<'src, T>(i: In<'src>, r: PResult<'src, T>) -> PResult<'src, Option<T>> { match r { Ok((i, x)) => Ok((i, Some(x))), Err(e) => if e.is_fatal() { Err(e) } else { Ok((i, None)) }, } } /// Parse a string literal. pub(crate) fn string(i: In) -> PResult<Spanned<String>> { let mut s = String::new(); let start = i.loc(); let (i, _) = punct(i, "\"")?; let mut chars = i.rest().chars().enumerate().peekable(); while let Some((char_offset, ch)) = chars.next() { match ch { '"' => { let i = i.advance(char_offset + 1); let end = i.loc(); return Ok((i, Spanned::new(Span { start, end }, s))); } '\\' => match chars.next() { Some((_, 'n')) => s.push('\n'), Some((_, 'r')) => s.push('\r'), Some((_, 't')) => s.push('\t'), Some((_, '\\')) => s.push('\\'), Some((_, '\'')) => s.push('\''), Some((_, '"')) => s.push('"'), Some((_, '0')) => s.push('\0'), _ => { return i .advance(char_offset) .expected("valid escape (\\n, \\r, \\t, \\\\, \\', \\\", or \\0)") } }, x => s.push(x), } } i.expected("end of string literal (\")") }
use super::Schedule; use crate::calendar::{CalendarRequest, LongtermHandling}; use bitflags::bitflags; use chrono::{naive::MIN_DATE, Duration, NaiveDate, TimeZone, Utc}; use icalendar::{Component, Event as IcalEvent}; use std::collections::{BTreeMap, HashSet}; use std::rc::Rc; pub(super) fn generate_events( schedules: Vec<Schedule>, cal_req: &CalendarRequest, ) -> Vec<IcalEvent> { let language: &str = &cal_req.language; match cal_req.longterm { LongtermHandling::Preserve => generate_events_preserve(schedules, language), LongtermHandling::Split => generate_events_split(schedules, language), LongtermHandling::Aggregate => generate_events_aggregate(schedules, language), } } trait ScheduleHelper { fn start_date(&self) -> NaiveDate; fn end_date(&self) -> NaiveDate; } impl ScheduleHelper for Schedule { fn start_date(&self) -> NaiveDate { self.start.naive_local().date() } fn end_date(&self) -> NaiveDate { self.end.naive_local().date() } } #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] enum EventPhase { // order of definition here prescribes order in which the entries appear in lists Begin, BeginEnd, End, Continued, } impl EventPhase { fn prefix(self, lang: &str) -> &'static str { // TODO: poor man's localization match (self, lang) { (EventPhase::Begin, "cs") => "Začátek: ", (EventPhase::Begin, _) => "Begin: ", (EventPhase::BeginEnd, "cs") => "Začátek a konec: ", (EventPhase::BeginEnd, _) => "Begin and end: ", (EventPhase::End, "cs") => "Konec: ", (EventPhase::End, _) => "End: ", (EventPhase::Continued, "cs") => "Pokračující: ", (EventPhase::Continued, _) => "Continued: ", } } fn format_count(self, count: usize, _lang: &str) -> String { // TODO: localise match self { EventPhase::Begin => format!("{} beginning", count), EventPhase::End => format!("{} ending", count), EventPhase::Continued => format!("{} continued", count), EventPhase::BeginEnd => unimplemented!("should not be used"), } } } fn generate_events_preserve(schedules: Vec<Schedule>, language: &str) -> Vec<IcalEvent> { schedules.iter().map(|s| create_ical_event(s, language)).collect() } fn generate_events_split(schedules: Vec<Schedule>, language: &str) -> Vec<IcalEvent> { let mut events: Vec<IcalEvent> = Vec::new(); for schedule in schedules { if schedule.is_long_term { let mut first_day_schedule = schedule.clone(); first_day_schedule.id = 1_000_000_000_000 + schedule.id; Rc::make_mut(&mut first_day_schedule.event).name = format!("{}{}", EventPhase::Begin.prefix(language), schedule.event.name); first_day_schedule.end = schedule.start.date().and_hms(0, 0, 0) + Duration::days(1); events.push(create_ical_event(&first_day_schedule, language)); let mut last_day_schedule = schedule.clone(); last_day_schedule.id = 2_000_000_000_000 + schedule.id; Rc::make_mut(&mut last_day_schedule.event).name = format!("{}{}", EventPhase::End.prefix(language), schedule.event.name); last_day_schedule.start = schedule.end.date().and_hms(0, 0, 0) - Duration::days(1); events.push(create_ical_event(&last_day_schedule, language)); } else { events.push(create_ical_event(&schedule, language)); } } events } #[derive(Debug, Default)] struct BreakDay<'a> { starts: Vec<&'a Schedule>, end_ids: HashSet<u64>, // exclusive, if schedule ends on day 23, we include it in day 24 } type BreakDayMap<'a> = BTreeMap<NaiveDate, BreakDay<'a>>; fn generate_events_aggregate(schedules: Vec<Schedule>, lang: &str) -> Vec<IcalEvent> { // TODO: possibly made more incremental by using forceSortByStart=ASC and tweaking algorithm. let mut events: Vec<IcalEvent> = Vec::new(); let mut breakdays: BreakDayMap = BTreeMap::new(); for schedule in schedules.iter() { if !schedule.is_long_term { events.push(create_ical_event(schedule, lang)); continue; } let start_breakday = breakdays.entry(schedule.start_date()).or_default(); start_breakday.starts.push(schedule); let end_breakday = breakdays.entry(schedule.end_date()).or_default(); end_breakday.end_ids.insert(schedule.id); } render_events_from_breakdays(&mut events, &breakdays, lang); events } fn render_events_from_breakdays(events: &mut Vec<IcalEvent>, breakdays: &BreakDayMap, lang: &str) { let mut date_cursor: NaiveDate = MIN_DATE; let mut active_schedules: Vec<&Schedule> = Vec::new(); for (&date, breakday) in breakdays.iter() { if !active_schedules.is_empty() { events.push(render_aggregate_event(date_cursor, date, &active_schedules, lang)); } active_schedules.retain(|s| !breakday.end_ids.contains(&s.id)); active_schedules.extend_from_slice(&breakday.starts); date_cursor = date; } assert_eq!(active_schedules.len(), 0, "Active schedules not exhausted.") } fn render_aggregate_event( start: NaiveDate, end: NaiveDate, schedules: &Vec<&Schedule>, lang: &str, ) -> IcalEvent { assert_ne!(schedules.len(), 0, "render_aggregate_event() must have at least 1 schedule."); let mut ical_event = IcalEvent::new(); ical_event.uid(&format!("LongTermSchedule{}@goout.net", start)); // icalendar currently needs Date (with timezone), but doesn't actually use the TZ. Convert. ical_event.start_date(Utc.from_utc_date(&start)); ical_event.end_date(Utc.from_utc_date(&end)); if schedules.len() == 1 { let schedule = schedules[0]; fill_basic_ical_event_props(&mut ical_event, schedule, lang); ical_event.description(&format!( "{} - {}\n\n{}", schedule.start_date(), schedule.end_date(), get_description(schedule, OptionalDescFields::default()) )); return ical_event; } set_dtstamp(&mut ical_event, schedules[0]); let mut categorised: BTreeMap<EventPhase, Vec<&Schedule>> = BTreeMap::new(); let mut counts: BTreeMap<EventPhase, usize> = BTreeMap::new(); for s in schedules.iter() { use EventPhase::*; let phase = match (s.start_date() == start, s.end_date() == end) { (true, true) => BeginEnd, (true, false) => Begin, (false, true) => End, (false, false) => Continued, }; categorised.entry(phase).or_default().push(s); let count_phases = if phase == BeginEnd { vec![Begin, End] } else { vec![phase] }; for count_phase in count_phases { *counts.entry(count_phase).or_default() += 1; } } ical_event.summary( &counts .into_iter() .map(|(phase, len)| phase.format_count(len, lang)) .collect::<Vec<_>>() .join(", "), ); ical_event.description( &categorised .iter() .flat_map(|(phase, schedules)| { schedules.iter().map(move |s| get_longterm_part_description(*phase, s, lang)) }) .collect::<Vec<_>>() .join("\n\n"), ); ical_event } fn get_longterm_part_description(phase: EventPhase, schedule: &Schedule, lang: &str) -> String { format!( "{}{}\n{} - {}\n{}", phase.prefix(lang), get_summary(schedule, lang), schedule.start_date(), schedule.end_date(), get_description(schedule, OptionalDescFields::empty()) ) } fn fill_basic_ical_event_props(ical_event: &mut IcalEvent, schedule: &Schedule, language: &str) { set_dtstamp(ical_event, schedule); ical_event.add_property("URL", &schedule.url); set_cancelled(ical_event, schedule.cancelled); let venue = &schedule.venue; ical_event.location(&format!( "{}, {}, {}, {}", venue.name, venue.address, venue.city, venue.locality.country.name )); ical_event.add_property("GEO", &format!("{};{}", venue.latitude, venue.longitude)); ical_event.summary(&get_summary(schedule, language)); } fn create_ical_event(schedule: &Schedule, language: &str) -> IcalEvent { let mut ical_event = IcalEvent::new(); fill_basic_ical_event_props(&mut ical_event, schedule, language); ical_event.uid(&format!("Schedule#{}@goout.net", schedule.id)); set_start_end(&mut ical_event, schedule); ical_event.description(&get_description(schedule, OptionalDescFields::default())); ical_event } fn set_dtstamp(ical_event: &mut IcalEvent, schedule: &Schedule) { let uploaded_on_str = &schedule.uploaded_on.format("%Y%m%dT%H%M%S").to_string(); ical_event.add_property("DTSTAMP", uploaded_on_str); } fn set_start_end(ical_event: &mut IcalEvent, schedule: &Schedule) { if schedule.hour_ignored || schedule.is_long_term { ical_event.start_date(schedule.start.date()); ical_event.end_date(schedule.end.date()); } else { ical_event.starts(schedule.start.with_timezone(&Utc)); ical_event.ends(schedule.end.with_timezone(&Utc)); } } fn set_cancelled(ical_event: &mut IcalEvent, cancelled: bool) { ical_event.add_property("STATUS", if cancelled { "CANCELLED" } else { "CONFIRMED" }); } fn get_summary(schedule: &Schedule, language: &str) -> String { let cancelled_prefix = if schedule.cancelled { // TODO: poor man's localisation match language { "cs" => "Zrušeno: ", _ => "Cancelled: ", } } else { "" }; format!( "{}{} ({})", cancelled_prefix, schedule.event.name, schedule .event .categories .values() .map(|c| &c.name[..]) // convert to &str, see https://stackoverflow.com/a/29026565/4345715 .collect::<Vec<_>>() .join(", ") ) } bitflags! { struct OptionalDescFields: u32 { const EVENT_TEXT = 0b00000001; } } impl Default for OptionalDescFields { fn default() -> Self { Self::EVENT_TEXT } } fn get_description(schedule: &Schedule, optional_fields: OptionalDescFields) -> String { let mut description = Vec::<&str>::new(); let performer_names = schedule .performers .iter() .map(|p| { if p.tags.is_empty() { p.name.clone() } else { format!("{} ({})", p.name, p.tags.join(", ")) } }) .collect::<Vec<_>>() .join(", "); description.push(&performer_names); let pricing = if !schedule.currency.is_empty() && !schedule.pricing.is_empty() { format!("{} {}", schedule.currency, schedule.pricing) } else { String::from("") }; description.push(&pricing); let trimmed_text; if optional_fields.contains(OptionalDescFields::EVENT_TEXT) { trimmed_text = format!("\n{}\n", schedule.event.text.trim()); description.push(&trimmed_text); } // Google Calendar ignores URL property, add it to text description.push(&schedule.url); description.into_iter().filter(|e| !e.trim().is_empty()).collect::<Vec<_>>().join("\n") }
use prost::{ DecodeError, Message, }; use sqs_executor::{ errors::{ CheckedError, Recoverable, }, event_decoder::PayloadDecoder, }; use crate::decoder::decompress::PayloadDecompressionError; #[derive(thiserror::Error, Debug)] pub enum ProtoDecoderError { #[error("DecompressionError")] DecompressionError(#[from] PayloadDecompressionError), #[error("ProtoError")] ProtoError(#[from] DecodeError), } impl CheckedError for ProtoDecoderError { fn error_type(&self) -> Recoverable { match self { Self::DecompressionError(_) => Recoverable::Persistent, Self::ProtoError(_) => Recoverable::Persistent, } } } #[derive(Debug, Clone, Default)] pub struct ProtoDecoder; impl<E> PayloadDecoder<E> for ProtoDecoder where E: Message + Default, { type DecoderError = ProtoDecoderError; fn decode(&mut self, body: Vec<u8>) -> Result<E, Self::DecoderError> where E: Message + Default, { let decompressed = super::decompress::maybe_decompress(body.as_slice())?; let buf = prost::bytes::Bytes::from(decompressed); E::decode(buf).map_err(|e| e.into()) } }
#[derive(Deserialize)] pub struct ZGUIRepositoryInfo { pub version: String, pub version_type: String }
//! Environment use std::collections::HashMap; use eval::{Function, Value}; use util::interner::{Interner, Name}; /// A stack of environments pub struct Stack<'a> { top: Env, bottom: Option<&'a Stack<'a>>, } impl<'a> Stack<'a> { /// Pushes a new environment into the stack pub fn push(&self, env: Env) -> Stack { Stack { top: env, bottom: Some(self), } } /// Searches the stack (from top to bottom) and retrieves the first value that's associated to /// `symbol` pub fn get(&self, symbol: &Name) -> Option<&Value> { self.top.get(symbol).or_else(|| { self.bottom.as_ref().and_then(|stack| stack.get(symbol)) }) } /// Inserts a `symbol`/`value` pair in the top environment pub fn insert(&mut self, symbol: Name, value: Value) { self.top.insert(symbol, value); } } /// Environment pub type Env = HashMap<Name, Value>; /// The default environment stack pub fn default(interner: &mut Interner) -> Stack<'static> { let mut env = Env::new(); env.insert(interner.intern("*"), Value::Function(Function::new(mul))); env.insert(interner.intern("+"), Value::Function(Function::new(add))); env.insert(interner.intern("-"), Value::Function(Function::new(sub))); env.insert(interner.intern("/"), Value::Function(Function::new(div))); env.insert(interner.intern("<"), Value::Function(Function::new(lt))); env.insert(interner.intern("<="), Value::Function(Function::new(le))); env.insert(interner.intern(">"), Value::Function(Function::new(gt))); env.insert(interner.intern(">="), Value::Function(Function::new(ge))); Stack { top: env, bottom: None, } } fn add(args: &[Value]) -> Option<Value> { match args { [Value::Integer(a), Value::Integer(b)] => Some(Value::Integer(a + b)), _ => None, } } fn div(args: &[Value]) -> Option<Value> { match args { [Value::Integer(a), Value::Integer(b)] => Some(Value::Integer(a / b)), _ => None, } } fn ge(args: &[Value]) -> Option<Value> { match args { [Value::Integer(a), Value::Integer(b)] => Some(Value::Bool(a >= b)), _ => None, } } fn gt(args: &[Value]) -> Option<Value> { match args { [Value::Integer(a), Value::Integer(b)] => Some(Value::Bool(a > b)), _ => None, } } fn le(args: &[Value]) -> Option<Value> { match args { [Value::Integer(a), Value::Integer(b)] => Some(Value::Bool(a <= b)), _ => None, } } fn lt(args: &[Value]) -> Option<Value> { match args { [Value::Integer(a), Value::Integer(b)] => Some(Value::Bool(a < b)), _ => None, } } fn mul(args: &[Value]) -> Option<Value> { match args { [Value::Integer(a), Value::Integer(b)] => Some(Value::Integer(a * b)), _ => None, } } fn sub(args: &[Value]) -> Option<Value> { match args { [Value::Integer(a), Value::Integer(b)] => Some(Value::Integer(a - b)), _ => None, } }
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. mod changer; mod restore; pub use self::changer::{Changer, MapChange, MapChangeType}; pub use self::restore::restore;
// Copyright 2016 Indoc Developers // // 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. //! This crate provides a procedural macro for indented string literals. The //! `indoc!()` macro takes a multiline string literal and un-indents it so the //! leftmost non-space character is in the first column. //! //! ```toml //! [dependencies] //! indoc = "0.3" //! ``` //! //! Release notes are available under [GitHub releases](https://github.com/dtolnay/indoc/releases). //! //! # Using Indoc //! //! ```rust #![cfg_attr(feature = "unstable", doc = " #![feature(proc_macro_hygiene)]")] #![cfg_attr(feature = "unstable", doc = "")] //! use indoc::indoc; //! //! fn main() { //! let testing = indoc!(" //! def hello(): //! print('Hello, world!') //! //! hello() //! "); //! let expected = "def hello():\n print('Hello, world!')\n\nhello()\n"; //! assert_eq!(testing, expected); //! } //! ``` //! //! Indoc also works with raw string literals: //! //! ```rust #![cfg_attr(feature = "unstable", doc = " #![feature(proc_macro_hygiene)]")] #![cfg_attr(feature = "unstable", doc = "")] //! use indoc::indoc; //! //! fn main() { //! let testing = indoc!(r#" //! def hello(): //! print("Hello, world!") //! //! hello() //! "#); //! let expected = "def hello():\n print(\"Hello, world!\")\n\nhello()\n"; //! assert_eq!(testing, expected); //! } //! ``` //! //! And byte string literals: //! //! ```rust #![cfg_attr(feature = "unstable", doc = " #![feature(proc_macro_hygiene)]")] #![cfg_attr(feature = "unstable", doc = "")] //! use indoc::indoc; //! //! fn main() { //! let testing = indoc!(b" //! def hello(): //! print('Hello, world!') //! //! hello() //! "); //! let expected = b"def hello():\n print('Hello, world!')\n\nhello()\n"; //! assert_eq!(testing[..], expected[..]); //! } //! ``` //! //! # Explanation //! //! The following rules characterize the behavior of the `indoc!()` macro: //! //! 1. Count the leading spaces of each line, ignoring the first line and any lines //! that are empty or contain spaces only. //! 2. Take the minimum. //! 3. If the first line is empty i.e. the string begins with a newline, remove the //! first line. //! 4. Remove the computed number of spaces from the beginning of each line. //! //! This means there are a few equivalent ways to format the same string, so choose //! one you like. All of the following result in the string `"line one\nline //! two\n"`: //! //! ```text //! indoc!(" / indoc!( / indoc!("line one //! line one / "line one / line two //! line two / line two / ") //! ") / ") / //! ``` #![cfg_attr(feature = "unstable", feature(decl_macro))] #![cfg_attr(feature = "cargo-clippy", allow(useless_attribute))] #![no_std] #[cfg(not(feature = "unstable"))] use proc_macro_hack::proc_macro_hack; #[cfg_attr(not(feature = "unstable"), proc_macro_hack)] pub use indoc_impl::indoc;
use std::marker::PhantomData; use futures::StreamExt; use openlimits::{ binance::{client::websocket::BinanceWebsocket, Binance}, exchange::Exchange, exchange_ws::OpenLimitsWs, model::websocket::Subscription, }; #[tokio::test] async fn orderbook() { let mut ws = init(); let sub = Subscription::OrderBook("bnbbtc".to_string(), 5); ws.subscribe(sub).await.unwrap(); let v = ws.next().await; println!("{:?}", v); } #[tokio::test] async fn trades() { let mut ws = init(); let sub = Subscription::Trade("btcusdt".to_string()); ws.subscribe(sub).await.unwrap(); let v = ws.next().await; println!("{:?}", v); } fn init() -> OpenLimitsWs<BinanceWebsocket> { OpenLimitsWs { websocket: BinanceWebsocket::new(), } }
#[cfg(feature = "async")] use crate::a_sync::AsyncResultSetCore; #[cfg(feature = "sync")] use crate::{sync::SyncResultSetCore, HdbResult}; use std::sync::Arc; pub(crate) type AmRsCore = Arc<MRsCore>; #[derive(Debug)] pub(crate) enum MRsCore { #[cfg(feature = "sync")] Sync(std::sync::Mutex<SyncResultSetCore>), #[cfg(feature = "async")] Async(tokio::sync::Mutex<AsyncResultSetCore>), } impl MRsCore { #[cfg(feature = "sync")] pub(crate) fn sync_lock(&self) -> HdbResult<std::sync::MutexGuard<SyncResultSetCore>> { match self { MRsCore::Sync(m_rscore) => Ok(m_rscore.lock()?), #[cfg(feature = "async")] _ => unimplemented!("async not supported here"), } } #[cfg(feature = "async")] pub(crate) async fn async_lock(&self) -> tokio::sync::MutexGuard<AsyncResultSetCore> { match self { MRsCore::Async(m_rscore) => m_rscore.lock().await, #[cfg(feature = "sync")] _ => unimplemented!("sync not supported here"), } } }
use crate::component_registry::ComponentRegistry; use crate::entities::{EntityId, EntityIds, SpatialEntitiesRes}; use crate::system_commands::{SystemCommandSender, SystemCommandSenderRes}; use spatialos_sdk::worker::connection::{Connection, WorkerConnection}; use spatialos_sdk::worker::op::WorkerOp; use specs::prelude::{Resources, System, SystemData}; use specs::shred::ResourceId; use specs::world::EntitiesRes; /// A system which receives operations from SpatialOS and applies them /// to the local world. /// /// This system should run at the beginning of each frame. /// /// This system **must not run in parallel with other systems**, or you may /// get a runtime panic. You can ensure this by creating a barrier after the system. /// /// ## Example /// /// ``` /// # use specs::prelude::*; /// # use spatialos_specs::*; /// # /// # struct MovePlayerSys; /// # impl<'a> System<'a> for MovePlayerSys{ /// # type SystemData = (); /// # /// # fn run(&mut self, _sys: ()) {} /// # } /// # /// let mut world = World::new(); /// /// let mut dispatcher = DispatcherBuilder::new() /// .with(SpatialReaderSystem, "reader", &[]) /// .with_barrier() /// /// .with(MovePlayerSys, "", &[]) /// /// .with_barrier() /// .with(SpatialWriterSystem, "writer", &[]) /// .build(); /// /// dispatcher.setup(&mut world.res); /// ``` pub struct SpatialReaderSystem; impl<'a> System<'a> for SpatialReaderSystem { type SystemData = ResourcesSystemData<'a>; fn setup(&mut self, res: &mut Resources) { Self::SystemData::setup(res); SystemCommandSender::setup(res); EntityIds::setup(res); } fn run(&mut self, res: Self::SystemData) { let res = res.res; let ops = { let mut connection = res.fetch_mut::<WorkerConnection>(); connection.get_op_list(0) }; for op in &ops { match op { WorkerOp::AddEntity(add_entity_op) => { res.fetch_mut::<SpatialEntitiesRes>() .got_new_entity(res, EntityId(add_entity_op.entity_id)); } WorkerOp::RemoveEntity(remove_entity_op) => { res.fetch_mut::<SpatialEntitiesRes>() .remove_entity(res, EntityId(remove_entity_op.entity_id)); } WorkerOp::AddComponent(add_component) => { match ComponentRegistry::get_interface(add_component.component_id) { None => {} Some(interface) => { let entity = EntityIds::fetch(res) .get_entity(EntityId(add_component.entity_id)) .unwrap(); interface.add_component(res, entity, add_component); } } } WorkerOp::RemoveComponent(remove_component) => { match ComponentRegistry::get_interface(remove_component.component_id) { None => {} Some(interface) => { let entity = EntityIds::fetch(res) .get_entity(EntityId(remove_component.entity_id)) .unwrap(); interface.remove_component(res, entity); } } } WorkerOp::ComponentUpdate(update) => { match ComponentRegistry::get_interface(update.component_id) { None => {} Some(interface) => { let entity = EntityIds::fetch(res) .get_entity(EntityId(update.entity_id)) .unwrap(); interface.apply_component_update(res, entity, update); } } } WorkerOp::AuthorityChange(authority_change) => { match ComponentRegistry::get_interface(authority_change.component_id) { None => {} Some(interface) => { let entity = EntityIds::fetch(res) .get_entity(EntityId(authority_change.entity_id)) .unwrap(); interface.apply_authority_change(res, entity, authority_change); } } } WorkerOp::CommandRequest(command_request) => { match ComponentRegistry::get_interface(command_request.component_id) { None => {} Some(interface) => { let entity = EntityIds::fetch(res) .get_entity(EntityId(command_request.entity_id)) .unwrap(); interface.on_command_request(res, entity, command_request); } } } WorkerOp::CommandResponse(command_response) => { match ComponentRegistry::get_interface(command_response.component_id) { None => {} Some(interface) => { interface.on_command_response(res, command_response); } } } WorkerOp::ReserveEntityIdsResponse(reserve_entity_ids_response) => { SystemCommandSenderRes::got_reserve_entity_ids_response( res, reserve_entity_ids_response, ); } WorkerOp::CreateEntityResponse(create_entity_response) => { SystemCommandSenderRes::got_create_entity_response(res, create_entity_response); } WorkerOp::DeleteEntityResponse(delete_entity_response) => { SystemCommandSenderRes::got_delete_entity_response(res, delete_entity_response); } WorkerOp::EntityQueryResponse(entity_query_response) => { SystemCommandSenderRes::got_entity_query_response(res, entity_query_response); } _ => {} } } } } /// A SystemData which gives a reference to Resources. /// /// This allows arbitrary fetches. This can cause runtime panics if a fetched /// resource has been fetched by another system running in parallel. #[doc(hidden)] pub struct ResourcesSystemData<'a> { pub(crate) res: &'a Resources, } impl<'a> SystemData<'a> for ResourcesSystemData<'a> { fn setup(_: &mut Resources) {} fn fetch(res: &'a Resources) -> Self { ResourcesSystemData { res } } fn reads() -> Vec<ResourceId> { vec![] } fn writes() -> Vec<ResourceId> { vec![ ResourceId::new::<EntitiesRes>(), ResourceId::new::<WorkerConnection>(), ] } }
mod symlink; mod downloader; mod archive_reader; mod ls; mod system_node; mod logger; mod node_version; mod commands; mod language; mod home_directory; mod autoselect; mod compiler; extern crate hyper; extern crate regex; extern crate os_type; extern crate rustc_serialize; extern crate semver; extern crate docopt; use docopt::Docopt; use std::process; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); const USAGE: &'static str = " avm Usage: avm install <language> <version> avm use <language> (<version>|system) avm ls <language> avm uninstall <language> <version> avm autoselect <language> avm [options] Options: -h --help --version "; #[derive(Debug, RustcDecodable)] struct Args { cmd_ls: bool, cmd_use: bool, cmd_system: bool, cmd_install: bool, cmd_uninstall: bool, cmd_autoselect: bool, arg_version: String, arg_language: String, flag_version: bool } fn handle_node(args: Args) { if args.cmd_install { commands::node::install(&args.arg_version); } if args.cmd_use && args.cmd_system { commands::node::use_version("system".into()); } else if args.cmd_use && !args.cmd_system { commands::node::use_version(args.arg_version.clone()); } if args.cmd_ls { commands::node::list_versions(); } if args.cmd_uninstall { commands::node::uninstall(args.arg_version.clone()); } if args.cmd_autoselect { commands::node::autoselect_version(); } } fn handle_ruby(args: Args) { if args.cmd_install { commands::ruby::install(&args.arg_version); } else if args.cmd_use { commands::ruby::use_version(args.arg_version.clone()); } else if args.cmd_ls { commands::ruby::list_versions(); } else if args.cmd_uninstall { commands::ruby::uninstall(args.arg_version.clone()); } else { logger::stderr("Unknown command"); std::process::exit(1); } } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if args.flag_version { logger::stdout(format!("avm -- v{}", VERSION)); process::exit(0); } match &args.arg_language[..] { "ruby" => handle_ruby(args), "node" => handle_node(args), _ => { logger::stderr(format!("Unsupported language {}", args.arg_language)); process::exit(1) } } }
use ansi_term::Color::{Green, Red, Yellow, Blue, Cyan, White}; use log::*; use chrono::prelude::*; pub fn Info(info: String) -> String { return Green.bold().paint(format!("{}", info)).to_string(); } pub fn printLn(info: String, target: String) -> String { let local: DateTime<Local> = Local::now(); return format!( "{} {} {} {} {} {}", Cyan.bold().paint(format!("<")), White.bold().paint(format!("{}", local)), Green.bold().paint(format!("INFO")), Green.bold().paint(format!("{}", info)), Blue.bold().paint(format!("{}", target)), Cyan.bold().paint(format!(">")) ).to_string(); } pub fn Error(err: String, target: String) -> String { let local: DateTime<Local> = Local::now(); return format!( "{} {} {} {} {} {}", Cyan.bold().paint(format!("<")), White.bold().paint(format!("{}", local)), Red.bold().paint(format!("ERROR")), Red.bold().paint(format!("{}", err)), Blue.bold().paint(format!("{}", target)), Cyan.bold().paint(format!(">")) ).to_string(); } pub fn Warn(warn: String, target: String) -> String { let local: DateTime<Local> = Local::now(); return format!( "{} {} {} {} {} {}", Cyan.bold().paint(format!("<")), White.bold().paint(format!("{}", local)), Yellow.bold().paint(format!("WARN")), Yellow.bold().paint(format!("{}", warn)), Blue.bold().paint(format!("{}", target)), Cyan.bold().paint(format!(">")) ).to_string(); } pub fn Debug(debug: String, target: String) -> String { let local: DateTime<Local> = Local::now(); return format!( "{} {} {} {} {} {}", Cyan.bold().paint(format!("<")), White.bold().paint(format!("{}", local)), Yellow.bold().paint(format!("WARN")), Yellow.bold().paint(format!("{}", debug)), Blue.bold().paint(format!("{}", target)), Cyan.bold().paint(format!(">")) ).to_string(); } pub fn Trace(trace: String, target: String) -> String { let local: DateTime<Local> = Local::now(); return format!( "{} {} {} {} {} {}", Cyan.bold().paint(format!("<")), White.bold().paint(format!("{}", local)), Yellow.bold().paint(format!("WARN")), Yellow.bold().paint(format!("{}", trace)), Blue.bold().paint(format!("{}", target)), Cyan.bold().paint(format!(">")) ).to_string(); }
// // Convert //! Convert to LWJGL key and mouse button values. // use terminal::event::{Key, MouseButton}; /// Converts a key to an LWJGL key code. pub fn key_to_lwjgl(key: Key) -> Option<i32> { match key { Key::Q => Some(16), Key::W => Some(17), Key::E => Some(18), Key::R => Some(19), Key::T => Some(20), Key::Y => Some(21), Key::U => Some(22), Key::I => Some(23), Key::O => Some(24), Key::P => Some(25), Key::A => Some(30), Key::S => Some(31), Key::D => Some(32), Key::F => Some(33), Key::G => Some(34), Key::H => Some(35), Key::J => Some(36), Key::K => Some(37), Key::L => Some(38), Key::Z => Some(44), Key::X => Some(45), Key::C => Some(46), Key::V => Some(47), Key::B => Some(48), Key::N => Some(49), Key::M => Some(50), Key::Number0 => Some(11), Key::Number1 => Some(2), Key::Number2 => Some(3), Key::Number3 => Some(4), Key::Number4 => Some(5), Key::Number5 => Some(6), Key::Number6 => Some(7), Key::Number7 => Some(8), Key::Number8 => Some(9), Key::Number9 => Some(10), Key::F1 => Some(59), Key::F2 => Some(60), Key::F3 => Some(61), Key::F4 => Some(62), Key::F5 => Some(63), Key::F6 => Some(64), Key::F7 => Some(65), Key::F8 => Some(66), Key::F9 => Some(67), Key::F10 => Some(68), Key::F11 => Some(87), Key::F12 => Some(88), Key::F13 => Some(100), Key::F14 => Some(101), Key::F15 => Some(102), Key::Space => Some(57), Key::Comma => Some(51), Key::Period => Some(52), Key::Backslash => Some(43), Key::Semicolon => Some(39), Key::Apostrophe => Some(40), Key::ForwardSlash => Some(53), Key::OpenBracket => Some(26), Key::CloseBracket => Some(27), Key::Equals => Some(13), Key::Minus => Some(12), Key::Tab => Some(15), Key::Backtick => Some(41), Key::Return => Some(28), Key::CapsLock => Some(58), Key::Escape => Some(1), Key::Backspace => Some(14), Key::Home => Some(199), Key::End => Some(207), Key::PageUp => Some(201), Key::PageDown => Some(209), Key::Up => Some(200), Key::Left => Some(203), Key::Right => Some(205), Key::Down => Some(208), Key::LeftShift => Some(42), Key::RightShift => Some(54), Key::LeftControl => Some(29), Key::RightControl => Some(157), Key::LeftAlt => Some(56), Key::RightAlt => Some(184), Key::LeftMeta => Some(219), Key::RightMeta => Some(220), _ => None, } } /// Converts a mouse button to an LWGJL one. pub fn button_to_lwjgl(button: MouseButton) -> i32 { match button { MouseButton::Left => 1, MouseButton::Middle => 3, MouseButton::Right => 2, } }
use super::{access::Access, deserialize_int_opt}; use serde::Deserialize; /// Bit-field properties of a register. #[non_exhaustive] #[derive(Clone, Debug, Default, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Field { /// Define the number of elements in an array. #[serde(default, deserialize_with = "deserialize_int_opt")] pub dim: Option<u32>, /// Specify the address increment, in Bytes, between two neighboring array members in the address map. #[serde(default, deserialize_with = "deserialize_int_opt")] pub dim_increment: Option<u32>, /// Name string used to identify the field. pub name: String, /// String describing the details of the register. #[serde(default)] pub description: String, /// The position of the least significant bit of the field within the register. #[serde(default, deserialize_with = "deserialize_int_opt")] pub bit_offset: Option<u32>, /// The bit-width of the bitfield within the register. #[serde(default, deserialize_with = "deserialize_int_opt")] pub bit_width: Option<u32>, /// The bit position of the least significant bit within the register. #[serde(default, deserialize_with = "deserialize_int_opt")] pub lsb: Option<u32>, /// The bit position of the most significant bit within the register. #[serde(default, deserialize_with = "deserialize_int_opt")] pub msb: Option<u32>, /// The access type. pub access: Option<Access>, } impl Field { /// Returns the position of the least significant bit of the field within /// the register. pub fn bit_offset(&self) -> u32 { self.bit_offset.or(self.lsb).expect("bit-range is missing") } /// Returns the bit-width of the bitfield within the register. pub fn bit_width(&self) -> u32 { self.bit_width .or_else(|| self.lsb.and_then(|lsb| self.msb.map(|msb| msb - lsb + 1))) .expect("bit-range is missing") } }
/// We want to support a commands like: /// /// cargo push commit -m "hello world" -t feature --story SVC-1111 mod commit; mod git; use commit::{perform_commit, ConventionalCommitType}; #[macro_use] extern crate lazy_static; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt( name = "cargo push", about = "A tool to abstract git and enforce consistency of commits and releases using the semver and conventional commits standards" )] enum Opt { Commit { #[structopt(short = "m", long = "message")] message: String, #[structopt(short = "t", long = "type")] commit_type: Option<ConventionalCommitType>, #[structopt(short = "s", long = "story")] ticket: Option<String>, }, Version { tag: Option<String>, }, } fn main() { let opt = Opt::from_args(); match opt { Opt::Commit { message, commit_type, ticket, } => { perform_commit(message, commit_type, ticket).expect("Failed to perform commit"); } _ => { println!("Not yet supported"); } }; }
use std::convert::TryFrom; use std::fmt; #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Level { VeryEasy, Easy, Normal, Hard, Absurd, } impl Level { pub fn iter() -> std::slice::Iter<'static, Level> { [ Level::VeryEasy, Level::Easy, Level::Normal, Level::Hard, Level::Absurd, ] .into_iter() } fn name(&self) -> &str { match self { Level::VeryEasy => "VeryEasy", Level::Easy => "Easy", Level::Normal => "Normal", Level::Hard => "Hard", Level::Absurd => "Absurd", } } } impl Default for Level { fn default() -> Self { Level::Easy } } impl TryFrom<&str> for Level { type Error = String; fn try_from(name: &str) -> Result<Self, Self::Error> { match name.to_lowercase().as_str() { "veryeasy" | "very_easy" | "level_very_easy.json" => { Ok(Self::VeryEasy) } "easy" | "level_easy.json" => Ok(Self::Easy), "normal" | "level_normal.json" => Ok(Self::Normal), "hard" | "level_hard.json" => Ok(Self::Hard), "absurd" | "level_absurd.json" => Ok(Self::Absurd), n => Err(format!("Level cannot be created from String '{}'", n)), } } } impl fmt::Display for Level { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name()) } }
pub fn check_numeric_rules(num: usize) -> Result<bool, &'static str> { let num_list = split_numeric(num)?; let mut found_double = false; for (i, num) in num_list.iter().enumerate() { if i < 5 { if *num > num_list[i + 1] { return Ok(false); } if found_double { continue; } if *num == num_list[i + 1] { found_double = true; } } } Ok(found_double) } pub fn check_extended_numeric_rules(num: usize) -> Result<bool, &'static str> { let num_list = split_numeric(num)?; let mut double_list: Vec<u8> = Vec::new(); let mut current_run: Option<u8> = None; for (i, num) in num_list.iter().enumerate() { if i < 5 { if *num > num_list[i + 1] { return Ok(false); } if *num == num_list[i + 1] { if current_run == Some(*num) { // We're in a run with more than one of the same type, but we only care if the // current double matches our number. if let Some(double) = double_list.pop() { // If the last found double wasn't our number put it back... if double != *num { double_list.push(*num); } } } else { current_run = Some(*num); double_list.push(*num); } } } } Ok(!double_list.is_empty()) } pub fn split_numeric(num: usize) -> Result<[u8; 6], &'static str> { // We can only handle six digit numbers if num < 100_000 || num >= 1_000_000 { return Err("value is outside the correct range"); } // Should probably do this recursively but its simple enough to just hard code these... let digits: [u8; 6] = [ (num / 100_000) as u8, (num / 10_000 % 10) as u8, (num / 1_000 % 10) as u8, (num / 100 % 10) as u8, (num / 10 % 10) as u8, (num % 10) as u8, ]; Ok(digits) } fn main() { let mut total_checked = 0; let mut match_count = 0; let mut extended_match_count = 0; // Note: The last number is not included in the range and the problem doesn't specify whether // this needs to be included or not. It doesn't matter in this case though as the first and // final digit both fail the validation rules. for num in 153_517..630_395 { total_checked += 1; if check_numeric_rules(num).unwrap() { match_count += 1; } if check_extended_numeric_rules(num).unwrap() { extended_match_count += 1; } } println!( "In the given range there were basic {} matches out of {}", match_count, total_checked ); println!( "In the given range there were extended {} matches out of {}", extended_match_count, total_checked ); } #[cfg(test)] mod tests { use super::*; #[test] fn test_numeric_rule_checker() { assert!(check_numeric_rules(111_111).unwrap()); assert!(!check_numeric_rules(223_450).unwrap()); assert!(!check_numeric_rules(123_789).unwrap()); assert!(check_numeric_rules(1_000).is_err()); assert!(check_numeric_rules(1_000_000).is_err()); } #[test] fn test_extended_numeric_rule_checker() { assert!(check_extended_numeric_rules(112_233).unwrap()); assert!(check_extended_numeric_rules(111_122).unwrap()); assert!(!check_extended_numeric_rules(111_111).unwrap()); assert!(!check_extended_numeric_rules(123_444).unwrap()); assert!(!check_extended_numeric_rules(223_450).unwrap()); assert!(!check_extended_numeric_rules(123_789).unwrap()); assert!(check_numeric_rules(1_000).is_err()); assert!(check_numeric_rules(1_000_000).is_err()); } #[test] fn test_split_numeric() { assert!(split_numeric(1_000).is_err()); assert!(split_numeric(1_000_000).is_err()); assert_eq!(split_numeric(123_456).unwrap(), [1, 2, 3, 4, 5, 6]); assert_eq!(split_numeric(783_100).unwrap(), [7, 8, 3, 1, 0, 0]); } }
use nanoserde::{DeBin, SerBin}; use naia_derive::Actor; use naia_shared::{Actor, Property}; use crate::ExampleActor; // Here's an example of a Custom Property #[derive(Default, PartialEq, Clone, DeBin, SerBin)] pub struct Name { pub first: String, pub last: String, } #[derive(Actor)] #[type_name = "ExampleActor"] pub struct PointActor { pub x: Property<u8>, pub y: Property<u8>, pub name: Property<Name>, } impl PointActor { pub fn new(x: u8, y: u8, first: &str, last: &str) -> PointActor { return PointActor::new_complete( x, y, Name { first: first.to_string(), last: last.to_string(), }, ); } pub fn step(&mut self) { let mut x = *self.x.get(); x += 1; if x > 20 { x = 0; } if x % 3 == 0 { let mut y = *self.y.get(); y = y.wrapping_add(1); self.y.set(y); } self.x.set(x); } }