text
stringlengths
8
4.13M
use sioctl::Sioctl; fn main() { let s = Sioctl::new(); println!("Initial state of controls:"); for control in s.controls() { println!("{:?}", control); } println!(""); println!("Watching for changes (press Enter to exit):"); let mut watcher = s.watch(|control| println!("{:?}", control)); // Wait for Enter: let mut buf = String::new(); std::io::stdin().read_line(&mut buf).unwrap(); println!("Shutting down..."); watcher.join(); println!("Gracefully shut down. Bye."); }
use sycamore::prelude::*; #[component(Nav<G>)] fn nav() -> Template<G> { template! { nav(class="fixed top-0 z-50 px-8 w-full \ backdrop-filter backdrop-blur-sm backdrop-saturate-150 bg-opacity-80 \ bg-gray-100 border-b border-gray-400") { div(class="flex flex-row justify-between items-center h-12") { // Brand section div(class="flex-initial") { div(class="flex space-x-4") { a(href="/#", class="py-2 px-3 text-sm text-white font-medium \ bg-gray-500 hover:bg-gray-600 transition-colors rounded") { "Sycamore" } } } // Links section div(class="flex flex-row ml-2 space-x-4 text-gray-600") { a(class="py-2 px-3 text-sm hover:text-gray-800 hover:underline", href="/docs/getting_started/installation", ) { "Book" } a(class="py-2 px-3 text-sm hover:text-gray-800 hover:underline", href="https://docs.rs/sycamore", ) { "API" } a(class="py-2 px-3 text-sm hover:text-gray-800 hover:underline", href="/news", ) { "News" } a(class="py-2 px-3 text-sm hover:text-gray-800 hover:underline", href="https://github.com/sycamore-rs/sycamore", ) { "GitHub" } a(class="py-2 px-3 text-sm hover:text-gray-800 hover:underline", href="https://discord.gg/vDwFUmm6mU", ) { "Discord" } } } } } } #[component(Header<G>)] pub fn header() -> Template<G> { template! { header { Nav() } } }
use std::borrow::Cow; use std::fmt::{Display, self}; use std::ops::Deref; use std::str::{self, FromStr}; use http::ByteStr; use Url; use url::ParseError as UrlError; use Error; /// The Request-URI of a Request's StartLine. /// /// From Section 5.3, Request Target: /// > Once an inbound connection is obtained, the client sends an HTTP /// > request message (Section 3) with a request-target derived from the /// > target URI. There are four distinct formats for the request-target, /// > depending on both the method being requested and whether the request /// > is to a proxy. /// > /// > ```notrust /// > request-target = origin-form /// > / absolute-form /// > / authority-form /// > / asterisk-form /// > ``` /// /// # Uri explanations /// ```notrust /// abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1 /// |-| |-------------------------------||--------| |-------------------| |-----| /// | | | | | /// scheme authority path query fragment /// ``` #[derive(Clone)] pub struct Uri { source: InternalUri, scheme_end: Option<usize>, authority_end: Option<usize>, query: Option<usize>, fragment: Option<usize>, } impl Uri { /// Parse a string into a `Uri`. fn new(s: InternalUri) -> Result<Uri, Error> { if s.len() == 0 { Err(Error::Uri(UrlError::RelativeUrlWithoutBase)) } else if s.as_bytes() == b"*" { Ok(Uri { source: InternalUri::Cow("*".into()), scheme_end: None, authority_end: None, query: None, fragment: None, }) } else if s.as_bytes() == b"/" { Ok(Uri::default()) } else if s.as_bytes()[0] == b'/' { let query = parse_query(&s); let fragment = parse_fragment(&s); Ok(Uri { source: s, scheme_end: None, authority_end: None, query: query, fragment: fragment, }) } else if s.contains("://") { let scheme = parse_scheme(&s); let auth = parse_authority(&s); if let Some(end) = scheme { match &s[..end] { "ftp" | "gopher" | "http" | "https" | "ws" | "wss" => {}, "blob" | "file" => return Err(Error::Method), _ => return Err(Error::Method), } match auth { Some(a) => { if (end + 3) == a { return Err(Error::Method); } }, None => return Err(Error::Method), } } let query = parse_query(&s); let fragment = parse_fragment(&s); Ok(Uri { source: s, scheme_end: scheme, authority_end: auth, query: query, fragment: fragment, }) } else if (s.contains("/") || s.contains("?")) && !s.contains("://") { return Err(Error::Method) } else { let len = s.len(); Ok(Uri { source: s, scheme_end: None, authority_end: Some(len), query: None, fragment: None, }) } } /// Get the path of this `Uri`. pub fn path(&self) -> &str { let index = self.authority_end.unwrap_or(self.scheme_end.unwrap_or(0)); let query_len = self.query.unwrap_or(0); let fragment_len = self.fragment.unwrap_or(0); let end = self.source.len() - if query_len > 0 { query_len + 1 } else { 0 } - if fragment_len > 0 { fragment_len + 1 } else { 0 }; if index >= end { if self.scheme().is_some() { "/" // absolute-form MUST have path } else { "" } } else { &self.source[index..end] } } /// Get the scheme of this `Uri`. pub fn scheme(&self) -> Option<&str> { if let Some(end) = self.scheme_end { Some(&self.source[..end]) } else { None } } /// Get the authority of this `Uri`. pub fn authority(&self) -> Option<&str> { if let Some(end) = self.authority_end { let index = self.scheme_end.map(|i| i + 3).unwrap_or(0); Some(&self.source[index..end]) } else { None } } /// Get the host of this `Uri`. pub fn host(&self) -> Option<&str> { if let Some(auth) = self.authority() { auth.split(":").next() } else { None } } /// Get the port of this `Uri`. pub fn port(&self) -> Option<u16> { match self.authority() { Some(auth) => auth.find(":").and_then(|i| u16::from_str(&auth[i+1..]).ok()), None => None, } } /// Get the query string of this `Uri`, starting after the `?`. pub fn query(&self) -> Option<&str> { let fragment_len = self.fragment.unwrap_or(0); let fragment_len = if fragment_len > 0 { fragment_len + 1 } else { 0 }; if let Some(len) = self.query { Some(&self.source[self.source.len() - len - fragment_len.. self.source.len() - fragment_len]) } else { None } } #[cfg(test)] fn fragment(&self) -> Option<&str> { if let Some(len) = self.fragment { Some(&self.source[self.source.len() - len..self.source.len()]) } else { None } } } fn parse_scheme(s: &str) -> Option<usize> { s.find(':') } fn parse_authority(s: &str) -> Option<usize> { let i = s.find("://").and_then(|p| Some(p + 3)).unwrap_or(0); Some(&s[i..].split("/") .next() .unwrap_or(s) .len() + i) } fn parse_query(s: &str) -> Option<usize> { match s.find('?') { Some(i) => { let frag_pos = s.find('#').unwrap_or(s.len()); if frag_pos < i + 1 { None } else { Some(frag_pos - i - 1) } }, None => None, } } fn parse_fragment(s: &str) -> Option<usize> { match s.find('#') { Some(i) => Some(s.len() - i - 1), None => None, } } impl FromStr for Uri { type Err = Error; fn from_str(s: &str) -> Result<Uri, Error> { //TODO: refactor such that the to_owned() is only required at the end //of successful parsing, so an Err doesn't needlessly clone the string. Uri::new(InternalUri::Cow(Cow::Owned(s.to_owned()))) } } impl From<Url> for Uri { fn from(url: Url) -> Uri { let s = InternalUri::Cow(Cow::Owned(url.into_string())); // TODO: we could build the indices with some simple subtraction, // instead of re-parsing an already parsed string. // For example: // let scheme_end = url[..url::Position::AfterScheme].as_ptr() as usize // - url.as_str().as_ptr() as usize; // etc Uri::new(s).expect("Uri::From<Url> failed") } } impl PartialEq for Uri { fn eq(&self, other: &Uri) -> bool { self.source.as_str() == other.source.as_str() } } impl Eq for Uri {} impl AsRef<str> for Uri { fn as_ref(&self) -> &str { self.source.as_str() } } impl Default for Uri { fn default() -> Uri { Uri { source: InternalUri::Cow("/".into()), scheme_end: None, authority_end: None, query: None, fragment: None, } } } impl fmt::Debug for Uri { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self.as_ref(), f) } } impl Display for Uri { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.as_ref()) } } pub fn from_mem_str(s: ByteStr) -> Result<Uri, Error> { Uri::new(InternalUri::Shared(s)) } #[derive(Clone)] enum InternalUri { Cow(Cow<'static, str>), Shared(ByteStr), } impl InternalUri { fn as_str(&self) -> &str { match *self { InternalUri::Cow(ref s) => s.as_ref(), InternalUri::Shared(ref m) => m.as_str(), } } } impl Deref for InternalUri { type Target = str; fn deref(&self) -> &str { self.as_str() } } macro_rules! test_parse { ( $test_name:ident, $str:expr, $($method:ident = $value:expr,)* ) => ( #[test] fn $test_name() { let uri = Uri::from_str($str).unwrap(); $( assert_eq!(uri.$method(), $value); )+ } ); } test_parse! { test_uri_parse_origin_form, "/some/path/here?and=then&hello#and-bye", scheme = None, authority = None, path = "/some/path/here", query = Some("and=then&hello"), fragment = Some("and-bye"), } test_parse! { test_uri_parse_absolute_form, "http://127.0.0.1:61761/chunks", scheme = Some("http"), authority = Some("127.0.0.1:61761"), path = "/chunks", query = None, fragment = None, port = Some(61761), } test_parse! { test_uri_parse_absolute_form_without_path, "https://127.0.0.1:61761", scheme = Some("https"), authority = Some("127.0.0.1:61761"), path = "/", query = None, fragment = None, port = Some(61761), } test_parse! { test_uri_parse_asterisk_form, "*", scheme = None, authority = None, path = "*", query = None, fragment = None, } test_parse! { test_uri_parse_authority_no_port, "localhost", scheme = None, authority = Some("localhost"), path = "", query = None, fragment = None, port = None, } test_parse! { test_uri_parse_authority_form, "localhost:3000", scheme = None, authority = Some("localhost:3000"), path = "", query = None, fragment = None, port = Some(3000), } test_parse! { test_uri_parse_absolute_with_default_port_http, "http://127.0.0.1:80", scheme = Some("http"), authority = Some("127.0.0.1:80"), path = "/", query = None, fragment = None, port = Some(80), } test_parse! { test_uri_parse_absolute_with_default_port_https, "https://127.0.0.1:443", scheme = Some("https"), authority = Some("127.0.0.1:443"), path = "/", query = None, fragment = None, port = Some(443), } test_parse! { test_uri_parse_fragment_questionmark, "http://127.0.0.1/#?", scheme = Some("http"), authority = Some("127.0.0.1"), path = "/", query = None, fragment = Some("?"), port = None, } #[test] fn test_uri_parse_error() { fn err(s: &str) { Uri::from_str(s).unwrap_err(); } err("http://"); err("htt:p//host"); err("hyper.rs/"); err("hyper.rs?key=val"); err("localhost/"); err("localhost?key=val"); } #[test] fn test_uri_from_url() { let uri = Uri::from(Url::parse("http://test.com/nazghul?test=3").unwrap()); assert_eq!(uri.path(), "/nazghul"); assert_eq!(uri.authority(), Some("test.com")); assert_eq!(uri.scheme(), Some("http")); assert_eq!(uri.query(), Some("test=3")); assert_eq!(uri.as_ref(), "http://test.com/nazghul?test=3"); }
use crate::types::*; use crate::objects::{get_static_objects, get_weapons, scenery_data}; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern { fn alert(s: &str); } #[wasm_bindgen] impl Game { pub fn new() -> Game { crate::utils::set_panic_hook(); Game { data :vec![], ready: false, screen: [[0; WIDTH as usize]; HEIGHT as usize], inverted: false, static_objects: get_static_objects().to_vec(), weapons: get_weapons().to_vec(), levels_data: crate::data::levels::levels(), objects_data: crate::data::objects::objects(), enemies_data: crate::data::enemies::enemies(), scenery: vec![], enemies: vec![], shots: vec![], is_playing: false, game_over: false, level: 0, time: 0, scene_x: 0, enemies_x: 0, player: Player { position: Vec2 { x: 3, y: 20 }, lives: 3, protection: 0, }, y_axis: Vec2 { x: 5, y: HEIGHT as i32 - PLAYER_HEIGHT as i32 }, weapon: Weapon { amount: 3, kind: WeaponKind::Missile }, score: 0, } } pub fn update(&mut self, _ctx: &Context) { self.clear(); if self.game_over { return; } self.keyboard(_ctx); if !self.is_playing { if self.level == 5 { self.game_over = true; return; } self.inverted = self.level_data().inverted_color; self.enemies = self.load_level(self.level); if self.level_data().upper == 1 { self.y_axis = Vec2 { x: 0, y: HEIGHT as i32 - PLAYER_HEIGHT as i32 - 5 }; } self.load_scenery(); self.player.position = Vec2 { x: 3, y: 20 }; self.scene_x = 0; self.enemies_x = 0; self.level += 1; self.is_playing = true; } // Enemies if self.enemies.len() == 0 { self.player.position.x += 1; } if self.player.position.x > WIDTH as i32 + 20 { self.is_playing = false; return; } let enemies_x = self.enemies_x; self.enemies = self .enemies .clone() .into_iter() .filter(|e| e.active() && enemies_x + e.position.x > -20) .map(|e| e.tick(self)) .collect::<Vec<_>>(); // Shots let nearest_y = if self.enemies.len() > 0 { self.enemies[0].position.y } else { self.player.position.y }; self.shots = self .shots .clone() .into_iter() .filter(|s| s.active && s.position.x < WIDTH as i32) .map(|s| s.tick(nearest_y)) .collect(); // The end if let Some(enemy) = self.enemies.last() { if self.enemies_x + enemy.position.x >= (WIDTH as i32 / 4) * 3 { self.scene_x -= 1; } } if self.player.protected() { self.player.protection -= 1; } self.time += 1; self.enemies_x -= 1; if self.player.lives == 0 { self.game_over = true; } } pub fn do_render(&mut self) { self.render(); } pub fn screen_pointer(&mut self) -> *mut [[u8; WIDTH as usize]; HEIGHT as usize] { &mut self.screen } } impl Game { pub fn level_data(&self) -> SceneryData { scenery_data[self.level as usize].clone() } pub fn keyboard(&mut self, _ctx: &Context) { let position = &mut self.player.position; if _ctx.key_right && position.x < WIDTH as i32 - PLAYER_WIDTH as i32 { position.x += 1; } else if _ctx.key_left && position.x > 0 { position.x -= 1; } else if _ctx.key_up && position.y > self.y_axis.x { position.y -= 1; } else if _ctx.key_down && position.y < self.y_axis.y { position.y += 1; } if self.time % 6 == 0 { if _ctx.key_space { let position = Vec2 { x: position.x + 9, y: position.y + 3 }; let shot = Shot { position, active: true, weapon_kind: WeaponKind::Standard, duration: 3 }; self.shots.push(shot); } else if _ctx.key_a { if self.weapon.amount > 0 { self.weapon.amount -= 1; let y = if self.weapon.kind == WeaponKind::Wall { 5 } else { position.y + 3 }; let position = Vec2 { x: position.x + 9, y: y }; let shot = Shot { position, active: true, weapon_kind: self.weapon.kind.clone(), duration: 3 }; self.shots.push(shot); } } } } pub fn load_scenery(&mut self) { self.scenery = vec![]; let mut x = 0; if self.level > 0 { while x < 1600 { let sd = &scenery_data[self.level as usize]; let n: u8 = crate::random() % sd.objects + sd.first_object; let rock = self.load_object(n); let y = if self.level_data().upper == 1 { 0 } else { HEIGHT as i32 - rock.size.y }; self.scenery.push(Scenery { position: Vec2 { x, y }, model: rock.clone() }); x += rock.size.x; } } } }
use std::collections::HashSet; #[derive(Debug)] pub struct LifeBoard { pub x_size: usize, pub y_size: usize, board: Box<[bool]>, pub active: HashSet<(usize, usize)> } impl LifeBoard { pub fn new(x: usize, y: usize) -> LifeBoard { return LifeBoard { x_size: x, y_size: y, board: vec![false; x*y].into_boxed_slice(), active: HashSet::with_capacity(x*y/2) } } pub fn get(&self, x: isize, y: isize) -> bool { // return self.active.contains(&(x,y)); let wrapped_x = wrap(x, self.x_size); let wrapped_y = wrap(y, self.y_size); return self.board[wrapped_x + wrapped_y*self.x_size]; // return self.active.contains(&(wrapped_x, wrapped_y)); } pub fn set(&mut self, x: isize, y: isize, v: bool) { let wrapped_x = wrap(x, self.x_size); let wrapped_y = wrap(y, self.y_size); if self.board[wrapped_x + wrapped_y * self.x_size] != v { if v { self.active.insert((wrapped_x, wrapped_y)); } else { self.active.remove(&(wrapped_x, wrapped_y)); } self.board[wrapped_x + wrapped_y*self.x_size] = v; } } } fn wrap(i : isize, max : usize) -> usize { ((i + max as isize) % max as isize) as usize }
use errors::*; use hex; use libsodacrypt; use net::endpoint::Endpoint; use net::event::{ClientEvent, Event}; use net::http; use net::message; use rmp_serde; use std; use std::io::{Read, Write}; #[derive(Debug, Clone, PartialEq)] pub enum SessionState { New, WaitPing, Ready, } pub struct SessionClient { pub session_id: String, pub local_node_id: Vec<u8>, pub local_discover: Vec<Endpoint>, pub remote_node_id: Vec<u8>, pub remote_discover: Vec<Endpoint>, pub endpoint: Endpoint, pub state: SessionState, pub last_ping: std::time::Instant, pub eph_pub: Vec<u8>, pub eph_priv: Vec<u8>, pub key_send: Vec<u8>, pub key_recv: Vec<u8>, pub cur_socket: Option<std::net::TcpStream>, pub cur_response: http::Request, } impl SessionClient { pub fn new(local_node_id: &[u8], endpoint: &Endpoint, discover: Vec<Endpoint>) -> Result<Self> { let (key_pub, key_priv) = libsodacrypt::kx::gen_keypair()?; Ok(SessionClient { session_id: "".to_string(), local_node_id: local_node_id.to_vec(), local_discover: discover, remote_node_id: Vec::new(), remote_discover: Vec::new(), endpoint: endpoint.clone(), state: SessionState::New, last_ping: std::time::Instant::now(), eph_pub: key_pub, eph_priv: key_priv, key_send: Vec::new(), key_recv: Vec::new(), cur_socket: None, cur_response: http::Request::new(http::RequestType::Response), }) } pub fn new_initial_connect( endpoint: &Endpoint, node_id: &[u8], discover: Vec<Endpoint>, ) -> Result<Self> { let mut socket = wrap_connect(endpoint)?; let mut session = SessionClient::new(node_id, endpoint, discover)?; let mut req = http::Request::new(http::RequestType::Request); req.method = "GET".to_string(); req.path = format!( "/{}/{}", hex::encode(node_id), hex::encode(&session.eph_pub) ); let output = req.generate(); if output.len() != socket.write(&output)? { panic!("incomplete write"); } session.cur_socket = Some(socket); Ok(session) } pub fn check_ping(&mut self) -> Result<()> { if self.last_ping.elapsed() > std::time::Duration::from_millis(100) { self.ping()?; } Ok(()) } pub fn ping(&mut self) -> Result<()> { self.last_ping = std::time::Instant::now(); let mut socket = wrap_connect(&self.endpoint)?; let ping_req = message::PingReq::new(&self.local_node_id, self.local_discover.clone()); let out = message::compile( &self.session_id, &[message::Message::PingReq(Box::new(ping_req))], http::RequestType::Request, &self.key_send, )?; if out.len() != socket.write(&out)? { panic!("incomplete write"); } self.cur_socket = Some(socket); Ok(()) } pub fn user_message(&mut self, data: Vec<u8>) -> Result<()> { let mut socket = wrap_connect(&self.endpoint)?; let msg = message::UserMessage::new(data); let out = message::compile( &self.session_id, &[message::Message::UserMessage(Box::new(msg))], http::RequestType::Request, &self.key_send, )?; if out.len() != socket.write(&out)? { panic!("incomplete write"); } self.cur_socket = Some(socket); Ok(()) } pub fn process_once(mut self) -> (Option<Self>, Vec<Event>) { let mut buf = [0u8; 1024]; let mut events: Vec<Event> = Vec::new(); let mut socket = match self.cur_socket.take() { None => { self.check_ping().unwrap(); return (Some(self), events); } Some(s) => s, }; let size = match socket.read(&mut buf) { Ok(b) => { if b < 1 { events.push(Event::OnClientEvent(ClientEvent::OnClose())); return (Some(self), events); } else { b } } Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => { self.cur_socket = Some(socket); return (Some(self), events); } Err(e) => { events.push(Event::OnClientEvent(ClientEvent::OnError(e.into()))); events.push(Event::OnClientEvent(ClientEvent::OnClose())); return (None, events); } }; { if !self.cur_response.check_parse(&buf[..size]) { self.cur_socket = Some(socket); return (Some(self), events); } } let response = self.cur_response; self.cur_response = http::Request::new(http::RequestType::Response); match self.state { SessionState::New => self.process_initial_handshake(events, response), SessionState::WaitPing => self.process_messages(events, response), SessionState::Ready => self.process_messages(events, response), } } // -- private -- // #[allow(unknown_lints)] #[allow(needless_pass_by_value)] fn process_initial_handshake( mut self, mut events: Vec<Event>, response: http::Request, ) -> (Option<Self>, Vec<Event>) { let (mut cli_recv, mut cli_send, mut remote_node_id, session_id) = match wrap_parse_initial_handshake(&response.body, &self.eph_pub, &self.eph_priv) { Ok(v) => v, Err(e) => { events.push(Event::OnClientEvent(ClientEvent::OnError(e))); events.push(Event::OnClientEvent(ClientEvent::OnClose())); return (None, events); } }; self.remote_node_id.append(&mut remote_node_id); self.eph_pub.drain(..); self.eph_priv.drain(..); self.key_send.append(&mut cli_send); self.key_recv.append(&mut cli_recv); self.session_id = session_id; self.state = SessionState::WaitPing; self.ping().unwrap(); (Some(self), events) } #[allow(unknown_lints)] #[allow(needless_pass_by_value)] fn process_messages( mut self, mut events: Vec<Event>, response: http::Request, ) -> (Option<Self>, Vec<Event>) { let msgs = message::parse(&response.body, &self.key_recv).unwrap(); for msg in msgs { match msg { message::Message::PingRes(mut r) => { if self.state != SessionState::Ready { self.state = SessionState::Ready; println!( "ping response in {} ms", message::get_millis() - r.origin_time ); } self.last_ping = std::time::Instant::now(); self.remote_node_id = r.node_id.drain(..).collect(); self.remote_discover = r.discover.drain(..).collect(); events.push(Event::OnClientEvent(ClientEvent::OnConnected( self.remote_node_id.clone(), self.endpoint.clone(), ))); } message::Message::UserMessage(r) => { events.push(Event::OnClientEvent(ClientEvent::OnDataReceived( self.remote_node_id.clone(), r.data, ))); } _ => { panic!("unexpected message: {:?}", msg); } } } (Some(self), events) } } fn wrap_connect(endpoint: &Endpoint) -> Result<std::net::TcpStream> { let timeout = std::time::Duration::from_millis(1000); let addr = endpoint.to_socket_addr()?; let socket = std::net::TcpStream::connect_timeout(&addr, timeout)?; socket.set_nonblocking(true)?; Ok(socket) } #[allow(unknown_lints)] #[allow(type_complexity)] fn wrap_parse_initial_handshake( data: &[u8], eph_pub: &[u8], eph_priv: &[u8], ) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>, String)> { let res: message::InitialHandshakeRes = rmp_serde::from_slice(data)?; let srv_pub = res.eph_pub; let remote_node_id = res.node_id; let session_id = res.session_id; let (cli_recv, cli_send) = libsodacrypt::kx::derive_client(eph_pub, eph_priv, &srv_pub)?; Ok((cli_recv, cli_send, remote_node_id, session_id)) }
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved // mod key_trait; pub use key_trait::HasKeyForVariants; mod fingerprints; pub use fingerprints::build_fingerprint; /// A short string that uniquely identifies all glTF objects other than `Mesh` `Primitives`. pub type MeldKey = String; /// A floating-point number that identifies logically identical `Mesh` `Primitives`. /// /// Most glTF objects are given a simple, unique key as part of the `MeldKey` mechanism. /// For geometry, things are trickier. To begin with, neither the order of triangles (indices) /// nor vectors are important, so any comparison must be order-agnostic. Worse, floating-point /// calculations are inexact, and so identity there must be of the ||x - x'|| < ε type. pub type Fingerprint = f64;
#![allow(non_snake_case)] use anyhow::Result; use dirs; use serde_derive::{Deserialize, Serialize}; use serde_json::json; use base64::encode; use std::collections::HashMap; use std::fs::{create_dir, remove_dir_all, File}; use std::io::{Read, Write}; use std::path::Path; use std::process::{Command, Stdio}; use std::str; use std::vec::Vec; use bollard::container::ListContainersOptions; use bollard::Docker; use tokio::runtime::Runtime; use regex::Regex; #[derive(Serialize, Deserialize, Debug)] struct ExtraMount { containerPath: String, hostPath: String, } #[derive(Serialize, Deserialize, Debug)] struct PortMapping { containerPort: u32, hostPort: u32, protocol: String, } #[derive(Serialize, Deserialize, Debug)] struct Node { role: String, extraMounts: Vec<ExtraMount>, extraPortMappings: Vec<PortMapping>, kubeadmConfigPatches: Vec<String>, } #[derive(Serialize, Deserialize, Debug)] struct ClusterConfig { kind: String, apiVersion: String, nodes: Vec<Node>, containerdConfigPatches: Vec<String>, } #[derive(Deserialize, Debug)] struct DockerLogin { Username: String, Secret: String, } pub struct Kind { pub name: String, pub ecr_repo: Option<String>, config_dir: String, local_registry: Option<String>, extra_port_mapping: Option<String>, verbose: bool, } impl Kind { fn extra_mount(container_path: Option<&str>, host_path: Option<&str>) -> Vec<ExtraMount> { if let Some(container_path) = container_path { if let Some(host_path) = host_path { return vec![ExtraMount { containerPath: String::from(container_path), hostPath: String::from(host_path), }]; } } vec![] } fn kind_node(role: &str, container_path: Option<&str>, host_path: Option<&str>) -> Node { Node { role: String::from(role), extraMounts: Kind::extra_mount(container_path, host_path), extraPortMappings: vec![], kubeadmConfigPatches: vec![], } } fn init_config_ingress_ready() -> String { String::from( r#"kind: InitConfiguration nodeRegistration: kubeletExtraArgs: node-labels: "ingress-ready=true""#, ) } fn get_kind_cluster_config( &self, ecr: &Option<String>, local_reg: &Option<String>, ) -> ClusterConfig { let mut cc = ClusterConfig { kind: String::from("Cluster"), apiVersion: String::from("kind.x-k8s.io/v1alpha4"), nodes: vec![], containerdConfigPatches: vec![], }; if let Some(ecr) = ecr { if let Ok(docker_path) = self.create_docker_ecr_config_file(ecr) { cc.nodes = vec![Kind::kind_node( "control-plane", Some("/var/lib/kubelet/config.json"), Some(&docker_path), )]; } } if let Some(local_reg) = local_reg { cc.containerdConfigPatches = vec![Kind::get_containerd_config_patch_to_local_registry( local_reg, )]; } cc } fn get_containerd_config_patch_to_local_registry(ip: &str) -> String { format!( r#" [plugins."io.containerd.grpc.v1.cri".registry.mirrors."localhost:5000"] endpoint = ["http://{}:5000"]"#, ip.trim() ) } /// Gets the Kind cluster name from the Docker container name. fn get_cluster_name(container_name: &str) -> Option<String> { if !container_name.ends_with("-control-plane") { None } else { Some( container_name .replace("-control-plane", "") .replace("/", ""), ) } } // Removes every entry in ~/.hake that does not have a corresponding kind docker container. async fn async_get_containers() -> Result<Vec<String>> { let docker = Docker::connect_with_local_defaults()?; let mut filter = HashMap::new(); filter.insert(String::from("status"), vec![String::from("running")]); let containers = &docker .list_containers(Some(ListContainersOptions { all: true, filters: filter, ..Default::default() })) .await?; let mut kind_containers = Vec::new(); for container in containers { if container.image.starts_with("kindest/node") { let name = String::from(container.names.get(0).unwrap()); match Kind::get_cluster_name(&name) { Some(name) => kind_containers.push(name), None => continue, } } } Ok(kind_containers) } pub fn get_kind_containers() -> Result<Vec<String>> { let mut rt = Runtime::new().unwrap(); rt.block_on(Kind::async_get_containers()) } fn get_docker_login(registry: &str) -> Result<String> { let creds = Kind::get_docker_credentials_from_helper(registry)?; let login: DockerLogin = serde_json::from_str(&creds)?; let encoded = encode(&format!("{}:{}", login.Username, login.Secret)); Ok(json!({ "auths": { registry: { "auth": encoded } } } ) .to_string()) } fn get_docker_credentials_from_helper(registry: &str) -> Result<String> { let mut cmd = Command::new("docker-credential-ecr-login") .arg("get") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .unwrap_or_else(|_| { panic!("Could not find docker credentials helper for {}", registry) }); cmd.stdin.as_mut().unwrap().write_all(registry.as_bytes())?; cmd.wait()?; let mut output = String::new(); cmd.stdout.unwrap().read_to_string(&mut output)?; Ok(output) } fn create_docker_ecr_config_file(&self, ecr: &str) -> Result<String> { let docker_login = Kind::get_docker_login(ecr).expect("could not get docker login"); // save docker_login() let docker_config_path = format!("{}/docker_config", self.config_dir); let mut docker_config = File::create(&docker_config_path)?; docker_config.write_all(&docker_login.into_bytes())?; Ok(docker_config_path) } fn create_dirs(cluster_name: &str) -> Result<()> { let home = Kind::get_config_dir()?; if !Path::new(&home).exists() { create_dir(&home)?; } create_dir(format!("{}/{}", &home, cluster_name))?; Ok(()) } pub fn get_config_dir() -> Result<String> { let home = String::from( dirs::home_dir() .expect("User does not have a home") .to_str() .unwrap(), ); Ok(format!("{}/.hake", home)) } pub fn configure_private_registry(&mut self, reg: Option<String>) { self.ecr_repo = reg; } pub fn set_verbose(&mut self, verbose: bool) { self.verbose = verbose; } fn find_local_registry(container_name: &str) -> Option<String> { let ip = Command::new("docker") .arg("inspect") .arg("-f") .arg("{{.NetworkSettings.IPAddress}}") .arg(container_name) .output() .expect(&format!( "Could not get IP from {} container", container_name )); Some(String::from_utf8(ip.stdout).unwrap().trim().to_string()) } pub fn use_local_registry(&mut self, container_name: &str) { self.local_registry = Kind::find_local_registry(container_name); } pub fn extra_port_mapping(&mut self, extra_port_mapping: &str) { self.extra_port_mapping = Some(String::from(extra_port_mapping)); } /// receives a string like: 80:80:TCP or 80:80 or 80 fn parse_extra_port_mappings(epm: &str) -> Option<PortMapping> { let mut container_port = 0; let mut host_port = 0; let mut proto = String::from("TCP"); let re0 = Regex::new(r"^(\d{2}):(\d{2}):(TCP|HTTP)$").unwrap(); let re1 = Regex::new(r"^(\d{2}):(\d{2})$").unwrap(); let re2 = Regex::new(r"^(\d+)$").unwrap(); if re0.is_match(epm) { let cap = re0.captures(epm).unwrap(); container_port = cap[1].parse::<u32>().unwrap(); host_port = cap[2].parse::<u32>().unwrap(); proto = String::from(&cap[3]); } else if let Some(cap) = re1.captures(epm) { container_port = cap[1].parse::<u32>().unwrap(); host_port = cap[2].parse::<u32>().unwrap(); } else if let Some(cap) = re2.captures(epm) { container_port = cap[1].parse::<u32>().unwrap(); host_port = container_port; } if container_port != 0 { Some(PortMapping { containerPort: container_port, hostPort: host_port, protocol: proto, }) } else { None } } pub fn create(self) -> Result<()> { Kind::create_dirs(&self.name)?; let mut args = vec!["create", "cluster"]; let kubeconfig; args.push("--name"); args.push(&self.name); kubeconfig = format!("{}/kubeconfig", self.config_dir); args.push("--kubeconfig"); args.push(&kubeconfig); args.push("--config"); let mut kind_config = self.get_kind_cluster_config(&self.ecr_repo, &self.local_registry); if let Some(extra_port_mapping) = self.extra_port_mapping { let epm = Kind::parse_extra_port_mappings(&extra_port_mapping); if let Some(epm) = epm { if let Some(mut node) = kind_config.nodes.get_mut(0) { node.extraPortMappings = vec![epm]; } else { let mut nn = Kind::kind_node("control-plane", None, None); nn.extraPortMappings = vec![epm]; kind_config.nodes = vec![nn]; }; kind_config.nodes[0].kubeadmConfigPatches = vec![Kind::init_config_ingress_ready()]; } } let kind_cluster_config = serde_yaml::to_string(&kind_config)?; let kind_config_path = format!("{}/kind_config", self.config_dir); let mut kind_config = File::create(&kind_config_path)?; kind_config.write_all(&kind_cluster_config.into_bytes())?; // point the config file to the one we just saved args.push(&kind_config_path); Kind::run(&args, self.verbose)?; let config_dir = Kind::get_config_dir()?; let config_dir = format!("{}/{}/kind_args", config_dir, &self.name); let mut saved_args = File::create(config_dir)?; saved_args.write_all(args.join(" ").as_bytes())?; Ok(()) } pub fn run(args: &Vec<&str>, verbose: bool) -> Result<()> { let mut command = Command::new("kind"); command.args(args); if verbose { command.spawn()?.wait()?; } else { command.output()?; } Ok(()) } pub fn recreate(name: &str, verbose: bool) -> Result<()> { let config_dir = format!("{}/{}", Kind::get_config_dir()?, name); let args_file = format!("{}/kind_args", config_dir); let mut contents = String::new(); let mut saved_args = File::open(args_file)?; saved_args.read_to_string(&mut contents)?; Kind::delete_cluster(name)?; let args: Vec<&str> = contents.split_ascii_whitespace().collect(); Kind::run(&args, verbose)?; Ok(()) } pub fn delete(&self) -> Result<()> { Kind::delete_cluster(&self.name)?; remove_dir_all(&self.config_dir)?; Ok(()) } fn delete_cluster(name: &str) -> Result<()> { let mut args = vec!["delete", "cluster"]; args.push("--name"); args.push(name); let _cmd = Command::new("kind").args(args).output()?; Ok(()) } pub fn new(name: &str) -> Kind { let config = Kind::get_config_dir(); if config.is_err() { panic!("User has no home!!"); } let home = config.unwrap(); Kind { name: String::from(name), ecr_repo: None, config_dir: format!("{}/{}", home, name), local_registry: None, extra_port_mapping: None, verbose: false, } } } #[cfg(test)] mod tests { use crate::kind::Kind; #[test] fn test_new() { // TODO: test configuration on home directory. let k = Kind::new("test"); let home = dirs::home_dir().unwrap(); assert_eq!(k.name, "test"); assert_eq!(k.ecr_repo, None); assert_eq!( k.config_dir, format!("{}/.hake/test", home.to_str().unwrap()) ); assert_eq!(k.local_registry, None); } #[test] fn test_get_cluster_name() { assert_eq!(Kind::get_cluster_name("not-us"), None); assert_eq!( Kind::get_cluster_name("this-is-us-control-plane"), Some(String::from("this-is-us")) ); assert_eq!( Kind::get_cluster_name("/this-is-us-control-plane"), Some(String::from("this-is-us")) ); } }
use async_trait::async_trait; use rbatis::crud::CRUDTable; use mav::{ChainType, NetType, WalletType, CTrue}; use mav::kits::sql_left_join_get_b; use mav::ma::{Dao, MEeeChainToken, MEeeChainTokenDefault, MEeeChainTokenShared, MWallet, MSubChainBasicInfo, MAccountInfoSyncProg, MEeeChainTokenAuth}; use crate::{Chain2WalletType, ChainShared, ContextTrait, deref_type, Load, WalletError}; use rbatis::rbatis::Rbatis; #[derive(Debug, Default)] pub struct EeeChainToken { pub m: MEeeChainToken, pub eee_chain_token_shared: EeeChainTokenShared, } deref_type!(EeeChainToken,MEeeChainToken); #[async_trait] impl Load for EeeChainToken { type MType = MEeeChainToken; async fn load(&mut self, context: &dyn ContextTrait, m: Self::MType) -> Result<(), WalletError> { self.m = m; let rb = context.db().wallets_db(); let token_shared = MEeeChainTokenShared::fetch_by_id(rb, "", &self.chain_token_shared_id).await?; let token_shared = token_shared.ok_or_else(|| WalletError::NoneError(format!("do not find id:{}, in {}", &self.chain_token_shared_id, MEeeChainTokenShared::table_name())))?; self.eee_chain_token_shared.load(context, token_shared).await?; Ok(()) } } #[derive(Debug, Default)] pub struct EeeChainTokenShared { pub m: MEeeChainTokenShared, //pub token_shared: TokenShared, } deref_type!(EeeChainTokenShared,MEeeChainTokenShared); impl From<MEeeChainTokenShared> for EeeChainTokenShared { fn from(token_shared: MEeeChainTokenShared) -> Self { Self { m: token_shared, } } } #[async_trait] impl Load for EeeChainTokenShared { type MType = MEeeChainTokenShared; async fn load(&mut self, _: &dyn ContextTrait, m: Self::MType) -> Result<(), WalletError> { self.m = m; //self.token_shared.m = self.m.token_shared.clone(); Ok(()) } } #[derive(Debug, Default)] pub struct EeeChainTokenDefault { pub m: MEeeChainTokenDefault, pub eee_chain_token_shared: EeeChainTokenShared, } deref_type!(EeeChainTokenDefault,MEeeChainTokenDefault); impl EeeChainTokenDefault { pub async fn list_by_net_type(context: &dyn ContextTrait, net_type: &NetType) -> Result<Vec<EeeChainTokenDefault>, WalletError> { let tx_id = ""; let wallets_db = context.db().wallets_db(); let tokens_shared: Vec<MEeeChainTokenShared> = { let default_name = MEeeChainTokenDefault::table_name(); let shared_name = MEeeChainTokenShared::table_name(); let wrapper = wallets_db.new_wrapper().eq(format!("{}.{}", default_name, MEeeChainTokenDefault::net_type).as_str(), net_type.to_string()); let sql = { let t = sql_left_join_get_b(&default_name, &MEeeChainTokenDefault::chain_token_shared_id, &shared_name, &MEeeChainTokenShared::id); format!("{} where {}", t, &wrapper.sql) }; wallets_db.fetch_prepare(tx_id, &sql, &wrapper.args).await? }; let mut tokens_default = { let wrapper = wallets_db.new_wrapper() .eq(MEeeChainTokenDefault::net_type, net_type.to_string()) .eq(MEeeChainTokenDefault::status, CTrue) .order_by(true, &[MEeeChainTokenDefault::position]); MEeeChainTokenDefault::list_by_wrapper(wallets_db, tx_id, &wrapper).await? }; for token_default in &mut tokens_default { for token_shared in &tokens_shared { if token_default.chain_token_shared_id == token_shared.id { token_default.chain_token_shared = token_shared.clone(); } } } let eee_tokens = tokens_default.iter().map(|token| EeeChainTokenDefault { m: token.clone(), eee_chain_token_shared: EeeChainTokenShared::from(token.chain_token_shared.clone()), }).collect::<Vec<EeeChainTokenDefault>>(); Ok(eee_tokens) } } #[derive(Debug, Default)] pub struct EeeChainTokenAuth { pub m: MEeeChainTokenAuth, pub eee_chain_token_shared: EeeChainTokenShared, } deref_type!(EeeChainTokenAuth,MEeeChainTokenAuth); impl EeeChainTokenAuth { pub async fn list_by_net_type(context: &dyn ContextTrait, net_type: &NetType, start_item: u64, page_size: u64) -> Result<Vec<EeeChainTokenAuth>, WalletError> { let tx_id = ""; let wallets_db = context.db().wallets_db(); let page_query = format!(" limit {} offset {}", page_size, start_item); let mut tokens_auth = { let wrapper = wallets_db.new_wrapper() .eq(MEeeChainTokenAuth::net_type, net_type.to_string()) .eq(MEeeChainTokenAuth::status, CTrue) .order_by(false, &[MEeeChainTokenAuth::create_time]).push_sql(&page_query); MEeeChainTokenAuth::list_by_wrapper(wallets_db, tx_id, &wrapper).await? }; let token_shared_id = format!("id in (SELECT {} FROM {} WHERE {}='{}' ORDER by {} desc {})", MEeeChainTokenAuth::chain_token_shared_id, MEeeChainTokenAuth::table_name(), MEeeChainTokenAuth::net_type, net_type.to_string(), MEeeChainTokenAuth::create_time, page_query); let token_shared_wrapper = wallets_db.new_wrapper().push_sql(&token_shared_id); let tokens_shared = MEeeChainTokenShared::list_by_wrapper(wallets_db, tx_id, &token_shared_wrapper).await?; let mut target_tokens = vec![]; for token_auth in &mut tokens_auth { for token_shared in &tokens_shared { let mut token = EeeChainTokenAuth::default(); if token_auth.chain_token_shared_id == token_shared.id { token.m = token_auth.clone(); token.eee_chain_token_shared = EeeChainTokenShared::from(token_shared.clone()); target_tokens.push(token) } } } Ok(target_tokens) } } #[derive(Debug, Default)] pub struct EeeChain { pub chain_shared: ChainShared, // pub address: Address, pub tokens: Vec<EeeChainToken>, } impl Chain2WalletType for EeeChain { fn chain_type(wallet_type: &WalletType, net_type: &NetType) -> ChainType { match (wallet_type, net_type) { (WalletType::Normal, NetType::Main) => ChainType::EEE, (WalletType::Test, NetType::Test) => ChainType::EeeTest, (WalletType::Test, NetType::Private) => ChainType::EeePrivate, (WalletType::Test, NetType::PrivateTest) => ChainType::EeePrivateTest, _ => ChainType::EeeTest, } } } /*#[async_trait]*/ impl EeeChain { pub async fn load(&mut self, context: &dyn ContextTrait, mw: MWallet, net_type: &NetType) -> Result<(), WalletError> { self.chain_shared.set_m(&mw); let wallet_type = WalletType::from(mw.wallet_type.as_str()); let chain_type = EeeChain::chain_type(&wallet_type, &net_type).to_string(); {//load address let wallet_id = self.chain_shared.wallet_id.clone(); self.chain_shared.set_addr(context, &wallet_id, &chain_type).await?; self.chain_shared.m.chain_type = chain_type.clone(); } {//load token let rb = context.db().data_db(&net_type); let wrapper = rb.new_wrapper() .eq(MEeeChainToken::wallet_id, mw.id.clone()) .eq(MEeeChainToken::chain_type, chain_type); let ms = MEeeChainToken::list_by_wrapper(&rb, "", &wrapper).await?; self.tokens.clear(); for it in ms { let mut token = EeeChainToken::default(); token.load(context, it).await?; self.tokens.push(token); } } Ok(()) } } #[derive(Debug, Default, Clone)] pub struct AccountInfoSyncProg { m: MAccountInfoSyncProg } deref_type!(AccountInfoSyncProg,MAccountInfoSyncProg); impl From<MAccountInfoSyncProg> for AccountInfoSyncProg { fn from(m_sync_prog: MAccountInfoSyncProg) -> Self { let mut info = AccountInfoSyncProg { m: Default::default() }; info.m = m_sync_prog; info } } impl AccountInfoSyncProg { pub async fn find_by_account(rb: &Rbatis, account: &str) -> Result<Option<MAccountInfoSyncProg>, WalletError> { let wrapper = rb.new_wrapper() .eq(MAccountInfoSyncProg::account, account.to_string()); let r = MAccountInfoSyncProg::fetch_by_wrapper(rb, "", &wrapper).await?.map(|info| info); Ok(r) } } #[derive(Debug, Default, Clone)] pub struct SubChainBasicInfo { m: MSubChainBasicInfo } deref_type!(SubChainBasicInfo,MSubChainBasicInfo); impl From<MSubChainBasicInfo> for SubChainBasicInfo { fn from(m_sub_info: MSubChainBasicInfo) -> Self { let mut info = SubChainBasicInfo { m: Default::default() }; info.m = m_sub_info; info } } impl SubChainBasicInfo { pub async fn find_by_version(rb: &Rbatis, genesis_hash: &str, runtime_version: i32, tx_version: i32) -> Result<Option<SubChainBasicInfo>, WalletError> { let wrapper = rb.new_wrapper() .eq(MSubChainBasicInfo::genesis_hash, genesis_hash.to_string()) .eq(MSubChainBasicInfo::runtime_version, runtime_version) .eq(MSubChainBasicInfo::tx_version, tx_version); let r = MSubChainBasicInfo::fetch_by_wrapper(rb, "", &wrapper).await?.map(|info| info.into()); Ok(r) } pub async fn get_default_version(rb: &Rbatis) -> Result<Option<SubChainBasicInfo>, WalletError> { let wrapper = rb.new_wrapper().eq(MSubChainBasicInfo::is_default, CTrue); let r = MSubChainBasicInfo::fetch_by_wrapper(rb, "", &wrapper).await?.map(|info| info.into()); Ok(r) } }
pub struct Solution; impl Solution { pub fn is_palindrome(s: String) -> bool { if s.is_empty() { return true; } let bytes = s.as_bytes(); let mut i = 0; let mut j = bytes.len() - 1; while i < j { while i < j && !bytes[i].is_ascii_alphanumeric() { i += 1; } while i < j && !bytes[j].is_ascii_alphanumeric() { j -= 1; } if i < j { if bytes[i].to_ascii_lowercase() == bytes[j].to_ascii_lowercase() { i += 1; j -= 1; } else { return false; } } } true } } #[test] fn test0125() { assert_eq!( Solution::is_palindrome("A man, a plan, a canal: Panama".to_string()), true ); assert_eq!(Solution::is_palindrome("race a car".to_string()), false); assert_eq!(Solution::is_palindrome("".to_string()), true); assert_eq!(Solution::is_palindrome("a.".to_string()), true); assert_eq!(Solution::is_palindrome("0P".to_string()), false); }
use super::{Cons, List, Nil}; use crate::{ common::*, functional::Func, maybe::{Just, Maybe, Nothing}, stepper::{Curr, Next, Stepper}, tuple::{Get0, Get1, Tuple2}, }; typ! { pub fn IsEmpty<list>(list: List) -> Bit { match list { #[generics(head, tail: List)] Cons::<head, tail> => false, Nil => true, } } pub fn PushFront<list, value>(list: List, value: _) -> List { Cons::<value, list> } pub fn PushBack<list, value>(list: List, value: _) -> List { match list { #[generics(head, tail: List)] Cons::<head, tail> => { let new_tail = PushBack(tail, value); Cons::<head, new_tail> } Nil => { Cons::<value, Nil> } } } pub fn PopFront<head, tail>(Cons::<head, tail>: List) -> List { tail } pub fn PopBack<head1, tail1: List>(Cons::<head1, tail1>: List) -> List { match tail1 { #[generics(head2, tail2: List)] Cons::<head2, tail2> => { let new_tail = PopBack(tail2); Cons::<head1, Cons<head2, new_tail>> } Nil => { Nil } } } pub fn Insert<list, index, value>(list: List, index: Unsigned, value: _) -> List { if index == 0u { Cons::<value, list> } else { match list { #[generics(head, tail: List)] Cons::<head, tail> => { let new_index: Unsigned = index - 1u; let new_tail = Insert(tail, new_index, value); Cons::<head, new_tail> } } } } pub fn Remove<head, tail: List, index>(Cons::<head, tail>: List, index: Unsigned) -> List { if index == 0u { tail } else { let new_index: Unsigned = index - 1u; let new_tail = Remove(tail, new_index); Cons::<head, new_tail> } } pub fn RemoveItem<list, item, step>(list: List, item: _, step: Stepper) -> List { match (list, step) { #[generics(tail: List)] #[capture(item)] (Cons::<item, tail>, Curr) => tail, #[generics(head, tail: List, remaining: Stepper)] (Cons::<head, tail>, Next::<remaining>) => { let new_tail = RemoveItem(tail, item, remaining); Cons::<head, new_tail> } } } pub fn ReplaceItem<list, prev, new, step>(list: List, prev: _, new: _, step: Stepper) -> List { match (list, step) { #[generics(tail: List)] #[capture(prev)] (Cons::<prev, tail>, Curr) => { Cons::<new, tail> } #[generics(head, tail: List, remaining: Stepper)] (Cons::<head, tail>, Next::<remaining>) => { let new_tail = ReplaceItem(tail, prev, new, remaining); Cons::<head, new_tail> } } } pub fn Extend<lhs, rhs>(lhs: List, rhs: List) -> List { match lhs { #[generics(head, tail: List)] Cons::<head, tail> => { let new_tail = Extend(tail, rhs); Cons::<head, new_tail> } Nil => rhs, } } pub fn Reverse<list>(list: List) -> List { ReverseRecursive(Nil, list) } fn ReverseRecursive<saved, remaining>(saved: List, remaining: List) -> List { match remaining { #[generics(head, tail: List)] Cons::<head, tail> => { let new_saved = Cons::<head, saved>; ReverseRecursive(new_saved, tail) } Nil => { saved } } } pub fn IndexOf<list, item, step>(list: List, item: _, step: Stepper) -> Unsigned { match (list, step) { #[generics(tail: List)] #[capture(item)] (Cons::<item, tail>, Curr) => 0u, #[generics(head, tail: List, remaining: Stepper)] (Cons::<head, tail>, Next::<remaining>) => { IndexOf(tail, item, remaining) + 1u } } } pub fn Len<list>(list: List) -> Unsigned { match list { #[generics(head, tail: List)] Cons::<head, tail> => { Len(tail) + 1u } Nil => 0u, } } pub fn First<head, tail: List>(Cons::<head, tail>: List) { head } pub fn Last<head, tail: List>(Cons::<head, tail>: List) { match tail { #[generics(head2, tail2: List)] Cons::<head2, tail2> => { Last(tail) } Nil => head, } } pub fn Zip<lhs, rhs>(lhs: List, rhs: List) -> List { match lhs { #[generics(lhead, ltail: List)] Cons::<lhead, ltail> => { match rhs { #[generics(rhead, rtail: List)] Cons::<rhead, rtail> => { let new_tail = Zip(ltail, rtail); Cons::<(lhead, rhead), new_tail> } } } Nil => { match rhs { Nil => Nil } } } } pub fn Get<list, index>(list: List, index: _) { match index { UTerm => GetByUnsigned(list, UTerm), #[generics(uint: Unsigned, bit: Bit)] UInt::<uint, bit> => { let index: Unsigned = index; GetByUnsigned(list, index) } #[generics(range_index)] Range::<range_index> => GetByRange(list, index), #[generics(range_index)] RangeInclusive::<range_index> => GetByRangeInclusive(list, index), #[generics(range_index)] RangeTo::<range_index> => GetByRangeTo(list, index), #[generics(range_index)] RangeToInclusive::<range_index> => GetByRangeToInclusive(list, index), #[generics(range_index)] RangeFrom::<range_index> => GetByRangeFrom(list, index), RangeFull => list, } } pub fn GetByUnsigned<list, index>(list: List, index: Unsigned) { match (list, index) { #[generics(head, tail: List)] (Cons::<head, tail>, UTerm) => head, #[generics(head, tail: List, uint: Unsigned, bit: Bit)] (Cons::<head, tail>, UInt::<uint, bit>) => { let new_index: Unsigned = index - 1u; GetByUnsigned(tail, new_index) } } } pub fn GetByRange<list, from: Unsigned, to: Unsigned>(list: List, Range::<(from, to)>: _) -> List { match (list, from) { #[generics(head, tail: List, uint: Unsigned, bit: Bit)] (Cons::<head, tail>, UInt::<uint, bit>) => { let new_from: Unsigned = from - 1u; let new_to: Unsigned = to - 1u; let new_range = Range::<(new_from, new_to)>; GetByRange(tail, new_range) } #[capture(list)] (list, UTerm) => { let new_range = RangeTo::<to>; GetByRangeTo(list, new_range) } } } pub fn GetByRangeInclusive<list, from: Unsigned, to: Unsigned>(list: List, RangeInclusive::<(from, to)>: _) -> List { let new_to: Unsigned = to + 1u; let new_range = Range::<(from, new_to)>; GetByRange(list, new_range) } pub fn GetByRangeFrom<list, index: Unsigned>(list: List, RangeFrom::<index>: _) -> List { match (list, index) { #[generics(head, tail: List, uint: Unsigned, bit: Bit)] (Cons::<head, tail>, UInt::<uint, bit>) => { let new_index: Unsigned = index - 1u; let new_range = RangeFrom::<new_index>; GetByRangeFrom(tail, new_range) } #[capture(list)] (list, UTerm) => { list } } } pub fn GetByRangeTo<list, range>(list: List, range: _) -> List { GetByRangeToRecursive(Nil, list, range) } pub fn GetByRangeToInclusive<list, index: Unsigned>(list: List, RangeToInclusive::<index>: _) -> List { let new_index: Unsigned = index + 1u; let new_range = RangeTo::<new_index>; GetByRangeToRecursive(Nil, list, new_range) } fn GetByRangeToRecursive<saved, remaining, to: Unsigned>(saved: List, remaining: List, RangeTo::<to>: _) -> List { match (remaining, to) { #[generics(head, tail: List, uint: Unsigned, bit: Bit)] (Cons::<head, tail>, UInt::<uint, bit>) => { let new_saved = Cons::<head, saved>; let new_to: Unsigned = to - 1u; let new_range = RangeTo::<new_to>; GetByRangeToRecursive(new_saved, tail, new_range) } #[capture(remaining)] (remaining, UTerm) => { Reverse(saved) } } } pub fn ReduceSum<head1, tail1: List>(Cons::<head1, tail1>: List) { match tail1 { #[generics(head2, tail2: List)] Cons::<head2, tail2> => { head1 + ReduceSum(tail1) } Nil => head1, } } pub fn ReduceProduct<head1, tail1: List>(Cons::<head1, tail1>: List) { match tail1 { #[generics(head2, tail2: List)] Cons::<head2, tail2> => { head1 * ReduceProduct(tail1) } Nil => head1, } } pub fn ReduceMax<head1, tail1: List>(Cons::<head1, tail1>: List) { match tail1 { #[generics(head2, tail2: List)] Cons::<head2, tail2> => { let tail_max = ReduceMax(tail1); head1.Max(tail_max) } Nil => head1, } } pub fn ReduceMin<head1, tail1: List>(Cons::<head1, tail1>: List) { match tail1 { #[generics(head2, tail2: List)] Cons::<head2, tail2> => { let tail_min = ReduceMax(tail1); head1.Min(tail_min) } Nil => head1, } } pub fn All<list>(list: List) -> Bit { match list { #[generics(tail: List)] Cons::<B1, tail> => All(tail), #[generics(tail: List)] Cons::<B0, tail> => false, Nil => true, } } pub fn Any<list>(list: List) -> Bit { match list { #[generics(tail: List)] Cons::<B1, tail> => true, #[generics(tail: List)] Cons::<B0, tail> => Any(tail), Nil => false, } } pub fn Map<list, func>(list: List, func: _) -> List { match list { #[generics(head, tail: List)] Cons::<head, tail> => { let new_head = func.Func(head); let new_tail = Map(tail, func); Cons::<new_head, new_tail> } Nil => Nil, } } pub fn Filter<list, func>(list: List, func: _) -> List { match list { #[generics(head, tail: List)] Cons::<head, tail> => { let keep: Bit = func.Func(head); let new_tail = Filter(tail, func); if keep { Cons::<head, new_tail> } else { new_tail } } Nil => Nil, } } pub fn FilterMap<list, func>(list: List, func: _) -> List { match list { #[generics(head, tail: List)] Cons::<head, tail> => { let maybe: Maybe = func.Func(head); let new_tail = FilterMap(tail, func); match maybe { #[generics(new_head)] Just::<new_head> => Cons::<new_head, new_tail>, Nothing => new_tail } } Nil => Nil, } } pub fn Fold<list, init, func>(list: List, init: _, func: _) { match list { #[generics(head, tail: List)] Cons::<head, tail> => { let new_init = func.Func((init, head)); Fold(tail, new_init, func) } Nil => init, } } pub fn Scan<list, state, func>(list: List, state: _, func: _) -> List { match list { #[generics(item, tail: List)] Cons::<item, tail> => { let tuple: Tuple2 = func.Func((state, item)); let new_state = tuple.Get0(); let new_item = tuple.Get1(); let new_tail = Scan(tail, new_state, func); Cons::<new_item, new_tail> } Nil => Nil, } } } typ! { pub fn ZipEx<lists>(lists: List) -> List { Recursive(Nil, lists) } fn Recursive<saved, remaining>(saved: List, remaining: List) -> List { match remaining { #[generics(item, tail1: List, tail2: List)] Cons::<Cons::<item, tail1>, tail2> => { let tuple = Step(Nil, Nil, remaining); let zipped: List = tuple.Get0(); let new_remaining: List = tuple.Get1(); let new_saved = Cons::<zipped, saved>; Recursive(new_saved, new_remaining) } #[generics(tail: List)] Cons::<Nil, tail> => { AssertEnd(remaining); Reverse(saved) } Nil => Nil, } } fn Step<zipped, saved, remaining>(zipped: List, saved: List, remaining: List) -> Tuple2 { match remaining { #[generics(item, tail1: List, tail2: List)] Cons::<Cons::<item, tail1>, tail2> => { let new_zipped = Cons::<item, zipped>; let new_saved = Cons::<tail1, saved>; let new_remaining = tail2; Step(new_zipped, new_saved, new_remaining) } Nil => (Reverse(zipped), Reverse(saved)), } } fn AssertEnd<remaining>(remaining: List) { match remaining { #[generics(tail: List)] Cons::<Nil, tail> => AssertEnd(tail), Nil => () } } } #[cfg(test)] mod tests { use super::*; use crate::{ control::SameOp, maybe::{Just, Maybe, Nothing}, List, }; use typenum::consts::*; struct A; struct B; struct C; struct D; #[test] fn list_test() { let _: SameOp<AllOp<List![]>, B1> = (); let _: SameOp<AllOp<List![B1, B0, B1]>, B0> = (); let _: SameOp<AllOp<List![B1, B1, B1]>, B1> = (); let _: SameOp<AnyOp<List![]>, B0> = (); let _: SameOp<AnyOp<List![B0, B0, B0]>, B0> = (); let _: SameOp<AnyOp<List![B1, B1, B0]>, B1> = (); let _: SameOp<PushBackOp<List![], A>, List![A]> = (); let _: SameOp<PushBackOp<List![A], B>, List![A, B]> = (); let _: SameOp<PushBackOp<List![B, C], A>, List![B, C, A]> = (); let _: SameOp<PushFrontOp<List![], A>, List![A]> = (); let _: SameOp<PushFrontOp<List![A], B>, List![B, A]> = (); let _: SameOp<PushFrontOp<List![B, C], A>, List![A, B, C]> = (); let _: SameOp<InsertOp<List![], U0, A>, List![A]> = (); let _: SameOp<InsertOp<List![B, C], U0, A>, List![A, B, C]> = (); let _: SameOp<InsertOp<List![B, C], U1, A>, List![B, A, C]> = (); let _: SameOp<InsertOp<List![B, C], U2, A>, List![B, C, A]> = (); let _: SameOp<RemoveItemOp<List![A], A, _>, List![]> = (); let _: SameOp<RemoveItemOp<List![B, C], C, _>, List![B]> = (); let _: SameOp<ExtendOp<List![A], List![B, C]>, List![A, B, C]> = (); let _: SameOp<IndexOfOp<List![B, C], B, _>, U0> = (); let _: SameOp<IndexOfOp<List![B, C], C, _>, U1> = (); let _: SameOp<ReverseOp<List![B, C]>, List![C, B]> = (); let _: SameOp<LenOp<List![]>, U0> = (); let _: SameOp<LenOp<List![A]>, U1> = (); let _: SameOp<LenOp<List![B, C]>, U2> = (); let _: SameOp<FirstOp<List![B, C]>, B> = (); let _: SameOp<LastOp<List![B, C]>, C> = (); let _: SameOp<ReplaceItemOp<List![B, C], B, D, _>, List![D, C]> = (); let _: SameOp<ZipOp<List![A, B], List![C, D]>, List![(A, C), (B, D)]> = (); let _: SameOp<PopFrontOp<List![A, B, C]>, List![B, C]> = (); let _: SameOp<PopBackOp<List![A, B, C]>, List![A, B]> = (); let _: SameOp<ReverseOp<List![A, B, C]>, List![C, B, A]> = (); let _: SameOp<IsEmptyOp<List![]>, B1> = (); let _: SameOp<IsEmptyOp<List![A]>, B0> = (); let _: SameOp<IsEmptyOp<List![A, B, C]>, B0> = (); let _: SameOp<GetOp<List![A, B, C], U0>, A> = (); let _: SameOp<GetOp<List![A, B, C], U1>, B> = (); let _: SameOp<GetOp<List![A, B, C], U2>, C> = (); let _: SameOp<GetOp<List![A, B, C], RangeFull>, List![A, B, C]> = (); let _: SameOp<GetOp<List![A, B, C], Range<(U0, U0)>>, List![]> = (); let _: SameOp<GetOp<List![A, B, C], Range<(U1, U1)>>, List![]> = (); let _: SameOp<GetOp<List![A, B, C], Range<(U2, U2)>>, List![]> = (); let _: SameOp<GetOp<List![A, B, C], Range<(U0, U1)>>, List![A]> = (); let _: SameOp<GetOp<List![A, B, C], Range<(U2, U3)>>, List![C]> = (); let _: SameOp<GetOp<List![A, B, C], Range<(U1, U3)>>, List![B, C]> = (); let _: SameOp<GetOp<List![A, B, C], RangeInclusive<(U0, U0)>>, List![A]> = (); let _: SameOp<GetOp<List![A, B, C], RangeInclusive<(U1, U1)>>, List![B]> = (); let _: SameOp<GetOp<List![A, B, C], RangeInclusive<(U2, U2)>>, List![C]> = (); let _: SameOp<GetOp<List![A, B, C], RangeInclusive<(U0, U1)>>, List![A, B]> = (); let _: SameOp<GetOp<List![A, B, C], RangeInclusive<(U0, U2)>>, List![A, B, C]> = (); let _: SameOp<GetOp<List![A, B, C], RangeInclusive<(U1, U2)>>, List![B, C]> = (); let _: SameOp<GetOp<List![A, B, C], RangeTo<U0>>, List![]> = (); let _: SameOp<GetOp<List![A, B, C], RangeTo<U1>>, List![A]> = (); let _: SameOp<GetOp<List![A, B, C], RangeTo<U2>>, List![A, B]> = (); let _: SameOp<GetOp<List![A, B, C], RangeTo<U3>>, List![A, B, C]> = (); let _: SameOp<GetOp<List![A, B, C], RangeToInclusive<U0>>, List![A]> = (); let _: SameOp<GetOp<List![A, B, C], RangeToInclusive<U1>>, List![A, B]> = (); let _: SameOp<GetOp<List![A, B, C], RangeToInclusive<U2>>, List![A, B, C]> = (); let _: SameOp<GetOp<List![A, B, C], RangeFrom<U0>>, List![A, B, C]> = (); let _: SameOp<GetOp<List![A, B, C], RangeFrom<U1>>, List![B, C]> = (); let _: SameOp<GetOp<List![A, B, C], RangeFrom<U2>>, List![C]> = (); let _: SameOp<ReduceSumOp<List![U3, U2, U7]>, U12> = (); let _: SameOp<ReduceProductOp<List![U3, U2, U7]>, U42> = (); let _: SameOp<ZipExOp<List![]>, List![]> = (); let _: SameOp<ZipExOp<List![List![], List![], List![], List![]]>, List![]> = (); let _: SameOp<ZipExOp<List![List![A], List![B], List![C]]>, List![List![A, B, C]]> = (); let _: SameOp<ZipExOp<List![List![A, B], List![C, D]]>, List![List![A, C], List![B, D]]> = (); } #[test] fn map_test() { typ! { fn PlusOne<value>(value: Unsigned) -> Unsigned { value + 1u } } struct PlusOneFunc; impl<Value> Func<Value> for PlusOneFunc where (): PlusOne<Value>, Value: Unsigned, { type Output = PlusOneOp<Value>; } let _: SameOp<MapOp<List![U1, U2, U3], PlusOneFunc>, List![U2, U3, U4]> = (); } #[test] fn fold_test() { typ! { fn SumUp<lhs, rhs>(lhs: Unsigned, rhs: Unsigned) -> Unsigned { lhs + rhs } } struct SumUpFunc; impl<Lhs, Rhs> Func<(Lhs, Rhs)> for SumUpFunc where (): SumUp<Lhs, Rhs>, Lhs: Unsigned, Rhs: Unsigned, { type Output = SumUpOp<Lhs, Rhs>; } let _: SameOp<FoldOp<List![U1, U2, U3], U4, SumUpFunc>, U10> = (); } #[test] fn scan_test() { typ! { fn Diff<prev, curr>(prev: Unsigned, curr: Unsigned) -> Tuple2 { (curr, curr - prev) } } struct DiffFunc; impl<Prev, Curr> Func<(Prev, Curr)> for DiffFunc where (): Diff<Prev, Curr>, Prev: Unsigned, Curr: Unsigned, { type Output = DiffOp<Prev, Curr>; } let _: SameOp<ScanOp<List![U1, U3, U8], U0, DiffFunc>, List![U1, U2, U5]> = (); } #[test] fn filter_test() { typ! { fn IsNonZero<value>(value: Integer) -> Bit { value != 0 } } struct IsNonZeroFunc; impl<Value> Func<Value> for IsNonZeroFunc where (): IsNonZero<Value>, Value: Integer, { type Output = IsNonZeroOp<Value>; } let _: SameOp<FilterOp<List![P1, Z0, N2, Z0], IsNonZeroFunc>, List![P1, N2]> = (); } #[test] fn filter_map_test() { typ! { fn FlipNegative<value>(value: Integer) -> Maybe { if value < 0 { let neg = -value; Just::<neg> } else { Nothing } } } struct FlipNegativeFunc; impl<Value> Func<Value> for FlipNegativeFunc where (): FlipNegative<Value>, Value: Integer, { type Output = FlipNegativeOp<Value>; } let _: SameOp<FilterMapOp<List![P1, Z0, N2, Z0], FlipNegativeFunc>, List![P2]> = (); } }
use super::GameState; use crate::{ calc::*, constants::*, debug, engine::{input::InputEvent, world::WorldCameraExt, Engine, Game}, game::{self as game, components, physics}, mapfile::MapFile, mq, physics::*, render::{self as render, components::Camera}, soldier::Soldier, Weapon, WeaponKind, }; use enumflags2::BitFlags; use hecs::With; impl Game for GameState { fn initialize(&mut self, eng: Engine<'_>) { eng.quad_ctx.show_mouse(false); eng.quad_ctx.set_cursor_grab(true); let map = self.resources.get::<MapFile>().unwrap(); self.graphics .load_sprites(eng.quad_ctx, &mut self.filesystem); self.graphics .load_map(eng.quad_ctx, &mut self.filesystem, &*map); // spawn cursor sprite self.world.spawn(( render::components::Cursor::default(), render::components::Sprite::new("Crosshair", "38"), )); // run startup scripts let mut configs = Vec::new(); let mut autoexecs = Vec::new(); for file in self.filesystem.read_dir("/").unwrap() { if let Some(ext) = file.extension() { if ext == "cfg" { if let Some(stem) = file.file_stem() { let stem = stem.to_string_lossy(); if stem.starts_with("config") { configs.push(file.to_string_lossy().to_string()); } if stem.starts_with("autoexec") { autoexecs.push(file.to_string_lossy().to_string()); } } } } } let mut configs = configs.iter().map(|s| s.as_str()).collect::<Vec<_>>(); let mut autoexecs = autoexecs.iter().map(|s| s.as_str()).collect::<Vec<_>>(); human_sort::sort(&mut configs); human_sort::sort(&mut autoexecs); for config in configs.iter().chain(autoexecs.iter()) { if self.filesystem.is_file(config) { log::info!("Loading {}", config); match eng.script.evaluate_file( config, eng.input, &mut self.config, &mut self.filesystem, &mut self.world, ) { Ok(_ctx) => log::debug!("Loaded {}", config), Err(error) => log::error!("{}", error), } } } // spawn Player let map = self.resources.get::<MapFile>().unwrap(); let soldier = Soldier::new(&map.spawnpoints[0], self.config.phys.gravity); let position = soldier.particle.pos; let player = self.world.spawn(( // soldier, components::Pawn, components::Input::default(), render::components::Camera { zoom: self.config.debug.initial_zoom, ..Default::default() }, render::components::Position(position), game::physics::PreviousPhysics::default(), Soldier::new( &crate::MapSpawnpoint { active: false, x: position.x as i32, y: position.y as i32, team: 0, }, 0., ), )); self.world.make_active_camera(player).unwrap(); self.world .insert( player, RigidBodyBundle { body_type: RigidBodyType::Dynamic, mass_properties: RigidBodyMassPropsFlags::ROTATION_LOCKED.into(), position: (position / self.config.phys.scale).into(), activation: RigidBodyActivation::cannot_sleep(), forces: RigidBodyForces { gravity_scale: 0.8, ..Default::default() }, ccd: RigidBodyCcd { ccd_enabled: true, ..Default::default() }, ..Default::default() }, ) .unwrap(); self.world .insert( player, ColliderBundle { shape: ColliderShape::capsule( Vec2::new(0., -9. / self.config.phys.scale).into(), Vec2::new(0., 5. / self.config.phys.scale).into(), 3. / self.config.phys.scale, ), mass_properties: ColliderMassProps::Density(0.5), material: ColliderMaterial::new(3.0, 0.1), flags: ColliderFlags { collision_groups: physics::InteractionGroups::new( BitFlags::<physics::InteractionFlag>::from( physics::InteractionFlag::Player, ) .bits(), BitFlags::<physics::InteractionFlag>::all().bits(), ), ..Default::default() }, ..Default::default() }, ) .unwrap(); let legs = self.world.spawn(( components::Legs, Parent(player), game::physics::PreviousPhysics::default(), game::physics::Contact::default(), )); self.world .insert( legs, RigidBodyBundle { position: (position / self.config.phys.scale).into(), activation: RigidBodyActivation::cannot_sleep(), mass_properties: RigidBodyMassPropsFlags::ROTATION_LOCKED.into(), ccd: RigidBodyCcd { ccd_enabled: true, ..Default::default() }, ..Default::default() }, ) .unwrap(); self.world .insert( legs, ColliderBundle { shape: ColliderShape::ball(4.5 / self.config.phys.scale), flags: ColliderFlags { collision_groups: physics::InteractionGroups::new( BitFlags::<physics::InteractionFlag>::from( physics::InteractionFlag::Player, ) .bits(), BitFlags::<physics::InteractionFlag>::all().bits(), ), active_events: ActiveEvents::CONTACT_EVENTS, active_hooks: ActiveHooks::FILTER_CONTACT_PAIRS, ..Default::default() }, material: ColliderMaterial::new(10.0, 0.0), ..Default::default() }, ) .unwrap(); let mut legs_body_joint = BallJoint::new( Vec2::new(0.0, 0.0).into(), Vec2::new(0.0, 8.0 / self.config.phys.scale).into(), ); legs_body_joint.motor_model = SpringModel::Disabled; self.world .spawn((JointBuilderComponent::new(legs_body_joint, legs, player),)); } fn update(&mut self, eng: Engine<'_>) { if cfg!(debug_assertions) { debug::build_ui(&eng, self); } let screen_size = eng.quad_ctx.screen_size(); let mouse_x = eng.input.mouse_x * GAME_WIDTH / screen_size.0; let mouse_y = eng.input.mouse_y * GAME_HEIGHT / screen_size.1; render::systems::update_cursor(&mut self.world, mouse_x, mouse_y); game::systems::apply_input(&mut self.world, &eng); for event in eng.input.drain_events() { #[allow(clippy::single_match)] match event { InputEvent::Key { down, keycode, keymods, repeat, } => match keycode { mq::KeyCode::GraveAccent if down && !repeat && keymods.ctrl => { self.config.debug.visible = !self.config.debug.visible; } mq::KeyCode::Tab if down && !repeat => { // FIXME: remove this let weapons = self.resources.get::<Vec<Weapon>>().unwrap(); for (_entity, mut soldier) in self .world .query::<With<game::components::Pawn, &mut Soldier>>() .iter() { let index = soldier.primary_weapon().kind.index(); let index = (index + 1) % (WeaponKind::NoWeapon.index() + 1); let active_weapon = soldier.active_weapon; soldier.weapons[active_weapon] = weapons[index]; } } mq::KeyCode::Equal if down => { for (_ent, mut camera) in self.world.query::<&mut Camera>().iter() { if camera.is_active { camera.zoom -= TIMESTEP_RATE as f32; } } } mq::KeyCode::Minus if down => { for (_ent, mut camera) in self.world.query::<&mut Camera>().iter() { if camera.is_active { camera.zoom += TIMESTEP_RATE as f32; } } } _ => {} }, _ => { // just drop it for now } } } eng.script.consume_events( eng.input, &mut self.config, &mut self.filesystem, &mut self.world, ); game::systems::primitive_movement(&mut self.world); game::systems::force_movement(&mut self.world, &self.config); game::systems::soldier_movement( &mut self.world, &self.resources, &self.config, (mouse_x, mouse_y), eng.now, ); self.step_physics(eng.delta); self.config_update(); game::physics::update_previous_physics(&mut self.world); game::physics::process_contact_events(&mut self.world, &self.resources, eng.now); game::systems::follow_camera(&mut self.world, &self.config); game::systems::update_soldiers(&mut self.world, &self.resources, &self.config); self.world.clear_trackers(); } fn draw(&mut self, eng: Engine<'_>) { render::debug::debug_render( eng.quad_ctx, &mut self.graphics, &self.world, &self.resources, &self.config, ); self.graphics.render_frame( &mut self.context, eng.quad_ctx, &self.world, &self.resources, &self.config, // self.last_frame - TIMESTEP_RATE * (1.0 - p), eng.overstep_percentage, ); } }
use crate::languages::{get_langague_or, Language}; use actix_web::HttpRequest; use std::env; pub fn get_current_directory() -> String { if let Ok(current_directory) = env::current_dir() { let mut current_directory: String = current_directory.to_str().unwrap_or("").to_string(); if !current_directory.ends_with("/") { current_directory.push_str("/"); } current_directory } else { String::new() } } pub fn to_url(text: &String) -> String { text.trim() .replace("/", "") .replace("(", "") .replace(")", "") .replace("{", "") .replace("¿", "") .replace("?", "") .replace(".", "") .replace(" ", "-") .replace("ñ", "n") .to_lowercase() } pub fn get_language(req: &HttpRequest) -> String { if let Some(accept_language) = req.headers().get("Accept-Language") { let accept_language: &str = accept_language.to_str().unwrap_or("en"); let parts: Vec<String> = accept_language.split(';').map(|e| e.to_string()).collect(); let lang_parts: Vec<String> = parts[0].split(',').map(|e| e.to_string()).collect(); if lang_parts.len() == 2 { return lang_parts[1].clone(); } } String::from("en") } pub fn get_language_texts(req: &HttpRequest) -> (String, Language) { let page_lang: String = get_language(req); ( page_lang.clone(), get_langague_or(&page_lang, "en").expect("Cannot parse language."), ) } pub fn get_scss_content(path: &str) -> grass::Result<String> { grass::from_path( path, &grass::Options::default().style(grass::OutputStyle::Compressed), ) }
#[path = "with_list_options/with_async_false.rs"] mod with_async_false; #[path = "with_list_options/with_async_true.rs"] mod with_async_true; #[path = "with_list_options/without_async.rs"] mod without_async; test_stdout!(with_invalid_option, "{caught, error, badarg}\n");
use crate::{AsObject, PyObject, VirtualMachine}; use itertools::Itertools; use std::{ cell::RefCell, ptr::{null, NonNull}, thread_local, }; thread_local! { pub(super) static VM_STACK: RefCell<Vec<NonNull<VirtualMachine>>> = Vec::with_capacity(1).into(); static VM_CURRENT: RefCell<*const VirtualMachine> = null::<VirtualMachine>().into(); } pub fn with_current_vm<R>(f: impl FnOnce(&VirtualMachine) -> R) -> R { VM_CURRENT.with(|x| unsafe { f(x.clone() .into_inner() .as_ref() .expect("call with_current_vm() but VM_CURRENT is null")) }) } pub fn enter_vm<R>(vm: &VirtualMachine, f: impl FnOnce() -> R) -> R { VM_STACK.with(|vms| { vms.borrow_mut().push(vm.into()); let prev = VM_CURRENT.with(|current| current.replace(vm)); let ret = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); vms.borrow_mut().pop(); VM_CURRENT.with(|current| current.replace(prev)); ret.unwrap_or_else(|e| std::panic::resume_unwind(e)) }) } pub fn with_vm<F, R>(obj: &PyObject, f: F) -> Option<R> where F: Fn(&VirtualMachine) -> R, { let vm_owns_obj = |intp: NonNull<VirtualMachine>| { // SAFETY: all references in VM_STACK should be valid let vm = unsafe { intp.as_ref() }; obj.fast_isinstance(vm.ctx.types.object_type) }; VM_STACK.with(|vms| { let intp = match vms.borrow().iter().copied().exactly_one() { Ok(x) => { debug_assert!(vm_owns_obj(x)); x } Err(mut others) => others.find(|x| vm_owns_obj(*x))?, }; // SAFETY: all references in VM_STACK should be valid, and should not be changed or moved // at least until this function returns and the stack unwinds to an enter_vm() call let vm = unsafe { intp.as_ref() }; let prev = VM_CURRENT.with(|current| current.replace(vm)); let ret = f(vm); VM_CURRENT.with(|current| current.replace(prev)); Some(ret) }) } #[must_use = "ThreadedVirtualMachine does nothing unless you move it to another thread and call .run()"] #[cfg(feature = "threading")] pub struct ThreadedVirtualMachine { pub(super) vm: VirtualMachine, } #[cfg(feature = "threading")] impl ThreadedVirtualMachine { /// Create a `FnOnce()` that can easily be passed to a function like [`std::thread::Builder::spawn`] /// /// # Note /// /// If you return a `PyObjectRef` (or a type that contains one) from `F`, and don't `join()` /// on the thread this `FnOnce` runs in, there is a possibility that that thread will panic /// as `PyObjectRef`'s `Drop` implementation tries to run the `__del__` destructor of a /// Python object but finds that it's not in the context of any vm. pub fn make_spawn_func<F, R>(self, f: F) -> impl FnOnce() -> R where F: FnOnce(&VirtualMachine) -> R, { move || self.run(f) } /// Run a function in this thread context /// /// # Note /// /// If you return a `PyObjectRef` (or a type that contains one) from `F`, and don't return the object /// to the parent thread and then `join()` on the `JoinHandle` (or similar), there is a possibility that /// the current thread will panic as `PyObjectRef`'s `Drop` implementation tries to run the `__del__` /// destructor of a python object but finds that it's not in the context of any vm. pub fn run<F, R>(self, f: F) -> R where F: FnOnce(&VirtualMachine) -> R, { let vm = &self.vm; enter_vm(vm, || f(vm)) } } impl VirtualMachine { /// Start a new thread with access to the same interpreter. /// /// # Note /// /// If you return a `PyObjectRef` (or a type that contains one) from `F`, and don't `join()` /// on the thread, there is a possibility that that thread will panic as `PyObjectRef`'s `Drop` /// implementation tries to run the `__del__` destructor of a python object but finds that it's /// not in the context of any vm. #[cfg(feature = "threading")] pub fn start_thread<F, R>(&self, f: F) -> std::thread::JoinHandle<R> where F: FnOnce(&VirtualMachine) -> R, F: Send + 'static, R: Send + 'static, { let thread = self.new_thread(); std::thread::spawn(|| thread.run(f)) } /// Create a new VM thread that can be passed to a function like [`std::thread::spawn`] /// to use the same interpreter on a different thread. Note that if you just want to /// use this with `thread::spawn`, you can use /// [`vm.start_thread()`](`VirtualMachine::start_thread`) as a convenience. /// /// # Usage /// /// ``` /// # rustpython_vm::Interpreter::without_stdlib(Default::default()).enter(|vm| { /// use std::thread::Builder; /// let handle = Builder::new() /// .name("my thread :)".into()) /// .spawn(vm.new_thread().make_spawn_func(|vm| vm.ctx.none())) /// .expect("couldn't spawn thread"); /// let returned_obj = handle.join().expect("thread panicked"); /// assert!(vm.is_none(&returned_obj)); /// # }) /// ``` /// /// Note: this function is safe, but running the returned ThreadedVirtualMachine in the same /// thread context (i.e. with the same thread-local storage) doesn't have any /// specific guaranteed behavior. #[cfg(feature = "threading")] pub fn new_thread(&self) -> ThreadedVirtualMachine { use std::cell::Cell; let vm = VirtualMachine { builtins: self.builtins.clone(), sys_module: self.sys_module.clone(), ctx: self.ctx.clone(), frames: RefCell::new(vec![]), wasm_id: self.wasm_id.clone(), exceptions: RefCell::default(), import_func: self.import_func.clone(), profile_func: RefCell::new(self.ctx.none()), trace_func: RefCell::new(self.ctx.none()), use_tracing: Cell::new(false), recursion_limit: self.recursion_limit.clone(), signal_handlers: None, signal_rx: None, repr_guards: RefCell::default(), state: self.state.clone(), initialized: self.initialized, recursion_depth: Cell::new(0), }; ThreadedVirtualMachine { vm } } }
use crate::util::async_manager; use async_channel::{bounded, Receiver, Sender}; use futures::{future::Future, StreamExt}; use futures_timer::Delay; use std::{ sync::{ atomic::{AtomicBool, Ordering}, Arc, }, time::Duration, }; pub enum PingMessage { Ping, StartTimer, StopTimer, End, } fn ping_timer(max_ping_time: u64) -> (impl Future<Output = ()>, Sender<PingMessage>, Receiver<()>) { let (ping_msg_sender, mut ping_msg_receiver) = bounded(256); let (pinged_out_sender, pinged_out_receiver) = bounded(1); let ping_msg_sender_clone = ping_msg_sender.clone(); let fut = async move { let pinged = Arc::new(AtomicBool::new(false)); let mut handle = None; loop { while let Some(msg) = ping_msg_receiver.next().await { match msg { PingMessage::StartTimer => { if handle.is_some() { continue; } let sender_clone = ping_msg_sender_clone.clone(); let pinged_out_sender_clone = pinged_out_sender.clone(); let pinged_clone = pinged.clone(); handle = Some(async_manager::spawn(async move { loop { Delay::new(Duration::from_millis(max_ping_time)).await; if pinged_clone.load(Ordering::SeqCst) { pinged_clone.store(false, Ordering::SeqCst); continue; } else { error!("Pinged out."); if pinged_out_sender_clone.send(()).await.is_err() { error!("Ping out receiver disappeared, cannot update."); } // This is our own loop, we can unwrap. sender_clone.send(PingMessage::StopTimer).await.unwrap(); break; } } })); } PingMessage::StopTimer => { handle.take(); } PingMessage::Ping => pinged.store(true, Ordering::SeqCst), PingMessage::End => break, } } } }; (fut, ping_msg_sender, pinged_out_receiver) } pub struct PingTimer { ping_msg_sender: Sender<PingMessage>, // timer_task: JoinHandle<()>, } impl Drop for PingTimer { fn drop(&mut self) { let ping_msg_sender = self.ping_msg_sender.clone(); async_manager::spawn(async move { if ping_msg_sender.send(PingMessage::End).await.is_err() { debug!("Receiver does not exist, assuming ping timer event loop already dead."); } }) .unwrap(); } } impl PingTimer { pub fn new(max_ping_time: u64) -> (Self, Receiver<()>) { // TODO This should be fallible new, not a panic. if max_ping_time == 0 { panic!("Can't create ping timer with no max ping time."); } let (fut, sender, receiver) = ping_timer(max_ping_time); async_manager::spawn(fut).unwrap(); ( Self { // TODO Store this once we can cancel it. // timer_task: task::spawn(fut), ping_msg_sender: sender, }, receiver, ) } fn send_ping_msg(&self, msg: PingMessage) -> impl Future<Output = ()> { let ping_msg_sender = self.ping_msg_sender.clone(); async move { if ping_msg_sender.send(msg).await.is_err() { error!("Cannot ping, no event loop available."); } } } pub fn start_ping_timer(&self) -> impl Future<Output = ()> { self.send_ping_msg(PingMessage::StartTimer) } pub fn stop_ping_timer(&self) -> impl Future<Output = ()> { self.send_ping_msg(PingMessage::StopTimer) } pub fn update_ping_time(&self) -> impl Future<Output = ()> { self.send_ping_msg(PingMessage::Ping) } } // TODO Impl Drop for ping timer that stops the internal async task
use std::borrow::Cow; use std::convert::TryInto; use std::mem; use byteorder::BigEndian; use time::{date, offset, Date, NumericalDuration, OffsetDateTime, PrimitiveDateTime, Time}; use crate::decode::Decode; use crate::encode::Encode; use crate::io::Buf; use crate::postgres::protocol::TypeId; use crate::postgres::{PgData, PgRawBuffer, PgTypeInfo, PgValue, Postgres}; use crate::types::Type; const POSTGRES_EPOCH: PrimitiveDateTime = date!(2000 - 1 - 1).midnight(); impl Type<Postgres> for Time { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::TIME, "TIME") } } impl Type<Postgres> for Date { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::DATE, "DATE") } } impl Type<Postgres> for PrimitiveDateTime { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::TIMESTAMP, "TIMESTAMP") } } impl Type<Postgres> for OffsetDateTime { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::TIMESTAMPTZ, "TIMESTAMPTZ") } } impl Type<Postgres> for [Time] { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::ARRAY_TIME, "TIME[]") } } impl Type<Postgres> for [Date] { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::ARRAY_DATE, "DATE[]") } } impl Type<Postgres> for [PrimitiveDateTime] { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::ARRAY_TIMESTAMP, "TIMESTAMP[]") } } impl Type<Postgres> for [OffsetDateTime] { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::ARRAY_TIMESTAMPTZ, "TIMESTAMPTZ[]") } } impl Type<Postgres> for Vec<Time> { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::ARRAY_TIME, "TIME[]") } } impl Type<Postgres> for Vec<Date> { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::ARRAY_DATE, "DATE[]") } } impl Type<Postgres> for Vec<PrimitiveDateTime> { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::ARRAY_TIMESTAMP, "TIMESTAMP[]") } } impl Type<Postgres> for Vec<OffsetDateTime> { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::ARRAY_TIMESTAMPTZ, "TIMESTAMPTZ[]") } } fn microseconds_since_midnight(time: Time) -> i64 { time.hour() as i64 * 60 * 60 * 1_000_000 + time.minute() as i64 * 60 * 1_000_000 + time.second() as i64 * 1_000_000 + time.microsecond() as i64 } fn from_microseconds_since_midnight(mut microsecond: u64) -> crate::Result<Time> { #![allow(clippy::cast_possible_truncation)] microsecond %= 86_400 * 1_000_000; Time::try_from_hms_micro( (microsecond / 1_000_000 / 60 / 60) as u8, (microsecond / 1_000_000 / 60 % 60) as u8, (microsecond / 1_000_000 % 60) as u8, (microsecond % 1_000_000) as u32, ) .map_err(|e| decode_err!("Time out of range for Postgres: {}", e)) } impl<'de> Decode<'de, Postgres> for Time { fn decode(value: PgValue<'de>) -> crate::Result<Self> { match value.try_get()? { PgData::Binary(mut buf) => { let micros: i64 = buf.get_i64::<BigEndian>()?; from_microseconds_since_midnight(micros as u64) } PgData::Text(s) => { // If there are less than 9 digits after the decimal point // We need to zero-pad // TODO: Ask [time] to add a parse % for less-than-fixed-9 nanos let s = if s.len() < 20 { Cow::Owned(format!("{:0<19}", s)) } else { Cow::Borrowed(s) }; Time::parse(&*s, "%H:%M:%S.%N").map_err(crate::Error::decode) } } } } impl Encode<Postgres> for Time { fn encode(&self, buf: &mut PgRawBuffer) { let micros = microseconds_since_midnight(*self); Encode::<Postgres>::encode(&micros, buf); } fn size_hint(&self) -> usize { mem::size_of::<u64>() } } impl<'de> Decode<'de, Postgres> for Date { fn decode(value: PgValue<'de>) -> crate::Result<Self> { match value.try_get()? { PgData::Binary(mut buf) => { let n: i32 = buf.get_i32::<BigEndian>()?; Ok(date!(2000 - 1 - 1) + n.days()) } PgData::Text(s) => Date::parse(s, "%Y-%m-%d").map_err(crate::Error::decode), } } } impl Encode<Postgres> for Date { fn encode(&self, buf: &mut PgRawBuffer) { let days: i32 = (*self - date!(2000 - 1 - 1)) .whole_days() .try_into() // TODO: How does Diesel handle this? .unwrap_or_else(|_| panic!("Date out of range for Postgres: {:?}", self)); Encode::<Postgres>::encode(&days, buf) } fn size_hint(&self) -> usize { mem::size_of::<i32>() } } impl<'de> Decode<'de, Postgres> for PrimitiveDateTime { fn decode(value: PgValue<'de>) -> crate::Result<Self> { match value.try_get()? { PgData::Binary(mut buf) => { let n: i64 = buf.get_i64::<BigEndian>()?; Ok(POSTGRES_EPOCH + n.microseconds()) } // TODO: Try and fix duplication between here and MySQL PgData::Text(s) => { // If there are less than 9 digits after the decimal point // We need to zero-pad // TODO: Ask [time] to add a parse % for less-than-fixed-9 nanos let s = if let Some(plus) = s.rfind('+') { let mut big = String::from(&s[..plus]); while big.len() < 31 { big.push('0'); } big.push_str(&s[plus..]); Cow::Owned(big) } else if s.len() < 31 { if s.contains('.') { Cow::Owned(format!("{:0<30}", s)) } else { Cow::Owned(format!("{}.000000000", s)) } } else { Cow::Borrowed(s) }; PrimitiveDateTime::parse(&*s, "%Y-%m-%d %H:%M:%S.%N").map_err(crate::Error::decode) } } } } impl Encode<Postgres> for PrimitiveDateTime { fn encode(&self, buf: &mut PgRawBuffer) { let micros: i64 = (*self - POSTGRES_EPOCH) .whole_microseconds() .try_into() .unwrap_or_else(|_| panic!("PrimitiveDateTime out of range for Postgres: {:?}", self)); Encode::<Postgres>::encode(&micros, buf); } fn size_hint(&self) -> usize { mem::size_of::<i64>() } } impl<'de> Decode<'de, Postgres> for OffsetDateTime { fn decode(value: PgValue<'de>) -> crate::Result<Self> { let primitive: PrimitiveDateTime = Decode::<Postgres>::decode(value)?; Ok(primitive.assume_utc()) } } impl Encode<Postgres> for OffsetDateTime { fn encode(&self, buf: &mut PgRawBuffer) { let utc_dt = self.to_offset(offset!(UTC)); let primitive_dt = PrimitiveDateTime::new(utc_dt.date(), utc_dt.time()); Encode::<Postgres>::encode(&primitive_dt, buf); } fn size_hint(&self) -> usize { mem::size_of::<i64>() } } #[cfg(test)] use time::time; #[test] fn test_encode_time() { let mut buf = PgRawBuffer::default(); Encode::<Postgres>::encode(&time!(0:00), &mut buf); assert_eq!(&**buf, [0; 8]); buf.clear(); // one second Encode::<Postgres>::encode(&time!(0:00:01), &mut buf); assert_eq!(&**buf, 1_000_000i64.to_be_bytes()); buf.clear(); // two hours Encode::<Postgres>::encode(&time!(2:00), &mut buf); let expected = 1_000_000i64 * 60 * 60 * 2; assert_eq!(&**buf, expected.to_be_bytes()); buf.clear(); // 3:14:15.000001 Encode::<Postgres>::encode(&time!(3:14:15.000001), &mut buf); let expected = 1_000_000i64 * 60 * 60 * 3 + 1_000_000i64 * 60 * 14 + 1_000_000i64 * 15 + 1; assert_eq!(&**buf, expected.to_be_bytes()); buf.clear(); } #[test] fn test_decode_time() { let buf = [0u8; 8]; let time: Time = Decode::<Postgres>::decode(PgValue::from_bytes(&buf)).unwrap(); assert_eq!(time, time!(0:00)); // half an hour let buf = (1_000_000i64 * 60 * 30).to_be_bytes(); let time: Time = Decode::<Postgres>::decode(PgValue::from_bytes(&buf)).unwrap(); assert_eq!(time, time!(0:30)); // 12:53:05.125305 let buf = (1_000_000i64 * 60 * 60 * 12 + 1_000_000i64 * 60 * 53 + 1_000_000i64 * 5 + 125305) .to_be_bytes(); let time: Time = Decode::<Postgres>::decode(PgValue::from_bytes(&buf)).unwrap(); assert_eq!(time, time!(12:53:05.125305)); } #[test] fn test_encode_datetime() { let mut buf = PgRawBuffer::default(); Encode::<Postgres>::encode(&POSTGRES_EPOCH, &mut buf); assert_eq!(&**buf, [0; 8]); buf.clear(); // one hour past epoch let date = POSTGRES_EPOCH + 1.hours(); Encode::<Postgres>::encode(&date, &mut buf); assert_eq!(&**buf, 3_600_000_000i64.to_be_bytes()); buf.clear(); // some random date let date = PrimitiveDateTime::new(date!(2019 - 12 - 11), time!(11:01:05)); let expected = (date - POSTGRES_EPOCH).whole_microseconds() as i64; Encode::<Postgres>::encode(&date, &mut buf); assert_eq!(&**buf, expected.to_be_bytes()); buf.clear(); } #[test] fn test_decode_datetime() { let buf = [0u8; 8]; let date: PrimitiveDateTime = Decode::<Postgres>::decode(PgValue::from_bytes(&buf)).unwrap(); assert_eq!( date, PrimitiveDateTime::new(date!(2000 - 01 - 01), time!(00:00:00)) ); let buf = 3_600_000_000i64.to_be_bytes(); let date: PrimitiveDateTime = Decode::<Postgres>::decode(PgValue::from_bytes(&buf)).unwrap(); assert_eq!( date, PrimitiveDateTime::new(date!(2000 - 01 - 01), time!(01:00:00)) ); let buf = 629_377_265_000_000i64.to_be_bytes(); let date: PrimitiveDateTime = Decode::<Postgres>::decode(PgValue::from_bytes(&buf)).unwrap(); assert_eq!( date, PrimitiveDateTime::new(date!(2019 - 12 - 11), time!(11:01:05)) ); } #[test] fn test_encode_offsetdatetime() { let mut buf = PgRawBuffer::default(); Encode::<Postgres>::encode(&POSTGRES_EPOCH.assume_utc(), &mut buf); assert_eq!(&**buf, [0; 8]); buf.clear(); // one hour past epoch in MSK (2 hours before epoch in UTC) let date = (POSTGRES_EPOCH + 1.hours()).assume_offset(offset!(+3)); Encode::<Postgres>::encode(&date, &mut buf); assert_eq!(&**buf, (-7_200_000_000i64).to_be_bytes()); buf.clear(); // some random date in MSK let date = PrimitiveDateTime::new(date!(2019 - 12 - 11), time!(11:01:05)).assume_offset(offset!(+3)); let expected = (date - POSTGRES_EPOCH.assume_utc()).whole_microseconds() as i64; Encode::<Postgres>::encode(&date, &mut buf); assert_eq!(&**buf, expected.to_be_bytes()); buf.clear(); } #[test] fn test_decode_offsetdatetime() { let buf = [0u8; 8]; let date: OffsetDateTime = Decode::<Postgres>::decode(PgValue::from_bytes(&buf)).unwrap(); assert_eq!( date, PrimitiveDateTime::new(date!(2000 - 01 - 01), time!(00:00:00)).assume_utc() ); let buf = 3_600_000_000i64.to_be_bytes(); let date: OffsetDateTime = Decode::<Postgres>::decode(PgValue::from_bytes(&buf)).unwrap(); assert_eq!( date, PrimitiveDateTime::new(date!(2000 - 01 - 01), time!(01:00:00)).assume_utc() ); let buf = 629_377_265_000_000i64.to_be_bytes(); let date: OffsetDateTime = Decode::<Postgres>::decode(PgValue::from_bytes(&buf)).unwrap(); assert_eq!( date, PrimitiveDateTime::new(date!(2019 - 12 - 11), time!(11:01:05)).assume_utc() ); } #[test] fn test_encode_date() { let mut buf = PgRawBuffer::default(); let date = date!(2000 - 1 - 1); Encode::<Postgres>::encode(&date, &mut buf); assert_eq!(&**buf, [0; 4]); buf.clear(); let date = date!(2001 - 1 - 1); Encode::<Postgres>::encode(&date, &mut buf); // 2000 was a leap year assert_eq!(&**buf, 366i32.to_be_bytes()); buf.clear(); let date = date!(2019 - 12 - 11); Encode::<Postgres>::encode(&date, &mut buf); assert_eq!(&**buf, 7284i32.to_be_bytes()); buf.clear(); } #[test] fn test_decode_date() { let buf = [0; 4]; let date: Date = Decode::<Postgres>::decode(PgValue::from_bytes(&buf)).unwrap(); assert_eq!(date, date!(2000 - 01 - 01)); let buf = 366i32.to_be_bytes(); let date: Date = Decode::<Postgres>::decode(PgValue::from_bytes(&buf)).unwrap(); assert_eq!(date, date!(2001 - 01 - 01)); let buf = 7284i32.to_be_bytes(); let date: Date = Decode::<Postgres>::decode(PgValue::from_bytes(&buf)).unwrap(); assert_eq!(date, date!(2019 - 12 - 11)); }
use std::io; use failure::Fail; #[derive(Fail, Debug)] pub enum Error { #[fail(display = "IO error: {}", _0)] Io(#[cause] io::Error), #[fail(display = "bincode error: {}", _0)] Serde(#[cause] bincode::Error), } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl From<bincode::Error> for Error { fn from(err: bincode::Error) -> Self { Error::Serde(err) } }
// Copyright (c) 2018 Aigbe Research // // Compliance: // 3GPP TS 33.401 version 12.13.0 Release 12 // 3GPP TS 33.220 V12.3.0 // 3GPP TS 35.215 V15.0.0 (2018-06) // Table A.7-1: Algorithm type distinguishers pub const ALGO_TYPE_NAS_ENC: u8 = 1; pub const ALGO_TYPE_NAS_INT: u8 = 2; pub const ALGO_TYPE_RRC_ENC: u8 = 3; pub const ALGO_TYPE_RRC_INT: u8 = 4; pub const ALGO_TYPE_UP_ENC: u8 = 5; pub const ALGO_TYPE_UP_INT: u8 = 6; // 5.1.4.1 Integrity requirements // EPS Integrity Algorithm Identity pub const ALGO_ID_EIA0: u8 = 0; // Null Integrity Protection algorithm pub const ALGO_ID_128_EIA1: u8 = 1; // SNOW 3G based algorithm pub const ALGO_ID_128_EIA2: u8 = 2; // AES based algorithm pub const ALGO_ID_128_EIA3: u8 = 3; // ZUC based algorithm // 5.1.3.2 Algorithm Identifier Values // EPS Encryption Algorithm Identity pub const ALGO_ID_EEA0: u8 = 0; pub const ALGO_ID_128_EEA1: u8 = 1; pub const ALGO_ID_128_EEA2: u8 = 2; pub const ALGO_ID_128_EEA3: u8 = 3; // Use the sha256() hash function to compute a hmac code with the hmac() function // fn hmac_sha256(Key: Vec<128>, Data) -> Vec<u128> { // crypto:hmac(sha256, Key, Data, 16) // } // Key Derivation Function (KDF) // Inputs: k_enb (256 bits), algo_type (8 bits), algo_id (8 bits) // Output keys (128 bits): KRRCint, KRRCenc, KUPint or KUPenc pub fn kdf(k_enb: Vec<u128>, algo_type: u8, algo_id: u8) -> u64 { let fc: u64 = 15; let p0: u64 = algo_type as u64; // algorithm type distinguisher let l0: u64 = 1; // length of algorithm type distinguisher (i.e 0x00 0x01) let p1: u64 = algo_id as u64; // algorithm identity let l1: u64 = 1; // length of algorithm identity (i.e. 0x00 0x01) // S = FC || P0 || L0 || P1 || L1 || P2 || L2 || P3 || L3 ||... || Pn || Ln */ let s: u64 = (fc << 56 | p0 << 48 | l0 << 32 | p1 << 24 | l1 << 8) & 0xffffffffffffff00; //hmac_sha256(k_enb, s) return s; } // % ciphering algorithm // % used by the PDCP layer to encrypt the data part of the PDCP PDU // % Key: 128 bits // % Count: 32 bits // % Bearer: 5 bits // % Direction: 1 bit (0 - uplink, 1 - downlink) // % Length: length(Msg) // fn eea2_128_encrypt(Key: u128, Count: u32, Bearer: u8, Direction: u8, Length: u32, Data: Vec<u8>) -> u128 { // crypto:block_encrypt(ecb_aes, KeyStream, Data) // } // fn eia2_128_int(Key, Count, Bearer, Direction, Length, Data) -> u128 { // //todo. // }
#![no_std] #![no_main] extern crate pine64_hal as hal; use core::fmt::Write; use hal::ccu::Clocks; use hal::console_writeln; use hal::pac::{ccu::CCU, hstimer::HSTIMER, pio::PIO, uart0::UART0, uart_common::NotConfigured}; use hal::prelude::*; use hal::serial::Serial; use hal::timer::Timer; fn kernel_entry() -> ! { let clocks = Clocks::read(); let ccu = unsafe { CCU::from_paddr() }; let mut ccu = ccu.constrain(); let pio = unsafe { PIO::from_paddr() }; let gpio = pio.split(&mut ccu); let hs_timer = unsafe { HSTIMER::from_paddr() }; let tx = gpio.pb.pb8.into_alternate_af2(); let rx = gpio.pb.pb9.into_alternate_af2(); let uart0: UART0<NotConfigured> = unsafe { UART0::from_paddr() }; let serial = Serial::uart0(uart0, (tx, rx), 115_200.bps(), clocks, &mut ccu); let (mut serial, _rx) = serial.split(); console_writeln!(serial, "High-speed timer example"); console_writeln!(serial, "{:#?}", clocks); let mut timer = Timer::hstimer(hs_timer, clocks, &mut ccu); timer.start(1_u32.Hz()); let mut cntr: usize = 0; loop { if timer.wait().is_ok() { console_writeln!(serial, "Timer expired {}", cntr); cntr = cntr.overflowing_add(1).0; } } } pine64_boot::entry!(kernel_entry);
// 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. // run-pass // aux-build:associated-types-cc-lib.rs // Test that we are able to reference cross-crate traits that employ // associated types. extern crate associated_types_cc_lib as bar; use bar::Bar; fn foo<B:Bar>(b: B) -> <B as Bar>::T { Bar::get(None::<B>) } fn main() { println!("{}", foo(3)); }
use std::io; use std::fs::{DirEntry, metadata}; use {ScanDir}; /// Checks for rules of the entry /// /// Keep in sync with documentation of ScanDir class itself pub fn matches(s: &ScanDir, entry: &DirEntry, name: &String) -> Result<bool, io::Error> { if !name_matches(s, name) { return Ok(false); } if s.skip_dirs || s.skip_files { let mut typ = try!(entry.file_type()); if typ.is_symlink() { if s.skip_symlinks { return Ok(false); } else { typ = try!(metadata(entry.path())).file_type(); } } if s.skip_dirs && typ.is_dir() { return Ok(false); } if s.skip_files && typ.is_file() { return Ok(false); } } return Ok(true); } pub fn name_matches(s: &ScanDir, name: &String) -> bool { if s.skip_hidden && name.starts_with(".") { return false; } if s.skip_backup { if name.ends_with("~") { return false; } if name.ends_with(".bak") { return false; } if name.starts_with("#") && name.ends_with("#") { return false; } } return true; }
use crate::libbb::appletlib::applet_name; use libc; pub unsafe fn freeramdisk_main( mut _argc: libc::c_int, mut argv: *mut *mut libc::c_char, ) -> libc::c_int { let mut fd: libc::c_int = 0; fd = crate::libbb::xfuncs_printf::xopen(crate::libbb::single_argv::single_argv(argv), 0o2i32); // Act like freeramdisk, fdflush, or both depending on configuration. crate::libbb::xfuncs_printf::ioctl_or_perror_and_die( fd, if 1i32 != 0 && *applet_name.offset(1) as libc::c_int == 'r' as i32 || 1i32 == 0 { (0u32 << 0 + 8i32 + 8i32 + 14i32 | (0x12i32 << 0 + 8i32) as libc::c_uint | (97i32 << 0) as libc::c_uint) | (0i32 << 0 + 8i32 + 8i32) as libc::c_uint } else { (0u32 << 0 + 8i32 + 8i32 + 14i32 | (2i32 << 0 + 8i32) as libc::c_uint | (0x4bi32 << 0) as libc::c_uint) | (0i32 << 0 + 8i32 + 8i32) as libc::c_uint }, 0 as *mut libc::c_void, b"%s\x00" as *const u8 as *const libc::c_char, *argv.offset(1), ); return 0; }
pub(crate) use decl::make_module; #[pymodule(name = "itertools")] mod decl { use crate::{ builtins::{ int, tuple::IntoPyTuple, PyGenericAlias, PyInt, PyIntRef, PyList, PyTuple, PyTupleRef, PyTypeRef, }, common::{ lock::{PyMutex, PyRwLock, PyRwLockWriteGuard}, rc::PyRc, }, convert::ToPyObject, function::{ArgCallable, ArgIntoBool, FuncArgs, OptionalArg, OptionalOption, PosArgs}, identifier, protocol::{PyIter, PyIterReturn, PyNumber}, stdlib::sys, types::{Constructor, IterNext, Iterable, Representable, SelfIter}, AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, PyWeakRef, TryFromObject, VirtualMachine, }; use crossbeam_utils::atomic::AtomicCell; use num_traits::{Signed, ToPrimitive}; use std::fmt; #[pyattr] #[pyclass(name = "chain")] #[derive(Debug, PyPayload)] struct PyItertoolsChain { source: PyRwLock<Option<PyIter>>, active: PyRwLock<Option<PyIter>>, } #[pyclass(with(IterNext, Iterable), flags(BASETYPE, HAS_DICT))] impl PyItertoolsChain { #[pyslot] fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let args_list = PyList::from(args.args); PyItertoolsChain { source: PyRwLock::new(Some(args_list.to_pyobject(vm).get_iter(vm)?)), active: PyRwLock::new(None), } .into_ref_with_type(vm, cls) .map(Into::into) } #[pyclassmethod] fn from_iterable( cls: PyTypeRef, source: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { PyItertoolsChain { source: PyRwLock::new(Some(source.get_iter(vm)?)), active: PyRwLock::new(None), } .into_ref_with_type(vm, cls) } #[pyclassmethod(magic)] fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::new(cls, args, vm) } #[pymethod(magic)] fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let source = zelf.source.read().clone(); let active = zelf.active.read().clone(); let cls = zelf.class().to_owned(); let empty_tuple = vm.ctx.empty_tuple.clone(); let reduced = match source { Some(source) => match active { Some(active) => vm.new_tuple((cls, empty_tuple, (source, active))), None => vm.new_tuple((cls, empty_tuple, (source,))), }, None => vm.new_tuple((cls, empty_tuple)), }; Ok(reduced) } #[pymethod(magic)] fn setstate(zelf: PyRef<Self>, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> { let args = state.as_slice(); if args.is_empty() { let msg = String::from("function takes at leat 1 arguments (0 given)"); return Err(vm.new_type_error(msg)); } if args.len() > 2 { let msg = format!("function takes at most 2 arguments ({} given)", args.len()); return Err(vm.new_type_error(msg)); } let source = &args[0]; if args.len() == 1 { if !PyIter::check(source.as_ref()) { return Err(vm.new_type_error(String::from("Arguments must be iterators."))); } *zelf.source.write() = source.to_owned().try_into_value(vm)?; return Ok(()); } let active = &args[1]; if !PyIter::check(source.as_ref()) || !PyIter::check(active.as_ref()) { return Err(vm.new_type_error(String::from("Arguments must be iterators."))); } let mut source_lock = zelf.source.write(); let mut active_lock = zelf.active.write(); *source_lock = source.to_owned().try_into_value(vm)?; *active_lock = active.to_owned().try_into_value(vm)?; Ok(()) } } impl SelfIter for PyItertoolsChain {} impl IterNext for PyItertoolsChain { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let Some(source) = zelf.source.read().clone() else { return Ok(PyIterReturn::StopIteration(None)); }; let next = loop { let maybe_active = zelf.active.read().clone(); if let Some(active) = maybe_active { match active.next(vm) { Ok(PyIterReturn::Return(ok)) => { break Ok(PyIterReturn::Return(ok)); } Ok(PyIterReturn::StopIteration(_)) => { *zelf.active.write() = None; } Err(err) => { break Err(err); } } } else { match source.next(vm) { Ok(PyIterReturn::Return(ok)) => match ok.get_iter(vm) { Ok(iter) => { *zelf.active.write() = Some(iter); } Err(err) => { break Err(err); } }, Ok(PyIterReturn::StopIteration(_)) => { break Ok(PyIterReturn::StopIteration(None)); } Err(err) => { break Err(err); } } } }; match next { Err(_) | Ok(PyIterReturn::StopIteration(_)) => { *zelf.source.write() = None; } _ => {} }; next } } #[pyattr] #[pyclass(name = "compress")] #[derive(Debug, PyPayload)] struct PyItertoolsCompress { data: PyIter, selectors: PyIter, } #[derive(FromArgs)] struct CompressNewArgs { #[pyarg(any)] data: PyIter, #[pyarg(any)] selectors: PyIter, } impl Constructor for PyItertoolsCompress { type Args = CompressNewArgs; fn py_new( cls: PyTypeRef, Self::Args { data, selectors }: Self::Args, vm: &VirtualMachine, ) -> PyResult { PyItertoolsCompress { data, selectors } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsCompress { #[pymethod(magic)] fn reduce(zelf: PyRef<Self>) -> (PyTypeRef, (PyIter, PyIter)) { ( zelf.class().to_owned(), (zelf.data.clone(), zelf.selectors.clone()), ) } } impl SelfIter for PyItertoolsCompress {} impl IterNext for PyItertoolsCompress { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { loop { let sel_obj = match zelf.selectors.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)), }; let verdict = sel_obj.clone().try_to_bool(vm)?; let data_obj = zelf.data.next(vm)?; if verdict { return Ok(data_obj); } } } } #[pyattr] #[pyclass(name = "count")] #[derive(Debug, PyPayload)] struct PyItertoolsCount { cur: PyRwLock<PyObjectRef>, step: PyObjectRef, } #[derive(FromArgs)] struct CountNewArgs { #[pyarg(positional, optional)] start: OptionalArg<PyObjectRef>, #[pyarg(positional, optional)] step: OptionalArg<PyObjectRef>, } impl Constructor for PyItertoolsCount { type Args = CountNewArgs; fn py_new( cls: PyTypeRef, Self::Args { start, step }: Self::Args, vm: &VirtualMachine, ) -> PyResult { let start = start.into_option().unwrap_or_else(|| vm.new_pyobj(0)); let step = step.into_option().unwrap_or_else(|| vm.new_pyobj(1)); if !PyNumber::check(&start) || !PyNumber::check(&step) { return Err(vm.new_type_error("a number is required".to_owned())); } Self { cur: PyRwLock::new(start), step, } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor, Representable))] impl PyItertoolsCount { // TODO: Implement this // if (lz->cnt == PY_SSIZE_T_MAX) // return Py_BuildValue("0(00)", Py_TYPE(lz), lz->long_cnt, lz->long_step); #[pymethod(magic)] fn reduce(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef,)) { (zelf.class().to_owned(), (zelf.cur.read().clone(),)) } } impl SelfIter for PyItertoolsCount {} impl IterNext for PyItertoolsCount { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let mut cur = zelf.cur.write(); let step = zelf.step.clone(); let result = cur.clone(); *cur = vm._iadd(&cur, step.as_object())?; Ok(PyIterReturn::Return(result.to_pyobject(vm))) } } impl Representable for PyItertoolsCount { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { let cur = format!("{}", zelf.cur.read().clone().repr(vm)?); let step = &zelf.step; if vm.bool_eq(step, vm.ctx.new_int(1).as_object())? { return Ok(format!("count({cur})")); } Ok(format!("count({}, {})", cur, step.repr(vm)?)) } } #[pyattr] #[pyclass(name = "cycle")] #[derive(Debug, PyPayload)] struct PyItertoolsCycle { iter: PyIter, saved: PyRwLock<Vec<PyObjectRef>>, index: AtomicCell<usize>, } impl Constructor for PyItertoolsCycle { type Args = PyIter; fn py_new(cls: PyTypeRef, iter: Self::Args, vm: &VirtualMachine) -> PyResult { Self { iter, saved: PyRwLock::new(Vec::new()), index: AtomicCell::new(0), } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsCycle {} impl SelfIter for PyItertoolsCycle {} impl IterNext for PyItertoolsCycle { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let item = if let PyIterReturn::Return(item) = zelf.iter.next(vm)? { zelf.saved.write().push(item.clone()); item } else { let saved = zelf.saved.read(); if saved.len() == 0 { return Ok(PyIterReturn::StopIteration(None)); } let last_index = zelf.index.fetch_add(1); if last_index >= saved.len() - 1 { zelf.index.store(0); } saved[last_index].clone() }; Ok(PyIterReturn::Return(item)) } } #[pyattr] #[pyclass(name = "repeat")] #[derive(Debug, PyPayload)] struct PyItertoolsRepeat { object: PyObjectRef, times: Option<PyRwLock<usize>>, } #[derive(FromArgs)] struct PyRepeatNewArgs { object: PyObjectRef, #[pyarg(any, optional)] times: OptionalArg<PyIntRef>, } impl Constructor for PyItertoolsRepeat { type Args = PyRepeatNewArgs; fn py_new( cls: PyTypeRef, Self::Args { object, times }: Self::Args, vm: &VirtualMachine, ) -> PyResult { let times = match times.into_option() { Some(int) => { let val: isize = int.try_to_primitive(vm)?; // times always >= 0. Some(PyRwLock::new(val.to_usize().unwrap_or(0))) } None => None, }; PyItertoolsRepeat { object, times } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor, Representable), flags(BASETYPE))] impl PyItertoolsRepeat { #[pymethod(magic)] fn length_hint(&self, vm: &VirtualMachine) -> PyResult<usize> { // Return TypeError, length_hint picks this up and returns the default. let times = self .times .as_ref() .ok_or_else(|| vm.new_type_error("length of unsized object.".to_owned()))?; Ok(*times.read()) } #[pymethod(magic)] fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let cls = zelf.class().to_owned(); Ok(match zelf.times { Some(ref times) => vm.new_tuple((cls, (zelf.object.clone(), *times.read()))), None => vm.new_tuple((cls, (zelf.object.clone(),))), }) } } impl SelfIter for PyItertoolsRepeat {} impl IterNext for PyItertoolsRepeat { fn next(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> { if let Some(ref times) = zelf.times { let mut times = times.write(); if *times == 0 { return Ok(PyIterReturn::StopIteration(None)); } *times -= 1; } Ok(PyIterReturn::Return(zelf.object.clone())) } } impl Representable for PyItertoolsRepeat { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { let mut fmt = format!("{}", &zelf.object.repr(vm)?); if let Some(ref times) = zelf.times { fmt.push_str(", "); fmt.push_str(&times.read().to_string()); } Ok(format!("repeat({fmt})")) } } #[pyattr] #[pyclass(name = "starmap")] #[derive(Debug, PyPayload)] struct PyItertoolsStarmap { function: PyObjectRef, iterable: PyIter, } #[derive(FromArgs)] struct StarmapNewArgs { #[pyarg(positional)] function: PyObjectRef, #[pyarg(positional)] iterable: PyIter, } impl Constructor for PyItertoolsStarmap { type Args = StarmapNewArgs; fn py_new( cls: PyTypeRef, Self::Args { function, iterable }: Self::Args, vm: &VirtualMachine, ) -> PyResult { PyItertoolsStarmap { function, iterable } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsStarmap { #[pymethod(magic)] fn reduce(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef, PyIter)) { ( zelf.class().to_owned(), (zelf.function.clone(), zelf.iterable.clone()), ) } } impl SelfIter for PyItertoolsStarmap {} impl IterNext for PyItertoolsStarmap { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let obj = zelf.iterable.next(vm)?; let function = &zelf.function; match obj { PyIterReturn::Return(obj) => { let args: Vec<_> = obj.try_to_value(vm)?; PyIterReturn::from_pyresult(function.call(args, vm), vm) } PyIterReturn::StopIteration(v) => Ok(PyIterReturn::StopIteration(v)), } } } #[pyattr] #[pyclass(name = "takewhile")] #[derive(Debug, PyPayload)] struct PyItertoolsTakewhile { predicate: PyObjectRef, iterable: PyIter, stop_flag: AtomicCell<bool>, } #[derive(FromArgs)] struct TakewhileNewArgs { #[pyarg(positional)] predicate: PyObjectRef, #[pyarg(positional)] iterable: PyIter, } impl Constructor for PyItertoolsTakewhile { type Args = TakewhileNewArgs; fn py_new( cls: PyTypeRef, Self::Args { predicate, iterable, }: Self::Args, vm: &VirtualMachine, ) -> PyResult { PyItertoolsTakewhile { predicate, iterable, stop_flag: AtomicCell::new(false), } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsTakewhile { #[pymethod(magic)] fn reduce(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef, PyIter), u32) { ( zelf.class().to_owned(), (zelf.predicate.clone(), zelf.iterable.clone()), zelf.stop_flag.load() as _, ) } #[pymethod(magic)] fn setstate(zelf: PyRef<Self>, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if let Ok(obj) = ArgIntoBool::try_from_object(vm, state) { zelf.stop_flag.store(*obj); } Ok(()) } } impl SelfIter for PyItertoolsTakewhile {} impl IterNext for PyItertoolsTakewhile { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { if zelf.stop_flag.load() { return Ok(PyIterReturn::StopIteration(None)); } // might be StopIteration or anything else, which is propagated upwards let obj = match zelf.iterable.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)), }; let predicate = &zelf.predicate; let verdict = predicate.call((obj.clone(),), vm)?; let verdict = verdict.try_to_bool(vm)?; if verdict { Ok(PyIterReturn::Return(obj)) } else { zelf.stop_flag.store(true); Ok(PyIterReturn::StopIteration(None)) } } } #[pyattr] #[pyclass(name = "dropwhile")] #[derive(Debug, PyPayload)] struct PyItertoolsDropwhile { predicate: ArgCallable, iterable: PyIter, start_flag: AtomicCell<bool>, } #[derive(FromArgs)] struct DropwhileNewArgs { #[pyarg(positional)] predicate: ArgCallable, #[pyarg(positional)] iterable: PyIter, } impl Constructor for PyItertoolsDropwhile { type Args = DropwhileNewArgs; fn py_new( cls: PyTypeRef, Self::Args { predicate, iterable, }: Self::Args, vm: &VirtualMachine, ) -> PyResult { PyItertoolsDropwhile { predicate, iterable, start_flag: AtomicCell::new(false), } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsDropwhile { #[pymethod(magic)] fn reduce(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef, PyIter), u32) { ( zelf.class().to_owned(), (zelf.predicate.clone().into(), zelf.iterable.clone()), (zelf.start_flag.load() as _), ) } #[pymethod(magic)] fn setstate(zelf: PyRef<Self>, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if let Ok(obj) = ArgIntoBool::try_from_object(vm, state) { zelf.start_flag.store(*obj); } Ok(()) } } impl SelfIter for PyItertoolsDropwhile {} impl IterNext for PyItertoolsDropwhile { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let predicate = &zelf.predicate; let iterable = &zelf.iterable; if !zelf.start_flag.load() { loop { let obj = match iterable.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => { return Ok(PyIterReturn::StopIteration(v)) } }; let pred = predicate.clone(); let pred_value = pred.invoke((obj.clone(),), vm)?; if !pred_value.try_to_bool(vm)? { zelf.start_flag.store(true); return Ok(PyIterReturn::Return(obj)); } } } iterable.next(vm) } } struct GroupByState { current_value: Option<PyObjectRef>, current_key: Option<PyObjectRef>, next_group: bool, grouper: Option<PyWeakRef<PyItertoolsGrouper>>, } impl fmt::Debug for GroupByState { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("GroupByState") .field("current_value", &self.current_value) .field("current_key", &self.current_key) .field("next_group", &self.next_group) .finish() } } impl GroupByState { fn is_current(&self, grouper: &Py<PyItertoolsGrouper>) -> bool { self.grouper .as_ref() .and_then(|g| g.upgrade()) .map_or(false, |ref current_grouper| grouper.is(current_grouper)) } } #[pyattr] #[pyclass(name = "groupby")] #[derive(PyPayload)] struct PyItertoolsGroupBy { iterable: PyIter, key_func: Option<PyObjectRef>, state: PyMutex<GroupByState>, } impl fmt::Debug for PyItertoolsGroupBy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PyItertoolsGroupBy") .field("iterable", &self.iterable) .field("key_func", &self.key_func) .field("state", &self.state.lock()) .finish() } } #[derive(FromArgs)] struct GroupByArgs { iterable: PyIter, #[pyarg(any, optional)] key: OptionalOption<PyObjectRef>, } impl Constructor for PyItertoolsGroupBy { type Args = GroupByArgs; fn py_new( cls: PyTypeRef, Self::Args { iterable, key }: Self::Args, vm: &VirtualMachine, ) -> PyResult { PyItertoolsGroupBy { iterable, key_func: key.flatten(), state: PyMutex::new(GroupByState { current_key: None, current_value: None, next_group: false, grouper: None, }), } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor))] impl PyItertoolsGroupBy { pub(super) fn advance( &self, vm: &VirtualMachine, ) -> PyResult<PyIterReturn<(PyObjectRef, PyObjectRef)>> { let new_value = match self.iterable.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)), }; let new_key = if let Some(ref kf) = self.key_func { kf.call((new_value.clone(),), vm)? } else { new_value.clone() }; Ok(PyIterReturn::Return((new_value, new_key))) } } impl SelfIter for PyItertoolsGroupBy {} impl IterNext for PyItertoolsGroupBy { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let mut state = zelf.state.lock(); state.grouper = None; if !state.next_group { // FIXME: unnecessary clone. current_key always exist until assigning new let current_key = state.current_key.clone(); drop(state); let (value, key) = if let Some(old_key) = current_key { loop { let (value, new_key) = match zelf.advance(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => { return Ok(PyIterReturn::StopIteration(v)) } }; if !vm.bool_eq(&new_key, &old_key)? { break (value, new_key); } } } else { match zelf.advance(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => { return Ok(PyIterReturn::StopIteration(v)) } } }; state = zelf.state.lock(); state.current_value = Some(value); state.current_key = Some(key); } state.next_group = false; let grouper = PyItertoolsGrouper { groupby: zelf.to_owned(), } .into_ref(&vm.ctx); state.grouper = Some(grouper.downgrade(None, vm).unwrap()); Ok(PyIterReturn::Return( (state.current_key.as_ref().unwrap().clone(), grouper).to_pyobject(vm), )) } } #[pyattr] #[pyclass(name = "_grouper")] #[derive(Debug, PyPayload)] struct PyItertoolsGrouper { groupby: PyRef<PyItertoolsGroupBy>, } #[pyclass(with(IterNext, Iterable))] impl PyItertoolsGrouper {} impl SelfIter for PyItertoolsGrouper {} impl IterNext for PyItertoolsGrouper { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let old_key = { let mut state = zelf.groupby.state.lock(); if !state.is_current(zelf) { return Ok(PyIterReturn::StopIteration(None)); } // check to see if the value has already been retrieved from the iterator if let Some(val) = state.current_value.take() { return Ok(PyIterReturn::Return(val)); } state.current_key.as_ref().unwrap().clone() }; let (value, key) = match zelf.groupby.advance(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)), }; if vm.bool_eq(&key, &old_key)? { Ok(PyIterReturn::Return(value)) } else { let mut state = zelf.groupby.state.lock(); state.current_value = Some(value); state.current_key = Some(key); state.next_group = true; state.grouper = None; Ok(PyIterReturn::StopIteration(None)) } } } #[pyattr] #[pyclass(name = "islice")] #[derive(Debug, PyPayload)] struct PyItertoolsIslice { iterable: PyIter, cur: AtomicCell<usize>, next: AtomicCell<usize>, stop: Option<usize>, step: usize, } // Restrict obj to ints with value 0 <= val <= sys.maxsize // On failure (out of range, non-int object) a ValueError is raised. fn pyobject_to_opt_usize( obj: PyObjectRef, name: &'static str, vm: &VirtualMachine, ) -> PyResult<usize> { let is_int = obj.fast_isinstance(vm.ctx.types.int_type); if is_int { let value = int::get_value(&obj).to_usize(); if let Some(value) = value { // Only succeeds for values for which 0 <= value <= sys.maxsize if value <= sys::MAXSIZE as usize { return Ok(value); } } } // We don't have an int or value was < 0 or > sys.maxsize Err(vm.new_value_error(format!( "{name} argument for islice() must be None or an integer: 0 <= x <= sys.maxsize." ))) } #[pyclass(with(IterNext, Iterable), flags(BASETYPE))] impl PyItertoolsIslice { #[pyslot] fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let (iter, start, stop, step) = match args.args.len() { 0 | 1 => { return Err(vm.new_type_error(format!( "islice expected at least 2 arguments, got {}", args.args.len() ))); } 2 => { let (iter, stop): (PyObjectRef, PyObjectRef) = args.bind(vm)?; (iter, 0usize, stop, 1usize) } _ => { let (iter, start, stop, step) = if args.args.len() == 3 { let (iter, start, stop): (PyObjectRef, PyObjectRef, PyObjectRef) = args.bind(vm)?; (iter, start, stop, 1usize) } else { let (iter, start, stop, step): ( PyObjectRef, PyObjectRef, PyObjectRef, PyObjectRef, ) = args.bind(vm)?; let step = if !vm.is_none(&step) { pyobject_to_opt_usize(step, "Step", vm)? } else { 1usize }; (iter, start, stop, step) }; let start = if !vm.is_none(&start) { pyobject_to_opt_usize(start, "Start", vm)? } else { 0usize }; (iter, start, stop, step) } }; let stop = if !vm.is_none(&stop) { Some(pyobject_to_opt_usize(stop, "Stop", vm)?) } else { None }; let iter = iter.get_iter(vm)?; PyItertoolsIslice { iterable: iter, cur: AtomicCell::new(0), next: AtomicCell::new(start), stop, step, } .into_ref_with_type(vm, cls) .map(Into::into) } #[pymethod(magic)] fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let cls = zelf.class().to_owned(); let itr = zelf.iterable.clone(); let cur = zelf.cur.take(); let next = zelf.next.take(); let step = zelf.step; match zelf.stop { Some(stop) => Ok(vm.new_tuple((cls, (itr, next, stop, step), (cur,)))), _ => Ok(vm.new_tuple((cls, (itr, next, vm.new_pyobj(()), step), (cur,)))), } } #[pymethod(magic)] fn setstate(zelf: PyRef<Self>, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> { let args = state.as_slice(); if args.len() != 1 { let msg = format!("function takes exactly 1 argument ({} given)", args.len()); return Err(vm.new_type_error(msg)); } let cur = &args[0]; if let Ok(cur) = cur.try_to_value(vm) { zelf.cur.store(cur); } else { return Err(vm.new_type_error(String::from("Argument must be usize."))); } Ok(()) } } impl SelfIter for PyItertoolsIslice {} impl IterNext for PyItertoolsIslice { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { while zelf.cur.load() < zelf.next.load() { zelf.iterable.next(vm)?; zelf.cur.fetch_add(1); } if let Some(stop) = zelf.stop { if zelf.cur.load() >= stop { return Ok(PyIterReturn::StopIteration(None)); } } let obj = match zelf.iterable.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)), }; zelf.cur.fetch_add(1); // TODO is this overflow check required? attempts to copy CPython. let (next, ovf) = zelf.next.load().overflowing_add(zelf.step); zelf.next.store(if ovf { zelf.stop.unwrap() } else { next }); Ok(PyIterReturn::Return(obj)) } } #[pyattr] #[pyclass(name = "filterfalse")] #[derive(Debug, PyPayload)] struct PyItertoolsFilterFalse { predicate: PyObjectRef, iterable: PyIter, } #[derive(FromArgs)] struct FilterFalseNewArgs { #[pyarg(positional)] predicate: PyObjectRef, #[pyarg(positional)] iterable: PyIter, } impl Constructor for PyItertoolsFilterFalse { type Args = FilterFalseNewArgs; fn py_new( cls: PyTypeRef, Self::Args { predicate, iterable, }: Self::Args, vm: &VirtualMachine, ) -> PyResult { PyItertoolsFilterFalse { predicate, iterable, } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsFilterFalse { #[pymethod(magic)] fn reduce(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef, PyIter)) { ( zelf.class().to_owned(), (zelf.predicate.clone(), zelf.iterable.clone()), ) } } impl SelfIter for PyItertoolsFilterFalse {} impl IterNext for PyItertoolsFilterFalse { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let predicate = &zelf.predicate; let iterable = &zelf.iterable; loop { let obj = match iterable.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)), }; let pred_value = if vm.is_none(predicate) { obj.clone() } else { predicate.call((obj.clone(),), vm)? }; if !pred_value.try_to_bool(vm)? { return Ok(PyIterReturn::Return(obj)); } } } } #[pyattr] #[pyclass(name = "accumulate")] #[derive(Debug, PyPayload)] struct PyItertoolsAccumulate { iterable: PyIter, binop: Option<PyObjectRef>, initial: Option<PyObjectRef>, acc_value: PyRwLock<Option<PyObjectRef>>, } #[derive(FromArgs)] struct AccumulateArgs { iterable: PyIter, #[pyarg(any, optional)] func: OptionalOption<PyObjectRef>, #[pyarg(named, optional)] initial: OptionalOption<PyObjectRef>, } impl Constructor for PyItertoolsAccumulate { type Args = AccumulateArgs; fn py_new(cls: PyTypeRef, args: AccumulateArgs, vm: &VirtualMachine) -> PyResult { PyItertoolsAccumulate { iterable: args.iterable, binop: args.func.flatten(), initial: args.initial.flatten(), acc_value: PyRwLock::new(None), } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor))] impl PyItertoolsAccumulate { #[pymethod(magic)] fn setstate(zelf: PyRef<Self>, state: PyObjectRef, _vm: &VirtualMachine) -> PyResult<()> { *zelf.acc_value.write() = Some(state); Ok(()) } #[pymethod(magic)] fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyTupleRef { let class = zelf.class().to_owned(); let binop = zelf.binop.clone(); let it = zelf.iterable.clone(); let acc_value = zelf.acc_value.read().clone(); if let Some(initial) = &zelf.initial { let chain_args = PyList::from(vec![initial.clone(), it.to_pyobject(vm)]); let chain = PyItertoolsChain { source: PyRwLock::new(Some(chain_args.to_pyobject(vm).get_iter(vm).unwrap())), active: PyRwLock::new(None), }; let tup = vm.new_tuple((chain, binop)); return vm.new_tuple((class, tup, acc_value)); } match acc_value { Some(obj) if obj.is(&vm.ctx.none) => { let chain_args = PyList::from(vec![]); let chain = PyItertoolsChain { source: PyRwLock::new(Some( chain_args.to_pyobject(vm).get_iter(vm).unwrap(), )), active: PyRwLock::new(None), } .into_pyobject(vm); let acc = Self { iterable: PyIter::new(chain), binop, initial: None, acc_value: PyRwLock::new(None), }; let tup = vm.new_tuple((acc, 1, None::<PyObjectRef>)); let islice_cls = PyItertoolsIslice::class(&vm.ctx).to_owned(); return vm.new_tuple((islice_cls, tup)); } _ => {} } let tup = vm.new_tuple((it, binop)); vm.new_tuple((class, tup, acc_value)) } } impl SelfIter for PyItertoolsAccumulate {} impl IterNext for PyItertoolsAccumulate { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let iterable = &zelf.iterable; let acc_value = zelf.acc_value.read().clone(); let next_acc_value = match acc_value { None => match &zelf.initial { None => match iterable.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => { return Ok(PyIterReturn::StopIteration(v)) } }, Some(obj) => obj.clone(), }, Some(value) => { let obj = match iterable.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => { return Ok(PyIterReturn::StopIteration(v)) } }; match &zelf.binop { None => vm._add(&value, &obj)?, Some(op) => op.call((value, obj), vm)?, } } }; *zelf.acc_value.write() = Some(next_acc_value.clone()); Ok(PyIterReturn::Return(next_acc_value)) } } #[derive(Debug)] struct PyItertoolsTeeData { iterable: PyIter, values: PyRwLock<Vec<PyObjectRef>>, } impl PyItertoolsTeeData { fn new(iterable: PyIter, _vm: &VirtualMachine) -> PyResult<PyRc<PyItertoolsTeeData>> { Ok(PyRc::new(PyItertoolsTeeData { iterable, values: PyRwLock::new(vec![]), })) } fn get_item(&self, vm: &VirtualMachine, index: usize) -> PyResult<PyIterReturn> { if self.values.read().len() == index { let result = match self.iterable.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)), }; self.values.write().push(result); } Ok(PyIterReturn::Return(self.values.read()[index].clone())) } } #[pyattr] #[pyclass(name = "tee")] #[derive(Debug, PyPayload)] struct PyItertoolsTee { tee_data: PyRc<PyItertoolsTeeData>, index: AtomicCell<usize>, } #[derive(FromArgs)] struct TeeNewArgs { #[pyarg(positional)] iterable: PyIter, #[pyarg(positional, optional)] n: OptionalArg<usize>, } impl Constructor for PyItertoolsTee { type Args = TeeNewArgs; // TODO: make tee() a function, rename this class to itertools._tee and make // teedata a python class fn py_new( _cls: PyTypeRef, Self::Args { iterable, n }: Self::Args, vm: &VirtualMachine, ) -> PyResult { let n = n.unwrap_or(2); let copyable = if iterable.class().has_attr(identifier!(vm, __copy__)) { vm.call_special_method(iterable.as_object(), identifier!(vm, __copy__), ())? } else { PyItertoolsTee::from_iter(iterable, vm)? }; let mut tee_vec: Vec<PyObjectRef> = Vec::with_capacity(n); for _ in 0..n { tee_vec.push(vm.call_special_method(&copyable, identifier!(vm, __copy__), ())?); } Ok(PyTuple::new_ref(tee_vec, &vm.ctx).into()) } } #[pyclass(with(IterNext, Iterable, Constructor))] impl PyItertoolsTee { fn from_iter(iterator: PyIter, vm: &VirtualMachine) -> PyResult { let class = PyItertoolsTee::class(&vm.ctx); if iterator.class().is(PyItertoolsTee::class(&vm.ctx)) { return vm.call_special_method(&iterator, identifier!(vm, __copy__), ()); } Ok(PyItertoolsTee { tee_data: PyItertoolsTeeData::new(iterator, vm)?, index: AtomicCell::new(0), } .into_ref_with_type(vm, class.to_owned())? .into()) } #[pymethod(magic)] fn copy(&self) -> Self { Self { tee_data: PyRc::clone(&self.tee_data), index: AtomicCell::new(self.index.load()), } } } impl SelfIter for PyItertoolsTee {} impl IterNext for PyItertoolsTee { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let value = match zelf.tee_data.get_item(vm, zelf.index.load())? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)), }; zelf.index.fetch_add(1); Ok(PyIterReturn::Return(value)) } } #[pyattr] #[pyclass(name = "product")] #[derive(Debug, PyPayload)] struct PyItertoolsProduct { pools: Vec<Vec<PyObjectRef>>, idxs: PyRwLock<Vec<usize>>, cur: AtomicCell<usize>, stop: AtomicCell<bool>, } #[derive(FromArgs)] struct ProductArgs { #[pyarg(named, optional)] repeat: OptionalArg<usize>, } impl Constructor for PyItertoolsProduct { type Args = (PosArgs<PyObjectRef>, ProductArgs); fn py_new(cls: PyTypeRef, (iterables, args): Self::Args, vm: &VirtualMachine) -> PyResult { let repeat = args.repeat.unwrap_or(1); let mut pools = Vec::new(); for arg in iterables.iter() { pools.push(arg.try_to_value(vm)?); } let pools = std::iter::repeat(pools) .take(repeat) .flatten() .collect::<Vec<Vec<PyObjectRef>>>(); let l = pools.len(); PyItertoolsProduct { pools, idxs: PyRwLock::new(vec![0; l]), cur: AtomicCell::new(l.wrapping_sub(1)), stop: AtomicCell::new(false), } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor))] impl PyItertoolsProduct { fn update_idxs(&self, mut idxs: PyRwLockWriteGuard<'_, Vec<usize>>) { if idxs.len() == 0 { self.stop.store(true); return; } let cur = self.cur.load(); let lst_idx = &self.pools[cur].len() - 1; if idxs[cur] == lst_idx { if cur == 0 { self.stop.store(true); return; } idxs[cur] = 0; self.cur.fetch_sub(1); self.update_idxs(idxs); } else { idxs[cur] += 1; self.cur.store(idxs.len() - 1); } } } impl SelfIter for PyItertoolsProduct {} impl IterNext for PyItertoolsProduct { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { // stop signal if zelf.stop.load() { return Ok(PyIterReturn::StopIteration(None)); } let pools = &zelf.pools; for p in pools { if p.is_empty() { return Ok(PyIterReturn::StopIteration(None)); } } let idxs = zelf.idxs.write(); let res = vm.ctx.new_tuple( pools .iter() .zip(idxs.iter()) .map(|(pool, idx)| pool[*idx].clone()) .collect(), ); zelf.update_idxs(idxs); Ok(PyIterReturn::Return(res.into())) } } #[pyattr] #[pyclass(name = "combinations")] #[derive(Debug, PyPayload)] struct PyItertoolsCombinations { pool: Vec<PyObjectRef>, indices: PyRwLock<Vec<usize>>, result: PyRwLock<Option<Vec<PyObjectRef>>>, r: AtomicCell<usize>, exhausted: AtomicCell<bool>, } #[derive(FromArgs)] struct CombinationsNewArgs { #[pyarg(any)] iterable: PyObjectRef, #[pyarg(any)] r: PyIntRef, } impl Constructor for PyItertoolsCombinations { type Args = CombinationsNewArgs; fn py_new( cls: PyTypeRef, Self::Args { iterable, r }: Self::Args, vm: &VirtualMachine, ) -> PyResult { let pool: Vec<_> = iterable.try_to_value(vm)?; let r = r.as_bigint(); if r.is_negative() { return Err(vm.new_value_error("r must be non-negative".to_owned())); } let r = r.to_usize().unwrap(); let n = pool.len(); Self { pool, indices: PyRwLock::new((0..r).collect()), result: PyRwLock::new(None), r: AtomicCell::new(r), exhausted: AtomicCell::new(r > n), } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor))] impl PyItertoolsCombinations { #[pymethod(magic)] fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyTupleRef { let r = zelf.r.load(); let class = zelf.class().to_owned(); if zelf.exhausted.load() { return vm.new_tuple(( class, vm.new_tuple((vm.ctx.empty_tuple.clone(), vm.ctx.new_int(r))), )); } let tup = vm.new_tuple((zelf.pool.clone().into_pytuple(vm), vm.ctx.new_int(r))); if zelf.result.read().is_none() { vm.new_tuple((class, tup)) } else { let mut indices: Vec<PyObjectRef> = Vec::new(); for item in &zelf.indices.read()[..r] { indices.push(vm.new_pyobj(*item)); } vm.new_tuple((class, tup, indices.into_pytuple(vm))) } } } impl SelfIter for PyItertoolsCombinations {} impl IterNext for PyItertoolsCombinations { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { // stop signal if zelf.exhausted.load() { return Ok(PyIterReturn::StopIteration(None)); } let n = zelf.pool.len(); let r = zelf.r.load(); if r == 0 { zelf.exhausted.store(true); return Ok(PyIterReturn::Return(vm.new_tuple(()).into())); } let mut result_lock = zelf.result.write(); let result = if let Some(ref mut result) = *result_lock { let mut indices = zelf.indices.write(); // Scan indices right-to-left until finding one that is not at its maximum (i + n - r). let mut idx = r as isize - 1; while idx >= 0 && indices[idx as usize] == idx as usize + n - r { idx -= 1; } // If no suitable index is found, then the indices are all at // their maximum value and we're done. if idx < 0 { zelf.exhausted.store(true); return Ok(PyIterReturn::StopIteration(None)); } else { // Increment the current index which we know is not at its // maximum. Then move back to the right setting each index // to its lowest possible value (one higher than the index // to its left -- this maintains the sort order invariant). indices[idx as usize] += 1; for j in idx as usize + 1..r { indices[j] = indices[j - 1] + 1; } // Update the result tuple for the new indices // starting with i, the leftmost index that changed for i in idx as usize..r { let index = indices[i]; let elem = &zelf.pool[index]; result[i] = elem.to_owned(); } result.to_vec() } } else { let res = zelf.pool[0..r].to_vec(); *result_lock = Some(res.clone()); res }; Ok(PyIterReturn::Return(vm.ctx.new_tuple(result).into())) } } #[pyattr] #[pyclass(name = "combinations_with_replacement")] #[derive(Debug, PyPayload)] struct PyItertoolsCombinationsWithReplacement { pool: Vec<PyObjectRef>, indices: PyRwLock<Vec<usize>>, r: AtomicCell<usize>, exhausted: AtomicCell<bool>, } impl Constructor for PyItertoolsCombinationsWithReplacement { type Args = CombinationsNewArgs; fn py_new( cls: PyTypeRef, Self::Args { iterable, r }: Self::Args, vm: &VirtualMachine, ) -> PyResult { let pool: Vec<_> = iterable.try_to_value(vm)?; let r = r.as_bigint(); if r.is_negative() { return Err(vm.new_value_error("r must be non-negative".to_owned())); } let r = r.to_usize().unwrap(); let n = pool.len(); PyItertoolsCombinationsWithReplacement { pool, indices: PyRwLock::new(vec![0; r]), r: AtomicCell::new(r), exhausted: AtomicCell::new(n == 0 && r > 0), } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor))] impl PyItertoolsCombinationsWithReplacement {} impl SelfIter for PyItertoolsCombinationsWithReplacement {} impl IterNext for PyItertoolsCombinationsWithReplacement { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { // stop signal if zelf.exhausted.load() { return Ok(PyIterReturn::StopIteration(None)); } let n = zelf.pool.len(); let r = zelf.r.load(); if r == 0 { zelf.exhausted.store(true); return Ok(PyIterReturn::Return(vm.new_tuple(()).into())); } let mut indices = zelf.indices.write(); let res = vm .ctx .new_tuple(indices.iter().map(|&i| zelf.pool[i].clone()).collect()); // Scan indices right-to-left until finding one that is not at its maximum (i + n - r). let mut idx = r as isize - 1; while idx >= 0 && indices[idx as usize] == n - 1 { idx -= 1; } // If no suitable index is found, then the indices are all at // their maximum value and we're done. if idx < 0 { zelf.exhausted.store(true); } else { let index = indices[idx as usize] + 1; // Increment the current index which we know is not at its // maximum. Then set all to the right to the same value. for j in idx as usize..r { indices[j] = index; } } Ok(PyIterReturn::Return(res.into())) } } #[pyattr] #[pyclass(name = "permutations")] #[derive(Debug, PyPayload)] struct PyItertoolsPermutations { pool: Vec<PyObjectRef>, // Collected input iterable indices: PyRwLock<Vec<usize>>, // One index per element in pool cycles: PyRwLock<Vec<usize>>, // One rollover counter per element in the result result: PyRwLock<Option<Vec<usize>>>, // Indexes of the most recently returned result r: AtomicCell<usize>, // Size of result tuple exhausted: AtomicCell<bool>, // Set when the iterator is exhausted } #[derive(FromArgs)] struct PermutationsNewArgs { #[pyarg(positional)] iterable: PyObjectRef, #[pyarg(positional, optional)] r: OptionalOption<PyObjectRef>, } impl Constructor for PyItertoolsPermutations { type Args = PermutationsNewArgs; fn py_new( cls: PyTypeRef, Self::Args { iterable, r }: Self::Args, vm: &VirtualMachine, ) -> PyResult { let pool: Vec<_> = iterable.try_to_value(vm)?; let n = pool.len(); // If r is not provided, r == n. If provided, r must be a positive integer, or None. // If None, it behaves the same as if it was not provided. let r = match r.flatten() { Some(r) => { let val = r .payload::<PyInt>() .ok_or_else(|| vm.new_type_error("Expected int as r".to_owned()))? .as_bigint(); if val.is_negative() { return Err(vm.new_value_error("r must be non-negative".to_owned())); } val.to_usize().unwrap() } None => n, }; Self { pool, indices: PyRwLock::new((0..n).collect()), cycles: PyRwLock::new((0..r.min(n)).map(|i| n - i).collect()), result: PyRwLock::new(None), r: AtomicCell::new(r), exhausted: AtomicCell::new(r > n), } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor))] impl PyItertoolsPermutations { #[pymethod(magic)] fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRef<PyTuple> { vm.new_tuple(( zelf.class().to_owned(), vm.new_tuple((zelf.pool.clone(), vm.ctx.new_int(zelf.r.load()))), )) } } impl SelfIter for PyItertoolsPermutations {} impl IterNext for PyItertoolsPermutations { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { // stop signal if zelf.exhausted.load() { return Ok(PyIterReturn::StopIteration(None)); } let n = zelf.pool.len(); let r = zelf.r.load(); if n == 0 { zelf.exhausted.store(true); return Ok(PyIterReturn::Return(vm.new_tuple(()).into())); } let mut result = zelf.result.write(); if let Some(ref mut result) = *result { let mut indices = zelf.indices.write(); let mut cycles = zelf.cycles.write(); let mut sentinel = false; // Decrement rightmost cycle, moving leftward upon zero rollover for i in (0..r).rev() { cycles[i] -= 1; if cycles[i] == 0 { // rotation: indices[i:] = indices[i+1:] + indices[i:i+1] let index = indices[i]; for j in i..n - 1 { indices[j] = indices[j + 1]; } indices[n - 1] = index; cycles[i] = n - i; } else { let j = cycles[i]; indices.swap(i, n - j); for k in i..r { // start with i, the leftmost element that changed // yield tuple(pool[k] for k in indices[:r]) result[k] = indices[k]; } sentinel = true; break; } } if !sentinel { zelf.exhausted.store(true); return Ok(PyIterReturn::StopIteration(None)); } } else { // On the first pass, initialize result tuple using the indices *result = Some((0..r).collect()); } Ok(PyIterReturn::Return( vm.ctx .new_tuple( result .as_ref() .unwrap() .iter() .map(|&i| zelf.pool[i].clone()) .collect(), ) .into(), )) } } #[derive(FromArgs)] struct ZipLongestArgs { #[pyarg(named, optional)] fillvalue: OptionalArg<PyObjectRef>, } impl Constructor for PyItertoolsZipLongest { type Args = (PosArgs<PyIter>, ZipLongestArgs); fn py_new(cls: PyTypeRef, (iterators, args): Self::Args, vm: &VirtualMachine) -> PyResult { let fillvalue = args.fillvalue.unwrap_or_none(vm); let iterators = iterators.into_vec(); PyItertoolsZipLongest { iterators, fillvalue: PyRwLock::new(fillvalue), } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyattr] #[pyclass(name = "zip_longest")] #[derive(Debug, PyPayload)] struct PyItertoolsZipLongest { iterators: Vec<PyIter>, fillvalue: PyRwLock<PyObjectRef>, } #[pyclass(with(IterNext, Iterable, Constructor))] impl PyItertoolsZipLongest { #[pymethod(magic)] fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let args: Vec<PyObjectRef> = zelf .iterators .iter() .map(|i| i.clone().to_pyobject(vm)) .collect(); Ok(vm.new_tuple(( zelf.class().to_owned(), vm.new_tuple(args), zelf.fillvalue.read().to_owned(), ))) } #[pymethod(magic)] fn setstate(zelf: PyRef<Self>, state: PyObjectRef, _vm: &VirtualMachine) -> PyResult<()> { *zelf.fillvalue.write() = state; Ok(()) } } impl SelfIter for PyItertoolsZipLongest {} impl IterNext for PyItertoolsZipLongest { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { if zelf.iterators.is_empty() { return Ok(PyIterReturn::StopIteration(None)); } let mut result: Vec<PyObjectRef> = Vec::new(); let mut numactive = zelf.iterators.len(); for idx in 0..zelf.iterators.len() { let next_obj = match zelf.iterators[idx].next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => { numactive -= 1; if numactive == 0 { return Ok(PyIterReturn::StopIteration(v)); } zelf.fillvalue.read().clone() } }; result.push(next_obj); } Ok(PyIterReturn::Return(vm.ctx.new_tuple(result).into())) } } #[pyattr] #[pyclass(name = "pairwise")] #[derive(Debug, PyPayload)] struct PyItertoolsPairwise { iterator: PyIter, old: PyRwLock<Option<PyObjectRef>>, } impl Constructor for PyItertoolsPairwise { type Args = PyIter; fn py_new(cls: PyTypeRef, iterator: Self::Args, vm: &VirtualMachine) -> PyResult { PyItertoolsPairwise { iterator, old: PyRwLock::new(None), } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor))] impl PyItertoolsPairwise {} impl SelfIter for PyItertoolsPairwise {} impl IterNext for PyItertoolsPairwise { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let old = match zelf.old.read().clone() { None => match zelf.iterator.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)), }, Some(obj) => obj, }; let new = match zelf.iterator.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)), }; *zelf.old.write() = Some(new.clone()); Ok(PyIterReturn::Return(vm.new_tuple((old, new)).into())) } } }
use crate::core::error::Error; use openexr_sys as sys; use std::cmp::{Eq, PartialEq}; use std::fmt::Debug; use std::mem::MaybeUninit; use std::os::raw::{c_int, c_uint}; type Result<T, E = Error> = std::result::Result<T, E>; /// Bit packing variants /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TimeCodePacking { /// packing for 60-field television /// Tv60, /// packing for 50-field television /// Tv50, /// packing for 24-frame film /// Film24, } impl TimeCodePacking { fn from_sys_packing(packing: sys::Imf_TimeCode_Packing) -> Self { match packing { sys::Imf_TimeCode_Packing_TV60_PACKING => TimeCodePacking::Tv60, sys::Imf_TimeCode_Packing_TV50_PACKING => TimeCodePacking::Tv50, sys::Imf_TimeCode_Packing_FILM24_PACKING => TimeCodePacking::Film24, _ => panic!("Packing is invalid"), } } fn to_sys_packing(&self) -> sys::Imf_TimeCode_Packing { match self { Self::Tv60 => sys::Imf_TimeCode_Packing_TV60_PACKING, Self::Tv50 => sys::Imf_TimeCode_Packing_TV50_PACKING, Self::Film24 => sys::Imf_TimeCode_Packing_FILM24_PACKING, } } } /// A TimeCode object stores time and control codes as described in SMPTE /// standard 12M-1999. A TimeCode object contains the following fields: /// /// Time Address: /// - hours: integer, range 0 - 23 /// - minutes: integer, range 0 - 59 /// - seconds: integer, range 0 - 59 /// - frame: integer, range 0 - 29 /// /// Flags: /// - drop frame flag: boolean /// - color frame flag: boolean /// - field/phase flag: boolean /// - bgf0: boolean /// - bgf1: boolean /// - bgf2: boolean /// /// Binary groups for user-defined data and control codes: /// - binary group 1: integer, range 0 - 15 /// - binary group 2: integer, range 0 - 15 /// - ... /// - binary group 8: integer, range 0 - 15 /// /// TimeCode contains methods to convert between the fields listed above and a /// more compact representation where the fields are packed into two unsigned /// 32-bit integers. In the packed integer representations, bit 0 is the least /// significant bit, and bit 31 is the most significant bit of the integer /// value. The time address and flags fields can be packed in three different /// ways: /// /// | bits | packing for 24-frame film | packing for 60-field television | packing for 50-field television | /// | ------- | ------------------------- | ------------------------------- | ------------------------------- | /// | 0 - 3 | frame units | frame units | frame units | /// | 4 - 5 | frame tens | frame tens | frame tens | /// | 6 | unused, set to 0 | drop frame flag | unused, set to 0 | /// | 7 | unused, set to 0 | color frame flag | color frame flag | /// | 8 - 11 | seconds units | seconds units | seconds units | /// | 12 - 14 | seconds tens | seconds tens | seconds tens | /// | 15 | phase flag | field/phase flag | bgf0 | /// | 16 - 19 | minutes units | minutes units | minutes units | /// | 20 - 22 | minutes tens | minutes tens | minutes tens | /// | 23 | bgf0 | bgf0 | bgf2 | /// | 24 - 27 | hours units | hours units | hours units | /// | 28 - 29 | hours tens | hours tens | hours tens | /// | 30 | bgf1 | bgf1 | bgf1 | /// | 31 | bgf2 | bgf2 | field/phase flag | /// /// User-defined data and control codes are packed as follows: /// /// | bits | field | /// | ------- | -------------- | /// | 0 - 3 | binary group 1 | /// | 4 - 7 | binary group 2 | /// | 8 - 11 | binary group 3 | /// | 12 - 15 | binary group 4 | /// | 16 - 19 | binary group 5 | /// | 20 - 23 | binary group 6 | /// | 24 - 27 | binary group 7 | /// | 28 - 31 | binary group 8 | /// pub struct TimeCode { inner: sys::Imf_TimeCode_t, } impl Default for TimeCode { fn default() -> Self { let mut inner = MaybeUninit::<sys::Imf_TimeCode_t>::uninit(); unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_default(inner.as_mut_ptr()); Self { inner: inner.assume_init(), } } } } impl Debug for TimeCode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("TimeCode") .field("hours", &self.hours()) .field("minutes", &self.minutes()) .field("seconds", &self.seconds()) .field("frame", &self.frame()) .field("drop_frame", &self.drop_frame()) .field("color_frame", &self.color_frame()) .field("field_phase", &self.field_phase()) .field("bgf0", &self.bgf0()) .field("bgf1", &self.bgf1()) .field("bgf2", &self.bgf2()) .field("binary_group1", &self.binary_group(1).unwrap()) .field("binary_group2", &self.binary_group(2).unwrap()) .field("binary_group3", &self.binary_group(3).unwrap()) .field("binary_group4", &self.binary_group(4).unwrap()) .field("binary_group5", &self.binary_group(5).unwrap()) .field("binary_group6", &self.binary_group(6).unwrap()) .field("binary_group7", &self.binary_group(7).unwrap()) .field("binary_group8", &self.binary_group(8).unwrap()) .finish() } } impl Clone for TimeCode { fn clone(&self) -> Self { let mut other = MaybeUninit::<sys::Imf_TimeCode_t>::uninit(); unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_copy(other.as_mut_ptr(), &self.inner); Self { inner: other.assume_init(), } } } } impl Drop for TimeCode { fn drop(&mut self) { unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_dtor(&mut self.inner); } } } impl PartialEq for TimeCode { fn eq(&self, other: &Self) -> bool { let mut result = false; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode__eq(&self.inner, &mut result, &other.inner); } result } } impl Eq for TimeCode {} impl TimeCode { /// Create a new TimeCode object. /// /// Errors: /// /// The following cases will return an error: /// /// - Setting hours outside of the range of 0 - 23 /// - Setting minutes outside of the range of 0 - 59 /// - Setting seconds outside of the range of 0 - 59 /// - Setting frame outside of the range of 0 - 29 /// #[allow(clippy::too_many_arguments)] pub fn new( hours: i32, minutes: i32, seconds: i32, frame: i32, drop_frame: bool, color_frame: bool, field_phase: bool, bgf0: bool, bgf1: bool, bgf2: bool, binary_group1: i32, binary_group2: i32, binary_group3: i32, binary_group4: i32, binary_group5: i32, binary_group6: i32, binary_group7: i32, binary_group8: i32, ) -> Result<Self> { let mut inner = MaybeUninit::<sys::Imf_TimeCode_t>::uninit(); unsafe { sys::Imf_TimeCode_ctor( inner.as_mut_ptr(), hours as c_int, minutes as c_int, seconds as c_int, frame as c_int, drop_frame, color_frame, field_phase, bgf0, bgf1, bgf2, binary_group1 as c_int, binary_group2 as c_int, binary_group3 as c_int, binary_group4 as c_int, binary_group5 as c_int, binary_group6 as c_int, binary_group7 as c_int, binary_group8 as c_int, ) .into_result()?; Ok(Self { inner: inner.assume_init(), }) } } /// Create a new TimeCode object from the packed representation of the /// object. /// pub fn from_time_and_flags( time_and_flags: u32, user_data: u32, packing: TimeCodePacking, ) -> Self { let mut inner = MaybeUninit::<sys::Imf_TimeCode_t>::uninit(); unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_from_time_and_flags( inner.as_mut_ptr(), time_and_flags as c_uint, user_data as c_uint, packing.to_sys_packing(), ); Self { inner: inner.assume_init(), } } } /// Return the hours from 0 - 23. /// pub fn hours(&self) -> i32 { let mut result: c_int = 0; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_hours(&self.inner, &mut result); } result as i32 } /// Set the hours of the time code. /// /// # Errors /// * [`Error::InvalidArgument`] if `hours` is less than 0 or greater than 23 /// pub fn set_hours(&mut self, hours: i32) -> Result<()> { unsafe { sys::Imf_TimeCode_setHours(&mut self.inner, hours as c_int) .into_result()?; } Ok(()) } /// Return the minutes from 0 - 59. /// pub fn minutes(&self) -> i32 { let mut result: c_int = 0; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_minutes(&self.inner, &mut result); } result as i32 } /// Set the minutes of the time code. /// /// # Errors /// * [`Error::InvalidArgument`] if `minutes` is less than 0 or greater than 59 /// pub fn set_minutes(&mut self, minutes: i32) -> Result<()> { unsafe { sys::Imf_TimeCode_setMinutes(&mut self.inner, minutes as c_int) .into_result()?; } Ok(()) } /// Return the seconds from 0 - 59. /// pub fn seconds(&self) -> i32 { let mut result: c_int = 0; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_seconds(&self.inner, &mut result); } result as i32 } /// Set the seconds of the time code. /// /// # Errors /// * [`Error::InvalidArgument`] if `seconds` is less than 0 or greater than 59 /// pub fn set_seconds(&mut self, seconds: i32) -> Result<()> { unsafe { sys::Imf_TimeCode_setSeconds(&mut self.inner, seconds as c_int) .into_result()?; } Ok(()) } /// Return the frame from 0 - 29. /// pub fn frame(&self) -> i32 { let mut result: c_int = 0; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_frame(&self.inner, &mut result); } result as i32 } /// Set the frame of the time code. /// /// # Errors /// * [`Error::InvalidArgument`] if `frame` is less than 0 or greater than 29 /// pub fn set_frame(&mut self, frame: i32) -> Result<()> { unsafe { sys::Imf_TimeCode_setFrame(&mut self.inner, frame as c_int) .into_result()?; } Ok(()) } /// Return if there is a drop frame. /// pub fn drop_frame(&self) -> bool { let mut result: bool = false; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_dropFrame(&self.inner, &mut result); } result } /// Set if there is a drop frame. /// pub fn set_drop_frame(&mut self, drop_frame: bool) { unsafe { sys::Imf_TimeCode_setDropFrame(&mut self.inner, drop_frame); } } /// Return if there is a color frame. /// pub fn color_frame(&self) -> bool { let mut result: bool = false; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_colorFrame(&self.inner, &mut result); } result } /// Set if there is a color frame. /// pub fn set_color_frame(&mut self, color_frame: bool) { unsafe { sys::Imf_TimeCode_setColorFrame(&mut self.inner, color_frame); } } /// Return if there is a field phase. /// pub fn field_phase(&self) -> bool { let mut result: bool = false; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_fieldPhase(&self.inner, &mut result); } result } /// Set if there is a field phase. /// pub fn set_field_phase(&mut self, field_phase: bool) { unsafe { sys::Imf_TimeCode_setFieldPhase(&mut self.inner, field_phase); } } /// Return the bgf0. /// pub fn bgf0(&self) -> bool { let mut result: bool = false; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_bgf0(&self.inner, &mut result); } result } /// Set the bgf0. /// pub fn set_bgf0(&mut self, bgf0: bool) { unsafe { sys::Imf_TimeCode_setBgf0(&mut self.inner, bgf0); } } /// Return the bgf1. /// pub fn bgf1(&self) -> bool { let mut result: bool = false; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_bgf1(&self.inner, &mut result); } result } /// Set the bgf1. /// pub fn set_bgf1(&mut self, bgf1: bool) { unsafe { sys::Imf_TimeCode_setBgf1(&mut self.inner, bgf1); } } /// Return the bgf2. /// pub fn bgf2(&self) -> bool { let mut result: bool = false; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_bgf2(&self.inner, &mut result); } result } /// Set the bgf2. /// pub fn set_bgf2(&mut self, bgf2: bool) { unsafe { sys::Imf_TimeCode_setBgf2(&mut self.inner, bgf2); } } /// Return the value for the binary group. /// /// # Errors /// * [`Error::InvalidArgument`] if `group` is not between 1 and 8. /// pub fn binary_group(&self, group: i32) -> Result<i32> { let mut result: c_int = 0; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_binaryGroup( &self.inner, &mut result, group as c_int, ) .into_result()?; } Ok(result as i32) } /// Set the binary group value. /// /// # Errors /// /// # Errors /// * [`Error::InvalidArgument`] if `group` is not between 1 and 8 or `value` /// is not between 1 and 15. /// pub fn set_binary_group(&mut self, group: i32, value: i32) -> Result<()> { if !(0..=15).contains(&value) { return Err(Error::InvalidArgument( "Binary group value must be between 0 and 15.".into(), )); } unsafe { sys::Imf_TimeCode_setBinaryGroup( &mut self.inner, group as c_int, value as c_int, ) .into_result()?; } Ok(()) } /// Return the time and flags for the given packing. /// pub fn time_and_flags(&self, packing: TimeCodePacking) -> u32 { let mut result: c_uint = 0; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_timeAndFlags( &self.inner, &mut result, packing.to_sys_packing(), ); } result as u32 } /// Set the time and flags for the given packing. /// pub fn set_time_and_flags(&mut self, value: u32, packing: TimeCodePacking) { unsafe { sys::Imf_TimeCode_setTimeAndFlags( &mut self.inner, value as c_uint, packing.to_sys_packing(), ); } } /// Return arbitrary user data. /// pub fn user_data(&self) -> u32 { let mut result: c_uint = 0; unsafe { // Function does not raise errors, so skipping error checking. sys::Imf_TimeCode_userData(&self.inner, &mut result); } result as u32 } /// Set arbitrary user data. /// pub fn set_user_data(&mut self, value: u32) { unsafe { sys::Imf_TimeCode_setUserData(&mut self.inner, value as c_uint); } } } #[cfg(test)] mod tests { use openexr_sys as sys; #[test] fn test_packing_from_sys_success() { let result = super::TimeCodePacking::from_sys_packing( sys::Imf_TimeCode_Packing_TV60_PACKING, ); assert_eq!(result, super::TimeCodePacking::Tv60); let result = super::TimeCodePacking::from_sys_packing( sys::Imf_TimeCode_Packing_TV50_PACKING, ); assert_eq!(result, super::TimeCodePacking::Tv50); let result = super::TimeCodePacking::from_sys_packing( sys::Imf_TimeCode_Packing_FILM24_PACKING, ); assert_eq!(result, super::TimeCodePacking::Film24); } #[test] #[should_panic] fn test_packing_from_sys_failure_invalid_value() { super::TimeCodePacking::from_sys_packing(sys::Imf_TimeCode_Packing( u32::MAX, )); } #[test] fn test_packing_to_sys_success() { let result = super::TimeCodePacking::Tv60.to_sys_packing(); assert_eq!(result, sys::Imf_TimeCode_Packing_TV60_PACKING); let result = super::TimeCodePacking::Tv50.to_sys_packing(); assert_eq!(result, sys::Imf_TimeCode_Packing_TV50_PACKING); let result = super::TimeCodePacking::Film24.to_sys_packing(); assert_eq!(result, sys::Imf_TimeCode_Packing_FILM24_PACKING); } #[test] fn test_timecode_default_success() { let result = super::TimeCode::default(); let mut is_eq = false; unsafe { sys::Imf_TimeCode__eq( &result.inner, &mut is_eq, &sys::Imf_TimeCode_t::default(), ); } assert!(is_eq); } #[test] fn test_timecode_new_success() { let hours = 1; let minutes = 2; let seconds = 3; let frame = 4; let drop_frame = true; let color_frame = true; let field_phase = true; let bgf0 = true; let bgf1 = true; let bgf2 = true; let binary_group1 = 1; let binary_group2 = 2; let binary_group3 = 3; let binary_group4 = 4; let binary_group5 = 5; let binary_group6 = 6; let binary_group7 = 7; let binary_group8 = 8; let result = super::TimeCode::new( hours, minutes, seconds, frame, drop_frame, color_frame, field_phase, bgf0, bgf1, bgf2, binary_group1, binary_group2, binary_group3, binary_group4, binary_group5, binary_group6, binary_group7, binary_group8, ) .unwrap(); assert_eq!(result.hours(), hours); assert_eq!(result.minutes(), minutes); assert_eq!(result.seconds(), seconds); assert_eq!(result.frame(), frame); assert_eq!(result.drop_frame(), drop_frame); assert_eq!(result.color_frame(), color_frame); assert_eq!(result.field_phase(), field_phase); assert_eq!(result.bgf0(), bgf0); assert_eq!(result.bgf1(), bgf1); assert_eq!(result.bgf2(), bgf2); assert_eq!(result.binary_group(1).unwrap(), binary_group1); assert_eq!(result.binary_group(2).unwrap(), binary_group2); assert_eq!(result.binary_group(3).unwrap(), binary_group3); assert_eq!(result.binary_group(4).unwrap(), binary_group4); assert_eq!(result.binary_group(5).unwrap(), binary_group5); assert_eq!(result.binary_group(6).unwrap(), binary_group6); assert_eq!(result.binary_group(7).unwrap(), binary_group7); assert_eq!(result.binary_group(8).unwrap(), binary_group8); } #[test] fn test_timecode_from_time_and_flags_success() { let hours = 1; let minutes = 2; let seconds = 3; let frame = 4; let drop_frame = false; let color_frame = false; let field_phase = false; let bgf0 = true; let bgf1 = true; let bgf2 = true; let binary_group1 = 1; let binary_group2 = 2; let binary_group3 = 3; let binary_group4 = 4; let binary_group5 = 5; let binary_group6 = 6; let binary_group7 = 7; let binary_group8 = 8; let example = super::TimeCode::new( hours, minutes, seconds, frame, drop_frame, color_frame, field_phase, bgf0, bgf1, bgf2, binary_group1, binary_group2, binary_group3, binary_group4, binary_group5, binary_group6, binary_group7, binary_group8, ) .unwrap(); let packing = super::TimeCodePacking::Film24; let result = super::TimeCode::from_time_and_flags( example.time_and_flags(packing), example.user_data(), packing, ); assert_eq!(example, result); } #[test] fn test_timecode_clone_success() { let left = super::TimeCode::default(); let right = left.clone(); assert_eq!(left, right); } #[test] fn test_timecode_eq_success() { let left = super::TimeCode::default(); let right = super::TimeCode::default(); assert_eq!(left, right); } #[test] fn test_timecode_ne_success() { let left = super::TimeCode::default(); let mut right = super::TimeCode::default(); right.set_hours(1).unwrap(); assert_ne!(left, right); } #[test] fn test_timecode_set_hours_to_min_success() { let mut timecode = super::TimeCode::default(); timecode.set_hours(0).unwrap(); assert_eq!(timecode.hours(), 0); } #[test] fn test_timecode_set_hours_to_max_success() { let mut timecode = super::TimeCode::default(); timecode.set_hours(23).unwrap(); assert_eq!(timecode.hours(), 23); } #[test] fn test_timecode_set_hours_to_less_than_min_failure() { let mut timecode = super::TimeCode::default(); assert_eq!(timecode.set_hours(-1).is_err(), true); } #[test] fn test_timecode_set_hours_to_greater_than_max_failure() { let mut timecode = super::TimeCode::default(); assert_eq!(timecode.set_hours(24).is_err(), true); } #[test] fn test_timecode_set_minutes_to_min_success() { let mut timecode = super::TimeCode::default(); timecode.set_minutes(0).unwrap(); assert_eq!(timecode.minutes(), 0); } #[test] fn test_timecode_set_minutes_to_max_success() { let mut timecode = super::TimeCode::default(); timecode.set_minutes(59).unwrap(); assert_eq!(timecode.minutes(), 59); } #[test] fn test_timecode_set_minutes_to_less_than_min_failure() { let mut timecode = super::TimeCode::default(); assert_eq!(timecode.set_minutes(-1).is_err(), true); } #[test] fn test_timecode_set_minutes_to_greater_than_max_failure() { let mut timecode = super::TimeCode::default(); assert_eq!(timecode.set_minutes(60).is_err(), true); } #[test] fn test_timecode_set_seconds_to_min_success() { let mut timecode = super::TimeCode::default(); timecode.set_seconds(0).unwrap(); assert_eq!(timecode.seconds(), 0); } #[test] fn test_timecode_set_seconds_to_max_success() { let mut timecode = super::TimeCode::default(); timecode.set_seconds(59).unwrap(); assert_eq!(timecode.seconds(), 59); } #[test] fn test_timecode_set_seconds_to_less_than_min_failure() { let mut timecode = super::TimeCode::default(); assert_eq!(timecode.set_seconds(-1).is_err(), true); } #[test] fn test_timecode_set_seconds_to_greater_than_max_failure() { let mut timecode = super::TimeCode::default(); assert_eq!(timecode.set_seconds(60).is_err(), true); } #[test] fn test_timecode_set_frame_to_min_success() { let mut timecode = super::TimeCode::default(); timecode.set_frame(0).unwrap(); assert_eq!(timecode.frame(), 0); } #[test] fn test_timecode_set_frame_to_max_success() { let mut timecode = super::TimeCode::default(); // NOTE: There is a bug with OpenEXR where the max time code should be 29, but v3.0.1 doesn't include that fix. timecode.set_frame(29).unwrap(); assert_eq!(timecode.frame(), 29); } #[test] fn test_timecode_set_frame_to_less_than_min_failure() { let mut timecode = super::TimeCode::default(); assert_eq!(timecode.set_frame(-1).is_err(), true); } #[test] fn test_timecode_set_frame_to_greater_than_max_failure() { let mut timecode = super::TimeCode::default(); // NOTE: There is a bug with OpenEXR where the max time code should be 29, but v3.0.1 doesn't include that fix. // Adding a check for a frame value of 30 to address future patches. assert_eq!( timecode.set_frame(30).is_ok(), true, "OpenEXR bug fixed post v3.0.1" ); assert_eq!(timecode.set_frame(60).is_err(), true); } #[test] fn test_timecode_set_drop_frame_success() { let mut timecode = super::TimeCode::default(); timecode.set_drop_frame(true); assert_eq!(timecode.drop_frame(), true); timecode.set_drop_frame(false); assert_eq!(timecode.drop_frame(), false); } #[test] fn test_timecode_set_color_frame_success() { let mut timecode = super::TimeCode::default(); timecode.set_color_frame(true); assert_eq!(timecode.color_frame(), true); timecode.set_color_frame(false); assert_eq!(timecode.color_frame(), false); } #[test] fn test_timecode_set_field_phase_success() { let mut timecode = super::TimeCode::default(); timecode.set_field_phase(true); assert_eq!(timecode.field_phase(), true); timecode.set_field_phase(false); assert_eq!(timecode.field_phase(), false); } #[test] fn test_timecode_set_bgf0_success() { let mut timecode = super::TimeCode::default(); timecode.set_bgf0(true); assert_eq!(timecode.bgf0(), true); timecode.set_bgf0(false); assert_eq!(timecode.bgf0(), false); } #[test] fn test_timecode_set_bgf1_success() { let mut timecode = super::TimeCode::default(); timecode.set_bgf1(true); assert_eq!(timecode.bgf1(), true); timecode.set_bgf1(false); assert_eq!(timecode.bgf1(), false); } #[test] fn test_timecode_set_bgf2_success() { let mut timecode = super::TimeCode::default(); timecode.set_bgf2(true); assert_eq!(timecode.bgf2(), true); timecode.set_bgf2(false); assert_eq!(timecode.bgf2(), false); } #[test] fn test_timecode_set_binary_group_min_group_success() { let mut timecode = super::TimeCode::default(); timecode.set_binary_group(1, 1).unwrap(); assert_eq!(timecode.binary_group(1).unwrap(), 1); } #[test] fn test_timecode_set_binary_group_max_group_success() { let mut timecode = super::TimeCode::default(); timecode.set_binary_group(8, 1).unwrap(); assert_eq!(timecode.binary_group(8).unwrap(), 1); } #[test] fn test_timecode_set_binary_group_less_than_min_group_failure() { let mut timecode = super::TimeCode::default(); assert_eq!(timecode.set_binary_group(0, 1).is_err(), true); } #[test] fn test_timecode_set_binary_group_greater_than_max_group_failure() { let mut timecode = super::TimeCode::default(); assert_eq!(timecode.set_binary_group(9, 1).is_err(), true); } #[test] fn test_timecode_set_binary_group_min_value_success() { let mut timecode = super::TimeCode::default(); timecode.set_binary_group(1, 0).unwrap(); assert_eq!(timecode.binary_group(1).unwrap(), 0); } #[test] fn test_timecode_set_binary_group_max_value_success() { let mut timecode = super::TimeCode::default(); timecode.set_binary_group(1, 15).unwrap(); assert_eq!(timecode.binary_group(1).unwrap(), 15); } #[test] fn test_timecode_set_binary_group_less_than_min_value_failure() { let mut timecode = super::TimeCode::default(); assert_eq!(timecode.set_binary_group(1, -1).is_err(), true); } #[test] fn test_timecode_set_binary_group_greater_than_max_value_failure() { let mut timecode = super::TimeCode::default(); assert_eq!(timecode.set_binary_group(1, 16).is_err(), true); } #[test] fn test_timecode_set_time_and_flags_success() { let mut timecode = super::TimeCode::default(); let hours = 1; let minutes = 2; let seconds = 3; let frame = 4; let drop_frame = false; let color_frame = false; let field_phase = false; let bgf0 = true; let bgf1 = true; let bgf2 = true; let binary_group1 = 1; let binary_group2 = 2; let binary_group3 = 3; let binary_group4 = 4; let binary_group5 = 5; let binary_group6 = 6; let binary_group7 = 7; let binary_group8 = 8; let example = super::TimeCode::new( hours, minutes, seconds, frame, drop_frame, color_frame, field_phase, bgf0, bgf1, bgf2, binary_group1, binary_group2, binary_group3, binary_group4, binary_group5, binary_group6, binary_group7, binary_group8, ) .unwrap(); let packing = super::TimeCodePacking::Film24; timecode.set_time_and_flags(example.time_and_flags(packing), packing); assert_eq!( timecode.time_and_flags(packing), example.time_and_flags(packing) ); } #[test] fn test_timecode_set_user_data_success() { let mut timecode = super::TimeCode::default(); timecode.set_user_data(1); assert_eq!(timecode.user_data(), 1); } }
use crate::controlled::DropResult; use crate::time::GameTime; use core::time::Duration; pub struct LockDelay { accumulated_time: Duration, prev_lock_time: Option<GameTime>, num_resets: u32, } const LOCK_DELAY: Duration = Duration::from_millis(500); const ALLOWED_RESETS: u32 = 5; impl LockDelay { pub fn new() -> Self { LockDelay { accumulated_time: Duration::from_millis(0), prev_lock_time: None, num_resets: 0, } } pub fn consume_time(&mut self, now: GameTime) -> DropResult { if let Some(prev) = self.prev_lock_time { self.accumulated_time += now - prev; } self.prev_lock_time = Some(now); if self.accumulated_time > LOCK_DELAY { DropResult::Stop } else { DropResult::Continue } } pub fn reset(&mut self) { if let Some(_) = self.prev_lock_time { if self.num_resets < ALLOWED_RESETS { self.accumulated_time = Duration::from_millis(0); self.prev_lock_time = None; self.num_resets += 1; } } } } #[cfg(test)] mod tests { use super::*; use crate::time::GameClock; const EPS: Duration = Duration::from_millis(1); #[test] fn simple_delay() { let start_time = GameClock::new().now(); let mut ld = LockDelay::new(); assert_eq!(ld.consume_time(start_time), DropResult::Continue); assert_eq!( ld.consume_time(start_time + LOCK_DELAY + EPS), DropResult::Stop ) } #[test] fn reset() { let start_time = GameClock::new().now(); let mut ld = LockDelay::new(); assert_eq!(ld.consume_time(start_time), DropResult::Continue); ld.reset(); assert_eq!( ld.consume_time(start_time + LOCK_DELAY + EPS), DropResult::Continue ); assert_eq!( ld.consume_time(start_time + (LOCK_DELAY + EPS) * 2), DropResult::Stop ); } #[test] fn consume_resets() { let start_time = GameClock::new().now(); let mut ld = LockDelay::new(); for i in 0..ALLOWED_RESETS { assert_eq!( ld.consume_time(start_time + (LOCK_DELAY + EPS) * i), DropResult::Continue ); ld.reset(); ld.reset(); } assert_eq!( ld.consume_time(start_time + (LOCK_DELAY + EPS) * ALLOWED_RESETS), DropResult::Continue ); ld.reset(); assert_eq!( ld.consume_time(start_time + (LOCK_DELAY + EPS) * (ALLOWED_RESETS + 1)), DropResult::Stop ); } }
use crate::{ast::nodes::FunctionDeclaration, runtime::{Runtime, nodes::{FunctionCall, FunctionCallType}}}; pub fn parse_function_declaration(runtime: &mut Runtime, statement: &FunctionDeclaration) { let current_scope = runtime.current_scope(); let name = statement.id.name.to_string(); let params = statement.to_owned().params; let body = statement.to_owned().body; let function_call = FunctionCall { function_type: FunctionCallType::RuntimeCall(body), arguments: vec![], }; current_scope.functions.insert(name, function_call); }
pub mod header; pub mod message_types; pub mod options;
use structopt::StructOpt; use std::fmt::{self, Display, Formatter}; #[derive(StructOpt)] #[structopt(name = "app")] pub struct AppArgs { #[structopt(subcommand)] pub command: Command, } #[derive(StructOpt)] pub enum Command { /// add operation #[structopt(name = "add")] Add(Elements), /// times operation #[structopt(name = "times")] Times(Elements), } #[derive(StructOpt)] pub struct Elements { pub elements: Vec<u32>, } impl Display for Elements { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "[{:#?}]", self.elements) } } fn main() { let opt = AppArgs::from_args(); match opt.command { Command::Add(e) => { let result = e.elements.iter().fold(0, |acc, &x| acc + x); println!("Operants: {}, result: {}", e, result); }, Command::Times(e) => { let result = e.elements.iter().fold(1, |acc, &x| acc * x); println!("Operants: {}, result: {}", e, result); }, } }
#![allow(dead_code)] extern crate kalmanfilter; extern crate nalgebra as na; extern crate num; extern crate rand; mod helpers; use kalmanfilter::nt; use na::{Real, DVector}; use helpers::model::*; #[test] fn compare_continuous_discrete() { let dt = 0.001; let eps = 1e-12; let sim_time = 20usize; let steps = (sim_time as f64 / dt) as usize; let mut cont : ContinuousLinearModel = example_model_2states_regular_stable().into(); let mut discr : DiscreteLinearModel = example_model_2states_regular_stable() .into_discrete(dt, eps).into(); for i in 0..steps { let t = i as f64 * dt; let u = if t < 5. { 0. } else { 1. }; let u = nt::InputVector(DVector::from_row_slice(1, &[u,])); cont.step(&u, dt); discr.step(&u); let diff = &discr.get_state().0 - &cont.get_state().0; let max = diff.iter().fold(0., |store, item| { store.max(*item) }); if max > 0.0001 { panic!("Continuous does not equal discrete form"); } } } #[test] fn compare_continuous_discrete_async() { let dt_discr = 0.1; let dt_cont = 0.001; let eps = 1e-12; let sim_time = 20usize; let steps = (sim_time as f64 / dt_cont) as usize; let discr_every = (dt_discr / dt_cont) as usize; let mut cont : ContinuousLinearModel = example_model_2states_regular_stable().into(); let mut discr : DiscreteLinearModel = example_model_2states_regular_stable() .into_discrete(dt_discr, eps).into(); for i in 0..steps { let t = i as f64 * dt_cont; // Note the <=: Make sure the continuous model does not get the step earlier let u = if t <= 5. { 0. } else { 1. }; let u = nt::InputVector(DVector::from_row_slice(1, &[u,])); cont.step(&u, dt_cont); if i % discr_every == 0 && i != 0 { discr.step(&u); let diff = &discr.get_state().0 - &cont.get_state().0; let max = diff.iter().fold(0., |store, item| { store.max(*item) }); if max > 0.0001 { panic!("Continuous does not equal discrete form"); } // if (t - t.trunc()) < dt_cont/2. { // //println!("t={}, discr={}, cont={}", t, discr.get_state(), cont.get_state()); // println!("t={}, diff={}", t, diff); // } } } } /// Tests `kalmanfilter::systems::calc_mat_h` #[test] fn compare_continuous_discrete_async_singular() { let dt_discr = 0.1; let dt_cont = 0.001; let eps = 1e-5; let sim_time = 20usize; let steps = (sim_time as f64 / dt_cont) as usize; let discr_every = (dt_discr / dt_cont) as usize; let mut cont : ContinuousLinearModel = example_model_2states_singular_stable().into(); let mut discr : DiscreteLinearModel = example_model_2states_singular_stable() .into_discrete(dt_discr, eps).into(); for i in 0..steps { let t = i as f64 * dt_cont; // Note the <=: Make sure the continuous model does not get the step earlier let u = if t <= 5. { 0. } else { 1. }; let u = nt::InputVector(DVector::from_row_slice(1, &[u,])); cont.step(&u, dt_cont); if i % discr_every == 0 && i != 0 { discr.step(&u); let diff = &discr.get_state().0 - &cont.get_state().0; let max = diff.iter().fold(0., |store, item| { store.max(*item) }); if max > 0.0001 { panic!("Continuous does not equal discrete form"); } // if (t - t.trunc()) < dt_cont/2. { // //println!("t={}, discr={}, cont={}", t, discr.get_state(), cont.get_state()); // println!("t={}, diff={}", t, diff); // } } } }
use serde_json::json; mod common; #[actix_rt::test] async fn create_index_lazy_by_pushing_documents() { let mut server = common::Server::with_uid("movies"); // 1 - Add documents let body = json!([{ "title": "Test", "comment": "comment test" }]); let url = "/indexes/movies/documents?primaryKey=title"; let (response, status_code) = server.post_request(&url, body).await; assert_eq!(status_code, 202); let update_id = response["updateId"].as_u64().unwrap(); server.wait_update_id(update_id).await; // 3 - Check update success let (response, status_code) = server.get_update_status(update_id).await; assert_eq!(status_code, 200); assert_eq!(response["status"], "processed"); } #[actix_rt::test] async fn create_index_lazy_by_pushing_documents_and_discover_pk() { let mut server = common::Server::with_uid("movies"); // 1 - Add documents let body = json!([{ "id": 1, "title": "Test", "comment": "comment test" }]); let url = "/indexes/movies/documents"; let (response, status_code) = server.post_request(&url, body).await; assert_eq!(status_code, 202); let update_id = response["updateId"].as_u64().unwrap(); server.wait_update_id(update_id).await; // 3 - Check update success let (response, status_code) = server.get_update_status(update_id).await; assert_eq!(status_code, 200); assert_eq!(response["status"], "processed"); } #[actix_rt::test] async fn create_index_lazy_by_pushing_documents_with_wrong_name() { let server = common::Server::with_uid("wrong&name"); let body = json!([{ "title": "Test", "comment": "comment test" }]); let url = "/indexes/wrong&name/documents?primaryKey=title"; let (response, status_code) = server.post_request(&url, body).await; assert_eq!(status_code, 400); assert_eq!(response["errorCode"], "invalid_index_uid"); } #[actix_rt::test] async fn create_index_lazy_add_documents_failed() { let mut server = common::Server::with_uid("wrong&name"); let body = json!([{ "title": "Test", "comment": "comment test" }]); let url = "/indexes/wrong&name/documents"; let (response, status_code) = server.post_request(&url, body).await; assert_eq!(status_code, 400); assert_eq!(response["errorCode"], "invalid_index_uid"); let (_, status_code) = server.get_index().await; assert_eq!(status_code, 404); } #[actix_rt::test] async fn create_index_lazy_by_sending_settings() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!({ "rankingRules": [ "typo", "words", "proximity", "attribute", "wordsPosition", "exactness", "desc(registered)", "desc(age)", ], "distinctAttribute": "id", "searchableAttributes": [ "id", "name", "color", "gender", "email", "phone", "address", "registered", "about" ], "displayedAttributes": [ "name", "gender", "email", "registered", "age", ], "stopWords": [ "ad", "in", "ut", ], "synonyms": { "road": ["street", "avenue"], "street": ["avenue"], }, "attributesForFaceting": ["name"], }); server.update_all_settings(body.clone()).await; // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 200); } #[actix_rt::test] async fn create_index_lazy_by_sending_settings_with_error() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!({ "rankingRules": [ "other", "words", "proximity", "attribute", "wordsPosition", "exactness", "desc(registered)", "desc(age)", ], "distinctAttribute": "id", "searchableAttributes": [ "id", "name", "color", "gender", "email", "phone", "address", "registered", "about" ], "displayedAttributes": [ "name", "gender", "email", "registered", "age", ], "stopWords": [ "ad", "in", "ut", ], "synonyms": { "road": ["street", "avenue"], "street": ["avenue"], }, "anotherSettings": ["name"], }); let (_, status_code) = server.update_all_settings_sync(body.clone()).await; assert_eq!(status_code, 400); // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 404); } #[actix_rt::test] async fn create_index_lazy_by_sending_ranking_rules() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!([ "typo", "words", "proximity", "attribute", "wordsPosition", "exactness", "desc(registered)", "desc(age)", ]); server.update_ranking_rules(body.clone()).await; // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 200); } #[actix_rt::test] async fn create_index_lazy_by_sending_ranking_rules_with_error() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!({ "rankingRules": 123, }); let (_, status_code) = server.update_ranking_rules_sync(body.clone()).await; assert_eq!(status_code, 400); // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 404); } #[actix_rt::test] async fn create_index_lazy_by_sending_distinct_attribute() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!("type"); server.update_distinct_attribute(body.clone()).await; // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 200); } #[actix_rt::test] async fn create_index_lazy_by_sending_distinct_attribute_with_error() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!(123); let (resp, status_code) = server.update_distinct_attribute_sync(body.clone()).await; eprintln!("resp: {:?}", resp); assert_eq!(status_code, 400); // 3 - Get all settings and compare to the previous one let (resp, status_code) = server.get_all_settings().await; eprintln!("resp: {:?}", resp); assert_eq!(status_code, 404); } #[actix_rt::test] async fn create_index_lazy_by_sending_searchable_attributes() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!(["title", "description"]); server.update_searchable_attributes(body.clone()).await; // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 200); } #[actix_rt::test] async fn create_index_lazy_by_sending_searchable_attributes_with_error() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!(123); let (_, status_code) = server.update_searchable_attributes_sync(body.clone()).await; assert_eq!(status_code, 400); // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 404); } #[actix_rt::test] async fn create_index_lazy_by_sending_displayed_attributes() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!(["title", "description"]); server.update_displayed_attributes(body.clone()).await; // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 200); } #[actix_rt::test] async fn create_index_lazy_by_sending_displayed_attributes_with_error() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!(123); let (_, status_code) = server.update_displayed_attributes_sync(body.clone()).await; assert_eq!(status_code, 400); // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 404); } #[actix_rt::test] async fn create_index_lazy_by_sending_attributes_for_faceting() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!(["title", "description"]); server.update_attributes_for_faceting(body.clone()).await; // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 200); } #[actix_rt::test] async fn create_index_lazy_by_sending_attributes_for_faceting_with_error() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!(123); let (_, status_code) = server .update_attributes_for_faceting_sync(body.clone()) .await; assert_eq!(status_code, 400); // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 404); } #[actix_rt::test] async fn create_index_lazy_by_sending_synonyms() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!({ "road": ["street", "avenue"], "street": ["avenue"], }); server.update_synonyms(body.clone()).await; // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 200); } #[actix_rt::test] async fn create_index_lazy_by_sending_synonyms_with_error() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!(123); let (_, status_code) = server.update_synonyms_sync(body.clone()).await; assert_eq!(status_code, 400); // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 404); } #[actix_rt::test] async fn create_index_lazy_by_sending_stop_words() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!(["le", "la", "les"]); server.update_stop_words(body.clone()).await; // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 200); } #[actix_rt::test] async fn create_index_lazy_by_sending_stop_words_with_error() { let mut server = common::Server::with_uid("movies"); // 2 - Send the settings let body = json!(123); let (_, status_code) = server.update_stop_words_sync(body.clone()).await; assert_eq!(status_code, 400); // 3 - Get all settings and compare to the previous one let (_, status_code) = server.get_all_settings().await; assert_eq!(status_code, 404); }
pub mod types; use std::cell::RefCell; use std::rc::Rc; use types::errors::{CursorError as ce, TowerError as te}; use types::{Cursor, Disk, Tower}; #[derive(Debug)] pub struct Game { pub towers: [Rc<RefCell<Tower>>; 3], pub cursor: Cursor, moves: u32, disks: u8, } impl Game { pub fn new(disks: u8) -> Self { let towers = [ Tower::new().as_rc(), Tower::new().as_rc(), Tower::new().as_rc(), ]; let cursor = Cursor { disk: None, selected_tower: towers[0].clone(), }; { let mut t = towers[0].borrow_mut(); for i in (1..=disks).rev() { t.push(Disk::new(i)).unwrap(); // tower is empty, can't error } } Game { towers, cursor, disks, moves: 0, } } pub fn run(&mut self) { println!("Use the numbers 2, 4, 6, and 8 (preferably on the numpad)"); println!("to play. 4 and 6 move left or right, respectively,"); println!("8 takes a disk from the current tower, and 2 drops the"); println!("disk on it. Type q to quit.\n"); self.main_loop(); println!("Total number of moves: {}", self.moves,); if self.solved() { println!( "You solved the puzzle{}! Yay!", match self.moves == 2u32.pow(self.disks as u32) - 1 { true => " with the optimal solution", _ => "", } ); } else { println!("You didn't solve the puzzle. :("); } } fn solved(&self) -> bool { self.towers[2].borrow().disks.len() as u8 == self.disks } fn main_loop(&mut self) { let mut buff = String::new(); let stdin = std::io::stdin(); while !self.solved() { self.draw_everything(); stdin.read_line(&mut buff).expect("Can't read from stdin"); match buff.chars().nth(0) { Some('q') => break, Some('2') => match self.cursor.drop() { Ok(()) => { println!("Dropped disk on tower."); self.moves += 1; } Err(ce::CannotDropDiskOnTower) => { println!("Cannot drop this disk on this tower.") } Err(ce::NoDisksToDrop) => println!("Not holding any disks now."), Err(ce::TE(te::SmallerDiskOnTower)) => println!("Disk on tower is smaller."), Err(e) => println!("Error while dropping: {:?}", e), }, Some('8') => match self.cursor.take() { Ok(()) => println!("Took disk from tower."), Err(ce::AlreadyHoldingADisk { .. }) => println!("Already holding a disk."), Err(ce::TE(te::NoDisksOnTower)) => println!("Tower is empty."), Err(e) => println!("Error while taking: {:?}", e), }, Some('4') => { let t = self.cursor.selected_tower.borrow().id() as usize; match t { 1 => println!("Can't move cursor to the left."), _ => { self.cursor.selected_tower = self.towers[t - 2].clone(); println!("Moved to the tower on the left."); } } } Some('6') => { let t = self.cursor.selected_tower.borrow().id() as usize; match t { 3 => println!("Can't move cursor to the right."), _ => { self.cursor.selected_tower = self.towers[t].clone(); println!("Moved to the tower on the right."); } } } Some(c) => println!("Unrecognized character: {:?}.", c), None => println!("Input is empty."), } buff.clear(); } } fn draw_everything(&self) { for t in &self.towers { println!( "Disks on tower #{}: {:?}", t.borrow().id(), t.borrow().disks ); } print!( "Cursor is over tower #{}, and it's ", self.cursor.selected_tower.borrow().id(), ); match &self.cursor.disk { Some(d) => println!("holding a disk of size {}.\n", d.size()), None => println!("not holding anything.\n"), }; } }
use fraction::Fraction; use projecteuler::fraction; fn main() { dbg!(min_product_sum(2)); dbg!(min_product_sum(64)); dbg!(solve(2, 6)); dbg!(solve(2, 12000)); } fn solve(low: usize, high: usize) -> usize { let mut values = Vec::new(); for i in low..=high { let min = min_product_sum(i); values.push(min); //dbg!((i, min)); } values.sort(); values.dedup(); values.into_iter().sum::<usize>() } fn min_product_sum(n: usize) -> usize { if n == 0 { panic!(); } if n == 1 { return 1; } let mut min = None; let mut numbers = vec![1; n]; numbers[1] = 2; let mut prod = 2; let mut sum = n + 1; loop { //dbg!(&numbers); //dbg!(sum); //dbg!(prod); //fix numbers[0] so that prod = sum let sum_tail = sum - numbers[0]; let prod_tail = prod / numbers[0]; let new_value = Fraction::new(sum_tail, prod_tail - 1); if new_value.is_integer() { // let new_value = new_value.floor(); sum = sum_tail + new_value; prod = prod_tail * new_value; numbers[0] = new_value; //found a solution, remember it if its smaller than the last one if min.is_none() || min.unwrap() > sum { min = Some(sum); } } //increment numbers[i] if the minimum prod of numbers stays below the minimum sum let mut sum_tail = sum - numbers[0]; let mut prod_tail = prod / numbers[0]; for i in 1..n { sum_tail -= numbers[i]; prod_tail /= numbers[i]; let next_value = numbers[i] + 1; let min_sum = sum_tail + next_value * (i + 1); let min_prod = next_value .checked_pow((i + 1) as u32) .and_then(|x| x.checked_mul(prod_tail)); //let min_prod = prod_tail * next_value.pow((i + 1) as u32); if min_prod.is_some() && min_prod.unwrap() <= min_sum { //there might be a solution for j in 0..=i { numbers[j] = next_value; } sum = min_sum; prod = min_prod.unwrap(); break; } if i == n - 1 { //if the product is always going to be bigger than the sum //there is nothing left we can do return min.unwrap(); } } } }
#![allow(clippy::comparison_chain)] #![allow(clippy::collapsible_if)] use std::cmp::Reverse; use std::cmp::{max, min}; use std::collections::{BTreeSet, HashMap, HashSet}; use std::fmt::Debug; use itertools::Itertools; use whiteread::parse_line; const ten97: usize = 1000_000_007; /// 2の逆元 mod ten97.割りたいときに使う const inv2ten97: u128 = 500_000_004; const mmm: usize = 998244353; fn main() { let n: usize = parse_line().unwrap(); let aa: Vec<usize> = parse_line().unwrap(); let bb: Vec<usize> = parse_line().unwrap(); let mut dp: Vec<Vec<usize>> = vec![vec![0; 3000 + 1]; n + 1]; if aa[0] == 0 { dp[1][0] = 1; } for i in 1..3001 { if aa[0] <= i && i <= bb[0] { dp[1][i] = dp[1][i - 1] + 1; } else { dp[1][i] = dp[1][i - 1]; } } // println!("{:?}", dp[1]); for i in 2..=n { if aa[i - 1] == 0 { dp[i][0] = 1; } for j in 1..=*bb.last().unwrap() { if j < aa[i - 1] || bb[i - 1] < j { dp[i][j] = dp[i][j - 1]; continue; } dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; dp[i][j] %= mmm; } } println!("{}", dp[n][*bb.last().unwrap()]); }
// First we define the datatype for all of our tokens: String // We chose string instead of some complex type because it is simple struct TokenType(String); //Now we define the a structure for the tokens themselves struct Token { Type : TokenType, Literal : String, } //Now we define the values for all of our tokens //Special Characters: const ILLEGAL: String = "ILLEGAL"; const EOF: String = "EOF"; //Identifiers and Literals const IDENTIFIER: String = "IDENTIFIER"; //Variable names const INT: String = "INT"; //integers //Operators //math const ASSIGN: String = ":="; const PLUS: String = "+"; const MINUS: String = "-"; const BANG: String = "!"; const STAR: String = "*"; const SLASH: String = "/"; //comparators const LT: String = "<"; const GT: String = ">"; const EQ: String = "="; const NEQ: String = "!="; //delimeters const COMMA: String = ","; const SEMICOLON: String = ";"; const LPAREN: String = "("; const RPAREN: String = ")"; const LCURLYBRACKET: String = "{"; const RCURLYBRACKET: String = "}"; const LSQUAREBRACKET: String = "["; const RSQUAREBRACKET: String = "]"; //Keywords const FUNCTION: String = "FUNCTION"; const LET: String= "LET"; const TRUE: String "TRUE"; const FALSE: String = "FALSE"; const RETURN: String = "RETURN"; const RETURNS: String = "RETURNS"; const KEY: String = "KEY"; const LOCK: String = "LOCK"; // //Initializes the hasmap we will use to map our keywords to their values // let mut keywords = HashMap::new(); // //Adds all of our keywords to our hashmap // keywords.insert(String::from("fn"), FUNCTION); // keywords.insert(String::from("let"), LET); // keywords.insert(String::from("true"), TRUE); // keywords.insert(String::from("false"), FALSE); // keywords.insert(String::from("return"), RETURN); // keywords.insert(String::from("returns"), RETURNS); // keywords.insert(String::from("key"), KEY); // keywords.insert(String::from("lock"), LOCK);
use std::process::exit; use termbin::cmd::Cmd; fn main() { if let Err(e) = Cmd::from_args().run() { eprintln!("error: {}", e); exit(2); } }
// Copyright 2017 Dasein Phaos aka. Luxko // // 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. //! direct command lists use super::*; /// An allocator for GPU commands #[derive(Debug)] pub struct DirectCommandAllocator { pub(crate) ptr: ComPtr<ID3D12CommandAllocator>, } impl DirectCommandAllocator { /// indicates that the associated memory would be recycled by the allocator. #[inline] pub fn reset(&mut self) -> Result<(), WinError> { let hr = unsafe {self.ptr.Reset()}; WinError::from_hresult(hr) } } /// a direct command list #[derive(Clone, Debug)] pub struct DirectCommandList { pub(crate) ptr: ComPtr<ID3D12GraphicsCommandList>, } impl DirectCommandList { /// start command recording. [more](https://msdn.microsoft.com/library/windows/desktop/dn903895(v=vs.85).aspx) pub fn start_graphics<'b>( mut self, alloc: &'b mut DirectCommandAllocator, initial_state: Option<&'b GraphicsPipelineState> ) -> Result<DirectCommandListRecording<'b, GraphicsPipelineState>, (WinError, Self)> { let p_initial_state = if let Some(initial_state) = initial_state { initial_state.ptr.as_mut_ptr() } else { ::std::ptr::null_mut() }; unsafe { let result = WinError::from_hresult(self.ptr.Reset(alloc.ptr.as_mut_ptr(), p_initial_state)); if result.is_ok() { Ok(DirectCommandListRecording{ ptr: self.ptr, alloc, initial_state}) } else { Err((result.unwrap_err(), self)) } } } /// start command recording. [more](https://msdn.microsoft.com/library/windows/desktop/dn903895(v=vs.85).aspx) pub fn start_compute<'b>( mut self, alloc: &'b mut DirectCommandAllocator, initial_state: Option<&'b ComputePipelineState> ) -> Result<DirectCommandListRecording<'b, ComputePipelineState>, (WinError, Self)> { let p_initial_state = if let Some(initial_state) = initial_state { initial_state.ptr.as_mut_ptr() } else { ::std::ptr::null_mut() }; unsafe { let result = WinError::from_hresult(self.ptr.Reset(alloc.ptr.as_mut_ptr(), p_initial_state)); if result.is_ok() { Ok(DirectCommandListRecording{ ptr: self.ptr, alloc, initial_state}) } else { Err((result.unwrap_err(), self)) } } } } /// a direct command list on recording state #[derive(Debug)] pub struct DirectCommandListRecording<'a, P: 'a> { pub(crate) ptr: ComPtr<ID3D12GraphicsCommandList>, /// command allocator used to back up command recording pub alloc: &'a mut DirectCommandAllocator, /// initial state of this command list pub initial_state: Option<&'a P>, } impl<'a, P: 'a + PipelineState> DirectCommandListRecording<'a, P> { /// record a command to clear the dsv. [more info](https://msdn.microsoft.com/library/windows/desktop/dn903840(v=vs.85).aspx) pub fn clear_dsv( &mut self, dsv: CpuDsvHandle, flags: DepthStencilClearFlags, depth: f32, stencil: u8, rects: Option<&[::format::Rect]> ) { let (numrects, prects) = if let Some(rects) = rects { (rects.len() as u32, rects.as_ptr()) } else { (0, ::std::ptr::null()) }; unsafe { self.ptr.ClearDepthStencilView( dsv.into(), ::std::mem::transmute(flags), depth, stencil, numrects, prects ); } } /// record a command to clear uav. [more info](https://msdn.microsoft.com/library/windows/desktop/dn903849(v=vs.85).aspx) pub fn clear_uav_f32<T: CsuHeap>( &mut self, heap: &mut T, index: u32, resource: &mut RawResource, values: &[f32; 4], rects: Option<&[::format::Rect]> ) { let (numrects, prects) = if let Some(rects) = rects { (rects.len() as u32, rects.as_ptr()) } else { (0, ::std::ptr::null()) }; unsafe { self.ptr.ClearUnorderedAccessViewFloat( heap.get_gpu_handle(index).into(), heap.get_cpu_handle(index).into(), resource.ptr.as_mut_ptr(), values.as_ptr() as *const _, numrects, prects ) } } /// record a command to clear uav. [more info](https://msdn.microsoft.com/library/windows/desktop/dn903849(v=vs.85).aspx) pub fn clear_uav_u32<T: CsuHeap>( &mut self, heap: &mut T, index: u32, resource: &mut RawResource, values: &[u32; 4], rects: Option<&[::format::Rect]> ) { let (numrects, prects) = if let Some(rects) = rects { (rects.len() as u32, rects.as_ptr()) } else { (0, ::std::ptr::null()) }; unsafe { self.ptr.ClearUnorderedAccessViewFloat( heap.get_gpu_handle(index).into(), heap.get_cpu_handle(index).into(), resource.ptr.as_mut_ptr(), values.as_ptr() as *const _, numrects, prects ) } } /// record clearing a rtv pub fn clear_rtv( &mut self, rtv: CpuRtvHandle, values: &[f32; 4], rects: Option<&[::format::Rect]> ) { let (numrects, prects) = if let Some(rects) = rects { (rects.len() as u32, rects.as_ptr()) } else { (0, ::std::ptr::null()) }; unsafe { self.ptr.ClearRenderTargetView( rtv.into(), values.as_ptr() as *const _, numrects, prects ) } } /// execute a bundle. [more](https://msdn.microsoft.com/library/windows/desktop/dn903882(v=vs.85).aspx) #[inline] pub fn execute_bundle(&mut self, bundle: &Bundle) { unsafe { self.ptr.ExecuteBundle(bundle.ptr.as_mut_ptr())} } /// set the stream output buffer views #[inline] pub fn so_set_targets( &mut self, start_slot: u32, sovs: &[::pipeline::so::StreamOutputBufferView] ) { unsafe { self.ptr.SOSetTargets( start_slot, sovs.len() as u32, sovs.as_ptr() as *const _ ) } } /// set scissor rectangles #[inline] pub fn rs_set_scissors(&mut self, scissors: &[::format::Rect]) { unsafe { self.ptr.RSSetScissorRects( scissors.len() as u32, scissors.as_ptr() as *const _ ) } } /// set viewports #[inline] pub fn rs_set_viewports(&mut self, viewports: &[::format::Viewport]) { unsafe { self.ptr.RSSetViewports( viewports.len() as u32, viewports.as_ptr() as *const _ ) } } /// resolve a multisampled resource into a non-MS resource. [more](https://msdn.microsoft.com/library/windows/desktop/dn903897(v=vs.85).aspx) #[inline] pub fn resolve_ms( &mut self, dst: &mut RawResource, dst_sub: u32, src: &mut RawResource, src_sub: u32, format: ::format::DxgiFormat ) { unsafe { self.ptr.ResolveSubresource( dst.ptr.as_mut_ptr(), dst_sub, src.ptr.as_mut_ptr(), src_sub, format ) } } /// synchronizaing multiple access to resources. [more](https://msdn.microsoft.com/library/windows/desktop/dn903898(v=vs.85).aspx) pub fn resource_barriers(&mut self, barriers: &ResourceBarriersBuilder) { let barriers = barriers.as_ffi_slice(); unsafe { self.ptr.ResourceBarrier( barriers.len() as u32, barriers.as_ptr() ) } } /// reset the state of a direct command list back to the state it was in when created. /// initial_state has to match this state pub fn clear_state(&mut self) { let p_initial_state = if let Some(initial_state) = self.initial_state { initial_state.as_raw_ptr().as_mut_ptr() } else { ::std::ptr::null_mut() }; unsafe { self.ptr.ClearState(p_initial_state)} } // TODO: double check descriptor heap settings #[inline] pub fn set_descriptor_heaps<T: CsuHeap, S: SamplerHeap>( &mut self, cbv_srv_uav_heap: Option<&mut T>, sampler_heap: Option<&mut S> ) { let mut heaps = [ ::std::ptr::null_mut(), ::std::ptr::null_mut(), ]; if let Some(heap) = cbv_srv_uav_heap { heaps[1] = heap.as_raw_ptr().as_mut_ptr(); } if let Some(heap) = sampler_heap { heaps[0] = heap.as_raw_ptr().as_mut_ptr(); } unsafe { self.ptr.SetDescriptorHeaps(2, heaps.as_mut_ptr()) } } /// reset a command list back to the initial state. [more](https://msdn.microsoft.com/library/windows/desktop/dn903895(v=vs.85).aspx) pub fn reset<'b, T: PipelineState+'b>( mut self, alloc: &'b mut DirectCommandAllocator, initial_state: Option<&'b T> ) -> Result<DirectCommandListRecording<'b, T>, (WinError, Self)> { let p_initial_state = if let Some(initial_state) = initial_state { initial_state.as_raw_ptr().as_mut_ptr() } else { ::std::ptr::null_mut() }; unsafe { let result = WinError::from_hresult(self.ptr.Reset(alloc.ptr.as_mut_ptr(), p_initial_state)); if result.is_ok() { Ok(DirectCommandListRecording{ ptr: self.ptr, alloc, initial_state}) } else { Err((result.unwrap_err(), self)) } } } /// close the current recording #[inline] pub fn close(mut self) -> Result<DirectCommandList, WinError> { unsafe{ WinError::from_hresult_or_ok(self.ptr.Close(), move || DirectCommandList{ ptr: self.ptr }) } } }
//! To run this code, clone the rusty_engine repository and run the command: //! //! cargo run --release --example keyboard_state use std::f32::consts::PI; use rusty_engine::prelude::*; fn main() { let mut game = Game::new(); let mut race_car = game.add_sprite("Race Car", SpritePreset::RacingCarGreen); race_car.translation = Vec2::new(0.0, 0.0); race_car.rotation = UP; race_car.scale = 1.0; let instructions = "Smooth movement with KeyboardState Example\n====================================\nChange translation (move): w a s d / arrows\nChange Rotation: z c\nChange Scale: + -"; let text = game.add_text("instructions", instructions); text.translation.y = 250.0; game.add_logic(logic); game.run(()); } fn logic(game_state: &mut Engine, _: &mut ()) { // Compute how fast we should move, rotate, and scale let move_amount = 200.0 * game_state.delta_f32; let rotation_amount = PI * game_state.delta_f32; let scale_amount = 1.0 * game_state.delta_f32; // Get the race car sprite let race_car = game_state.sprites.get_mut("Race Car").unwrap(); // Handle keyboard input let ks = &mut game_state.keyboard_state; if ks.pressed_any(&[KeyCode::W, KeyCode::Up, KeyCode::Comma]) { race_car.translation.y += move_amount; } if ks.pressed_any(&[KeyCode::A, KeyCode::Left]) { race_car.translation.x -= move_amount; } if ks.pressed_any(&[KeyCode::S, KeyCode::Down, KeyCode::O]) { race_car.translation.y -= move_amount; } if ks.pressed_any(&[KeyCode::D, KeyCode::Right, KeyCode::E]) { race_car.translation.x += move_amount; } // If you prefer a more functional style that is equivalent to the kind of logic above, // but takes closures to run if the buttons are pressed, you can call `.chain()` ks.chain() .pressed_any(&[KeyCode::Z, KeyCode::Semicolon], |_| { race_car.rotation += rotation_amount; }) .pressed_any(&[KeyCode::C, KeyCode::J], |_| { race_car.rotation -= rotation_amount; }) .pressed_any(&[KeyCode::Plus, KeyCode::Equals], |_| { race_car.scale *= 1.0 + scale_amount; }) .pressed_any(&[KeyCode::Minus, KeyCode::Underline], |_| { race_car.scale *= 1.0 - scale_amount; }); // Clamp the scale to a certain range so the scaling is reasonable race_car.scale = race_car.scale.clamp(0.1, 3.0); // Clamp the translation so that the car stays on the screen race_car.translation = race_car.translation.clamp( -game_state.window_dimensions * 0.5, game_state.window_dimensions * 0.5, ); }
extern crate dot_vox; extern crate structopt; use structopt::StructOpt; use dot_vox::load; use gobs::cubic_surface_extractor::extract_cubic_mesh; use gobs::raw_volume::RawVolume; use gobs::raw_volume_sampler::RawVolumeSampler; use gobs::region::Region; use gobs::volume::Volume; use std::fs::File; use std::io::{self, Error, Write}; #[derive(StructOpt, Debug)] #[structopt(name = "gobs-cli")] struct Options { #[structopt(name = "vox-file")] vox_file: String, #[structopt(name = "out-file")] output: Option<String>, } impl Options { fn get_output(&self) -> Result<Box<dyn Write>, Error> { match self.output { Some(ref path) => File::create(path).map(|f| Box::new(f) as Box<dyn Write>), None => Ok(Box::new(io::stdout())), } } } fn main() -> std::io::Result<()> { let options = Options::from_args(); let mut out = options.get_output().unwrap(); let vox_file = load(&options.vox_file).unwrap(); let hex_palette = vox_file .palette .iter() .map(|rgba| { let a = (rgba >> 24) as u8; let b = (rgba >> 16) as u8; let g = (rgba >> 8) as u8; let r = *rgba as u8; format!("{{\"r\":{},\"g\":{},\"b\":{},\"a\":{}}}", r, g, b, a) }) .collect::<Vec<String>>() .join(", "); writeln!(out, "{{")?; writeln!(out, " \"palette\": [{}],", hex_palette)?; writeln!(out, " \"models\": [")?; let mut first = true; for model in vox_file.models { let region = Region::sized( model.size.x as i32, model.size.y as i32, model.size.z as i32, ); let mut volume = RawVolume::new(region); for voxel in model.voxels { volume .set_voxel_at(voxel.x as i32, voxel.y as i32, voxel.z as i32, voxel.i) .unwrap(); } let mesh = extract_cubic_mesh( &mut RawVolumeSampler::new(&volume), &volume.valid_region, None, None, ) .unwrap(); let vertices = mesh .vertices() .iter() .map(|v| { let pos = v.decode(); format!( "{{\"x\":{},\"y\":{},\"z\":{},\"c\":{}}}", pos.x, pos.y, pos.z, v.data ) }) .collect::<Vec<String>>() .join(","); let polygons = mesh .indices() .chunks(3) .map(|tri| format!("[{},{},{}]", tri[0], tri[1], tri[2])) .collect::<Vec<String>>() .join(","); if first { first = false; } else { writeln!(out, ",")?; } writeln!(out, " {{")?; writeln!(out, " \"vertices\": [{}],", vertices)?; writeln!(out, " \"polygons\": [{}]", polygons)?; write!(out, " }}")?; } writeln!(out, "\n ]")?; writeln!(out, "}}")?; Ok(()) }
impl_database_ext! { sqlx::sqlite::Sqlite { bool, i32, i64, f32, f64, String, Vec<u8>, }, ParamChecking::Weak, feature-types: _info => None, row = sqlx::sqlite::SqliteRow }
//! Curve used for interpolation (e.g. gradients) use serde_derive::{Deserialize, Serialize}; use std::fmt::Debug; pub trait CurveNode: Copy + Clone + std::ops::Mul<f32, Output = Self> + std::ops::Add<Output = Self> + Debug + std::ops::Sub<Output = Self> { } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Curve<T> where T: CurveNode, { xs: Vec<f32>, ys: Vec<T>, } impl<T> Default for Curve<T> where T: CurveNode, { fn default() -> Self { Self { xs: vec![], ys: vec![], } } } impl<T> Curve<T> where T: CurveNode, { pub fn y(&self, t: f32) -> T { // why use a curve otherwise. assert!(self.xs.len() == self.ys.len() && !self.ys.is_empty()); // First find the x corresponding to this t. (lower bound) let mut idx = 0usize; for (i, &x) in self.xs.iter().enumerate() { if x > t { break; } idx = i; } let lower_y = unsafe { *self.ys.get_unchecked(idx) }; if idx == self.ys.len() - 1 { lower_y } else { let lower_t: f32 = *unsafe { self.xs.get_unchecked(idx) }; let higher_t: f32 = *unsafe { self.xs.get_unchecked(idx + 1) }; let higher_y = unsafe { *self.ys.get_unchecked(idx + 1) }; let slope = (higher_y - lower_y) * (1.0 / (higher_t - lower_t)); let val = lower_y + slope * (t - lower_t); val } } } impl CurveNode for glam::Vec2 {} impl CurveNode for f32 {}
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Commands from linux/fcntl.h. pub const F_DUPFD : i32 = 0; pub const F_GETFD : i32 = 1; pub const F_SETFD : i32 = 2; pub const F_GETFL : i32 = 3; pub const F_SETFL : i32 = 4; pub const F_SETLK : i32 = 6; pub const F_SETLKW : i32 = 7; pub const F_SETOWN : i32 = 8; pub const F_GETOWN : i32 = 9; pub const F_SETOWN_EX : i32 = 15; pub const F_GETOWN_EX : i32 = 16; pub const F_DUPFD_CLOEXEC : i32 = 1024 + 6; pub const F_SETPIPE_SZ : i32 = 1024 + 7; pub const F_GETPIPE_SZ : i32 = 1024 + 8; // Commands for F_SETLK. pub const F_RDLCK : i32 = 0; pub const F_WRLCK : i32 = 1; pub const F_UNLCK : i32 = 2; // Flags for fcntl. pub const FD_CLOEXEC : i32 = 1; // Flock is the lock structure for F_SETLK. #[repr(C)] pub struct Flock { pub Type : i16, pub Whence : i16, pub Start : i64, pub Len : i64, pub Pid : i32, } // Flags for F_SETOWN_EX and F_GETOWN_EX. pub const F_OWNER_TID :i32 = 0; pub const F_OWNER_PID :i32 = 1; pub const F_OWNER_PGRP :i32 = 2; // FOwnerEx is the owner structure for F_SETOWN_EX and F_GETOWN_EX. #[repr(C)] #[derive(Default, Clone, Copy)] pub struct FOwnerEx { pub Type : i32, pub PID : i32, }
// Day 5 use std::error::Error; use std::fs; use std::process; fn main() { let input_filename = "input.txt"; if let Err(e) = run(input_filename) { println!("Application error: {}", e); process::exit(1); } } fn run(filename: &str) -> Result<(), Box<dyn Error>> { // Read the input file let contents = fs::read_to_string(filename)?; // Convert comma-separated string to vector of ints // let contents = "3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99"; // let contents = "3,9,7,9,10,9,4,9,99,-1,8"; let mut instruction_set: Vec<i32> = contents .trim() .split(",") .map(|x| x.parse().unwrap()) .collect(); println!("{:?}", instruction_set); let mut cursor: usize = 0; run_tape(instruction_set, cursor); Ok(()) } fn run_tape(mut memory: Vec<i32>, mut cursor: usize) -> () { loop { // Read the memory at the cursor position, and parse the opcode. println!("cursor position: {}", cursor); let instruction = Instruction::new(&mut memory, cursor); println!("{:?}", instruction); let prev_cursor = cursor; process_instruction(&mut memory, &instruction, &mut cursor); if cursor == prev_cursor { cursor += &instruction.parameters.len() + 1; // +1 to include the opcode } } } fn process_instruction(memory: &mut Vec<i32>, instruction: &Instruction, cursor: &mut usize) -> () { // match of the opcode match instruction.opcode { OpcodeKind::Add => { // parameters are [noun, verb, target] let noun_mode = instruction.modes[0]; let mut noun_value = -1; // THIS IS DANGEROUS let mut verb_value = -1; if noun_mode == 0 { // then it is position mode let noun_position = instruction.parameters[0] as usize; noun_value = memory[noun_position]; } else if noun_mode == 1 { // then it is immediate mode noun_value = instruction.parameters[0]; } else { panic!("unexpected mode") } let verb_mode = instruction.modes[1]; if verb_mode == 0 { // then it is position mode let verb_position = instruction.parameters[1] as usize; verb_value = memory[verb_position]; } else if verb_mode == 1 { // then it is immediate mode verb_value = instruction.parameters[1]; } else { panic!("unexpected mode") } let result = noun_value + verb_value; let result_position = instruction.parameters[2] as usize; memory[result_position] = result; } OpcodeKind::Multiply => { // parameters are [noun, verb, target] let noun_mode = instruction.modes[0]; let mut noun_value = -1; // THIS IS DANGEROUS let mut verb_value = -1; if noun_mode == 0 { // then it is position mode let noun_position = instruction.parameters[0] as usize; noun_value = memory[noun_position]; } else if noun_mode == 1 { // then it is immediate mode noun_value = instruction.parameters[0]; } else { panic!("unexpected mode") } let verb_mode = instruction.modes[1]; if verb_mode == 0 { // then it is position mode let verb_position = instruction.parameters[1] as usize; verb_value = memory[verb_position]; } else if verb_mode == 1 { // then it is immediate mode verb_value = instruction.parameters[1]; } else { panic!("unexpected mode") } let result = noun_value * verb_value; let result_position = instruction.parameters[2] as usize; memory[result_position] = result; } OpcodeKind::Input => { println!("Please give program input."); let mut input = String::new(); std::io::stdin() .read_line(&mut input) .expect("Failed to read input"); // Write input to the memory in position given by the parameter let position: usize = instruction.parameters[0] as usize; memory[position] = input.trim().parse().unwrap(); } OpcodeKind::Output => { let mode = instruction.modes[0]; if mode == 0 { let position: usize = instruction.parameters[0] as usize; let value = memory[position]; println!("***********Instruction output: {}", value); } else if mode == 1 { let value = instruction.parameters[0]; println!("***********Instruction output: {}", value); } } OpcodeKind::JumpIfTrue => { let mode = instruction.modes[0]; let mut condition: bool = false; if mode == 0 { let position: usize = instruction.parameters[0] as usize; condition = memory[position] != 0; } else if mode == 1 { condition = instruction.parameters[0] != 0; } if condition { if instruction.modes[1] == 0 { let position: usize = instruction.parameters[1] as usize; *cursor = memory[position] as usize; } else if instruction.modes[1] == 1 { *cursor = instruction.parameters[1] as usize; } } } OpcodeKind::JumpIfFalse => { let mode = instruction.modes[0]; let mut condition: bool = false; if mode == 0 { let position: usize = instruction.parameters[0] as usize; condition = memory[position] == 0; } else if mode == 1 { condition = instruction.parameters[0] == 0; } if condition { if instruction.modes[1] == 0 { let position: usize = instruction.parameters[1] as usize; *cursor = memory[position] as usize; } else if instruction.modes[1] == 1 { *cursor = instruction.parameters[1] as usize; } } } OpcodeKind::IsLessThan => { let noun_mode = instruction.modes[0]; let mut noun_value = -1; // THIS IS DANGEROUS let mut verb_value = -1; if noun_mode == 0 { // then it is position mode let noun_position = instruction.parameters[0] as usize; noun_value = memory[noun_position]; } else if noun_mode == 1 { // then it is immediate mode noun_value = instruction.parameters[0]; } else { panic!("unexpected mode") } let verb_mode = instruction.modes[1]; if verb_mode == 0 { // then it is position mode let verb_position = instruction.parameters[1] as usize; verb_value = memory[verb_position]; } else if verb_mode == 1 { // then it is immediate mode verb_value = instruction.parameters[1]; } else { panic!("unexpected mode") } if noun_value < verb_value { let result_position = instruction.parameters[2] as usize; memory[result_position] = 1; } else { let result_position = instruction.parameters[2] as usize; memory[result_position] = 0; } } OpcodeKind::IsEquals => { let noun_mode = instruction.modes[0]; let mut noun_value = -1; // THIS IS DANGEROUS let mut verb_value = -1; if noun_mode == 0 { // then it is position mode let noun_position = instruction.parameters[0] as usize; noun_value = memory[noun_position]; } else if noun_mode == 1 { // then it is immediate mode noun_value = instruction.parameters[0]; } else { panic!("unexpected mode") } let verb_mode = instruction.modes[1]; if verb_mode == 0 { // then it is position mode let verb_position = instruction.parameters[1] as usize; verb_value = memory[verb_position]; } else if verb_mode == 1 { // then it is immediate mode verb_value = instruction.parameters[1]; } else { panic!("unexpected mode") } if noun_value == verb_value { let result_position = instruction.parameters[2] as usize; memory[result_position] = 1; } else { let result_position = instruction.parameters[2] as usize; memory[result_position] = 0; } } OpcodeKind::Exit => { std::process::exit(0); } } } // Mapping of opcodes to instructions. // Each opcode has a name and an associated // number of instuctions #[derive(Debug, Copy, Clone)] enum OpcodeKind { Add, Multiply, Input, Output, JumpIfTrue, JumpIfFalse, IsLessThan, IsEquals, Exit, } #[derive(Debug)] struct Instruction { opcode_value: i32, opcode: OpcodeKind, modes: Vec<i32>, parameters: Vec<i32>, } impl Instruction { /* Read the opcode string. Parse the first two digits. Lookup the relevant OpcodeKind. Do stuff based on OpcodeKind. */ fn new(memory: &Vec<i32>, cursor: usize) -> Instruction { let opcode_value: i32 = memory[cursor]; let mut int_to_operation_map = std::collections::HashMap::new(); int_to_operation_map.insert(1, OpcodeKind::Add); int_to_operation_map.insert(2, OpcodeKind::Multiply); int_to_operation_map.insert(3, OpcodeKind::Input); int_to_operation_map.insert(4, OpcodeKind::Output); int_to_operation_map.insert(5, OpcodeKind::JumpIfTrue); int_to_operation_map.insert(6, OpcodeKind::JumpIfFalse); int_to_operation_map.insert(7, OpcodeKind::IsLessThan); int_to_operation_map.insert(8, OpcodeKind::IsEquals); int_to_operation_map.insert(99, OpcodeKind::Exit); // Make immutable let int_to_operation_map = int_to_operation_map; match opcode_value { 99 => { let opcode: OpcodeKind = *int_to_operation_map.get(&99).expect("Opcode not found!"); let modes: Vec<i32> = Vec::new(); let parameters: Vec<i32> = Vec::new(); return Instruction { opcode_value: opcode_value, opcode: opcode, modes: modes, parameters, }; } _ => { let mut digits = get_digits(opcode_value).into_iter().rev(); let opcode_int = digits.next().unwrap().clone(); let opcode: OpcodeKind = *int_to_operation_map .get(&opcode_int) .expect("Opcode not found!"); let zero = digits.next(); match zero { Some(0) => { let mut modes: Vec<i32> = digits.collect(); while modes.len() < 3 { modes.push(0); } let parameters: Vec<i32> = match opcode_int { 1 => vec![memory[cursor + 1], memory[cursor + 2], memory[cursor + 3]], 2 => vec![memory[cursor + 1], memory[cursor + 2], memory[cursor + 3]], 4 => vec![memory[cursor + 1]], 5 => vec![memory[cursor + 1], memory[cursor + 2]], 6 => vec![memory[cursor + 1], memory[cursor + 2]], 7 => vec![memory[cursor + 1], memory[cursor + 2], memory[cursor + 3]], 8 => vec![memory[cursor + 1], memory[cursor + 2], memory[cursor + 3]], _ => panic!("opcode not found!"), }; return Instruction { opcode_value: opcode_value, opcode: opcode, modes: modes, parameters: parameters, }; } None => { let modes: Vec<i32> = vec![0, 0, 0]; let parameters: Vec<i32> = match opcode_int { 1 => vec![memory[cursor + 1], memory[cursor + 2], memory[cursor + 3]], 2 => vec![memory[cursor + 1], memory[cursor + 2], memory[cursor + 3]], 3 => vec![memory[cursor + 1]], 4 => vec![memory[cursor + 1]], 5 => vec![memory[cursor + 1], memory[cursor + 2]], 6 => vec![memory[cursor + 1], memory[cursor + 2]], 7 => vec![memory[cursor + 1], memory[cursor + 2], memory[cursor + 3]], 8 => vec![memory[cursor + 1], memory[cursor + 2], memory[cursor + 3]], _ => panic!("opcode not found!"), }; return Instruction { opcode_value: opcode_value, opcode: opcode, modes: modes, parameters: parameters, }; } _ => { println!("{}", opcode_value); panic!("crash and burn") } } } }; } } fn get_digits(n: i32) -> Vec<i32> { fn x_inner(n: i32, xs: &mut Vec<i32>) { if n >= 10 { x_inner(n / 10, xs); } xs.push(n % 10); } let mut xs = Vec::new(); x_inner(n, &mut xs); xs }
use super::component_prelude::*; pub type CheckpointId = usize; pub struct Checkpoint { pub applied: bool, pub id: CheckpointId, pub respawn_anchor: AmethystAnchor, } impl Checkpoint { pub fn new(id: CheckpointId, respawn_anchor: AmethystAnchor) -> Self { Self { id, respawn_anchor, applied: false, } } pub fn respawn_pos( &self, pos: &Vector, size: &Size, padding: &Vector, ) -> Vector { use AmethystAnchor as AA; let half_size = (size.w * 0.5, size.h * 0.5); match self.respawn_anchor { AA::Middle => (pos.0, pos.1), AA::MiddleLeft => (pos.0 - half_size.0 + padding.0, pos.1), AA::MiddleRight => (pos.0 + half_size.0 - padding.0, pos.1), AA::TopMiddle => (pos.0, pos.1 + half_size.1 - padding.1), AA::TopLeft => ( pos.0 - half_size.0 + padding.0, pos.1 + half_size.1 - padding.1, ), AA::TopRight => ( pos.0 + half_size.0 - padding.0, pos.1 + half_size.1 - padding.1, ), AA::BottomMiddle => (pos.0, pos.1 - half_size.1 + padding.1), AA::BottomLeft => ( pos.0 - half_size.0 + padding.0, pos.1 - half_size.1 + padding.1, ), AA::BottomRight => ( pos.0 + half_size.0 - padding.0, pos.1 - half_size.1 + padding.1, ), } .into() } } impl Component for Checkpoint { type Storage = VecStorage<Self>; }
extern crate libc; extern crate unicode_normalization; use std::env::args as env_args; use std::io::Write; use std::process::exit; use std::error::Error as StdError; mod caesar; mod args; mod error; use args::Args; use error::Error; fn usage() { print!( r#" Caesar encrypter tool Encrypt options: -k, --key <key> - specifies a key to encrypting or decrypting process. The key must be a number between 1(including) and 25(including). Default: 3 -o, --output <source_file> - sets the destiny output file. Default: stdout -i, --input <destny_file> - sets the clear message source. Default: stdin -f, --force - forces decryptation (brute force) and shows all possible results. Default: not force Commands: encrypt - encrypts a message decrypt - decrypts a message Usage: caesar encrypt [-k <key>] [-i <clear_text>] [-o <cipher>] caesar decrypt [-f] [-k <key>] [-i <cipher>] [-o <clear_text>] "# ) } fn exec_command<'a>(command: String, args: &mut Args) -> Result<(), Error> { let mut text = String::new(); match (* args.input).read_to_string(&mut text) { Ok(0) => { return Err(Error{message: String::from("Empty input")}) }, Ok(_) => {}, Err(_) => { return Err(Error{message: String::from("Can't read input")}) } }; match command.as_str() { "decrypt" => { if args.force { for key in 1..26 { try!(writeln!(* args.output, "Result using key {}:", key)); try!(writeln!(* args.output, "{}", caesar::decrypt(&text, key))); } } else { try!(write!(* args.output, "{}", caesar::decrypt(&text, args.key))); try!((* args.output).flush()); } }, "encrypt" => { try!(write!(* args.output, "{}", caesar::encrypt(&text, args.key))); try!((* args.output).flush()); }, _ => { return Err(Error{message: String::from("Invalid command, type `caesar --help` for help")}) } }; Ok(()) } fn main() { let mut args = match Args::from_env_args(env_args()) { Ok(args) => args, Err(err) => { match writeln!(&mut std::io::stderr(), "Error: {}", err) { Ok(_) => {}, Err(_) => panic!("WTF!"), }; exit(1); } }; let command = match args.command { Some(ref s) => s.clone(), None => { usage(); exit(1); } }; match exec_command(command, &mut args) { Err(err) => { match writeln!(&mut std::io::stderr(), "Error: {}", err.description()) { Ok(_) => {}, Err(_) => panic!("WTF!"), }; exit(1); }, _ => {}, }; }
extern crate web_sys; extern crate virtual_filesystem; mod utils; use wasm_bindgen::prelude::*; use virtual_filesystem::virtual_filesystem::shell::{CommandError, Shell}; use virtual_filesystem::virtual_filesystem_core::logger::LoggerRepository; macro_rules! log { ( $( $t:tt )* ) => { web_sys::console::log_1(&format!( $( $t )* ).into()); } } #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; struct ConsoleLoggerRepository {} impl LoggerRepository for ConsoleLoggerRepository { fn print(&self, message: &str) { log!("{}", message); } } #[wasm_bindgen] pub struct Cli { shell: Shell<ConsoleLoggerRepository>, } #[wasm_bindgen] impl Cli { pub fn new() -> Cli { utils::set_panic_hook(); Cli { shell: Shell::init_with_logger(ConsoleLoggerRepository{}) } } pub fn run(&mut self, command: &str) -> String { match self.shell.run(command) { Ok(None) => { "".to_string() }, Ok(Some(response)) => { format!("{}", response) }, Err(CommandError::UnknownError) => { format!("unknown error.") }, Err(CommandError::NotFound) => { format!("not found.") }, Err(CommandError::IllegalArgument) => { format!("illegal argument.") }, Err(CommandError::NotFile) => { format!("not file.") }, Err(CommandError::CommandNotFound(command)) => { format!("{} command not found.", command) }, } } }
use icell::{runtime::Runtime, write_all}; #[test] fn create() { let owner = Runtime::owner(); assert_eq!(std::mem::size_of_val(&owner), 6); } #[test] #[cfg(feature = "std")] fn create_once_with_reuse() { icell::runtime_id!(type Once(());); icell::global_reuse!(type OnceReuse(Once)); type Runtime = icell::runtime::Runtime<Once, OnceReuse>; let owner = Runtime::with_counter_and_reuse(OnceReuse); assert!(Runtime::try_with_counter_and_reuse(OnceReuse).is_err()); assert_eq!(std::mem::size_of_val(&owner), 0); drop(owner); assert!(Runtime::try_with_counter_and_reuse(OnceReuse).is_ok()); } #[test] fn read() { let owner = Runtime::owner(); assert_eq!(std::mem::size_of_val(&owner), 6); let cell = owner.cell::<u32>(0xdead_beef); assert_eq!(*owner.read(&cell), 0xdead_beef); } #[test] fn write() { let mut owner = Runtime::owner(); assert_eq!(std::mem::size_of_val(&owner), 6); let cell = owner.cell::<u32>(0xdead_beef); let value = owner.write(&cell); *value = 0; assert_eq!(*owner.read(&cell), 0); } #[test] fn write_all() { let mut owner = Runtime::owner(); assert_eq!(std::mem::size_of_val(&owner), 6); let a = owner.cell::<u32>(0xdead_beef); let b = owner.cell::<u32>(0xbeef_dead); let c = owner.cell::<u32>(0xdead_baaf); let d = owner.cell::<u32>(0xdeed_beef); { let (a, b, c, d) = write_all!(owner => a, b, c, d); std::mem::swap(a, b); std::mem::swap(c, d); std::mem::swap(a, d); } let &a = owner.read(&a); let &b = owner.read(&b); let &c = owner.read(&c); let &d = owner.read(&d); assert_eq!(a, 0xdead_baaf); assert_eq!(b, 0xdead_beef); assert_eq!(c, 0xdeed_beef); assert_eq!(d, 0xbeef_dead); } #[test] #[cfg_attr(miri, ignore)] #[should_panic = "Tried to read using an unrelated owner"] fn read_unrelated() { let owner = Runtime::owner(); assert_eq!(std::mem::size_of_val(&owner), 6); let cell = owner.cell::<u32>(0xdead_beef); let owner = Runtime::owner(); assert_eq!(*owner.read(&cell), 0xdead_beef); }
pub mod physics; pub mod renderable;
#![feature( const_fn, link_llvm_intrinsics, allocator_api, naked_functions, )] extern crate nabi; #[macro_use] mod print; pub mod abi; mod types; mod handle; mod wasm; mod process; mod channel; mod event; // mod mutex; // mod dlmalloc; pub mod interrupt; pub mod driver; pub use handle::Handle; pub use wasm::Wasm; pub use process::Process; pub use channel::{Channel, WriteChannel, ReadChannel}; pub use event::Event; // pub use mutex::{Mutex, MutexGuard}; use std::fmt; pub use nabi::{Result, Error}; // #[global_allocator] // static ALLOC: dlmalloc::GlobalDlmalloc = dlmalloc::GlobalDlmalloc; pub fn print(x: &str) { unsafe { abi::print(x.as_ptr(), x.len()); } } pub struct PrintWriter; impl fmt::Write for PrintWriter { fn write_str(&mut self, s: &str) -> fmt::Result { print(s); Ok(()) } }
#![cfg_attr(not(feature = "std"), no_std)] use ink_lang as ink; pub use self::newomegastorage::NewOmegaStorage; pub use self::newomegastorage::CommanderData; pub use self::newomegastorage::PlayerData; /// Isolated storage for all things which should be considered player progress. /// This module should only ever change if a serious API change is needed, but otherwise /// it should survive most upgrades of the rest of the system, preserving the Game Board /// (state of the game) across upgrades and bugfixes. /// The only logic that belongs here is accessors for the storage. #[ink::contract] mod newomegastorage { use ink_prelude::vec::Vec; use ink_storage::{ collections::{ Vec as StorageVec, HashMap as StorageHashMap, }, traits::{ PackedLayout, SpreadLayout }, }; /// Holds the current progress of a commander #[derive(scale::Encode, scale::Decode, SpreadLayout, PackedLayout, Clone, Default, Copy, Debug, Eq, PartialEq)] #[cfg_attr( feature = "std", derive( scale_info::TypeInfo, ink_storage::traits::StorageLayout ) )] pub struct CommanderData { /// Experience points xp: u32, } /// Holds the current leaderboard standing of a player #[derive(scale::Encode, scale::Decode, SpreadLayout, PackedLayout, Clone, Default, Copy, Debug, Eq, PartialEq)] #[cfg_attr( feature = "std", derive( scale_info::TypeInfo, ink_storage::traits::StorageLayout ) )] pub struct PlayerData { /// Number of wins ranked_wins: u32, /// Number of losses ranked_losses: u32, } #[ink(storage)] pub struct NewOmegaStorage { owners: StorageVec<AccountId>, players: StorageHashMap<AccountId, PlayerData>, commanders: StorageHashMap<(AccountId, u8), CommanderData>, } impl NewOmegaStorage { #[ink(constructor)] pub fn new() -> Self { let mut owners = StorageVec::default(); owners.push(Self::env().caller()); Self { owners, players: StorageHashMap::default(), commanders: StorageHashMap::default(), } } #[ink(constructor)] pub fn default() -> Self { Self::new() } /// Clears all the contract authorisations. #[ink(message)] pub fn clear_authorisations(&mut self) { assert!(self.owners.iter().any(|owner| *owner == self.env().caller())); self.owners.clear(); self.owners.push(self.env().caller()); } /// Authorises a contract to allow it to use this contract. /// Only authorised contracts can manipulate the storage. /// /// # Arguments /// /// * `contract` - The contract address to be authorised #[ink(message)] pub fn authorise_contract(&mut self, contract: AccountId) { assert!(self.owners.iter().any(|owner| *owner == self.env().caller())); self.owners.push(contract); } /// Ensures that a player data structure is defined. /// Inserts the default if it is not. /// /// # Arguments /// /// * `caller` - The account id of the player to ensure data for fn ensure_player(&mut self, caller: AccountId) -> &mut PlayerData { self.players .entry(caller) .or_insert(PlayerData::default()) } /// Marks a ranked win for a player /// /// # Arguments /// /// * `caller` - The account id of the player to mark #[ink(message)] pub fn mark_ranked_win(&mut self, caller: AccountId) { assert!(self.owners.iter().any(|owner| *owner == self.env().caller())); let player_data = self.ensure_player(caller); player_data.ranked_wins = player_data.ranked_wins + 1; } /// Marks a ranked loss for a player /// /// # Arguments /// /// * `caller` - The account id of the player to mark #[ink(message)] pub fn mark_ranked_loss(&mut self, caller: AccountId) { assert!(self.owners.iter().any(|owner| *owner == self.env().caller())); let player_data = self.ensure_player(caller); player_data.ranked_losses = player_data.ranked_losses + 1; } /// Adds Experience Points to a player's commander /// /// # Arguments /// /// * `caller` - The account id of the player to mark /// * `commander_id` - The id of commander to increase XP for /// * `amount` - The amount of XP to increase #[ink(message)] pub fn add_commander_xp(&mut self, caller: AccountId, commander_id: u8, amount: u32) { assert!(self.owners.iter().any(|owner| *owner == self.env().caller())); self.commanders .entry((caller, commander_id)) .or_insert(CommanderData::default()).xp += amount; } /// Gets all the owned commanders for a player. /// /// # Arguments /// /// * `caller` - The account id of the player to get commanders for /// /// # Returns /// /// * `commanders` - A Vec containing a tuple of (commander id, commander data) #[ink(message)] pub fn get_commanders(&self, caller: AccountId) -> Vec<(u8, CommanderData)> { self.commanders .iter() .filter_map(|entry| { let (&key, &value) = entry; let (account, commander_id) = key; if account == caller { Some((commander_id, value)) } else { None } }) .collect() } /// Checks whether a player owns a commander. /// /// # Arguments /// /// * `caller` - The account id of the player to get commanders for /// * `commander_id` - The id of the commander to check for /// /// # Returns /// /// * `has_commander` - Whether player owns the commander #[ink(message)] pub fn has_commander(&self, caller: AccountId, commander_id: u8) -> bool { self.commanders.contains_key(&(caller, commander_id)) } /// Gets the current ranked leaderboard. /// /// # Returns /// /// * `leaderboard` - A Vec containing a tuple of (player account id, player data) #[ink(message)] pub fn get_leaderboard(&self) -> Vec<(AccountId, PlayerData)> { self.players .iter() .filter_map(|entry| { let (&key, &value) = entry; Some((key, value)) }) .collect() } } #[cfg(test)] mod tests { use super::*; use ink_env::{ test, }; use ink_lang as ink; type Accounts = test::DefaultAccounts<Environment>; fn default_accounts() -> Accounts { test::default_accounts() .expect("Test environment is expected to be initialized.") } #[ink::test] fn test_ranked_marking() { let mut contract = NewOmegaStorage::default(); let accounts = default_accounts(); contract.mark_ranked_win(accounts.alice); contract.mark_ranked_loss(accounts.bob); let leaderboard: Vec<(AccountId, PlayerData)> = contract.get_leaderboard(); assert_eq!(leaderboard.len(), 2); assert_eq!(leaderboard[0].1.ranked_wins, 1); assert_eq!(leaderboard[0].1.ranked_losses, 0); assert_eq!(leaderboard[1].1.ranked_wins, 0); assert_eq!(leaderboard[1].1.ranked_losses, 1); } #[ink::test] fn test_commanders() { let mut contract = NewOmegaStorage::default(); let accounts = default_accounts(); contract.add_commander_xp(accounts.alice, 0, 100); contract.add_commander_xp(accounts.bob, 1, 50); let commanders_alice: Vec<(u8, CommanderData)> = contract.get_commanders(accounts.alice); let commanders_bob: Vec<(u8, CommanderData)> = contract.get_commanders(accounts.bob); let commanders_eve: Vec<(u8, CommanderData)> = contract.get_commanders(accounts.eve); assert_eq!(commanders_alice.len(), 1); assert_eq!(commanders_bob.len(), 1); assert_eq!(commanders_eve.len(), 0); let (commander_index_alice, commander_data_alice) = commanders_alice[0]; assert_eq!(commander_index_alice, 0); assert_eq!(commander_data_alice.xp, 100); let (commander_index_bob, commander_data_bob) = commanders_bob[0]; assert_eq!(commander_index_bob, 1); assert_eq!(commander_data_bob.xp, 50); } } }
use binary_search::BinarySearch; use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let m: usize = rd.get(); let a: Vec<i32> = rd.get_vec(n); let mut b: Vec<i32> = rd.get_vec(m); let mut ans = (a[0] - b[0]).abs(); b.sort(); for x in a { let j = b.lower_bound(&x); if let Some(&y) = b.get(j) { ans = ans.min((x - y).abs()); } if j >= 1 { if let Some(&y) = b.get(j - 1) { ans = ans.min((x - y).abs()); } } } println!("{}", ans); }
/// An enumeration of different triplet feels. #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum TripletFeel { None, Eighth, Sixteenth } pub(crate) fn get_triplet_feel(value: i8) -> TripletFeel { match value { 0 => TripletFeel::None, 1 => TripletFeel::Eighth, 2 => TripletFeel::Sixteenth, _ => panic!("Invalid triplet feel"), } } pub(crate) fn from_triplet_feel(value: &TripletFeel) -> u8 { match value { TripletFeel::None => 0, TripletFeel::Eighth => 1, TripletFeel::Sixteenth => 2, } } /// An enumeration of available clefs #[allow(dead_code)] #[repr(u8)] #[derive(Debug,Clone)] pub enum MeasureClef { Treble, Bass, Tenor, Alto } /// A line break directive: `NONE: no line break`, `BREAK: break line`, `Protect the line from breaking`. #[repr(u8)] #[derive(Debug,Clone)] pub enum LineBreak { None, Break, Protect } pub(crate) fn get_line_break(value: u8) -> LineBreak { match value { 1 => LineBreak::Break, 2 => LineBreak::Protect, _ => LineBreak::None, } } pub(crate) fn from_line_break(value: &LineBreak) -> u8 { match value { LineBreak::None => 0, LineBreak::Break => 1, LineBreak::Protect => 2, } } /// An enumeration of all supported slide types. #[repr(i8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum SlideType { IntoFromAbove = -2, //-2 IntoFromBelow = -1, //-1 None = 0, //0 ShiftSlideTo, LegatoSlideTo, OutDownwards, OutUpWards } pub(crate) fn get_slide_type(value: i8) -> SlideType { match value { -2 => SlideType::IntoFromAbove, -1 => SlideType::IntoFromBelow, 0 => SlideType::None, 1 => SlideType::ShiftSlideTo, 2 => SlideType::LegatoSlideTo, 3 => SlideType::OutDownwards, 4 => SlideType::OutUpWards, _ => panic!("Invalid slide type"), } } pub(crate) fn from_slide_type(value: &SlideType) -> i8 { match value { SlideType::IntoFromAbove => -2, SlideType::IntoFromBelow => -1, SlideType::None => 0, SlideType::ShiftSlideTo => 1, SlideType::LegatoSlideTo => 2, SlideType::OutDownwards => 3, SlideType::OutUpWards => 4, } } /// An enumeration of all supported slide types. #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum NoteType { Rest, //0 Normal, Tie, Dead, Unknown(u8), } pub(crate) fn get_note_type(value: u8) -> NoteType { match value { 0 => NoteType::Rest, 1 => NoteType::Normal, 2 => NoteType::Tie, 3 => NoteType::Dead, _ => NoteType::Unknown(value), //panic!("Cannot read note type"), } } pub(crate) fn from_note_type(value: &NoteType) -> u8 { match value { NoteType::Rest => 0, NoteType::Normal => 1, NoteType::Tie => 2, NoteType::Dead => 3, NoteType::Unknown(value) => *value, //panic!("Cannot read note type"), } } #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum BeatStatus {Empty, Normal, Rest} pub(crate) fn get_beat_status(value: u8) -> BeatStatus { match value { 0 => BeatStatus::Empty, 1 => BeatStatus::Normal, 2 => BeatStatus::Rest, _ => BeatStatus::Normal, //panic!("Cannot get beat status"), } } pub(crate) fn from_beat_status(value: &BeatStatus) -> u8 { match value { BeatStatus::Empty => 0, BeatStatus::Normal => 1, BeatStatus::Rest => 2, } } #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum TupletBracket {None, Start, End} /// Octave signs #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum Octave { None, Ottava, Quindicesima, OttavaBassa, QuindicesimaBassa } pub(crate) fn get_octave(value: u8) -> Octave { match value { 0 => Octave::None, 1 => Octave::Ottava, 2 => Octave::Quindicesima, 3 => Octave::OttavaBassa, 4 => Octave::QuindicesimaBassa, _ => panic!("Cannot get octave value"), } } pub(crate) fn from_octave(value: &Octave) -> u8 { match value { Octave::None => 0, Octave::Ottava => 1, Octave::Quindicesima => 2, Octave::OttavaBassa => 3, Octave::QuindicesimaBassa => 4, } } /// All beat stroke directions #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum BeatStrokeDirection { None, Up, Down } pub(crate) fn get_beat_stroke_direction(value: i8) -> BeatStrokeDirection { match value { 0 => BeatStrokeDirection::None, 1 => BeatStrokeDirection::Up, 2 => BeatStrokeDirection::Down, _ => panic!("Cannot read beat stroke direction"), } } pub(crate) fn from_beat_stroke_direction(value: &BeatStrokeDirection) -> i8 { match value { BeatStrokeDirection::None => 0, BeatStrokeDirection::Up => 1, BeatStrokeDirection::Down => 2, } } /// Characteristic of articulation #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum SlapEffect { None, Tapping, Slapping, Popping } pub(crate) fn get_slap_effect(value: u8) -> SlapEffect { match value { 0 => SlapEffect::None, 1 => SlapEffect::Tapping, 2 => SlapEffect::Slapping, 3 => SlapEffect::Popping, _ => panic!("Cannot read slap effect for the beat effects"), } } pub(crate) fn from_slap_effect(value: &SlapEffect) -> u8 { match value { SlapEffect::None => 0, SlapEffect::Tapping => 1, SlapEffect::Slapping => 2, SlapEffect::Popping => 3, } } /// Voice directions indicating the direction of beams #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum VoiceDirection { None, Up, Down } /// Type of the chord. #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum ChordType { /// Major chord. Major, /// Dominant seventh chord. Seventh, /// Major seventh chord. MajorSeventh, /// Add sixth chord. Sixth, /// Minor chord. Minor, /// Minor seventh chord. MinorSeventh, /// Minor major seventh chord. MinorMajor, /// Minor add sixth chord. MinorSixth, /// Suspended second chord. SuspendedSecond, /// Suspended fourth chord. SuspendedFourth, /// Seventh suspended second chord. SeventhSuspendedSecond, /// Seventh suspended fourth chord. SeventhSuspendedFourth, /// Diminished chord. Diminished, /// Augmented chord. Augmented, /// Power chord. Power, Unknown(u8), } pub(crate) fn get_chord_type(value: u8) -> ChordType { match value { 0 => ChordType::Major, 1 => ChordType::Seventh, 2 => ChordType::MajorSeventh, 3 => ChordType::Sixth, 4 => ChordType::Minor, 5 => ChordType::MinorSeventh, 6 => ChordType::MinorMajor, 7 => ChordType::MinorSixth, 8 => ChordType::SuspendedSecond, 9 => ChordType::SuspendedFourth, 10 => ChordType::SeventhSuspendedSecond, 11 => ChordType::SeventhSuspendedFourth, 12 => ChordType::Diminished, 13 => ChordType::Augmented, 14 => ChordType::Power, _ => ChordType::Unknown(value), //panic!("Cannot read chord type (new format)"), } } pub(crate) fn from_chord_type(value: &ChordType) -> u8 { match value { ChordType::Major => 0, ChordType::Seventh => 1, ChordType::MajorSeventh => 2, ChordType::Sixth => 3, ChordType::Minor => 4, ChordType::MinorSeventh => 5, ChordType::MinorMajor => 6, ChordType::MinorSixth => 7, ChordType::SuspendedSecond => 8, ChordType::SuspendedFourth => 9, ChordType::SeventhSuspendedSecond => 10, ChordType::SeventhSuspendedFourth => 11, ChordType::Diminished => 12, ChordType::Augmented => 13, ChordType::Power => 14, ChordType::Unknown(value) => *value, } } /// Tonality of the chord #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum ChordAlteration { /// Perfect. Perfect, /// Diminished. Diminished, /// Augmented. Augmented, } pub(crate) fn get_chord_alteration(value: u8) -> ChordAlteration { match value { 0 => ChordAlteration::Perfect, 1 => ChordAlteration::Diminished, 2 => ChordAlteration::Augmented, _ => panic!("Cannot read chord fifth (new format)"), } } pub(crate) fn from_chord_alteration(value: &ChordAlteration) -> u8 { match value { ChordAlteration::Perfect => 0, ChordAlteration::Diminished => 1, ChordAlteration::Augmented => 2, } } /// Extension type of the chord #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum ChordExtension { None, /// Ninth chord. Ninth, /// Eleventh chord. Eleventh, /// Thirteenth chord. Thirteenth, Unknown(u8) } pub(crate) fn get_chord_extension(value: u8) -> ChordExtension { match value { 0 => ChordExtension::None, 1 => ChordExtension::Ninth, 2 => ChordExtension::Eleventh, 3 => ChordExtension::Thirteenth, _ => ChordExtension::Unknown(value), //panic!("Cannot read chord type (new format)"), } } pub(crate) fn from_chord_extension(value: &ChordExtension) -> u8 { match value { ChordExtension::None => 0, ChordExtension::Ninth => 1, ChordExtension::Eleventh => 2, ChordExtension::Thirteenth => 3, ChordExtension::Unknown(value) => *value, //panic!("Cannot read chord type (new format)"), } } /// Left and right hand fingering used in tabs and chord diagram editor. #[repr(i8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum Fingering { /// Open or muted. Open = -1, //-1? /// Thumb. Thumb = 0, /// Index finger. Index, /// Middle finger. Middle, /// Annular finger. Annular, /// Little finger. Little, Unknown(i8), } pub(crate) fn get_fingering(value: i8) -> Fingering { match value { -1 => Fingering::Open, 0 => Fingering::Thumb, 1 => Fingering::Index, 2 => Fingering::Middle, 3 => Fingering::Annular, 4 => Fingering::Little, _ => Fingering::Unknown(value), //panic!("Cannot get fingering! How can you have more than 5 fingers per hand?!?"), } } pub(crate) fn from_fingering(value: &Fingering) -> i8 { match value { Fingering::Open => -1, Fingering::Thumb => 0, Fingering::Index => 1, Fingering::Middle => 2, Fingering::Annular => 3, Fingering::Little => 4, Fingering::Unknown(value) => *value, //panic!("Cannot get fingering! How can you have more than 5 fingers per hand?!?"), } } /// All Bend presets #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum BendType { /// No Preset. None, //Bends /// A simple bend. Bend, /// A bend and release afterwards. BendRelease, /// A bend, then release and rebend. BendReleaseBend, /// Prebend. Prebend, /// Prebend and then release. PrebendRelease, //Tremolo Bar /// Dip the bar down and then back up. Dip, /// Dive the bar. Dive, /// Release the bar up. ReleaseUp, /// Dip the bar up and then back down. InvertedDip, /// Return the bar. Return, /// Release the bar down. ReleaseDown } pub(crate) fn get_bend_type(value: i8) -> BendType { match value { 0 => BendType::None, 1 => BendType::Bend, 2 => BendType::BendRelease, 3 => BendType::BendReleaseBend, 4 => BendType::Prebend, 5 => BendType::PrebendRelease, 6 => BendType::Dip, 7 => BendType::Dive, 8 => BendType::ReleaseUp, 9 => BendType::InvertedDip, 10 => BendType::Return, 11 => BendType::ReleaseDown, _ => panic!("Cannot read bend type"), } } pub(crate) fn from_bend_type(value: &BendType) -> i8 { match value { BendType::None => 0, BendType::Bend => 1, BendType::BendRelease => 2, BendType::BendReleaseBend => 3, BendType::Prebend => 4, BendType::PrebendRelease => 5, BendType::Dip => 6, BendType::Dive => 7, BendType::ReleaseUp => 8, BendType::InvertedDip => 9, BendType::Return => 10, BendType::ReleaseDown => 11, } } /// All transition types for grace notes. #[repr(i8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum GraceEffectTransition { ///No transition None = 0, ///Slide from the grace note to the real one. Slide, ///Perform a bend from the grace note to the real one. Bend, ///Perform a hammer on. Hammer } pub(crate) fn get_grace_effect_transition(value: i8) -> GraceEffectTransition { match value { 0 => GraceEffectTransition::None, 1 => GraceEffectTransition::Slide, 2 => GraceEffectTransition::Bend, 3 => GraceEffectTransition::Hammer, _ => panic!("Cannot get transition for the grace effect"), } } pub(crate) fn from_grace_effect_transition(value: &GraceEffectTransition) -> i8 { match value { GraceEffectTransition::None => 0, GraceEffectTransition::Slide => 1, GraceEffectTransition::Bend => 2, GraceEffectTransition::Hammer => 3, } } #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq)] pub enum HarmonicType { Natural = 1, //1 Artificial, Tapped, Pinch, Semi, //5 } pub(crate) fn from_harmonic_type(value: &HarmonicType) -> i8 { match value { HarmonicType::Natural => 1, HarmonicType::Artificial => 2, HarmonicType::Tapped => 3, HarmonicType::Pinch => 4, HarmonicType::Semi => 5, } } /// Values of auto-accentuation on the beat found in track RSE settings #[repr(u8)] #[derive(Debug,Clone)] pub enum Accentuation { None, VerySoft, Soft, Medium, Strong, VeryStrong } pub(crate) fn get_accentuation(value: u8) -> Accentuation { match value { 0 => Accentuation::None, 1 => Accentuation::VerySoft, 2 => Accentuation::Soft, 3 => Accentuation::Medium, 4 => Accentuation::Strong, 5 => Accentuation::VeryStrong, _ => panic!("Cannot get accentuation"), } } pub(crate) fn from_accentuation(value: &Accentuation) -> u8 { match value { Accentuation::None => 0, Accentuation::VerySoft => 1, Accentuation::Soft => 2, Accentuation::Medium => 3, Accentuation::Strong => 4, Accentuation::VeryStrong => 5, } } /// A navigation sign like *Coda* (𝄌: U+1D10C) or *Segno* (𝄋 or 𝄉: U+1D10B or U+1D109). #[repr(u8)] #[derive(Debug,Clone,PartialEq,Eq,Hash)] pub enum DirectionSign { Coda, DoubleCoda, Segno, SegnoSegno, Fine, DaCapo, DaCapoAlCoda, DaCapoAlDoubleCoda, DaCapoAlFine, DaSegno, DaSegnoAlCoda, DaSegnoAlDoubleCoda, DaSegnoAlFine, DaSegnoSegno, DaSegnoSegnoAlCoda, DaSegnoSegnoAlDoubleCoda, DaSegnoSegnoAlFine, DaCoda, DaDoubleCoda, }
// This file is Copyright its original authors, visible in version control // history. // // This file is 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. // You may not use this file except in accordance with one or both of these // licenses. use senseicore::hex_utils; use std::{ fs::File, io::{self, Read}, }; use clap::{Arg, Command}; use sensei::GetBalanceRequest; use sensei::{admin_client::AdminClient, node_client::NodeClient}; use tonic::{metadata::MetadataValue, transport::Channel, Request}; use crate::sensei::{ CloseChannelRequest, ConnectPeerRequest, CreateAdminRequest, CreateInvoiceRequest, CreateNodeRequest, GetUnusedAddressRequest, InfoRequest, KeysendRequest, ListChannelsRequest, ListNodesRequest, ListPaymentsRequest, ListPeersRequest, ListUnspentRequest, NetworkGraphInfoRequest, OpenChannelRequest, OpenChannelsRequest, PayInvoiceRequest, SignMessageRequest, StartNodeRequest, }; pub mod sensei { tonic::include_proto!("sensei"); } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let matches = Command::new("senseicli") .version("1.0") .author("John Cantrell <john@l2.technology>") .about("Control your sensei node from a cli") .arg( Arg::new("datadir") .short('d') .long("datadir") .value_name("DATADIR") .help("Sets a custom Sensei data directory") .takes_value(true), ) .arg( Arg::new("node") .short('n') .long("node") .value_name("NODE") .help("Sets the node to issue commands to") .takes_value(true), ) .subcommand( Command::new("init") .about("initialize your Sensei node") .arg( Arg::new("username") .required(true) .index(1) .help("username for the root lightning node"), ) .arg( Arg::new("alias") .required(true) .index(2) .help("alias used for the root lightning node"), ), ) .subcommand(Command::new("start").about("unlock and start your sensei node")) .subcommand(Command::new("listnodes").about("list all the lightning nodes")) .subcommand( Command::new("createnode") .about("create a new child node") .arg( Arg::new("username") .required(true) .index(1) .help("username to use for this lightning node"), ) .arg( Arg::new("alias") .required(true) .index(2) .help("alias to use for this lightning node"), ), ) .subcommand(Command::new("startnode").about("start a child lightning node")) .subcommand(Command::new("getbalance").about("gets wallet's balance")) .subcommand(Command::new("getaddress").about("get wallet's next unused address")) .subcommand( Command::new("createinvoice") .about("create an invoice for an amount in msats") .arg( Arg::new("amt_msat") .required(true) .index(1) .help("amount in msats"), ), ) .subcommand( Command::new("openchannel") .about("open a channel with another node") .arg( Arg::new("node_connection_string") .required(true) .index(1) .help("connection string formatted pubkey@host:port"), ) .arg( Arg::new("amt_satoshis") .required(true) .index(2) .help("how many satoshis to put into this channel"), ) .arg( Arg::new("public") .index(3) .takes_value(true) .long("public") .possible_values(&["true", "false"]) .required(true) .help("announce this channel to the network?"), ), ) .subcommand( Command::new("closechannel") .about("close a channel") .arg( Arg::new("channel_id") .required(true) .index(1) .help("the id of the channel"), ) .arg( Arg::new("force") .index(2) .takes_value(true) .long("force") .possible_values(&["true", "false"]) .required(true) .help("force close this channel?"), ), ) .subcommand( Command::new("payinvoice").about("pay an invoice").arg( Arg::new("invoice") .required(true) .index(1) .help("bolt11 invoice"), ), ) .subcommand( Command::new("keysend") .about("send a payment to a public key") .arg( Arg::new("dest_pubkey") .required(true) .index(1) .help("destination public key to send payment to"), ) .arg( Arg::new("amt_msat") .required(true) .index(2) .help("amount of millisatoshis to pay"), ), ) .subcommand( Command::new("connectpeer") .about("connect to a peer on the lightning network") .arg( Arg::new("node_connection_string") .required(true) .index(1) .help("peer's connection string formatted pubkey@host:port"), ), ) .subcommand( Command::new("signmessage") .about("sign a message with your nodes key") .arg( Arg::new("message") .required(true) .index(1) .help("the message to be signed"), ), ) .subcommand(Command::new("listchannels").about("list channels")) .subcommand(Command::new("listpayments").about("list payments")) .subcommand(Command::new("listpeers").about("list peers")) .subcommand(Command::new("nodeinfo").about("see information about your node")) .get_matches(); let (command, command_args) = matches.subcommand().unwrap(); if command == "init" { let channel = Channel::from_static("http://0.0.0.0:3000") .connect() .await?; let mut admin_client = AdminClient::new(channel); let username = command_args.value_of("username").unwrap(); let mut passphrase = String::new(); print!("set a passphrase: "); io::stdin().read_line(&mut passphrase)?; let request = tonic::Request::new(CreateAdminRequest { username: username.to_string(), passphrase, }); let response = admin_client.create_admin(request).await?; println!("{:?}", response.into_inner()); } else { let data_dir = matches.value_of("datadir").unwrap_or("./.sensei"); let node = matches.value_of("node").unwrap_or("admin"); let macaroon_path = format!("{}/{}/.ldk/admin.macaroon", data_dir, node); println!("macaroon path: {:?}", macaroon_path); let mut macaroon_file = File::open(macaroon_path)?; let mut macaroon_raw = Vec::new(); let _bytes = macaroon_file.read_to_end(&mut macaroon_raw)?; let macaroon_hex_str = hex_utils::hex_str(&macaroon_raw); let channel = Channel::from_static("http://0.0.0.0:3000") .connect() .await?; let macaroon = MetadataValue::from_str(&macaroon_hex_str)?; let admin_macaroon = macaroon.clone(); let mut client = NodeClient::with_interceptor(channel, move |mut req: Request<()>| { req.metadata_mut().insert("macaroon", macaroon.clone()); Ok(req) }); let admin_channel = Channel::from_static("http://0.0.0.0:3000") .connect() .await?; let mut admin_client = AdminClient::with_interceptor(admin_channel, move |mut req: Request<()>| { req.metadata_mut() .insert("macaroon", admin_macaroon.clone()); Ok(req) }); match command { "listnodes" => { let request = tonic::Request::new(ListNodesRequest { pagination: None }); let response = admin_client.list_nodes(request).await?; println!("{:?}", response.into_inner()); } "createnode" => { let username = command_args.value_of("username").unwrap(); let alias = command_args.value_of("alias").unwrap(); let mut passphrase = String::new(); println!("set a passphrase: "); io::stdin().read_line(&mut passphrase)?; let request = tonic::Request::new(CreateNodeRequest { username: username.to_string(), alias: alias.to_string(), passphrase, start: false, entropy: None, cross_node_entropy: None, }); let response = admin_client.create_node(request).await?; println!("{:?}", response.into_inner()); } "startnode" => { let mut passphrase = String::new(); println!("enter your passphrase: "); io::stdin().read_line(&mut passphrase)?; let request = tonic::Request::new(StartNodeRequest { passphrase }); let response = client.start_node(request).await?; println!("{:?}", response.into_inner()); } "getbalance" => { let request = tonic::Request::new(GetBalanceRequest {}); let response = client.get_balance(request).await?; println!("{:?}", response.into_inner()); } "getaddress" => { let request = tonic::Request::new(GetUnusedAddressRequest {}); let response = client.get_unused_address(request).await?; println!("{:?}", response.into_inner()); } "createinvoice" => { let amt_msat: Option<Result<u64, _>> = command_args .value_of("amt_msat") .map(|str_amt| str_amt.parse()); match amt_msat { Some(amt_msat) => { if let Ok(amt_msat) = amt_msat { let request = tonic::Request::new(CreateInvoiceRequest { amt_msat, description: String::from(""), }); let response = client.create_invoice(request).await?; println!("{:?}", response.into_inner()); } else { println!("invalid amount, please specify in msats"); } } None => { println!("amt_msat is required to create an invoice"); } } } "openchannel" => { let args = command_args; let amt_satoshis: u64 = args .value_of("amt_satoshis") .expect("amt_satoshis is required field") .parse() .expect("amount must be in satoshis"); let node_connection_string = args .value_of("node_connection_string") .expect("node_connection_string required"); let public: bool = args .value_of("public") .expect("public field required") .parse() .expect("public must be true or false"); let mut split = node_connection_string.split('@'); let pubkey = split.next().expect("you must provide pubkey@host:port"); let host_and_port = split.next().unwrap(); let request = tonic::Request::new(OpenChannelsRequest { requests: vec![OpenChannelRequest { counterparty_pubkey: pubkey.to_string(), amount_sats: amt_satoshis, public, scid_alias: None, push_amount_msats: None, custom_id: None, counterparty_host_port: Some(host_and_port.to_string()), forwarding_fee_proportional_millionths: None, forwarding_fee_base_msat: None, cltv_expiry_delta: None, max_dust_htlc_exposure_msat: None, force_close_avoidance_max_fee_satoshis: None, }], }); let response = client.open_channels(request).await?; println!("{:?}", response.into_inner()); } "closechannel" => { let args = command_args; let channel_id = args.value_of("channel_id").expect("channel_id required"); let force: bool = args .value_of("force") .expect("force field required") .parse() .expect("force must be true or false"); let request = tonic::Request::new(CloseChannelRequest { channel_id: channel_id.to_string(), force, }); let response = client.close_channel(request).await?; println!("{:?}", response.into_inner()); } "payinvoice" => { let args = command_args; let invoice = args.value_of("invoice").expect("invoice required"); let request = tonic::Request::new(PayInvoiceRequest { invoice: invoice.to_string(), }); let response = client.pay_invoice(request).await?; println!("{:?}", response.into_inner()); } "keysend" => { let args = command_args; let dest_pubkey = args.value_of("dest_pubkey").expect("dest_pubkey required"); let amt_msat: u64 = args .value_of("amt_msat") .expect("amt_msat is required field") .parse() .expect("amount must be in millisatoshis"); let request = tonic::Request::new(KeysendRequest { dest_pubkey: dest_pubkey.to_string(), amt_msat, }); let response = client.keysend(request).await?; println!("{:?}", response.into_inner()); } "connectpeer" => { let args = command_args; let node_connection_string = args .value_of("node_connection_string") .expect("node_connection_string required"); let request = tonic::Request::new(ConnectPeerRequest { node_connection_string: node_connection_string.to_string(), }); let response = client.connect_peer(request).await?; println!("{:?}", response.into_inner()); } "signmessage" => { let args = command_args; let message = args.value_of("message").expect("message required"); let request = tonic::Request::new(SignMessageRequest { message: message.to_string(), }); let response = client.sign_message(request).await?; println!("{:?}", response.into_inner()); } "listchannels" => { let request = tonic::Request::new(ListChannelsRequest { pagination: None }); let response = client.list_channels(request).await?; println!("{:?}", response.into_inner()); } "listpayments" => { let request = tonic::Request::new(ListPaymentsRequest { pagination: None, filter: None, }); let response = client.list_payments(request).await?; println!("{:?}", response.into_inner()); } "listpeers" => { let request = tonic::Request::new(ListPeersRequest {}); let response = client.list_peers(request).await?; println!("{:?}", response.into_inner()); } "listunspent" => { let request = tonic::Request::new(ListUnspentRequest {}); let response = client.list_unspent(request).await?; println!("{:?}", response.into_inner()); } "networkgraphinfo" => { let request = tonic::Request::new(NetworkGraphInfoRequest {}); let response = client.network_graph_info(request).await?; println!("{:?}", response.into_inner()); } "nodeinfo" => { let request = tonic::Request::new(InfoRequest {}); let response = client.info(request).await?; println!("{:?}", response.into_inner()); } _ => { println!("invalid command. use senseicli --help to see usage instructions.") } } } Ok(()) }
pub mod evaluator; pub mod cutoff; pub mod input; pub mod maximum; pub mod panic; pub mod sensor; pub mod smooth; pub mod step; pub use input::cutoff::Cutoff; pub use input::input::Input; pub use input::maximum::Maximum; pub use input::sensor::SensorInput; pub use input::panic::Panic; pub use input::smooth::Smooth; pub use input::step::{ Step, Steps };
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use x86_64::structures::paging::{PageTable}; use x86_64::structures::paging::page_table::PageTableEntry; use x86_64::structures::paging::page_table::PageTableIndex; use x86_64::PhysAddr; use x86_64::VirtAddr; use x86_64::structures::paging::PageTableFlags; use alloc::alloc::{Layout, alloc, dealloc}; use alloc::vec::Vec; use core::sync::atomic::AtomicU64; use core::sync::atomic::Ordering; use super::common::{Error, Result, Allocator}; use super::addr::*; use super::linux_def::*; use super::mem::stackvec::*; use super::super::asm::*; #[derive(Default)] pub struct PageTables { //Root page guest physical address pub root: AtomicU64, } impl PageTables { pub fn New(pagePool: &Allocator) -> Result<Self> { let root = pagePool.AllocPage(true)?; Ok(Self { root: AtomicU64::new(root) }) } pub fn Clone(&self) -> Self { return Self { root: AtomicU64::new(self.GetRoot()) } } pub fn Init(root: u64) -> Self { return Self { root: AtomicU64::new(root) } } pub fn SwitchTo(&self) { let addr = self.GetRoot(); Self::Switch(addr); } pub fn IsActivePagetable(&self) -> bool { let root = self.GetRoot(); return root == Self::CurrentCr3() } pub fn CurrentCr3() -> u64 { return CurrentCr3() } //switch pagetable for the cpu, Cr3 pub fn Switch(cr3: u64) { //unsafe { llvm_asm!("mov $0, %cr3" : : "r" (cr3) ) }; LoadCr3(cr3) } pub fn SetRoot(&self, root: u64) { self.root.store(root, Ordering::Release) } pub fn GetRoot(&self) -> u64 { return self.root.load(Ordering::Acquire) } pub fn SwapZero(&self) -> u64 { return self.root.swap(0, Ordering::Acquire) } pub fn Print(&self) { //let cr3 : u64; //unsafe { llvm_asm!("mov %cr3, $0" : "=r" (cr3) ) }; let cr3 = CurrentCr3(); info!("the page root is {:x}, the cr3 is {:x}", self.GetRoot(), cr3); } pub fn CopyRange(&self, to: &Self, start: u64, len: u64, pagePool: &Allocator) -> Result<()> { if start & MemoryDef::PAGE_MASK != 0 || len & MemoryDef::PAGE_MASK != 0 { return Err(Error::UnallignedAddress); } let mut vAddr = start; while vAddr < start + len { match self.VirtualToEntry(vAddr) { Ok(entry) => { let phyAddr = entry.addr().as_u64(); to.MapPage(Addr(vAddr), Addr(phyAddr), entry.flags(), pagePool)?; } Err(_) => () } vAddr += MemoryDef::PAGE_SIZE; } Ok(()) } // Copy the range and make the range readonly for from and to pagetable. It is used for VirtualArea private area. // The Copy On Write will be done when write to the page pub fn ForkRange(&self, to: &Self, start: u64, len: u64, pagePool: &Allocator) -> Result<()> { if start & MemoryDef::PAGE_MASK != 0 || len & MemoryDef::PAGE_MASK != 0 { return Err(Error::UnallignedAddress); } //change to read only //todo: there is chance the orignal range is changed to readonly by mprotected before. Need to handle. let _ = self.MProtect(Addr(start), Addr(start + len), PageOpts::UserReadOnly().Val(), false);//there won't be any failure let mut vAddr = start; while vAddr < start + len { match self.VirtualToEntry(vAddr) { Ok(entry) => { let phyAddr = entry.addr().as_u64(); to.MapPage(Addr(vAddr), Addr(phyAddr), PageOpts::UserReadOnly().Val(), pagePool)?; } Err(_) => () } vAddr += MemoryDef::PAGE_SIZE; } Ok(()) } pub fn PrintPath(&self, vaddr: u64) { let vaddr = VirtAddr::new(vaddr); let p4Idx = vaddr.p4_index(); let p3Idx = vaddr.p3_index(); let p2Idx = vaddr.p2_index(); let p1Idx = vaddr.p1_index(); let pt: *mut PageTable = self.GetRoot() as *mut PageTable; unsafe { info!("pt1: {:x}", self.GetRoot()); let pgdEntry = &(*pt)[p4Idx]; if pgdEntry.is_unused() { return; } let pudTbl = pgdEntry.addr().as_u64() as *const PageTable; info!("pt2: {:x}", pgdEntry.addr().as_u64()); let pudEntry = &(*pudTbl)[p3Idx]; if pudEntry.is_unused() { return; } let pmdTbl = pudEntry.addr().as_u64() as *const PageTable; info!("pt3: {:x}", pudEntry.addr().as_u64()); let pmdEntry = &(*pmdTbl)[p2Idx]; if pmdEntry.is_unused() { return; } let pteTbl = pmdEntry.addr().as_u64() as *const PageTable; info!("pt4: {:x}", pmdEntry.addr().as_u64()); let pteEntry = &(*pteTbl)[p1Idx]; if pteEntry.is_unused() { return; } } } #[inline] pub fn VirtualToEntry(&self, vaddr: u64) -> Result<&PageTableEntry> { let addr = vaddr; let vaddr = VirtAddr::new(vaddr); let p4Idx = vaddr.p4_index(); let p3Idx = vaddr.p3_index(); let p2Idx = vaddr.p2_index(); let p1Idx = vaddr.p1_index(); let pt: *mut PageTable = self.GetRoot() as *mut PageTable; unsafe { let pgdEntry = &(*pt)[p4Idx]; if pgdEntry.is_unused() { return Err(Error::AddressNotMap(addr)) } let pudTbl = pgdEntry.addr().as_u64() as *const PageTable; let pudEntry = &(*pudTbl)[p3Idx]; if pudEntry.is_unused() { return Err(Error::AddressNotMap(addr)) } let pmdTbl = pudEntry.addr().as_u64() as *const PageTable; let pmdEntry = &(*pmdTbl)[p2Idx]; if pmdEntry.is_unused() { return Err(Error::AddressNotMap(addr)) } let pteTbl = pmdEntry.addr().as_u64() as *const PageTable; let pteEntry = &(*pteTbl)[p1Idx]; if pteEntry.is_unused() { return Err(Error::AddressNotMap(addr)) } return Ok(pteEntry); } } pub fn VirtualToPhy(&self, vaddr: u64) -> Result<(u64, AccessType)> { let pteEntry = self.VirtualToEntry(vaddr)?; if pteEntry.is_unused() { return Err(Error::AddressNotMap(vaddr)) } let vaddr = VirtAddr::new(vaddr); let pageAddr: u64 = vaddr.page_offset().into(); let phyAddr = pteEntry.addr().as_u64() + pageAddr; let permission = AccessType::NewFromPageFlags(pteEntry.flags()); return Ok((phyAddr, permission)) } pub fn PrintPageFlags(&self, vaddr: u64) -> Result<()> { let pteEntry = self.VirtualToEntry(vaddr)?; if pteEntry.is_unused() { return Err(Error::AddressNotMap(vaddr)) } info!("Flags is {:x?}", pteEntry); return Ok(()) } pub fn MapVsyscall(&self, phyAddrs: &[u64]/*4 pages*/) { let vaddr = 0xffffffffff600000; let pt: *mut PageTable = self.GetRoot() as *mut PageTable; unsafe { let p4Idx = VirtAddr::new(vaddr).p4_index(); let pgdEntry = &mut (*pt)[p4Idx]; let pudTbl: *mut PageTable; assert!(pgdEntry.is_unused()); pudTbl = phyAddrs[3] as *mut PageTable; pgdEntry.set_addr(PhysAddr::new(pudTbl as u64), PageTableFlags::PRESENT | PageTableFlags::USER_ACCESSIBLE); Invlpg(vaddr); } } pub fn MapPage(&self, vaddr: Addr, phyAddr: Addr, flags: PageTableFlags, pagePool: &Allocator) -> Result<bool> { let mut res = false; let vaddr = Addr(vaddr.0 & !(PAGE_SIZE - 1)); let pt: *mut PageTable = self.GetRoot() as *mut PageTable; unsafe { let p4Idx = VirtAddr::new(vaddr.0).p4_index(); let p3Idx = VirtAddr::new(vaddr.0).p3_index(); let p2Idx = VirtAddr::new(vaddr.0).p2_index(); let p1Idx = VirtAddr::new(vaddr.0).p1_index(); let pgdEntry = &mut (*pt)[p4Idx]; let pudTbl: *mut PageTable; if pgdEntry.is_unused() { pudTbl = pagePool.AllocPage(true)? as *mut PageTable; pgdEntry.set_addr(PhysAddr::new(pudTbl as u64), PageTableFlags::PRESENT | PageTableFlags::WRITABLE | PageTableFlags::USER_ACCESSIBLE); } else { pudTbl = pgdEntry.addr().as_u64() as *mut PageTable; } let pudEntry = &mut (*pudTbl)[p3Idx]; let pmdTbl: *mut PageTable; if pudEntry.is_unused() { pmdTbl = pagePool.AllocPage(true)? as *mut PageTable; pudEntry.set_addr(PhysAddr::new(pmdTbl as u64), PageTableFlags::PRESENT | PageTableFlags::WRITABLE | PageTableFlags::USER_ACCESSIBLE); } else { pmdTbl = pudEntry.addr().as_u64() as *mut PageTable; } let pmdEntry = &mut (*pmdTbl)[p2Idx]; let pteTbl: *mut PageTable; if pmdEntry.is_unused() { pteTbl = pagePool.AllocPage(true)? as *mut PageTable; pmdEntry.set_addr(PhysAddr::new(pteTbl as u64), PageTableFlags::PRESENT | PageTableFlags::WRITABLE | PageTableFlags::USER_ACCESSIBLE); } else { pteTbl = pmdEntry.addr().as_u64() as *mut PageTable; } let pteEntry = &mut (*pteTbl)[p1Idx]; pagePool.Ref(phyAddr.0).unwrap(); if !pteEntry.is_unused() { Self::freeEntry(pteEntry, pagePool)?; /*let addr = pteEntry.addr().as_u64(); let bit9 = pteEntry.flags() & PageTableFlags::BIT_9 == PageTableFlags::BIT_9; if vaddr.0 != 0 && !bit9 { pagePool.Deref(addr).unwrap(); }*/ res = true; Invlpg(vaddr.0); } pteEntry.set_addr(PhysAddr::new(phyAddr.0), flags); Invlpg(vaddr.0); } return Ok(res); } pub fn Remap(&self, start: Addr, end: Addr, oldStart: Addr, flags: PageTableFlags, pagePool: &Allocator) -> Result<bool> { start.PageAligned()?; oldStart.PageAligned()?; if end.0 < start.0 { return Err(Error::AddressNotInRange); } let mut addrs = Vec::new(); let mut offset = 0; while start.0 + offset < end.0 { let entry = self.VirtualToEntry(oldStart.0 + offset); match entry { Ok(oldentry) => { let phyAddr = oldentry.addr().as_u64(); addrs.push(Some(phyAddr)); pagePool.Ref(phyAddr).unwrap(); self.Unmap(oldStart.0 + offset, oldStart.0 + offset + MemoryDef::PAGE_SIZE, pagePool)?; } Err(_) => { addrs.push(None); } } offset += MemoryDef::PAGE_SIZE; } let mut offset = 0; let mut idx = 0; while start.0 + offset < end.0 { match addrs[idx] { Some(phyAddr) => { self.MapPage(Addr(start.0+offset), Addr(phyAddr), flags, pagePool)?; pagePool.Deref(phyAddr).unwrap(); } None =>() } offset += MemoryDef::PAGE_SIZE; idx += 1; } return Ok(false) } pub fn RemapForFile(&self, start: Addr, end: Addr, physical: Addr, oldStart: Addr, oldEnd: Addr, flags: PageTableFlags, pagePool: &Allocator) -> Result<bool> { start.PageAligned()?; oldStart.PageAligned()?; if end.0 < start.0 { return Err(Error::AddressNotInRange); } /*let mut addrs = Vec::new(); let mut offset = 0; while start.0 + offset < end.0 { let entry = self.VirtualToEntry(oldStart.0 + offset); match entry { Ok(oldentry) => { let phyAddr = oldentry.addr().as_u64(); addrs.push(Some(phyAddr)); pagePool.Ref(phyAddr).unwrap(); self.Unmap(oldStart.0 + offset, oldStart.0 + offset + MemoryDef::PAGE_SIZE, pagePool)?; } Err(_) => { addrs.push(None); } } offset += MemoryDef::PAGE_SIZE; }*/ // todo: handle overlap... let mut offset = 0; 'a: while start.0 + offset < end.0 { if oldStart.0 + offset < oldEnd.0 { let entry = self.VirtualToEntry(oldStart.0 + offset); match entry { Ok(oldentry) => { let phyAddr = oldentry.addr().as_u64(); self.MapPage(Addr(start.0+offset), Addr(phyAddr), flags, pagePool)?; self.Unmap(oldStart.0 + offset, oldStart.0 + offset + MemoryDef::PAGE_SIZE, pagePool)?; offset += MemoryDef::PAGE_SIZE; continue 'a; } Err(_) =>() } } let targetPhyAddr = physical.0 + offset; self.MapPage(Addr(start.0 + offset), Addr(targetPhyAddr), flags, pagePool)?; offset += MemoryDef::PAGE_SIZE; } return Ok(false) } pub fn MapWith1G(&self, start: Addr, end: Addr, physical: Addr, flags: PageTableFlags, pagePool: &Allocator, _kernel: bool) -> Result<bool> { if start.0 & (MemoryDef::HUGE_PAGE_SIZE_1G - 1) != 0 || end.0 & (MemoryDef::HUGE_PAGE_SIZE_1G - 1) != 0 { panic!("start/end address not 1G aligned") } let mut res = false; let mut curAddr = start; let pt: *mut PageTable = self.GetRoot() as *mut PageTable; unsafe { let mut p4Idx = VirtAddr::new(curAddr.0).p4_index(); let mut p3Idx = VirtAddr::new(curAddr.0).p3_index(); while curAddr.0 < end.0 { let pgdEntry = &mut (*pt)[p4Idx]; let pudTbl: *mut PageTable; if pgdEntry.is_unused() { pudTbl = pagePool.AllocPage(true)? as *mut PageTable; pgdEntry.set_addr(PhysAddr::new(pudTbl as u64), PageTableFlags::PRESENT | PageTableFlags::WRITABLE | PageTableFlags::USER_ACCESSIBLE); } else { pudTbl = pgdEntry.addr().as_u64() as *mut PageTable; } while curAddr.0 < end.0 { let pudEntry = &mut (*pudTbl)[p3Idx]; let newphysAddr = curAddr.0 - start.0 + physical.0; // Question: if we also do this for kernel, do we still need this? if !pudEntry.is_unused() { res = Self::freeEntry(pudEntry, pagePool)?; } pudEntry.set_addr(PhysAddr::new(newphysAddr), flags | PageTableFlags::HUGE_PAGE); curAddr = curAddr.AddLen(MemoryDef::HUGE_PAGE_SIZE_1G)?; if p3Idx == PageTableIndex::new(MemoryDef::ENTRY_COUNT - 1) { p3Idx = PageTableIndex::new(0); break; } else { p3Idx = PageTableIndex::new(u16::from(p3Idx) + 1); } } p4Idx = PageTableIndex::new(u16::from(p4Idx) + 1); } } return Ok(res); } //return true when there is previous mapping in the range pub fn Map(&self, start: Addr, end: Addr, physical: Addr, flags: PageTableFlags, pagePool: &Allocator, kernel: bool) -> Result<bool> { start.PageAligned()?; end.PageAligned()?; if end.0 < start.0 { return Err(Error::AddressNotInRange); } if start.0 < MemoryDef::LOWER_TOP { if end.0 <= MemoryDef::LOWER_TOP { return self.mapCanonical(start, end, physical, flags, pagePool, kernel) } else if end.0 > MemoryDef::LOWER_TOP && end.0 <= MemoryDef::UPPER_BOTTOM { return self.mapCanonical(start, Addr(MemoryDef::LOWER_TOP), physical, flags, pagePool, kernel) } else { return self.mapCanonical(start, Addr(MemoryDef::LOWER_TOP), physical, flags, pagePool, kernel) //todo: check the physical address //self.mapCanonical(UPPER_BOTTOM, end, physical, opts) } } else if start.0 < MemoryDef::UPPER_BOTTOM { if end.0 > MemoryDef::UPPER_BOTTOM { return self.mapCanonical(Addr(MemoryDef::UPPER_BOTTOM), end, physical, flags, pagePool, kernel) } } else { return self.mapCanonical(start, end, physical, flags, pagePool, kernel) } return Ok(false); } pub fn UnmapNext(start: u64, size: u64) -> u64 { let mut start = start; start &= !(size - 1); start += size; return start; } pub fn Unmap(&self, start: u64, end: u64, pagePool: &Allocator) -> Result<()> { Addr(start).PageAligned()?; Addr(end).PageAligned()?; let mut start = start; let pt: *mut PageTable = self.GetRoot() as *mut PageTable; unsafe { let mut p4Idx : u16 = VirtAddr::new(start).p4_index().into(); while start < end && p4Idx < MemoryDef::ENTRY_COUNT { let pgdEntry : &mut PageTableEntry = &mut (*pt)[PageTableIndex::new(p4Idx)]; if pgdEntry.is_unused() { start = Self::UnmapNext(start, MemoryDef::PGD_SIZE); p4Idx += 1; continue; } let pudTbl = pgdEntry.addr().as_u64() as *mut PageTable; let mut clearPUDEntries = 0; let mut p3Idx : u16 = VirtAddr::new(start).p3_index().into(); while p3Idx < MemoryDef::ENTRY_COUNT && start < end { let pudEntry : &mut PageTableEntry = &mut (*pudTbl)[PageTableIndex::new(p3Idx)]; if pudEntry.is_unused() { clearPUDEntries += 1; start = Self::UnmapNext(start, MemoryDef::PUD_SIZE); p3Idx += 1; continue; } let pmdTbl = pudEntry.addr().as_u64() as *mut PageTable; let mut clearPMDEntries = 0; let mut p2Idx : u16 = VirtAddr::new(start).p2_index().into(); while p2Idx < MemoryDef::ENTRY_COUNT && start < end { let pmdEntry : &mut PageTableEntry = &mut (*pmdTbl)[PageTableIndex::new(p2Idx)]; if pmdEntry.is_unused() { clearPMDEntries += 1; start = Self::UnmapNext(start, MemoryDef::PMD_SIZE); p2Idx += 1; continue; } let pteTbl = pmdEntry.addr().as_u64() as *mut PageTable; let mut clearPTEEntries = 0; let mut p1Idx : u16 = VirtAddr::new(start).p1_index().into(); while p1Idx < MemoryDef::ENTRY_COUNT && start < end { let pteEntry : &mut PageTableEntry = &mut (*pteTbl)[PageTableIndex::new(p1Idx)]; clearPTEEntries += 1; if pteEntry.is_unused() { start += MemoryDef::PAGE_SIZE; p1Idx += 1; continue; } match Self::freeEntry(pteEntry, pagePool) { Err(_e) => { //info!("pagetable::Unmap Error: paddr {:x}, vaddr is {:x}, error is {:x?}", // pteEntry.addr().as_u64(), start, e); } Ok(_) => (), } Invlpg(start); start += MemoryDef::PAGE_SIZE; p1Idx += 1; } if clearPTEEntries == MemoryDef::ENTRY_COUNT { let currAddr = pmdEntry.addr().as_u64(); let _refCnt = pagePool.Deref(currAddr)?; pmdEntry.set_unused(); clearPMDEntries += 1; //info!("unmap pmdEntry {:x}", currAddr); } p2Idx += 1; } if clearPMDEntries == MemoryDef::ENTRY_COUNT { let currAddr = pudEntry.addr().as_u64(); pagePool.Deref(currAddr)?; pudEntry.set_unused(); clearPUDEntries += 1; //info!("unmap pudEntry {:x}", currAddr); } p3Idx += 1; } if clearPUDEntries == MemoryDef::ENTRY_COUNT { let currAddr = pgdEntry.addr().as_u64(); pagePool.Deref(currAddr)?; pgdEntry.set_unused(); //info!("unmap pgdEntry {:x}", currAddr); } p4Idx += 1; } } return Ok(()) } pub fn ToVirtualAddr(p4Idx: PageTableIndex, p3Idx: PageTableIndex, p2Idx: PageTableIndex, p1Idx: PageTableIndex) -> Addr { let p4Idx = u64::from(p4Idx); let p3Idx = u64::from(p3Idx); let p2Idx = u64::from(p2Idx); let p1Idx = u64::from(p1Idx); let addr = (p4Idx << MemoryDef::PGD_SHIFT) + (p3Idx << MemoryDef::PUD_SHIFT) + (p2Idx << MemoryDef::PMD_SHIFT) + (p1Idx << MemoryDef::PTE_SHIFT); return Addr(addr) } pub fn Traverse(&self, start: Addr, end: Addr, mut f: impl FnMut(&mut PageTableEntry, u64), failFast: bool) -> Result<()> { start.PageAligned()?; end.PageAligned()?; //let mut curAddr = start; let pt: *mut PageTable = self.GetRoot() as *mut PageTable; unsafe { let mut p4Idx = VirtAddr::new(start.0).p4_index(); let mut p3Idx = VirtAddr::new(start.0).p3_index(); let mut p2Idx = VirtAddr::new(start.0).p2_index(); let mut p1Idx = VirtAddr::new(start.0).p1_index(); while Self::ToVirtualAddr(p4Idx, p3Idx, p2Idx, p1Idx).0 < end.0 { let pgdEntry = &mut (*pt)[p4Idx]; let pudTbl: *mut PageTable; if pgdEntry.is_unused() { if failFast { return Err(Error::AddressNotMap(Self::ToVirtualAddr(p4Idx, p3Idx, p2Idx, p1Idx).0)); } p4Idx = PageTableIndex::new(u16::from(p4Idx) + 1); p3Idx = PageTableIndex::new(0); p2Idx = PageTableIndex::new(0); p1Idx = PageTableIndex::new(0); continue; } else { pudTbl = pgdEntry.addr().as_u64() as *mut PageTable; } while Self::ToVirtualAddr(p4Idx, p3Idx, p2Idx, p1Idx).0 < end.0 { let pudEntry = &mut (*pudTbl)[p3Idx]; let pmdTbl: *mut PageTable; if pudEntry.is_unused() { if failFast { return Err(Error::AddressNotMap(Self::ToVirtualAddr(p4Idx, p3Idx, p2Idx, p1Idx).0)); } if p3Idx == PageTableIndex::new(MemoryDef::ENTRY_COUNT - 1) { p3Idx = PageTableIndex::new(0); break; } else { p3Idx = PageTableIndex::new(u16::from(p3Idx) + 1); } p2Idx = PageTableIndex::new(0); p1Idx = PageTableIndex::new(0); continue; } else { pmdTbl = pudEntry.addr().as_u64() as *mut PageTable; } while Self::ToVirtualAddr(p4Idx, p3Idx, p2Idx, p1Idx).0 < end.0 { let pmdEntry = &mut (*pmdTbl)[p2Idx]; let pteTbl: *mut PageTable; if pmdEntry.is_unused() { if failFast { return Err(Error::AddressNotMap(Self::ToVirtualAddr(p4Idx, p3Idx, p2Idx, p1Idx).0)); } if p2Idx == PageTableIndex::new(MemoryDef::ENTRY_COUNT - 1) { p2Idx = PageTableIndex::new(0); break; } else { p2Idx = PageTableIndex::new(u16::from(p2Idx) + 1); } p1Idx = PageTableIndex::new(0); continue; } else { pteTbl = pmdEntry.addr().as_u64() as *mut PageTable; } while Self::ToVirtualAddr(p4Idx, p3Idx, p2Idx, p1Idx).0 < end.0 { let pteEntry = &mut (*pteTbl)[p1Idx]; if pteEntry.is_unused() { if failFast { return Err(Error::AddressNotMap(Self::ToVirtualAddr(p4Idx, p3Idx, p2Idx, p1Idx).0)); } } else { f(pteEntry, Self::ToVirtualAddr(p4Idx, p3Idx, p2Idx, p1Idx).0); } if p1Idx == PageTableIndex::new(MemoryDef::ENTRY_COUNT - 1) { p1Idx = PageTableIndex::new(0); break; } else { p1Idx = PageTableIndex::new(u16::from(p1Idx) + 1); } } if p2Idx == PageTableIndex::new(MemoryDef::ENTRY_COUNT - 1) { p2Idx = PageTableIndex::new(0); break; } else { p2Idx = PageTableIndex::new(u16::from(p2Idx) + 1); } } if p3Idx == PageTableIndex::new(MemoryDef::ENTRY_COUNT - 1) { p3Idx = PageTableIndex::new(0); break; } else { p3Idx = PageTableIndex::new(u16::from(p3Idx) + 1); } } p4Idx = PageTableIndex::new(u16::from(p4Idx) + 1); } } return Ok(()); } pub fn SetPageFlags(&self, addr: Addr, flags: PageTableFlags) { //self.MProtect(addr, addr.AddLen(4096).unwrap(), PageTableFlags::PRESENT | PageTableFlags::WRITABLE | PageTableFlags::USER_ACCESSIBLE, false).unwrap(); self.MProtect(addr, addr.AddLen(MemoryDef::PAGE_SIZE).unwrap(), flags, true).unwrap(); } pub fn CheckZeroPage(pageStart: u64) { use alloc::slice; unsafe { let arr = slice::from_raw_parts_mut(pageStart as *mut u64, 512); for i in 0..512 { if arr[i] != 0 { panic!("alloc non zero page {:x}", pageStart); } } } } pub fn MProtect(&self, start: Addr, end: Addr, flags: PageTableFlags, failFast: bool) -> Result<()> { //info!("MProtoc: start={:x}, end={:x}, flag = {:?}", start.0, end.0, flags); return self.Traverse(start, end, |entry, virtualAddr| { entry.set_flags(flags); Invlpg(virtualAddr); }, failFast) } //get the list for page phyaddress for a virtual address range pub fn GetAddresses(&self, start: Addr, end: Addr, vec: &mut StackVec<u64>) -> Result<()> { self.Traverse(start, end, |entry, _virtualAddr| { let addr = entry.addr().as_u64(); vec.Push(addr); }, true)?; return Ok(()) } fn freeEntry(entry: &mut PageTableEntry, pagePool: &Allocator) -> Result<bool> { let currAddr = entry.addr().as_u64(); pagePool.Deref(currAddr)?; entry.set_unused(); return Ok(true) } // if kernel == true, don't need to reference in the pagePool fn mapCanonical(&self, start: Addr, end: Addr, phyAddr: Addr, flags: PageTableFlags, pagePool: &Allocator, kernel: bool) -> Result<bool> { let mut res = false; //info!("mapCanonical virtual start is {:x}, len is {:x}, phystart is {:x}", start.0, end.0 - start.0, phyAddr.0); let mut curAddr = start; let pt: *mut PageTable = self.GetRoot() as *mut PageTable; unsafe { let mut p4Idx = VirtAddr::new(curAddr.0).p4_index(); let mut p3Idx = VirtAddr::new(curAddr.0).p3_index(); let mut p2Idx = VirtAddr::new(curAddr.0).p2_index(); let mut p1Idx = VirtAddr::new(curAddr.0).p1_index(); while curAddr.0 < end.0 { let pgdEntry = &mut (*pt)[p4Idx]; let pudTbl: *mut PageTable; if pgdEntry.is_unused() { pudTbl = pagePool.AllocPage(true)? as *mut PageTable; pgdEntry.set_addr(PhysAddr::new(pudTbl as u64), PageTableFlags::PRESENT | PageTableFlags::WRITABLE | PageTableFlags::USER_ACCESSIBLE); } else { pudTbl = pgdEntry.addr().as_u64() as *mut PageTable; } while curAddr.0 < end.0 { let pudEntry = &mut (*pudTbl)[p3Idx]; let pmdTbl: *mut PageTable; if pudEntry.is_unused() { pmdTbl = pagePool.AllocPage(true)? as *mut PageTable; pudEntry.set_addr(PhysAddr::new(pmdTbl as u64), PageTableFlags::PRESENT | PageTableFlags::WRITABLE | PageTableFlags::USER_ACCESSIBLE); } else { pmdTbl = pudEntry.addr().as_u64() as *mut PageTable; } while curAddr.0 < end.0 { let pmdEntry = &mut (*pmdTbl)[p2Idx]; let pteTbl: *mut PageTable; if pmdEntry.is_unused() { pteTbl = pagePool.AllocPage(true)? as *mut PageTable; pmdEntry.set_addr(PhysAddr::new(pteTbl as u64), PageTableFlags::PRESENT | PageTableFlags::WRITABLE | PageTableFlags::USER_ACCESSIBLE); } else { pteTbl = pmdEntry.addr().as_u64() as *mut PageTable; } while curAddr.0 < end.0 { let pteEntry = &mut (*pteTbl)[p1Idx]; let newAddr = curAddr.0 - start.0 + phyAddr.0; if !kernel { pagePool.Ref(newAddr)?; } if !pteEntry.is_unused() { /*let bit9 = pteEntry.flags() & PageTableFlags::BIT_9 == PageTableFlags::BIT_9; if !bit9 { res = true; let currAddr = pteEntry.addr().as_u64(); pagePool.Deref(currAddr)?; pteEntry.set_flags(PageTableFlags::PRESENT | PageTableFlags::BIT_9); }*/ res = Self::freeEntry(pteEntry, pagePool)?; Invlpg(curAddr.0); } //info!("set addr: vaddr is {:x}, paddr is {:x}, flags is {:b}", curAddr.0, phyAddr.0, flags.bits()); pteEntry.set_addr(PhysAddr::new(newAddr), flags); Invlpg(curAddr.0); curAddr = curAddr.AddLen(MemoryDef::PAGE_SIZE_4K)?; if p1Idx == PageTableIndex::new(MemoryDef::ENTRY_COUNT - 1) { p1Idx = PageTableIndex::new(0); break; } else { p1Idx = PageTableIndex::new(u16::from(p1Idx) + 1); } } if p2Idx == PageTableIndex::new(MemoryDef::ENTRY_COUNT - 1) { p2Idx = PageTableIndex::new(0); break; } else { p2Idx = PageTableIndex::new(u16::from(p2Idx) + 1); } } if p3Idx == PageTableIndex::new(MemoryDef::ENTRY_COUNT - 1) { p3Idx = PageTableIndex::new(0); break; } else { p3Idx = PageTableIndex::new(u16::from(p3Idx) + 1); } } p4Idx = PageTableIndex::new(u16::from(p4Idx) + 1); } } return Ok(res); } } pub struct PageBufAllocator { pub buf: Vec<u64>, pub allocator: AlignedAllocator, } impl PageBufAllocator { pub fn New() -> Self { return Self { buf: Vec::with_capacity(4096 * 16), allocator: AlignedAllocator::New(MemoryDef::PAGE_SIZE as usize, MemoryDef::PAGE_SIZE as usize), } } pub fn Allocate(&mut self) -> Result<u64> { match self.buf.pop() { None => return self.allocator.Allocate(), Some(addr) => return Ok(addr) } } pub fn Free(&mut self, addr: u64) -> Result<()> { if self.buf.len() < 4096 * 16 { self.buf.push(addr); return Ok(()) } return self.allocator.Free(addr); } } pub struct AlignedAllocator { pub size: usize, pub align: usize, } impl AlignedAllocator { pub fn New(size: usize, align: usize) -> Self { return Self { size: size, align: align, } } pub fn Allocate(&self) -> Result<u64> { let layout = Layout::from_size_align(self.size, self.align); match layout { Err(_e) => Err(Error::UnallignedAddress), Ok(l) => unsafe { let addr = alloc(l); Ok(addr as u64) } } } pub fn Free(&self, addr: u64) -> Result<()> { let layout = Layout::from_size_align(self.size, self.align); match layout { Err(_e) => Err(Error::UnallignedAddress), Ok(l) => unsafe { dealloc(addr as *mut u8, l); Ok(()) } } } } #[cfg(test1)] mod tests { use super::*; use super::super::buddyallocator::*; use alloc::vec::Vec; #[repr(align(4096))] #[derive(Clone)] struct Page { data: [u64; 512] } impl Default for Page { fn default() -> Self { return Page { data: [0; 512] }; } } #[test] fn test_MapPage() { let mem: Vec<Page> = vec![Default::default(); 256]; //256 Pages let mut allocator = MemAllocator::Init(&mem[0] as *const _ as u64, 8); //2^8 let mut pt = PageTables::New(&Allocator).unwrap(); let phyAddr = 6 * 4096; pt.MapPage(Addr(0), Addr(phyAddr), PageOpts::UserReadOnly().Val(), &Allocator).unwrap(); let res = pt.VirtualToPhy(0).unwrap(); assert_eq!(res, phyAddr); } #[test] fn test_Map() { let mem: Vec<Page> = vec![Default::default(); 256]; //256 Pages let mut allocator = MemAllocator::Init(&mem[0] as *const _ as u64, 8); //2^8 let mut pt = PageTables::New(&Allocator).unwrap(); pt.Map(Addr(4096 * 500), Addr(4096 * 600), Addr(4096 * 550), PageOpts::UserReadOnly().Val(), &Allocator).unwrap(); for i in 500..600 { let vAddr = i * 4096; let pAddr = pt.VirtualToPhy(vAddr).unwrap(); assert_eq!(vAddr + 50 * 4096, pAddr); } } #[test] fn test_KernelPage() { let mem: Vec<Page> = vec![Default::default(); 1024]; //256 Pages let mut allocator = MemAllocator::Init(&mem[0] as *const _ as u64, 10); //2^10 let mut pt = PageTables::New(&Allocator).unwrap(); pt.InitKernel(&Allocator).unwrap(); let nPt = pt.NewWithKernelPageTables(&Allocator).unwrap(); assert_eq!(pt.VirtualToPhy(0).unwrap(), nPt.VirtualToPhy(0).unwrap()); } #[test] fn test_CopyRange() { let mem: Vec<Page> = vec![Default::default(); 256]; //256 Pages let mut allocator = MemAllocator::Init(&mem[0] as *const _ as u64, 8); //2^8 let mut pt = PageTables::New(&Allocator).unwrap(); pt.Map(Addr(4096 * 500), Addr(4096 * 600), Addr(4096 * 550), PageOpts::UserReadOnly().Val(), &Allocator).unwrap(); let mut nPt = PageTables::New(&Allocator).unwrap(); pt.CopyRange(&mut nPt, 4096 * 500, 4096 * 100, &Allocator).unwrap(); for i in 500..600 { let vAddr = i * 4096; let pAddr = nPt.VirtualToPhy(vAddr).unwrap(); assert_eq!(vAddr + 50 * 4096, pAddr); } } #[test] fn test_ForkRange() { let mem: Vec<Page> = vec![Default::default(); 256]; //256 Pages let mut allocator = MemAllocator::Init(&mem[0] as *const _ as u64, 8); //2^8 let mut pt = PageTables::New(&Allocator).unwrap(); pt.Map(Addr(4096 * 400), Addr(4096 * 600), Addr(4096 * 450), PageOpts::UserReadWrite().Val(), &Allocator).unwrap(); let mut nPt = PageTables::New(&Allocator).unwrap(); pt.ForkRange(&mut nPt, 4096 * 500, 4096 * 100, &Allocator).unwrap(); //pt.MProtect(Addr(4096 * 500), Addr(4096 * 600), PageOpts::UserReadOnly().Val(), true).unwrap(); for i in 500..600 { let vAddr = i * 4096; let pAddr = nPt.VirtualToPhy(vAddr).unwrap(); assert_eq!(vAddr + 50 * 4096, pAddr); assert_eq!(pt.VirtualToEntry(vAddr).unwrap().flags(), PageOpts::UserReadOnly().Val()); assert_eq!(nPt.VirtualToEntry(vAddr).unwrap().flags(), PageOpts::UserReadOnly().Val()); } for i in 400..500 { let vAddr = i * 4096; assert_eq!(pt.VirtualToEntry(vAddr).unwrap().flags(), PageOpts::UserReadWrite().Val()); } } }
use super::context::Context; use crate::graphql_schema::resolver::{Member, Team}; mod members; mod teams; pub struct QueryRoot; #[juniper::object(Context = Context)] impl QueryRoot { fn members(context: &Context) -> Vec<Member> { QueryRoot::members_impl(context) } fn teams(context: &Context) -> Vec<Team> { QueryRoot::teams_impl(context) } }
macro_rules! number_infix_operator { ($left:ident, $right:ident, $process:ident, $checked:ident, $infix:tt) => {{ use anyhow::*; use num_bigint::BigInt; use liblumen_alloc::erts::exception::*; use liblumen_alloc::erts::process::trace::Trace; use liblumen_alloc::erts::term::prelude::*; use crate::number::Operands::*; let operands = match ($left.decode().unwrap(), $right.decode().unwrap()) { (TypedTerm::SmallInteger(left_small_integer), TypedTerm::SmallInteger(right_small_integer)) => { let left_isize = left_small_integer.into(); let right_isize = right_small_integer.into(); ISizes(left_isize, right_isize) } (TypedTerm::SmallInteger(left_small_integer), TypedTerm::BigInteger(right_big_integer)) => { let left_big_int: BigInt = left_small_integer.into(); let right_big_int: &BigInt = right_big_integer.as_ref().into(); BigInts(left_big_int, right_big_int.clone()) } (TypedTerm::SmallInteger(left_small_integer), TypedTerm::Float(right_float)) => { let left_f64: f64 = left_small_integer.into(); let right_f64 = right_float.into(); Floats(left_f64, right_f64) } (TypedTerm::BigInteger(left_big_integer), TypedTerm::SmallInteger(right_small_integer)) => { let left_big_int: &BigInt = left_big_integer.as_ref().into(); let right_big_int: BigInt = right_small_integer.into(); BigInts(left_big_int.clone(), right_big_int) } (TypedTerm::Float(left_float), TypedTerm::SmallInteger(right_small_integer)) => { let left_f64 = left_float.into(); let right_f64: f64 = right_small_integer.into(); Floats(left_f64, right_f64) } (TypedTerm::BigInteger(left_big_integer), TypedTerm::BigInteger(right_big_integer)) => { let left_big_int: &BigInt = left_big_integer.as_ref().into(); let right_big_int: &BigInt = right_big_integer.as_ref().into(); BigInts(left_big_int.clone(), right_big_int.clone()) } (TypedTerm::BigInteger(left_big_integer), TypedTerm::Float(right_float)) => { let left_f64: f64 = left_big_integer.into(); let right_f64 = right_float.into(); Floats(left_f64, right_f64) } (TypedTerm::Float(left_float), TypedTerm::BigInteger(right_big_integer)) => { let left_f64 = left_float.into(); let right_f64: f64 = right_big_integer.into(); Floats(left_f64, right_f64) } (TypedTerm::Float(left_float), TypedTerm::Float(right_float)) => { let left_f64 = left_float.into(); let right_f64 = right_float.into(); Floats(left_f64, right_f64) } _ => Bad }; match operands { Bad => Err( badarith( Trace::capture(), Some( anyhow!( "{} ({}) and {} ({}) aren't both numbers", stringify!($left), $left, stringify!($right), $right ).into() ) ).into() ), ISizes(left_isize, right_isize) => { match left_isize.$checked(right_isize) { Some(sum_isize) => Ok($process.integer(sum_isize)), None => { let left_big_int: BigInt = left_isize.into(); let right_big_int: BigInt = right_isize.into(); let sum_big_int = left_big_int $infix right_big_int; let sum_term = $process.integer(sum_big_int); Ok(sum_term) } } } Floats(left, right) => { let output = left $infix right; let output_term = $process.float(output); Ok(output_term) } BigInts(left, right) => { let output = left $infix right; let output_term = $process.integer(output); Ok(output_term) } } }}; } macro_rules! number_to_integer { ($f:ident) => { use anyhow::*; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; use crate::erlang::number_to_integer::{f64_to_integer, NumberToInteger}; #[native_implemented::function(erlang:$f/1)] pub fn result(process: &Process, number: Term) -> exception::Result<Term> { match number.into() { NumberToInteger::Integer(integer) => Ok(integer), NumberToInteger::F64(f) => { let ceiling = f.$f(); Ok(f64_to_integer(process, ceiling)) } NumberToInteger::NotANumber => Err(TypeError) .context(term_is_not_number!(number)) .map_err(From::from), } } }; }
extern crate rand; extern crate crypto; use rand::seq::SliceRandom; use crypto::sha2::Sha256; use crypto::digest::Digest; const BASE_STR: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const STRETCHING: u32 = 1024; fn genelate_random_string() -> String { let mut rng = &mut rand::thread_rng(); String::from_utf8( BASE_STR.as_bytes() .choose_multiple(&mut rng, 16) .cloned() .collect() ).unwrap() } fn genelate_key(email: &str) -> String { let param = genelate_random_string(); let value = format!("{}{}", &param, email); let mut sha256 = Sha256::new(); sha256.input_str(&value); sha256.result_str() } pub fn create_hash_from_password(password: &str, email: &str) -> (String, String, String) { let salt = genelate_random_string(); let value = format!("{}{}", &salt, password); (stretch_hash_value(&value), salt, genelate_key(&email)) } pub fn stretch_hash_value(value: &str) -> String { let mut sha256 = Sha256::new(); for _ in 0..STRETCHING { sha256.input_str(&value); } sha256.result_str() } pub fn hash_salt_and_password(salt: &str, password: &str) -> String { let value = format!("{}{}", &salt, password); stretch_hash_value(&value) }
use crate::error::Diagnostic; #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Default)] pub struct Index { pub line: usize, pub column: usize, pub byte: usize, } fn idx_min(a: Index, b: Index) -> Index { if a.byte < b.byte { a } else { b } } fn idx_max(a: Index, b: Index) -> Index { if a.byte > b.byte { a } else { b } } impl Index { pub fn advance_by(mut self, ch: char) -> Self { self.byte += ch.len_utf8(); self.column += 1; if ch == '\n' { self.line += 1; self.column = 0; } self } } #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Default)] pub struct Span { pub start: Index, pub end: Index, } impl Span { pub fn new(start: Index, end: Index) -> Self { debug_assert!(start.byte <= end.byte); Span { start, end } } pub fn shrink_n_same_line(mut self, n: usize) -> Self { self.start.byte += n; self.start.column += n; self.end.byte -= n; self.end.column -= n; self } pub fn byte_len(&self) -> usize { self.end.byte - self.start.byte } pub fn union(self, other: Span) -> Self { assert!(self.end.byte >= self.start.byte); let lo = idx_min(self.start, other.start); let hi = idx_max(self.end, other.end); Span { start: lo, end: hi } } pub fn error_diagnostic(self) -> Diagnostic { self.into() } }
use std::thread; use std::net::{TcpListener, TcpStream, Shutdown}; use std::io::{Read, Write}; use std::str; fn handle_client(mut stream: TcpStream){ let mut data = [0 as u8; 50]; // using 50 byte buffer for receiving data while match stream.read(&mut data) { Ok(size) => { // reply to client and echo str when the size of data over 0! if size > 0 { stream.write(&data[0..size]).unwrap(); println!("received text: {}", str::from_utf8(&data).unwrap()); } true }, Err(_) => { // handle error println!("An error occured, terminating connection with {}", stream.peer_addr().unwrap()); stream.shutdown(Shutdown::Both).unwrap(); false } }{} } fn main() { // bind a port to receive clients let listener = TcpListener::bind("0.0.0:3333").unwrap(); // accept connections and process them, spawning a new thread for eacjh one println!("Server lisening on port 3333"); println!("Server listening on port 3333"); for stream in listener.incoming() { match stream { Ok(stream) => { // print when accept a coneection and print the ip address println!("New connection: {}", stream.peer_addr().unwrap()); // start a new thread to handle the connection thread::spawn(move|| { //connection succeeded handle_client(stream) }); } Err(e) => { println!("Error: {}", e); /* connection failed */ } } } // close the socket server drop(listener); }
use std::str; use std::io::{Read, stdin}; use crate::{constants, editor_visual}; pub(crate) fn editor_read_key() -> Option<String> { let mut input_buffer = [0; constants::INPUT_BUFFER_SIZE]; while stdin().read_exact(&mut input_buffer).is_err() {} match str::from_utf8(& input_buffer) { Ok(input_char) => { Some(input_char.to_string()) } Err(e) => { editor_visual::error_and_exit(format!("{} {}", constants::MESSAGE_ERROR_INVALID_UTF8, e)); None } } } pub fn preprocess_characters(input_char: String) -> String { match input_char.as_str() { constants::TERMINAL_ESCAPE => { editor_read_key(); let arrow_key = editor_read_key(); if let Some(arrow) = arrow_key { match arrow.as_str() { constants::ARROW_UP => constants::MOVE_CURSOR_UP.to_string(), constants::ARROW_DOWN => constants::MOVE_CURSOR_DOWN.to_string(), constants::ARROW_RIGHT => constants::MOVE_CURSOR_RIGHT.to_string(), constants::ARROW_LEFT => constants::MOVE_CURSOR_LEFT.to_string(), _ => input_char } } else { input_char } } _ => input_char } }
use console::style; fn main() { for i in 0..=255 { print!("{:03} ", style(i).color256(i)); if i % 16 == 15 { println!(); } } for i in 0..=255 { print!("{:03} ", style(i).black().on_color256(i)); if i % 16 == 15 { println!(); } } }
use std::fmt; // Sedgewick edition (~30% faster than Cormen's one) // p.251 /// Insertion sort. /// /// Time complexity: /// /// * best: Ω(n) /// * avg: Θ(n^2) /// * worst: O(n^2) /// /// Space complexity: /// /// * O(1) pub fn sort<T: Ord + fmt::Debug>(input: &mut Vec<T>) { for i in 1..input.len() { // as right border is not included, do: i+1 'back: for j in (1..(i + 1)).rev() { if input[j - 1] > input[j] { input.swap(j - 1, j); } else { break 'back; } } } } //use std::clone; //// Cormen edition //// p.18 //pub fn sort<T: Ord + fmt::Debug + clone::Clone>(input: &mut Vec<T>) { // for j in 1..input.len() { // let key = input[j].clone(); // let mut i = j - 1; // // dirty hack: as "i" has usize type, it can't be < 0 // // but we need to be able to update a first element of the vector // let mut insert_first = false; // 'back: while input[i] > key { // input[i + 1] = input[i].clone(); // if i == 0 { // insert_first = true; // break 'back; // } else { // i = i - 1; // } // } // input[if insert_first {0} else {i + 1}] = key; // } //} add_common_tests!();
{{#*inline "choice_ids"~}} ({{~#each arguments}}{{this.[1].def.keys.IdType}},{{/each~}}) {{/inline~}} /// Stores the domains of each variable. #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct DomainStore { {{#each choices}} {{name}}: Arc<FxHashMap<{{>choice_ids this}}, {{>value_type.name value_type}}>>, {{/each}} } #[allow(dead_code)] impl DomainStore { /// Creates a new domain store and allocates the variables for the given BBMap. pub fn new(ir_instance: &ir::Function) -> Self { let mut store = DomainStore::default(); store.init(ir_instance); store } /// Initializes the domain. #[allow(unused_variables, unused_mut)] fn init(&mut self, ir_instance: &ir::Function) { {{#each choices~}} {{#>loop_nest iteration_space~}} {{>alloc}} {{/loop_nest~}} {{/each~}} } /// Allocates the choices when new objects are created. #[allow(unused_variables, unused_mut)] pub fn alloc(&mut self, ir_instance: &ir::Function, new_objs: &ir::NewObjs) { {{#each partial_iterators~}} {{#>iter_new_objects this.[0]~}} {{>alloc this.[1].choice arg_names=this.[1].arg_names value_type=this.[1].value_type}} {{/iter_new_objects~}} {{/each~}} } {{#each choices}}{{>getter this}}{{/each}} } /// Stores the old values of a modified `DomainStore`. #[derive(Default)] pub struct DomainDiff { {{#each choices}} pub {{name}}: FxHashMap<{{>choice_ids this}}, ({{>value_type.name value_type}}, {{>value_type.name value_type}})>, {{/each}} } impl DomainDiff { /// Indicates if the `DomainDiff` does not holds any modification. pub fn is_empty(&self) -> bool { {{~#if choices~}} {{#each choices~}} {{~#unless @first}} && {{/unless~}} self.{{name}}.is_empty() {{~/each}} {{else}}true{{/if~}} } {{#each choices}} /// Removes all the modifications of '{name}' and returns them. pub fn pop_{{name}}_diff(&mut self) -> Option<(({{>choice_ids}}), {{~>value_type.name value_type}}, {{>value_type.name value_type}})> { self.{{name}}.keys().cloned().next().map(|k| { let (old, new) = unwrap!(self.{{name}}.remove(&k)); (k, old, new) }) } {{/each}} }
extern crate serde; extern crate serde_json; include!(concat!(env!("OUT_DIR"), "/serde_types.rs")); extern crate ring; extern crate webpki; extern crate untrusted; extern crate base64; extern crate hex_slice; // XXX REMOVE #[macro_use] extern crate error_chain; pub mod challenge; pub mod registration; pub use self::challenge::challenge;
// Workaround for clippy bug. #![allow(clippy::unnecessary_wraps)] mod lexer; use lexer::{Lexer, Token, Keyword}; use crate::{Value, Label, Type, LargeKeyMap, Module, Instruction, IntPredicate, BinaryOp, Map, Function, UnaryOp, Cast}; impl Keyword { fn to_type(&self) -> Option<Type> { Some(match self { Keyword::U1 => Type::U1, Keyword::U8 => Type::U8, Keyword::U16 => Type::U16, Keyword::U32 => Type::U32, Keyword::U64 => Type::U64, _ => return None, }) } fn to_unary_operator(&self) -> Option<UnaryOp> { Some(match self { Keyword::Neg => UnaryOp::Neg, Keyword::Not => UnaryOp::Not, _ => return None, }) } fn to_binary_operator(&self) -> Option<BinaryOp> { Some(match self { Keyword::Add => BinaryOp::Add, Keyword::Sub => BinaryOp::Sub, Keyword::Mul => BinaryOp::Mul, Keyword::Umod => BinaryOp::ModU, Keyword::Udiv => BinaryOp::DivU, Keyword::Smod => BinaryOp::ModS, Keyword::Sdiv => BinaryOp::DivS, Keyword::Shr => BinaryOp::Shr, Keyword::Shl => BinaryOp::Shl, Keyword::Sar => BinaryOp::Sar, Keyword::And => BinaryOp::And, Keyword::Or => BinaryOp::Or, Keyword::Xor => BinaryOp::Xor, _ => return None, }) } fn to_int_predicate(&self) -> Option<IntPredicate> { Some(match self { Keyword::Eq => IntPredicate::Equal, Keyword::Ne => IntPredicate::NotEqual, Keyword::Ugt => IntPredicate::GtU, Keyword::Ugte => IntPredicate::GteU, Keyword::Sgt => IntPredicate::GtS, Keyword::Sgte => IntPredicate::GteS, Keyword::Ult => IntPredicate::LtU, Keyword::Ulte => IntPredicate::LteU, Keyword::Slt => IntPredicate::LtS, Keyword::Slte => IntPredicate::LteS, _ => return None, }) } fn to_cast(&self) -> Option<Cast> { Some(match self { Keyword::Zext => Cast::ZeroExtend, Keyword::Sext => Cast::SignExtend, Keyword::Trunc => Cast::Truncate, Keyword::Bitcast => Cast::Bitcast, _ => return None, }) } } #[derive(Default)] struct FunctionContext { values: LargeKeyMap<String, Value>, labels: LargeKeyMap<String, Label>, types: Map<Value, Type>, labels_defined: Map<Label, bool>, } impl FunctionContext { fn label(&mut self, label_name: &str, ir: &mut Module) -> Label { if let Some(label) = self.labels.get(label_name) { return *label; } let label = ir.create_label(); self.labels.insert(label_name.to_string(), label); self.labels_defined.entry(label).or_insert(false); label } fn value(&mut self, value_name: &str, ir: &mut Module) -> Value { if let Some(value) = self.values.get(value_name) { return *value; } let value = ir.function_mut(ir.active_point().function).allocate_value(); self.values.insert(value_name.to_string(), value); value } fn switch_label(&mut self, label_name: &str, ir: &mut Module) { let label = if self.labels.is_empty() { let label = ir.entry_label(); self.labels.insert(label_name.to_string(), label); label } else { self.label(label_name, ir) }; self.labels_defined.insert(label, true); ir.switch_label(label); } fn force_type(&mut self, value: Value, ty: Type) { if let Some(before) = self.types.insert(value, ty) { assert_eq!(before, ty, "{} type mistmatch ({} vs {}).", value, before, ty); } } } struct Parser { lexer: Lexer, functions: LargeKeyMap<String, Function>, function_contexts: Map<Function, FunctionContext>, function_cursors: Map<Function, usize>, } impl Parser { fn new(source: &str) -> Self { Self { lexer: Lexer::new(source), functions: LargeKeyMap::default(), function_contexts: Map::default(), function_cursors: Map::default(), } } fn comma(&mut self) { self.lexer.eat_expect(&Token::Comma); } fn parse_argument_list(&mut self, open: Token, close: Token, mut callback: impl FnMut(&mut Self)) { self.lexer.eat_expect(&open); loop { if self.lexer.current() == &close { self.lexer.eat(); break; } callback(self); let current = self.lexer.current(); if current == &Token::Comma { self.lexer.eat(); } else { assert_eq!(current, &close, "Expected comma or closing paren \ in argument list. Got {:?}.", current); } } } fn parse_type_keyword(&mut self, keyword: Keyword) -> Type { let mut ty = keyword.to_type().expect("Expected type keyword."); loop { if self.lexer.current() != &Token::Star { break; } ty = ty.ptr(); self.lexer.eat(); } ty } fn parse_type(&mut self) -> Type { let keyword = self.lexer.eat_keyword(); self.parse_type_keyword(keyword) } fn parse_return_type(&mut self) -> Option<Type> { if self.lexer.current() == &Token::Keyword(Keyword::Void) { self.lexer.eat(); return None; } Some(self.parse_type()) } fn parse_label(&mut self, cx: &mut FunctionContext, ir: &mut Module) -> Label { cx.label(self.lexer.eat_identifier(), ir) } fn parse_value(&mut self, ty: Type, cx: &mut FunctionContext, ir: &mut Module) -> Value { let value = match self.lexer.current() { Token::Keyword(Keyword::Undefined) => { self.lexer.eat(); ir.function_mut(ir.active_point().function).undefined_value(ty) } Token::Identifier(_) => { if let Token::Identifier(identifier) = self.lexer.eat() { cx.value(identifier, ir) } else { unreachable!() } } Token::Keyword(Keyword::Null) | Token::Keyword(Keyword::True) | Token::Keyword(Keyword::False) | Token::Literal(..) => { let constant = self.parse_constant(ty); ir.iconst(constant, ty) } x => panic!("Unexpected token when parsing value: {:?}.", x), }; cx.force_type(value, ty); value } fn parse_constant(&mut self, ty: Type) -> u64 { match self.lexer.eat() { &Token::Keyword(keyword) => { match keyword { Keyword::True | Keyword::False => { assert_eq!(ty, Type::U1, "true/false constants can be only used for U1."); (keyword == Keyword::True) as u64 } Keyword::Null => { assert!(ty.is_pointer(), "null constant can be only used for pointers."); 0 } _ => panic!("Invalid constant keyword {:?}.", keyword), } } Token::Literal(literal) => { let literal = *literal; macro_rules! fits_within { ($value: expr, $type: ty) => { $value as i64 <= <$type>::MAX as i64 && $value as i64 >= <$type>::MIN as i64 } } let fits = match ty { Type::U1 => literal == 0 || literal == 1, Type::U8 => fits_within!(literal, i8), Type::U16 => fits_within!(literal, i16), Type::U32 => fits_within!(literal, i32), _ => fits_within!(literal, i64), }; assert!(fits, "Literal {} doesn't fit in {}.", literal, ty); literal as u64 } x => panic!("Unexpected token when parsing constant: {:?}.", x), } } fn parse_call(&mut self, destination: Option<Value>, cx: &mut FunctionContext, ir: &mut Module) -> Instruction { let return_ty = self.parse_return_type(); let name = self.lexer.eat_identifier(); let function = self.functions[name]; assert_eq!(destination.is_some(), return_ty.is_some(), "Call return type mismatch."); if let Some(destination) = destination { cx.force_type(destination, return_ty.unwrap()); } let mut arguments = Vec::new(); self.parse_argument_list(Token::ParenOpen, Token::ParenClose, |parser| { let argument_ty = parser.parse_type(); let argument = parser.parse_value(argument_ty, cx, ir); arguments.push(argument); }); Instruction::Call { dst: destination, func: function, args: arguments, } } fn parse_non_returning_instruction(&mut self, keyword: Keyword, cx: &mut FunctionContext, ir: &mut Module) -> Instruction { macro_rules! value { ($type: expr) => { self.parse_value($type, cx, ir) } } macro_rules! label { () => { self.parse_label(cx, ir) } } match keyword { Keyword::Store => { let ptr_ty = self.parse_type(); let ptr = value!(ptr_ty); self.comma(); let value_ty = self.parse_type(); let value = value!(value_ty); Instruction::Store { ptr, value, } } Keyword::Branch => { let target = label!(); Instruction::Branch { target, } } Keyword::Bcond => { let cond_ty = self.parse_type(); let cond = value!(cond_ty); self.comma(); let on_true = label!(); self.comma(); let on_false = label!(); Instruction::BranchCond { cond, on_true, on_false, } } Keyword::Ret => { let value = self.parse_return_type().map(|ty| value!(ty)); Instruction::Return { value, } } Keyword::Call => self.parse_call(None, cx, ir), Keyword::Nop => Instruction::Nop, _ => panic!("Unexpected keyword for non-returning instruction: {:?}.", keyword), } } fn parse_returning_instruction(&mut self, keyword: Keyword, output: String, cx: &mut FunctionContext, ir: &mut Module) -> Instruction { macro_rules! value { ($type: expr) => { self.parse_value($type, cx, ir) } } let dst = cx.value(&output, ir); if let Some(op) = keyword.to_unary_operator() { let ty = self.parse_type(); let value = value!(ty); return Instruction::ArithmeticUnary { dst, op, value, }; } if let Some(op) = keyword.to_binary_operator() { let ty = self.parse_type(); let a = value!(ty); self.comma(); let b = value!(ty); return Instruction::ArithmeticBinary { dst, a, op, b, }; } if let Some(cast) = keyword.to_cast() { let value_ty = self.parse_type(); let value = value!(value_ty); self.lexer.eat_expect(&Token::Keyword(Keyword::To)); let dest_ty = self.parse_type(); return Instruction::Cast { dst, cast, value, ty: dest_ty, }; } match keyword { Keyword::Cmp => { let pred = self.lexer.eat_keyword() .to_int_predicate() .expect("Expected int predicate."); let ty = self.parse_type(); let a = value!(ty); self.comma(); let b = value!(ty); Instruction::IntCompare { dst, a, pred, b, } } Keyword::Load => { let dst_ty = self.parse_type(); self.comma(); let ptr_ty = self.parse_type(); let ptr = value!(ptr_ty); cx.force_type(dst, dst_ty); Instruction::Load { dst, ptr, } } Keyword::Stackalloc => { let ty = self.parse_type(); let mut size = 1; if self.lexer.current() == &Token::Comma { self.lexer.eat(); size = self.parse_constant(Type::U64) as usize; } Instruction::StackAlloc { dst, ty, size, } } Keyword::Gep => { let source_ty = self.parse_type(); let source = value!(source_ty); self.comma(); let index_ty = self.parse_type(); let index = value!(index_ty); Instruction::GetElementPtr { dst, index, source, } } Keyword::Select => { let cond_ty = self.parse_type(); let cond = value!(cond_ty); self.comma(); let value_ty = self.parse_type(); let on_true = value!(value_ty); self.comma(); let on_false = value!(value_ty); Instruction::Select { dst, cond, on_true, on_false, } } Keyword::Phi => { let ty = self.parse_type(); let mut incoming = Vec::new(); self.parse_argument_list(Token::BracketOpen, Token::BracketClose, |parser| { let label = parser.parse_label(cx, ir); parser.lexer.eat_expect(&Token::Colon); let value = parser.parse_value(ty, cx, ir); incoming.push((label, value)); }); Instruction::Phi { dst, incoming, } } Keyword::Alias => { let value_ty = self.parse_type(); let value = value!(value_ty); Instruction::Alias { dst, value, } } Keyword::Call => { self.parse_call(Some(dst), cx, ir) } _ => panic!("Unexpected keyword for returning instruction: {:?}.", keyword), } } fn parse_function_body(&mut self, cx: &mut FunctionContext, ir: &mut Module) { self.lexer.eat_expect(&Token::BraceOpen); let mut has_label = false; while self.lexer.current() != &Token::BraceClose { let mut instruction = None; match self.lexer.eat() { &Token::Keyword(keyword) => { assert!(has_label, "Instruction isn't part of any block."); instruction = Some(self.parse_non_returning_instruction(keyword, cx, ir)); } Token::Identifier(identifier) => { let identifier = identifier.to_string(); match self.lexer.eat() { Token::Assign => { assert!(has_label, "Instruction isn't part of any block."); let keyword = self.lexer.eat_keyword(); instruction = Some(self.parse_returning_instruction(keyword, identifier, cx, ir)); } Token::Colon => { cx.switch_label(&identifier, ir); has_label = true; } x => panic!("Unexpected token after identifier \ in function body: {:?}.", x), } } x => panic!("Unexpected token in function body: {:?}.", x), } if let Some(instruction) = instruction { let active_point = ir.active_point(); ir.function_mut(active_point.function) .insert(active_point.label, instruction); } } self.lexer.eat_expect(&Token::BraceClose); } fn parse_function_prototype(&mut self, ir: &mut Module) { let return_ty = self.parse_return_type(); let name = self.lexer.eat_identifier().to_string(); let mut arguments = Vec::new(); self.parse_argument_list(Token::ParenOpen, Token::ParenClose, |parser| { let ty = parser.parse_type(); let argument = parser.lexer.eat_identifier().to_string(); arguments.push((ty, argument)); }); let argument_types: Vec<_> = arguments.iter() .map(|(ty, _)| *ty) .collect(); let function = ir.create_function(&name, return_ty, argument_types); let cursor = self.lexer.cursor(); ir.switch_function(function); let mut cx = FunctionContext::default(); for (index, (_, argument_name)) in arguments.into_iter().enumerate() { cx.values.insert(argument_name, ir.argument(index)); } self.lexer.eat_expect(&Token::BraceOpen); while self.lexer.eat() != &Token::BraceClose {} assert!(self.functions.insert(name.to_string(), function).is_none(), "Multiple functions with the same name ({}).", name); assert!(self.function_contexts.insert(function, cx).is_none(), "Function {} already has context.", name); assert!(self.function_cursors.insert(function, cursor).is_none(), "Function {} already has cursor.", name); } fn parse_functions(&mut self, ir: &mut Module) { while self.lexer.current() != &Token::Eof { self.parse_function_prototype(ir); } let cursors = std::mem::take(&mut self.function_cursors); for (function, cursor) in cursors { let mut cx = self.function_contexts.remove(&function) .expect("Function doesn't have context for some reason."); ir.switch_function(function); self.lexer.set_cursor(cursor); self.parse_function_body(&mut cx, ir); assert!(self.function_contexts.insert(function, cx).is_none(), "Context already exists."); } } } pub fn parse(source: &str) -> Module { let mut parser = Parser::new(source); let mut ir = Module::new(); parser.parse_functions(&mut ir); for cx in parser.function_contexts.values() { let reverse_lookup: Map<Label, String> = cx.labels.iter().map(|(name, label)| { (*label, name.to_string()) }).collect(); for (label, defined) in &cx.labels_defined { assert!(defined, "Label {} used but not defined.", reverse_lookup[&label]); } } ir.finalize(); for (&function, cx) in &parser.function_contexts { let function_data = ir.function(function); for (value, ty) in &cx.types { let actual = function_data.value_type(*value); assert_eq!(actual, *ty, "{}: {} type mistmatch (user {} vs infered {}).", function_data.prototype.name, value, ty, actual); } } ir }
use crate::gl_wrapper::texture_2d::Texture2D; use crate::gl_wrapper::rbo::RBO; #[derive(Debug)] pub enum DepthStencilTarget { Texture2D(Texture2D), RBO(RBO) } #[derive(Debug)] pub struct FBO { id: u32, pub(crate) color_texture: Texture2D, depth_stencil_target: DepthStencilTarget, } impl FBO { pub fn new(color_texture: Texture2D, depth_stencil_target: DepthStencilTarget) -> Self { let mut id = 0u32; gl_call!(gl::CreateFramebuffers(1, &mut id)); // Bind color gl_call!(gl::NamedFramebufferTexture(id, gl::COLOR_ATTACHMENT0, color_texture.id, 0)); // Bind depth & stencil match &depth_stencil_target { DepthStencilTarget::Texture2D(texture) => { gl_call!(gl::NamedFramebufferTexture(id, gl::DEPTH_STENCIL_ATTACHMENT, texture.id, 0)); } DepthStencilTarget::RBO(rbo) => { gl_call!(gl::NamedFramebufferRenderbuffer(id, gl::DEPTH_STENCIL_ATTACHMENT, gl::RENDERBUFFER, rbo.id)); } } if gl_call!(gl::CheckNamedFramebufferStatus(id, gl::FRAMEBUFFER)) != gl::FRAMEBUFFER_COMPLETE { panic!("Framebuffer {} is not complete", id); } FBO { id, color_texture, depth_stencil_target } } pub fn bind(&self) { gl_call!(gl::BindFramebuffer(gl::FRAMEBUFFER, self.id)); } pub fn bind_default() { gl_call!(gl::BindFramebuffer(gl::FRAMEBUFFER, 0)); } } impl Drop for FBO { fn drop(&mut self) { gl_call!(gl::DeleteFramebuffers(1, &self.id)); } }
use super::Transform; use crate::{ event, event::{Event, Value}, topology::config::{DataType, TransformConfig, TransformContext, TransformDescription}, }; use bytes::Bytes; use lru::LruCache; use serde::{Deserialize, Serialize}; use string_cache::DefaultAtom as Atom; #[derive(Deserialize, Serialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub enum FieldMatchConfig { #[serde(rename = "match")] MatchFields(Vec<Atom>), #[serde(rename = "ignore")] IgnoreFields(Vec<String>), #[serde(skip)] Default, } #[derive(Deserialize, Serialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct CacheConfig { pub num_events: usize, } #[derive(Deserialize, Serialize, Debug)] #[serde(deny_unknown_fields)] pub struct DedupeConfig { #[serde(default = "default_field_match_config")] pub fields: FieldMatchConfig, #[serde(default = "default_cache_config")] pub cache: CacheConfig, } fn default_cache_config() -> CacheConfig { CacheConfig { num_events: 5000 } } /// Note that the value returned by this is just a placeholder. To get the real default you must /// call fill_default() on the parsed DedupeConfig instance. fn default_field_match_config() -> FieldMatchConfig { FieldMatchConfig::Default } impl DedupeConfig { /// We cannot rely on Serde to populate the default since we want it to be based on the user's /// configured log_schema, which we only know about after we've already parsed the config. pub fn fill_default(&self) -> Self { let fields = match &self.fields { FieldMatchConfig::MatchFields(x) => FieldMatchConfig::MatchFields(x.clone()), FieldMatchConfig::IgnoreFields(y) => FieldMatchConfig::IgnoreFields(y.clone()), FieldMatchConfig::Default => FieldMatchConfig::MatchFields(vec![ event::log_schema().timestamp_key().into(), event::log_schema().host_key().into(), event::log_schema().message_key().into(), ]), }; Self { fields, cache: self.cache.clone(), } } } pub struct Dedupe { config: DedupeConfig, cache: LruCache<CacheEntry, bool>, } inventory::submit! { TransformDescription::new_without_default::<DedupeConfig>("dedupe") } #[typetag::serde(name = "dedupe")] impl TransformConfig for DedupeConfig { fn build(&self, _cx: TransformContext) -> crate::Result<Box<dyn Transform>> { Ok(Box::new(Dedupe::new(self.fill_default()))) } fn input_type(&self) -> DataType { DataType::Log } fn output_type(&self) -> DataType { DataType::Log } fn transform_type(&self) -> &'static str { "dedupe" } } type TypeId = u8; /// A CacheEntry comes in two forms, depending on the FieldMatchConfig in use. /// /// When matching fields, a CacheEntry contains a vector of optional 2-tuples. Each element in the /// vector represents one field in the corresponding LogEvent. Elements in the vector will /// correspond 1:1 (and in order) to the fields specified in "fields.match". The tuples each store /// the TypeId for this field and the data as Bytes for the field. There is no need to store the /// field name because the elements of the vector correspond 1:1 to "fields.match", so there is /// never any ambiguity about what field is being referred to. If a field from "fields.match" does /// not show up in an incoming Event, the CacheEntry will have None in the correspond location in /// the vector. /// /// When ignoring fields, a CacheEntry contains a vector of 3-tuples. Each element in the vector /// represents one field in the corresponding LogEvent. The tuples will each contain the field /// name, TypeId, and data as Bytes for the corresponding field (in that order). Since the set of /// fields that might go into CacheEntries is not known at startup, we must store the field names /// as part of CacheEntries. Since Event objects store their field in alphabetic order (as they /// are backed by a BTreeMap), and we build CacheEntries by iterating over the fields of the /// incoming Events, we know that the CacheEntries for 2 equivalent events will always contain the /// fields in the same order. #[derive(PartialEq, Eq, Hash)] enum CacheEntry { Match(Vec<Option<(TypeId, Bytes)>>), Ignore(Vec<(Atom, TypeId, Bytes)>), } /// Assigns a unique number to each of the types supported by Event::Value. fn type_id_for_value(val: &Value) -> TypeId { match val { Value::Bytes(_) => 0, Value::Timestamp(_) => 1, Value::Integer(_) => 2, Value::Float(_) => 3, Value::Boolean(_) => 4, Value::Map(_) => 5, Value::Array(_) => 6, Value::Null => 7, } } impl Dedupe { pub fn new(config: DedupeConfig) -> Self { let num_entries = config.cache.num_events; Self { config, cache: LruCache::new(num_entries), } } } /// Takes in an Event and returns a CacheEntry to place into the LRU cache containing /// all relevant information for the fields that need matching against according to the /// specified FieldMatchConfig. fn build_cache_entry(event: &Event, fields: &FieldMatchConfig) -> CacheEntry { match &fields { FieldMatchConfig::MatchFields(fields) => { let mut entry = Vec::new(); for field_name in fields.iter() { if let Some(value) = event.as_log().get(&field_name) { entry.push(Some((type_id_for_value(&value), value.as_bytes()))); } else { entry.push(None); } } CacheEntry::Match(entry) } FieldMatchConfig::IgnoreFields(fields) => { let mut entry = Vec::new(); for (field_name, value) in event.as_log().all_fields() { if !fields.contains(&field_name) { entry.push(( Atom::from(field_name), type_id_for_value(&value), value.as_bytes(), )); } } CacheEntry::Ignore(entry) } FieldMatchConfig::Default => { panic!("Dedupe transform config contains Default FieldMatchConfig while running"); } } } impl Transform for Dedupe { fn transform(&mut self, event: Event) -> Option<Event> { let cache_entry = build_cache_entry(&event, &self.config.fields); if self.cache.put(cache_entry, true).is_some() { warn!( message = "Encountered duplicate event; discarding", rate_limit_secs = 30 ); trace!(message = "Encountered duplicate event; discarding", ?event); None } else { Some(event) } } } #[cfg(test)] mod tests { use super::Dedupe; use crate::transforms::dedupe::{CacheConfig, DedupeConfig, FieldMatchConfig}; use crate::{event::Event, event::Value, transforms::Transform}; use std::collections::BTreeMap; use string_cache::DefaultAtom as Atom; fn make_match_transform(num_events: usize, fields: Vec<Atom>) -> Dedupe { Dedupe::new(DedupeConfig { cache: CacheConfig { num_events }, fields: { FieldMatchConfig::MatchFields(fields) }, }) } fn make_ignore_transform(num_events: usize, given_fields: Vec<String>) -> Dedupe { // "message" and "timestamp" are added automatically to all Events let mut fields = vec!["message".into(), "timestamp".into()]; fields.extend(given_fields); Dedupe::new(DedupeConfig { cache: CacheConfig { num_events }, fields: { FieldMatchConfig::IgnoreFields(fields) }, }) } #[test] fn dedupe_match_basic() { let transform = make_match_transform(5, vec!["matched".into()]); basic(transform); } #[test] fn dedupe_ignore_basic() { let transform = make_ignore_transform(5, vec!["unmatched".into()]); basic(transform); } fn basic(mut transform: Dedupe) { let mut event1 = Event::from("message"); event1.as_mut_log().insert("matched", "some value"); event1.as_mut_log().insert("unmatched", "another value"); // Test that unmatched field isn't considered let mut event2 = Event::from("message"); event2.as_mut_log().insert("matched", "some value2"); event2.as_mut_log().insert("unmatched", "another value"); // Test that matched field is considered let mut event3 = Event::from("message"); event3.as_mut_log().insert("matched", "some value"); event3.as_mut_log().insert("unmatched", "another value2"); // First event should always be passed through as-is. let new_event = transform.transform(event1).unwrap(); assert_eq!(new_event.as_log()[&"matched".into()], "some value".into()); // Second event differs in matched field so should be outputted even though it // has the same value for unmatched field. let new_event = transform.transform(event2).unwrap(); assert_eq!(new_event.as_log()[&"matched".into()], "some value2".into()); // Third event has the same value for "matched" as first event, so it should be dropped. assert_eq!(None, transform.transform(event3)); } #[test] fn dedupe_match_field_name_matters() { let transform = make_match_transform(5, vec!["matched1".into(), "matched2".into()]); field_name_matters(transform); } #[test] fn dedupe_ignore_field_name_matters() { let transform = make_ignore_transform(5, vec![]); field_name_matters(transform); } fn field_name_matters(mut transform: Dedupe) { let mut event1 = Event::from("message"); event1.as_mut_log().insert("matched1", "some value"); let mut event2 = Event::from("message"); event2.as_mut_log().insert("matched2", "some value"); // First event should always be passed through as-is. let new_event = transform.transform(event1).unwrap(); assert_eq!(new_event.as_log()[&"matched1".into()], "some value".into()); // Second event has a different matched field name with the same value, so it should not be // considered a dupe let new_event = transform.transform(event2).unwrap(); assert_eq!(new_event.as_log()[&"matched2".into()], "some value".into()); } #[test] fn dedupe_match_field_order_irrelevant() { let transform = make_match_transform(5, vec!["matched1".into(), "matched2".into()]); field_order_irrelevant(transform); } #[test] fn dedupe_ignore_field_order_irrelevant() { let transform = make_ignore_transform(5, vec!["randomData".into()]); field_order_irrelevant(transform); } /// Test that two Events that are considered duplicates get handled that way, even /// if the order of the matched fields is different between the two. fn field_order_irrelevant(mut transform: Dedupe) { let mut event1 = Event::from("message"); event1.as_mut_log().insert("matched1", "value1"); event1.as_mut_log().insert("matched2", "value2"); // Add fields in opposite order let mut event2 = Event::from("message"); event2.as_mut_log().insert("matched2", "value2"); event2.as_mut_log().insert("matched1", "value1"); // First event should always be passed through as-is. let new_event = transform.transform(event1).unwrap(); assert_eq!(new_event.as_log()[&"matched1".into()], "value1".into()); assert_eq!(new_event.as_log()[&"matched2".into()], "value2".into()); // Second event is the same just with different field order, so it shouldn't be outputted. assert_eq!(None, transform.transform(event2)); } #[test] fn dedupe_match_age_out() { // Construct transform with a cache size of only 1 entry. let transform = make_match_transform(1, vec!["matched".into()]); age_out(transform); } #[test] fn dedupe_ignore_age_out() { // Construct transform with a cache size of only 1 entry. let transform = make_ignore_transform(1, vec![]); age_out(transform); } /// Test the eviction behavior of the underlying LruCache fn age_out(mut transform: Dedupe) { let mut event1 = Event::from("message"); event1.as_mut_log().insert("matched", "some value"); let mut event2 = Event::from("message"); event2.as_mut_log().insert("matched", "some value2"); // This event is a duplicate of event1, but won't be treated as such. let event3 = event1.clone(); // First event should always be passed through as-is. let new_event = transform.transform(event1).unwrap(); assert_eq!(new_event.as_log()[&"matched".into()], "some value".into()); // Second event gets outputted because it's not a dupe. This causes the first // Event to be evicted from the cache. let new_event = transform.transform(event2).unwrap(); assert_eq!(new_event.as_log()[&"matched".into()], "some value2".into()); // Third event is a dupe but gets outputted anyway because the first event has aged // out of the cache. let new_event = transform.transform(event3).unwrap(); assert_eq!(new_event.as_log()[&"matched".into()], "some value".into()); } #[test] fn dedupe_match_type_matching() { let transform = make_match_transform(5, vec!["matched".into()]); type_matching(transform); } #[test] fn dedupe_ignore_type_matching() { let transform = make_ignore_transform(5, vec![]); type_matching(transform); } /// Test that two events with values for the matched fields that have different /// types but the same string representation aren't considered duplicates. fn type_matching(mut transform: Dedupe) { let mut event1 = Event::from("message"); event1.as_mut_log().insert("matched", "123"); let mut event2 = Event::from("message"); event2.as_mut_log().insert("matched", 123); // First event should always be passed through as-is. let new_event = transform.transform(event1).unwrap(); assert_eq!(new_event.as_log()[&"matched".into()], "123".into()); // Second event should also get passed through even though the string representations of // "matched" are the same. let new_event = transform.transform(event2).unwrap(); assert_eq!(new_event.as_log()[&"matched".into()], 123.into()); } #[test] fn dedupe_match_type_matching_nested_objects() { let transform = make_match_transform(5, vec!["matched".into()]); type_matching_nested_objects(transform); } #[test] fn dedupe_ignore_type_matching_nested_objects() { let transform = make_ignore_transform(5, vec![]); type_matching_nested_objects(transform); } /// Test that two events where the matched field is a sub object and that object contains values /// that have different types but the same string representation aren't considered duplicates. fn type_matching_nested_objects(mut transform: Dedupe) { let mut map1: BTreeMap<String, Value> = BTreeMap::new(); map1.insert("key".into(), "123".into()); let mut event1 = Event::from("message"); event1.as_mut_log().insert("matched", map1); let mut map2: BTreeMap<String, Value> = BTreeMap::new(); map2.insert("key".into(), 123.into()); let mut event2 = Event::from("message"); event2.as_mut_log().insert("matched", map2); // First event should always be passed through as-is. let new_event = transform.transform(event1).unwrap(); let res_value = new_event.as_log()[&"matched".into()].clone(); if let Value::Map(map) = res_value { assert_eq!(map.get("key").unwrap(), &Value::from("123")); } // Second event should also get passed through even though the string representations of // "matched" are the same. let new_event = transform.transform(event2).unwrap(); let res_value = new_event.as_log()[&"matched".into()].clone(); if let Value::Map(map) = res_value { assert_eq!(map.get("key").unwrap(), &Value::from(123)); } } #[test] fn dedupe_match_null_vs_missing() { let transform = make_match_transform(5, vec!["matched".into()]); ignore_vs_missing(transform); } #[test] fn dedupe_ignore_null_vs_missing() { let transform = make_ignore_transform(5, vec![]); ignore_vs_missing(transform); } /// Test an explicit null vs a field being missing are treated as different. fn ignore_vs_missing(mut transform: Dedupe) { let mut event1 = Event::from("message"); event1.as_mut_log().insert("matched", Value::Null); let event2 = Event::from("message"); // First event should always be passed through as-is. let new_event = transform.transform(event1).unwrap(); assert_eq!(new_event.as_log()[&"matched".into()], Value::Null); // Second event should also get passed through as null is different than missing let new_event = transform.transform(event2).unwrap(); assert_eq!(false, new_event.as_log().contains(&"matched".into())); } }
use proto::mesos as pb; /// Callback interface to be implemented by frameworks' executors. Note that /// only one callback will be invoked at a time, so it is not recommended that /// you block within a callback because it may cause a deadlock. /// /// Each callback includes a reference to the executor driver that was used /// to run this executor. The reference will not change for the duration /// of an executor (i.e., from the point you do `ExecutorDriver::start` to /// the point that `ExecutorDriver::join` returns. This is intended for /// convenience so that an executor doesn't need to store a reference to the /// driver itself. pub trait Executor { /// Invoked once the executor driver has been able to successfully /// connect with Mesos. In particular, a scheduler can pass some data /// to its executors through the ExecutorInfo's `data` field. fn registered( &self, executor_info: &pb::ExecutorInfo, framework_info: &pb::FrameworkInfo, slave_info: &pb::SlaveInfo); /// Invoked when the executor re-registers with a restarted slave. fn reregistered( &self, slave_info: &pb::SlaveInfo); /// Invoked when the executor becomes "disconnected" from the slave /// (e.g., the slave was restarted due to an upgrade). fn disconnected(&self); /// Invoked when a task has been launched on this executor (initiated /// via `SchedulerDriver::launch_tasks`. Note that this task can be /// realized with a thread, a process, or some simple computation, /// however, no other callbacks will be invoked on this executor until /// this callback has returned. fn launch_task( &self, task: &pb::TaskInfo); /// Invoked when a task running within this executor has been killed /// (via `SchedulerDriver::kill_task`). Note that no status update will /// be sent on behalf of the executor, the executor is responsible for /// creating a new TaskStatus (i.e., with TASK_KILLED) and invoking /// `ExecutorDriver::send_status_update`. fn kill_task( &self, task_id: &pb::TaskID); /// Invoked when a framework message has arrived for this executor. /// These messages are best effort; do not expect a framework message /// to be retransmitted in any reliable fashion. fn framework_message( &self, data: &Vec<u8>); /// Invoked when the executor should terminate all of it's currently /// running tasks. Note that after Mesos has determined that an executor /// has terminated any tasks that the executor did not send terminal /// status updates for (e.g. TASK_KILLED, TASK_FINISHED, TASK_FAILED, /// TASK_LOST, TASK_ERROR, etc) a TASK_LOST status update will be /// created. fn shutdown(&self); /// Invoked when a fatal error has occurred with the executor and/or /// executor driver. The driver will be aborted BEFORE invoking this /// callback. fn error(&self, message: String); } /// Abstract interface for connecting an executor to Mesos. This interface /// is used both to manage the executor's lifecycle (start it, stop it, or /// wait for it to finish) and to interact with Mesos (e.g., send status /// updates, send framework messages, etc.). pub trait ExecutorDriver { /// Starts and immediately joins (i.e., blocks on) the driver. fn run(&mut self) -> i32; /// Stops the executor driver. fn stop(&self) -> i32; /// Sends a status update to the framework scheduler, retrying as /// necessary until an acknowledgement has been received or the executor /// is terminated (in which case, a TASK_LOST status update will be /// sent). See `Scheduler::status_update` for more information about /// status update acknowledgements. fn send_status_update( &self, task_status: &pb::TaskStatus) -> i32; /// Sends a message to the framework scheduler. These messages are best /// effort; do not expect a framework message to be retransmitted in /// any reliable fashion. fn send_framework_message( &self, data: &Vec<u8>) -> i32; }
use serde::{Deserialize, Serialize}; use super::name::Name; #[derive(Serialize, Deserialize, Debug)] pub struct PermissionLevel { pub actor: Name, pub permission: Name, }
extern crate clear_on_drop; extern crate libsecp256k1; extern crate quickcheck; extern crate rand; extern crate secp256k1; #[macro_use(quickcheck)] extern crate quickcheck_macros; use libsecp256k1::curve::*; use libsecp256k1::schnorr::{schnorr_verify, SchnorrSignature}; use libsecp256k1::*; use rand::thread_rng; use secp256k1::ecdh::SharedSecret as SecpSharedSecret; use secp256k1::key; use secp256k1::schnorrsig::{ schnorr_sign as secp_schnorr_sign, schnorr_verify as secp_schnorr_verify, }; use secp256k1::{ Error as SecpError, Message as SecpMessage, RecoverableSignature as SecpRecoverableSignature, RecoveryId as SecpRecoveryId, Secp256k1, Signature as SecpSignature, Signing, }; use std::cmp::min; #[quickcheck] fn test_schnorr_verify(msg: Vec<u8>) -> bool { let secp256k1 = Secp256k1::new(); let mut message_arr = [5u8; 32]; for i in 0..min(32, msg.len()) { message_arr[i] = msg[i]; } let (privkey, pubkey) = secp256k1.generate_keypair(&mut thread_rng()); let message = SecpMessage::from_slice(&message_arr).unwrap(); let schnorrsig = secp_schnorr_sign(&secp256k1, &message, &privkey).0; assert!(secp_schnorr_verify(&secp256k1, &message, &schnorrsig, &pubkey).is_ok()); let schnorrsig_arr = schnorrsig.serialize_default(); assert_eq!(schnorrsig_arr.len(), 64); let ctx_schnorrsig = SchnorrSignature::parse(&schnorrsig_arr); let pubkey_arr = pubkey.serialize_uncompressed(); assert_eq!(pubkey_arr.len(), 65); let mut pubkey_a = [0u8; 65]; for i in 0..65 { pubkey_a[i] = pubkey_arr[i]; } let ctx_pubkey = PublicKey::parse(&pubkey_a).unwrap(); let ctx_message = Message::parse(&message_arr); schnorr_verify(&ctx_message, &ctx_schnorrsig, &ctx_pubkey) } #[quickcheck] fn test_schnorr_fail_incorrect(msg: Vec<u8>) -> bool { let secp256k1 = Secp256k1::new(); let mut message_arr = [5u8; 32]; for i in 0..min(32, msg.len()) { message_arr[i] = msg[i]; } let (privkey, _) = secp256k1.generate_keypair(&mut thread_rng()); let (_, wrong_pubkey) = secp256k1.generate_keypair(&mut thread_rng()); let message = SecpMessage::from_slice(&message_arr).unwrap(); let schnorrsig = secp_schnorr_sign(&secp256k1, &message, &privkey).0; assert!(!secp_schnorr_verify(&secp256k1, &message, &schnorrsig, &wrong_pubkey).is_ok()); let schnorrsig_arr = schnorrsig.serialize_default(); assert_eq!(schnorrsig_arr.len(), 64); let ctx_schnorrsig = SchnorrSignature::parse(&schnorrsig_arr); let pubkey_arr = wrong_pubkey.serialize_uncompressed(); assert_eq!(pubkey_arr.len(), 65); let mut pubkey_a = [0u8; 65]; for i in 0..65 { pubkey_a[i] = pubkey_arr[i]; } let ctx_pubkey = PublicKey::parse(&pubkey_a).unwrap(); let ctx_message = Message::parse(&message_arr); !schnorr_verify(&ctx_message, &ctx_schnorrsig, &ctx_pubkey) } #[quickcheck] fn test_verify(msg: Vec<u8>) -> bool { let secp256k1 = Secp256k1::new(); let mut message_arr = [5u8; 32]; for i in 0..min(32, msg.len()) { message_arr[i] = msg[i]; } let (privkey, pubkey) = secp256k1.generate_keypair(&mut thread_rng()); let message = SecpMessage::from_slice(&message_arr).unwrap(); let signature = secp256k1.sign(&message, &privkey); let pubkey_arr = pubkey.serialize_uncompressed(); assert_eq!(pubkey_arr.len(), 65); let mut pubkey_a = [0u8; 65]; for i in 0..65 { pubkey_a[i] = pubkey_arr[i]; } let ctx_pubkey = PublicKey::parse(&pubkey_a).unwrap(); let ctx_message = Message::parse(&message_arr); let signature_arr = signature.serialize_compact(); assert_eq!(signature_arr.len(), 64); let mut signature_a = [0u8; 64]; for i in 0..64 { signature_a[i] = signature_arr[i]; } let ctx_sig = Signature::parse(&signature_a); secp256k1.verify(&message, &signature, &pubkey).unwrap(); let mut f_ctx_sig = ctx_sig.clone(); f_ctx_sig.r.set_int(0); if f_ctx_sig.r != ctx_sig.r { assert!(!ECMULT_CONTEXT.verify_raw( &f_ctx_sig.r, &ctx_sig.s, &ctx_pubkey.clone().into(), &ctx_message.0 )); } f_ctx_sig.r.set_int(1); if f_ctx_sig.r != ctx_sig.r { assert!(!ECMULT_CONTEXT.verify_raw( &f_ctx_sig.r, &ctx_sig.s, &ctx_pubkey.clone().into(), &ctx_message.0 )); } verify(&ctx_message, &ctx_sig, &ctx_pubkey) } #[test] fn secret_clear_on_drop() { let secret: [u8; 32] = [1; 32]; let mut seckey = SecretKey::parse(&secret).unwrap(); clear_on_drop::clear::Clear::clear(&mut seckey); assert_eq!(seckey, SecretKey::default()); } #[test] fn test_recover() { let secp256k1 = Secp256k1::new(); let message_arr = [5u8; 32]; let (privkey, pubkey) = secp256k1.generate_keypair(&mut thread_rng()); let message = SecpMessage::from_slice(&message_arr).unwrap(); let signature = secp256k1.sign_recoverable(&message, &privkey); let pubkey_arr = pubkey.serialize_uncompressed(); assert_eq!(pubkey_arr.len(), 65); let mut pubkey_a = [0u8; 65]; for i in 0..65 { pubkey_a[i] = pubkey_arr[i]; } let ctx_message = Message::parse(&message_arr); let (rec_id, signature_arr) = signature.serialize_compact(); assert_eq!(signature_arr.len(), 64); let mut signature_a = [0u8; 64]; for i in 0..64 { signature_a[i] = signature_arr[i]; } let ctx_sig = Signature::parse(&signature_a); // secp256k1.recover(&message, &signature).unwrap(); let ctx_pubkey = recover( &ctx_message, &ctx_sig, &RecoveryId::parse(rec_id.to_i32() as u8).unwrap(), ) .unwrap(); let sp = ctx_pubkey.serialize(); let sps: &[u8] = &sp; let gps: &[u8] = &pubkey_a; assert_eq!(sps, gps); } #[test] fn test_signature_der() { let secp256k1 = Secp256k1::new(); let message_arr = [5u8; 32]; let (privkey, _) = secp256k1.generate_keypair(&mut thread_rng()); assert!(privkey[..].len() == 32); let mut privkey_a = [0u8; 32]; for i in 0..32 { privkey_a[i] = privkey[i]; } let ctx_privkey = SecretKey::parse(&privkey_a).unwrap(); let ctx_message = Message::parse(&message_arr); let (signature, _) = sign(&ctx_message, &ctx_privkey).unwrap(); let reconstructed = Signature::parse_der(signature.serialize_der().as_ref()).unwrap(); assert_eq!(signature, reconstructed); } fn from_hex(hex: &str, target: &mut [u8]) -> Result<usize, ()> { if hex.len() % 2 == 1 || hex.len() > target.len() * 2 { return Err(()); } let mut b = 0; let mut idx = 0; for c in hex.bytes() { b <<= 4; match c { b'A'...b'F' => b |= c - b'A' + 10, b'a'...b'f' => b |= c - b'a' + 10, b'0'...b'9' => b |= c - b'0', _ => return Err(()), } if (idx & 1) == 1 { target[idx / 2] = b; b = 0; } idx += 1; } Ok(idx / 2) } macro_rules! hex { ($hex:expr) => {{ let mut result = vec![0; $hex.len() / 2]; from_hex($hex, &mut result).expect("valid hex string"); result }}; } #[test] fn test_signature_der_lax() { macro_rules! check_lax_sig { ($hex:expr) => {{ let sig = hex!($hex); assert!(Signature::parse_der_lax(&sig[..]).is_ok()); }}; } check_lax_sig!("304402204c2dd8a9b6f8d425fcd8ee9a20ac73b619906a6367eac6cb93e70375225ec0160220356878eff111ff3663d7e6bf08947f94443845e0dcc54961664d922f7660b80c"); check_lax_sig!("304402202ea9d51c7173b1d96d331bd41b3d1b4e78e66148e64ed5992abd6ca66290321c0220628c47517e049b3e41509e9d71e480a0cdc766f8cdec265ef0017711c1b5336f"); check_lax_sig!("3045022100bf8e050c85ffa1c313108ad8c482c4849027937916374617af3f2e9a881861c9022023f65814222cab09d5ec41032ce9c72ca96a5676020736614de7b78a4e55325a"); check_lax_sig!("3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45"); check_lax_sig!("3046022100eaa5f90483eb20224616775891397d47efa64c68b969db1dacb1c30acdfc50aa022100cf9903bbefb1c8000cf482b0aeeb5af19287af20bd794de11d82716f9bae3db1"); check_lax_sig!("3045022047d512bc85842ac463ca3b669b62666ab8672ee60725b6c06759e476cebdc6c102210083805e93bd941770109bcc797784a71db9e48913f702c56e60b1c3e2ff379a60"); check_lax_sig!("3044022023ee4e95151b2fbbb08a72f35babe02830d14d54bd7ed1320e4751751d1baa4802206235245254f58fd1be6ff19ca291817da76da65c2f6d81d654b5185dd86b8acf"); } #[test] fn test_low_s() { // nb this is a transaction on testnet // txid 8ccc87b72d766ab3128f03176bb1c98293f2d1f85ebfaf07b82cc81ea6891fa9 // input number 3 let sig = hex!("3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45"); let pk = hex!("031ee99d2b786ab3b0991325f2de8489246a6a3fdb700f6d0511b1d80cf5f4cd43"); let msg = hex!("a4965ca63b7d8562736ceec36dfa5a11bf426eb65be8ea3f7a49ae363032da0d"); let secp = Secp256k1::new(); let mut sig = Signature::parse_der(&sig[..]).unwrap(); let pk = key::PublicKey::from_slice(&pk[..]).unwrap(); let msg = SecpMessage::from_slice(&msg[..]).unwrap(); // without normalization we expect this will fail assert_eq!( secp.verify( &msg, &SecpSignature::from_compact(&sig.serialize()).unwrap(), &pk ), Err(SecpError::IncorrectSignature) ); // after normalization it should pass sig.normalize_s(); assert_eq!( secp.verify( &msg, &SecpSignature::from_compact(&sig.serialize()).unwrap(), &pk ), Ok(()) ); } #[test] fn test_convert_key1() { let secret: [u8; 32] = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, ]; let expected: &[u8] = &[ 0x04, 0x79, 0xbe, 0x66, 0x7e, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xce, 0x87, 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xce, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, 0x17, 0x98, 0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65, 0x5d, 0xa4, 0xfb, 0xfc, 0x0e, 0x11, 0x08, 0xa8, 0xfd, 0x17, 0xb4, 0x48, 0xa6, 0x85, 0x54, 0x19, 0x9c, 0x47, 0xd0, 0x8f, 0xfb, 0x10, 0xd4, 0xb8, ]; let seckey = SecretKey::parse(&secret).unwrap(); let pubkey = PublicKey::from_secret_key(&seckey); assert_eq!(expected, &pubkey.serialize()[..]); let pubkey_compressed = PublicKey::parse_compressed(&pubkey.serialize_compressed()).unwrap(); assert_eq!(expected, &pubkey_compressed.serialize()[..]); } #[test] fn test_convert_key2() { let secret: [u8; 32] = [ 0x4d, 0x5d, 0xb4, 0x10, 0x7d, 0x23, 0x7d, 0xf6, 0xa3, 0xd5, 0x8e, 0xe5, 0xf7, 0x0a, 0xe6, 0x3d, 0x73, 0xd7, 0x65, 0x8d, 0x40, 0x26, 0xf2, 0xee, 0xfd, 0x2f, 0x20, 0x4c, 0x81, 0x68, 0x2c, 0xb7, ]; let expected: &[u8] = &[ 0x04, 0x3f, 0xa8, 0xc0, 0x8c, 0x65, 0xa8, 0x3f, 0x6b, 0x4e, 0xa3, 0xe0, 0x4e, 0x1c, 0xc7, 0x0c, 0xbe, 0x3c, 0xd3, 0x91, 0x49, 0x9e, 0x3e, 0x05, 0xab, 0x7d, 0xed, 0xf2, 0x8a, 0xff, 0x9a, 0xfc, 0x53, 0x82, 0x00, 0xff, 0x93, 0xe3, 0xf2, 0xb2, 0xcb, 0x50, 0x29, 0xf0, 0x3c, 0x7e, 0xbe, 0xe8, 0x20, 0xd6, 0x3a, 0x4c, 0x5a, 0x95, 0x41, 0xc8, 0x3a, 0xce, 0xbe, 0x29, 0x3f, 0x54, 0xca, 0xcf, 0x0e, ]; let seckey = SecretKey::parse(&secret).unwrap(); let pubkey = PublicKey::from_secret_key(&seckey); assert_eq!(expected, &pubkey.serialize()[..]); let pubkey_compressed = PublicKey::parse_compressed(&pubkey.serialize_compressed()).unwrap(); assert_eq!(expected, &pubkey_compressed.serialize()[..]); } #[test] fn test_convert_anykey() { let secp256k1 = Secp256k1::new(); let (secp_privkey, secp_pubkey) = secp256k1.generate_keypair(&mut thread_rng()); let mut secret = [0u8; 32]; for i in 0..32 { secret[i] = secp_privkey[i]; } let seckey = SecretKey::parse(&secret).unwrap(); let pubkey = PublicKey::from_secret_key(&seckey); let public = pubkey.serialize(); let public_compressed = pubkey.serialize_compressed(); let pubkey_r: &[u8] = &public; let pubkey_compressed_r: &[u8] = &public_compressed; let secp_pubkey_arr = secp_pubkey.serialize_uncompressed(); assert_eq!(secp_pubkey_arr.len(), 65); let secp_pubkey_compressed_arr = secp_pubkey.serialize(); assert_eq!(secp_pubkey_compressed_arr.len(), 33); let mut secp_pubkey_a = [0u8; 65]; for i in 0..65 { secp_pubkey_a[i] = secp_pubkey_arr[i]; } let mut secp_pubkey_compressed_a = [0u8; 33]; for i in 0..33 { secp_pubkey_compressed_a[i] = secp_pubkey_compressed_arr[i]; } let secp_pubkey_r: &[u8] = &secp_pubkey_a; let secp_pubkey_compressed_r: &[u8] = &secp_pubkey_compressed_a; assert_eq!(secp_pubkey_r, pubkey_r); assert_eq!(secp_pubkey_compressed_r, pubkey_compressed_r); } #[test] fn test_sign_verify() { let secp256k1 = Secp256k1::new(); let message_arr = [6u8; 32]; let (secp_privkey, secp_pubkey) = secp256k1.generate_keypair(&mut thread_rng()); let secp_message = SecpMessage::from_slice(&message_arr).unwrap(); let pubkey_arr = secp_pubkey.serialize_uncompressed(); assert_eq!(pubkey_arr.len(), 65); let mut pubkey_a = [0u8; 65]; for i in 0..65 { pubkey_a[i] = pubkey_arr[i]; } let pubkey = PublicKey::parse(&pubkey_a).unwrap(); let mut seckey_a = [0u8; 32]; for i in 0..32 { seckey_a[i] = secp_privkey[i]; } let seckey = SecretKey::parse(&seckey_a).unwrap(); let message = Message::parse(&message_arr); let (sig, recid) = sign(&message, &seckey).unwrap(); // Self verify assert!(verify(&message, &sig, &pubkey)); // Self recover let recovered_pubkey = recover(&message, &sig, &recid).unwrap(); let rpa = recovered_pubkey.serialize(); let opa = pubkey.serialize(); let rpr: &[u8] = &rpa; let opr: &[u8] = &opa; assert_eq!(rpr, opr); let signature_a = sig.serialize(); let secp_recid = SecpRecoveryId::from_i32(recid.into()).unwrap(); let secp_rec_signature = SecpRecoverableSignature::from_compact(&signature_a, secp_recid).unwrap(); let secp_signature = SecpSignature::from_compact(&signature_a).unwrap(); // External verify secp256k1 .verify(&secp_message, &secp_signature, &secp_pubkey) .unwrap(); // External recover let recovered_pubkey = secp256k1 .recover(&secp_message, &secp_rec_signature) .unwrap(); let rpa = recovered_pubkey.serialize_uncompressed(); let rpr: &[u8] = &rpa; assert_eq!(rpr, opr); } #[test] fn test_failing_sign_verify() { let seckey_a: [u8; 32] = [ 169, 195, 92, 103, 2, 159, 75, 46, 158, 79, 249, 49, 208, 28, 48, 210, 5, 47, 136, 77, 21, 51, 224, 54, 213, 165, 90, 122, 233, 199, 0, 248, ]; let seckey = SecretKey::parse(&seckey_a).unwrap(); let pubkey = PublicKey::from_secret_key(&seckey); let message_arr = [6u8; 32]; let message = Message::parse(&message_arr); let (sig, recid) = sign(&message, &seckey).unwrap(); let tmp: u8 = recid.into(); assert_eq!(tmp, 1u8); let recovered_pubkey = recover(&message, &sig, &recid).unwrap(); let rpa = recovered_pubkey.serialize(); let opa = pubkey.serialize(); let rpr: &[u8] = &rpa; let opr: &[u8] = &opa; assert_eq!(rpr, opr); } fn genkey<C: Signing>( secp256k1: &Secp256k1<C>, ) -> (key::PublicKey, key::SecretKey, PublicKey, SecretKey) { let (secp_privkey, secp_pubkey) = secp256k1.generate_keypair(&mut thread_rng()); let pubkey_arr = secp_pubkey.serialize_uncompressed(); assert_eq!(pubkey_arr.len(), 65); let mut pubkey_a = [0u8; 65]; for i in 0..65 { pubkey_a[i] = pubkey_arr[i]; } let pubkey = PublicKey::parse(&pubkey_a).unwrap(); let mut seckey_a = [0u8; 32]; for i in 0..32 { seckey_a[i] = secp_privkey[i]; } let seckey = SecretKey::parse(&seckey_a).unwrap(); (secp_pubkey, secp_privkey, pubkey, seckey) } #[test] fn test_shared_secret() { let secp256k1 = Secp256k1::new(); let (spub1, ssec1, pub1, sec1) = genkey(&secp256k1); let (spub2, ssec2, pub2, sec2) = genkey(&secp256k1); let shared1 = SharedSecret::new(&pub1, &sec2).unwrap(); let shared2 = SharedSecret::new(&pub2, &sec1).unwrap(); let secp_shared1 = SecpSharedSecret::new(&spub1, &ssec2); let secp_shared2 = SecpSharedSecret::new(&spub2, &ssec1); assert_eq!(shared1, shared2); for i in 0..32 { assert_eq!(shared1.as_ref()[i], secp_shared1[i]); } for i in 0..32 { assert_eq!(shared2.as_ref()[i], secp_shared2[i]); } } #[test] fn test_pubkey_combine() { let pk1 = PublicKey::parse(&[ 4, 126, 60, 36, 91, 73, 177, 194, 111, 11, 3, 99, 246, 204, 86, 122, 109, 85, 28, 43, 169, 243, 35, 76, 152, 90, 76, 241, 17, 108, 232, 215, 115, 15, 19, 23, 164, 151, 43, 28, 44, 59, 141, 167, 134, 112, 105, 251, 15, 193, 183, 224, 238, 154, 204, 230, 163, 216, 235, 112, 77, 239, 98, 135, 132, ]) .unwrap(); let pk2 = PublicKey::parse(&[ 4, 40, 127, 167, 223, 38, 53, 6, 223, 67, 83, 204, 60, 226, 227, 107, 231, 172, 34, 3, 187, 79, 112, 167, 0, 217, 118, 69, 218, 189, 208, 150, 190, 54, 186, 220, 95, 80, 220, 183, 202, 117, 160, 18, 84, 245, 181, 23, 32, 51, 73, 178, 173, 92, 118, 92, 122, 83, 49, 54, 195, 194, 16, 229, 39, ]) .unwrap(); let cpk = PublicKey::parse(&[ 4, 101, 166, 20, 152, 34, 76, 121, 113, 139, 80, 13, 92, 122, 96, 38, 194, 205, 149, 93, 19, 147, 132, 195, 173, 42, 86, 26, 221, 170, 127, 180, 168, 145, 21, 75, 45, 248, 90, 114, 118, 62, 196, 194, 143, 245, 204, 184, 16, 175, 202, 175, 228, 207, 112, 219, 94, 237, 75, 105, 186, 56, 102, 46, 147, ]) .unwrap(); assert_eq!(PublicKey::combine(&[pk1, pk2]).unwrap(), cpk); }
use std::time::Duration; use async_trait::async_trait; use std::future::Future; use tokio::time::error::Elapsed; /// An extension trait to add wall-clock execution timeouts to a future running /// in a tokio runtime. /// /// Uses [tokio::time::timeout] internally to apply the timeout. #[async_trait] pub trait FutureTimeout: Future + Sized { /// Wraps `self` returning the result, or panicking if the future hasn't /// completed after `d` length of time. /// /// # Safety /// /// This method panics if `d` elapses before the task rejoins. #[track_caller] async fn with_timeout_panic(mut self, d: Duration) -> <Self as Future>::Output { self.with_timeout(d) .await .expect("timeout waiting for task to join") } /// Wraps `self` returning the result, or an error if the future hasn't /// completed after `d` length of time. #[track_caller] async fn with_timeout(mut self, d: Duration) -> Result<<Self as Future>::Output, Elapsed> { tokio::time::timeout(d, self).await } } impl<F> FutureTimeout for F where F: Future {} #[cfg(test)] mod tests { use tokio::sync::oneshot; use super::*; #[tokio::test] #[should_panic(expected = "timeout")] async fn test_exceeded_panic() { let (_tx, rx) = oneshot::channel::<()>(); let task = tokio::spawn(rx); let _ = task.with_timeout_panic(Duration::from_millis(1)).await; } #[tokio::test] async fn test_exceeded() { let (_tx, rx) = oneshot::channel::<()>(); let task = tokio::spawn(rx); let _ = task .with_timeout(Duration::from_millis(1)) .await .expect_err("should time out"); } }
use serde::de::Error as SerdeError; use serde::{Deserialize, Deserializer}; use alacritty_config_derive::{ConfigDeserialize, SerdeReplace}; /// Maximum scrollback amount configurable. pub const MAX_SCROLLBACK_LINES: u32 = 100_000; /// Struct for scrolling related settings. #[derive(ConfigDeserialize, Copy, Clone, Debug, PartialEq, Eq)] pub struct Scrolling { pub multiplier: u8, history: ScrollingHistory, } impl Default for Scrolling { fn default() -> Self { Self { multiplier: 3, history: Default::default() } } } impl Scrolling { pub fn history(self) -> u32 { self.history.0 } // Update the history size, used in ref tests. pub fn set_history(&mut self, history: u32) { self.history = ScrollingHistory(history); } } #[derive(SerdeReplace, Copy, Clone, Debug, PartialEq, Eq)] struct ScrollingHistory(u32); impl Default for ScrollingHistory { fn default() -> Self { Self(10_000) } } impl<'de> Deserialize<'de> for ScrollingHistory { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let lines = u32::deserialize(deserializer)?; if lines > MAX_SCROLLBACK_LINES { Err(SerdeError::custom(format!( "exceeded maximum scrolling history ({lines}/{MAX_SCROLLBACK_LINES})" ))) } else { Ok(Self(lines)) } } }
extern crate csv; extern crate rustc_serialize; pub mod fileformat; pub mod types;
fn main() { let db = std::fs::read_to_string("input") .unwrap() .trim() .lines() .map(|line| { let mut tokens = line.split([':', '-', '"', ' ',].as_ref()); let low = tokens.next().unwrap().parse::<usize>().unwrap(); let high = tokens.next().unwrap().parse::<usize>().unwrap(); let letter = tokens.next().unwrap().chars().next().unwrap(); tokens.next().unwrap(); let pwd = tokens.next().unwrap().to_string(); (low, high, letter, pwd) }) .collect::<Vec<_>>(); let part_1 = db .iter() .filter(|&(low, high, letter, pwd)| { let count = pwd.chars().filter(|c| letter == c).count(); &count >= low && &count <= high }) .count(); dbg!(part_1); let part_2 = db .iter() .filter(|&(low, high, letter, pwd)| { (pwd.chars().nth(low - 1).unwrap() == *letter) ^ (pwd.chars().nth(high - 1).unwrap() == *letter) }) .count(); dbg!(part_2); }
pub mod bubble; pub mod gnome; pub mod quicksort; pub mod insert; pub mod select; pub mod merge; pub mod quick3; macro_rules! sorting_test { ($($name:ident: $algorithm:expr,)*) => { $( #[cfg(test)] mod $name { #[test] fn should_sort_sorted() { let expected = vec![4, 8, 15, 16, 23, 42]; let elements = vec![4, 8, 15, 16, 23, 42]; let sorted = $algorithm(&elements); assert_eq!(sorted, expected); } #[test] fn should_sort_random_sorted() { let expected = vec![4, 8, 15, 16, 23, 42]; let elements = vec![23, 4, 16, 15, 8, 42]; let sorted = $algorithm(&elements); assert_eq!(sorted, expected); } #[test] fn should_sort_nearly_sorted() { let expected = vec![4, 8, 15, 16, 23, 42]; let elements = vec![8, 4, 15, 23, 16, 42]; let sorted = $algorithm(&elements); assert_eq!(sorted, expected); } #[test] fn should_sort_reversed() { let expected = vec![4, 8, 15, 16, 23, 42]; let elements = vec![42, 23, 16, 15, 8, 4]; let sorted = $algorithm(&elements); assert_eq!(sorted, expected); } #[test] fn should_sort_few_unique() { let expected = vec![8, 8, 23, 23, 42, 42]; let elements = vec![42, 23, 8, 23, 8, 42]; let sorted = $algorithm(&elements); assert_eq!(sorted, expected); } } )* } } sorting_test! { bubble_sort: super::bubble::sort, gnome_sort: super::gnome::sort, quick_sort: super::quicksort::sort, three_way_quick_sort: super::quick3::sort, insert_sort: super::insert::sort, select_sort: super::select::sort, merge_top_down_sort: super::merge::top_down::sort, merge_bottom_up_sort: super::merge::bottom_up::sort, }
use crate::nat_type::{Inc, Nat, N0}; pub trait Comparison { type Neg: Comparison; const VALUE: i8; } pub struct LessThan; pub struct GreaterThan; pub struct Equal; impl Comparison for LessThan { type Neg = GreaterThan; const VALUE: i8 = -1; } impl Comparison for GreaterThan { type Neg = LessThan; const VALUE: i8 = 1; } impl Comparison for Equal { type Neg = Self; const VALUE: i8 = 0; } pub trait Cmp<T1: Nat> { type Result: Comparison; } impl Cmp<N0> for N0 { type Result = Equal; } impl<T: Nat> Cmp<N0> for Inc<T> { type Result = GreaterThan; } impl<T: Nat> Cmp<Inc<T>> for N0 { type Result = LessThan; } impl<T1: Nat + Cmp<T2>, T2: Nat> Cmp<Inc<T2>> for Inc<T1> { type Result = <T1 as Cmp<T2>>::Result; } pub trait Max<T1: Nat> { type Max: Nat; } impl<T: Nat + Cmp<T1>, T1: Nat> Max<T1> for T where (T, T1, <T as Cmp<T1>>::Result): InnerMax, { type Max = <(T, T1, <T as Cmp<T1>>::Result) as InnerMax>::Result; } pub trait Min<T1: Nat> { type Min: Nat; } impl<T: Nat + Cmp<T1>, T1: Nat> Min<T1> for T where (T, T1, <<T as Cmp<T1>>::Result as Comparison>::Neg): InnerMax, { type Min = <(T, T1, <<T as Cmp<T1>>::Result as Comparison>::Neg) as InnerMax>::Result; } pub trait InnerMax { type Result: Nat; } impl<T1: Nat, T2: Nat> InnerMax for (T1, T2, LessThan) { type Result = T2; } impl<T1: Nat, T2: Nat> InnerMax for (T1, T2, Equal) { type Result = T1; } impl<T1: Nat, T2: Nat> InnerMax for (T1, T2, GreaterThan) { type Result = T1; } // This does not work because of conflicting implementations. // Workaround from: https://stackoverflow.com/questions/40392524/conflicting-trait-implementations-even-though-associated-types-differ // // impl<T1: Nat + Cmp<T2, Result = GreaterThan>, T2: Nat> Max<T2> for T1 { // type Max = T1; // } // // impl<T1: Nat + Cmp<T2, Result = Equal>, T2: Nat> Max<T2> for T1 { // type Max = T1; // } // // impl<T1: Nat + Cmp<T2, Result = LessThan>, T2: Nat> Max<T2> for T1 { // type Max = T2; // }
#[macro_use] extern crate serde_derive; extern crate toml; extern crate i3ipc; use std::collections::BTreeMap; use std::{fs, env}; use i3ipc::{I3Connection, I3EventListener, Subscription}; use i3ipc::reply::NodeType; use i3ipc::event::{Event, WindowEventInfo, inner::WindowChange}; #[derive(Debug, Deserialize)] struct Config { #[serde(rename = "default-gamma")] default_gamma: BTreeMap<String, f32>, #[serde(rename = "window")] windows: Vec<WindowConfig> } #[derive(Debug, Deserialize)] struct WindowConfig { title: String, gamma: BTreeMap<String, f32> } fn main() { let args = env::args().collect::<Vec<_>>(); let config_filename = args.get(1).expect("configuration file name not provided"); let config_file = fs::read_to_string(config_filename).expect("cannot open configuration"); let config: Config = toml::from_str(&config_file).expect("cannot parse configuration"); let mut connection = I3Connection::connect().expect("cannot connect to i3"); let mut listener = I3EventListener::connect().expect("cannot listen for i3 events"); listener.subscribe(&[Subscription::Window]).expect("cannot subscribe to i3 events"); for event in listener.listen() { match event.expect("cannot receive i3 events") { Event::WindowEvent(WindowEventInfo { change: WindowChange::Focus, .. }) => { let mut tree = &connection.get_tree().expect("cannot request i3 node tree"); let mut output = None; while !tree.focused { if tree.nodetype == NodeType::Output { output = tree.name.as_ref(); } for node in tree.nodes.iter().chain(tree.floating_nodes.iter()) { if node.id == tree.focus[0] { tree = &node; break } } } if !tree.focused { continue } let output = output.expect("window does not belong to any output"); println!("output {output} switched to window {title:?}", output=output, title=tree.name); let mut found = false; for window in config.windows.iter() { if tree.name.as_ref().map(|x| x.as_str()) == Some(window.title.as_ref()) { if window.gamma.contains_key(output) { let gamma = window.gamma[output]; println!("output {output} set gamma to {gamma} for {title}", output=output, gamma=gamma, title=window.title); connection .run_command(&format!( "exec xrandr --output {output} \ --gamma {gamma}:{gamma}:{gamma}", output=output, gamma=gamma)) .expect("cannot run xrandr"); found = true; break } } } if !found && config.default_gamma.contains_key(output) { let gamma = config.default_gamma[output]; println!("output {output} set gamma to {gamma} by default", output=output, gamma=gamma); connection .run_command(&format!( "exec xrandr --output {output} --gamma {gamma}:{gamma}:{gamma}", output=output, gamma=gamma)) .expect("cannot run xrandr"); } } _ => () } } }
extern crate byteorder; extern crate libc; #[macro_use] extern crate plugkit; use std::io::{Cursor, Error, ErrorKind}; use byteorder::BigEndian; use plugkit::reader::ByteReader; use plugkit::layer::{Confidence, Layer}; use plugkit::context::Context; use plugkit::worker::Worker; use plugkit::variant::Value; use plugkit::token::Token; use plugkit::attr::ResultValue; fn get_protocol(val: u32) -> Option<(Token, Token)> { match val { 0x02 => Some((token!("[igmp]"), token!("ipv6.protocol.igmp"))), 0x06 => Some((token!("[tcp]"), token!("ipv6.protocol.tcp"))), 0x11 => Some((token!("[udp]"), token!("ipv6.protocol.udp"))), 0x3a => Some((token!("[icmp]"), token!("ipv6.protocol.icmp"))), _ => None, } } struct IPv6Worker {} impl Worker for IPv6Worker { fn analyze(&mut self, ctx: &mut Context, layer: &mut Layer) -> Result<(), Error> { let (slice, payload_range) = { let payload = layer .payloads() .next() .ok_or(Error::new(ErrorKind::Other, "no payload"))?; let slice = payload .slices() .next() .ok_or(Error::new(ErrorKind::Other, "no slice"))?; (slice, payload.range()) }; let child = layer.add_layer(ctx, token!("ipv6")); child.set_confidence(Confidence::Exact); child.add_tag(ctx, token!("ipv6")); child.set_range(&payload_range); (|| -> Result<(), Error> { let mut rdr = Cursor::new(slice); let (header, _) = ByteReader::read_u8(&mut rdr)?; let (header2, _) = ByteReader::read_u8(&mut rdr)?; let version = header >> 4; let traffic_class = (header & 0b00001111 << 4) | ((header2 & 0b11110000) >> 4); { let attr = child.add_attr(ctx, token!("ipv6.version")); attr.set(&version); attr.set_range(&(0..1)); } { let attr = child.add_attr(ctx, token!("ipv6.trafficClass")); attr.set(&traffic_class); attr.set_range(&(0..2)); } let (flow_level, _) = ByteReader::read_u16::<BigEndian>(&mut rdr)?; { let attr = child.add_attr(ctx, token!("ipv6.flowLevel")); attr.set(&(flow_level | ((header2 & 0b00001111) << 16))); attr.set_range(&(1..4)); } { let attr = child.add_attr(ctx, token!("ipv6.payloadLength")); attr.set_with_range(&ByteReader::read_u16::<BigEndian>(&mut rdr)?); } let (mut next_header, mut next_range) = ByteReader::read_u8(&mut rdr)?; { let attr = child.add_attr(ctx, token!("ipv6.nextHeader")); attr.set(&next_header); attr.set_range(&next_range); } { let attr = child.add_attr(ctx, token!("ipv6.hopLimit")); attr.set_with_range(&ByteReader::read_u8(&mut rdr)?); } { child.add_attr_alias(ctx, token!("_.src"), token!("ipv6.src")); let attr = child.add_attr(ctx, token!("ipv6.src")); attr.set_typ(token!("@ipv6:addr")); attr.set_with_range(&ByteReader::read_slice(&mut rdr, 16)?); } { child.add_attr_alias(ctx, token!("_.dst"), token!("ipv6.dst")); let attr = child.add_attr(ctx, token!("ipv6.dst")); attr.set_typ(token!("@ipv6:addr")); attr.set_with_range(&ByteReader::read_slice(&mut rdr, 16)?); } loop { match next_header { // Hop-by-Hop Options, Destination Options 0 | 60 => { let (h, r) = ByteReader::read_u8(&mut rdr)?; next_header = h; next_range = r; let (ext_len, _) = ByteReader::read_u8(&mut rdr)?; let byte_len = (ext_len + 1) * 8; ByteReader::read_slice(&mut rdr, byte_len as usize)?; } // TODO: // case 43 # Routing // case 44 # Fragment // case 51 # Authentication Header // case 50 # Encapsulating Security Payload // case 135 # Mobility // No Next Header 59 => break, _ => break, } } let protocol = next_header; let range = next_range; { let attr = child.add_attr(ctx, token!("ipv6.protocol")); attr.set_typ(token!("@enum")); attr.set(&protocol); attr.set_range(&range); } if let Some(item) = get_protocol(protocol) { let (tag, id) = item; child.add_tag(ctx, tag); let attr = child.add_attr(ctx, id); attr.set(&true); attr.set_typ(token!("@novalue")); attr.set_range(&range); } let (data, range) = ByteReader::read_slice_to_end(&mut rdr)?; let payload = child.add_payload(ctx); let offset = payload_range.start; payload.add_slice(data); payload.set_range(&(range.start + offset..range.end + offset)); Ok(()) })() .or_else(|_| { child.add_error(ctx, token!("!out-of-bounds"), ""); child.set_confidence(Confidence::Probable); Ok(()) }) } } plugkit_module!({}); plugkit_api_layer_hints!(token!("[ipv6]")); plugkit_api_worker!(IPv6Worker, IPv6Worker {});
use crate::compiling::v1::assemble::prelude::*; macro_rules! tuple { ($slf:expr, $variant:ident, $c:ident, $span:expr, $($var:ident),*) => {{ let guard = $c.scopes.push_child($span)?; let mut it = $slf.items.iter(); $( let ($var, _) = it.next().ok_or_else(|| CompileError::new($span, CompileErrorKind::Custom { message: "items ended unexpectedly" }))?; let $var = $var.assemble($c, Needs::Value)?.apply_targeted($c)?; )* $c.asm.push( Inst::$variant { args: [$($var,)*], }, $span, ); $c.scopes.pop(guard, $span)?; }}; } /// Compile a literal tuple. impl Assemble for ast::ExprTuple { fn assemble(&self, c: &mut Compiler<'_>, needs: Needs) -> CompileResult<Asm> { let span = self.span(); log::trace!("ExprTuple => {:?}", c.source.source(span)); if self.items.is_empty() { c.asm.push(Inst::unit(), span); } else { match self.items.len() { 1 => tuple!(self, Tuple1, c, span, e1), 2 => tuple!(self, Tuple2, c, span, e1, e2), 3 => tuple!(self, Tuple3, c, span, e1, e2, e3), 4 => tuple!(self, Tuple4, c, span, e1, e2, e3, e4), _ => { for (expr, _) in &self.items { expr.assemble(c, Needs::Value)?.apply(c)?; c.scopes.decl_anon(expr.span())?; } c.asm.push( Inst::Tuple { count: self.items.len(), }, span, ); c.scopes.undecl_anon(span, self.items.len())?; } } } if !needs.value() { c.diagnostics.not_used(c.source_id, span, c.context()); c.asm.push(Inst::Pop, span); } Ok(Asm::top(span)) } }
use join::Join; use rand::{rngs::SmallRng, RngCore, SeedableRng}; use std::{ alloc, cmp::{self, Ordering}, fmt::{self, Formatter}, ptr, }; struct Node<T> { x: T, priority: u64, parent: *mut Node<T>, left: *mut Node<T>, right: *mut Node<T>, size: usize, } pub struct Treap<T> { n: usize, root: *mut Node<T>, rng: SmallRng, } impl<T> Treap<T> { pub fn new() -> Self { Self { n: 0, root: ptr::null_mut(), rng: SmallRng::seed_from_u64(122333), } } fn gen_priority(&mut self) -> u64 { self.rng.next_u64() } fn rotate_right(&mut self, u: *mut Node<T>) { // u w // | | // +---+---+ +---+---+ // | | | | // w c -> a u // | | // +---+---+ +---+---+ // | | | | // a b b c let w = unsafe { &*u }.left; debug_assert_ne!(w, ptr::null_mut()); let p = unsafe { (*u).parent }; if p == ptr::null_mut() { debug_assert_eq!(self.root, u); self.root = w; unsafe { (*w).parent = ptr::null_mut() }; } else { unsafe { (*w).parent = p }; if unsafe { (*p).left } == u { unsafe { (*p).left = w }; } else { debug_assert_eq!(unsafe { (*p).right }, u); unsafe { (*p).right = w }; } } unsafe { (*u).parent = w }; let b = unsafe { (*w).right }; if b == ptr::null_mut() { unsafe { (*u).left = ptr::null_mut() }; } else { unsafe { (*b).parent = u }; unsafe { (*u).left = b }; } unsafe { (*w).right = u }; unsafe { (*u).size = 1 + Self::node_size(b) + Self::node_size((*u).right) }; unsafe { (*w).size = 1 + Self::node_size((*w).left) + (*u).size }; } fn rotate_left(&mut self, u: *mut Node<T>) { // u w // | | // +---+---+ +---+---+ // | | | | // a w -> u c // | | // +---+---+ +---+---+ // | | | | // b c a b let w = unsafe { &*u }.right; debug_assert_ne!(w, ptr::null_mut()); let p = unsafe { (*u).parent }; if p == ptr::null_mut() { debug_assert_eq!(self.root, u); self.root = w; unsafe { (*w).parent = ptr::null_mut() }; } else { unsafe { (*w).parent = p }; if unsafe { (*p).left } == u { unsafe { (*p).left = w }; } else { debug_assert_eq!(unsafe { (*p).right }, u); unsafe { (*p).right = w }; } } unsafe { (*u).parent = w }; let b = unsafe { (*w).left }; if b == ptr::null_mut() { unsafe { (*u).right = ptr::null_mut() }; } else { unsafe { (*b).parent = u }; unsafe { (*u).right = b }; } unsafe { (*w).left = u }; unsafe { (*u).size = 1 + Self::node_size((*u).left) + Self::node_size(b) }; unsafe { (*w).size = 1 + (*u).size + Self::node_size((*w).right) }; } fn node_size(u: *mut Node<T>) -> usize { if u == ptr::null_mut() { 0 } else { unsafe { &*u }.size } } fn nth_inner(&self, n: usize, u: *mut Node<T>) -> Option<&T> { debug_assert_ne!(u, ptr::null_mut()); let left = unsafe { &*u }.left; let left_size = Self::node_size(left); if left_size == n { Some(&unsafe { &*u }.x) } else if left_size > n { debug_assert_ne!(left, ptr::null_mut()); self.nth_inner(n, left) } else { let right = unsafe { &*u }.right; debug_assert_ne!(right, ptr::null_mut()); self.nth_inner(n - left_size - 1, right) } } } trait SSet<T> { fn size(&self) -> usize; fn add(&mut self, x: T) -> bool; fn remove(&mut self, x: &T) -> bool; fn find(&self, x: &T) -> Option<&T>; fn nth(&self, n: usize) -> Option<&T>; } impl<T> Treap<T> where T: cmp::Ord, { fn find_last(&self, x: &T) -> *mut Node<T> { let mut w = self.root; let mut prev = ptr::null_mut(); while w != ptr::null_mut() { prev = w; match x.cmp(&unsafe { &*w }.x) { Ordering::Less => { w = unsafe { &*w }.left; } Ordering::Greater => { w = unsafe { &*w }.right; } Ordering::Equal => { return w; } } } prev } fn add_child(&mut self, p: *mut Node<T>, x: T) -> *mut Node<T> { let u = if p == ptr::null_mut() { debug_assert_eq!(self.root, ptr::null_mut()); self.root = Box::into_raw(Box::new(Node { x, priority: self.gen_priority(), parent: ptr::null_mut(), left: ptr::null_mut(), right: ptr::null_mut(), size: 1, })); self.root } else { let y = &unsafe { &*p }.x; let ord = x.cmp(y); let u = Box::into_raw(Box::new(Node { x, priority: self.gen_priority(), parent: p, left: ptr::null_mut(), right: ptr::null_mut(), size: 1, })); match ord { Ordering::Less => { debug_assert_eq!(unsafe { &*p }.left, ptr::null_mut()); unsafe { (*p).left = u }; u } Ordering::Greater => { debug_assert_eq!(unsafe { &*p }.right, ptr::null_mut()); unsafe { (*p).right = u }; u } Ordering::Equal => { unreachable!(); } } }; self.n += 1; u } } impl<T> SSet<T> for Treap<T> where T: cmp::Ord, { fn size(&self) -> usize { self.n } fn add(&mut self, x: T) -> bool { let p = self.find_last(&x); if p != ptr::null_mut() && unsafe { &*p }.x.eq(&x) { return false; } let u = self.add_child(p, x); // bubble up loop { let p = unsafe { &*u }.parent; if p == ptr::null_mut() { break; } if unsafe { &*p }.priority < unsafe { &*u }.priority { break; } if unsafe { &*p }.right == u { self.rotate_left(p); } else if unsafe { &*p }.left == u { self.rotate_right(p); } else { unreachable!(); } } if unsafe { &*u }.parent == ptr::null_mut() { self.root = u; } // update size let mut u = u; while u != self.root { unsafe { (*u).size = 1 + Self::node_size((*u).left) + Self::node_size((*u).right) }; u = unsafe { &*u }.parent; } unsafe { (*u).size = 1 + Self::node_size((*u).left) + Self::node_size((*u).right) }; true } fn remove(&mut self, x: &T) -> bool { let u = self.find_last(x); if u == ptr::null_mut() { // 空の状態から削除しようとしたとき return false; } if !unsafe { &*u }.x.eq(x) { return false; } // trickle down loop { let left = unsafe { &*u }.left; let right = unsafe { &*u }.right; if left == ptr::null_mut() && right == ptr::null_mut() { if self.root == u { self.root = ptr::null_mut(); } else { let p = unsafe { &*u }.parent; debug_assert_ne!(p, ptr::null_mut()); if unsafe { &*p }.left == u { unsafe { (*p).left = ptr::null_mut() }; } else if unsafe { &*p }.right == u { unsafe { (*p).right = ptr::null_mut() }; } else { unreachable!(); } // update size let mut v = p; while v != self.root { unsafe { (*v).size = 1 + Self::node_size((*v).left) + Self::node_size((*v).right) }; v = unsafe { &*v }.parent; } unsafe { (*v).size = 1 + Self::node_size((*v).left) + Self::node_size((*v).right) }; } unsafe { ptr::drop_in_place(u) }; unsafe { alloc::dealloc(u as *mut u8, alloc::Layout::new::<Node<T>>()) }; break; } if left == ptr::null_mut() { self.rotate_left(u); } else if right == ptr::null_mut() { self.rotate_right(u); } else if unsafe { &*left }.priority < unsafe { &*right }.priority { self.rotate_right(u); } else { self.rotate_left(u); } } self.n -= 1; true } fn find(&self, x: &T) -> Option<&T> { let mut w = self.root; let mut z = ptr::null_mut(); loop { if w == ptr::null_mut() { break; } let y = &unsafe { &*w }.x; match x.cmp(y) { Ordering::Less => { z = w; w = unsafe { &*w }.left; } Ordering::Greater => { w = unsafe { &*w }.right; } Ordering::Equal => { return Some(y); } } } if z == ptr::null_mut() { None } else { Some(&unsafe { &*z }.x) } } // 0-indexed fn nth(&self, n: usize) -> Option<&T> { if n >= self.size() { None } else { self.nth_inner(n, self.root) } } } impl<T> fmt::Debug for Treap<T> where T: fmt::Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { if self.root == ptr::null_mut() { return Ok(()); } let mut stack = Vec::new(); stack.push((self.root, true, 0)); while let Some((u, first_visit, depth)) = stack.pop() { assert_ne!(u, ptr::null_mut()); if first_visit { stack.push((u, false, depth)); let left = unsafe { &*u }.left; let right = unsafe { &*u }.right; if left != ptr::null_mut() { stack.push((left, true, depth + 1)); } if right != ptr::null_mut() { stack.push((right, true, depth + 1)); } } else { write!( f, "[{:p}] parent = {:p}, left = {:p}, right = {:p}, x = {:?}, priority = {}, size = {}", u, unsafe { &*u }.parent, unsafe { &*u }.left, unsafe { &*u }.right, unsafe { &*u }.x, unsafe { &*u }.priority, unsafe { &*u }.size )?; if u != self.root { writeln!(f)?; } } } Ok(()) } } use proconio::input; fn main() { input! { n: usize, q: usize, names: [String; n], }; let mut set = Treap::new(); for i in 0..n { set.add((names[i].clone(), i)); } for _ in 0..q { input! { x: usize, t: String, }; let (s, i) = set.nth(x - 1).unwrap().clone(); set.remove(&(s, i)); set.add((t, i)); } let mut ans = vec![String::new(); n]; for i in 0..n { let (s, j) = set.nth(i).unwrap().clone(); ans[j] = s; } println!("{}", ans.iter().join(" ")); }
pub mod application; mod window; mod keyboard;
use kincaid::syllables_in_text; use kincaid::WORD_PATTERN; use regex::Regex; use std::collections::HashMap; use std::collections::HashSet; use std::fs; #[macro_use] extern crate lazy_static; const DICTIONARY_PATH: &str = "tests/cmudict.txt"; const PRONUNCIATION_PATTERN: &str = r"((?:[\w\n]+ ?)+)"; const VOWEL_PATTERN: &str = r"\b[AEIOU]"; lazy_static! { pub static ref LINE_REGEX: Regex = Regex::new(&format!("{}.* {}", WORD_PATTERN, PRONUNCIATION_PATTERN)).unwrap(); pub static ref VOWEL_REGEX: Regex = Regex::new(VOWEL_PATTERN).unwrap(); } #[test] fn test_against_cmudict() { // The original encoding of the CMU dictionary on their website is ISO 8859-1 // Save it to UTF-8 when replacing with a new copy let file_contents = fs::read_to_string(DICTIONARY_PATH).expect("Failed to read the dictionary to a string"); let mut word_to_valid_syllable_counts: HashMap<&str, HashSet<usize>> = HashMap::new(); file_contents .lines() .filter_map(|line| extract_word_and_syllable_count(line)) .for_each(|(word, syllable_count)| { word_to_valid_syllable_counts .entry(word) .or_insert(HashSet::new()) .insert(syllable_count); }); let mut mistake_count = 0; for (word, expected_syllables) in word_to_valid_syllable_counts { let predicted_syllables = syllables_in_text(word); if !expected_syllables.contains(&predicted_syllables) { mistake_count += 1; println!( "{}: {:?} (expected) {} (calculated)", word, expected_syllables, predicted_syllables ) } } assert_eq!(mistake_count, 6842); } fn extract_word_and_syllable_count(line: &str) -> Option<(&str, usize)> { let capture = LINE_REGEX.captures(line)?; let word = capture.get(1).unwrap().as_str(); let phonemes = capture.get(2).unwrap().as_str(); let syllables = VOWEL_REGEX.find_iter(phonemes).count(); return Some((word, syllables)); }
use clap::Clap; use std::error::Error; mod show_usb; pub use self::show_usb::*; // From Cargo.toml const PKG_NAME: &str = env!("CARGO_PKG_NAME"); const VERSION: &str = env!("CARGO_PKG_VERSION"); pub(crate) trait SubApp { fn process(&mut self) -> Result<(), Box<dyn Error>>; } #[derive(Clap, Debug)] #[clap(name = PKG_NAME, version = VERSION, about = "Use this tool to manage USB devices")] struct Options { #[clap(subcommand)] commands: SubCommand, } #[derive(Clap, Debug)] enum SubCommand { #[clap(name = "show", about = "Display connected USB devices")] ShowUSB(ShowUSBApp) } #[derive(Debug)] pub struct USBTool { options: Options, } impl USBTool { pub fn new() -> USBTool { USBTool { options: Options::parse() } } pub fn run(&mut self) -> Result<(), Box<dyn Error>> { match &mut self.options.commands { SubCommand::ShowUSB(app) => app.process() } } }
use crate::measure; use std::cmp; use std::io::BufRead; pub fn run(input: impl BufRead) { let trees = read_trees(input); measure::duration(|| { println!("* Part 1: {}", count_visible(&trees)); }); measure::duration(|| { println!("* Part 2: {}", max_scenic_score(&trees)); }); } fn read_trees(input: impl BufRead) -> Vec<Vec<Tree>> { input .lines() .map(|l| l.expect("expected line")) .map(|l| l.chars().map(|h| Tree::from(h)).collect()) .collect() } struct Tree { height: u8, } impl From<char> for Tree { fn from(h: char) -> Self { Tree { height: h as u8 - '0' as u8, } } } fn count_visible(trees: &Vec<Vec<Tree>>) -> usize { trees.iter().enumerate().fold(0, |subtotal, (tr, row)| { row.iter().enumerate().fold(subtotal, |total, (tc, tree)| { if (0..tr).rev().all(|r| trees[r][tc].height < tree.height) { total + 1 } else if (0..tc).rev().all(|c| trees[tr][c].height < tree.height) { total + 1 } else if (tr + 1..trees.len()).all(|r| trees[r][tc].height < tree.height) { total + 1 } else if (tc + 1..row.len()).all(|c| trees[tr][c].height < tree.height) { total + 1 } else { total } }) }) } fn max_scenic_score(trees: &Vec<Vec<Tree>>) -> usize { (0..trees.len()).fold(0, |score, tr| { (0..trees[tr].len()).fold(score, |score, tc| { cmp::max(score, scenic_score(trees, tr, tc)) }) }) } fn scenic_score(trees: &Vec<Vec<Tree>>, tr: usize, tc: usize) -> usize { let tree = &trees[tr][tc]; let n = cmp::min( (0..tr) .rev() .take_while(|&r| trees[r][tc].height < tree.height) .count() + 1, tr, ); let w = cmp::min( (0..tc) .rev() .take_while(|&c| trees[tr][c].height < tree.height) .count() + 1, tc, ); let s = cmp::min( (tr + 1..trees.len()) .take_while(|&r| trees[r][tc].height < tree.height) .count() + 1, trees.len() - tr - 1, ); let e = cmp::min( (tc + 1..trees[tr].len()) .take_while(|&c| trees[tr][c].height < tree.height) .count() + 1, trees[tr].len() - tc - 1, ); n * w * s * e } #[cfg(test)] mod tests { use super::*; const INPUT: &[u8] = b"30373 25512 65332 33549 35390 "; #[test] fn test_read_trees() { let trees = read_trees(INPUT); let trees: Vec<Vec<u8>> = trees .iter() .map(|r| r.iter().map(|t| t.height).collect()) .collect(); assert_eq!( trees, vec![ vec![3, 0, 3, 7, 3], vec![2, 5, 5, 1, 2], vec![6, 5, 3, 3, 2], vec![3, 3, 5, 4, 9], vec![3, 5, 3, 9, 0], ], ); } #[test] fn test_count_visible() { let trees = read_trees(INPUT); assert_eq!(count_visible(&trees), 21); } #[test] fn test_scenic_score() { let trees = read_trees(INPUT); assert_eq!(scenic_score(&trees, 1, 2), 4); assert_eq!(scenic_score(&trees, 3, 2), 8); assert_eq!(scenic_score(&trees, 0, 2), 0); } #[test] fn test_max_scenic_score() { let trees = read_trees(INPUT); assert_eq!(max_scenic_score(&trees), 8); } }
use clap::{Clap, FromArgMatches, IntoApp}; use humansize::{file_size_opts, FileSize}; use std::io::Read; use std::path::PathBuf; mod passes; #[derive(Clap, Debug)] #[clap()] struct CommandLineOpts { /// Input file to optimize. By default will use STDIN. input: Option<PathBuf>, /// Output file. Required. #[clap(short, long)] output: PathBuf, } fn main() { let passes = passes::create(); let mut app = <CommandLineOpts as IntoApp>::into_app(); for pass in &passes { let args = pass.args(); for arg in args.get_arguments() { app = app.arg(arg); } } let matches = app.get_matches(); let opts = <CommandLineOpts as FromArgMatches>::from_arg_matches(&matches); let content = if let Some(i) = opts.input { std::fs::read(&i).expect("Could not read the file.") } else { let mut buff = Vec::new(); std::io::stdin() .read_to_end(&mut buff) .expect("Could not read STDIN."); buff }; eprintln!( "Original: {:>8}", content.len().file_size(file_size_opts::BINARY).unwrap() ); let original_wasm_size = content.len(); let mut wasm_size = content.len(); let mut wasm_back = content; for pass in passes { eprintln!("{}...", pass.description()); let new_wasm = pass.opt(&wasm_back, &matches).expect("Pass failed:"); if new_wasm.len() < wasm_back.len() { wasm_back = new_wasm; eprintln!( " Size: {:>8} ({:3.1}% smaller)", wasm_back.len().file_size(file_size_opts::BINARY).unwrap(), (1.0 - ((wasm_back.len() as f64) / (wasm_size as f64))) * 100.0 ); } else { eprintln!("Pass did not result in smaller WASM... Skipping."); } wasm_size = wasm_back.len(); } eprintln!( "\nFinal Size: {} ({:3.1}% smaller)", wasm_back.len().file_size(file_size_opts::BINARY).unwrap(), (1.0 - ((wasm_back.len() as f64) / (original_wasm_size as f64))) * 100.0 ); std::fs::write(opts.output, wasm_back).expect("Could not write output file."); }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_ast::ast::ExplainKind; use common_catalog::table_context::TableContext; use common_exception::ErrorCode; use common_exception::Result; use common_expression::types::DataType; use common_expression::types::StringType; use common_expression::DataBlock; use common_expression::DataField; use common_expression::DataSchemaRef; use common_expression::DataSchemaRefExt; use common_expression::FromData; use common_profile::ProfSpanSetRef; use common_sql::MetadataRef; use crate::interpreters::Interpreter; use crate::pipelines::executor::ExecutorSettings; use crate::pipelines::executor::PipelineCompleteExecutor; use crate::pipelines::executor::PipelinePullingExecutor; use crate::pipelines::PipelineBuildResult; use crate::schedulers::build_query_pipeline; use crate::schedulers::Fragmenter; use crate::schedulers::QueryFragmentsActions; use crate::sessions::QueryContext; use crate::sql::executor::PhysicalPlan; use crate::sql::executor::PhysicalPlanBuilder; use crate::sql::optimizer::SExpr; use crate::sql::plans::Plan; pub struct ExplainInterpreter { ctx: Arc<QueryContext>, schema: DataSchemaRef, kind: ExplainKind, plan: Plan, } #[async_trait::async_trait] impl Interpreter for ExplainInterpreter { fn name(&self) -> &str { "ExplainInterpreterV2" } fn schema(&self) -> DataSchemaRef { self.schema.clone() } async fn execute2(&self) -> Result<PipelineBuildResult> { let blocks = match &self.kind { ExplainKind::Raw => self.explain_plan(&self.plan)?, ExplainKind::Plan => match &self.plan { Plan::Query { s_expr, metadata, .. } => { let ctx = self.ctx.clone(); let settings = ctx.get_settings(); let enable_distributed_eval_index = settings.get_enable_distributed_eval_index()?; settings.set_enable_distributed_eval_index(false)?; scopeguard::defer! { let _ = settings.set_enable_distributed_eval_index(enable_distributed_eval_index); } let mut builder = PhysicalPlanBuilder::new(metadata.clone(), ctx); let plan = builder.build(s_expr).await?; self.explain_physical_plan(&plan, metadata)? } _ => self.explain_plan(&self.plan)?, }, ExplainKind::JOIN => match &self.plan { Plan::Query { s_expr, metadata, .. } => { let ctx = self.ctx.clone(); let settings = ctx.get_settings(); let enable_distributed_eval_index = settings.get_enable_distributed_eval_index()?; settings.set_enable_distributed_eval_index(false)?; scopeguard::defer! { let _ = settings.set_enable_distributed_eval_index(enable_distributed_eval_index); } let mut builder = PhysicalPlanBuilder::new(metadata.clone(), ctx); let plan = builder.build(s_expr).await?; self.explain_join_order(&plan, metadata)? } _ => Err(ErrorCode::Unimplemented( "Unsupported EXPLAIN JOIN statement", ))?, }, ExplainKind::AnalyzePlan => match &self.plan { Plan::Query { s_expr, metadata, ignore_result, .. } => { let ctx = self.ctx.clone(); let settings = ctx.get_settings(); let enable_distributed_eval_index = settings.get_enable_distributed_eval_index()?; settings.set_enable_distributed_eval_index(false)?; scopeguard::defer! { let _ = settings.set_enable_distributed_eval_index(enable_distributed_eval_index); } self.explain_analyze(s_expr, metadata, *ignore_result) .await? } _ => Err(ErrorCode::Unimplemented( "Unsupported EXPLAIN ANALYZE statement", ))?, }, ExplainKind::Pipeline => match &self.plan { Plan::Query { s_expr, metadata, ignore_result, .. } => { self.explain_pipeline(*s_expr.clone(), metadata.clone(), *ignore_result) .await? } _ => { return Err(ErrorCode::Unimplemented("Unsupported EXPLAIN statement")); } }, ExplainKind::Fragments => match &self.plan { Plan::Query { s_expr, metadata, .. } => { self.explain_fragments(*s_expr.clone(), metadata.clone()) .await? } _ => { return Err(ErrorCode::Unimplemented("Unsupported EXPLAIN statement")); } }, ExplainKind::Graph => { return Err(ErrorCode::Unimplemented( "ExplainKind graph is unimplemented", )); } ExplainKind::Ast(display_string) | ExplainKind::Syntax(display_string) | ExplainKind::Memo(display_string) => { let line_split_result: Vec<&str> = display_string.lines().collect(); let column = StringType::from_data(line_split_result); vec![DataBlock::new_from_columns(vec![column])] } }; PipelineBuildResult::from_blocks(blocks) } } impl ExplainInterpreter { pub fn try_create(ctx: Arc<QueryContext>, plan: Plan, kind: ExplainKind) -> Result<Self> { let data_field = DataField::new("explain", DataType::String); let schema = DataSchemaRefExt::create(vec![data_field]); Ok(ExplainInterpreter { ctx, schema, plan, kind, }) } pub fn explain_plan(&self, plan: &Plan) -> Result<Vec<DataBlock>> { let result = plan.format_indent()?; let line_split_result: Vec<&str> = result.lines().collect(); let formatted_plan = StringType::from_data(line_split_result); Ok(vec![DataBlock::new_from_columns(vec![formatted_plan])]) } pub fn explain_physical_plan( &self, plan: &PhysicalPlan, metadata: &MetadataRef, ) -> Result<Vec<DataBlock>> { let result = plan .format(metadata.clone(), ProfSpanSetRef::default())? .format_pretty()?; let line_split_result: Vec<&str> = result.lines().collect(); let formatted_plan = StringType::from_data(line_split_result); Ok(vec![DataBlock::new_from_columns(vec![formatted_plan])]) } pub fn explain_join_order( &self, plan: &PhysicalPlan, metadata: &MetadataRef, ) -> Result<Vec<DataBlock>> { let result = plan.format_join(metadata)?.format_pretty()?; let line_split_result: Vec<&str> = result.lines().collect(); let formatted_plan = StringType::from_data(line_split_result); Ok(vec![DataBlock::new_from_columns(vec![formatted_plan])]) } pub async fn explain_pipeline( &self, s_expr: SExpr, metadata: MetadataRef, ignore_result: bool, ) -> Result<Vec<DataBlock>> { let mut builder = PhysicalPlanBuilder::new(metadata, self.ctx.clone()); let plan = builder.build(&s_expr).await?; let build_res = build_query_pipeline(&self.ctx, &[], &plan, ignore_result, false).await?; let mut blocks = Vec::with_capacity(1 + build_res.sources_pipelines.len()); // Format root pipeline let line_split_result = format!("{}", build_res.main_pipeline.display_indent()) .lines() .map(|s| s.as_bytes().to_vec()) .collect::<Vec<_>>(); let column = StringType::from_data(line_split_result); blocks.push(DataBlock::new_from_columns(vec![column])); // Format child pipelines for pipeline in build_res.sources_pipelines.iter() { let line_split_result = format!("\n{}", pipeline.display_indent()) .lines() .map(|s| s.as_bytes().to_vec()) .collect::<Vec<_>>(); let column = StringType::from_data(line_split_result); blocks.push(DataBlock::new_from_columns(vec![column])); } Ok(blocks) } async fn explain_fragments( &self, s_expr: SExpr, metadata: MetadataRef, ) -> Result<Vec<DataBlock>> { let ctx = self.ctx.clone(); let plan = PhysicalPlanBuilder::new(metadata.clone(), self.ctx.clone()) .build(&s_expr) .await?; let root_fragment = Fragmenter::try_create(ctx.clone())?.build_fragment(&plan)?; let mut fragments_actions = QueryFragmentsActions::create(ctx.clone()); root_fragment.get_actions(ctx, &mut fragments_actions)?; let display_string = fragments_actions.display_indent(&metadata).to_string(); let line_split_result = display_string .lines() .map(|s| s.as_bytes().to_vec()) .collect::<Vec<_>>(); let formatted_plan = StringType::from_data(line_split_result); Ok(vec![DataBlock::new_from_columns(vec![formatted_plan])]) } async fn explain_analyze( &self, s_expr: &SExpr, metadata: &MetadataRef, ignore_result: bool, ) -> Result<Vec<DataBlock>> { let mut builder = PhysicalPlanBuilder::new(metadata.clone(), self.ctx.clone()); let plan = builder.build(s_expr).await?; let mut build_res = build_query_pipeline(&self.ctx, &[], &plan, ignore_result, true).await?; let prof_span_set = build_res.prof_span_set.clone(); let settings = self.ctx.get_settings(); let query_id = self.ctx.get_id(); build_res.set_max_threads(settings.get_max_threads()? as usize); let settings = ExecutorSettings::try_create(&settings, query_id)?; // Drain the data if build_res.main_pipeline.is_complete_pipeline()? { let mut pipelines = build_res.sources_pipelines; pipelines.push(build_res.main_pipeline); let complete_executor = PipelineCompleteExecutor::from_pipelines(pipelines, settings)?; complete_executor.execute()?; } else { let mut pulling_executor = PipelinePullingExecutor::from_pipelines(build_res, settings)?; pulling_executor.start(); while (pulling_executor.pull_data()?).is_some() {} } let result = plan .format(metadata.clone(), prof_span_set)? .format_pretty()?; let line_split_result: Vec<&str> = result.lines().collect(); let formatted_plan = StringType::from_data(line_split_result); Ok(vec![DataBlock::new_from_columns(vec![formatted_plan])]) } }
//! Unwinding for targets without unwind support //! //! Since we can't raise exceptions on these platforms, they simply abort use core::intrinsics; use super::ErlangPanic; pub unsafe fn cause(_ptr: *mut u8) -> *mut ErlangPanic { intrinsics::abort() } pub unsafe fn cleanup(_ptr: *mut u8) { intrinsics::abort() } pub unsafe fn panic(_data: *mut ErlangPanic) -> u32 { intrinsics::abort() }
// 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::str; use common_exception::Result; use super::table_test_fixture::append_sample_data; use super::table_test_fixture::append_sample_data_overwrite; use super::table_test_fixture::check_data_dir; use super::table_test_fixture::execute_command; use super::table_test_fixture::history_should_have_item; use super::table_test_fixture::TestFixture; pub enum TestTableOperation { Optimize(String), Analyze, } pub async fn do_insertions(fixture: &TestFixture) -> Result<()> { fixture.create_default_table().await?; // ingests 1 block, 1 segment, 1 snapshot append_sample_data(1, fixture).await?; // then, overwrite the table, new data set: 1 block, 1 segment, 1 snapshot append_sample_data_overwrite(1, true, fixture).await?; Ok(()) } pub async fn do_purge_test( case_name: &str, operation: TestTableOperation, snapshot_count: u32, table_statistic_count: u32, segment_count: u32, block_count: u32, index_count: u32, after_compact: Option<(u32, u32, u32, u32, u32)>, ) -> Result<()> { let fixture = TestFixture::new().await; let db = fixture.default_db_name(); let tbl = fixture.default_table_name(); let qry = match operation { TestTableOperation::Optimize(op) => format!("optimize table {}.{} {}", db, tbl, op), TestTableOperation::Analyze => format!("analyze table {}.{}", db, tbl), }; // insert, and then insert overwrite (1 snapshot, 1 segment, 1 data block, 1 index block for each insertion); do_insertions(&fixture).await?; // execute the query let ctx = fixture.ctx(); execute_command(ctx, &qry).await?; check_data_dir( &fixture, case_name, snapshot_count, table_statistic_count, segment_count, block_count, index_count, Some(()), None, ) .await?; history_should_have_item(&fixture, case_name, snapshot_count).await?; if let Some((snapshot_count, table_statistic_count, segment_count, block_count, index_count)) = after_compact { let qry = format!("optimize table {}.{} all", db, tbl); execute_command(fixture.ctx().clone(), &qry).await?; check_data_dir( &fixture, case_name, snapshot_count, table_statistic_count, segment_count, block_count, index_count, Some(()), None, ) .await?; history_should_have_item(&fixture, case_name, snapshot_count).await?; }; Ok(()) }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // dummy main. We do not copy this binary to fuchsia, only tests. fn main() {} #[cfg(test)] mod tests { use fidl_fuchsia_diagnostics_inspect::{ DisplaySettings, FormatSettings, ReaderMarker, TextSettings, }; use fuchsia_async as fasync; use fuchsia_component::client::connect_to_service; #[fasync::run_singlethreaded(test)] async fn test_all_reader_endpoints() { let control = connect_to_service::<ReaderMarker>().unwrap(); control.clear_selectors().unwrap(); let format_settings = FormatSettings { format: Some(DisplaySettings::Text(TextSettings { indent: 4 })) }; // No point reading the returned data yet since this test is hermetic and // doesn't generate any /hub information for the inspect service to read. let format_response = control.format(format_settings).await; assert!(format_response.is_ok()); assert!(format_response.unwrap().is_ok()); } }
use nabi; use abi; use handle::Handle; pub struct Channel(Handle); impl Channel { pub const INITIAL: ReadChannel = ReadChannel(Handle(0)); pub fn create() -> nabi::Result<(WriteChannel, ReadChannel)> { let (mut handle_tx, mut handle_rx) = (0, 0); let res: nabi::Result<u32> = unsafe { abi::channel_create(&mut handle_tx, &mut handle_rx) }.into(); res.map(|_| (WriteChannel(Handle(handle_tx)), ReadChannel(Handle(handle_rx)))) } } pub struct WriteChannel(pub(crate) Handle); impl WriteChannel { pub fn send(&self, data: &[u8]) -> nabi::Result<()> { let res: nabi::Result<u32> = unsafe { abi::channel_send((self.0).0, data.as_ptr(), data.len()) }.into(); res.map(|_| ()) } } pub struct ReadChannel(pub(crate) Handle); impl ReadChannel { pub fn recv_raw_nonblocking(&self, buffer: &mut [u8]) -> (usize, nabi::Result<()>) { let mut msg_size_out = 0; let res: nabi::Result<u32> = unsafe { abi::channel_recv((self.0).0, buffer.as_mut_ptr(), buffer.len(), &mut msg_size_out) }.into(); (msg_size_out, res.map(|_| ())) } pub fn recv_nonblocking(&self) -> nabi::Result<Vec<u8>> { let mut faux_buf = [0; 0]; let (msg_size, faux_res) = self.recv_raw_nonblocking(&mut faux_buf); faux_res?; let mut buffer = Vec::new(); buffer.resize(msg_size, 0); let (_, res) = self.recv_raw_nonblocking(&mut buffer); res.map(|_| buffer) } pub fn recv_raw(&self, buffer: &mut [u8]) -> (usize, nabi::Result<()>) { let mut faux_buf = [0; 0]; let (_, faux_res) = self.recv_raw_nonblocking(&mut faux_buf); match faux_res { Err(nabi::Error::BUFFER_TOO_SMALL) => { self.recv_raw_nonblocking(buffer) }, Err(nabi::Error::SHOULD_WAIT) => { let res: nabi::Result<u32> = unsafe { abi::object_wait_one((self.0).0, 1 << 0) }.into(); match res { Ok(_) => self.recv_raw_nonblocking(buffer), Err(e) => (0, Err(e)), } }, Err(e) => (0, Err(e)), Ok(_) => (0, Ok(())), } } pub fn recv(&self) -> nabi::Result<Vec<u8>> { let mut faux_buf = [0; 0]; let (msg_size, faux_res) = self.recv_raw_nonblocking(&mut faux_buf); match faux_res { Err(nabi::Error::BUFFER_TOO_SMALL) => { let mut buffer = Vec::new(); buffer.resize(msg_size, 0); self.recv_raw_nonblocking(&mut buffer).1.map(|_| buffer) }, Err(nabi::Error::SHOULD_WAIT) => { let res: nabi::Result<u32> = unsafe { abi::object_wait_one((self.0).0, 1 << 0) }.into(); res?; let (msg_size, faux_res) = self.recv_raw_nonblocking(&mut faux_buf); match faux_res { Err(nabi::Error::BUFFER_TOO_SMALL) => { let mut buffer = Vec::new(); buffer.resize(msg_size, 0); self.recv_raw_nonblocking(&mut buffer).1.map(|_| buffer) }, Err(e) => Err(e), Ok(_) => Ok(Vec::new()), } }, Err(e) => Err(e), Ok(_) => Ok(Vec::new()), } } } impl Iterator for ReadChannel { type Item = Vec<u8>; fn next(&mut self) -> Option<Vec<u8>> { self.recv().ok() } }
use std::os::unix::process::ExitStatusExt; use std::process::{ExitStatus, Stdio}; use std::sync::Arc; use tokio::process::Command; use tokio::sync::{Notify, OnceCell}; use common::job_status::Completed; use common::output_event::Stream as OutputStream; use common::*; use crate::client_cert::ClientName; use crate::output_stream::OutputHandler; /// Map status of a completed process to `JobStatus` fn completed_status(status: ExitStatus) -> JobStatus { if let Some(value) = status.code() { JobStatus { completed: Some(Completed::StatusCode(value)), } } else if let Some(value) = status.signal() { JobStatus { completed: Some(Completed::Signal(value)), } } else { panic!("Unknown process exit state") } } /// A single running job, i.e. a process pub struct Job { pub owner: ClientName, status: Arc<OnceCell<ExitStatus>>, kill_request: Arc<Notify>, pub stdout: Arc<OutputHandler>, pub stderr: Arc<OutputHandler>, } impl Job { pub fn spawn(owner: ClientName, req: JobStartRequest) -> Result<Self, String> { let mut cmd = Command::new(req.path); cmd.args(req.args); cmd.stdout(Stdio::piped()); cmd.stderr(Stdio::piped()); // TODO: use pre_exec to configure cgroups and namespaces let mut child = cmd.spawn().map_err(|e| format!("{:?}", e))?; let stdout = OutputHandler::setup(OutputStream::Stdout, child.stdout.take().unwrap()); let stderr = OutputHandler::setup(OutputStream::Stderr, child.stderr.take().unwrap()); let status = Arc::new(OnceCell::new()); let kill_request = Arc::new(Notify::new()); // State management task let status_handle = status.clone(); let kill_requested = kill_request.clone(); tokio::spawn(async move { tokio::select! { wait_result = child.wait() => { // Process completed log::debug!("Process completed {:?}", wait_result); let _ = status_handle.set(wait_result.expect("Unknown process exit state")); }, _ = kill_requested.notified() => { // Kill the process log::debug!("Killing job"); child.kill().await.expect("kill failed"); let wait_result = child.wait().await.expect("wait failed"); // Process completed log::debug!("Job killed {:?}", wait_result); let _ = status_handle.set(wait_result); } } }); Ok(Self { owner, status, kill_request, stdout, stderr, }) } /// Start an asynchronous kill operation pub fn start_kill(&mut self) { self.kill_request.notify_waiters(); } pub fn status(&mut self) -> JobStatus { match self.status.get() { Some(status) => completed_status(*status), None => JobStatus { completed: None }, } } }
use core::{ convert::TryFrom, fmt::{Debug, Display}, mem::MaybeUninit, ops::{Index, IndexMut}, }; /// Static Vector, for when a vector would be nice but there is no dynamic memory allocation. pub struct SVec<T, const N: usize> { inner: [MaybeUninit<T>; N], length: usize, } /// Standard debug, print the debug info of `self.get_slice()` impl<T: Debug, const N: usize> Debug for SVec<T, N> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{:?}", self.get_slice()) } } impl<T, const N: usize> SVec<T, N> { /// Creates a new empty SVec. /// Kindly always run this before doing anything else. pub const fn new() -> Self { Self { inner: MaybeUninit::uninit_array(), length: 0, } } } impl<T, const N: usize> SVec<T, N> { /// Get the current number of know initialized objects in the SVec. pub fn len(&self) -> usize { self.length } /// The maximum capacity of the SVec pub fn capacity(&self) -> usize { N } /// Pushes an object into the SVec. /// Panics if this would exceed `capacity`. pub fn push(&mut self, value: T) { self.inner[self.length] = MaybeUninit::new(value); self.length += 1; } /// Pops the last added objet from the SVec /// Returns `None` if length is 0. pub fn pop(&mut self) -> Option<T> { if self.length > 0 { self.length -= 1; Some(unsafe { self.inner[self.length].assume_init_read() }) } else { None } } /// Removes an object from the specified index, and then re-arranges the SVec through `ptr::copy`. pub fn remove(&mut self, index: usize) -> T { if index >= self.length { panic!("Index out of bounds"); } unsafe { let t = core::ptr::read(&self.inner[index]).assume_init(); if index + 1 < self.length { core::ptr::copy( &self.inner[index + 1], &mut self.inner[index], self.length - index - 1, ); } self.length -= 1; t } } /// Returns a slice of all known initialized objects in the SVec. pub fn get_slice(&self) -> &[T] { unsafe { core::mem::transmute(&self.inner[..self.length]) } } pub fn get_slice_mut(&mut self) -> &mut [T] { unsafe { core::mem::transmute(&mut self.inner[..self.length]) } } } impl<T, const N: usize> Index<usize> for SVec<T, N> { type Output = T; /// Returns a referense to the object at `index`. /// Panics if `index` is not known to contain something. fn index(&self, index: usize) -> &Self::Output { if index >= self.length { panic!( "Index out of bounds; index was {}, max was {}", index, self.length - 1 ); } else { unsafe { self.inner[index].assume_init_ref() } } } } impl<T, const N: usize> IndexMut<usize> for SVec<T, N> { /// Returns a mutable reference to object at `index`. /// Panics if `index` is not known to contain something. fn index_mut(&mut self, index: usize) -> &mut Self::Output { if index >= self.length { panic!( "Index out of bounds; index was {}, max was {}", index, self.length - 1 ); } else { unsafe { self.inner[index].assume_init_mut() } } } } impl<T: Clone, const N: usize> Clone for SVec<T, N> { /// Clones this SVec by making a new SVec and pushing a clone of each item one-by-one. fn clone(&self) -> Self { let mut ret = SVec::new(); for i in self.get_slice() { ret.push(i.clone()); } ret } } impl<T, const N: usize> Drop for SVec<T, N> { /// Drops each item in self first. fn drop(&mut self) { for item in self.get_slice_mut() { core::mem::drop(item); } } } impl<const N: usize> SVec<u8, N> { /// Get the `str` value of this `SVec`, interpretted as UTF-8 meaning compatibility with ASCII. pub fn to_str(&self) -> &str { if self.length == 0 { return ""; } core::str::from_utf8(self.get_slice()).unwrap() } } #[rustfmt::skip] impl<const N: usize> SVec<char, N> where [(); N * 4]: { /// Converts the `char`s into `u8`s one-by-one. /// # Example /// ``` /// // Main reason for implementation is converting to a &str // let s = "A &str"; /// let svec: SVec<char, 6> = SVec::new(); /// svec.push("A"); /// svec.push(" "); /// svec.push("&"); /// svec.push("s"); /// svec.push("t"); /// svec.push("r"); /// /// asserteq!(b"A &str", svec.to_u8()); /// asserteq!("A &str", svec.to_u8().to_str()); /// ``` pub fn to_u8(&self) -> SVec<u8, { N * 4 }> { let slice = self.get_slice(); let mut ret = SVec::new(); for c in slice { let mut buf = [0; 4]; let s = c.encode_utf8(&mut buf); for b in s.bytes() { ret.push(b); } } ret } } impl<T: Clone, const N: usize> TryFrom<&[T]> for SVec<T, N> { type Error = (); /// TryFrom /// /// Uses `self.clone` for conversion. fn try_from(value: &[T]) -> Result<Self, Self::Error> { if value.len() > N { return Err(()); } let mut svec = SVec::new(); for val in value { svec.push(val.clone()); } Ok(svec) } } impl<const N: usize> Display for SVec<u8, N> { /// Print `u8 SVec`s as `&str` fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.to_str()) } }
//! Describes CUDA-enabled GPUs. use telamon::codegen::Function; use telamon::device; use telamon::ir::{self, Type}; use telamon::model::{self, HwPressure}; use telamon::search_space::*; use fxhash::FxHashMap; use std::io::Write; use crate::printer::X86printer; /// Represents CUDA GPUs. #[derive(Clone)] pub struct Cpu { /// The name of the CPU. pub name: String, } impl Cpu { pub fn dummy_cpu() -> Self { Cpu { name: String::from("x86"), } } } impl device::Device for Cpu { fn print(&self, fun: &Function, out: &mut dyn Write) { write!(out, "{}", X86printer::default().wrapper_function(fun)).unwrap(); } fn check_type(&self, t: Type) -> Result<(), ir::TypeError> { match t { Type::I(i) | Type::F(i) if i == 32 || i == 64 => Ok(()), Type::I(i) if i == 1 || i == 8 || i == 16 => Ok(()), Type::PtrTo(_) => Ok(()), t => Err(ir::TypeError::InvalidType { t }), } } // block dimensions do not make sense on cpu fn max_block_dims(&self) -> u32 { 0 } fn max_inner_block_size(&self) -> u32 { 1 } fn max_threads(&self) -> u32 { 8 } fn max_unrolling(&self) -> u32 { 512 } fn can_vectorize(&self, _: &ir::Dimension, _: &ir::Operator) -> bool { false } fn max_vectorization(&self, _: &ir::Operator) -> [u32; 2] { [1, 1] } fn has_vector_registers(&self) -> bool { false } fn shared_mem(&self) -> u32 { 0 } fn pointer_type(&self, _: MemSpace) -> ir::Type { // TODO: pointer bitwidth ir::Type::I(64) } fn supported_mem_flags(&self, op: &ir::Operator) -> InstFlag { match op { ir::Operator::Ld(..) | ir::Operator::St(..) | ir::Operator::TmpLd(..) | ir::Operator::TmpSt(..) => InstFlag::BLOCK_COHERENT, _ => panic!("not a memory operation"), } } fn name(&self) -> &str { &self.name } fn add_block_overhead( &self, _: model::size::FactorRange, _: model::size::FactorRange, _: model::size::Range, _: &mut HwPressure, ) { } fn lower_type(&self, t: ir::Type, _space: &SearchSpace) -> Option<ir::Type> { Some(t) } fn hw_pressure( &self, _: &SearchSpace, _: &FxHashMap<ir::DimId, model::size::Range>, _: &FxHashMap<ir::StmtId, model::Nesting>, _: &dyn ir::Statement, _: &dyn device::Context, ) -> model::HwPressure { // TODO(model): implement model model::HwPressure::zero(self) } fn loop_iter_pressure(&self, _kind: DimKind) -> (HwPressure, HwPressure) { //TODO(model): implement minimal model (model::HwPressure::zero(self), model::HwPressure::zero(self)) } fn thread_rates(&self) -> HwPressure { //TODO(model): implement minimal model model::HwPressure::new(1.0, vec![]) } fn block_rates(&self) -> HwPressure { //TODO(model): implement minimal model model::HwPressure::new(1.0, vec![]) } fn total_rates(&self) -> HwPressure { //TODO(model): implement minimal model model::HwPressure::new(1.0, vec![]) } fn bottlenecks(&self) -> &[&'static str] { &[] } fn block_parallelism(&self, _space: &SearchSpace) -> u32 { 1 } fn additive_indvar_pressure(&self, _t: &ir::Type) -> HwPressure { //TODO(model): implement minimal model model::HwPressure::zero(self) } fn multiplicative_indvar_pressure(&self, _t: &ir::Type) -> HwPressure { //TODO(model): implement minimal model model::HwPressure::zero(self) } }
extern crate time; use std::thread; use std::sync::mpsc; use std::sync::mpsc::{SyncSender, Receiver}; use std::io::prelude::*; use std::fs::File; use std::vec::Vec; use time::PreciseTime; const TOTAL : i32 = 10000000; fn id(input : Receiver<i32>, output : SyncSender<i32>) { for _ in 1..TOTAL { let x = input.recv().unwrap(); output.send(x).unwrap(); } } fn prefix(n : i32, input : Receiver<i32>, output : SyncSender<i32>) { output.send(n).unwrap(); id(input, output); } fn delta(input : Receiver<i32>, out0 : SyncSender<i32>, out1 : SyncSender<i32>) { for _ in 1..TOTAL { let x = input.recv().unwrap(); out0.send(x).unwrap(); out1.send(x).unwrap(); } } fn succ(input : Receiver<i32>, output : SyncSender<i32>) { for _ in 1..TOTAL { let x = input.recv().unwrap(); output.send(x + 1).unwrap(); } } fn consume(input : Receiver<i32>) { let mut vec = Vec::new(); for _ in 1..(TOTAL / 10000) { let start = time::precise_time_ns(); for _ in 1..10000 { input.recv().unwrap(); } let total = (time::precise_time_ns() - start) / 10000; println!("{} ns", total); vec.push(total); } let mut buffer = File::create("ct-rust.csv").unwrap(); for v in vec { write!(buffer, "{},", v); } buffer.flush(); } fn main() { let (a_tx, a_rx) = mpsc::sync_channel(0); let (b_tx, b_rx) = mpsc::sync_channel(0); let (c_tx, c_rx) = mpsc::sync_channel(0); let (d_tx, d_rx) = mpsc::sync_channel(0); let p = thread::spawn(|| { prefix(0, a_rx, b_tx); }); let d = thread::spawn(|| { delta(b_rx, c_tx, d_tx); }); let s = thread::spawn(|| { succ(c_rx, a_tx); }); consume(d_rx); }
use crate::common::types::{TspResult, VertexId, Weight}; use crate::common::utils::{ cmp, into_undirected_graph_tab, read_lines, to_edges_from_xy_position, vertices, }; use crate::week2::types::{EnumSet, VertexSubset}; use itertools::Itertools; use rayon::prelude::*; use std::collections::HashMap; use std::f64::MAX; /// Computes the solution to the TSP problem for the file /// located at `filename` using dynamic programming. pub fn solve_for_file(filename: &str) -> TspResult { let file_contents: Vec<Vec<Weight>> = read_lines(filename); let g = to_edges_from_xy_position(file_contents); let mut vs = vertices(&g); let g = into_undirected_graph_tab(&g); let vertex_set = VertexSubset::from(&vs); // Initialize the cost table `C` with the cost of the home vertex to itself (which is 0). let home_vertex = 0; let mut cost_accum: HashMap<(VertexSubset, VertexId), Weight> = HashMap::new(); cost_accum.insert((VertexSubset::from(&home_vertex), home_vertex), 0f64); // We need to remove the home vertex, since it won't be // accounted for in the rest of the path. vs.remove(&home_vertex); let n = vs.len(); for i in 1..=n { // We compute all the vertex subsets of size `i` (excluding the home vertex), // and iterate over each one of them. let subsets = vs.iter().combinations(i); for mut subset in subsets { // We build an instance of `VertexSubset` which contains all the vertices // for this particular vertex subset `subset`. subset.push(&home_vertex); let subset_key = VertexSubset::from(&subset); // We iterate over all the vertices in this particular vertex subset `subset` to // compute the minimum cost from the home vertex up to these. for &j in &subset { if *j != home_vertex { let cost = subset .par_iter() .filter(|&i| *i != j) .map(|&i| { let key = (subset_key.remove(j), *i); let vertices = (*i, *j); let weight = g.get(&vertices).unwrap(); let current_cost = cost_accum.get(&key).or(Some(&MAX)).unwrap(); return weight + current_cost; }) .min_by(cmp) .or(Some(MAX)) .unwrap(); cost_accum.insert((subset_key.clone(), *j), cost); } } } } let min_cost = cost_accum .iter() .filter(|((s, _), _)| *s == vertex_set) .map(|((_, j), cost)| { let vertices = (home_vertex, *j); let weight = g.get(&vertices).or(Some(&MAX)).unwrap(); return cost + weight; }) .min_by(cmp); match min_cost { Some(c) => c.floor() as TspResult, None => 0, } } pub fn solve() { let result = solve_for_file("resources/week2/tsp.txt"); println!("{}", result); }
pub(crate) mod mock; pub(crate) mod skipped; use std::{ fmt::{Debug, Display}, sync::Arc, }; use async_trait::async_trait; use data_types::PartitionId; /// A source of partitions, noted by [`PartitionId`](data_types::PartitionId). /// /// Specifically finds a subset of the given partitions, /// usually by performing a catalog lookup using the grouped set of partitions. #[async_trait] pub(crate) trait PartitionsSubsetSource: Debug + Display + Send + Sync { /// Given a set of partitions, return a subset. /// /// This method performs retries. async fn fetch(&self, partitions: &[PartitionId]) -> Vec<PartitionId>; } #[async_trait] impl<T> PartitionsSubsetSource for Arc<T> where T: PartitionsSubsetSource + ?Sized, { async fn fetch(&self, partitions: &[PartitionId]) -> Vec<PartitionId> { self.as_ref().fetch(partitions).await } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct ADRENTRY { pub ulReserved1: u32, pub cValues: u32, pub rgPropVals: *mut SPropValue, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ADRENTRY {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for ADRENTRY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for ADRENTRY { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ADRENTRY").field("ulReserved1", &self.ulReserved1).field("cValues", &self.cValues).field("rgPropVals", &self.rgPropVals).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for ADRENTRY { fn eq(&self, other: &Self) -> bool { self.ulReserved1 == other.ulReserved1 && self.cValues == other.cValues && self.rgPropVals == other.rgPropVals } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for ADRENTRY {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for ADRENTRY { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct ADRLIST { pub cEntries: u32, pub aEntries: [ADRENTRY; 1], } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ADRLIST {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for ADRLIST { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for ADRLIST { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ADRLIST").field("cEntries", &self.cEntries).field("aEntries", &self.aEntries).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for ADRLIST { fn eq(&self, other: &Self) -> bool { self.cEntries == other.cEntries && self.aEntries == other.aEntries } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for ADRLIST {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for ADRLIST { type Abi = Self; } #[derive(:: core :: clone :: Clone)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct ADRPARM { pub cbABContEntryID: u32, pub lpABContEntryID: *mut ENTRYID, pub ulFlags: u32, pub lpReserved: *mut ::core::ffi::c_void, pub ulHelpContext: u32, pub lpszHelpFileName: *mut i8, pub lpfnABSDI: ::core::option::Option<LPFNABSDI>, pub lpfnDismiss: ::core::option::Option<LPFNDISMISS>, pub lpvDismissContext: *mut ::core::ffi::c_void, pub lpszCaption: *mut i8, pub lpszNewEntryTitle: *mut i8, pub lpszDestWellsTitle: *mut i8, pub cDestFields: u32, pub nDestFieldFocus: u32, pub lppszDestTitles: *mut *mut i8, pub lpulDestComps: *mut u32, pub lpContRestriction: *mut SRestriction, pub lpHierRestriction: *mut SRestriction, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ADRPARM {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for ADRPARM { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for ADRPARM { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ADRPARM") .field("cbABContEntryID", &self.cbABContEntryID) .field("lpABContEntryID", &self.lpABContEntryID) .field("ulFlags", &self.ulFlags) .field("lpReserved", &self.lpReserved) .field("ulHelpContext", &self.ulHelpContext) .field("lpszHelpFileName", &self.lpszHelpFileName) .field("lpvDismissContext", &self.lpvDismissContext) .field("lpszCaption", &self.lpszCaption) .field("lpszNewEntryTitle", &self.lpszNewEntryTitle) .field("lpszDestWellsTitle", &self.lpszDestWellsTitle) .field("cDestFields", &self.cDestFields) .field("nDestFieldFocus", &self.nDestFieldFocus) .field("lppszDestTitles", &self.lppszDestTitles) .field("lpulDestComps", &self.lpulDestComps) .field("lpContRestriction", &self.lpContRestriction) .field("lpHierRestriction", &self.lpHierRestriction) .finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for ADRPARM { fn eq(&self, other: &Self) -> bool { self.cbABContEntryID == other.cbABContEntryID && self.lpABContEntryID == other.lpABContEntryID && self.ulFlags == other.ulFlags && self.lpReserved == other.lpReserved && self.ulHelpContext == other.ulHelpContext && self.lpszHelpFileName == other.lpszHelpFileName && self.lpfnABSDI.map(|f| f as usize) == other.lpfnABSDI.map(|f| f as usize) && self.lpfnDismiss.map(|f| f as usize) == other.lpfnDismiss.map(|f| f as usize) && self.lpvDismissContext == other.lpvDismissContext && self.lpszCaption == other.lpszCaption && self.lpszNewEntryTitle == other.lpszNewEntryTitle && self.lpszDestWellsTitle == other.lpszDestWellsTitle && self.cDestFields == other.cDestFields && self.nDestFieldFocus == other.nDestFieldFocus && self.lppszDestTitles == other.lppszDestTitles && self.lpulDestComps == other.lpulDestComps && self.lpContRestriction == other.lpContRestriction && self.lpHierRestriction == other.lpHierRestriction } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for ADRPARM {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for ADRPARM { type Abi = ::core::mem::ManuallyDrop<Self>; } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn BuildDisplayTable<'a, Param3: ::windows::core::IntoParam<'a, super::Com::IMalloc>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::HINSTANCE>>( lpallocatebuffer: ::core::option::Option<LPALLOCATEBUFFER>, lpallocatemore: ::core::option::Option<LPALLOCATEMORE>, lpfreebuffer: ::core::option::Option<LPFREEBUFFER>, lpmalloc: Param3, hinstance: Param4, cpages: u32, lppage: *mut DTPAGE, ulflags: u32, lpptable: *mut ::core::option::Option<IMAPITable>, lpptbldata: *mut ::core::option::Option<ITableData>, ) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn BuildDisplayTable(lpallocatebuffer: ::windows::core::RawPtr, lpallocatemore: ::windows::core::RawPtr, lpfreebuffer: ::windows::core::RawPtr, lpmalloc: ::windows::core::RawPtr, hinstance: super::super::Foundation::HINSTANCE, cpages: u32, lppage: *mut DTPAGE, ulflags: u32, lpptable: *mut ::windows::core::RawPtr, lpptbldata: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; } BuildDisplayTable( ::core::mem::transmute(lpallocatebuffer), ::core::mem::transmute(lpallocatemore), ::core::mem::transmute(lpfreebuffer), lpmalloc.into_param().abi(), hinstance.into_param().abi(), ::core::mem::transmute(cpages), ::core::mem::transmute(lppage), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpptable), ::core::mem::transmute(lpptbldata), ) .ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } pub type CALLERRELEASE = unsafe extern "system" fn(ulcallerdata: u32, lptbldata: ::windows::core::RawPtr, lpvue: ::windows::core::RawPtr); #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ChangeIdleRoutine(ftg: *mut ::core::ffi::c_void, lpfnidle: ::core::option::Option<PFNIDLE>, lpvidleparam: *mut ::core::ffi::c_void, priidle: i16, csecidle: u32, iroidle: u16, ircidle: u16) { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ChangeIdleRoutine(ftg: *mut ::core::ffi::c_void, lpfnidle: ::windows::core::RawPtr, lpvidleparam: *mut ::core::ffi::c_void, priidle: i16, csecidle: u32, iroidle: u16, ircidle: u16); } ::core::mem::transmute(ChangeIdleRoutine(::core::mem::transmute(ftg), ::core::mem::transmute(lpfnidle), ::core::mem::transmute(lpvidleparam), ::core::mem::transmute(priidle), ::core::mem::transmute(csecidle), ::core::mem::transmute(iroidle), ::core::mem::transmute(ircidle))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn CreateIProp(lpinterface: *mut ::windows::core::GUID, lpallocatebuffer: ::core::option::Option<LPALLOCATEBUFFER>, lpallocatemore: ::core::option::Option<LPALLOCATEMORE>, lpfreebuffer: ::core::option::Option<LPFREEBUFFER>, lpvreserved: *mut ::core::ffi::c_void, lpppropdata: *mut ::core::option::Option<IPropData>) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CreateIProp(lpinterface: *mut ::windows::core::GUID, lpallocatebuffer: ::windows::core::RawPtr, lpallocatemore: ::windows::core::RawPtr, lpfreebuffer: ::windows::core::RawPtr, lpvreserved: *mut ::core::ffi::c_void, lpppropdata: *mut ::windows::core::RawPtr) -> i32; } ::core::mem::transmute(CreateIProp(::core::mem::transmute(lpinterface), ::core::mem::transmute(lpallocatebuffer), ::core::mem::transmute(lpallocatemore), ::core::mem::transmute(lpfreebuffer), ::core::mem::transmute(lpvreserved), ::core::mem::transmute(lpppropdata))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn CreateTable(lpinterface: *mut ::windows::core::GUID, lpallocatebuffer: ::core::option::Option<LPALLOCATEBUFFER>, lpallocatemore: ::core::option::Option<LPALLOCATEMORE>, lpfreebuffer: ::core::option::Option<LPFREEBUFFER>, lpvreserved: *mut ::core::ffi::c_void, ultabletype: u32, ulproptagindexcolumn: u32, lpsproptagarraycolumns: *mut SPropTagArray, lpptabledata: *mut ::core::option::Option<ITableData>) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CreateTable(lpinterface: *mut ::windows::core::GUID, lpallocatebuffer: ::windows::core::RawPtr, lpallocatemore: ::windows::core::RawPtr, lpfreebuffer: ::windows::core::RawPtr, lpvreserved: *mut ::core::ffi::c_void, ultabletype: u32, ulproptagindexcolumn: u32, lpsproptagarraycolumns: *mut SPropTagArray, lpptabledata: *mut ::windows::core::RawPtr) -> i32; } ::core::mem::transmute(CreateTable( ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpallocatebuffer), ::core::mem::transmute(lpallocatemore), ::core::mem::transmute(lpfreebuffer), ::core::mem::transmute(lpvreserved), ::core::mem::transmute(ultabletype), ::core::mem::transmute(ulproptagindexcolumn), ::core::mem::transmute(lpsproptagarraycolumns), ::core::mem::transmute(lpptabledata), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTBLBUTTON { pub ulbLpszLabel: u32, pub ulFlags: u32, pub ulPRControl: u32, } impl DTBLBUTTON {} impl ::core::default::Default for DTBLBUTTON { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DTBLBUTTON { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DTBLBUTTON").field("ulbLpszLabel", &self.ulbLpszLabel).field("ulFlags", &self.ulFlags).field("ulPRControl", &self.ulPRControl).finish() } } impl ::core::cmp::PartialEq for DTBLBUTTON { fn eq(&self, other: &Self) -> bool { self.ulbLpszLabel == other.ulbLpszLabel && self.ulFlags == other.ulFlags && self.ulPRControl == other.ulPRControl } } impl ::core::cmp::Eq for DTBLBUTTON {} unsafe impl ::windows::core::Abi for DTBLBUTTON { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTBLCHECKBOX { pub ulbLpszLabel: u32, pub ulFlags: u32, pub ulPRPropertyName: u32, } impl DTBLCHECKBOX {} impl ::core::default::Default for DTBLCHECKBOX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DTBLCHECKBOX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DTBLCHECKBOX").field("ulbLpszLabel", &self.ulbLpszLabel).field("ulFlags", &self.ulFlags).field("ulPRPropertyName", &self.ulPRPropertyName).finish() } } impl ::core::cmp::PartialEq for DTBLCHECKBOX { fn eq(&self, other: &Self) -> bool { self.ulbLpszLabel == other.ulbLpszLabel && self.ulFlags == other.ulFlags && self.ulPRPropertyName == other.ulPRPropertyName } } impl ::core::cmp::Eq for DTBLCHECKBOX {} unsafe impl ::windows::core::Abi for DTBLCHECKBOX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTBLCOMBOBOX { pub ulbLpszCharsAllowed: u32, pub ulFlags: u32, pub ulNumCharsAllowed: u32, pub ulPRPropertyName: u32, pub ulPRTableName: u32, } impl DTBLCOMBOBOX {} impl ::core::default::Default for DTBLCOMBOBOX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DTBLCOMBOBOX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DTBLCOMBOBOX").field("ulbLpszCharsAllowed", &self.ulbLpszCharsAllowed).field("ulFlags", &self.ulFlags).field("ulNumCharsAllowed", &self.ulNumCharsAllowed).field("ulPRPropertyName", &self.ulPRPropertyName).field("ulPRTableName", &self.ulPRTableName).finish() } } impl ::core::cmp::PartialEq for DTBLCOMBOBOX { fn eq(&self, other: &Self) -> bool { self.ulbLpszCharsAllowed == other.ulbLpszCharsAllowed && self.ulFlags == other.ulFlags && self.ulNumCharsAllowed == other.ulNumCharsAllowed && self.ulPRPropertyName == other.ulPRPropertyName && self.ulPRTableName == other.ulPRTableName } } impl ::core::cmp::Eq for DTBLCOMBOBOX {} unsafe impl ::windows::core::Abi for DTBLCOMBOBOX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTBLDDLBX { pub ulFlags: u32, pub ulPRDisplayProperty: u32, pub ulPRSetProperty: u32, pub ulPRTableName: u32, } impl DTBLDDLBX {} impl ::core::default::Default for DTBLDDLBX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DTBLDDLBX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DTBLDDLBX").field("ulFlags", &self.ulFlags).field("ulPRDisplayProperty", &self.ulPRDisplayProperty).field("ulPRSetProperty", &self.ulPRSetProperty).field("ulPRTableName", &self.ulPRTableName).finish() } } impl ::core::cmp::PartialEq for DTBLDDLBX { fn eq(&self, other: &Self) -> bool { self.ulFlags == other.ulFlags && self.ulPRDisplayProperty == other.ulPRDisplayProperty && self.ulPRSetProperty == other.ulPRSetProperty && self.ulPRTableName == other.ulPRTableName } } impl ::core::cmp::Eq for DTBLDDLBX {} unsafe impl ::windows::core::Abi for DTBLDDLBX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTBLEDIT { pub ulbLpszCharsAllowed: u32, pub ulFlags: u32, pub ulNumCharsAllowed: u32, pub ulPropTag: u32, } impl DTBLEDIT {} impl ::core::default::Default for DTBLEDIT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DTBLEDIT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DTBLEDIT").field("ulbLpszCharsAllowed", &self.ulbLpszCharsAllowed).field("ulFlags", &self.ulFlags).field("ulNumCharsAllowed", &self.ulNumCharsAllowed).field("ulPropTag", &self.ulPropTag).finish() } } impl ::core::cmp::PartialEq for DTBLEDIT { fn eq(&self, other: &Self) -> bool { self.ulbLpszCharsAllowed == other.ulbLpszCharsAllowed && self.ulFlags == other.ulFlags && self.ulNumCharsAllowed == other.ulNumCharsAllowed && self.ulPropTag == other.ulPropTag } } impl ::core::cmp::Eq for DTBLEDIT {} unsafe impl ::windows::core::Abi for DTBLEDIT { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTBLGROUPBOX { pub ulbLpszLabel: u32, pub ulFlags: u32, } impl DTBLGROUPBOX {} impl ::core::default::Default for DTBLGROUPBOX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DTBLGROUPBOX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DTBLGROUPBOX").field("ulbLpszLabel", &self.ulbLpszLabel).field("ulFlags", &self.ulFlags).finish() } } impl ::core::cmp::PartialEq for DTBLGROUPBOX { fn eq(&self, other: &Self) -> bool { self.ulbLpszLabel == other.ulbLpszLabel && self.ulFlags == other.ulFlags } } impl ::core::cmp::Eq for DTBLGROUPBOX {} unsafe impl ::windows::core::Abi for DTBLGROUPBOX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTBLLABEL { pub ulbLpszLabelName: u32, pub ulFlags: u32, } impl DTBLLABEL {} impl ::core::default::Default for DTBLLABEL { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DTBLLABEL { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DTBLLABEL").field("ulbLpszLabelName", &self.ulbLpszLabelName).field("ulFlags", &self.ulFlags).finish() } } impl ::core::cmp::PartialEq for DTBLLABEL { fn eq(&self, other: &Self) -> bool { self.ulbLpszLabelName == other.ulbLpszLabelName && self.ulFlags == other.ulFlags } } impl ::core::cmp::Eq for DTBLLABEL {} unsafe impl ::windows::core::Abi for DTBLLABEL { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTBLLBX { pub ulFlags: u32, pub ulPRSetProperty: u32, pub ulPRTableName: u32, } impl DTBLLBX {} impl ::core::default::Default for DTBLLBX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DTBLLBX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DTBLLBX").field("ulFlags", &self.ulFlags).field("ulPRSetProperty", &self.ulPRSetProperty).field("ulPRTableName", &self.ulPRTableName).finish() } } impl ::core::cmp::PartialEq for DTBLLBX { fn eq(&self, other: &Self) -> bool { self.ulFlags == other.ulFlags && self.ulPRSetProperty == other.ulPRSetProperty && self.ulPRTableName == other.ulPRTableName } } impl ::core::cmp::Eq for DTBLLBX {} unsafe impl ::windows::core::Abi for DTBLLBX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTBLMVDDLBX { pub ulFlags: u32, pub ulMVPropTag: u32, } impl DTBLMVDDLBX {} impl ::core::default::Default for DTBLMVDDLBX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DTBLMVDDLBX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DTBLMVDDLBX").field("ulFlags", &self.ulFlags).field("ulMVPropTag", &self.ulMVPropTag).finish() } } impl ::core::cmp::PartialEq for DTBLMVDDLBX { fn eq(&self, other: &Self) -> bool { self.ulFlags == other.ulFlags && self.ulMVPropTag == other.ulMVPropTag } } impl ::core::cmp::Eq for DTBLMVDDLBX {} unsafe impl ::windows::core::Abi for DTBLMVDDLBX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTBLMVLISTBOX { pub ulFlags: u32, pub ulMVPropTag: u32, } impl DTBLMVLISTBOX {} impl ::core::default::Default for DTBLMVLISTBOX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DTBLMVLISTBOX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DTBLMVLISTBOX").field("ulFlags", &self.ulFlags).field("ulMVPropTag", &self.ulMVPropTag).finish() } } impl ::core::cmp::PartialEq for DTBLMVLISTBOX { fn eq(&self, other: &Self) -> bool { self.ulFlags == other.ulFlags && self.ulMVPropTag == other.ulMVPropTag } } impl ::core::cmp::Eq for DTBLMVLISTBOX {} unsafe impl ::windows::core::Abi for DTBLMVLISTBOX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTBLPAGE { pub ulbLpszLabel: u32, pub ulFlags: u32, pub ulbLpszComponent: u32, pub ulContext: u32, } impl DTBLPAGE {} impl ::core::default::Default for DTBLPAGE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DTBLPAGE { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DTBLPAGE").field("ulbLpszLabel", &self.ulbLpszLabel).field("ulFlags", &self.ulFlags).field("ulbLpszComponent", &self.ulbLpszComponent).field("ulContext", &self.ulContext).finish() } } impl ::core::cmp::PartialEq for DTBLPAGE { fn eq(&self, other: &Self) -> bool { self.ulbLpszLabel == other.ulbLpszLabel && self.ulFlags == other.ulFlags && self.ulbLpszComponent == other.ulbLpszComponent && self.ulContext == other.ulContext } } impl ::core::cmp::Eq for DTBLPAGE {} unsafe impl ::windows::core::Abi for DTBLPAGE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTBLRADIOBUTTON { pub ulbLpszLabel: u32, pub ulFlags: u32, pub ulcButtons: u32, pub ulPropTag: u32, pub lReturnValue: i32, } impl DTBLRADIOBUTTON {} impl ::core::default::Default for DTBLRADIOBUTTON { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DTBLRADIOBUTTON { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DTBLRADIOBUTTON").field("ulbLpszLabel", &self.ulbLpszLabel).field("ulFlags", &self.ulFlags).field("ulcButtons", &self.ulcButtons).field("ulPropTag", &self.ulPropTag).field("lReturnValue", &self.lReturnValue).finish() } } impl ::core::cmp::PartialEq for DTBLRADIOBUTTON { fn eq(&self, other: &Self) -> bool { self.ulbLpszLabel == other.ulbLpszLabel && self.ulFlags == other.ulFlags && self.ulcButtons == other.ulcButtons && self.ulPropTag == other.ulPropTag && self.lReturnValue == other.lReturnValue } } impl ::core::cmp::Eq for DTBLRADIOBUTTON {} unsafe impl ::windows::core::Abi for DTBLRADIOBUTTON { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTCTL { pub ulCtlType: u32, pub ulCtlFlags: u32, pub lpbNotif: *mut u8, pub cbNotif: u32, pub lpszFilter: *mut i8, pub ulItemID: u32, pub ctl: DTCTL_0, } impl DTCTL {} impl ::core::default::Default for DTCTL { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for DTCTL { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for DTCTL {} unsafe impl ::windows::core::Abi for DTCTL { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub union DTCTL_0 { pub lpv: *mut ::core::ffi::c_void, pub lplabel: *mut DTBLLABEL, pub lpedit: *mut DTBLEDIT, pub lplbx: *mut DTBLLBX, pub lpcombobox: *mut DTBLCOMBOBOX, pub lpddlbx: *mut DTBLDDLBX, pub lpcheckbox: *mut DTBLCHECKBOX, pub lpgroupbox: *mut DTBLGROUPBOX, pub lpbutton: *mut DTBLBUTTON, pub lpradiobutton: *mut DTBLRADIOBUTTON, pub lpmvlbx: *mut DTBLMVLISTBOX, pub lpmvddlbx: *mut DTBLMVDDLBX, pub lppage: *mut DTBLPAGE, } impl DTCTL_0 {} impl ::core::default::Default for DTCTL_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for DTCTL_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for DTCTL_0 {} unsafe impl ::windows::core::Abi for DTCTL_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DTPAGE { pub cctl: u32, pub lpszResourceName: *mut i8, pub Anonymous: DTPAGE_0, pub lpctl: *mut DTCTL, } impl DTPAGE {} impl ::core::default::Default for DTPAGE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for DTPAGE { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for DTPAGE {} unsafe impl ::windows::core::Abi for DTPAGE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub union DTPAGE_0 { pub lpszComponent: *mut i8, pub ulItemID: u32, } impl DTPAGE_0 {} impl ::core::default::Default for DTPAGE_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for DTPAGE_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for DTPAGE_0 {} unsafe impl ::windows::core::Abi for DTPAGE_0 { type Abi = Self; } #[inline] pub unsafe fn DeinitMapiUtil() { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DeinitMapiUtil(); } ::core::mem::transmute(DeinitMapiUtil()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DeregisterIdleRoutine(ftg: *mut ::core::ffi::c_void) { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DeregisterIdleRoutine(ftg: *mut ::core::ffi::c_void); } ::core::mem::transmute(DeregisterIdleRoutine(::core::mem::transmute(ftg))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ENTRYID { pub abFlags: [u8; 4], pub ab: [u8; 1], } impl ENTRYID {} impl ::core::default::Default for ENTRYID { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ENTRYID { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ENTRYID").field("abFlags", &self.abFlags).field("ab", &self.ab).finish() } } impl ::core::cmp::PartialEq for ENTRYID { fn eq(&self, other: &Self) -> bool { self.abFlags == other.abFlags && self.ab == other.ab } } impl ::core::cmp::Eq for ENTRYID {} unsafe impl ::windows::core::Abi for ENTRYID { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ERROR_NOTIFICATION { pub cbEntryID: u32, pub lpEntryID: *mut ENTRYID, pub scode: i32, pub ulFlags: u32, pub lpMAPIError: *mut MAPIERROR, } impl ERROR_NOTIFICATION {} impl ::core::default::Default for ERROR_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ERROR_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ERROR_NOTIFICATION").field("cbEntryID", &self.cbEntryID).field("lpEntryID", &self.lpEntryID).field("scode", &self.scode).field("ulFlags", &self.ulFlags).field("lpMAPIError", &self.lpMAPIError).finish() } } impl ::core::cmp::PartialEq for ERROR_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.cbEntryID == other.cbEntryID && self.lpEntryID == other.lpEntryID && self.scode == other.scode && self.ulFlags == other.ulFlags && self.lpMAPIError == other.lpMAPIError } } impl ::core::cmp::Eq for ERROR_NOTIFICATION {} unsafe impl ::windows::core::Abi for ERROR_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct EXTENDED_NOTIFICATION { pub ulEvent: u32, pub cb: u32, pub pbEventParameters: *mut u8, } impl EXTENDED_NOTIFICATION {} impl ::core::default::Default for EXTENDED_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for EXTENDED_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("EXTENDED_NOTIFICATION").field("ulEvent", &self.ulEvent).field("cb", &self.cb).field("pbEventParameters", &self.pbEventParameters).finish() } } impl ::core::cmp::PartialEq for EXTENDED_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.cb == other.cb && self.pbEventParameters == other.pbEventParameters } } impl ::core::cmp::Eq for EXTENDED_NOTIFICATION {} unsafe impl ::windows::core::Abi for EXTENDED_NOTIFICATION { type Abi = Self; } pub const E_IMAPI_BURN_VERIFICATION_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600697i32 as _); pub const E_IMAPI_DF2DATA_CLIENT_NAME_IS_NOT_VALID: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599672i32 as _); pub const E_IMAPI_DF2DATA_INVALID_MEDIA_STATE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599678i32 as _); pub const E_IMAPI_DF2DATA_MEDIA_IS_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599674i32 as _); pub const E_IMAPI_DF2DATA_MEDIA_NOT_BLANK: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599675i32 as _); pub const E_IMAPI_DF2DATA_RECORDER_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599673i32 as _); pub const E_IMAPI_DF2DATA_STREAM_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599677i32 as _); pub const E_IMAPI_DF2DATA_STREAM_TOO_LARGE_FOR_CURRENT_MEDIA: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599676i32 as _); pub const E_IMAPI_DF2DATA_WRITE_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599680i32 as _); pub const E_IMAPI_DF2DATA_WRITE_NOT_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599679i32 as _); pub const E_IMAPI_DF2RAW_CLIENT_NAME_IS_NOT_VALID: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599164i32 as _); pub const E_IMAPI_DF2RAW_DATA_BLOCK_TYPE_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599154i32 as _); pub const E_IMAPI_DF2RAW_MEDIA_IS_NOT_BLANK: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599162i32 as _); pub const E_IMAPI_DF2RAW_MEDIA_IS_NOT_PREPARED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599166i32 as _); pub const E_IMAPI_DF2RAW_MEDIA_IS_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599161i32 as _); pub const E_IMAPI_DF2RAW_MEDIA_IS_PREPARED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599165i32 as _); pub const E_IMAPI_DF2RAW_NOT_ENOUGH_SPACE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599159i32 as _); pub const E_IMAPI_DF2RAW_NO_RECORDER_SPECIFIED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599158i32 as _); pub const E_IMAPI_DF2RAW_RECORDER_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599152i32 as _); pub const E_IMAPI_DF2RAW_STREAM_LEADIN_TOO_SHORT: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599153i32 as _); pub const E_IMAPI_DF2RAW_STREAM_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599155i32 as _); pub const E_IMAPI_DF2RAW_WRITE_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599168i32 as _); pub const E_IMAPI_DF2RAW_WRITE_NOT_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599167i32 as _); pub const E_IMAPI_DF2TAO_CLIENT_NAME_IS_NOT_VALID: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599409i32 as _); pub const E_IMAPI_DF2TAO_INVALID_ISRC: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599413i32 as _); pub const E_IMAPI_DF2TAO_INVALID_MCN: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599412i32 as _); pub const E_IMAPI_DF2TAO_MEDIA_IS_NOT_BLANK: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599418i32 as _); pub const E_IMAPI_DF2TAO_MEDIA_IS_NOT_PREPARED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599422i32 as _); pub const E_IMAPI_DF2TAO_MEDIA_IS_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599417i32 as _); pub const E_IMAPI_DF2TAO_MEDIA_IS_PREPARED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599421i32 as _); pub const E_IMAPI_DF2TAO_NOT_ENOUGH_SPACE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599415i32 as _); pub const E_IMAPI_DF2TAO_NO_RECORDER_SPECIFIED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599414i32 as _); pub const E_IMAPI_DF2TAO_PROPERTY_FOR_BLANK_MEDIA_ONLY: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599420i32 as _); pub const E_IMAPI_DF2TAO_RECORDER_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599410i32 as _); pub const E_IMAPI_DF2TAO_STREAM_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599411i32 as _); pub const E_IMAPI_DF2TAO_TABLE_OF_CONTENTS_EMPTY_DISC: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599419i32 as _); pub const E_IMAPI_DF2TAO_TRACK_LIMIT_REACHED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599416i32 as _); pub const E_IMAPI_DF2TAO_WRITE_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599424i32 as _); pub const E_IMAPI_DF2TAO_WRITE_NOT_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599423i32 as _); pub const E_IMAPI_ERASE_CLIENT_NAME_IS_NOT_VALID: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062598389i32 as _); pub const E_IMAPI_ERASE_DISC_INFORMATION_TOO_SMALL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136340222i32 as _); pub const E_IMAPI_ERASE_DRIVE_FAILED_ERASE_COMMAND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136340219i32 as _); pub const E_IMAPI_ERASE_DRIVE_FAILED_SPINUP_COMMAND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136340216i32 as _); pub const E_IMAPI_ERASE_MEDIA_IS_NOT_ERASABLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136340220i32 as _); pub const E_IMAPI_ERASE_MEDIA_IS_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062598391i32 as _); pub const E_IMAPI_ERASE_MODE_PAGE_2A_TOO_SMALL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136340221i32 as _); pub const E_IMAPI_ERASE_ONLY_ONE_RECORDER_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136340223i32 as _); pub const E_IMAPI_ERASE_RECORDER_IN_USE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136340224i32 as _); pub const E_IMAPI_ERASE_RECORDER_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062598390i32 as _); pub const E_IMAPI_ERASE_TOOK_LONGER_THAN_ONE_HOUR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136340218i32 as _); pub const E_IMAPI_ERASE_UNEXPECTED_DRIVE_RESPONSE_DURING_ERASE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136340217i32 as _); pub const E_IMAPI_LOSS_OF_STREAMING: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599936i32 as _); pub const E_IMAPI_RAW_IMAGE_INSUFFICIENT_SPACE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136339963i32 as _); pub const E_IMAPI_RAW_IMAGE_IS_READ_ONLY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136339968i32 as _); pub const E_IMAPI_RAW_IMAGE_NO_TRACKS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136339965i32 as _); pub const E_IMAPI_RAW_IMAGE_SECTOR_TYPE_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136339966i32 as _); pub const E_IMAPI_RAW_IMAGE_TOO_MANY_TRACKS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136339967i32 as _); pub const E_IMAPI_RAW_IMAGE_TOO_MANY_TRACK_INDEXES: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136339962i32 as _); pub const E_IMAPI_RAW_IMAGE_TRACKS_ALREADY_ADDED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136339964i32 as _); pub const E_IMAPI_RAW_IMAGE_TRACK_INDEX_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136339961i32 as _); pub const E_IMAPI_RAW_IMAGE_TRACK_INDEX_OFFSET_ZERO_CANNOT_BE_CLEARED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136339959i32 as _); pub const E_IMAPI_RAW_IMAGE_TRACK_INDEX_TOO_CLOSE_TO_OTHER_INDEX: ::windows::core::HRESULT = ::windows::core::HRESULT(-2136339958i32 as _); pub const E_IMAPI_RECORDER_CLIENT_NAME_IS_NOT_VALID: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600175i32 as _); pub const E_IMAPI_RECORDER_COMMAND_TIMEOUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600179i32 as _); pub const E_IMAPI_RECORDER_DVD_STRUCTURE_NOT_PRESENT: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600178i32 as _); pub const E_IMAPI_RECORDER_FEATURE_IS_NOT_CURRENT: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600181i32 as _); pub const E_IMAPI_RECORDER_GET_CONFIGURATION_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600180i32 as _); pub const E_IMAPI_RECORDER_INVALID_MODE_PARAMETERS: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600184i32 as _); pub const E_IMAPI_RECORDER_INVALID_RESPONSE_FROM_DEVICE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599937i32 as _); pub const E_IMAPI_RECORDER_LOCKED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600176i32 as _); pub const E_IMAPI_RECORDER_MEDIA_BECOMING_READY: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600187i32 as _); pub const E_IMAPI_RECORDER_MEDIA_BUSY: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600185i32 as _); pub const E_IMAPI_RECORDER_MEDIA_FORMAT_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600186i32 as _); pub const E_IMAPI_RECORDER_MEDIA_INCOMPATIBLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600189i32 as _); pub const E_IMAPI_RECORDER_MEDIA_NOT_FORMATTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600174i32 as _); pub const E_IMAPI_RECORDER_MEDIA_NO_MEDIA: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600190i32 as _); pub const E_IMAPI_RECORDER_MEDIA_SPEED_MISMATCH: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600177i32 as _); pub const E_IMAPI_RECORDER_MEDIA_UPSIDE_DOWN: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600188i32 as _); pub const E_IMAPI_RECORDER_MEDIA_WRITE_PROTECTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600183i32 as _); pub const E_IMAPI_RECORDER_NO_SUCH_FEATURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600182i32 as _); pub const E_IMAPI_RECORDER_NO_SUCH_MODE_PAGE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600191i32 as _); pub const E_IMAPI_RECORDER_REQUIRED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600701i32 as _); pub const E_IMAPI_REQUEST_CANCELLED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062600702i32 as _); pub const E_IMAPI_UNEXPECTED_RESPONSE_FROM_DEVICE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062599935i32 as _); #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EnableIdleRoutine<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(ftg: *mut ::core::ffi::c_void, fenable: Param1) { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EnableIdleRoutine(ftg: *mut ::core::ffi::c_void, fenable: super::super::Foundation::BOOL); } ::core::mem::transmute(EnableIdleRoutine(::core::mem::transmute(ftg), fenable.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } pub const FACILITY_IMAPI2: u32 = 170u32; #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn FEqualNames(lpname1: *mut MAPINAMEID, lpname2: *mut MAPINAMEID) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FEqualNames(lpname1: *mut MAPINAMEID, lpname2: *mut MAPINAMEID) -> super::super::Foundation::BOOL; } ::core::mem::transmute(FEqualNames(::core::mem::transmute(lpname1), ::core::mem::transmute(lpname2))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct FLATENTRY { pub cb: u32, pub abEntry: [u8; 1], } impl FLATENTRY {} impl ::core::default::Default for FLATENTRY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for FLATENTRY { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("FLATENTRY").field("cb", &self.cb).field("abEntry", &self.abEntry).finish() } } impl ::core::cmp::PartialEq for FLATENTRY { fn eq(&self, other: &Self) -> bool { self.cb == other.cb && self.abEntry == other.abEntry } } impl ::core::cmp::Eq for FLATENTRY {} unsafe impl ::windows::core::Abi for FLATENTRY { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct FLATENTRYLIST { pub cEntries: u32, pub cbEntries: u32, pub abEntries: [u8; 1], } impl FLATENTRYLIST {} impl ::core::default::Default for FLATENTRYLIST { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for FLATENTRYLIST { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("FLATENTRYLIST").field("cEntries", &self.cEntries).field("cbEntries", &self.cbEntries).field("abEntries", &self.abEntries).finish() } } impl ::core::cmp::PartialEq for FLATENTRYLIST { fn eq(&self, other: &Self) -> bool { self.cEntries == other.cEntries && self.cbEntries == other.cbEntries && self.abEntries == other.abEntries } } impl ::core::cmp::Eq for FLATENTRYLIST {} unsafe impl ::windows::core::Abi for FLATENTRYLIST { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct FLATMTSIDLIST { pub cMTSIDs: u32, pub cbMTSIDs: u32, pub abMTSIDs: [u8; 1], } impl FLATMTSIDLIST {} impl ::core::default::Default for FLATMTSIDLIST { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for FLATMTSIDLIST { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("FLATMTSIDLIST").field("cMTSIDs", &self.cMTSIDs).field("cbMTSIDs", &self.cbMTSIDs).field("abMTSIDs", &self.abMTSIDs).finish() } } impl ::core::cmp::PartialEq for FLATMTSIDLIST { fn eq(&self, other: &Self) -> bool { self.cMTSIDs == other.cMTSIDs && self.cbMTSIDs == other.cbMTSIDs && self.abMTSIDs == other.abMTSIDs } } impl ::core::cmp::Eq for FLATMTSIDLIST {} unsafe impl ::windows::core::Abi for FLATMTSIDLIST { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] pub type FNIDLE = unsafe extern "system" fn(param0: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn FPropCompareProp(lpspropvalue1: *mut SPropValue, ulrelop: u32, lpspropvalue2: *mut SPropValue) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FPropCompareProp(lpspropvalue1: *mut SPropValue, ulrelop: u32, lpspropvalue2: *mut SPropValue) -> super::super::Foundation::BOOL; } ::core::mem::transmute(FPropCompareProp(::core::mem::transmute(lpspropvalue1), ::core::mem::transmute(ulrelop), ::core::mem::transmute(lpspropvalue2))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn FPropContainsProp(lpspropvaluedst: *mut SPropValue, lpspropvaluesrc: *mut SPropValue, ulfuzzylevel: u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FPropContainsProp(lpspropvaluedst: *mut SPropValue, lpspropvaluesrc: *mut SPropValue, ulfuzzylevel: u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(FPropContainsProp(::core::mem::transmute(lpspropvaluedst), ::core::mem::transmute(lpspropvaluesrc), ::core::mem::transmute(ulfuzzylevel))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn FPropExists<'a, Param0: ::windows::core::IntoParam<'a, IMAPIProp>>(lpmapiprop: Param0, ulproptag: u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FPropExists(lpmapiprop: ::windows::core::RawPtr, ulproptag: u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(FPropExists(lpmapiprop.into_param().abi(), ::core::mem::transmute(ulproptag))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn FreePadrlist(lpadrlist: *mut ADRLIST) { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FreePadrlist(lpadrlist: *mut ADRLIST); } ::core::mem::transmute(FreePadrlist(::core::mem::transmute(lpadrlist))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn FreeProws(lprows: *mut SRowSet) { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FreeProws(lprows: *mut SRowSet); } ::core::mem::transmute(FreeProws(::core::mem::transmute(lprows))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn FtAddFt<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::FILETIME>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::FILETIME>>(ftaddend1: Param0, ftaddend2: Param1) -> super::super::Foundation::FILETIME { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FtAddFt(ftaddend1: super::super::Foundation::FILETIME, ftaddend2: super::super::Foundation::FILETIME) -> super::super::Foundation::FILETIME; } ::core::mem::transmute(FtAddFt(ftaddend1.into_param().abi(), ftaddend2.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn FtMulDw<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::FILETIME>>(ftmultiplier: u32, ftmultiplicand: Param1) -> super::super::Foundation::FILETIME { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FtMulDw(ftmultiplier: u32, ftmultiplicand: super::super::Foundation::FILETIME) -> super::super::Foundation::FILETIME; } ::core::mem::transmute(FtMulDw(::core::mem::transmute(ftmultiplier), ftmultiplicand.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn FtMulDwDw(ftmultiplicand: u32, ftmultiplier: u32) -> super::super::Foundation::FILETIME { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FtMulDwDw(ftmultiplicand: u32, ftmultiplier: u32) -> super::super::Foundation::FILETIME; } ::core::mem::transmute(FtMulDwDw(::core::mem::transmute(ftmultiplicand), ::core::mem::transmute(ftmultiplier))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn FtNegFt<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::FILETIME>>(ft: Param0) -> super::super::Foundation::FILETIME { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FtNegFt(ft: super::super::Foundation::FILETIME) -> super::super::Foundation::FILETIME; } ::core::mem::transmute(FtNegFt(ft.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn FtSubFt<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::FILETIME>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::FILETIME>>(ftminuend: Param0, ftsubtrahend: Param1) -> super::super::Foundation::FILETIME { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FtSubFt(ftminuend: super::super::Foundation::FILETIME, ftsubtrahend: super::super::Foundation::FILETIME) -> super::super::Foundation::FILETIME; } ::core::mem::transmute(FtSubFt(ftminuend.into_param().abi(), ftsubtrahend.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn FtgRegisterIdleRoutine(lpfnidle: ::core::option::Option<PFNIDLE>, lpvidleparam: *mut ::core::ffi::c_void, priidle: i16, csecidle: u32, iroidle: u16) -> *mut ::core::ffi::c_void { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FtgRegisterIdleRoutine(lpfnidle: ::windows::core::RawPtr, lpvidleparam: *mut ::core::ffi::c_void, priidle: i16, csecidle: u32, iroidle: u16) -> *mut ::core::ffi::c_void; } ::core::mem::transmute(FtgRegisterIdleRoutine(::core::mem::transmute(lpfnidle), ::core::mem::transmute(lpvidleparam), ::core::mem::transmute(priidle), ::core::mem::transmute(csecidle), ::core::mem::transmute(iroidle))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct Gender(pub i32); pub const genderUnspecified: Gender = Gender(0i32); pub const genderFemale: Gender = Gender(1i32); pub const genderMale: Gender = Gender(2i32); impl ::core::convert::From<i32> for Gender { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for Gender { type Abi = Self; } #[inline] pub unsafe fn HrAddColumns<'a, Param0: ::windows::core::IntoParam<'a, IMAPITable>>(lptbl: Param0, lpproptagcolumnsnew: *mut SPropTagArray, lpallocatebuffer: ::core::option::Option<LPALLOCATEBUFFER>, lpfreebuffer: ::core::option::Option<LPFREEBUFFER>) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HrAddColumns(lptbl: ::windows::core::RawPtr, lpproptagcolumnsnew: *mut SPropTagArray, lpallocatebuffer: ::windows::core::RawPtr, lpfreebuffer: ::windows::core::RawPtr) -> ::windows::core::HRESULT; } HrAddColumns(lptbl.into_param().abi(), ::core::mem::transmute(lpproptagcolumnsnew), ::core::mem::transmute(lpallocatebuffer), ::core::mem::transmute(lpfreebuffer)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HrAddColumnsEx<'a, Param0: ::windows::core::IntoParam<'a, IMAPITable>>(lptbl: Param0, lpproptagcolumnsnew: *mut SPropTagArray, lpallocatebuffer: ::core::option::Option<LPALLOCATEBUFFER>, lpfreebuffer: ::core::option::Option<LPFREEBUFFER>, lpfnfiltercolumns: isize) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HrAddColumnsEx(lptbl: ::windows::core::RawPtr, lpproptagcolumnsnew: *mut SPropTagArray, lpallocatebuffer: ::windows::core::RawPtr, lpfreebuffer: ::windows::core::RawPtr, lpfnfiltercolumns: isize) -> ::windows::core::HRESULT; } HrAddColumnsEx(lptbl.into_param().abi(), ::core::mem::transmute(lpproptagcolumnsnew), ::core::mem::transmute(lpallocatebuffer), ::core::mem::transmute(lpfreebuffer), ::core::mem::transmute(lpfnfiltercolumns)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn HrAllocAdviseSink(lpfncallback: ::core::option::Option<LPNOTIFCALLBACK>, lpvcontext: *mut ::core::ffi::c_void, lppadvisesink: *mut ::core::option::Option<IMAPIAdviseSink>) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HrAllocAdviseSink(lpfncallback: ::windows::core::RawPtr, lpvcontext: *mut ::core::ffi::c_void, lppadvisesink: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; } HrAllocAdviseSink(::core::mem::transmute(lpfncallback), ::core::mem::transmute(lpvcontext), ::core::mem::transmute(lppadvisesink)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HrDispatchNotifications(ulflags: u32) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HrDispatchNotifications(ulflags: u32) -> ::windows::core::HRESULT; } HrDispatchNotifications(::core::mem::transmute(ulflags)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn HrGetOneProp<'a, Param0: ::windows::core::IntoParam<'a, IMAPIProp>>(lpmapiprop: Param0, ulproptag: u32, lppprop: *mut *mut SPropValue) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HrGetOneProp(lpmapiprop: ::windows::core::RawPtr, ulproptag: u32, lppprop: *mut *mut SPropValue) -> ::windows::core::HRESULT; } HrGetOneProp(lpmapiprop.into_param().abi(), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lppprop)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_System_Com_StructuredStorage")] #[inline] pub unsafe fn HrIStorageFromStream<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(lpunkin: Param0, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lppstorageout: *mut ::core::option::Option<super::Com::StructuredStorage::IStorage>) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HrIStorageFromStream(lpunkin: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lppstorageout: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; } HrIStorageFromStream(lpunkin.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppstorageout)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn HrQueryAllRows<'a, Param0: ::windows::core::IntoParam<'a, IMAPITable>>(lptable: Param0, lpproptags: *mut SPropTagArray, lprestriction: *mut SRestriction, lpsortorderset: *mut SSortOrderSet, crowsmax: i32, lpprows: *mut *mut SRowSet) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HrQueryAllRows(lptable: ::windows::core::RawPtr, lpproptags: *mut SPropTagArray, lprestriction: *mut SRestriction, lpsortorderset: *mut SSortOrderSet, crowsmax: i32, lpprows: *mut *mut SRowSet) -> ::windows::core::HRESULT; } HrQueryAllRows(lptable.into_param().abi(), ::core::mem::transmute(lpproptags), ::core::mem::transmute(lprestriction), ::core::mem::transmute(lpsortorderset), ::core::mem::transmute(crowsmax), ::core::mem::transmute(lpprows)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn HrSetOneProp<'a, Param0: ::windows::core::IntoParam<'a, IMAPIProp>>(lpmapiprop: Param0, lpprop: *mut SPropValue) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HrSetOneProp(lpmapiprop: ::windows::core::RawPtr, lpprop: *mut SPropValue) -> ::windows::core::HRESULT; } HrSetOneProp(lpmapiprop.into_param().abi(), ::core::mem::transmute(lpprop)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HrThisThreadAdviseSink<'a, Param0: ::windows::core::IntoParam<'a, IMAPIAdviseSink>>(lpadvisesink: Param0) -> ::windows::core::Result<IMAPIAdviseSink> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HrThisThreadAdviseSink(lpadvisesink: ::windows::core::RawPtr, lppadvisesink: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; } let mut result__: <IMAPIAdviseSink as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HrThisThreadAdviseSink(lpadvisesink.into_param().abi(), &mut result__).from_abi::<IMAPIAdviseSink>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IABContainer(pub ::windows::core::IUnknown); impl IABContainer { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } pub unsafe fn GetContentsTable(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } pub unsafe fn GetHierarchyTable(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } pub unsafe fn OpenEntry(&self, cbentryid: u32, lpentryid: *const ENTRYID, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lpulobjtype: *mut u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(lpinterface), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpulobjtype), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetSearchCriteria(&self, lprestriction: *const SRestriction, lpcontainerlist: *const SBinaryArray, ulsearchflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(lprestriction), ::core::mem::transmute(lpcontainerlist), ::core::mem::transmute(ulsearchflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetSearchCriteria(&self, ulflags: u32, lpprestriction: *mut *mut SRestriction, lppcontainerlist: *mut *mut SBinaryArray, lpulsearchstate: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpprestriction), ::core::mem::transmute(lppcontainerlist), ::core::mem::transmute(lpulsearchstate)).ok() } pub unsafe fn CreateEntry(&self, cbentryid: u32, lpentryid: *const ENTRYID, ulcreateflags: u32) -> ::windows::core::Result<IMAPIProp> { let mut result__: <IMAPIProp as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(ulcreateflags), &mut result__).from_abi::<IMAPIProp>(result__) } pub unsafe fn CopyEntries<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpentries: *const SBinaryArray, uluiparam: usize, lpprogress: Param2, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpentries), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn DeleteEntries(&self, lpentries: *const SBinaryArray, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpentries), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn ResolveNames(&self, lpproptagarray: *const SPropTagArray, ulflags: u32, lpadrlist: *const ADRLIST) -> ::windows::core::Result<_flaglist> { let mut result__: <_flaglist as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpadrlist), &mut result__).from_abi::<_flaglist>(result__) } } unsafe impl ::windows::core::Interface for IABContainer { type Vtable = IABContainer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IABContainer> for ::windows::core::IUnknown { fn from(value: IABContainer) -> Self { value.0 } } impl ::core::convert::From<&IABContainer> for ::windows::core::IUnknown { fn from(value: &IABContainer) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IABContainer { 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 IABContainer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IABContainer> for IMAPIContainer { fn from(value: IABContainer) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IABContainer> for IMAPIContainer { fn from(value: &IABContainer) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIContainer> for IABContainer { fn into_param(self) -> ::windows::core::Param<'a, IMAPIContainer> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIContainer> for &IABContainer { fn into_param(self) -> ::windows::core::Param<'a, IMAPIContainer> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } impl ::core::convert::From<IABContainer> for IMAPIProp { fn from(value: IABContainer) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IABContainer> for IMAPIProp { fn from(value: &IABContainer) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for IABContainer { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for &IABContainer { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IABContainer_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lpulobjtype: *mut u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lprestriction: *const SRestriction, lpcontainerlist: *const SBinaryArray, ulsearchflags: u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpprestriction: *mut *mut SRestriction, lppcontainerlist: *mut *mut SBinaryArray, lpulsearchstate: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, ulcreateflags: u32, lppmapipropentry: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpentries: *const SBinaryArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpentries: *const SBinaryArray, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *const SPropTagArray, ulflags: u32, lpadrlist: *const ADRLIST, lpflaglist: *mut _flaglist) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IAddrBook(pub ::windows::core::IUnknown); impl IAddrBook { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } pub unsafe fn OpenEntry(&self, cbentryid: u32, lpentryid: *mut ENTRYID, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lpulobjtype: *mut u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(lpinterface), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpulobjtype), ::core::mem::transmute(lppunk)).ok() } pub unsafe fn CompareEntryIDs(&self, cbentryid1: u32, lpentryid1: *mut ENTRYID, cbentryid2: u32, lpentryid2: *mut ENTRYID, ulflags: u32, lpulresult: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid1), ::core::mem::transmute(lpentryid1), ::core::mem::transmute(cbentryid2), ::core::mem::transmute(lpentryid2), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpulresult)).ok() } pub unsafe fn Advise<'a, Param3: ::windows::core::IntoParam<'a, IMAPIAdviseSink>>(&self, cbentryid: u32, lpentryid: *mut ENTRYID, uleventmask: u32, lpadvisesink: Param3, lpulconnection: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(uleventmask), lpadvisesink.into_param().abi(), ::core::mem::transmute(lpulconnection)).ok() } pub unsafe fn Unadvise(&self, ulconnection: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulconnection)).ok() } pub unsafe fn CreateOneOff(&self, lpszname: *mut i8, lpszadrtype: *mut i8, lpszaddress: *mut i8, ulflags: u32, lpcbentryid: *mut u32, lppentryid: *mut *mut ENTRYID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpszname), ::core::mem::transmute(lpszadrtype), ::core::mem::transmute(lpszaddress), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcbentryid), ::core::mem::transmute(lppentryid)).ok() } pub unsafe fn NewEntry(&self, uluiparam: u32, ulflags: u32, cbeidcontainer: u32, lpeidcontainer: *mut ENTRYID, cbeidnewentrytpl: u32, lpeidnewentrytpl: *mut ENTRYID, lpcbeidnewentry: *mut u32, lppeidnewentry: *mut *mut ENTRYID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).19)( ::core::mem::transmute_copy(self), ::core::mem::transmute(uluiparam), ::core::mem::transmute(ulflags), ::core::mem::transmute(cbeidcontainer), ::core::mem::transmute(lpeidcontainer), ::core::mem::transmute(cbeidnewentrytpl), ::core::mem::transmute(lpeidnewentrytpl), ::core::mem::transmute(lpcbeidnewentry), ::core::mem::transmute(lppeidnewentry), ) .ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn ResolveName(&self, uluiparam: usize, ulflags: u32, lpsznewentrytitle: *mut i8, lpadrlist: *mut ADRLIST) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), ::core::mem::transmute(uluiparam), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpsznewentrytitle), ::core::mem::transmute(lpadrlist)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn Address(&self, lpuluiparam: *mut u32, lpadrparms: *mut ADRPARM, lppadrlist: *mut *mut ADRLIST) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpuluiparam), ::core::mem::transmute(lpadrparms), ::core::mem::transmute(lppadrlist)).ok() } pub unsafe fn Details(&self, lpuluiparam: *mut usize, lpfndismiss: ::core::option::Option<LPFNDISMISS>, lpvdismisscontext: *mut ::core::ffi::c_void, cbentryid: u32, lpentryid: *mut ENTRYID, lpfbuttoncallback: ::core::option::Option<LPFNBUTTON>, lpvbuttoncontext: *mut ::core::ffi::c_void, lpszbuttontext: *mut i8, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).22)( ::core::mem::transmute_copy(self), ::core::mem::transmute(lpuluiparam), ::core::mem::transmute(lpfndismiss), ::core::mem::transmute(lpvdismisscontext), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(lpfbuttoncallback), ::core::mem::transmute(lpvbuttoncontext), ::core::mem::transmute(lpszbuttontext), ::core::mem::transmute(ulflags), ) .ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn RecipOptions(&self, uluiparam: u32, ulflags: u32, lprecip: *mut ADRENTRY) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).23)(::core::mem::transmute_copy(self), ::core::mem::transmute(uluiparam), ::core::mem::transmute(ulflags), ::core::mem::transmute(lprecip)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn QueryDefaultRecipOpt(&self, lpszadrtype: *mut i8, ulflags: u32, lpcvalues: *mut u32, lppoptions: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).24)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpszadrtype), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppoptions)).ok() } pub unsafe fn GetPAB(&self, lpcbentryid: *mut u32, lppentryid: *mut *mut ENTRYID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).25)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpcbentryid), ::core::mem::transmute(lppentryid)).ok() } pub unsafe fn SetPAB(&self, cbentryid: u32, lpentryid: *mut ENTRYID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).26)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid)).ok() } pub unsafe fn GetDefaultDir(&self, lpcbentryid: *mut u32, lppentryid: *mut *mut ENTRYID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).27)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpcbentryid), ::core::mem::transmute(lppentryid)).ok() } pub unsafe fn SetDefaultDir(&self, cbentryid: u32, lpentryid: *mut ENTRYID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).28)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetSearchPath(&self, ulflags: u32, lppsearchpath: *mut *mut SRowSet) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).29)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppsearchpath)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetSearchPath(&self, ulflags: u32, lpsearchpath: *mut SRowSet) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).30)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpsearchpath)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn PrepareRecips(&self, ulflags: u32, lpproptagarray: *mut SPropTagArray, lpreciplist: *mut ADRLIST) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).31)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lpreciplist)).ok() } } unsafe impl ::windows::core::Interface for IAddrBook { type Vtable = IAddrBook_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IAddrBook> for ::windows::core::IUnknown { fn from(value: IAddrBook) -> Self { value.0 } } impl ::core::convert::From<&IAddrBook> for ::windows::core::IUnknown { fn from(value: &IAddrBook) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAddrBook { 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 IAddrBook { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IAddrBook> for IMAPIProp { fn from(value: IAddrBook) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IAddrBook> for IMAPIProp { fn from(value: &IAddrBook) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for IAddrBook { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for &IAddrBook { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IAddrBook_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *mut ENTRYID, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lpulobjtype: *mut u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid1: u32, lpentryid1: *mut ENTRYID, cbentryid2: u32, lpentryid2: *mut ENTRYID, ulflags: u32, lpulresult: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *mut ENTRYID, uleventmask: u32, lpadvisesink: ::windows::core::RawPtr, lpulconnection: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulconnection: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpszname: *mut i8, lpszadrtype: *mut i8, lpszaddress: *mut i8, ulflags: u32, lpcbentryid: *mut u32, lppentryid: *mut *mut ENTRYID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uluiparam: u32, ulflags: u32, cbeidcontainer: u32, lpeidcontainer: *mut ENTRYID, cbeidnewentrytpl: u32, lpeidnewentrytpl: *mut ENTRYID, lpcbeidnewentry: *mut u32, lppeidnewentry: *mut *mut ENTRYID) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uluiparam: usize, ulflags: u32, lpsznewentrytitle: *mut i8, lpadrlist: *mut ADRLIST) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpuluiparam: *mut u32, lpadrparms: *mut ::core::mem::ManuallyDrop<ADRPARM>, lppadrlist: *mut *mut ADRLIST) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpuluiparam: *mut usize, lpfndismiss: ::windows::core::RawPtr, lpvdismisscontext: *mut ::core::ffi::c_void, cbentryid: u32, lpentryid: *mut ENTRYID, lpfbuttoncallback: ::windows::core::RawPtr, lpvbuttoncontext: *mut ::core::ffi::c_void, lpszbuttontext: *mut i8, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uluiparam: u32, ulflags: u32, lprecip: *mut ADRENTRY) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpszadrtype: *mut i8, ulflags: u32, lpcvalues: *mut u32, lppoptions: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpcbentryid: *mut u32, lppentryid: *mut *mut ENTRYID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *mut ENTRYID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpcbentryid: *mut u32, lppentryid: *mut *mut ENTRYID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *mut ENTRYID) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppsearchpath: *mut *mut SRowSet) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpsearchpath: *mut SRowSet) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpproptagarray: *mut SPropTagArray, lpreciplist: *mut ADRLIST) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IAttach(pub ::windows::core::IUnknown); impl IAttach { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } } unsafe impl ::windows::core::Interface for IAttach { type Vtable = IAttach_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IAttach> for ::windows::core::IUnknown { fn from(value: IAttach) -> Self { value.0 } } impl ::core::convert::From<&IAttach> for ::windows::core::IUnknown { fn from(value: &IAttach) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAttach { 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 IAttach { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IAttach> for IMAPIProp { fn from(value: IAttach) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IAttach> for IMAPIProp { fn from(value: &IAttach) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for IAttach { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for &IAttach { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IAttach_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::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 IDistList(pub ::windows::core::IUnknown); impl IDistList { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } pub unsafe fn GetContentsTable(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } pub unsafe fn GetHierarchyTable(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } pub unsafe fn OpenEntry(&self, cbentryid: u32, lpentryid: *const ENTRYID, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lpulobjtype: *mut u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(lpinterface), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpulobjtype), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetSearchCriteria(&self, lprestriction: *const SRestriction, lpcontainerlist: *const SBinaryArray, ulsearchflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(lprestriction), ::core::mem::transmute(lpcontainerlist), ::core::mem::transmute(ulsearchflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetSearchCriteria(&self, ulflags: u32, lpprestriction: *mut *mut SRestriction, lppcontainerlist: *mut *mut SBinaryArray, lpulsearchstate: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpprestriction), ::core::mem::transmute(lppcontainerlist), ::core::mem::transmute(lpulsearchstate)).ok() } pub unsafe fn CreateEntry(&self, cbentryid: u32, lpentryid: *const ENTRYID, ulcreateflags: u32) -> ::windows::core::Result<IMAPIProp> { let mut result__: <IMAPIProp as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(ulcreateflags), &mut result__).from_abi::<IMAPIProp>(result__) } pub unsafe fn CopyEntries<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpentries: *const SBinaryArray, uluiparam: usize, lpprogress: Param2, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpentries), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn DeleteEntries(&self, lpentries: *const SBinaryArray, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpentries), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn ResolveNames(&self, lpproptagarray: *const SPropTagArray, ulflags: u32, lpadrlist: *const ADRLIST) -> ::windows::core::Result<_flaglist> { let mut result__: <_flaglist as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpadrlist), &mut result__).from_abi::<_flaglist>(result__) } } unsafe impl ::windows::core::Interface for IDistList { type Vtable = IDistList_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IDistList> for ::windows::core::IUnknown { fn from(value: IDistList) -> Self { value.0 } } impl ::core::convert::From<&IDistList> for ::windows::core::IUnknown { fn from(value: &IDistList) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDistList { 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 IDistList { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IDistList> for IMAPIContainer { fn from(value: IDistList) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IDistList> for IMAPIContainer { fn from(value: &IDistList) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIContainer> for IDistList { fn into_param(self) -> ::windows::core::Param<'a, IMAPIContainer> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIContainer> for &IDistList { fn into_param(self) -> ::windows::core::Param<'a, IMAPIContainer> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } impl ::core::convert::From<IDistList> for IMAPIProp { fn from(value: IDistList) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IDistList> for IMAPIProp { fn from(value: &IDistList) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for IDistList { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for &IDistList { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IDistList_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lpulobjtype: *mut u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lprestriction: *const SRestriction, lpcontainerlist: *const SBinaryArray, ulsearchflags: u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpprestriction: *mut *mut SRestriction, lppcontainerlist: *mut *mut SBinaryArray, lpulsearchstate: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, ulcreateflags: u32, lppmapipropentry: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpentries: *const SBinaryArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpentries: *const SBinaryArray, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *const SPropTagArray, ulflags: u32, lpadrlist: *const ADRLIST, lpflaglist: *mut _flaglist) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMAPIAdviseSink(pub ::windows::core::IUnknown); impl IMAPIAdviseSink { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn OnNotify(&self, cnotif: u32, lpnotifications: *mut NOTIFICATION) -> u32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(cnotif), ::core::mem::transmute(lpnotifications))) } } unsafe impl ::windows::core::Interface for IMAPIAdviseSink { type Vtable = IMAPIAdviseSink_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IMAPIAdviseSink> for ::windows::core::IUnknown { fn from(value: IMAPIAdviseSink) -> Self { value.0 } } impl ::core::convert::From<&IMAPIAdviseSink> for ::windows::core::IUnknown { fn from(value: &IMAPIAdviseSink) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMAPIAdviseSink { 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 IMAPIAdviseSink { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMAPIAdviseSink_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cnotif: u32, lpnotifications: *mut NOTIFICATION) -> u32, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMAPIContainer(pub ::windows::core::IUnknown); impl IMAPIContainer { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } pub unsafe fn GetContentsTable(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } pub unsafe fn GetHierarchyTable(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } pub unsafe fn OpenEntry(&self, cbentryid: u32, lpentryid: *const ENTRYID, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lpulobjtype: *mut u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(lpinterface), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpulobjtype), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetSearchCriteria(&self, lprestriction: *const SRestriction, lpcontainerlist: *const SBinaryArray, ulsearchflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(lprestriction), ::core::mem::transmute(lpcontainerlist), ::core::mem::transmute(ulsearchflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetSearchCriteria(&self, ulflags: u32, lpprestriction: *mut *mut SRestriction, lppcontainerlist: *mut *mut SBinaryArray, lpulsearchstate: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpprestriction), ::core::mem::transmute(lppcontainerlist), ::core::mem::transmute(lpulsearchstate)).ok() } } unsafe impl ::windows::core::Interface for IMAPIContainer { type Vtable = IMAPIContainer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IMAPIContainer> for ::windows::core::IUnknown { fn from(value: IMAPIContainer) -> Self { value.0 } } impl ::core::convert::From<&IMAPIContainer> for ::windows::core::IUnknown { fn from(value: &IMAPIContainer) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMAPIContainer { 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 IMAPIContainer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IMAPIContainer> for IMAPIProp { fn from(value: IMAPIContainer) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IMAPIContainer> for IMAPIProp { fn from(value: &IMAPIContainer) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for IMAPIContainer { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for &IMAPIContainer { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IMAPIContainer_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lpulobjtype: *mut u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lprestriction: *const SRestriction, lpcontainerlist: *const SBinaryArray, ulsearchflags: u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpprestriction: *mut *mut SRestriction, lppcontainerlist: *mut *mut SBinaryArray, lpulsearchstate: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMAPIControl(pub ::windows::core::IUnknown); impl IMAPIControl { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32) -> ::windows::core::Result<*mut MAPIERROR> { let mut result__: <*mut MAPIERROR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), &mut result__).from_abi::<*mut MAPIERROR>(result__) } pub unsafe fn Activate(&self, ulflags: u32, uluiparam: usize) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(uluiparam)).ok() } pub unsafe fn GetState(&self, ulflags: u32, lpulstate: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpulstate)).ok() } } unsafe impl ::windows::core::Interface for IMAPIControl { type Vtable = IMAPIControl_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IMAPIControl> for ::windows::core::IUnknown { fn from(value: IMAPIControl) -> Self { value.0 } } impl ::core::convert::From<&IMAPIControl> for ::windows::core::IUnknown { fn from(value: &IMAPIControl) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMAPIControl { 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 IMAPIControl { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMAPIControl_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, uluiparam: usize) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpulstate: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMAPIFolder(pub ::windows::core::IUnknown); impl IMAPIFolder { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } pub unsafe fn GetContentsTable(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } pub unsafe fn GetHierarchyTable(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } pub unsafe fn OpenEntry(&self, cbentryid: u32, lpentryid: *const ENTRYID, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lpulobjtype: *mut u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(lpinterface), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpulobjtype), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetSearchCriteria(&self, lprestriction: *const SRestriction, lpcontainerlist: *const SBinaryArray, ulsearchflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(lprestriction), ::core::mem::transmute(lpcontainerlist), ::core::mem::transmute(ulsearchflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetSearchCriteria(&self, ulflags: u32, lpprestriction: *mut *mut SRestriction, lppcontainerlist: *mut *mut SBinaryArray, lpulsearchstate: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpprestriction), ::core::mem::transmute(lppcontainerlist), ::core::mem::transmute(lpulsearchstate)).ok() } pub unsafe fn CreateMessage(&self, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lppmessage: *mut ::core::option::Option<IMessage>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpinterface), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmessage)).ok() } pub unsafe fn CopyMessages<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpmsglist: *const SBinaryArray, lpinterface: *const ::windows::core::GUID, lpdestfolder: *const ::core::ffi::c_void, uluiparam: usize, lpprogress: Param4, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpmsglist), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestfolder), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn DeleteMessages<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpmsglist: *const SBinaryArray, uluiparam: usize, lpprogress: Param2, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpmsglist), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn CreateFolder(&self, ulfoldertype: u32, lpszfoldername: *const i8, lpszfoldercomment: *const i8, lpinterface: *const ::windows::core::GUID, ulflags: u32) -> ::windows::core::Result<IMAPIFolder> { let mut result__: <IMAPIFolder as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulfoldertype), ::core::mem::transmute(lpszfoldername), ::core::mem::transmute(lpszfoldercomment), ::core::mem::transmute(lpinterface), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPIFolder>(result__) } pub unsafe fn CopyFolder<'a, Param6: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, cbentryid: u32, lpentryid: *const ENTRYID, lpinterface: *const ::windows::core::GUID, lpdestfolder: *const ::core::ffi::c_void, lpsznewfoldername: *const i8, uluiparam: usize, lpprogress: Param6, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).23)( ::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestfolder), ::core::mem::transmute(lpsznewfoldername), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(ulflags), ) .ok() } pub unsafe fn DeleteFolder<'a, Param3: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, cbentryid: u32, lpentryid: *const ENTRYID, uluiparam: usize, lpprogress: Param3, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).24)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn SetReadFlags<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpmsglist: *const SBinaryArray, uluiparam: usize, lpprogress: Param2, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).25)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpmsglist), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn GetMessageStatus(&self, cbentryid: u32, lpentryid: *const ENTRYID, ulflags: u32) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).26)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(ulflags), &mut result__).from_abi::<u32>(result__) } pub unsafe fn SetMessageStatus(&self, cbentryid: u32, lpentryid: *const ENTRYID, ulnewstatus: u32, ulnewstatusmask: u32) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).27)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(ulnewstatus), ::core::mem::transmute(ulnewstatusmask), &mut result__).from_abi::<u32>(result__) } pub unsafe fn SaveContentsSort(&self, lpsortcriteria: *const SSortOrderSet, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).28)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpsortcriteria), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn EmptyFolder<'a, Param1: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, uluiparam: usize, lpprogress: Param1, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).29)(::core::mem::transmute_copy(self), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(ulflags)).ok() } } unsafe impl ::windows::core::Interface for IMAPIFolder { type Vtable = IMAPIFolder_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IMAPIFolder> for ::windows::core::IUnknown { fn from(value: IMAPIFolder) -> Self { value.0 } } impl ::core::convert::From<&IMAPIFolder> for ::windows::core::IUnknown { fn from(value: &IMAPIFolder) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMAPIFolder { 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 IMAPIFolder { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IMAPIFolder> for IMAPIContainer { fn from(value: IMAPIFolder) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IMAPIFolder> for IMAPIContainer { fn from(value: &IMAPIFolder) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIContainer> for IMAPIFolder { fn into_param(self) -> ::windows::core::Param<'a, IMAPIContainer> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIContainer> for &IMAPIFolder { fn into_param(self) -> ::windows::core::Param<'a, IMAPIContainer> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } impl ::core::convert::From<IMAPIFolder> for IMAPIProp { fn from(value: IMAPIFolder) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IMAPIFolder> for IMAPIProp { fn from(value: &IMAPIFolder) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for IMAPIFolder { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for &IMAPIFolder { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IMAPIFolder_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lpulobjtype: *mut u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lprestriction: *const SRestriction, lpcontainerlist: *const SBinaryArray, ulsearchflags: u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpprestriction: *mut *mut SRestriction, lppcontainerlist: *mut *mut SBinaryArray, lpulsearchstate: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, ulflags: u32, lppmessage: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpmsglist: *const SBinaryArray, lpinterface: *const ::windows::core::GUID, lpdestfolder: *const ::core::ffi::c_void, uluiparam: usize, lpprogress: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpmsglist: *const SBinaryArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulfoldertype: u32, lpszfoldername: *const i8, lpszfoldercomment: *const i8, lpinterface: *const ::windows::core::GUID, ulflags: u32, lppfolder: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, lpinterface: *const ::windows::core::GUID, lpdestfolder: *const ::core::ffi::c_void, lpsznewfoldername: *const i8, uluiparam: usize, lpprogress: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, uluiparam: usize, lpprogress: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpmsglist: *const SBinaryArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, ulflags: u32, lpulmessagestatus: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, ulnewstatus: u32, ulnewstatusmask: u32, lpuloldstatus: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpsortcriteria: *const SSortOrderSet, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uluiparam: usize, lpprogress: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMAPIProgress(pub ::windows::core::IUnknown); impl IMAPIProgress { pub unsafe fn Progress(&self, ulvalue: u32, ulcount: u32, ultotal: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulvalue), ::core::mem::transmute(ulcount), ::core::mem::transmute(ultotal)).ok() } pub unsafe fn GetFlags(&self, lpulflags: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpulflags)).ok() } pub unsafe fn GetMax(&self, lpulmax: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpulmax)).ok() } pub unsafe fn GetMin(&self, lpulmin: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpulmin)).ok() } pub unsafe fn SetLimits(&self, lpulmin: *mut u32, lpulmax: *mut u32, lpulflags: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpulmin), ::core::mem::transmute(lpulmax), ::core::mem::transmute(lpulflags)).ok() } } unsafe impl ::windows::core::Interface for IMAPIProgress { type Vtable = IMAPIProgress_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IMAPIProgress> for ::windows::core::IUnknown { fn from(value: IMAPIProgress) -> Self { value.0 } } impl ::core::convert::From<&IMAPIProgress> for ::windows::core::IUnknown { fn from(value: &IMAPIProgress) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMAPIProgress { 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 IMAPIProgress { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMAPIProgress_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, ulvalue: u32, ulcount: u32, ultotal: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpulflags: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpulmax: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpulmin: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpulmin: *mut u32, lpulmax: *mut u32, lpulflags: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMAPIProp(pub ::windows::core::IUnknown); impl IMAPIProp { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } } unsafe impl ::windows::core::Interface for IMAPIProp { type Vtable = IMAPIProp_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IMAPIProp> for ::windows::core::IUnknown { fn from(value: IMAPIProp) -> Self { value.0 } } impl ::core::convert::From<&IMAPIProp> for ::windows::core::IUnknown { fn from(value: &IMAPIProp) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMAPIProp { 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 IMAPIProp { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMAPIProp_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::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 IMAPIStatus(pub ::windows::core::IUnknown); impl IMAPIStatus { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } pub unsafe fn ValidateState(&self, uluiparam: usize, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(uluiparam), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn SettingsDialog(&self, uluiparam: usize, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(uluiparam), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn ChangePassword(&self, lpoldpass: *const i8, lpnewpass: *const i8, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpoldpass), ::core::mem::transmute(lpnewpass), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn FlushQueues(&self, uluiparam: usize, cbtargettransport: u32, lptargettransport: *const ENTRYID, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(uluiparam), ::core::mem::transmute(cbtargettransport), ::core::mem::transmute(lptargettransport), ::core::mem::transmute(ulflags)).ok() } } unsafe impl ::windows::core::Interface for IMAPIStatus { type Vtable = IMAPIStatus_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IMAPIStatus> for ::windows::core::IUnknown { fn from(value: IMAPIStatus) -> Self { value.0 } } impl ::core::convert::From<&IMAPIStatus> for ::windows::core::IUnknown { fn from(value: &IMAPIStatus) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMAPIStatus { 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 IMAPIStatus { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IMAPIStatus> for IMAPIProp { fn from(value: IMAPIStatus) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IMAPIStatus> for IMAPIProp { fn from(value: &IMAPIStatus) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for IMAPIStatus { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for &IMAPIStatus { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IMAPIStatus_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uluiparam: usize, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uluiparam: usize, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpoldpass: *const i8, lpnewpass: *const i8, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uluiparam: usize, cbtargettransport: u32, lptargettransport: *const ENTRYID, ulflags: u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMAPITable(pub ::windows::core::IUnknown); impl IMAPITable { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn Advise<'a, Param1: ::windows::core::IntoParam<'a, IMAPIAdviseSink>>(&self, uleventmask: u32, lpadvisesink: Param1, lpulconnection: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(uleventmask), lpadvisesink.into_param().abi(), ::core::mem::transmute(lpulconnection)).ok() } pub unsafe fn Unadvise(&self, ulconnection: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulconnection)).ok() } pub unsafe fn GetStatus(&self, lpultablestatus: *mut u32, lpultabletype: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpultablestatus), ::core::mem::transmute(lpultabletype)).ok() } pub unsafe fn SetColumns(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn QueryColumns(&self, ulflags: u32, lpproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpproptagarray)).ok() } pub unsafe fn GetRowCount(&self, ulflags: u32, lpulcount: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpulcount)).ok() } pub unsafe fn SeekRow(&self, bkorigin: u32, lrowcount: i32, lplrowssought: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(bkorigin), ::core::mem::transmute(lrowcount), ::core::mem::transmute(lplrowssought)).ok() } pub unsafe fn SeekRowApprox(&self, ulnumerator: u32, uldenominator: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulnumerator), ::core::mem::transmute(uldenominator)).ok() } pub unsafe fn QueryPosition(&self, lpulrow: *mut u32, lpulnumerator: *mut u32, lpuldenominator: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpulrow), ::core::mem::transmute(lpulnumerator), ::core::mem::transmute(lpuldenominator)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn FindRow(&self, lprestriction: *mut SRestriction, bkorigin: u32, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(lprestriction), ::core::mem::transmute(bkorigin), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn Restrict(&self, lprestriction: *mut SRestriction, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(lprestriction), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn CreateBookmark(&self, lpbkposition: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpbkposition)).ok() } pub unsafe fn FreeBookmark(&self, bkposition: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(bkposition)).ok() } pub unsafe fn SortTable(&self, lpsortcriteria: *mut SSortOrderSet, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpsortcriteria), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn QuerySortOrder(&self, lppsortcriteria: *mut *mut SSortOrderSet) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppsortcriteria)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn QueryRows(&self, lrowcount: i32, ulflags: u32, lpprows: *mut *mut SRowSet) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(lrowcount), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpprows)).ok() } pub unsafe fn Abort(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn ExpandRow(&self, cbinstancekey: u32, pbinstancekey: *mut u8, ulrowcount: u32, ulflags: u32, lpprows: *mut *mut SRowSet, lpulmorerows: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbinstancekey), ::core::mem::transmute(pbinstancekey), ::core::mem::transmute(ulrowcount), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpprows), ::core::mem::transmute(lpulmorerows)).ok() } pub unsafe fn CollapseRow(&self, cbinstancekey: u32, pbinstancekey: *mut u8, ulflags: u32, lpulrowcount: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbinstancekey), ::core::mem::transmute(pbinstancekey), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpulrowcount)).ok() } pub unsafe fn WaitForCompletion(&self, ulflags: u32, ultimeout: u32, lpultablestatus: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).23)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(ultimeout), ::core::mem::transmute(lpultablestatus)).ok() } pub unsafe fn GetCollapseState(&self, ulflags: u32, cbinstancekey: u32, lpbinstancekey: *mut u8, lpcbcollapsestate: *mut u32, lppbcollapsestate: *mut *mut u8) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).24)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(cbinstancekey), ::core::mem::transmute(lpbinstancekey), ::core::mem::transmute(lpcbcollapsestate), ::core::mem::transmute(lppbcollapsestate)).ok() } pub unsafe fn SetCollapseState(&self, ulflags: u32, cbcollapsestate: u32, pbcollapsestate: *mut u8, lpbklocation: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).25)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(cbcollapsestate), ::core::mem::transmute(pbcollapsestate), ::core::mem::transmute(lpbklocation)).ok() } } unsafe impl ::windows::core::Interface for IMAPITable { type Vtable = IMAPITable_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IMAPITable> for ::windows::core::IUnknown { fn from(value: IMAPITable) -> Self { value.0 } } impl ::core::convert::From<&IMAPITable> for ::windows::core::IUnknown { fn from(value: &IMAPITable) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMAPITable { 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 IMAPITable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMAPITable_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uleventmask: u32, lpadvisesink: ::windows::core::RawPtr, lpulconnection: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulconnection: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpultablestatus: *mut u32, lpultabletype: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpulcount: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bkorigin: u32, lrowcount: i32, lplrowssought: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulnumerator: u32, uldenominator: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpulrow: *mut u32, lpulnumerator: *mut u32, lpuldenominator: *mut u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lprestriction: *mut SRestriction, bkorigin: u32, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lprestriction: *mut SRestriction, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpbkposition: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bkposition: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpsortcriteria: *mut SSortOrderSet, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppsortcriteria: *mut *mut SSortOrderSet) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lrowcount: i32, ulflags: u32, lpprows: *mut *mut SRowSet) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbinstancekey: u32, pbinstancekey: *mut u8, ulrowcount: u32, ulflags: u32, lpprows: *mut *mut SRowSet, lpulmorerows: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbinstancekey: u32, pbinstancekey: *mut u8, ulflags: u32, lpulrowcount: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, ultimeout: u32, lpultablestatus: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, cbinstancekey: u32, lpbinstancekey: *mut u8, lpcbcollapsestate: *mut u32, lppbcollapsestate: *mut *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, cbcollapsestate: u32, pbcollapsestate: *mut u8, lpbklocation: *mut u32) -> ::windows::core::HRESULT, ); pub const IMAPI_E_BAD_MULTISESSION_PARAMETER: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555294i32 as _); pub const IMAPI_E_BOOT_EMULATION_IMAGE_SIZE_MISMATCH: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555318i32 as _); pub const IMAPI_E_BOOT_IMAGE_DATA: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555320i32 as _); pub const IMAPI_E_BOOT_OBJECT_CONFLICT: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555319i32 as _); pub const IMAPI_E_DATA_STREAM_CREATE_FAILURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555350i32 as _); pub const IMAPI_E_DATA_STREAM_INCONSISTENCY: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555352i32 as _); pub const IMAPI_E_DATA_STREAM_READ_FAILURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555351i32 as _); pub const IMAPI_E_DATA_TOO_BIG: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555342i32 as _); pub const IMAPI_E_DIRECTORY_READ_FAILURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555349i32 as _); pub const IMAPI_E_DIR_NOT_EMPTY: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555382i32 as _); pub const IMAPI_E_DIR_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555366i32 as _); pub const IMAPI_E_DISC_MISMATCH: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555304i32 as _); pub const IMAPI_E_DUP_NAME: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555374i32 as _); pub const IMAPI_E_EMPTY_DISC: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555312i32 as _); pub const IMAPI_E_FILE_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555367i32 as _); pub const IMAPI_E_FILE_SYSTEM_CHANGE_NOT_ALLOWED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555293i32 as _); pub const IMAPI_E_FILE_SYSTEM_FEATURE_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555308i32 as _); pub const IMAPI_E_FILE_SYSTEM_NOT_EMPTY: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555386i32 as _); pub const IMAPI_E_FILE_SYSTEM_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555310i32 as _); pub const IMAPI_E_FILE_SYSTEM_READ_CONSISTENCY_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555309i32 as _); pub const IMAPI_E_FSI_INTERNAL_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555392i32 as _); pub const IMAPI_E_IMAGEMANAGER_IMAGE_NOT_ALIGNED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555136i32 as _); pub const IMAPI_E_IMAGEMANAGER_IMAGE_TOO_BIG: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555133i32 as _); pub const IMAPI_E_IMAGEMANAGER_NO_IMAGE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555134i32 as _); pub const IMAPI_E_IMAGEMANAGER_NO_VALID_VD_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555135i32 as _); pub const IMAPI_E_IMAGE_SIZE_LIMIT: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555360i32 as _); pub const IMAPI_E_IMAGE_TOO_BIG: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555359i32 as _); pub const IMAPI_E_IMPORT_MEDIA_NOT_ALLOWED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555303i32 as _); pub const IMAPI_E_IMPORT_READ_FAILURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555305i32 as _); pub const IMAPI_E_IMPORT_SEEK_FAILURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555306i32 as _); pub const IMAPI_E_IMPORT_TYPE_COLLISION_DIRECTORY_EXISTS_AS_FILE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555298i32 as _); pub const IMAPI_E_IMPORT_TYPE_COLLISION_FILE_EXISTS_AS_DIRECTORY: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555307i32 as _); pub const IMAPI_E_INCOMPATIBLE_MULTISESSION_TYPE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555301i32 as _); pub const IMAPI_E_INCOMPATIBLE_PREVIOUS_SESSION: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555341i32 as _); pub const IMAPI_E_INVALID_DATE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555387i32 as _); pub const IMAPI_E_INVALID_PARAM: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555391i32 as _); pub const IMAPI_E_INVALID_PATH: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555376i32 as _); pub const IMAPI_E_INVALID_VOLUME_NAME: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555388i32 as _); pub const IMAPI_E_INVALID_WORKING_DIRECTORY: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555328i32 as _); pub const IMAPI_E_ISO9660_LEVELS: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555343i32 as _); pub const IMAPI_E_ITEM_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555368i32 as _); pub const IMAPI_E_MULTISESSION_NOT_SET: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555299i32 as _); pub const IMAPI_E_NOT_DIR: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555383i32 as _); pub const IMAPI_E_NOT_FILE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555384i32 as _); pub const IMAPI_E_NOT_IN_FILE_SYSTEM: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555381i32 as _); pub const IMAPI_E_NO_COMPATIBLE_MULTISESSION_TYPE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555300i32 as _); pub const IMAPI_E_NO_OUTPUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555389i32 as _); pub const IMAPI_E_NO_SUPPORTED_FILE_SYSTEM: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555311i32 as _); pub const IMAPI_E_NO_UNIQUE_NAME: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555373i32 as _); pub const IMAPI_E_PROPERTY_NOT_ACCESSIBLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555296i32 as _); pub const IMAPI_E_READONLY: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555390i32 as _); pub const IMAPI_E_RESTRICTED_NAME_VIOLATION: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555375i32 as _); pub const IMAPI_E_STASHFILE_MOVE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555326i32 as _); pub const IMAPI_E_STASHFILE_OPEN_FAILURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555336i32 as _); pub const IMAPI_E_STASHFILE_READ_FAILURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555333i32 as _); pub const IMAPI_E_STASHFILE_SEEK_FAILURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555335i32 as _); pub const IMAPI_E_STASHFILE_WRITE_FAILURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555334i32 as _); pub const IMAPI_E_TOO_MANY_DIRS: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555344i32 as _); pub const IMAPI_E_UDF_NOT_WRITE_COMPATIBLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555302i32 as _); pub const IMAPI_E_UDF_REVISION_CHANGE_NOT_ALLOWED: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555295i32 as _); pub const IMAPI_E_WORKING_DIRECTORY_SPACE: ::windows::core::HRESULT = ::windows::core::HRESULT(-1062555327i32 as _); pub const IMAPI_S_IMAGE_FEATURE_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(11186527i32 as _); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMailUser(pub ::windows::core::IUnknown); impl IMailUser { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } } unsafe impl ::windows::core::Interface for IMailUser { type Vtable = IMailUser_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IMailUser> for ::windows::core::IUnknown { fn from(value: IMailUser) -> Self { value.0 } } impl ::core::convert::From<&IMailUser> for ::windows::core::IUnknown { fn from(value: &IMailUser) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMailUser { 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 IMailUser { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IMailUser> for IMAPIProp { fn from(value: IMailUser) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IMailUser> for IMAPIProp { fn from(value: &IMailUser) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for IMailUser { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for &IMailUser { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IMailUser_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::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 IMessage(pub ::windows::core::IUnknown); impl IMessage { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } pub unsafe fn GetAttachmentTable(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } pub unsafe fn OpenAttach(&self, ulattachmentnum: u32, lpinterface: *const ::windows::core::GUID, ulflags: u32) -> ::windows::core::Result<IAttach> { let mut result__: <IAttach as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulattachmentnum), ::core::mem::transmute(lpinterface), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IAttach>(result__) } pub unsafe fn CreateAttach(&self, lpinterface: *const ::windows::core::GUID, ulflags: u32, lpulattachmentnum: *mut u32, lppattach: *mut ::core::option::Option<IAttach>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpinterface), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpulattachmentnum), ::core::mem::transmute(lppattach)).ok() } pub unsafe fn DeleteAttach<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ulattachmentnum: u32, uluiparam: usize, lpprogress: Param2, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulattachmentnum), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn GetRecipientTable(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn ModifyRecipients(&self, ulflags: u32, lpmods: *const ADRLIST) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpmods)).ok() } pub unsafe fn SubmitMessage(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn SetReadFlag(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } } unsafe impl ::windows::core::Interface for IMessage { type Vtable = IMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IMessage> for ::windows::core::IUnknown { fn from(value: IMessage) -> Self { value.0 } } impl ::core::convert::From<&IMessage> for ::windows::core::IUnknown { fn from(value: &IMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMessage { 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 IMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IMessage> for IMAPIProp { fn from(value: IMessage) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IMessage> for IMAPIProp { fn from(value: &IMessage) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for IMessage { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for &IMessage { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IMessage_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulattachmentnum: u32, lpinterface: *const ::windows::core::GUID, ulflags: u32, lppattach: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpinterface: *const ::windows::core::GUID, ulflags: u32, lpulattachmentnum: *mut u32, lppattach: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulattachmentnum: u32, uluiparam: usize, lpprogress: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpmods: *const ADRLIST) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMsgStore(pub ::windows::core::IUnknown); impl IMsgStore { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } pub unsafe fn Advise<'a, Param3: ::windows::core::IntoParam<'a, IMAPIAdviseSink>>(&self, cbentryid: u32, lpentryid: *const ENTRYID, uleventmask: u32, lpadvisesink: Param3) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(uleventmask), lpadvisesink.into_param().abi(), &mut result__).from_abi::<u32>(result__) } pub unsafe fn Unadvise(&self, ulconnection: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulconnection)).ok() } pub unsafe fn CompareEntryIDs(&self, cbentryid1: u32, lpentryid1: *const ENTRYID, cbentryid2: u32, lpentryid2: *const ENTRYID, ulflags: u32) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid1), ::core::mem::transmute(lpentryid1), ::core::mem::transmute(cbentryid2), ::core::mem::transmute(lpentryid2), ::core::mem::transmute(ulflags), &mut result__).from_abi::<u32>(result__) } pub unsafe fn OpenEntry(&self, cbentryid: u32, lpentryid: *const ENTRYID, lpinterface: *const ::windows::core::GUID, ulflags: u32, lpulobjtype: *mut u32, ppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(lpinterface), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpulobjtype), ::core::mem::transmute(ppunk)).ok() } pub unsafe fn SetReceiveFolder(&self, lpszmessageclass: *const i8, ulflags: u32, cbentryid: u32, lpentryid: *const ENTRYID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpszmessageclass), ::core::mem::transmute(ulflags), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid)).ok() } pub unsafe fn GetReceiveFolder(&self, lpszmessageclass: *const i8, ulflags: u32, lpcbentryid: *mut u32, lppentryid: *mut *mut ENTRYID, lppszexplicitclass: *mut *mut i8) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpszmessageclass), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcbentryid), ::core::mem::transmute(lppentryid), ::core::mem::transmute(lppszexplicitclass)).ok() } pub unsafe fn GetReceiveFolderTable(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } pub unsafe fn StoreLogoff(&self, lpulflags: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpulflags)).ok() } pub unsafe fn AbortSubmit(&self, cbentryid: u32, lpentryid: *const ENTRYID, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn GetOutgoingQueue(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).23)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } pub unsafe fn SetLockState<'a, Param0: ::windows::core::IntoParam<'a, IMessage>>(&self, lpmessage: Param0, ullockstate: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).24)(::core::mem::transmute_copy(self), lpmessage.into_param().abi(), ::core::mem::transmute(ullockstate)).ok() } pub unsafe fn FinishedMsg(&self, ulflags: u32, cbentryid: u32, lpentryid: *const ENTRYID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).25)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(cbentryid), ::core::mem::transmute(lpentryid)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn NotifyNewMail(&self, lpnotification: *const NOTIFICATION) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).26)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpnotification)).ok() } } unsafe impl ::windows::core::Interface for IMsgStore { type Vtable = IMsgStore_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IMsgStore> for ::windows::core::IUnknown { fn from(value: IMsgStore) -> Self { value.0 } } impl ::core::convert::From<&IMsgStore> for ::windows::core::IUnknown { fn from(value: &IMsgStore) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMsgStore { 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 IMsgStore { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IMsgStore> for IMAPIProp { fn from(value: IMsgStore) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IMsgStore> for IMAPIProp { fn from(value: &IMsgStore) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for IMsgStore { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for &IMsgStore { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IMsgStore_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, uleventmask: u32, lpadvisesink: ::windows::core::RawPtr, lpulconnection: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulconnection: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid1: u32, lpentryid1: *const ENTRYID, cbentryid2: u32, lpentryid2: *const ENTRYID, ulflags: u32, lpulresult: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, lpinterface: *const ::windows::core::GUID, ulflags: u32, lpulobjtype: *mut u32, ppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpszmessageclass: *const i8, ulflags: u32, cbentryid: u32, lpentryid: *const ENTRYID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpszmessageclass: *const i8, ulflags: u32, lpcbentryid: *mut u32, lppentryid: *mut *mut ENTRYID, lppszexplicitclass: *mut *mut i8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpulflags: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbentryid: u32, lpentryid: *const ENTRYID, ulflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpmessage: ::windows::core::RawPtr, ullockstate: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, cbentryid: u32, lpentryid: *const ENTRYID) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpnotification: *const NOTIFICATION) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IProfSect(pub ::windows::core::IUnknown); impl IProfSect { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } } unsafe impl ::windows::core::Interface for IProfSect { type Vtable = IProfSect_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IProfSect> for ::windows::core::IUnknown { fn from(value: IProfSect) -> Self { value.0 } } impl ::core::convert::From<&IProfSect> for ::windows::core::IUnknown { fn from(value: &IProfSect) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IProfSect { 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 IProfSect { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IProfSect> for IMAPIProp { fn from(value: IProfSect) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IProfSect> for IMAPIProp { fn from(value: &IProfSect) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for IProfSect { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for &IProfSect { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IProfSect_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::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 IPropData(pub ::windows::core::IUnknown); impl IPropData { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn SaveChanges(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn GetProps(&self, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcvalues), ::core::mem::transmute(lppproparray)).ok() } pub unsafe fn GetPropList(&self, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptagarray)).ok() } pub unsafe fn OpenProperty(&self, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulproptag), ::core::mem::transmute(lpiid), ::core::mem::transmute(ulinterfaceoptions), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppunk)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn SetProps(&self, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn DeleteProps(&self, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(lppproblems)).ok() } pub unsafe fn CopyTo<'a, Param4: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param4, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)( ::core::mem::transmute_copy(self), ::core::mem::transmute(ciidexclude), ::core::mem::transmute(rgiidexclude), ::core::mem::transmute(lpexcludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems), ) .ok() } pub unsafe fn CopyProps<'a, Param2: ::windows::core::IntoParam<'a, IMAPIProgress>>(&self, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: Param2, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpincludeprops), ::core::mem::transmute(uluiparam), lpprogress.into_param().abi(), ::core::mem::transmute(lpinterface), ::core::mem::transmute(lpdestobj), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproblems)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNamesFromIDs(&self, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptags), ::core::mem::transmute(lppropsetguid), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpcpropnames), ::core::mem::transmute(lppppropnames)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIDsFromNames(&self, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(cpropnames), ::core::mem::transmute(lpppropnames), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppproptags)).ok() } pub unsafe fn HrSetObjAccess(&self, ulaccess: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulaccess)).ok() } pub unsafe fn HrSetPropAccess(&self, lpproptagarray: *mut SPropTagArray, rgulaccess: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpproptagarray), ::core::mem::transmute(rgulaccess)).ok() } pub unsafe fn HrGetPropAccess(&self, lppproptagarray: *mut *mut SPropTagArray, lprgulaccess: *mut *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptagarray), ::core::mem::transmute(lprgulaccess)).ok() } pub unsafe fn HrAddObjProps(&self, lppproptagarray: *mut SPropTagArray, lprgulaccess: *mut *mut SPropProblemArray) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(lppproptagarray), ::core::mem::transmute(lprgulaccess)).ok() } } unsafe impl ::windows::core::Interface for IPropData { type Vtable = IPropData_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IPropData> for ::windows::core::IUnknown { fn from(value: IPropData) -> Self { value.0 } } impl ::core::convert::From<&IPropData> for ::windows::core::IUnknown { fn from(value: &IPropData) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPropData { 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 IPropData { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IPropData> for IMAPIProp { fn from(value: IPropData) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IPropData> for IMAPIProp { fn from(value: &IPropData) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for IPropData { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMAPIProp> for &IPropData { fn into_param(self) -> ::windows::core::Param<'a, IMAPIProp> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IPropData_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, ulflags: u32, lpcvalues: *mut u32, lppproparray: *mut *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lppproptagarray: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulproptag: u32, lpiid: *mut ::windows::core::GUID, ulinterfaceoptions: u32, ulflags: u32, lppunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cvalues: u32, lpproparray: *mut SPropValue, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ciidexclude: u32, rgiidexclude: *mut ::windows::core::GUID, lpexcludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpincludeprops: *mut SPropTagArray, uluiparam: usize, lpprogress: ::windows::core::RawPtr, lpinterface: *mut ::windows::core::GUID, lpdestobj: *mut ::core::ffi::c_void, ulflags: u32, lppproblems: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptags: *mut *mut SPropTagArray, lppropsetguid: *mut ::windows::core::GUID, ulflags: u32, lpcpropnames: *mut u32, lppppropnames: *mut *mut *mut MAPINAMEID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cpropnames: u32, lpppropnames: *mut *mut MAPINAMEID, ulflags: u32, lppproptags: *mut *mut SPropTagArray) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulaccess: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpproptagarray: *mut SPropTagArray, rgulaccess: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptagarray: *mut *mut SPropTagArray, lprgulaccess: *mut *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lppproptagarray: *mut SPropTagArray, lprgulaccess: *mut *mut SPropProblemArray) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IProviderAdmin(pub ::windows::core::IUnknown); impl IProviderAdmin { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32) -> ::windows::core::Result<*mut MAPIERROR> { let mut result__: <*mut MAPIERROR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), &mut result__).from_abi::<*mut MAPIERROR>(result__) } pub unsafe fn GetProviderTable(&self, ulflags: u32) -> ::windows::core::Result<IMAPITable> { let mut result__: <IMAPITable as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IMAPITable>(result__) } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn CreateProvider(&self, lpszprovider: *const i8, cvalues: u32, lpprops: *const SPropValue, uluiparam: usize, ulflags: u32) -> ::windows::core::Result<MAPIUID> { let mut result__: <MAPIUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpszprovider), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpprops), ::core::mem::transmute(uluiparam), ::core::mem::transmute(ulflags), &mut result__).from_abi::<MAPIUID>(result__) } pub unsafe fn DeleteProvider(&self, lpuid: *const MAPIUID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpuid)).ok() } pub unsafe fn OpenProfileSection(&self, lpuid: *const MAPIUID, lpinterface: *const ::windows::core::GUID, ulflags: u32) -> ::windows::core::Result<IProfSect> { let mut result__: <IProfSect as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpuid), ::core::mem::transmute(lpinterface), ::core::mem::transmute(ulflags), &mut result__).from_abi::<IProfSect>(result__) } } unsafe impl ::windows::core::Interface for IProviderAdmin { type Vtable = IProviderAdmin_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IProviderAdmin> for ::windows::core::IUnknown { fn from(value: IProviderAdmin) -> Self { value.0 } } impl ::core::convert::From<&IProviderAdmin> for ::windows::core::IUnknown { fn from(value: &IProviderAdmin) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IProviderAdmin { 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 IProviderAdmin { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IProviderAdmin_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpptable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpszprovider: *const i8, cvalues: u32, lpprops: *const SPropValue, uluiparam: usize, ulflags: u32, lpuid: *mut MAPIUID) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpuid: *const MAPIUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpuid: *const MAPIUID, lpinterface: *const ::windows::core::GUID, ulflags: u32, lppprofsect: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ITableData(pub ::windows::core::IUnknown); impl ITableData { pub unsafe fn HrGetView(&self, lpssortorderset: *mut SSortOrderSet, lpfcallerrelease: *mut ::core::option::Option<CALLERRELEASE>, ulcallerdata: u32, lppmapitable: *mut ::core::option::Option<IMAPITable>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpssortorderset), ::core::mem::transmute(lpfcallerrelease), ::core::mem::transmute(ulcallerdata), ::core::mem::transmute(lppmapitable)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn HrModifyRow(&self, param0: *mut SRow) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(param0)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn HrDeleteRow(&self, lpspropvalue: *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpspropvalue)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn HrQueryRow(&self, lpspropvalue: *mut SPropValue, lppsrow: *mut *mut SRow, lpulirow: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpspropvalue), ::core::mem::transmute(lppsrow), ::core::mem::transmute(lpulirow)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn HrEnumRow(&self, ulrownumber: u32, lppsrow: *mut *mut SRow) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulrownumber), ::core::mem::transmute(lppsrow)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn HrNotify(&self, ulflags: u32, cvalues: u32, lpspropvalue: *mut SPropValue) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpspropvalue)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn HrInsertRow(&self, ulirow: u32, lpsrow: *mut SRow) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulirow), ::core::mem::transmute(lpsrow)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn HrModifyRows(&self, ulflags: u32, lpsrowset: *mut SRowSet) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpsrowset)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn HrDeleteRows(&self, ulflags: u32, lprowsettodelete: *mut SRowSet, crowsdeleted: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(lprowsettodelete), ::core::mem::transmute(crowsdeleted)).ok() } } unsafe impl ::windows::core::Interface for ITableData { type Vtable = ITableData_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<ITableData> for ::windows::core::IUnknown { fn from(value: ITableData) -> Self { value.0 } } impl ::core::convert::From<&ITableData> for ::windows::core::IUnknown { fn from(value: &ITableData) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ITableData { 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 ITableData { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ITableData_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, lpssortorderset: *mut SSortOrderSet, lpfcallerrelease: *mut ::windows::core::RawPtr, ulcallerdata: u32, lppmapitable: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, param0: *mut SRow) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpspropvalue: *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpspropvalue: *mut SPropValue, lppsrow: *mut *mut SRow, lpulirow: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulrownumber: u32, lppsrow: *mut *mut SRow) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, cvalues: u32, lpspropvalue: *mut SPropValue) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulirow: u32, lpsrow: *mut SRow) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lpsrowset: *mut SRowSet) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulflags: u32, lprowsettodelete: *mut SRowSet, crowsdeleted: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWABExtInit(pub ::windows::core::IUnknown); impl IWABExtInit { #[cfg(feature = "Win32_Foundation")] pub unsafe fn Initialize(&self, lpwabextdisplay: *mut WABEXTDISPLAY) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpwabextdisplay)).ok() } } unsafe impl ::windows::core::Interface for IWABExtInit { type Vtable = IWABExtInit_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xea22ebf0_87a4_11d1_9acf_00a0c91f9c8b); } impl ::core::convert::From<IWABExtInit> for ::windows::core::IUnknown { fn from(value: IWABExtInit) -> Self { value.0 } } impl ::core::convert::From<&IWABExtInit> for ::windows::core::IUnknown { fn from(value: &IWABExtInit) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWABExtInit { 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 IWABExtInit { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWABExtInit_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpwabextdisplay: *mut ::core::mem::ManuallyDrop<WABEXTDISPLAY>) -> ::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 IWABOBJECT_(pub ::windows::core::IUnknown); impl IWABOBJECT_ { pub unsafe fn QueryInterface(&self, riid: *const ::windows::core::GUID, ppvobj: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(riid), ::core::mem::transmute(ppvobj)).ok() } pub unsafe fn AddRef(&self) -> u32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self))) } pub unsafe fn Release(&self) -> u32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self))) } pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn AllocateBuffer(&self, cbsize: u32, lppbuffer: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbsize), ::core::mem::transmute(lppbuffer)).ok() } pub unsafe fn AllocateMore(&self, cbsize: u32, lpobject: *const ::core::ffi::c_void, lppbuffer: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbsize), ::core::mem::transmute(lpobject), ::core::mem::transmute(lppbuffer)).ok() } pub unsafe fn FreeBuffer(&self, lpbuffer: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpbuffer)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Backup<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(&self, lpfilename: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), lpfilename.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Import<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(&self, lpwip: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), lpwip.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Find<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(&self, lpiab: Param0, hwnd: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), hwnd.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn VCardDisplay<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(&self, lpiab: Param0, hwnd: Param1, lpszfilename: Param2) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), hwnd.into_param().abi(), lpszfilename.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn LDAPUrl<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(&self, lpiab: Param0, hwnd: Param1, ulflags: u32, lpszurl: Param3) -> ::windows::core::Result<IMailUser> { let mut result__: <IMailUser as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), hwnd.into_param().abi(), ::core::mem::transmute(ulflags), lpszurl.into_param().abi(), &mut result__).from_abi::<IMailUser>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn VCardCreate<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param3: ::windows::core::IntoParam<'a, IMailUser>>(&self, lpiab: Param0, ulflags: u32, lpszvcard: Param2, lpmailuser: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), ::core::mem::transmute(ulflags), lpszvcard.into_param().abi(), lpmailuser.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn VCardRetrieve<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(&self, lpiab: Param0, ulflags: u32, lpszvcard: Param2) -> ::windows::core::Result<IMailUser> { let mut result__: <IMailUser as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), ::core::mem::transmute(ulflags), lpszvcard.into_param().abi(), &mut result__).from_abi::<IMailUser>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetMe<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(&self, lpiab: Param0, ulflags: u32, lpdwaction: *mut u32, lpsbeid: *mut SBinary, hwnd: Param4) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpdwaction), ::core::mem::transmute(lpsbeid), hwnd.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetMe<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param2: ::windows::core::IntoParam<'a, SBinary>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(&self, lpiab: Param0, ulflags: u32, sbeid: Param2, hwnd: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), ::core::mem::transmute(ulflags), sbeid.into_param().abi(), hwnd.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IWABOBJECT_ { type Vtable = IWABOBJECT__abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IWABOBJECT_> for ::windows::core::IUnknown { fn from(value: IWABOBJECT_) -> Self { value.0 } } impl ::core::convert::From<&IWABOBJECT_> for ::windows::core::IUnknown { fn from(value: &IWABOBJECT_) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWABOBJECT_ { 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 IWABOBJECT_ { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWABOBJECT__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, riid: *const ::windows::core::GUID, ppvobj: *mut *mut ::core::ffi::c_void) -> ::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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbsize: u32, lppbuffer: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbsize: u32, lpobject: *const ::core::ffi::c_void, lppbuffer: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpbuffer: *const ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpfilename: super::super::Foundation::PSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpwip: super::super::Foundation::PSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, hwnd: super::super::Foundation::HWND) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, hwnd: super::super::Foundation::HWND, lpszfilename: super::super::Foundation::PSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, hwnd: super::super::Foundation::HWND, ulflags: u32, lpszurl: super::super::Foundation::PSTR, lppmailuser: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, ulflags: u32, lpszvcard: super::super::Foundation::PSTR, lpmailuser: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, ulflags: u32, lpszvcard: super::super::Foundation::PSTR, lppmailuser: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, ulflags: u32, lpdwaction: *mut u32, lpsbeid: *mut SBinary, hwnd: super::super::Foundation::HWND) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, ulflags: u32, sbeid: SBinary, hwnd: super::super::Foundation::HWND) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); pub type IWABOBJECT_AddRef_METHOD = unsafe extern "system" fn() -> u32; pub type IWABOBJECT_AllocateBuffer_METHOD = unsafe extern "system" fn(cbsize: u32, lppbuffer: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT; pub type IWABOBJECT_AllocateMore_METHOD = unsafe extern "system" fn(cbsize: u32, lpobject: *const ::core::ffi::c_void, lppbuffer: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub type IWABOBJECT_Backup_METHOD = unsafe extern "system" fn(lpfilename: super::super::Foundation::PSTR) -> ::windows::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub type IWABOBJECT_Find_METHOD = unsafe extern "system" fn(lpiab: ::windows::core::RawPtr, hwnd: super::super::Foundation::HWND) -> ::windows::core::HRESULT; pub type IWABOBJECT_FreeBuffer_METHOD = unsafe extern "system" fn(lpbuffer: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; pub type IWABOBJECT_GetLastError_METHOD = unsafe extern "system" fn(hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub type IWABOBJECT_GetMe_METHOD = unsafe extern "system" fn(lpiab: ::windows::core::RawPtr, ulflags: u32, lpdwaction: *mut u32, lpsbeid: *mut SBinary, hwnd: super::super::Foundation::HWND) -> ::windows::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub type IWABOBJECT_Import_METHOD = unsafe extern "system" fn(lpwip: super::super::Foundation::PSTR) -> ::windows::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub type IWABOBJECT_LDAPUrl_METHOD = unsafe extern "system" fn(lpiab: ::windows::core::RawPtr, hwnd: super::super::Foundation::HWND, ulflags: u32, lpszurl: super::super::Foundation::PSTR, lppmailuser: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; pub type IWABOBJECT_QueryInterface_METHOD = unsafe extern "system" fn(riid: *const ::windows::core::GUID, ppvobj: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT; pub type IWABOBJECT_Release_METHOD = unsafe extern "system" fn() -> u32; #[cfg(feature = "Win32_Foundation")] pub type IWABOBJECT_SetMe_METHOD = unsafe extern "system" fn(lpiab: ::windows::core::RawPtr, ulflags: u32, sbeid: SBinary, hwnd: super::super::Foundation::HWND) -> ::windows::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub type IWABOBJECT_VCardCreate_METHOD = unsafe extern "system" fn(lpiab: ::windows::core::RawPtr, ulflags: u32, lpszvcard: super::super::Foundation::PSTR, lpmailuser: ::windows::core::RawPtr) -> ::windows::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub type IWABOBJECT_VCardDisplay_METHOD = unsafe extern "system" fn(lpiab: ::windows::core::RawPtr, hwnd: super::super::Foundation::HWND, lpszfilename: super::super::Foundation::PSTR) -> ::windows::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub type IWABOBJECT_VCardRetrieve_METHOD = unsafe extern "system" fn(lpiab: ::windows::core::RawPtr, ulflags: u32, lpszvcard: super::super::Foundation::PSTR, lppmailuser: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWABObject(pub ::windows::core::IUnknown); impl IWABObject { pub unsafe fn GetLastError(&self, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hresult), ::core::mem::transmute(ulflags), ::core::mem::transmute(lppmapierror)).ok() } pub unsafe fn AllocateBuffer(&self, cbsize: u32, lppbuffer: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbsize), ::core::mem::transmute(lppbuffer)).ok() } pub unsafe fn AllocateMore(&self, cbsize: u32, lpobject: *const ::core::ffi::c_void, lppbuffer: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(cbsize), ::core::mem::transmute(lpobject), ::core::mem::transmute(lppbuffer)).ok() } pub unsafe fn FreeBuffer(&self, lpbuffer: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpbuffer)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Backup<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(&self, lpfilename: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), lpfilename.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Import<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(&self, lpwip: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), lpwip.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Find<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(&self, lpiab: Param0, hwnd: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), hwnd.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn VCardDisplay<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(&self, lpiab: Param0, hwnd: Param1, lpszfilename: Param2) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), hwnd.into_param().abi(), lpszfilename.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn LDAPUrl<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(&self, lpiab: Param0, hwnd: Param1, ulflags: u32, lpszurl: Param3) -> ::windows::core::Result<IMailUser> { let mut result__: <IMailUser as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), hwnd.into_param().abi(), ::core::mem::transmute(ulflags), lpszurl.into_param().abi(), &mut result__).from_abi::<IMailUser>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn VCardCreate<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param3: ::windows::core::IntoParam<'a, IMailUser>>(&self, lpiab: Param0, ulflags: u32, lpszvcard: Param2, lpmailuser: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), ::core::mem::transmute(ulflags), lpszvcard.into_param().abi(), lpmailuser.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn VCardRetrieve<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(&self, lpiab: Param0, ulflags: u32, lpszvcard: Param2) -> ::windows::core::Result<IMailUser> { let mut result__: <IMailUser as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), ::core::mem::transmute(ulflags), lpszvcard.into_param().abi(), &mut result__).from_abi::<IMailUser>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetMe<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(&self, lpiab: Param0, ulflags: u32, lpdwaction: *mut u32, lpsbeid: *mut SBinary, hwnd: Param4) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpdwaction), ::core::mem::transmute(lpsbeid), hwnd.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetMe<'a, Param0: ::windows::core::IntoParam<'a, IAddrBook>, Param2: ::windows::core::IntoParam<'a, SBinary>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(&self, lpiab: Param0, ulflags: u32, sbeid: Param2, hwnd: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), lpiab.into_param().abi(), ::core::mem::transmute(ulflags), sbeid.into_param().abi(), hwnd.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IWABObject { type Vtable = IWABObject_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::zeroed(); } impl ::core::convert::From<IWABObject> for ::windows::core::IUnknown { fn from(value: IWABObject) -> Self { value.0 } } impl ::core::convert::From<&IWABObject> for ::windows::core::IUnknown { fn from(value: &IWABObject) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWABObject { 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 IWABObject { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWABObject_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, hresult: ::windows::core::HRESULT, ulflags: u32, lppmapierror: *mut *mut MAPIERROR) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbsize: u32, lppbuffer: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cbsize: u32, lpobject: *const ::core::ffi::c_void, lppbuffer: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpbuffer: *const ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpfilename: super::super::Foundation::PSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpwip: super::super::Foundation::PSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, hwnd: super::super::Foundation::HWND) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, hwnd: super::super::Foundation::HWND, lpszfilename: super::super::Foundation::PSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, hwnd: super::super::Foundation::HWND, ulflags: u32, lpszurl: super::super::Foundation::PSTR, lppmailuser: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, ulflags: u32, lpszvcard: super::super::Foundation::PSTR, lpmailuser: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, ulflags: u32, lpszvcard: super::super::Foundation::PSTR, lppmailuser: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, ulflags: u32, lpdwaction: *mut u32, lpsbeid: *mut SBinary, hwnd: super::super::Foundation::HWND) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpiab: ::windows::core::RawPtr, ulflags: u32, sbeid: SBinary, hwnd: super::super::Foundation::HWND) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); pub type LPALLOCATEBUFFER = unsafe extern "system" fn(cbsize: u32, lppbuffer: *mut *mut ::core::ffi::c_void) -> i32; pub type LPALLOCATEMORE = unsafe extern "system" fn(cbsize: u32, lpobject: *mut ::core::ffi::c_void, lppbuffer: *mut *mut ::core::ffi::c_void) -> i32; pub type LPCREATECONVERSATIONINDEX = unsafe extern "system" fn(cbparent: u32, lpbparent: *mut u8, lpcbconvindex: *mut u32, lppbconvindex: *mut *mut u8) -> i32; pub type LPDISPATCHNOTIFICATIONS = unsafe extern "system" fn(ulflags: u32) -> ::windows::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub type LPFNABSDI = unsafe extern "system" fn(uluiparam: usize, lpvmsg: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL; pub type LPFNBUTTON = unsafe extern "system" fn(uluiparam: usize, lpvcontext: *mut ::core::ffi::c_void, cbentryid: u32, lpselection: *mut ENTRYID, ulflags: u32) -> i32; pub type LPFNDISMISS = unsafe extern "system" fn(uluiparam: usize, lpvcontext: *mut ::core::ffi::c_void); pub type LPFREEBUFFER = unsafe extern "system" fn(lpbuffer: *mut ::core::ffi::c_void) -> u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub type LPNOTIFCALLBACK = unsafe extern "system" fn(lpvcontext: *mut ::core::ffi::c_void, cnotification: u32, lpnotifications: *mut NOTIFICATION) -> i32; #[cfg(feature = "Win32_System_Com")] pub type LPOPENSTREAMONFILE = unsafe extern "system" fn(lpallocatebuffer: ::windows::core::RawPtr, lpfreebuffer: ::windows::core::RawPtr, ulflags: u32, lpszfilename: *const i8, lpszprefix: *const i8, lppstream: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; pub type LPWABALLOCATEBUFFER = unsafe extern "system" fn(lpwabobject: ::windows::core::RawPtr, cbsize: u32, lppbuffer: *mut *mut ::core::ffi::c_void) -> i32; pub type LPWABALLOCATEMORE = unsafe extern "system" fn(lpwabobject: ::windows::core::RawPtr, cbsize: u32, lpobject: *mut ::core::ffi::c_void, lppbuffer: *mut *mut ::core::ffi::c_void) -> i32; pub type LPWABFREEBUFFER = unsafe extern "system" fn(lpwabobject: ::windows::core::RawPtr, lpbuffer: *mut ::core::ffi::c_void) -> u32; #[cfg(feature = "Win32_Foundation")] pub type LPWABOPEN = unsafe extern "system" fn(lppadrbook: *mut ::windows::core::RawPtr, lppwabobject: *mut ::windows::core::RawPtr, lpwp: *mut WAB_PARAM, reserved2: u32) -> ::windows::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub type LPWABOPENEX = unsafe extern "system" fn(lppadrbook: *mut ::windows::core::RawPtr, lppwabobject: *mut ::windows::core::RawPtr, lpwp: *mut WAB_PARAM, reserved: u32, fnallocatebuffer: ::windows::core::RawPtr, fnallocatemore: ::windows::core::RawPtr, fnfreebuffer: ::windows::core::RawPtr) -> ::windows::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn LPropCompareProp(lpspropvaluea: *mut SPropValue, lpspropvalueb: *mut SPropValue) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn LPropCompareProp(lpspropvaluea: *mut SPropValue, lpspropvalueb: *mut SPropValue) -> i32; } ::core::mem::transmute(LPropCompareProp(::core::mem::transmute(lpspropvaluea), ::core::mem::transmute(lpspropvalueb))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn LpValFindProp(ulproptag: u32, cvalues: u32, lpproparray: *mut SPropValue) -> *mut SPropValue { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn LpValFindProp(ulproptag: u32, cvalues: u32, lpproparray: *mut SPropValue) -> *mut SPropValue; } ::core::mem::transmute(LpValFindProp(::core::mem::transmute(ulproptag), ::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn MAPIDeinitIdle() { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn MAPIDeinitIdle(); } ::core::mem::transmute(MAPIDeinitIdle()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct MAPIERROR { pub ulVersion: u32, pub lpszError: *mut i8, pub lpszComponent: *mut i8, pub ulLowLevelError: u32, pub ulContext: u32, } impl MAPIERROR {} impl ::core::default::Default for MAPIERROR { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for MAPIERROR { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MAPIERROR").field("ulVersion", &self.ulVersion).field("lpszError", &self.lpszError).field("lpszComponent", &self.lpszComponent).field("ulLowLevelError", &self.ulLowLevelError).field("ulContext", &self.ulContext).finish() } } impl ::core::cmp::PartialEq for MAPIERROR { fn eq(&self, other: &Self) -> bool { self.ulVersion == other.ulVersion && self.lpszError == other.lpszError && self.lpszComponent == other.lpszComponent && self.ulLowLevelError == other.ulLowLevelError && self.ulContext == other.ulContext } } impl ::core::cmp::Eq for MAPIERROR {} unsafe impl ::windows::core::Abi for MAPIERROR { type Abi = Self; } #[cfg(feature = "Win32_System_Com")] #[inline] pub unsafe fn MAPIGetDefaultMalloc() -> ::core::option::Option<super::Com::IMalloc> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn MAPIGetDefaultMalloc() -> ::core::option::Option<super::Com::IMalloc>; } ::core::mem::transmute(MAPIGetDefaultMalloc()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn MAPIInitIdle(lpvreserved: *mut ::core::ffi::c_void) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn MAPIInitIdle(lpvreserved: *mut ::core::ffi::c_void) -> i32; } ::core::mem::transmute(MAPIInitIdle(::core::mem::transmute(lpvreserved))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct MAPINAMEID { pub lpguid: *mut ::windows::core::GUID, pub ulKind: u32, pub Kind: MAPINAMEID_0, } #[cfg(feature = "Win32_Foundation")] impl MAPINAMEID {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for MAPINAMEID { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for MAPINAMEID { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for MAPINAMEID {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for MAPINAMEID { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union MAPINAMEID_0 { pub lID: i32, pub lpwstrName: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl MAPINAMEID_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for MAPINAMEID_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for MAPINAMEID_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for MAPINAMEID_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for MAPINAMEID_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct MAPIUID { pub ab: [u8; 16], } impl MAPIUID {} impl ::core::default::Default for MAPIUID { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for MAPIUID { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MAPIUID").field("ab", &self.ab).finish() } } impl ::core::cmp::PartialEq for MAPIUID { fn eq(&self, other: &Self) -> bool { self.ab == other.ab } } impl ::core::cmp::Eq for MAPIUID {} unsafe impl ::windows::core::Abi for MAPIUID { type Abi = Self; } pub const MAPI_COMPOUND: u32 = 128u32; pub const MAPI_DIM: u32 = 1u32; pub const MAPI_ERROR_VERSION: i32 = 0i32; pub const MAPI_E_CALL_FAILED: i32 = -2147467259i32; pub const MAPI_E_INTERFACE_NOT_SUPPORTED: i32 = -2147467262i32; pub const MAPI_E_INVALID_PARAMETER: i32 = -2147024809i32; pub const MAPI_E_NOT_ENOUGH_MEMORY: i32 = -2147024882i32; pub const MAPI_E_NO_ACCESS: i32 = -2147024891i32; pub const MAPI_NOTRECIP: u32 = 64u32; pub const MAPI_NOTRESERVED: u32 = 8u32; pub const MAPI_NOW: u32 = 16u32; pub const MAPI_ONE_OFF_NO_RICH_INFO: u32 = 1u32; pub const MAPI_P1: u32 = 268435456u32; pub const MAPI_SHORTTERM: u32 = 128u32; pub const MAPI_SUBMITTED: u32 = 2147483648u32; pub const MAPI_THISSESSION: u32 = 32u32; pub const MAPI_USE_DEFAULT: u32 = 64u32; pub const MNID_ID: u32 = 0u32; pub const MNID_STRING: u32 = 1u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct MTSID { pub cb: u32, pub ab: [u8; 1], } impl MTSID {} impl ::core::default::Default for MTSID { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for MTSID { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MTSID").field("cb", &self.cb).field("ab", &self.ab).finish() } } impl ::core::cmp::PartialEq for MTSID { fn eq(&self, other: &Self) -> bool { self.cb == other.cb && self.ab == other.ab } } impl ::core::cmp::Eq for MTSID {} unsafe impl ::windows::core::Abi for MTSID { type Abi = Self; } pub const MV_FLAG: u32 = 4096u32; pub const MV_INSTANCE: u32 = 8192u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct NEWMAIL_NOTIFICATION { pub cbEntryID: u32, pub lpEntryID: *mut ENTRYID, pub cbParentID: u32, pub lpParentID: *mut ENTRYID, pub ulFlags: u32, pub lpszMessageClass: *mut i8, pub ulMessageFlags: u32, } impl NEWMAIL_NOTIFICATION {} impl ::core::default::Default for NEWMAIL_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for NEWMAIL_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("NEWMAIL_NOTIFICATION") .field("cbEntryID", &self.cbEntryID) .field("lpEntryID", &self.lpEntryID) .field("cbParentID", &self.cbParentID) .field("lpParentID", &self.lpParentID) .field("ulFlags", &self.ulFlags) .field("lpszMessageClass", &self.lpszMessageClass) .field("ulMessageFlags", &self.ulMessageFlags) .finish() } } impl ::core::cmp::PartialEq for NEWMAIL_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.cbEntryID == other.cbEntryID && self.lpEntryID == other.lpEntryID && self.cbParentID == other.cbParentID && self.lpParentID == other.lpParentID && self.ulFlags == other.ulFlags && self.lpszMessageClass == other.lpszMessageClass && self.ulMessageFlags == other.ulMessageFlags } } impl ::core::cmp::Eq for NEWMAIL_NOTIFICATION {} unsafe impl ::windows::core::Abi for NEWMAIL_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct NOTIFICATION { pub ulEventType: u32, pub ulAlignPad: u32, pub info: NOTIFICATION_0, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl NOTIFICATION {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for NOTIFICATION { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for NOTIFICATION {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub union NOTIFICATION_0 { pub err: ERROR_NOTIFICATION, pub newmail: NEWMAIL_NOTIFICATION, pub obj: OBJECT_NOTIFICATION, pub tab: TABLE_NOTIFICATION, pub ext: EXTENDED_NOTIFICATION, pub statobj: STATUS_OBJECT_NOTIFICATION, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl NOTIFICATION_0 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for NOTIFICATION_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for NOTIFICATION_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for NOTIFICATION_0 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for NOTIFICATION_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct NOTIFKEY { pub cb: u32, pub ab: [u8; 1], } impl NOTIFKEY {} impl ::core::default::Default for NOTIFKEY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for NOTIFKEY { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("NOTIFKEY").field("cb", &self.cb).field("ab", &self.ab).finish() } } impl ::core::cmp::PartialEq for NOTIFKEY { fn eq(&self, other: &Self) -> bool { self.cb == other.cb && self.ab == other.ab } } impl ::core::cmp::Eq for NOTIFKEY {} unsafe impl ::windows::core::Abi for NOTIFKEY { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct OBJECT_NOTIFICATION { pub cbEntryID: u32, pub lpEntryID: *mut ENTRYID, pub ulObjType: u32, pub cbParentID: u32, pub lpParentID: *mut ENTRYID, pub cbOldID: u32, pub lpOldID: *mut ENTRYID, pub cbOldParentID: u32, pub lpOldParentID: *mut ENTRYID, pub lpPropTagArray: *mut SPropTagArray, } impl OBJECT_NOTIFICATION {} impl ::core::default::Default for OBJECT_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for OBJECT_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("OBJECT_NOTIFICATION") .field("cbEntryID", &self.cbEntryID) .field("lpEntryID", &self.lpEntryID) .field("ulObjType", &self.ulObjType) .field("cbParentID", &self.cbParentID) .field("lpParentID", &self.lpParentID) .field("cbOldID", &self.cbOldID) .field("lpOldID", &self.lpOldID) .field("cbOldParentID", &self.cbOldParentID) .field("lpOldParentID", &self.lpOldParentID) .field("lpPropTagArray", &self.lpPropTagArray) .finish() } } impl ::core::cmp::PartialEq for OBJECT_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.cbEntryID == other.cbEntryID && self.lpEntryID == other.lpEntryID && self.ulObjType == other.ulObjType && self.cbParentID == other.cbParentID && self.lpParentID == other.lpParentID && self.cbOldID == other.cbOldID && self.lpOldID == other.lpOldID && self.cbOldParentID == other.cbOldParentID && self.lpOldParentID == other.lpOldParentID && self.lpPropTagArray == other.lpPropTagArray } } impl ::core::cmp::Eq for OBJECT_NOTIFICATION {} unsafe impl ::windows::core::Abi for OBJECT_NOTIFICATION { type Abi = Self; } #[cfg(feature = "Win32_System_Com")] #[inline] pub unsafe fn OpenStreamOnFile(lpallocatebuffer: ::core::option::Option<LPALLOCATEBUFFER>, lpfreebuffer: ::core::option::Option<LPFREEBUFFER>, ulflags: u32, lpszfilename: *const i8, lpszprefix: *const i8) -> ::windows::core::Result<super::Com::IStream> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn OpenStreamOnFile(lpallocatebuffer: ::windows::core::RawPtr, lpfreebuffer: ::windows::core::RawPtr, ulflags: u32, lpszfilename: *const i8, lpszprefix: *const i8, lppstream: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; } let mut result__: <super::Com::IStream as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); OpenStreamOnFile(::core::mem::transmute(lpallocatebuffer), ::core::mem::transmute(lpfreebuffer), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpszfilename), ::core::mem::transmute(lpszprefix), &mut result__).from_abi::<super::Com::IStream>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] pub type PFNIDLE = unsafe extern "system" fn() -> super::super::Foundation::BOOL; pub const PRIHIGHEST: u32 = 32767u32; pub const PRILOWEST: i32 = -32768i32; pub const PRIUSER: u32 = 0u32; pub const PROP_ID_INVALID: u32 = 65535u32; pub const PROP_ID_NULL: u32 = 0u32; pub const PROP_ID_SECURE_MAX: u32 = 26623u32; pub const PROP_ID_SECURE_MIN: u32 = 26608u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn PpropFindProp(lpproparray: *mut SPropValue, cvalues: u32, ulproptag: u32) -> *mut SPropValue { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn PpropFindProp(lpproparray: *mut SPropValue, cvalues: u32, ulproptag: u32) -> *mut SPropValue; } ::core::mem::transmute(PpropFindProp(::core::mem::transmute(lpproparray), ::core::mem::transmute(cvalues), ::core::mem::transmute(ulproptag))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn PropCopyMore(lpspropvaluedest: *mut SPropValue, lpspropvaluesrc: *mut SPropValue, lpfallocmore: ::core::option::Option<LPALLOCATEMORE>, lpvobject: *mut ::core::ffi::c_void) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn PropCopyMore(lpspropvaluedest: *mut SPropValue, lpspropvaluesrc: *mut SPropValue, lpfallocmore: ::windows::core::RawPtr, lpvobject: *mut ::core::ffi::c_void) -> i32; } ::core::mem::transmute(PropCopyMore(::core::mem::transmute(lpspropvaluedest), ::core::mem::transmute(lpspropvaluesrc), ::core::mem::transmute(lpfallocmore), ::core::mem::transmute(lpvobject))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RTFSync<'a, Param0: ::windows::core::IntoParam<'a, IMessage>>(lpmessage: Param0, ulflags: u32, lpfmessageupdated: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RTFSync(lpmessage: ::windows::core::RawPtr, ulflags: u32, lpfmessageupdated: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT; } RTFSync(lpmessage.into_param().abi(), ::core::mem::transmute(ulflags), ::core::mem::transmute(lpfmessageupdated)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct SAndRestriction { pub cRes: u32, pub lpRes: *mut SRestriction, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl SAndRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for SAndRestriction { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for SAndRestriction { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SAndRestriction").field("cRes", &self.cRes).field("lpRes", &self.lpRes).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for SAndRestriction { fn eq(&self, other: &Self) -> bool { self.cRes == other.cRes && self.lpRes == other.lpRes } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for SAndRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for SAndRestriction { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SAppTimeArray { pub cValues: u32, pub lpat: *mut f64, } impl SAppTimeArray {} impl ::core::default::Default for SAppTimeArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SAppTimeArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SAppTimeArray").field("cValues", &self.cValues).field("lpat", &self.lpat).finish() } } impl ::core::cmp::PartialEq for SAppTimeArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lpat == other.lpat } } impl ::core::cmp::Eq for SAppTimeArray {} unsafe impl ::windows::core::Abi for SAppTimeArray { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SBinary { pub cb: u32, pub lpb: *mut u8, } impl SBinary {} impl ::core::default::Default for SBinary { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SBinary { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SBinary").field("cb", &self.cb).field("lpb", &self.lpb).finish() } } impl ::core::cmp::PartialEq for SBinary { fn eq(&self, other: &Self) -> bool { self.cb == other.cb && self.lpb == other.lpb } } impl ::core::cmp::Eq for SBinary {} unsafe impl ::windows::core::Abi for SBinary { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SBinaryArray { pub cValues: u32, pub lpbin: *mut SBinary, } impl SBinaryArray {} impl ::core::default::Default for SBinaryArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SBinaryArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SBinaryArray").field("cValues", &self.cValues).field("lpbin", &self.lpbin).finish() } } impl ::core::cmp::PartialEq for SBinaryArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lpbin == other.lpbin } } impl ::core::cmp::Eq for SBinaryArray {} unsafe impl ::windows::core::Abi for SBinaryArray { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SBitMaskRestriction { pub relBMR: u32, pub ulPropTag: u32, pub ulMask: u32, } impl SBitMaskRestriction {} impl ::core::default::Default for SBitMaskRestriction { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SBitMaskRestriction { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SBitMaskRestriction").field("relBMR", &self.relBMR).field("ulPropTag", &self.ulPropTag).field("ulMask", &self.ulMask).finish() } } impl ::core::cmp::PartialEq for SBitMaskRestriction { fn eq(&self, other: &Self) -> bool { self.relBMR == other.relBMR && self.ulPropTag == other.ulPropTag && self.ulMask == other.ulMask } } impl ::core::cmp::Eq for SBitMaskRestriction {} unsafe impl ::windows::core::Abi for SBitMaskRestriction { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct SCommentRestriction { pub cValues: u32, pub lpRes: *mut SRestriction, pub lpProp: *mut SPropValue, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl SCommentRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for SCommentRestriction { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for SCommentRestriction { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCommentRestriction").field("cValues", &self.cValues).field("lpRes", &self.lpRes).field("lpProp", &self.lpProp).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for SCommentRestriction { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lpRes == other.lpRes && self.lpProp == other.lpProp } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for SCommentRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for SCommentRestriction { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SComparePropsRestriction { pub relop: u32, pub ulPropTag1: u32, pub ulPropTag2: u32, } impl SComparePropsRestriction {} impl ::core::default::Default for SComparePropsRestriction { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SComparePropsRestriction { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SComparePropsRestriction").field("relop", &self.relop).field("ulPropTag1", &self.ulPropTag1).field("ulPropTag2", &self.ulPropTag2).finish() } } impl ::core::cmp::PartialEq for SComparePropsRestriction { fn eq(&self, other: &Self) -> bool { self.relop == other.relop && self.ulPropTag1 == other.ulPropTag1 && self.ulPropTag2 == other.ulPropTag2 } } impl ::core::cmp::Eq for SComparePropsRestriction {} unsafe impl ::windows::core::Abi for SComparePropsRestriction { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct SContentRestriction { pub ulFuzzyLevel: u32, pub ulPropTag: u32, pub lpProp: *mut SPropValue, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl SContentRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for SContentRestriction { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for SContentRestriction { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SContentRestriction").field("ulFuzzyLevel", &self.ulFuzzyLevel).field("ulPropTag", &self.ulPropTag).field("lpProp", &self.lpProp).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for SContentRestriction { fn eq(&self, other: &Self) -> bool { self.ulFuzzyLevel == other.ulFuzzyLevel && self.ulPropTag == other.ulPropTag && self.lpProp == other.lpProp } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for SContentRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for SContentRestriction { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_System_Com")] pub struct SCurrencyArray { pub cValues: u32, pub lpcur: *mut super::Com::CY, } #[cfg(feature = "Win32_System_Com")] impl SCurrencyArray {} #[cfg(feature = "Win32_System_Com")] impl ::core::default::Default for SCurrencyArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_System_Com")] impl ::core::fmt::Debug for SCurrencyArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCurrencyArray").field("cValues", &self.cValues).field("lpcur", &self.lpcur).finish() } } #[cfg(feature = "Win32_System_Com")] impl ::core::cmp::PartialEq for SCurrencyArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lpcur == other.lpcur } } #[cfg(feature = "Win32_System_Com")] impl ::core::cmp::Eq for SCurrencyArray {} #[cfg(feature = "Win32_System_Com")] unsafe impl ::windows::core::Abi for SCurrencyArray { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct SDateTimeArray { pub cValues: u32, pub lpft: *mut super::super::Foundation::FILETIME, } #[cfg(feature = "Win32_Foundation")] impl SDateTimeArray {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for SDateTimeArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for SDateTimeArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SDateTimeArray").field("cValues", &self.cValues).field("lpft", &self.lpft).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for SDateTimeArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lpft == other.lpft } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for SDateTimeArray {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for SDateTimeArray { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SDoubleArray { pub cValues: u32, pub lpdbl: *mut f64, } impl SDoubleArray {} impl ::core::default::Default for SDoubleArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SDoubleArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SDoubleArray").field("cValues", &self.cValues).field("lpdbl", &self.lpdbl).finish() } } impl ::core::cmp::PartialEq for SDoubleArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lpdbl == other.lpdbl } } impl ::core::cmp::Eq for SDoubleArray {} unsafe impl ::windows::core::Abi for SDoubleArray { type Abi = Self; } pub const SERVICE_UI_ALLOWED: u32 = 16u32; pub const SERVICE_UI_ALWAYS: u32 = 2u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SExistRestriction { pub ulReserved1: u32, pub ulPropTag: u32, pub ulReserved2: u32, } impl SExistRestriction {} impl ::core::default::Default for SExistRestriction { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SExistRestriction { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SExistRestriction").field("ulReserved1", &self.ulReserved1).field("ulPropTag", &self.ulPropTag).field("ulReserved2", &self.ulReserved2).finish() } } impl ::core::cmp::PartialEq for SExistRestriction { fn eq(&self, other: &Self) -> bool { self.ulReserved1 == other.ulReserved1 && self.ulPropTag == other.ulPropTag && self.ulReserved2 == other.ulReserved2 } } impl ::core::cmp::Eq for SExistRestriction {} unsafe impl ::windows::core::Abi for SExistRestriction { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SGuidArray { pub cValues: u32, pub lpguid: *mut ::windows::core::GUID, } impl SGuidArray {} impl ::core::default::Default for SGuidArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SGuidArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SGuidArray").field("cValues", &self.cValues).field("lpguid", &self.lpguid).finish() } } impl ::core::cmp::PartialEq for SGuidArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lpguid == other.lpguid } } impl ::core::cmp::Eq for SGuidArray {} unsafe impl ::windows::core::Abi for SGuidArray { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct SLPSTRArray { pub cValues: u32, pub lppszA: *mut super::super::Foundation::PSTR, } #[cfg(feature = "Win32_Foundation")] impl SLPSTRArray {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for SLPSTRArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for SLPSTRArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SLPSTRArray").field("cValues", &self.cValues).field("lppszA", &self.lppszA).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for SLPSTRArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lppszA == other.lppszA } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for SLPSTRArray {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for SLPSTRArray { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SLargeIntegerArray { pub cValues: u32, pub lpli: *mut i64, } impl SLargeIntegerArray {} impl ::core::default::Default for SLargeIntegerArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SLargeIntegerArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SLargeIntegerArray").field("cValues", &self.cValues).field("lpli", &self.lpli).finish() } } impl ::core::cmp::PartialEq for SLargeIntegerArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lpli == other.lpli } } impl ::core::cmp::Eq for SLargeIntegerArray {} unsafe impl ::windows::core::Abi for SLargeIntegerArray { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SLongArray { pub cValues: u32, pub lpl: *mut i32, } impl SLongArray {} impl ::core::default::Default for SLongArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SLongArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SLongArray").field("cValues", &self.cValues).field("lpl", &self.lpl).finish() } } impl ::core::cmp::PartialEq for SLongArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lpl == other.lpl } } impl ::core::cmp::Eq for SLongArray {} unsafe impl ::windows::core::Abi for SLongArray { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct SNotRestriction { pub ulReserved: u32, pub lpRes: *mut SRestriction, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl SNotRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for SNotRestriction { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for SNotRestriction { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SNotRestriction").field("ulReserved", &self.ulReserved).field("lpRes", &self.lpRes).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for SNotRestriction { fn eq(&self, other: &Self) -> bool { self.ulReserved == other.ulReserved && self.lpRes == other.lpRes } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for SNotRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for SNotRestriction { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct SOrRestriction { pub cRes: u32, pub lpRes: *mut SRestriction, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl SOrRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for SOrRestriction { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for SOrRestriction { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SOrRestriction").field("cRes", &self.cRes).field("lpRes", &self.lpRes).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for SOrRestriction { fn eq(&self, other: &Self) -> bool { self.cRes == other.cRes && self.lpRes == other.lpRes } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for SOrRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for SOrRestriction { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SPropProblem { pub ulIndex: u32, pub ulPropTag: u32, pub scode: i32, } impl SPropProblem {} impl ::core::default::Default for SPropProblem { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SPropProblem { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SPropProblem").field("ulIndex", &self.ulIndex).field("ulPropTag", &self.ulPropTag).field("scode", &self.scode).finish() } } impl ::core::cmp::PartialEq for SPropProblem { fn eq(&self, other: &Self) -> bool { self.ulIndex == other.ulIndex && self.ulPropTag == other.ulPropTag && self.scode == other.scode } } impl ::core::cmp::Eq for SPropProblem {} unsafe impl ::windows::core::Abi for SPropProblem { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SPropProblemArray { pub cProblem: u32, pub aProblem: [SPropProblem; 1], } impl SPropProblemArray {} impl ::core::default::Default for SPropProblemArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SPropProblemArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SPropProblemArray").field("cProblem", &self.cProblem).field("aProblem", &self.aProblem).finish() } } impl ::core::cmp::PartialEq for SPropProblemArray { fn eq(&self, other: &Self) -> bool { self.cProblem == other.cProblem && self.aProblem == other.aProblem } } impl ::core::cmp::Eq for SPropProblemArray {} unsafe impl ::windows::core::Abi for SPropProblemArray { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SPropTagArray { pub cValues: u32, pub aulPropTag: [u32; 1], } impl SPropTagArray {} impl ::core::default::Default for SPropTagArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SPropTagArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SPropTagArray").field("cValues", &self.cValues).field("aulPropTag", &self.aulPropTag).finish() } } impl ::core::cmp::PartialEq for SPropTagArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.aulPropTag == other.aulPropTag } } impl ::core::cmp::Eq for SPropTagArray {} unsafe impl ::windows::core::Abi for SPropTagArray { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct SPropValue { pub ulPropTag: u32, pub dwAlignPad: u32, pub Value: _PV, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl SPropValue {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for SPropValue { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for SPropValue { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for SPropValue {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for SPropValue { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct SPropertyRestriction { pub relop: u32, pub ulPropTag: u32, pub lpProp: *mut SPropValue, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl SPropertyRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for SPropertyRestriction { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for SPropertyRestriction { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SPropertyRestriction").field("relop", &self.relop).field("ulPropTag", &self.ulPropTag).field("lpProp", &self.lpProp).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for SPropertyRestriction { fn eq(&self, other: &Self) -> bool { self.relop == other.relop && self.ulPropTag == other.ulPropTag && self.lpProp == other.lpProp } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for SPropertyRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for SPropertyRestriction { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SRealArray { pub cValues: u32, pub lpflt: *mut f32, } impl SRealArray {} impl ::core::default::Default for SRealArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SRealArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SRealArray").field("cValues", &self.cValues).field("lpflt", &self.lpflt).finish() } } impl ::core::cmp::PartialEq for SRealArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lpflt == other.lpflt } } impl ::core::cmp::Eq for SRealArray {} unsafe impl ::windows::core::Abi for SRealArray { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct SRestriction { pub rt: u32, pub res: SRestriction_0, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl SRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for SRestriction { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for SRestriction { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for SRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for SRestriction { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub union SRestriction_0 { pub resCompareProps: SComparePropsRestriction, pub resAnd: SAndRestriction, pub resOr: SOrRestriction, pub resNot: SNotRestriction, pub resContent: SContentRestriction, pub resProperty: SPropertyRestriction, pub resBitMask: SBitMaskRestriction, pub resSize: SSizeRestriction, pub resExist: SExistRestriction, pub resSub: SSubRestriction, pub resComment: SCommentRestriction, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl SRestriction_0 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for SRestriction_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for SRestriction_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for SRestriction_0 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for SRestriction_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct SRow { pub ulAdrEntryPad: u32, pub cValues: u32, pub lpProps: *mut SPropValue, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl SRow {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for SRow { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for SRow { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SRow").field("ulAdrEntryPad", &self.ulAdrEntryPad).field("cValues", &self.cValues).field("lpProps", &self.lpProps).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for SRow { fn eq(&self, other: &Self) -> bool { self.ulAdrEntryPad == other.ulAdrEntryPad && self.cValues == other.cValues && self.lpProps == other.lpProps } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for SRow {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for SRow { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct SRowSet { pub cRows: u32, pub aRow: [SRow; 1], } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl SRowSet {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for SRowSet { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for SRowSet { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SRowSet").field("cRows", &self.cRows).field("aRow", &self.aRow).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for SRowSet { fn eq(&self, other: &Self) -> bool { self.cRows == other.cRows && self.aRow == other.aRow } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for SRowSet {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for SRowSet { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SShortArray { pub cValues: u32, pub lpi: *mut i16, } impl SShortArray {} impl ::core::default::Default for SShortArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SShortArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SShortArray").field("cValues", &self.cValues).field("lpi", &self.lpi).finish() } } impl ::core::cmp::PartialEq for SShortArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lpi == other.lpi } } impl ::core::cmp::Eq for SShortArray {} unsafe impl ::windows::core::Abi for SShortArray { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SSizeRestriction { pub relop: u32, pub ulPropTag: u32, pub cb: u32, } impl SSizeRestriction {} impl ::core::default::Default for SSizeRestriction { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SSizeRestriction { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SSizeRestriction").field("relop", &self.relop).field("ulPropTag", &self.ulPropTag).field("cb", &self.cb).finish() } } impl ::core::cmp::PartialEq for SSizeRestriction { fn eq(&self, other: &Self) -> bool { self.relop == other.relop && self.ulPropTag == other.ulPropTag && self.cb == other.cb } } impl ::core::cmp::Eq for SSizeRestriction {} unsafe impl ::windows::core::Abi for SSizeRestriction { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SSortOrder { pub ulPropTag: u32, pub ulOrder: u32, } impl SSortOrder {} impl ::core::default::Default for SSortOrder { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SSortOrder { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SSortOrder").field("ulPropTag", &self.ulPropTag).field("ulOrder", &self.ulOrder).finish() } } impl ::core::cmp::PartialEq for SSortOrder { fn eq(&self, other: &Self) -> bool { self.ulPropTag == other.ulPropTag && self.ulOrder == other.ulOrder } } impl ::core::cmp::Eq for SSortOrder {} unsafe impl ::windows::core::Abi for SSortOrder { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SSortOrderSet { pub cSorts: u32, pub cCategories: u32, pub cExpanded: u32, pub aSort: [SSortOrder; 1], } impl SSortOrderSet {} impl ::core::default::Default for SSortOrderSet { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SSortOrderSet { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SSortOrderSet").field("cSorts", &self.cSorts).field("cCategories", &self.cCategories).field("cExpanded", &self.cExpanded).field("aSort", &self.aSort).finish() } } impl ::core::cmp::PartialEq for SSortOrderSet { fn eq(&self, other: &Self) -> bool { self.cSorts == other.cSorts && self.cCategories == other.cCategories && self.cExpanded == other.cExpanded && self.aSort == other.aSort } } impl ::core::cmp::Eq for SSortOrderSet {} unsafe impl ::windows::core::Abi for SSortOrderSet { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct SSubRestriction { pub ulSubObject: u32, pub lpRes: *mut SRestriction, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl SSubRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for SSubRestriction { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for SSubRestriction { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SSubRestriction").field("ulSubObject", &self.ulSubObject).field("lpRes", &self.lpRes).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for SSubRestriction { fn eq(&self, other: &Self) -> bool { self.ulSubObject == other.ulSubObject && self.lpRes == other.lpRes } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for SSubRestriction {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for SSubRestriction { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct STATUS_OBJECT_NOTIFICATION { pub cbEntryID: u32, pub lpEntryID: *mut ENTRYID, pub cValues: u32, pub lpPropVals: *mut SPropValue, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl STATUS_OBJECT_NOTIFICATION {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for STATUS_OBJECT_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::fmt::Debug for STATUS_OBJECT_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("STATUS_OBJECT_NOTIFICATION").field("cbEntryID", &self.cbEntryID).field("lpEntryID", &self.lpEntryID).field("cValues", &self.cValues).field("lpPropVals", &self.lpPropVals).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for STATUS_OBJECT_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.cbEntryID == other.cbEntryID && self.lpEntryID == other.lpEntryID && self.cValues == other.cValues && self.lpPropVals == other.lpPropVals } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for STATUS_OBJECT_NOTIFICATION {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for STATUS_OBJECT_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct SWStringArray { pub cValues: u32, pub lppszW: *mut super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl SWStringArray {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for SWStringArray { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for SWStringArray { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SWStringArray").field("cValues", &self.cValues).field("lppszW", &self.lppszW).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for SWStringArray { fn eq(&self, other: &Self) -> bool { self.cValues == other.cValues && self.lppszW == other.lppszW } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for SWStringArray {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for SWStringArray { type Abi = Self; } pub const S_IMAPI_BOTHADJUSTED: ::windows::core::HRESULT = ::windows::core::HRESULT(11141126i32 as _); pub const S_IMAPI_COMMAND_HAS_SENSE_DATA: ::windows::core::HRESULT = ::windows::core::HRESULT(11141632i32 as _); pub const S_IMAPI_RAW_IMAGE_TRACK_INDEX_ALREADY_EXISTS: ::windows::core::HRESULT = ::windows::core::HRESULT(11143688i32 as _); pub const S_IMAPI_ROTATIONADJUSTED: ::windows::core::HRESULT = ::windows::core::HRESULT(11141125i32 as _); pub const S_IMAPI_SPEEDADJUSTED: ::windows::core::HRESULT = ::windows::core::HRESULT(11141124i32 as _); pub const S_IMAPI_WRITE_NOT_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(11141890i32 as _); #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn ScCopyNotifications(cnotification: i32, lpnotifications: *mut NOTIFICATION, lpvdst: *mut ::core::ffi::c_void, lpcb: *mut u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ScCopyNotifications(cnotification: i32, lpnotifications: *mut NOTIFICATION, lpvdst: *mut ::core::ffi::c_void, lpcb: *mut u32) -> i32; } ::core::mem::transmute(ScCopyNotifications(::core::mem::transmute(cnotification), ::core::mem::transmute(lpnotifications), ::core::mem::transmute(lpvdst), ::core::mem::transmute(lpcb))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn ScCopyProps(cvalues: i32, lpproparray: *mut SPropValue, lpvdst: *mut ::core::ffi::c_void, lpcb: *mut u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ScCopyProps(cvalues: i32, lpproparray: *mut SPropValue, lpvdst: *mut ::core::ffi::c_void, lpcb: *mut u32) -> i32; } ::core::mem::transmute(ScCopyProps(::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lpvdst), ::core::mem::transmute(lpcb))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn ScCountNotifications(cnotifications: i32, lpnotifications: *mut NOTIFICATION, lpcb: *mut u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ScCountNotifications(cnotifications: i32, lpnotifications: *mut NOTIFICATION, lpcb: *mut u32) -> i32; } ::core::mem::transmute(ScCountNotifications(::core::mem::transmute(cnotifications), ::core::mem::transmute(lpnotifications), ::core::mem::transmute(lpcb))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn ScCountProps(cvalues: i32, lpproparray: *mut SPropValue, lpcb: *mut u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ScCountProps(cvalues: i32, lpproparray: *mut SPropValue, lpcb: *mut u32) -> i32; } ::core::mem::transmute(ScCountProps(::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lpcb))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ScCreateConversationIndex(cbparent: u32, lpbparent: *mut u8, lpcbconvindex: *mut u32, lppbconvindex: *mut *mut u8) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ScCreateConversationIndex(cbparent: u32, lpbparent: *mut u8, lpcbconvindex: *mut u32, lppbconvindex: *mut *mut u8) -> i32; } ::core::mem::transmute(ScCreateConversationIndex(::core::mem::transmute(cbparent), ::core::mem::transmute(lpbparent), ::core::mem::transmute(lpcbconvindex), ::core::mem::transmute(lppbconvindex))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn ScDupPropset(cvalues: i32, lpproparray: *mut SPropValue, lpallocatebuffer: ::core::option::Option<LPALLOCATEBUFFER>, lppproparray: *mut *mut SPropValue) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ScDupPropset(cvalues: i32, lpproparray: *mut SPropValue, lpallocatebuffer: ::windows::core::RawPtr, lppproparray: *mut *mut SPropValue) -> i32; } ::core::mem::transmute(ScDupPropset(::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lpallocatebuffer), ::core::mem::transmute(lppproparray))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ScInitMapiUtil(ulflags: u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ScInitMapiUtil(ulflags: u32) -> i32; } ::core::mem::transmute(ScInitMapiUtil(::core::mem::transmute(ulflags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ScLocalPathFromUNC<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(lpszunc: Param0, lpszlocal: Param1, cchlocal: u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ScLocalPathFromUNC(lpszunc: super::super::Foundation::PSTR, lpszlocal: super::super::Foundation::PSTR, cchlocal: u32) -> i32; } ::core::mem::transmute(ScLocalPathFromUNC(lpszunc.into_param().abi(), lpszlocal.into_param().abi(), ::core::mem::transmute(cchlocal))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn ScRelocNotifications(cnotification: i32, lpnotifications: *mut NOTIFICATION, lpvbaseold: *mut ::core::ffi::c_void, lpvbasenew: *mut ::core::ffi::c_void, lpcb: *mut u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ScRelocNotifications(cnotification: i32, lpnotifications: *mut NOTIFICATION, lpvbaseold: *mut ::core::ffi::c_void, lpvbasenew: *mut ::core::ffi::c_void, lpcb: *mut u32) -> i32; } ::core::mem::transmute(ScRelocNotifications(::core::mem::transmute(cnotification), ::core::mem::transmute(lpnotifications), ::core::mem::transmute(lpvbaseold), ::core::mem::transmute(lpvbasenew), ::core::mem::transmute(lpcb))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn ScRelocProps(cvalues: i32, lpproparray: *mut SPropValue, lpvbaseold: *mut ::core::ffi::c_void, lpvbasenew: *mut ::core::ffi::c_void, lpcb: *mut u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ScRelocProps(cvalues: i32, lpproparray: *mut SPropValue, lpvbaseold: *mut ::core::ffi::c_void, lpvbasenew: *mut ::core::ffi::c_void, lpcb: *mut u32) -> i32; } ::core::mem::transmute(ScRelocProps(::core::mem::transmute(cvalues), ::core::mem::transmute(lpproparray), ::core::mem::transmute(lpvbaseold), ::core::mem::transmute(lpvbasenew), ::core::mem::transmute(lpcb))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ScUNCFromLocalPath<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(lpszlocal: Param0, lpszunc: Param1, cchunc: u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ScUNCFromLocalPath(lpszlocal: super::super::Foundation::PSTR, lpszunc: super::super::Foundation::PSTR, cchunc: u32) -> i32; } ::core::mem::transmute(ScUNCFromLocalPath(lpszlocal.into_param().abi(), lpszunc.into_param().abi(), ::core::mem::transmute(cchunc))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn SzFindCh(lpsz: *mut i8, ch: u16) -> *mut i8 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SzFindCh(lpsz: *mut i8, ch: u16) -> *mut i8; } ::core::mem::transmute(SzFindCh(::core::mem::transmute(lpsz), ::core::mem::transmute(ch))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn SzFindLastCh(lpsz: *mut i8, ch: u16) -> *mut i8 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SzFindLastCh(lpsz: *mut i8, ch: u16) -> *mut i8; } ::core::mem::transmute(SzFindLastCh(::core::mem::transmute(lpsz), ::core::mem::transmute(ch))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn SzFindSz(lpsz: *mut i8, lpszkey: *mut i8) -> *mut i8 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SzFindSz(lpsz: *mut i8, lpszkey: *mut i8) -> *mut i8; } ::core::mem::transmute(SzFindSz(::core::mem::transmute(lpsz), ::core::mem::transmute(lpszkey))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } pub const TABLE_CHANGED: u32 = 1u32; pub const TABLE_ERROR: u32 = 2u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub struct TABLE_NOTIFICATION { pub ulTableEvent: u32, pub hResult: ::windows::core::HRESULT, pub propIndex: SPropValue, pub propPrior: SPropValue, pub row: SRow, pub ulPad: u32, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl TABLE_NOTIFICATION {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for TABLE_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for TABLE_NOTIFICATION { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for TABLE_NOTIFICATION {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for TABLE_NOTIFICATION { type Abi = Self; } pub const TABLE_RELOAD: u32 = 9u32; pub const TABLE_RESTRICT_DONE: u32 = 7u32; pub const TABLE_ROW_ADDED: u32 = 3u32; pub const TABLE_ROW_DELETED: u32 = 4u32; pub const TABLE_ROW_MODIFIED: u32 = 5u32; pub const TABLE_SETCOL_DONE: u32 = 8u32; pub const TABLE_SORT_DONE: u32 = 6u32; pub const TAD_ALL_ROWS: u32 = 1u32; #[inline] pub unsafe fn UFromSz(lpsz: *mut i8) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn UFromSz(lpsz: *mut i8) -> u32; } ::core::mem::transmute(UFromSz(::core::mem::transmute(lpsz))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } pub const UI_CURRENT_PROVIDER_FIRST: u32 = 4u32; pub const UI_SERVICE: u32 = 2u32; #[inline] pub unsafe fn UlAddRef(lpunk: *mut ::core::ffi::c_void) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn UlAddRef(lpunk: *mut ::core::ffi::c_void) -> u32; } ::core::mem::transmute(UlAddRef(::core::mem::transmute(lpunk))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] #[inline] pub unsafe fn UlPropSize(lpspropvalue: *mut SPropValue) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn UlPropSize(lpspropvalue: *mut SPropValue) -> u32; } ::core::mem::transmute(UlPropSize(::core::mem::transmute(lpspropvalue))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn UlRelease(lpunk: *mut ::core::ffi::c_void) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn UlRelease(lpunk: *mut ::core::ffi::c_void) -> u32; } ::core::mem::transmute(UlRelease(::core::mem::transmute(lpunk))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct WABEXTDISPLAY { pub cbSize: u32, pub lpWABObject: ::core::option::Option<IWABObject>, pub lpAdrBook: ::core::option::Option<IAddrBook>, pub lpPropObj: ::core::option::Option<IMAPIProp>, pub fReadOnly: super::super::Foundation::BOOL, pub fDataChanged: super::super::Foundation::BOOL, pub ulFlags: u32, pub lpv: *mut ::core::ffi::c_void, pub lpsz: *mut i8, } #[cfg(feature = "Win32_Foundation")] impl WABEXTDISPLAY {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for WABEXTDISPLAY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for WABEXTDISPLAY { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("WABEXTDISPLAY") .field("cbSize", &self.cbSize) .field("lpWABObject", &self.lpWABObject) .field("lpAdrBook", &self.lpAdrBook) .field("lpPropObj", &self.lpPropObj) .field("fReadOnly", &self.fReadOnly) .field("fDataChanged", &self.fDataChanged) .field("ulFlags", &self.ulFlags) .field("lpv", &self.lpv) .field("lpsz", &self.lpsz) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for WABEXTDISPLAY { fn eq(&self, other: &Self) -> bool { self.cbSize == other.cbSize && self.lpWABObject == other.lpWABObject && self.lpAdrBook == other.lpAdrBook && self.lpPropObj == other.lpPropObj && self.fReadOnly == other.fReadOnly && self.fDataChanged == other.fDataChanged && self.ulFlags == other.ulFlags && self.lpv == other.lpv && self.lpsz == other.lpsz } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for WABEXTDISPLAY {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for WABEXTDISPLAY { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: clone :: Clone)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct WABIMPORTPARAM { pub cbSize: u32, pub lpAdrBook: ::core::option::Option<IAddrBook>, pub hWnd: super::super::Foundation::HWND, pub ulFlags: u32, pub lpszFileName: super::super::Foundation::PSTR, } #[cfg(feature = "Win32_Foundation")] impl WABIMPORTPARAM {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for WABIMPORTPARAM { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for WABIMPORTPARAM { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("WABIMPORTPARAM").field("cbSize", &self.cbSize).field("lpAdrBook", &self.lpAdrBook).field("hWnd", &self.hWnd).field("ulFlags", &self.ulFlags).field("lpszFileName", &self.lpszFileName).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for WABIMPORTPARAM { fn eq(&self, other: &Self) -> bool { self.cbSize == other.cbSize && self.lpAdrBook == other.lpAdrBook && self.hWnd == other.hWnd && self.ulFlags == other.ulFlags && self.lpszFileName == other.lpszFileName } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for WABIMPORTPARAM {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for WABIMPORTPARAM { type Abi = ::core::mem::ManuallyDrop<Self>; } pub const WABOBJECT_LDAPURL_RETURN_MAILUSER: u32 = 1u32; pub const WABOBJECT_ME_NEW: u32 = 1u32; pub const WABOBJECT_ME_NOCREATE: u32 = 2u32; pub const WAB_CONTEXT_ADRLIST: u32 = 2u32; pub const WAB_DISPLAY_ISNTDS: u32 = 4u32; pub const WAB_DISPLAY_LDAPURL: u32 = 1u32; pub const WAB_ENABLE_PROFILES: u32 = 4194304u32; pub const WAB_IGNORE_PROFILES: u32 = 8388608u32; pub const WAB_LOCAL_CONTAINERS: u32 = 1048576u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct WAB_PARAM { pub cbSize: u32, pub hwnd: super::super::Foundation::HWND, pub szFileName: super::super::Foundation::PSTR, pub ulFlags: u32, pub guidPSExt: ::windows::core::GUID, } #[cfg(feature = "Win32_Foundation")] impl WAB_PARAM {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for WAB_PARAM { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for WAB_PARAM { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("WAB_PARAM").field("cbSize", &self.cbSize).field("hwnd", &self.hwnd).field("szFileName", &self.szFileName).field("ulFlags", &self.ulFlags).field("guidPSExt", &self.guidPSExt).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for WAB_PARAM { fn eq(&self, other: &Self) -> bool { self.cbSize == other.cbSize && self.hwnd == other.hwnd && self.szFileName == other.szFileName && self.ulFlags == other.ulFlags && self.guidPSExt == other.guidPSExt } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for WAB_PARAM {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for WAB_PARAM { type Abi = Self; } pub const WAB_PROFILE_CONTENTS: u32 = 2097152u32; pub const WAB_USE_OE_SENDMAIL: u32 = 1u32; pub const WAB_VCARD_FILE: u32 = 0u32; pub const WAB_VCARD_STREAM: u32 = 1u32; #[cfg(feature = "Win32_System_Com")] #[inline] pub unsafe fn WrapCompressedRTFStream<'a, Param0: ::windows::core::IntoParam<'a, super::Com::IStream>>(lpcompressedrtfstream: Param0, ulflags: u32) -> ::windows::core::Result<super::Com::IStream> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn WrapCompressedRTFStream(lpcompressedrtfstream: ::windows::core::RawPtr, ulflags: u32, lpuncompressedrtfstream: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; } let mut result__: <super::Com::IStream as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); WrapCompressedRTFStream(lpcompressedrtfstream.into_param().abi(), ::core::mem::transmute(ulflags), &mut result__).from_abi::<super::Com::IStream>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn WrapStoreEntryID(ulflags: u32, lpszdllname: *const i8, cborigentry: u32, lporigentry: *const ENTRYID, lpcbwrappedentry: *mut u32, lppwrappedentry: *mut *mut ENTRYID) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn WrapStoreEntryID(ulflags: u32, lpszdllname: *const i8, cborigentry: u32, lporigentry: *const ENTRYID, lpcbwrappedentry: *mut u32, lppwrappedentry: *mut *mut ENTRYID) -> ::windows::core::HRESULT; } WrapStoreEntryID(::core::mem::transmute(ulflags), ::core::mem::transmute(lpszdllname), ::core::mem::transmute(cborigentry), ::core::mem::transmute(lporigentry), ::core::mem::transmute(lpcbwrappedentry), ::core::mem::transmute(lppwrappedentry)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub union _PV { pub i: i16, pub l: i32, pub ul: u32, pub flt: f32, pub dbl: f64, pub b: u16, pub cur: super::Com::CY, pub at: f64, pub ft: super::super::Foundation::FILETIME, pub lpszA: super::super::Foundation::PSTR, pub bin: SBinary, pub lpszW: super::super::Foundation::PWSTR, pub lpguid: *mut ::windows::core::GUID, pub li: i64, pub MVi: SShortArray, pub MVl: SLongArray, pub MVflt: SRealArray, pub MVdbl: SDoubleArray, pub MVcur: SCurrencyArray, pub MVat: SAppTimeArray, pub MVft: SDateTimeArray, pub MVbin: SBinaryArray, pub MVszA: SLPSTRArray, pub MVszW: SWStringArray, pub MVguid: SGuidArray, pub MVli: SLargeIntegerArray, pub err: i32, pub x: i32, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl _PV {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::default::Default for _PV { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::PartialEq for _PV { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] impl ::core::cmp::Eq for _PV {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] unsafe impl ::windows::core::Abi for _PV { type Abi = Self; } #[repr(C)] #[derive(:: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy)] pub struct _WABACTIONITEM(pub u8); #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct _flaglist { pub cFlags: u32, pub ulFlag: [u32; 1], } impl _flaglist {} impl ::core::default::Default for _flaglist { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for _flaglist { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_flaglist").field("cFlags", &self.cFlags).field("ulFlag", &self.ulFlag).finish() } } impl ::core::cmp::PartialEq for _flaglist { fn eq(&self, other: &Self) -> bool { self.cFlags == other.cFlags && self.ulFlag == other.ulFlag } } impl ::core::cmp::Eq for _flaglist {} unsafe impl ::windows::core::Abi for _flaglist { type Abi = Self; }
use super::unit_data::UnitType; use nanoserde::DeRon; fn load_units() -> Vec<UnitType> { let units: Vec<UnitType> = DeRon::deserialize_ron(include_str!("../assets/Units.ron")).unwrap(); units } lazy_static! { pub static ref UNIT_TYPES: Vec<UnitType> = load_units(); }
use crate::{Filter, NodeIterator, SourceCode, ValidationError, Validator}; use tree_sitter::Node; #[allow(unused_macros)] macro_rules! assert_some { ($expression:expr) => { match $expression { Some(item) => item, None => panic!("assertion failed: Option instance is not some"), } }; } #[allow(unused_macros)] macro_rules! assert_err { ($expression:expr) => { match $expression { Err(err) => err, ok => panic!("assertion failed: {:?} does not match Err()", ok), } }; } fn recur_validate( node: &Node, source: &str, validator: Box<dyn Validator>, filter: &dyn Filter, ) -> Result<(), ValidationError> { for n in NodeIterator::new(node.walk(), source, filter) { validator.validate(&n, source)?; } Ok(()) } pub fn node_lowercase_contains(node_kind: &str, node: &Node, source: &str, pat: &str) -> bool { match get_text(node_kind, node, source) { Some(ident) => ident.to_lowercase().contains(pat), None => false, } } pub fn node_lowercase_eq(node_kind: &str, node: &Node, source: &str, s: &str) -> bool { match get_text(node_kind, node, source) { Some(ident) => ident.to_lowercase().eq(s), None => false, } } fn get_text<'a>(node_kind: &str, node: &Node, source: &'a str) -> Option<&'a str> { if node.kind() == node_kind { let ident = match node.utf8_text(source.as_bytes()) { Ok(ident) => ident, Err(err) => { error!("failed to get identifier: {:?}", err); return None; } }; return Some(ident); } None } #[allow(dead_code)] pub fn assert_source_ok(source_code: &str, validator: Box<dyn Validator>, filter: &dyn Filter) { let res = validate(source_code, validator, filter); assert!(res.is_ok()); } pub fn validate( source_code: &str, validator: Box<dyn Validator>, filter: &dyn Filter, ) -> Result<(), ValidationError> { let parse_result = SourceCode::parse(source_code); let source = assert_some!(parse_result); let root = source.get_root_node(); recur_validate(&root, source_code, validator, filter) }