text
stringlengths
8
4.13M
use std::cmp::max; use std::ffi::{ c_void, CString, }; use std::hash::{ Hash, Hasher, }; use std::sync::{ Arc, Mutex, Weak, }; use ash::vk; use ash::vk::Handle; use smallvec::SmallVec; use sourcerenderer_core::graphics::{ AddressMode, Filter, SamplerInfo, Texture, TextureDimension, TextureInfo, TextureUsage, TextureView, TextureViewInfo, }; use crate::bindless::VkBindlessDescriptorSet; use crate::format::format_to_vk; use crate::pipeline::{ compare_func_to_vk, samples_to_vk, }; use crate::raw::{ RawVkDevice, VkFeatures, }; use crate::VkBackend; pub struct VkTexture { image: vk::Image, allocation: Option<vma_sys::VmaAllocation>, device: Arc<RawVkDevice>, info: TextureInfo, bindless_slot: Mutex<Option<VkTextureBindlessSlot>>, } unsafe impl Send for VkTexture {} unsafe impl Sync for VkTexture {} struct VkTextureBindlessSlot { bindless_set: Weak<VkBindlessDescriptorSet>, slot: u32, } impl VkTexture { pub fn new(device: &Arc<RawVkDevice>, info: &TextureInfo, name: Option<&str>) -> Self { let mut create_info = vk::ImageCreateInfo { flags: vk::ImageCreateFlags::empty(), tiling: vk::ImageTiling::OPTIMAL, initial_layout: vk::ImageLayout::UNDEFINED, sharing_mode: vk::SharingMode::EXCLUSIVE, usage: texture_usage_to_vk(info.usage), image_type: match info.dimension { TextureDimension::Dim1DArray | TextureDimension::Dim1D => vk::ImageType::TYPE_1D, TextureDimension::Dim2DArray | TextureDimension::Dim2D => vk::ImageType::TYPE_2D, TextureDimension::Dim3D => vk::ImageType::TYPE_3D }, extent: vk::Extent3D { width: max(1, info.width), height: max(1, info.height), depth: max(1, info.depth), }, format: format_to_vk(info.format, device.supports_d24), mip_levels: info.mip_levels, array_layers: info.array_length, samples: samples_to_vk(info.samples), ..Default::default() }; debug_assert!(info.array_length == 1 || (info.dimension == TextureDimension::Dim1DArray || info.dimension == TextureDimension::Dim2DArray)); debug_assert!(info.depth == 1 || info.dimension == TextureDimension::Dim3D); debug_assert!(info.height == 1 || (info.dimension == TextureDimension::Dim2D || info.dimension == TextureDimension::Dim2DArray || info.dimension == TextureDimension::Dim3D)); let mut compatible_formats = SmallVec::<[vk::Format; 2]>::with_capacity(2); compatible_formats.push(create_info.format); let mut format_list = vk::ImageFormatListCreateInfo { view_format_count: compatible_formats.len() as u32, p_view_formats: compatible_formats.as_ptr(), ..Default::default() }; if info.supports_srgb { create_info.flags |= vk::ImageCreateFlags::MUTABLE_FORMAT; if device.features.contains(VkFeatures::IMAGE_FORMAT_LIST) { format_list.p_next = std::mem::replace( &mut create_info.p_next, &format_list as *const vk::ImageFormatListCreateInfo as *const c_void, ); } } let mut props: vk::ImageFormatProperties2 = Default::default(); unsafe { device .instance .get_physical_device_image_format_properties2( device.physical_device, &vk::PhysicalDeviceImageFormatInfo2 { format: create_info.format, ty: create_info.image_type, tiling: create_info.tiling, usage: create_info.usage, flags: create_info.flags, ..Default::default() }, &mut props, ) .unwrap() }; let allocation_create_info = vma_sys::VmaAllocationCreateInfo { flags: vma_sys::VmaAllocationCreateFlags::default(), usage: vma_sys::VmaMemoryUsage_VMA_MEMORY_USAGE_UNKNOWN, preferredFlags: vk::MemoryPropertyFlags::DEVICE_LOCAL, requiredFlags: vk::MemoryPropertyFlags::empty(), memoryTypeBits: 0, pool: std::ptr::null_mut(), pUserData: std::ptr::null_mut(), priority: if info.usage.intersects( TextureUsage::STORAGE | TextureUsage::DEPTH_STENCIL | TextureUsage::RENDER_TARGET, ) { 1f32 } else { 0f32 }, }; let mut image: vk::Image = vk::Image::null(); let mut allocation: vma_sys::VmaAllocation = std::ptr::null_mut(); unsafe { assert_eq!( vma_sys::vmaCreateImage( device.allocator, &create_info, &allocation_create_info, &mut image, &mut allocation, std::ptr::null_mut() ), vk::Result::SUCCESS ); }; if let Some(name) = name { if let Some(debug_utils) = device.instance.debug_utils.as_ref() { let name_cstring = CString::new(name).unwrap(); unsafe { debug_utils .debug_utils_loader .set_debug_utils_object_name( device.handle(), &vk::DebugUtilsObjectNameInfoEXT { object_type: vk::ObjectType::IMAGE, object_handle: image.as_raw(), p_object_name: name_cstring.as_ptr(), ..Default::default() }, ) .unwrap(); } } } Self { image, allocation: Some(allocation), device: device.clone(), info: info.clone(), bindless_slot: Mutex::new(None), } } pub fn from_image(device: &Arc<RawVkDevice>, image: vk::Image, info: TextureInfo) -> Self { VkTexture { image, device: device.clone(), info, allocation: None, bindless_slot: Mutex::new(None), } } pub fn handle(&self) -> &vk::Image { &self.image } pub(crate) fn set_bindless_slot(&self, bindless_set: &Arc<VkBindlessDescriptorSet>, slot: u32) { let mut lock = self.bindless_slot.lock().unwrap(); *lock = Some(VkTextureBindlessSlot { bindless_set: Arc::downgrade(bindless_set), slot, }); } } fn texture_usage_to_vk(usage: TextureUsage) -> vk::ImageUsageFlags { let mut flags = vk::ImageUsageFlags::empty(); if usage.contains(TextureUsage::STORAGE) { flags |= vk::ImageUsageFlags::STORAGE; } if usage.contains(TextureUsage::SAMPLED) { flags |= vk::ImageUsageFlags::SAMPLED; } let transfer_src_usages = TextureUsage::BLIT_SRC | TextureUsage::COPY_SRC | TextureUsage::RESOLVE_SRC; // TODO: sync2 if usage.intersects(transfer_src_usages) { flags |= vk::ImageUsageFlags::TRANSFER_SRC; } let transfer_dst_usages = TextureUsage::BLIT_DST | TextureUsage::COPY_DST | TextureUsage::RESOLVE_DST; if usage.intersects(transfer_dst_usages) { flags |= vk::ImageUsageFlags::TRANSFER_DST; } if usage.contains(TextureUsage::DEPTH_STENCIL) { flags |= vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT; } if usage.contains(TextureUsage::RENDER_TARGET) { flags |= vk::ImageUsageFlags::COLOR_ATTACHMENT; } flags } impl Drop for VkTexture { fn drop(&mut self) { let mut bindless_slot = self.bindless_slot.lock().unwrap(); if let Some(bindless_slot) = bindless_slot.take() { let set = bindless_slot.bindless_set.upgrade(); if let Some(set) = set { set.free_slot(bindless_slot.slot); } } if let Some(alloc) = self.allocation { unsafe { vma_sys::vmaDestroyImage(self.device.allocator, self.image, alloc); } } } } impl Texture for VkTexture { fn info(&self) -> &TextureInfo { &self.info } } impl Hash for VkTexture { fn hash<H: Hasher>(&self, state: &mut H) { self.image.hash(state); } } impl PartialEq for VkTexture { fn eq(&self, other: &Self) -> bool { self.image == other.image } } impl Eq for VkTexture {} fn filter_to_vk(filter: Filter) -> vk::Filter { match filter { Filter::Linear => vk::Filter::LINEAR, Filter::Nearest => vk::Filter::NEAREST, Filter::Max => vk::Filter::LINEAR, Filter::Min => vk::Filter::LINEAR, } } fn filter_to_vk_mip(filter: Filter) -> vk::SamplerMipmapMode { match filter { Filter::Linear => vk::SamplerMipmapMode::LINEAR, Filter::Nearest => vk::SamplerMipmapMode::NEAREST, Filter::Max => panic!("Can't use max as mipmap filter."), Filter::Min => panic!("Can't use min as mipmap filter."), } } fn filter_to_reduction_mode(filter: Filter) -> vk::SamplerReductionMode { match filter { Filter::Max => vk::SamplerReductionMode::MAX, Filter::Min => vk::SamplerReductionMode::MIN, _ => unreachable!(), } } fn address_mode_to_vk(address_mode: AddressMode) -> vk::SamplerAddressMode { match address_mode { AddressMode::Repeat => vk::SamplerAddressMode::REPEAT, AddressMode::ClampToBorder => vk::SamplerAddressMode::CLAMP_TO_BORDER, AddressMode::ClampToEdge => vk::SamplerAddressMode::CLAMP_TO_EDGE, AddressMode::MirroredRepeat => vk::SamplerAddressMode::MIRRORED_REPEAT, } } pub struct VkTextureView { view: vk::ImageView, texture: Arc<VkTexture>, device: Arc<RawVkDevice>, info: TextureViewInfo, } impl VkTextureView { pub(crate) fn new( device: &Arc<RawVkDevice>, texture: &Arc<VkTexture>, info: &TextureViewInfo, name: Option<&str>, ) -> Self { let format = info.format.unwrap_or(texture.info.format); let view_create_info = vk::ImageViewCreateInfo { image: *texture.handle(), view_type: match texture.info.dimension { TextureDimension::Dim1D => vk::ImageViewType::TYPE_1D, TextureDimension::Dim2D => vk::ImageViewType::TYPE_2D, TextureDimension::Dim3D => vk::ImageViewType::TYPE_3D, TextureDimension::Dim1DArray => vk::ImageViewType::TYPE_1D_ARRAY, TextureDimension::Dim2DArray => vk::ImageViewType::TYPE_2D_ARRAY, }, format: format_to_vk(format, device.supports_d24), components: vk::ComponentMapping { r: vk::ComponentSwizzle::IDENTITY, g: vk::ComponentSwizzle::IDENTITY, b: vk::ComponentSwizzle::IDENTITY, a: vk::ComponentSwizzle::IDENTITY, }, subresource_range: vk::ImageSubresourceRange { aspect_mask: if format.is_depth() { vk::ImageAspectFlags::DEPTH } else { vk::ImageAspectFlags::COLOR }, base_mip_level: info.base_mip_level, level_count: info.mip_level_length, base_array_layer: info.base_array_layer, layer_count: info.array_layer_length, }, ..Default::default() }; let view = unsafe { device.create_image_view(&view_create_info, None) }.unwrap(); if let Some(name) = name { if let Some(debug_utils) = device.instance.debug_utils.as_ref() { let name_cstring = CString::new(name).unwrap(); unsafe { debug_utils .debug_utils_loader .set_debug_utils_object_name( device.handle(), &vk::DebugUtilsObjectNameInfoEXT { object_type: vk::ObjectType::IMAGE_VIEW, object_handle: view.as_raw(), p_object_name: name_cstring.as_ptr(), ..Default::default() }, ) .unwrap(); } } } Self { view, texture: texture.clone(), device: device.clone(), info: info.clone(), } } #[inline] pub(crate) fn view_handle(&self) -> &vk::ImageView { &self.view } pub(crate) fn texture(&self) -> &Arc<VkTexture> { &self.texture } } impl Drop for VkTextureView { fn drop(&mut self) { unsafe { self.device.destroy_image_view(self.view, None); } } } impl TextureView<VkBackend> for VkTextureView { fn texture(&self) -> &Arc<VkTexture> { &self.texture } fn info(&self) -> &TextureViewInfo { &self.info } } impl Hash for VkTextureView { fn hash<H: Hasher>(&self, state: &mut H) { self.texture.hash(state); self.view.hash(state); } } impl PartialEq for VkTextureView { fn eq(&self, other: &Self) -> bool { self.texture == other.texture && self.view == other.view } } impl Eq for VkTextureView {} pub struct VkSampler { sampler: vk::Sampler, device: Arc<RawVkDevice>, } impl VkSampler { pub fn new(device: &Arc<RawVkDevice>, info: &SamplerInfo) -> Self { let mut sampler_create_info = vk::SamplerCreateInfo { mag_filter: filter_to_vk(info.mag_filter), min_filter: filter_to_vk(info.mag_filter), mipmap_mode: filter_to_vk_mip(info.mip_filter), address_mode_u: address_mode_to_vk(info.address_mode_u), address_mode_v: address_mode_to_vk(info.address_mode_v), address_mode_w: address_mode_to_vk(info.address_mode_u), mip_lod_bias: info.mip_bias, anisotropy_enable: (info.max_anisotropy.abs() >= 1.0f32) as u32, max_anisotropy: info.max_anisotropy, compare_enable: info.compare_op.is_some() as u32, compare_op: info .compare_op .map_or(vk::CompareOp::ALWAYS, compare_func_to_vk), min_lod: info.min_lod, max_lod: info.max_lod.unwrap_or(vk::LOD_CLAMP_NONE), border_color: vk::BorderColor::INT_OPAQUE_BLACK, unnormalized_coordinates: 0, ..Default::default() }; let mut sampler_minmax_info = vk::SamplerReductionModeCreateInfo::default(); if info.min_filter == Filter::Min || info.min_filter == Filter::Max { assert!(device.features.contains(VkFeatures::MIN_MAX_FILTER)); sampler_minmax_info.reduction_mode = filter_to_reduction_mode(info.min_filter); sampler_create_info.p_next = &sampler_minmax_info as *const vk::SamplerReductionModeCreateInfo as *const c_void; } debug_assert_ne!(info.mag_filter, Filter::Min); debug_assert_ne!(info.mag_filter, Filter::Max); debug_assert_ne!(info.mip_filter, Filter::Min); debug_assert_ne!(info.mip_filter, Filter::Max); let sampler = unsafe { device.create_sampler(&sampler_create_info, None) }.unwrap(); Self { sampler, device: device.clone(), } } #[inline] pub(crate) fn handle(&self) -> &vk::Sampler { &self.sampler } } impl Drop for VkSampler { fn drop(&mut self) { unsafe { self.device.destroy_sampler(self.sampler, None); } } } impl Hash for VkSampler { fn hash<H: Hasher>(&self, state: &mut H) { self.sampler.hash(state); } } impl PartialEq for VkSampler { fn eq(&self, other: &Self) -> bool { self.sampler == other.sampler } } impl Eq for VkSampler {}
// Copyright (c) 2020 DarkWeb Design // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /// Get string length. /// /// # Description /// /// Returns the length of the given string. /// /// # Examples /// /// Example #1 strlen() example /// /// ``` /// use phpify::string::strlen; /// /// let str = "abcdef"; /// assert_eq!(strlen(str), 6); /// /// let str = " ab cd "; /// assert_eq!(strlen(str), 7); /// ``` /// /// # notes /// /// strlen() returns the number of bytes rather than the number of characters in a string. pub fn strlen<S>(string: S) -> usize where S: AsRef<str> { string.as_ref().len() } #[cfg(test)] mod tests { use crate::string::strlen; #[test] fn test() { assert_eq!(strlen("Hello World"), 11); assert_eq!(strlen(""), 0); } }
extern crate subdemo; fn main() { subdemo::hello_world(); }
use rand::seq::SliceRandom; use rand::thread_rng; use std::char; use std::fmt; use serde::{Deserialize, Serialize}; #[derive(Debug)] pub struct Deck { pub cards: Vec<Card>, } impl Deck { pub fn shuffle(mut self) -> Self { self.cards.shuffle(&mut thread_rng()); return self; } } impl Default for Deck { fn default() -> Self { let mut deck = Deck { cards: vec![] }; for rank in 2..15 { deck.cards.push(Card { suit: Suit::Club, rank: CardRank::from_usize(rank), }); deck.cards.push(Card { suit: Suit::Diamond, rank: CardRank::from_usize(rank), }); deck.cards.push(Card { suit: Suit::Heart, rank: CardRank::from_usize(rank), }); deck.cards.push(Card { suit: Suit::Spade, rank: CardRank::from_usize(rank), }); } return deck; } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Suit { Club, Diamond, Heart, Spade, } impl Suit { pub fn unicode_code_point(&self) -> u32 { match self { Suit::Spade => 0xA0, Suit::Heart => 0xB0, Suit::Diamond => 0xC0, Suit::Club => 0xD0, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CardValue { Wild, Numeric(usize), } #[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum CardRank { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace, } impl CardRank { pub fn from_usize(rank: usize) -> CardRank { match rank { 2 => CardRank::Two, 3 => CardRank::Three, 4 => CardRank::Four, 5 => CardRank::Five, 6 => CardRank::Six, 7 => CardRank::Seven, 8 => CardRank::Eight, 9 => CardRank::Nine, 10 => CardRank::Ten, 11 => CardRank::Jack, 12 => CardRank::Queen, 13 => CardRank::King, 14 => CardRank::Ace, _ => panic!("Unknown rank: {}", rank), } } pub fn unicode_code_point(&self) -> u32 { match self { CardRank::Two => 0x2, CardRank::Three => 0x3, CardRank::Four => 0x4, CardRank::Five => 0x5, CardRank::Six => 0x6, CardRank::Seven => 0x7, CardRank::Eight => 0x8, CardRank::Nine => 0x9, CardRank::Ten => 0xA, CardRank::Jack => 0xB, CardRank::Queen => 0xD, CardRank::King => 0xE, CardRank::Ace => 0x1, } } } #[derive(Clone, PartialEq, Serialize, Deserialize)] pub struct Card { pub suit: Suit, pub rank: CardRank, } impl fmt::Debug for Card { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self) } } const PLAYING_CARD_UNICODE_CODE_POINT_LOWER_BOUND: u32 = 0x1F000; impl fmt::Display for Card { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", char::from_u32( PLAYING_CARD_UNICODE_CODE_POINT_LOWER_BOUND + self.suit.unicode_code_point() + self.rank.unicode_code_point() ) .expect(&format!( "Invalid card to unicode conversion for: {:#?} {:#?}", self.rank, self.suit )) .to_string(), ) } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CardGroupVisibility { FaceDown, FaceUp, TopFaceUpRestFaceDown, VisibleToOwner, } #[derive(Clone, PartialEq, Serialize, Deserialize)] pub struct CardGroup { #[serde(default)] pub cards: Vec<Card>, pub initial_deal_count: Option<usize>, pub visibility: CardGroupVisibility, } impl CardGroup { pub fn at_or_over_initial_deal_size(&self) -> Option<bool> { if let Some(initial_deal_count) = self.initial_deal_count { if self.cards.len() >= initial_deal_count { return Some(true); } else { return Some(false); } } return None; } } impl fmt::Debug for CardGroup { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self) } } const PLAYING_CARD_BACK: &str = "🂠 "; // TODO: Fix visible only to owner once users have different outputs impl fmt::Display for CardGroup { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let string_repr = match self.visibility { CardGroupVisibility::FaceDown => self .cards .iter() .map(|_| PLAYING_CARD_BACK.to_string()) .collect::<Vec<String>>() .join(", "), CardGroupVisibility::FaceUp | CardGroupVisibility::VisibleToOwner => self .cards .iter() .map(|c| c.to_string()) .collect::<Vec<String>>() .join(", "), CardGroupVisibility::TopFaceUpRestFaceDown => { if self.cards.len() == 0 { "".to_string() } else { self.cards[0].to_string() } } }; write!(f, "{}", string_repr) } }
//! Error and Result module. use std::error::Error as StdError; use std::fmt; use std::io; use httparse; use http; /// Result type often returned from methods that can have hyper `Error`s. pub type Result<T> = ::std::result::Result<T, Error>; type Cause = Box<StdError + Send + Sync>; /// Represents errors that can occur handling HTTP streams. pub struct Error { inner: Box<ErrorImpl>, } struct ErrorImpl { kind: Kind, cause: Option<Cause>, } #[derive(Debug, PartialEq)] pub(crate) enum Kind { Parse(Parse), /// A message reached EOF, but is not complete. Incomplete, /// A client connection received a response when not waiting for one. MismatchedResponse, /// A pending item was dropped before ever being processed. Canceled, /// Indicates a connection is closed. Closed, /// An `io::Error` that occurred while trying to read or write to a network stream. Io, /// Error occurred while connecting. Connect, /// Error creating a TcpListener. #[cfg(feature = "runtime")] Listen, /// Error accepting on an Incoming stream. Accept, /// Error calling user's NewService::new_service(). NewService, /// Error from future of user's Service::call(). Service, /// Error while reading a body from connection. Body, /// Error while writing a body to connection. BodyWrite, /// Error calling user's Payload::poll_data(). BodyUser, /// Error calling AsyncWrite::shutdown() Shutdown, /// A general error from h2. Http2, /// User tried to create a Request with bad version. UnsupportedVersion, /// User tried to create a CONNECT Request with the Client. UnsupportedRequestMethod, /// User tried to respond with a 1xx (not 101) response code. UnsupportedStatusCode, /// User tried to send a Request with Client with non-absolute URI. AbsoluteUriRequired, /// User tried polling for an upgrade that doesn't exist. NoUpgrade, /// User polled for an upgrade, but low-level API is not using upgrades. ManualUpgrade, /// Error trying to call `Executor::execute`. Execute, } #[derive(Debug, PartialEq)] pub(crate) enum Parse { Method, Version, VersionH2, Uri, Header, TooLarge, Status, } /* #[derive(Debug)] pub(crate) enum User { VersionNotSupported, MethodNotSupported, InvalidRequestUri, } */ impl Error { /// Returns true if this was an HTTP parse error. pub fn is_parse(&self) -> bool { match self.inner.kind { Kind::Parse(_) => true, _ => false, } } /// Returns true if this error was caused by user code. pub fn is_user(&self) -> bool { match self.inner.kind { Kind::BodyUser | Kind::NewService | Kind::Service | Kind::Closed | Kind::UnsupportedVersion | Kind::UnsupportedRequestMethod | Kind::UnsupportedStatusCode | Kind::AbsoluteUriRequired | Kind::NoUpgrade | Kind::Execute => true, _ => false, } } /// Returns true if this was about a `Request` that was canceled. pub fn is_canceled(&self) -> bool { self.inner.kind == Kind::Canceled } /// Returns true if a sender's channel is closed. pub fn is_closed(&self) -> bool { self.inner.kind == Kind::Closed } /// Returns true if this was an error from `Connect`. pub fn is_connect(&self) -> bool { self.inner.kind == Kind::Connect } /// Returns the error's cause. /// /// This is identical to `Error::cause` except that it provides extra /// bounds required to be able to downcast the error. pub fn cause2(&self) -> Option<&(StdError + 'static + Sync + Send)> { self.inner.cause.as_ref().map(|e| &**e) } /// Consumes the error, returning its cause. pub fn into_cause(self) -> Option<Box<StdError + Sync + Send>> { self.inner.cause } pub(crate) fn new(kind: Kind, cause: Option<Cause>) -> Error { Error { inner: Box::new(ErrorImpl { kind, cause, }), } } pub(crate) fn kind(&self) -> &Kind { &self.inner.kind } pub(crate) fn new_canceled<E: Into<Cause>>(cause: Option<E>) -> Error { Error::new(Kind::Canceled, cause.map(Into::into)) } pub(crate) fn new_incomplete() -> Error { Error::new(Kind::Incomplete, None) } pub(crate) fn new_too_large() -> Error { Error::new(Kind::Parse(Parse::TooLarge), None) } pub(crate) fn new_header() -> Error { Error::new(Kind::Parse(Parse::Header), None) } pub(crate) fn new_version_h2() -> Error { Error::new(Kind::Parse(Parse::VersionH2), None) } pub(crate) fn new_mismatched_response() -> Error { Error::new(Kind::MismatchedResponse, None) } pub(crate) fn new_io(cause: io::Error) -> Error { Error::new(Kind::Io, Some(cause.into())) } #[cfg(feature = "runtime")] pub(crate) fn new_listen<E: Into<Cause>>(cause: E) -> Error { Error::new(Kind::Listen, Some(cause.into())) } pub(crate) fn new_accept<E: Into<Cause>>(cause: E) -> Error { Error::new(Kind::Accept, Some(cause.into())) } pub(crate) fn new_connect<E: Into<Cause>>(cause: E) -> Error { Error::new(Kind::Connect, Some(cause.into())) } pub(crate) fn new_closed() -> Error { Error::new(Kind::Closed, None) } pub(crate) fn new_body<E: Into<Cause>>(cause: E) -> Error { Error::new(Kind::Body, Some(cause.into())) } pub(crate) fn new_body_write<E: Into<Cause>>(cause: E) -> Error { Error::new(Kind::BodyWrite, Some(cause.into())) } pub(crate) fn new_user_unsupported_version() -> Error { Error::new(Kind::UnsupportedVersion, None) } pub(crate) fn new_user_unsupported_request_method() -> Error { Error::new(Kind::UnsupportedRequestMethod, None) } pub(crate) fn new_user_unsupported_status_code() -> Error { Error::new(Kind::UnsupportedStatusCode, None) } pub(crate) fn new_user_absolute_uri_required() -> Error { Error::new(Kind::AbsoluteUriRequired, None) } pub(crate) fn new_user_no_upgrade() -> Error { Error::new(Kind::NoUpgrade, None) } pub(crate) fn new_user_manual_upgrade() -> Error { Error::new(Kind::ManualUpgrade, None) } pub(crate) fn new_user_new_service<E: Into<Cause>>(cause: E) -> Error { Error::new(Kind::NewService, Some(cause.into())) } pub(crate) fn new_user_service<E: Into<Cause>>(cause: E) -> Error { Error::new(Kind::Service, Some(cause.into())) } pub(crate) fn new_user_body<E: Into<Cause>>(cause: E) -> Error { Error::new(Kind::BodyUser, Some(cause.into())) } pub(crate) fn new_shutdown(cause: io::Error) -> Error { Error::new(Kind::Shutdown, Some(Box::new(cause))) } pub(crate) fn new_execute<E: Into<Cause>>(cause: E) -> Error { Error::new(Kind::Execute, Some(cause.into())) } pub(crate) fn new_h2(cause: ::h2::Error) -> Error { Error::new(Kind::Http2, Some(Box::new(cause))) } } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut f = f.debug_struct("Error"); f.field("kind", &self.inner.kind); if let Some(ref cause) = self.inner.cause { f.field("cause", cause); } f.finish() } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(ref cause) = self.inner.cause { write!(f, "{}: {}", self.description(), cause) } else { f.write_str(self.description()) } } } impl StdError for Error { fn description(&self) -> &str { match self.inner.kind { Kind::Parse(Parse::Method) => "invalid Method specified", Kind::Parse(Parse::Version) => "invalid HTTP version specified", Kind::Parse(Parse::VersionH2) => "invalid HTTP version specified (Http2)", Kind::Parse(Parse::Uri) => "invalid URI", Kind::Parse(Parse::Header) => "invalid Header provided", Kind::Parse(Parse::TooLarge) => "message head is too large", Kind::Parse(Parse::Status) => "invalid Status provided", Kind::Incomplete => "parsed HTTP message from remote is incomplete", Kind::MismatchedResponse => "response received without matching request", Kind::Closed => "connection closed", Kind::Connect => "an error occurred trying to connect", Kind::Canceled => "an operation was canceled internally before starting", #[cfg(feature = "runtime")] Kind::Listen => "error creating server listener", Kind::Accept => "error accepting connection", Kind::NewService => "calling user's new_service failed", Kind::Service => "error from user's server service", Kind::Body => "error reading a body from connection", Kind::BodyWrite => "error writing a body to connection", Kind::BodyUser => "error from user's Payload stream", Kind::Shutdown => "error shutting down connection", Kind::Http2 => "http2 general error", Kind::UnsupportedVersion => "request has unsupported HTTP version", Kind::UnsupportedRequestMethod => "request has unsupported HTTP method", Kind::UnsupportedStatusCode => "response has 1xx status code, not supported by server", Kind::AbsoluteUriRequired => "client requires absolute-form URIs", Kind::NoUpgrade => "no upgrade available", Kind::ManualUpgrade => "upgrade expected but low level API in use", Kind::Execute => "executor failed to spawn task", Kind::Io => "an IO error occurred", } } fn cause(&self) -> Option<&StdError> { self .inner .cause .as_ref() .map(|cause| &**cause as &StdError) } } #[doc(hidden)] impl From<Parse> for Error { fn from(err: Parse) -> Error { Error::new(Kind::Parse(err), None) } } impl From<httparse::Error> for Parse { fn from(err: httparse::Error) -> Parse { match err { httparse::Error::HeaderName | httparse::Error::HeaderValue | httparse::Error::NewLine | httparse::Error::Token => Parse::Header, httparse::Error::Status => Parse::Status, httparse::Error::TooManyHeaders => Parse::TooLarge, httparse::Error::Version => Parse::Version, } } } impl From<http::method::InvalidMethod> for Parse { fn from(_: http::method::InvalidMethod) -> Parse { Parse::Method } } impl From<http::status::InvalidStatusCode> for Parse { fn from(_: http::status::InvalidStatusCode) -> Parse { Parse::Status } } impl From<http::uri::InvalidUri> for Parse { fn from(_: http::uri::InvalidUri) -> Parse { Parse::Uri } } impl From<http::uri::InvalidUriBytes> for Parse { fn from(_: http::uri::InvalidUriBytes) -> Parse { Parse::Uri } } impl From<http::uri::InvalidUriParts> for Parse { fn from(_: http::uri::InvalidUriParts) -> Parse { Parse::Uri } } #[doc(hidden)] trait AssertSendSync: Send + Sync + 'static {} #[doc(hidden)] impl AssertSendSync for Error {} #[cfg(test)] mod tests { }
#![allow(dead_code)] // extern crate num_cpus; extern crate crossbeam_channel; extern crate crossbeam_utils; extern crate image; extern crate sourcerenderer_bsp; extern crate sourcerenderer_core; extern crate sourcerenderer_mdl; extern crate sourcerenderer_vmt; extern crate sourcerenderer_vpk; extern crate sourcerenderer_vtf; extern crate sourcerenderer_vtx; extern crate sourcerenderer_vvd; #[macro_use] extern crate legion; extern crate bitset_core; extern crate bitvec; extern crate gltf; extern crate instant; extern crate rand; extern crate rayon; extern crate regex; extern crate smallvec; pub use camera::{ ActiveCamera, Camera, }; pub use transform::{ Parent, Transform, }; #[cfg(feature = "threading")] pub use self::engine::Engine; pub use self::game::{ DeltaTime, Tick, TickDelta, TickDuration, TickRate, }; #[cfg(feature = "threading")] mod engine; mod asset; mod camera; pub mod fps_camera; mod math; mod spinning_cube; pub mod transform; mod game; mod game_internal; mod input; mod physics; pub mod renderer; mod ui;
pub use crate::ma::dao::*; pub use crate::ma::data::{*}; pub use crate::ma::data_btc::{*}; pub use crate::ma::data_eee::{*}; pub use crate::ma::data_eth::{*}; pub use crate::ma::db::*; pub use crate::ma::detail::{*}; pub use crate::ma::detail_btc::{*}; pub use crate::ma::detail_eee::{EeeTokenType, MEeeChainTokenShared, MEeeChainTokenAuth, MEeeChainTokenDefault}; pub use crate::ma::detail_eth::{*}; pub use crate::ma::mnemonic::MMnemonic; pub use crate::ma::setting::*; mod mnemonic; mod detail; mod detail_eth; mod detail_eee; mod detail_btc; mod data; mod data_eth; mod data_eee; mod data_btc; mod setting; mod dao; mod db;
#[doc = "Reader of register BOOT4_PRGR"] pub type R = crate::R<u32, super::BOOT4_PRGR>; #[doc = "Writer for register BOOT4_PRGR"] pub type W = crate::W<u32, super::BOOT4_PRGR>; #[doc = "Register BOOT4_PRGR `reset()`'s with value 0"] impl crate::ResetValue for super::BOOT4_PRGR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `BOOT_CM4_ADD1`"] pub type BOOT_CM4_ADD1_R = crate::R<u16, u16>; #[doc = "Write proxy for field `BOOT_CM4_ADD1`"] pub struct BOOT_CM4_ADD1_W<'a> { w: &'a mut W, } impl<'a> BOOT_CM4_ADD1_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0xffff << 16)) | (((value as u32) & 0xffff) << 16); self.w } } #[doc = "Reader of field `BOOT_CM4_ADD0`"] pub type BOOT_CM4_ADD0_R = crate::R<u16, u16>; #[doc = "Write proxy for field `BOOT_CM4_ADD0`"] pub struct BOOT_CM4_ADD0_W<'a> { w: &'a mut W, } impl<'a> BOOT_CM4_ADD0_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } impl R { #[doc = "Bits 16:31 - Arm Cortex-M4 boot address 1 configuration"] #[inline(always)] pub fn boot_cm4_add1(&self) -> BOOT_CM4_ADD1_R { BOOT_CM4_ADD1_R::new(((self.bits >> 16) & 0xffff) as u16) } #[doc = "Bits 0:15 - Arm Cortex-M4 boot address 0 configuration"] #[inline(always)] pub fn boot_cm4_add0(&self) -> BOOT_CM4_ADD0_R { BOOT_CM4_ADD0_R::new((self.bits & 0xffff) as u16) } } impl W { #[doc = "Bits 16:31 - Arm Cortex-M4 boot address 1 configuration"] #[inline(always)] pub fn boot_cm4_add1(&mut self) -> BOOT_CM4_ADD1_W { BOOT_CM4_ADD1_W { w: self } } #[doc = "Bits 0:15 - Arm Cortex-M4 boot address 0 configuration"] #[inline(always)] pub fn boot_cm4_add0(&mut self) -> BOOT_CM4_ADD0_W { BOOT_CM4_ADD0_W { w: self } } }
use crate::semantic; use serde_derive::{Deserialize, Serialize}; use std::str; use strum_macros::{Display, EnumIter}; // TODO: not compatible yet pub type Tips = u16; pub type Score = u16; pub type MoveNo = u16; const CONSOLE: yew::services::ConsoleService = yew::services::ConsoleService {}; #[derive(Deserialize, Clone, PartialEq, Debug)] pub enum Special { // TODO: rename to NPC Assassin, Neutral, } #[derive(Deserialize, Clone, PartialEq, Debug)] #[serde(untagged)] pub enum CardTeam { // TODO: rename to Owner Special(Special), Team(Team), } // TODO: use String instead and add semantic color #[derive(Deserialize, Serialize, EnumIter, PartialEq, Display, Debug, Clone, Copy)] pub enum Team { Red, Blue, Green, Purple, Orange, Teal, Pink, Brown, } impl Default for Team { fn default() -> Self { Team::Red } } impl Into<crate::semantic::Color> for Team { fn into(self) -> semantic::Color { // TODO: Serialize String into semantic::Color match self { Team::Blue => semantic::Color::Blue, Team::Red => semantic::Color::Red, Team::Green => semantic::Color::Green, Team::Purple => semantic::Color::Purple, Team::Orange => semantic::Color::Orange, Team::Teal => semantic::Color::Teal, Team::Brown => semantic::Color::Brown, Team::Pink => semantic::Color::Pink, } } } impl Into<crate::semantic::Color> for &Team { fn into(self) -> semantic::Color { (*self).into() } } #[derive(Deserialize, Clone, PartialEq, Debug)] #[serde(rename_all = "camelCase")] pub struct Word { word: String, owned_by: Option<CardTeam>, revealed: bool, } #[derive(EnumIter, Serialize, Deserialize, Display, Clone, Copy, PartialEq, Debug)] pub enum Role { Spy, Spymaster, } impl Default for Role { fn default() -> Self { Role::Spymaster } } #[derive(Deserialize, PartialEq, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct Game { team_order: Vec<Team>, active_role: Role, words: Vec<Word>, remaining_words: Vec<(Team, Score)>, latest_move: Option<MoveEntry>, #[serde(deserialize_with = "to_latest_tip")] latest_tip: Option<(String, Tips)>, } use serde::de::Error; fn to_latest_tip<'de, D>(deserializer: D) -> Result<Option<(String, Tips)>, D::Error> where D: serde::Deserializer<'de>, { let latest_move: Option<LatestTip> = serde::Deserialize::deserialize(deserializer)?; match latest_move { Some(LatestTip { r#move: Move::Tip(word, tips), }) => Ok(Some((word, tips))), None => Ok(None), _ => Err(<D::Error as Error>::invalid_type( serde::de::Unexpected::TupleVariant, &"expected Tip", )), } } impl AsRef<[Word]> for Game { fn as_ref(&self) -> &[Word] { self.words.as_ref() } } impl Game { pub fn current_players(&self) -> (Team, Role) { (self.team_order[0], self.active_role) } pub fn current_tip(&self) -> Option<(&str, Tips)> { self.latest_tip .as_ref() .map(|(s, tips)| (s.as_str(), *tips)) .filter(|_| self.active_role == Role::Spy) } pub fn score(&self, team: Team) -> Option<Score> { self.remaining_words .iter() .filter(|(score_team, _)| score_team == &team) .map(|(_, score)| *score) .next() } pub fn select(&self, text: &str) -> Move { Move::Select(text.to_string()) } pub fn post(&self, r#move: Move) -> MovePost { MovePost { r#move, no: self.latest_move.as_ref().map(|latest_move| latest_move.no + 1).or(Some(0)), // TODO move 0 to constant } } pub fn current_move(&self) -> Option<MoveNo> { self.latest_move.as_ref().map(|me| me.no) } // TODO: // apply_effects could easily fail with the response of POST /moves // maybe POST /moves should return list of all effects of moves between requesting and responding! pub fn apply_effects(&mut self, effects: Effects) { let current_no = self.current_move(); let apply = match &current_no { None if effects.no == 0 => true, // TODO move 0 to constant Some(no) if effects.no == no + 1 => true, Some(no) if effects.no <= *no => { // no problem for the client, but this might hint at a server problem CONSOLE.warn(&format!("ignoring old effect ({}>={})", no, effects.no)); false } _ => { // we have a problem CONSOLE.error(&format!( "ignoring old effect ({:?}<{})", &current_no, effects.no )); false // FIXME: return with Result::Err instead } }; if apply { self.latest_move = Some(MoveEntry { no: effects.no }); effects .effects .into_iter() .for_each(|effect| self.apply_effect(effect)); } } pub fn apply_effect(&mut self, effect: Effect) { match effect { Effect::TeamWon(_team) => (), // TODO Effect::TurnOf(team) => { self.team_order = vec![team]; self.active_role = Role::Spymaster; self.latest_tip = None; } Effect::TeamLost(_team) => (), // TODO Effect::TipSubmitted(s, num) => { self.active_role = Role::Spy; self.latest_tip = Some((s, num)); } Effect::Revealed(word, card_team) => { self.words.iter_mut().filter(|w| w.word == word).for_each(|w| { w.owned_by = Some(card_team.clone()); w.revealed = true; }); } Effect::RemainingWords(team, score) => { self.remaining_words .iter_mut() .filter(|(t, _)| t == &team) .for_each(|(_, ref mut s)| *s = score); } } } } impl Word { pub fn text(&self) -> &str { self.word.as_ref() } pub fn team(&self) -> Option<CardTeam> { self.owned_by.clone() } pub fn revealed(&self) -> bool { self.revealed } } #[derive(Serialize, Deserialize, Clone, PartialEq)] #[serde(tag = "tag", content = "contents")] pub enum Move { Tip(String, Tips), Select(String), Concede(Team), } #[derive(Deserialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct LatestTip { r#move: Move, } #[derive(Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MovePost { r#move: Move, no: Option<MoveNo>, } #[derive(Deserialize, PartialEq, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct MoveEntry { no: MoveNo, } #[derive(Deserialize, PartialEq)] #[serde(tag = "tag", content = "contents")] pub enum Effect { TeamWon(Team), TurnOf(Team), TeamLost(Team), TipSubmitted(String, Tips), Revealed(String, CardTeam), RemainingWords(Team, Score), } #[derive(Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct EffectsOnly(Vec<Effect>); impl EffectsOnly { pub fn with_move(self, r#move: &str) -> Effects { Effects { effects: self.0, no: r#move.parse().unwrap(), } } } #[derive(Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Effects { effects: Vec<Effect>, no: MoveNo, }
#[doc = "Reader of register AHB1RSTR"] pub type R = crate::R<u32, super::AHB1RSTR>; #[doc = "Writer for register AHB1RSTR"] pub type W = crate::W<u32, super::AHB1RSTR>; #[doc = "Register AHB1RSTR `reset()`'s with value 0"] impl crate::ResetValue for super::AHB1RSTR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "DMA1 block reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DMA1RST_A { #[doc = "1: Reset the selected module"] RESET = 1, } impl From<DMA1RST_A> for bool { #[inline(always)] fn from(variant: DMA1RST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `DMA1RST`"] pub type DMA1RST_R = crate::R<bool, DMA1RST_A>; impl DMA1RST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<bool, DMA1RST_A> { use crate::Variant::*; match self.bits { true => Val(DMA1RST_A::RESET), i => Res(i), } } #[doc = "Checks if the value of the field is `RESET`"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == DMA1RST_A::RESET } } #[doc = "Write proxy for field `DMA1RST`"] pub struct DMA1RST_W<'a> { w: &'a mut W, } impl<'a> DMA1RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DMA1RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(DMA1RST_A::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "DMA2 block reset"] pub type DMA2RST_A = DMA1RST_A; #[doc = "Reader of field `DMA2RST`"] pub type DMA2RST_R = crate::R<bool, DMA1RST_A>; #[doc = "Write proxy for field `DMA2RST`"] pub struct DMA2RST_W<'a> { w: &'a mut W, } impl<'a> DMA2RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DMA2RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(DMA1RST_A::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "ADC1&2 block reset"] pub type ADC12RST_A = DMA1RST_A; #[doc = "Reader of field `ADC12RST`"] pub type ADC12RST_R = crate::R<bool, DMA1RST_A>; #[doc = "Write proxy for field `ADC12RST`"] pub struct ADC12RST_W<'a> { w: &'a mut W, } impl<'a> ADC12RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADC12RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(DMA1RST_A::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "ETH1MAC block reset"] pub type ETH1MACRST_A = DMA1RST_A; #[doc = "Reader of field `ETH1MACRST`"] pub type ETH1MACRST_R = crate::R<bool, DMA1RST_A>; #[doc = "Write proxy for field `ETH1MACRST`"] pub struct ETH1MACRST_W<'a> { w: &'a mut W, } impl<'a> ETH1MACRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ETH1MACRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(DMA1RST_A::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "USB1OTG block reset"] pub type USB1OTGRST_A = DMA1RST_A; #[doc = "Reader of field `USB1OTGRST`"] pub type USB1OTGRST_R = crate::R<bool, DMA1RST_A>; #[doc = "Write proxy for field `USB1OTGRST`"] pub struct USB1OTGRST_W<'a> { w: &'a mut W, } impl<'a> USB1OTGRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USB1OTGRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(DMA1RST_A::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "USB2OTG block reset"] pub type USB2OTGRST_A = DMA1RST_A; #[doc = "Reader of field `USB2OTGRST`"] pub type USB2OTGRST_R = crate::R<bool, DMA1RST_A>; #[doc = "Write proxy for field `USB2OTGRST`"] pub struct USB2OTGRST_W<'a> { w: &'a mut W, } impl<'a> USB2OTGRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USB2OTGRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Reset the selected module"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(DMA1RST_A::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27); self.w } } impl R { #[doc = "Bit 0 - DMA1 block reset"] #[inline(always)] pub fn dma1rst(&self) -> DMA1RST_R { DMA1RST_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - DMA2 block reset"] #[inline(always)] pub fn dma2rst(&self) -> DMA2RST_R { DMA2RST_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 5 - ADC1&2 block reset"] #[inline(always)] pub fn adc12rst(&self) -> ADC12RST_R { ADC12RST_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 15 - ETH1MAC block reset"] #[inline(always)] pub fn eth1macrst(&self) -> ETH1MACRST_R { ETH1MACRST_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 25 - USB1OTG block reset"] #[inline(always)] pub fn usb1otgrst(&self) -> USB1OTGRST_R { USB1OTGRST_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 27 - USB2OTG block reset"] #[inline(always)] pub fn usb2otgrst(&self) -> USB2OTGRST_R { USB2OTGRST_R::new(((self.bits >> 27) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - DMA1 block reset"] #[inline(always)] pub fn dma1rst(&mut self) -> DMA1RST_W { DMA1RST_W { w: self } } #[doc = "Bit 1 - DMA2 block reset"] #[inline(always)] pub fn dma2rst(&mut self) -> DMA2RST_W { DMA2RST_W { w: self } } #[doc = "Bit 5 - ADC1&2 block reset"] #[inline(always)] pub fn adc12rst(&mut self) -> ADC12RST_W { ADC12RST_W { w: self } } #[doc = "Bit 15 - ETH1MAC block reset"] #[inline(always)] pub fn eth1macrst(&mut self) -> ETH1MACRST_W { ETH1MACRST_W { w: self } } #[doc = "Bit 25 - USB1OTG block reset"] #[inline(always)] pub fn usb1otgrst(&mut self) -> USB1OTGRST_W { USB1OTGRST_W { w: self } } #[doc = "Bit 27 - USB2OTG block reset"] #[inline(always)] pub fn usb2otgrst(&mut self) -> USB2OTGRST_W { USB2OTGRST_W { w: self } } }
//! Azul is a free, functional, immediate-mode GUI framework for rapid development //! of desktop applications written in Rust, supported by the Mozilla WebRender //! rendering engine, using a flexbox-based CSS / DOM model for layout and styling. //! //! # Concept //! //! Azul is largely based on the principle of immediate-mode GUI frameworks, which //! is that the entire UI (in Azuls case the DOM) is reconstructed and re-rendered //! on every frame (instead of having functions that mutate the UI state like //! `button.setText()`). This method of constructing UIs has a performance overhead //! over methods that retain the UI, therefore Azul only calls the [`Layout::layout()`] //! function when its absolutely necessary - inside of a callback, you can return //! whether it is necessary to redraw the screen or not (by returning //! [`Redraw`] or [`DontRedraw`], respectively). //! //! In difference to other immediate-mode frameworks, Azul does not immediately //! draw to the screen, but rather "draws" to a `Dom`. This has several advantages, //! such as making it possible to layout code at runtime, [loading a `Dom` from //! an XML file], recognizing state changes by diffing two frames, as well as being //! able to reparent DOMs into almost any configuration to make components reusable //! independent of the context they are in. //! //! # Development lifecycle //! //! A huge problem when working with GUI applications in Rust is managing the //! compile time. Having to recompile your entire code when you just want to //! shift an element a pixel to the right is not a good developer experience. //! Azul has three main methods of combating compile time: //! //! - The [XML] system, which allows you to load DOMs at runtime [from a file] //! - The [CSS] system, which allows you to [load and parse stylesheets] //! //! Due to Azuls stateless rendering architecutre, hot-reloading also preserves //! the current application state. Once you are done layouting your applications //! UI, you can [transpile the XML code to valid Rust source code] using [azulc], //! the Azul-XML-to-Rust compiler. //! //! Please note that the compiler isn't perfect - the XML system is very limited, //! and parsing XML has a certain performance overhead, since it's done on every frame. //! That is fine for debug builds, but the XML system should not be used in release mode. //! //! When you are done with designing the callbacks of your widget, you may want to //! package the widget up to autmatically react to certain events without having the //! user of your widget write any code to hook up the callbacks - for this purpose, //! Azul features a [two way data binding] system. //! //! # Custom drawing and embedding external applications //! //! Azul is mostly concerned with rendering text, images and rectangular boxes (divs). //! Any other content can be drawn by drawing to an OpenGL texture (using a //! [`GlTextureCallback`]) and handing the texture as an "image" to Azul. This is also how //! components like a video player or other OpenGL-based visualizations can exist //! outside of the core library and be "injected" into the UI. //! //! You can draw to an OpenGL texture and hand it to Azul in order to display it //! in the UI - the texture doesn't have to come from Azul itself, you can inject //! it from an external application. //! //! # Limitations //! //! There are a few limitations that should be noted: //! //! - There are no scrollbars yet. Creating scrollable frames can be done by //! [creating an `IFrameCallback`]. //! - Similarly, there is no clipping of overflowing content yet - clipping only //! works for `IFrameCallback`s. //! - There is no support for CSS animations of any kind yet //! - Changing dynamic variables will trigger an entire UI relayout and restyling //! //! # Hello world //! //! ```no_run //! extern crate azul; //! //! use azul::prelude::*; //! //! struct MyDataModel { } //! //! impl Layout for MyDataModel { //! fn layout(&self, _: LayoutInfo<Self>) -> Dom<Self> { //! Dom::label("Hello World") //! } //! } //! //! fn main() { //! let mut app = App::new(MyDataModel { }, AppConfig::default()).unwrap(); //! let window = app.create_window(WindowCreateOptions::default(), css::native()).unwrap(); //! app.run(window).unwrap(); //! } //! ``` //! //! Running this code should return a window similar to this: //! //! ![Opening a blank window](https://raw.githubusercontent.com/maps4print/azul/master/doc/azul_tutorial_empty_window.png) //! //! # Tutorials //! //! Explaining all concepts and examples is too much to be included in //! this API reference. Please refer to the [wiki](https://github.com/maps4print/azul/wiki) //! or use the links below to learn about how to use Azul. //! //! - [Getting Started](https://github.com/maps4print/azul/wiki/Getting-Started) //! - [A simple counter](https://github.com/maps4print/azul/wiki/A-simple-counter) //! - [Styling your app with CSS](https://github.com/maps4print/azul/wiki/Styling-your-application-with-CSS) //! - [SVG drawing](https://github.com/maps4print/azul/wiki/SVG-drawing) //! - [OpenGL drawing](https://github.com/maps4print/azul/wiki/OpenGL-drawing) //! - [Timers, timers, tasks and async IO](https://github.com/maps4print/azul/wiki/Timers,-timers,-tasks-and-async-IO) //! - [Two-way data binding](https://github.com/maps4print/azul/wiki/Two-way-data-binding) //! - [Unit testing](https://github.com/maps4print/azul/wiki/Unit-testing) //! //! [`Layout::layout()`]: ../azul/traits/trait.Layout.html //! [widgets]: ../azul/widgets/index.html //! [loading a `Dom` from an XML file]: ../azul/dom/struct.Dom.html#method.from_file //! [XML]: ../azul/xml/index.html //! [`Redraw`]: ../azul/callbacks/constant.Redraw.html //! [`DontRedraw`]: ../azul/callbacks/constant.DontRedraw.html //! [`GlTextureCallback`]: ../azul/callbacks/struct.GlTextureCallback.html //! [creating an `IFrameCallback`]: ../azul/dom/struct.Dom.html#method.iframe //! [from a file]: ../azul/dom/struct.Dom.html#method.from_file //! [CSS]: ../azul/css/index.html //! [load and parse stylesheets]: ../azul/css/fn.from_str.html //! [transpile the XML code to valid Rust source code]: https://github.com/maps4print/azul/wiki/XML-to-Rust-compilation //! [azulc]: https://crates.io/crates/azulc //! [two way data binding]: https://github.com/maps4print/azul/wiki/Two-way-data-binding #![doc( html_logo_url = "https://raw.githubusercontent.com/maps4print/azul/master/assets/images/azul_logo_full_min.svg.png", html_favicon_url = "https://raw.githubusercontent.com/maps4print/azul/master/assets/images/favicon.ico", )] #![allow(dead_code)] #![deny(unused_must_use)] #![deny(unreachable_patterns)] #![deny(missing_copy_implementations)] #![deny(clippy::all)] #[macro_use(warn, error, lazy_static)] #[cfg_attr(feature = "svg", macro_use(implement_vertex, uniform))] pub extern crate azul_dependencies; #[cfg(feature = "serde_serialization")] #[cfg_attr(feature = "serde_serialization", macro_use)] extern crate serde; #[cfg(feature = "serde_serialization")] #[cfg_attr(feature = "serde_serialization", macro_use)] extern crate serde_derive; pub(crate) use azul_dependencies::glium as glium; pub(crate) use azul_dependencies::gleam as gleam; pub(crate) use azul_dependencies::euclid; pub(crate) use azul_dependencies::webrender; pub(crate) use azul_dependencies::app_units; pub(crate) use azul_dependencies::unicode_normalization; pub(crate) use azul_dependencies::tinyfiledialogs; pub(crate) use azul_dependencies::clipboard2; pub(crate) use azul_dependencies::font_loader; pub(crate) use azul_dependencies::xmlparser; pub(crate) use azul_dependencies::harfbuzz_sys; #[cfg(feature = "logging")] pub(crate) use azul_dependencies::log; #[cfg(feature = "svg")] pub(crate) use azul_dependencies::stb_truetype; #[cfg(feature = "logging")] pub(crate) use azul_dependencies::fern; #[cfg(feature = "logging")] pub(crate) use azul_dependencies::backtrace; #[cfg(feature = "image_loading")] pub(crate) use azul_dependencies::image; #[cfg(feature = "svg")] pub(crate) use azul_dependencies::lyon; #[cfg(feature = "svg_parsing")] pub(crate) use azul_dependencies::usvg; #[cfg(feature = "faster-hashing")] pub(crate) use azul_dependencies::twox_hash; #[cfg(feature = "css_parser")] extern crate azul_css; extern crate azul_native_style; extern crate azul_css_parser; // Crate-internal macros #[macro_use] mod macros; /// Manages application state (`App` / `AppState` / `AppResources`), wrapping resources and app state pub mod app; /// Async IO helpers / (`Task` / `Timer` / `Thread`) pub mod async; /// Type definitions for various types of callbacks, as well as focus and scroll handling pub mod callbacks; /// CSS type definitions / CSS parsing functions #[cfg(any(feature = "css_parser", feature = "native_style"))] pub mod css; /// Bindings to the native file-chooser, color picker, etc. dialogs pub mod dialogs; /// DOM / HTML node handling pub mod dom; /// Re-exports of errors pub mod error; /// Handles text layout (modularized, can be used as a standalone module) pub mod text_layout; /// Main `Layout` trait definition + convenience traits for `Arc<Mutex<T>>` pub mod traits; /// Container for default widgets (`TextInput` / `Button` / `Label`, `TableView`, ...) pub mod widgets; /// Window state handling and window-related information pub mod window; /// XML-based DOM serialization and XML-to-Rust compiler implementation pub mod xml; /// UI Description & display list handling (webrender) mod ui_description; /// HarfBuzz text shaping utilities mod text_shaping; /// Converts the UI description (the styled HTML nodes) /// to an actual display list (+ layout) mod display_list; /// Slab allocator for nodes, based on IDs (replaces kuchiki + markup5ever) mod id_tree; /// State handling for user interfaces mod ui_state; /// The compositor takes all textures (user-defined + the UI texture(s)) and draws them on /// top of each other mod compositor; /// Default logger, can be turned off with `feature = "logging"` #[cfg(feature = "logging")] mod logging; /// Flexbox-based UI solver mod ui_solver; /// DOM styling module mod style; /// DOM diffing mod diff; /// Checks that two-way bound values are on the stack mod stack_checked_pointer; /// Window state handling and diffing mod window_state; /// ImageId / FontId handling and caching mod app_resources; /// Font & image resource handling, lookup and caching pub mod resources { // re-export everything *except* the AppResources (which are exported under the "app" module) pub use app_resources::{ FontId, ImageId, LoadedFont, RawImage, FontReloadError, FontSource, ImageReloadError, ImageSource, RawImageFormat, CssFontId, CssImageId, TextCache, TextId, }; } // Faster implementation of a HashMap (optional, disabled by default, turn on with --feature="faster-hashing") #[cfg(feature = "faster-hashing")] type FastHashMap<T, U> = ::std::collections::HashMap<T, U, ::std::hash::BuildHasherDefault<::twox_hash::XxHash>>; #[cfg(feature = "faster-hashing")] type FastHashSet<T> = ::std::collections::HashSet<T, ::std::hash::BuildHasherDefault<::twox_hash::XxHash>>; #[cfg(not(feature = "faster-hashing"))] type FastHashMap<T, U> = ::std::collections::HashMap<T, U>; #[cfg(not(feature = "faster-hashing"))] type FastHashSet<T> = ::std::collections::HashSet<T>; /// Quick exports of common types pub mod prelude { #[cfg(feature = "css_parser")] pub use azul_css::*; pub use app::{App, AppConfig, AppState, AppResources}; pub use async::{Task, TerminateTimer, TimerId, Timer, DropCheck}; pub use resources::{ RawImageFormat, ImageId, FontId, FontSource, ImageSource, TextCache, TextId, }; pub use callbacks::{ Callback, TimerCallback, IFrameCallback, GlTextureCallback, UpdateScreen, Redraw, DontRedraw, CallbackInfo, FocusTarget, LayoutInfo, HidpiAdjustedBounds, Texture, }; pub use dom::{ Dom, DomHash, NodeType, NodeData, On, DomString, TabIndex, EventFilter, HoverEventFilter, FocusEventFilter, NotEventFilter, WindowEventFilter, }; pub use traits::{Layout, Modify}; pub use window::{ MonitorIter, Window, WindowCreateOptions, WindowMonitorTarget, RendererType, ReadOnlyWindow }; pub use window_state::{WindowState, KeyboardState, MouseState, DebugState, keymap, AcceleratorKey}; pub use glium::glutin::{ dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}, VirtualKeyCode, ScanCode, Icon, }; pub use stack_checked_pointer::StackCheckedPointer; pub use text_layout::{TextLayoutOptions, GlyphInstance}; pub use xml::{XmlComponent, XmlComponentMap}; #[cfg(any(feature = "css_parser", feature = "native_style"))] pub use css; #[cfg(feature = "logging")] pub use log::LevelFilter; }
pub mod vm; extern crate either; fn main() { println!("Hello, world!"); }
// does not test any rustfixable lints #![warn(clippy::mixed_case_hex_literals)] #![warn(clippy::zero_prefixed_literal)] #![warn(clippy::unseparated_literal_suffix)] #![warn(clippy::separated_literal_suffix)] #![allow(dead_code)] fn main() { let ok1 = 0xABCD; let ok3 = 0xab_cd; let ok4 = 0xab_cd_i32; let ok5 = 0xAB_CD_u32; let ok5 = 0xAB_CD_isize; let fail1 = 0xabCD; let fail2 = 0xabCD_u32; let fail2 = 0xabCD_isize; let fail_multi_zero = 000_123usize; let ok9 = 0; let ok10 = 0_i64; let fail8 = 0123; let ok11 = 0o123; let ok12 = 0b10_1010; let ok13 = 0xab_abcd; let ok14 = 0xBAFE_BAFE; let ok15 = 0xab_cabc_abca_bcab_cabc; let ok16 = 0xFE_BAFE_ABAB_ABCD; let ok17 = 0x123_4567_8901_usize; let ok18 = 0xF; let fail19 = 12_3456_21; let fail22 = 3__4___23; let fail23 = 3__16___23; let fail24 = 0xAB_ABC_AB; let fail25 = 0b01_100_101; let ok26 = 0x6_A0_BF; let ok27 = 0b1_0010_0101; }
#[derive(Debug)] pub struct RawVec<T> { buf: Vec<T>, } impl<T> RawVec<T> { #[inline] pub fn with_capacity(cap: usize) -> Self { RawVec { buf: Vec::with_capacity(cap), } } #[inline] pub fn ptr(&self) -> *mut T { let ptr = self.buf.as_ptr(); ptr as *mut T } #[inline] pub fn cap(&self) -> usize { self.buf.capacity() } }
#[doc = "Reader of register M1FAR"] pub type R = crate::R<u32, super::M1FAR>; #[doc = "Writer for register M1FAR"] pub type W = crate::W<u32, super::M1FAR>; #[doc = "Register M1FAR `reset()`'s with value 0"] impl crate::ResetValue for super::M1FAR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `ECCSEIE`"] pub type ECCSEIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ECCSEIE`"] pub struct ECCSEIE_W<'a> { w: &'a mut W, } impl<'a> ECCSEIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `ECCDEIE`"] pub type ECCDEIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ECCDEIE`"] pub struct ECCDEIE_W<'a> { w: &'a mut W, } impl<'a> ECCDEIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `ECCDEBWIE`"] pub type ECCDEBWIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ECCDEBWIE`"] pub struct ECCDEBWIE_W<'a> { w: &'a mut W, } impl<'a> ECCDEBWIE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `ECCELEN`"] pub type ECCELEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ECCELEN`"] pub struct ECCELEN_W<'a> { w: &'a mut W, } impl<'a> ECCELEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } impl R { #[doc = "Bit 2 - ECC single error interrupt enable"] #[inline(always)] pub fn eccseie(&self) -> ECCSEIE_R { ECCSEIE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - ECC double error interrupt enable"] #[inline(always)] pub fn eccdeie(&self) -> ECCDEIE_R { ECCDEIE_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - ECC double error on byte write (BW) interrupt enable"] #[inline(always)] pub fn eccdebwie(&self) -> ECCDEBWIE_R { ECCDEBWIE_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - ECC error latching enable"] #[inline(always)] pub fn eccelen(&self) -> ECCELEN_R { ECCELEN_R::new(((self.bits >> 5) & 0x01) != 0) } } impl W { #[doc = "Bit 2 - ECC single error interrupt enable"] #[inline(always)] pub fn eccseie(&mut self) -> ECCSEIE_W { ECCSEIE_W { w: self } } #[doc = "Bit 3 - ECC double error interrupt enable"] #[inline(always)] pub fn eccdeie(&mut self) -> ECCDEIE_W { ECCDEIE_W { w: self } } #[doc = "Bit 4 - ECC double error on byte write (BW) interrupt enable"] #[inline(always)] pub fn eccdebwie(&mut self) -> ECCDEBWIE_W { ECCDEBWIE_W { w: self } } #[doc = "Bit 5 - ECC error latching enable"] #[inline(always)] pub fn eccelen(&mut self) -> ECCELEN_W { ECCELEN_W { w: self } } }
use pest::iterators::Pair; use std::borrow::Cow; use std::fmt; #[derive(Parser)] #[grammar = "nono.pest"] pub struct NonoParser; #[derive(Clone, Debug, Eq, PartialEq)] pub struct Clue(pub Vec<usize>); impl<'a> From<Pair<'a, Rule>> for Clue { fn from(pair: Pair<Rule>) -> Self { assert_eq!(pair.as_rule(), Rule::clue); Clue( pair.into_inner() .map(|n| usize::from_str_radix(n.as_str(), 10).unwrap()) .collect::<Vec<_>>(), ) } } impl fmt::Display for Clue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some((first, rest)) = self.0.split_first() { write!(f, "{}", first)?; for number in rest { write!(f, ",{}", number)?; } } Ok(()) } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct ClueList(pub Vec<Clue>); impl<'a> From<Pair<'a, Rule>> for ClueList { fn from(pair: Pair<Rule>) -> Self { assert_eq!(pair.as_rule(), Rule::clue_list); ClueList(pair.into_inner().map(Clue::from).collect()) } } impl fmt::Display for ClueList { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let (first, rest) = self.0.split_first().unwrap(); write!(f, "{}", first)?; for number in rest { write!(f, ";{}", number)?; } Ok(()) } } #[derive(Debug, Eq, PartialEq)] pub enum Cell { Filled, Crossed, Undecided, Impossible, } impl<'a> From<Pair<'a, Rule>> for Cell { fn from(pair: Pair<Rule>) -> Self { assert_eq!(pair.as_rule(), Rule::cell); match pair.into_inner().next().unwrap().as_rule() { Rule::filled => Cell::Filled, Rule::crossed => Cell::Crossed, Rule::undecided => Cell::Undecided, Rule::impossible => Cell::Impossible, _ => unreachable!(), } } } impl fmt::Display for Cell { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Cell::Filled => write!(f, "#"), Cell::Crossed => write!(f, "x"), Cell::Undecided => write!(f, "."), Cell::Impossible => write!(f, "!"), } } } #[derive(Debug, Eq, PartialEq)] pub struct GridLine(pub Vec<Cell>); impl<'a> From<Pair<'a, Rule>> for GridLine { fn from(pair: Pair<Rule>) -> Self { assert_eq!(pair.as_rule(), Rule::grid_line); GridLine(pair.into_inner().map(Cell::from).collect()) } } impl fmt::Display for GridLine { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for cell in &self.0 { write!(f, "{}", cell)?; } Ok(()) } } #[derive(Debug, Eq, PartialEq)] pub struct Grid(pub Vec<GridLine>); impl<'a> From<Pair<'a, Rule>> for Grid { fn from(pair: Pair<Rule>) -> Self { assert_eq!(pair.as_rule(), Rule::grid); Grid(pair.into_inner().map(GridLine::from).collect()) } } impl fmt::Display for Grid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let (first, rest) = self.0.split_first().unwrap(); write!(f, "{}", first)?; for grid_line in rest { write!(f, ";{}", grid_line)?; } Ok(()) } } #[derive(Debug, Eq, PartialEq)] pub struct Puzzle<'a> { pub vert_clues: Cow<'a, ClueList>, pub horz_clues: Cow<'a, ClueList>, pub grid: Option<Grid>, } impl<'a> From<Pair<'a, Rule>> for Puzzle<'a> { fn from(pair: Pair<Rule>) -> Self { assert_eq!(pair.as_rule(), Rule::puzzle); let mut pairs = pair.into_inner(); let vert_clues = Cow::Owned(pairs.next().map(ClueList::from).unwrap()); let horz_clues = Cow::Owned(pairs.next().map(ClueList::from).unwrap()); let grid = pairs.next().map(Grid::from); Puzzle { vert_clues, horz_clues, grid, } } } impl<'a> fmt::Display for Puzzle<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(grid) = &self.grid { write!(f, "[{}|{}|{}]", self.vert_clues, self.horz_clues, grid) } else { write!(f, "[{}|{}]", self.vert_clues, self.horz_clues) } } } #[cfg(test)] mod tests { use super::*; use pest::Parser; fn test_roundtrip<T, F>(f: F, orig: T) where F: Fn(&str) -> Vec<T>, T: fmt::Debug + fmt::Display + Eq, { let items = f(&format!("{}", &orig)); assert_eq!(items.as_slice(), [orig]); } #[test] fn clue() { fn deser(s: &str) -> Vec<Clue> { NonoParser::parse(Rule::clue, s) .unwrap_or_else(|e| panic!("{}", e)) .map(Clue::from) .collect() } test_roundtrip(deser, Clue(vec![])); test_roundtrip(deser, Clue(vec![10])); test_roundtrip(deser, Clue(vec![1, 3, 5])); } #[test] fn clue_list() { fn deser(s: &str) -> Vec<ClueList> { NonoParser::parse(Rule::clue_list, s) .unwrap_or_else(|e| panic!("{}", e)) .map(ClueList::from) .collect() } test_roundtrip(deser, ClueList(vec![Clue(vec![1])])); test_roundtrip(deser, ClueList(vec![Clue(vec![1]), Clue(vec![2])])); test_roundtrip(deser, ClueList(vec![Clue(vec![]), Clue(vec![2])])); test_roundtrip(deser, ClueList(vec![Clue(vec![1]), Clue(vec![])])); test_roundtrip( deser, ClueList(vec![Clue(vec![1]), Clue(vec![2]), Clue(vec![3])]), ); test_roundtrip( deser, ClueList(vec![Clue(vec![1]), Clue(vec![]), Clue(vec![3])]), ); } #[test] fn cell() { fn deser(s: &str) -> Vec<Cell> { NonoParser::parse(Rule::cell, s) .unwrap_or_else(|e| panic!("{}", e)) .map(Cell::from) .collect() } test_roundtrip(deser, Cell::Filled); test_roundtrip(deser, Cell::Crossed); test_roundtrip(deser, Cell::Undecided); test_roundtrip(deser, Cell::Impossible); } #[test] fn grid_line() { fn deser(s: &str) -> Vec<GridLine> { NonoParser::parse(Rule::grid_line, s) .unwrap_or_else(|e| panic!("{}", e)) .map(GridLine::from) .collect() } test_roundtrip(deser, GridLine(vec![Cell::Undecided])); test_roundtrip(deser, GridLine(vec![Cell::Filled, Cell::Crossed])); } #[test] fn grid() { fn deser(s: &str) -> Vec<Grid> { NonoParser::parse(Rule::grid, s) .unwrap_or_else(|e| panic!("{}", e)) .map(Grid::from) .collect() } test_roundtrip(deser, Grid(vec![GridLine(vec![Cell::Undecided])])); test_roundtrip( deser, Grid(vec![ GridLine(vec![Cell::Undecided, Cell::Filled]), GridLine(vec![Cell::Crossed, Cell::Impossible]), ]), ); } #[test] fn puzzle() { fn test_roundtrip(orig: Puzzle) { let s = format!("{}", &orig); let items: Vec<_> = NonoParser::parse(Rule::puzzle, &s) .unwrap_or_else(|e| panic!("{}", e)) .map(Puzzle::from) .collect(); assert_eq!(items.as_slice(), [orig]); } test_roundtrip(Puzzle { vert_clues: Cow::Owned(ClueList(vec![Clue(vec![]), Clue(vec![1])])), horz_clues: Cow::Owned(ClueList(vec![Clue(vec![1]), Clue(vec![])])), grid: None, }); test_roundtrip(Puzzle { vert_clues: Cow::Owned(ClueList(vec![Clue(vec![]), Clue(vec![1])])), horz_clues: Cow::Owned(ClueList(vec![Clue(vec![1]), Clue(vec![])])), grid: Some(Grid(vec![ GridLine(vec![Cell::Undecided, Cell::Filled]), GridLine(vec![Cell::Crossed, Cell::Impossible]), ])), }); } }
use anyhow::{Context, Result}; use std::{env, fs::read}; use synacor::program::Program; fn main() -> Result<()> { env_logger::init(); let mut args = env::args(); args.next(); let input_file = args.next().context("expected argument")?; let bytes = read(input_file).context("failed to open file")?; let mut program = Program::new(bytes); program.execute(); Ok(()) }
use crate::pdf::{Dict, Name, Object}; use std::collections::LinkedList; use std::rc::Rc; pub mod path; pub use path::Path; pub mod text; pub use text::{Font, Text}; pub mod context; use context::GraphicParameters; pub use context::{Color, Graphic, GraphicsContextType, Point, Rect}; #[derive(Debug)] pub struct GraphicContext { // Mutable state current: Rc<GraphicParameters>, stack: LinkedList<GraphicParameters>, // Output stream stream: Vec<u8>, // Resource Dict resources: Rc<Dict>, fonts: Rc<Dict>, external_resources: Vec<Rc<dyn Object>>, } impl GraphicContext { pub fn new() -> Self { Self { current: Rc::new(GraphicParameters::default()), stack: LinkedList::new(), stream: vec![], resources: Dict::from_vec(vec![( "ProcSet", Rc::new(vec![Name::new("PDF"), Name::new("Text")]), )]), fonts: Dict::new(), external_resources: vec![], } } fn with_type(t: GraphicsContextType) -> Self { Self { current: Rc::new(GraphicParameters::with_type(t)), stack: LinkedList::new(), stream: vec![], resources: Dict::from_vec(vec![( "ProcSet", Rc::new(vec![Name::new("PDF"), Name::new("Text")]), )]), fonts: Dict::new(), external_resources: vec![], } } pub fn render(&mut self, object: Rc<impl Graphic>) { // Check Colors, and update as needed GraphicParameters::update(self, object.get_graphics_parameters()); // Render object object.render(self); } fn command(&mut self, params: &mut [Parameter], operator: &str) { for p in params { self.stream.push(' ' as u8); self.stream.append(&mut p.raw); } self.stream.push(' ' as u8); self.stream.extend(operator.bytes()); } fn add_resource(&mut self, obj: Rc<dyn Object>) { self.external_resources.push(obj); } fn add_font(&mut self, f: Rc<text::Font>) { // self.fonts.add_entry(f.name(), f.object()); // self.external_resources.push(f.object()); } pub fn compile( self, // write: &mut crate::pdf::PDFWrite, ) -> ( Vec<Rc<crate::pdf::ObjRef<crate::pdf::types::Stream>>>, Rc<crate::pdf::Dict>, ) { if !self.fonts.is_empty() { self.resources.add_entry("Font", self.fonts); } let streams = vec![crate::pdf::ObjRef::new( 0, crate::pdf::types::Stream::new(crate::pdf::Dict::new(), self.stream), )]; // for obj in streams.iter().cloned() { // write.add_object(obj); // } // for obj in self.external_resources { // write.add_object(obj); // } (streams, self.resources) } } /// A raw, compiled representation of a set of parameters /// /// Should never have trailing whitespace pub struct Parameter { raw: Vec<u8>, } impl From<&str> for Parameter { fn from(o: &str) -> Self { Self { raw: format!("({})", o).bytes().collect(), } } } impl From<&String> for Parameter { fn from(o: &String) -> Self { Self { raw: format!("({})", o).bytes().collect(), } } } impl From<String> for Parameter { fn from(o: String) -> Self { Self { raw: format!("({})", o).bytes().collect(), } } } impl From<usize> for Parameter { fn from(o: usize) -> Self { Self { raw: o.to_string().bytes().collect(), } } } impl From<f64> for Parameter { fn from(o: f64) -> Self { Self { raw: o.to_string().bytes().collect(), } } } impl From<&f64> for Parameter { fn from(o: &f64) -> Self { Self { raw: o.to_string().bytes().collect(), } } } impl From<Rc<Name>> for Parameter { fn from(r: Rc<Name>) -> Self { Self { raw: r.to_string().bytes().collect(), } } }
#[macro_use] extern crate lazy_static; extern crate nix; use nix::sys::wait::{waitpid, WaitPidFlag, WaitStatus}; use nix::unistd::{fork, ForkResult, Pid, chdir, execvp}; use std::collections::HashMap; use std::ffi::CString; use std::io::{self, Write}; use std::process::exit; lazy_static! { pub static ref BUILDIN_FUNCTIONS: HashMap<&'static str, fn(&Vec<&str>)> = [ ("cd", buildin_cd as fn(&Vec<&str>)), ("help", buildin_help as fn(&Vec<&str>)), ("exit", buildin_exit as fn(&Vec<&str>)) ].iter().cloned().collect(); } fn buildin_cd(args: &Vec<&str>) { if args.len() < 2 { println!("lsh: expected argument to \"cd\""); return; } match chdir(args[1]) { Ok(_) => println!("moved"), Err(_) => println!("move failed") } } fn buildin_help(_args: &Vec<&str>) { println!("esh v0.01"); BUILDIN_FUNCTIONS.iter().for_each(|(name, _)| { println!("- {}", name) }); } fn buildin_exit(_args: &Vec<&str>) { exit(0); } fn wait_loop(pid: Pid) -> Result<i32, String> { // pidのプロセスが終了するまでループ match waitpid(pid, Some(WaitPidFlag::WUNTRACED)) { Ok(WaitStatus::Exited(_, status)) => Ok(status), Ok(WaitStatus::Signaled(_, _, _)) => Err("signaled".to_string()), _ => wait_loop(pid), } } fn esh_launch(args: &Vec<&str>) { let argsc: Vec<CString> = args.iter().map(|&arg|{ CString::new(arg).unwrap() }).collect(); if let Err(_) = execvp(&argsc[0], &argsc) { println!("execvp failed."); } } fn esh_execute(commands: Vec<Vec<&str>>) -> Result<i32, String> { let commands_index: usize = 0; let command: &Vec<&str> = &commands[commands_index]; match fork() { Ok(ForkResult::Parent {child, .. }) => { wait_loop(child) } Ok(ForkResult::Child) => { match BUILDIN_FUNCTIONS.get(command[0]) { Some(f) => f(command), None => esh_launch(command), } exit(1); } Err(_) => Err("fork failed".to_string()), } } fn esh_loop() { loop { print!("$ "); io::stdout().flush().unwrap(); let mut line = String::new(); let _ = io::stdin().read_line(&mut line); let commands: Vec<Vec<&str>> = line.split("|").map(|c| c.split_whitespace().collect()).collect(); let status: Result<i32, String> = esh_execute(commands); match status { Ok(status) => { println!("{}", status); } Err(e) => { println!("{}", e); } } } } fn main() { println!("esh v0.01"); esh_loop(); }
use log::error; mod args; use args::*; use lupo::errors::*; use lupo::*; // Rust doesn't trap a unix signal appropriately occasionally: https://github.com/rust-lang/rust/issues/46016 fn reset_signal_pipe_handler() -> Result<()> { #[cfg(target_family = "unix")] { use nix::sys::signal; unsafe { signal::signal(signal::Signal::SIGPIPE, signal::SigHandler::SigDfl) .chain_err(|| "Internal error: cannot trap signal")?; } } Ok(()) } fn main() { reset_signal_pipe_handler().unwrap(); if let Err(ref e) = run() { let mut s = e.to_string(); for e in e.iter().skip(1) { s.push_str(&format!("\n\tcaused by: {}", e)); } // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { s.push_str(&format!("\n\tbacktrace:\n{:?}", backtrace)); } error!("{}", s); ::std::process::exit(1); } } fn run() -> Result<()> { let opts = parse_args(); stderrlog::new() .module(module_path!()) .show_level(false) .quiet(opts.quiet) .verbosity(opts.verbose + 1) // The user needs warnings .timestamp(opts.ts.unwrap_or(stderrlog::Timestamp::Off)) .init() .unwrap(); let home_dir = &opts.directory.unwrap(); match opts.subcmd { SubCommand::Init { force } => { let store = Store::new(home_dir, force)?; println!("Data directory: {}", store.home_dir.to_string_lossy()); Ok(()) } SubCommand::Check {} => { let store = Store::open(home_dir)?; let (ct, cs) = store.check()?; println!("{} trades processed correctly.", ct); println!("{} stocks processed correctly.", cs); Ok(()) } SubCommand::Trades { name_substring } => { let store = Store::open(home_dir)?; let trades = store.trades(name_substring)?; trades.iter().for_each(|t| println!("{}", t)); Ok(()) } SubCommand::Port {} => { let store = Store::open(home_dir)?; let port_lines = store.port()?; port_lines.iter().for_each(|l| println!("{:}", l)); Ok(()) } } }
use super::*; use std::thread; use std::time::Duration; #[test] fn with_invalid_unit_errors_badarg() { with_process(|process| { assert_badarg!( result(process, atom!("invalid")), "atom (invalid) is not supported" ); }); } #[test] fn with_second_increases_after_2_seconds() { with_process(|process| { let unit = Atom::str_to_term("second"); let first = result(process, unit).unwrap(); thread::sleep(Duration::from_secs(2)); let second = result(process, unit).unwrap(); assert!(first < second); }); } #[test] fn with_millisecond_increases_after_2_milliseconds() { with_process(|process| { let unit = Atom::str_to_term("millisecond"); let first = result(process, unit).unwrap(); thread::sleep(Duration::from_millis(2)); let second = result(process, unit).unwrap(); assert!(first < second); }); } #[test] fn with_microsecond_increases_after_2_milliseconds() { with_process(|process| { let unit = Atom::str_to_term("microsecond"); let first = result(process, unit).unwrap(); thread::sleep(Duration::from_millis(2)); let second = result(process, unit).unwrap(); assert!(first < second); }); } #[test] fn with_nanosecond_increases_after_2_milliseconds() { with_process(|process| { let unit = Atom::str_to_term("nanosecond"); let first = result(process, unit).unwrap(); thread::sleep(Duration::from_millis(2)); let second = result(process, unit).unwrap(); assert!(first < second); }); } #[test] fn with_native_increases_after_2_native_time_units() { with_process(|process| { let unit = Atom::str_to_term("native"); let first = result(process, unit).unwrap(); thread::sleep(Duration::from_millis(2)); let second = result(process, unit).unwrap(); assert!(first < second); }); } #[test] fn with_perf_counter_increases_after_2_perf_counter_ticks() { with_process(|process| { let unit = Atom::str_to_term("perf_counter"); let first = result(process, unit).unwrap(); thread::sleep(Duration::from_millis(2)); let second = result(process, unit).unwrap(); assert!(first < second); }); }
pub mod ai; pub mod game; pub mod grid; pub use ai::AI; pub use game::TicTacToe; pub use grid::Grid; use std::ops::Add; #[derive(Debug, PartialEq)] pub struct Side(pub u16); #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Coordinates { pub x: i16, pub y: i16, } impl Add<Coordinates> for Coordinates { type Output = Coordinates; fn add(self, rhs: Coordinates) -> Coordinates { Coordinates { x: self.x + rhs.x, y: self.y + rhs.y, } } } #[derive(Debug, Clone, Copy, PartialEq)] pub enum Player { Zero, Cross, } impl Player { pub fn to_char(&self) -> char { match self { Self::Zero => '0', Self::Cross => 'X', } } } #[derive(Debug, PartialEq)] pub enum InputEvent { Direction(Direction), Mark, Quit, } #[derive(Debug, PartialEq)] // Marked this as non-exhaustive because it's possible to have variants for diagonal // movements. #[non_exhaustive] pub enum Direction { Up, Down, Left, Right, } impl Direction { pub fn get_relative_coords(&self) -> Coordinates { match &self { Direction::Up => Coordinates { x: 0, y: -1 }, Direction::Down => Coordinates { x: 0, y: 1 }, Direction::Left => Coordinates { x: -1, y: 0 }, Direction::Right => Coordinates { x: 1, y: 0 }, // _ => panic!("diagonal movement is not yet implemented!"), } } } impl Default for Grid { /// The general game of TicTacToe has a square grid of length 3. fn default() -> Self { Self::from(Side(3)) } }
use std::fmt; #[derive(Clone)] struct NucleotideCompressorError { nucleotide: char } impl fmt::Display for NucleotideCompressorError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Invalid nucleotide: {}", self.nucleotide) } } pub struct NucleotideCompressor { bit_string: u32 } impl NucleotideCompressor { pub fn new(gene: String) -> Option<Self> { let bit_string = match NucleotideCompressor::compress(gene) { Ok(b) => b, Err(e) => { eprintln!("{}", e); return None } }; Some(NucleotideCompressor { bit_string }) } fn compress(gene: String) -> Result<u32, NucleotideCompressorError> { let mut bit_string = 1; for nucleotide in gene.chars() { bit_string <<= 2; bit_string |= match nucleotide { 'A' => 0, 'C' => 1, 'G' => 2, 'T' => 3, _ => return Err(NucleotideCompressorError { nucleotide }) } } Ok(bit_string) } fn bit_length(&self) -> u32 { ((self.bit_string as f64).log2() as u32) + 1 } fn decompress(&self) -> String { let n = self.bit_length(); let mut gene = vec![]; for i in (0..n-1).step_by(2) { let bits = self.bit_string >> i & 3; let c = match bits { 0 => 'A', 1 => 'C', 2 => 'G', 3 => 'T', _ => unreachable!() }; gene.push(c); } gene.iter().rev().collect() } } impl fmt::Display for NucleotideCompressor { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.decompress()) } } impl fmt::Debug for NucleotideCompressor { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Bit string: {:b}", self.bit_string) } }
//use std::env; //use std::process; //use minigrep::Config; fn main() { println!("Rust book chapter 12 minigrep"); //let args: Vec<String> = std::env::args().collect(); //println!("{:?}", args); let config = minigrep::Config::new(std::env::args()).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); std::process::exit(1); }); //println!("Searching for {}", config.query); //println!("In file {}", config.filename); if let Err(e) = minigrep::run(config) { eprintln!("Application error: {}", e); std::process::exit(1); } }
use game::*; pub use biomes::*; pub fn add_chunk(game: &mut Game1, coords: &(i64, i64)){ add_grass_biome(game,coords) } impl ChunkLoader{ pub fn new(chunk_loaders: &mut GVec<ChunkLoader>)->ChunkLoaderID{ ChunkLoaderID{id: chunk_loaders.add(ChunkLoader{loaded_chunks: Vec::new(), keep_loaded: Vec::new(), terrain_updates: Vec::new(), chunks_added: Vec::new(), chunks_added_stack: Vec::new(), chunks_removed: Vec::new()}) } } pub fn remove(game: &mut Game1, id: ChunkLoaderID){ game.chunk_loaders.remove(id.id); } } impl BasicChunkLoader{ pub fn new(chunk_loaders: &mut GVec<ChunkLoader>, basic_chunk_loaders: &mut GVec<BasicChunkLoader>, mover_id: MoverID)->BasicChunkLoaderID{ let loader_id=ChunkLoader::new(chunk_loaders); BasicChunkLoaderID{id: basic_chunk_loaders.add(BasicChunkLoader{loader_id: loader_id, mover_id: mover_id})} } pub fn remove(game: &mut Game1, id: BasicChunkLoaderID){ let basic_loader=game.basic_chunk_loaders.remove(id.id); ChunkLoader::remove(game, basic_loader.loader_id); } } impl Chunk{ pub fn begin_step(game: &mut Game1){ for (_coords, chunk) in game.chunks.iter_mut(){ chunk.updates_since_last_frame.clear(); } } pub fn get_chunk_coords(x: f64, y: f64)->(i64,i64){ let chunk_x=(x/CHUNK_WIDTH_PIXELS).floor() as i64; let chunk_y=(y/CHUNK_WIDTH_PIXELS).floor() as i64; (chunk_x,chunk_y) } pub fn get_chunk_coords_from_square(x: i64, y: i64)->(i64, i64){ Self::get_chunk_coords((x as f64)*SQUARE_SIZE,(y as f64)*SQUARE_SIZE) } pub fn get_square_coords_absolute(x: f64, y: f64)->(i64,i64){ let (cx,cy)=Self::get_chunk_coords(x,y); let (spx,spy)=Self::get_square_coords(x,y); let spx=(spx as i64)+cx*CHUNK_WIDTH; let spy=(spy as i64)+cy*CHUNK_WIDTH; (spx,spy) } pub fn get_square_coords(x: f64, y: f64)->(usize,usize){ let (cx,cy)=Self::get_chunk_coords(x,y); let spx=x-(cx as f64)*CHUNK_WIDTH_PIXELS; let spy=y-(cy as f64)*CHUNK_WIDTH_PIXELS; ((spx/SQUARE_SIZE) as usize,(spy/SQUARE_SIZE) as usize) } pub fn get_square_coords_from_square(x: i64, y: i64)->(usize, usize){ Self::get_square_coords((x as f64)*SQUARE_SIZE, (y as f64)*SQUARE_SIZE) } pub fn get_colliding_damageable_terrains_small(chunks: &HashMap<(i64, i64),Chunk>, us: &Mover)->Vec<DamageableID>{ let mut ret=Vec::new(); for i in -1..2{ for j in -1..2{ let mut square=Mover::default(us.x+(i as i64 as f64)*SQUARE_SIZE,us.y+(j as i64 as f64)*SQUARE_SIZE); square.snap_grid(); let (chunk_x, chunk_y)=Self::get_chunk_coords(square.x,square.y); let (square_x, square_y)=Self::get_square_coords(square.x,square.y); if !square.collide(us) { continue } let chunk=chunks.get(&(chunk_x,chunk_y)); if chunk.is_none(){ continue; } let chunk=chunk.unwrap(); for damageable in chunk.damageable_terrain[square_y][square_x].iter(){ ret.push(damageable.damageable_id); } } } ret } pub fn get_colliding_damageable_terrains(game: &mut Game1, us: &Mover)->Vec<DamageableID>{ Self::get_colliding_damageable_terrains_small(&game.chunks, us) } pub fn terrain_update(&mut self, x: usize, y: usize){ let mut ret=Vec::new(); for terrain in self.terrain[y][x].iter(){ ret.push(terrain.sprite); } self.updates_since_last_frame.push((x,y,ret)); } } pub fn step_chunk_loaders(game: &mut Game1){ for (_coords, chunk) in game.chunks.iter_mut(){ chunk.loading=false; } for i in 0..game.chunk_loaders.len(){ let loader=game.chunk_loaders[i].take(); if loader.is_none() {continue;} let mut loader=loader.unwrap(); for coords in loader.keep_loaded.iter(){ if let Some(chunk)=game.chunks.get_mut(coords) {chunk.loading=true;}; } for coords in loader.loaded_chunks.iter(){ if !game.chunks.contains_key(coords){ add_chunk(game, coords); } let chunk=game.chunks.get_mut(coords).expect("Chunk deloaded right after creation"); if !loader.chunks_added.contains(coords){ loader.chunks_added.push(*coords); loader.chunks_added_stack.push(*coords); } chunk.loading=true; } let mut new_added_chunks=Vec::new(); for coords in loader.chunks_added.drain(..){ if let Some(_chunk)=game.chunks.get(&coords){ new_added_chunks.push(coords); } else { loader.chunks_removed.push(coords); } } loader.chunks_added.append(&mut new_added_chunks); game.chunk_loaders[i]=Some(loader); }; } pub fn end_step_chunk_loaders(game: &mut Game1){ for loader in game.chunk_loaders.iter_mut(){ for coords in loader.keep_loaded.iter(){ let chunk=game.chunks.get(&coords); if chunk.is_none() {continue}; let chunk=chunk.unwrap(); for &(ref x,ref y,ref update) in chunk.updates_since_last_frame.iter(){ loader.terrain_updates.push((*x as i64+coords.0*CHUNK_WIDTH,*y as i64+coords.1*CHUNK_WIDTH,update.clone())); } } } } const BASIC_LOADER_LOAD_RANGE: i64=2; const BASIC_LOADER_KEEP_LOADED_RANGE: i64 =4; pub fn step_basic_chunk_loaders(game: &mut Game1){ for loader in game.basic_chunk_loaders.iter(){ let mover=game.movers.at(loader.mover_id.id); let base_loader=game.chunk_loaders.at_mut(loader.loader_id.id); base_loader.loaded_chunks.clear(); base_loader.keep_loaded.clear(); let (chunk_x,chunk_y)=Chunk::get_chunk_coords(mover.x,mover.y); for x in -BASIC_LOADER_LOAD_RANGE..BASIC_LOADER_LOAD_RANGE+1{ for y in -BASIC_LOADER_LOAD_RANGE..BASIC_LOADER_LOAD_RANGE+1{ base_loader.loaded_chunks.push((chunk_x+x,chunk_y+y)); } } for x in -BASIC_LOADER_KEEP_LOADED_RANGE..BASIC_LOADER_KEEP_LOADED_RANGE+1{ for y in -BASIC_LOADER_KEEP_LOADED_RANGE..BASIC_LOADER_KEEP_LOADED_RANGE+1{ base_loader.keep_loaded.push((chunk_x+x,chunk_y+y)); } } }; } pub fn cull_chunks(chunks: &mut HashMap<(i64,i64), Chunk>){ let dead_keys: Vec<(i64,i64)>=chunks.iter().filter(|ref v|!v.1.loading).map(|v|*v.0).collect(); for dead_key in dead_keys{ let _chunk=chunks.remove(&dead_key).unwrap(); } } pub fn begin_step_terrains(game: &mut Game1){ Chunk::begin_step(game); } pub fn step_terrains(game: &mut Game1){ step_biomes(game); step_basic_chunk_loaders(game); step_chunk_loaders(game); cull_chunks(&mut game.chunks); } pub fn end_step_terrains(game: &mut Game1){ end_step_biomes(game); end_step_chunk_loaders(game); }
mod mersenne; use mersenne::{MersenneTwister}; fn main() { let mut rand1 = MersenneTwister::new_from_seed(44332); let mut out = [0;624]; for i in 0..624{ out[i] = rand1.gen_rand(); } let mut rand2 = MersenneTwister::clone(&out); for i in 0..100000{ assert_eq!(rand1.gen_rand(),rand2.gen_rand()); } println!("successful cloning"); }
use result::{Error, Payload}; use rocket_contrib::json::Json; pub type ApiResponse<T> = Result<Json<Payload<T>>, Error>;
use super::system_prelude::*; #[derive(Default)] pub struct SpikeSystem; impl<'a> System<'a> for SpikeSystem { type SystemData = ( Entities<'a>, Write<'a, ResetLevel>, Write<'a, PlayerDeaths>, ReadStorage<'a, Spike>, ReadStorage<'a, Player>, ReadStorage<'a, Collision>, ReadStorage<'a, Loadable>, ReadStorage<'a, Loaded>, ); fn run( &mut self, ( entities, mut reset_level, mut player_deaths, spikes, players, collisions, loadables, loadeds, ): Self::SystemData, ) { if let Some((_, player_collision)) = (&players, &collisions).join().next() { for (spike_entity, spike, loadable_opt, loaded_opt) in (&entities, &spikes, loadables.maybe(), loadeds.maybe()).join() { if let (None, None) | (Some(_), Some(_)) = (loadable_opt, loaded_opt) { if spike.enabled { if let Some(collision::Data { side: Side::Inner, .. }) = player_collision.collision_with(spike_entity.id()) { reset_level.0 = true; player_deaths.0 += 1; break; } } } } } } }
#[doc = "Reader of register OR"] pub type R = crate::R<u32, super::OR>; #[doc = "Writer for register OR"] pub type W = crate::W<u32, super::OR>; #[doc = "Register OR `reset()`'s with value 0"] impl crate::ResetValue for super::OR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TI4_RMP`"] pub type TI4_RMP_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TI4_RMP`"] pub struct TI4_RMP_W<'a> { w: &'a mut W, } impl<'a> TI4_RMP_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 6)) | (((value as u32) & 0x03) << 6); self.w } } impl R { #[doc = "Bits 6:7 - Timer Input 4 remap"] #[inline(always)] pub fn ti4_rmp(&self) -> TI4_RMP_R { TI4_RMP_R::new(((self.bits >> 6) & 0x03) as u8) } } impl W { #[doc = "Bits 6:7 - Timer Input 4 remap"] #[inline(always)] pub fn ti4_rmp(&mut self) -> TI4_RMP_W { TI4_RMP_W { w: self } } }
use crate::math; use std::f32; #[derive(Clone)] pub struct Camera { pub view: math::Mat4x4f, pub pos: math::Vec3f, pub pitch: f32, pub yaw: f32, pub near: f32, pub far: f32, pub aspect: f32, pub fov: f32, } pub fn create_default_camera(width: u32, height: u32) -> Camera { Camera { view: math::Mat4x4f::identity(), // pos: math::Vec3f::new(0., 500., 0.), pos: math::Vec3f::new(0., 0., 200.), pitch: 0., yaw: 0., near: 10.1, far: 10000.0, aspect: width as f32 / height as f32, fov: f32::consts::PI / 2. * 0.66, } }
extern crate thin; extern crate fn_move; use thin::ThinBox; use fn_move::FnMove; #[test] fn thin_box_closure() { let v1 = vec![1i32,2,3]; let v2 = vec![-1i32, -2, -3]; let closure: ThinBox<FnMove() -> Vec<i32>> = ThinBox::new(move ||{ v1.into_iter() .zip(v2) // have to return a Vec because fixed-size arrays still // don't implement IntoIterator .flat_map(|(x, y)| { vec![x, y] }) .collect::<Vec<_>>() }); closure(); // assert_eq!(closure(), &[1, -1, 2, -2, 3, -3]); }
use std::io::Write; use crate::Color; use crate::util::clamp; pub fn write_color<W: Write>(out: &mut W, pixel_color: Color, samples_per_pixel: i32) { // Divide the color by the number of samples and gamma-correct for gamma=2.0. let scale = 1.0 / samples_per_pixel as f64; let r = (pixel_color.x() * scale).sqrt(); let g = (pixel_color.y() * scale).sqrt(); let b = (pixel_color.z() * scale).sqrt(); // Write the translated [0,255] value of each color component. writeln!( out, "{} {} {}", (256.0 * clamp(r, 0.0, 0.999)) as u8, (256.0 * clamp(g, 0.0, 0.999)) as u8, (256.0 * clamp(b, 0.0, 0.999)) as u8, ).unwrap(); }
use core::ops::ControlFlow; use anyhow::anyhow; use firefly_diagnostics::{SourceSpan, Span}; use firefly_intern::{symbols, Ident}; use firefly_pass::Pass; use firefly_syntax_base::FunctionName; use crate::ast::*; use crate::visit::{self as visit, VisitMut}; /// This pass performs expansion of records and record operations into raw /// tuple operations. /// /// Once this pass has run, there should no longer be _any_ record expressions /// in the AST, anywhere. If there are, its an invariant violation and should /// cause an ICE. pub struct ExpandRecords<'m> { module: &'m Module, } impl<'m> ExpandRecords<'m> { pub fn new(module: &'m Module) -> Self { Self { module } } } impl<'m> Pass for ExpandRecords<'m> { type Input<'a> = &'a mut Function; type Output<'a> = &'a mut Function; fn run<'a>(&mut self, f: Self::Input<'a>) -> anyhow::Result<Self::Output<'a>> { let mut visitor = ExpandRecordsVisitor::new(self.module, f); match visitor.visit_mut_function(f) { ControlFlow::Continue(_) => { f.var_counter = visitor.var_counter; Ok(f) } ControlFlow::Break(err) => Err(err), } } } struct ExpandRecordsVisitor<'m> { module: &'m Module, var_counter: usize, in_pattern: bool, in_guard: bool, expand_record_info: bool, } impl<'m> ExpandRecordsVisitor<'m> { fn new(module: &'m Module, f: &Function) -> Self { let record_info = FunctionName::new_local(symbols::RecordInfo, 2); let expand_record_info = module.functions.get(&record_info).is_none(); Self { module, in_pattern: false, in_guard: false, expand_record_info, var_counter: f.var_counter, } } fn next_var(&mut self, span: Option<SourceSpan>) -> Ident { let id = self.var_counter; self.var_counter += 1; let var = format!("${}", id); let mut ident = Ident::from_str(&var); match span { None => ident, Some(span) => { ident.span = span; ident } } } } impl<'m> VisitMut<anyhow::Error> for ExpandRecordsVisitor<'m> { fn visit_mut_pattern(&mut self, pattern: &mut Expr) -> ControlFlow<anyhow::Error> { self.in_pattern = true; visit::visit_mut_pattern(self, pattern)?; self.in_pattern = false; ControlFlow::Continue(()) } fn visit_mut_clause(&mut self, clause: &mut Clause) -> ControlFlow<anyhow::Error> { // TODO: Once the clause has been visited, convert any is_record calls // to pattern matches if possible, as these can be better optimized away // later to avoid redundant checks visit::visit_mut_clause(self, clause) } fn visit_mut_guard(&mut self, guard: &mut Guard) -> ControlFlow<anyhow::Error> { self.in_guard = true; visit::visit_mut_guard(self, guard)?; self.in_guard = false; ControlFlow::Continue(()) } fn visit_mut_expr(&mut self, expr: &mut Expr) -> ControlFlow<anyhow::Error> { match expr { // Expand calls to record_info/2 if not shadowed Expr::Apply(ref mut apply) if self.expand_record_info => { self.visit_mut_apply(apply)?; if let Some(callee) = apply.callee.as_ref().as_atom() { if callee.name != symbols::RecordInfo || apply.args.len() != 2 { return ControlFlow::Continue(()); } let prop = &apply.args[0]; let record_name = &apply.args[1]; if let ControlFlow::Continue(info) = self.try_expand_record_info(record_name, prop) { *expr = info; } } ControlFlow::Continue(()) } // Record creation, or pattern match Expr::Record(ref mut record) => { // Work inside-out, so visit the record body first self.visit_mut_record(record)?; // Convert this record into a tuple expression let tuple = self.expand_record(record)?; // Replace the original expression *expr = tuple; ControlFlow::Continue(()) } // Accessing a record field value, e.g. Expr#myrec.field1 Expr::RecordAccess(ref mut access) => { // Convert this to: // // case Expr of // {myrec, .., _Field1, ...} -> // _Field1; // _0 -> // erlang:error({badrecord, _0}) // end self.visit_mut_record_access(access)?; let expanded = self.expand_access(access)?; *expr = expanded; ControlFlow::Continue(()) } // Referencing a record fields index, e.g. #myrec.field1 Expr::RecordIndex(ref record_index) => { // Convert this to a literal let literal = self.expand_index(record_index)?; *expr = literal; ControlFlow::Continue(()) } // Update a record field value, e.g. Expr#myrec{field1=ValueExpr} Expr::RecordUpdate(ref mut update) => { assert!(!self.in_guard, "record updates are not valid in guards"); assert!(!self.in_pattern, "record updates are not valid in patterns"); // Convert this to: // // case Expr of // {myrec, _, ..} -> // erlang:setelement(N, erlang:setelement(N - 1, .., ..), $ValueN); // $0 -> // erlang:error({badrecord, $0}) // end self.visit_mut_record_update(update)?; let expanded = self.expand_update(update)?; *expr = expanded; ControlFlow::Continue(()) } _ => visit::visit_mut_expr(self, expr), } } } impl<'m> ExpandRecordsVisitor<'m> { fn try_expand_record_info( &self, record_name: &Expr, prop: &Expr, ) -> ControlFlow<anyhow::Error, Expr> { let record_name = record_name .as_atom() .map(ControlFlow::Continue) .unwrap_or_else(|| { ControlFlow::Break(anyhow!( "expected atom name in call to record_info/2, got '{:?}'", record_name )) })?; let prop = prop .as_atom() .map(ControlFlow::Continue) .unwrap_or_else(|| { ControlFlow::Break(anyhow!( "expected the atom 'size' or 'fields' in call to record_info/2, got '{:?}'", record_name )) })?; let span = record_name.span; if let Some(definition) = self.module.record(record_name.name) { let prop_name = prop.as_str().get(); match prop_name { "size" => ControlFlow::Continue(Expr::Literal(Literal::Integer( span, (1 + definition.fields.len()).into(), ))), "fields" => { let field_name_list = definition.fields.iter().rev().fold( Expr::Literal(Literal::Nil(span)), |tail, f| { let field_name = Expr::Literal(Literal::Atom(f.name)); Expr::Cons(Cons { span, head: Box::new(field_name), tail: Box::new(tail), }) }, ); ControlFlow::Continue(field_name_list) } _ => ControlFlow::Break(anyhow!( "expected the atom 'size' or 'fields' in call to record_info/2, but got '{}'", &prop_name )), } } else { ControlFlow::Break(anyhow!( "unable to expand record info for '{}', no such record", record_name )) } } fn expand_record(&self, record: &Record) -> ControlFlow<anyhow::Error, Expr> { let name = record.name; let symbol = name.name; let definition = self .module .record(symbol) .map(ControlFlow::Continue) .unwrap_or_else(|| ControlFlow::Break(anyhow!("use of undefined record '{}'", name)))?; let span = record.span.clone(); let mut elements = Vec::with_capacity(definition.fields.len()); // The first element is the record name atom elements.push(Expr::Literal(Literal::Atom(Ident::with_empty_span(symbol)))); // For each definition, in order the fields are declared, fetch the corresponding value // from the record expression, then depending on whether this is a pattern match or a // constructor, we construct an appropriate tuple element expression for defined in definition.fields.iter() { let provided = record.fields.iter().find_map(|f| { if f.name == defined.name { f.value.as_ref() } else { None } }); if let Some(value_expr) = provided { elements.push(value_expr.clone()); } else if self.in_pattern { // This is a pattern, so elided fields need a wildcard pattern elements.push(Expr::Var( Ident::with_empty_span(symbols::Underscore).into(), )); } else { // This is a constructor, so use the default initializer, or the atom 'undefined' if one isn't present if let Some(default_expr) = defined.value.as_ref() { elements.push(default_expr.clone()); } else { elements.push(Expr::Literal(Literal::Atom(Ident::with_empty_span( symbols::Undefined, )))); } } } ControlFlow::Continue(Expr::Tuple(Tuple { span, elements })) } fn expand_index(&self, record_index: &RecordIndex) -> ControlFlow<anyhow::Error, Expr> { let name = record_index.name; let field = record_index.field; let definition = self .module .record(name.name) .map(ControlFlow::Continue) .unwrap_or_else(|| { ControlFlow::Break(anyhow!("reference to undefined record '{}'", name)) })?; let index = definition .fields .iter() .position(|f| f.name == field) .map(ControlFlow::Continue) .unwrap_or_else(|| { ControlFlow::Break(anyhow!( "reference to undefined field '{}' of record '{}'", field, name )) })?; ControlFlow::Continue(Expr::Literal(Literal::Integer( record_index.span.clone(), (index + 1).into(), ))) } fn expand_access(&mut self, record_access: &RecordAccess) -> ControlFlow<anyhow::Error, Expr> { let name = record_access.name; let field_name = record_access.field; let span = record_access.span.clone(); let definition = self .module .record(name.name) .map(ControlFlow::Continue) .unwrap_or_else(|| { ControlFlow::Break(anyhow!("reference to undefined record '{}'", name)) })?; let field = definition .fields .iter() .find(|f| f.name == field_name) .map(ControlFlow::Continue) .unwrap_or_else(|| { ControlFlow::Break(anyhow!( "reference to undefined field '{}' of record '{}'", field_name, name )) })?; let field_var = self.next_var(Some(field_name.span)); let catch_all_var = self.next_var(Some(span)); let tuple_pattern = self.expand_record(&Record { span, name: name.clone(), fields: vec![RecordField { span: field_name.span, name: field.name, value: Some(Expr::Var(field_var.into())), ty: None, }], })?; // The callee for pattern match failure let erlang_error = Expr::FunctionVar(FunctionVar::Resolved(Span::new( span, FunctionName::new(symbols::Erlang, symbols::Error, 1), ))); // The error reason let reason = Expr::Tuple(Tuple { span, elements: vec![ Expr::Literal(Literal::Atom(Ident::with_empty_span(symbols::Badrecord))), Expr::Var(catch_all_var.into()), ], }); // The expanded representation: // case Expr of // {myrec, _, .., $0, ..} -> // $0; // $1 -> // erlang:error({badrecord, $1}) // end ControlFlow::Continue(Expr::Case(Case { span: record_access.span.clone(), expr: record_access.record.clone(), clauses: vec![ Clause { span, patterns: vec![tuple_pattern], guards: vec![], body: vec![Expr::Var(field_var.into())], compiler_generated: true, }, Clause { span, patterns: vec![Expr::Var(catch_all_var.into())], guards: vec![], body: vec![Expr::Apply(Apply { span, callee: Box::new(erlang_error), args: vec![reason], })], compiler_generated: true, }, ], })) } fn expand_update(&mut self, record_update: &RecordUpdate) -> ControlFlow<anyhow::Error, Expr> { let name = record_update.name; let span = record_update.span.clone(); let definition = self .module .record(name.name) .map(ControlFlow::Continue) .unwrap_or_else(|| { ControlFlow::Break(anyhow!("reference to undefined record '{}'", name)) })?; // Save a copy of the record expression as we'll need that let expr = record_update.record.as_ref().clone(); // If there are no updates for some reason, treat this expression as transparent if record_update.updates.is_empty() { return ControlFlow::Continue(expr); } // Generate vars for use in the pattern match phase let bound_var = self.next_var(Some(span)); let catch_all_var = self.next_var(Some(span)); // Expand the updates to a sequence of nested setelement calls such that they evaluate in the correct order let expanded_updates = record_update .updates .iter() .rev() .try_fold::<_, _, ControlFlow<anyhow::Error, Expr>>( Expr::Var(bound_var.into()), |acc, update| { let field_name = update.name; let position = definition .fields .iter() .position(|f| f.name == field_name) .map(ControlFlow::Continue) .unwrap_or_else(|| { ControlFlow::Break(anyhow!( "reference to undefined field '{}' of record '{}'", field_name, name )) })?; let callee = Expr::FunctionVar(FunctionVar::Resolved(Span::new( span, FunctionName::new(symbols::Erlang, symbols::Setelement, 3), ))); let index = Expr::Literal(Literal::Integer(span, (position + 1).into())); let value = update.value.as_ref().unwrap().clone(); ControlFlow::Continue(Expr::Apply(Apply { span, callee: Box::new(callee), args: vec![index, acc, value], })) }, )?; // Generate an empty pattern, i.e. all wildcards, that validates the input is a tuple of the appropriate type/shape let tuple_pattern = self.expand_record(&Record { span, name, fields: vec![], })?; // The callee for pattern match failure let erlang_error = Expr::FunctionVar(FunctionVar::Resolved(Span::new( span, FunctionName::new(symbols::Erlang, symbols::Error, 1), ))); // The error reason let reason = Expr::Tuple(Tuple { span, elements: vec![ Expr::Literal(Literal::Atom(Ident::with_empty_span(symbols::Badrecord))), Expr::Var(catch_all_var.into()), ], }); ControlFlow::Continue(Expr::Case(Case { span, expr: Box::new(expr), clauses: vec![ Clause { span, patterns: vec![tuple_pattern], guards: vec![], body: vec![expanded_updates], compiler_generated: true, }, Clause { span, patterns: vec![Expr::Var(catch_all_var.into())], guards: vec![], body: vec![Expr::Apply(Apply { span, callee: Box::new(erlang_error), args: vec![reason], })], compiler_generated: true, }, ], })) } }
#[doc = "Reader of register MDIOS_RDFR"] pub type R = crate::R<u32, super::MDIOS_RDFR>; #[doc = "Reader of field `RDF`"] pub type RDF_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - Read flags for MDIO registers 0 to 31"] #[inline(always)] pub fn rdf(&self) -> RDF_R { RDF_R::new((self.bits & 0xffff_ffff) as u32) } }
use crate::error::RpcError; use crate::module::Module; pub(crate) mod methods; /// Registers all methods for the pathfinder RPC API pub fn register_methods(module: Module) -> anyhow::Result<Module> { let module = module .register_method_with_no_input("v0.1_pathfinder_version", |_| async { Result::<_, RpcError>::Ok(pathfinder_common::consts::VERGEN_GIT_DESCRIBE) })? .register_method("v0.1_pathfinder_getProof", methods::get_proof)? .register_method( "v0.1_pathfinder_getTransactionStatus", methods::get_transaction_status, )?; Ok(module) }
use failure::Error; use yew::{html, Callback, Component, ComponentLink, Html, Renderable, ShouldRender}; use yew::services::fetch::FetchTask; use crate::services::froovie_service::{FroovieService, Selections, Movie}; pub struct UserSelectionModel { froovie: FroovieService, callback: Callback<Result<Selections, Error>>, pub selections: Option<Selections>, task: Option<FetchTask>, error: Option<String>, } pub enum Msg { Selections, FroovieReady(Result<Selections, Error>), } impl Component for UserSelectionModel { type Message = Msg; type Properties = (); fn create(_: Self::Properties, mut link: ComponentLink<Self>) -> Self { UserSelectionModel { froovie: FroovieService::new(), callback: link.send_back(Msg::FroovieReady), selections: None, task: None, error: None, } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::Selections => { let task = self.froovie.get_user_selection("1", self.callback.clone()); self.task = Some(task); } Msg::FroovieReady(Ok(selections)) => { self.selections = Some(selections); } Msg::FroovieReady(Err(error)) => { self.error = Some(error.to_string()); } } true } } impl Renderable<UserSelectionModel> for UserSelectionModel { fn view(&self) -> Html<Self> { let view_movie = |movie| html! { <li> { movie } </li> }; let selections = self.selections.as_ref(); let movies: Vec<Movie> = selections.iter() .flat_map(|user|user.movies.clone()) .collect(); html! { <div> <button onclick=|_| Msg::Selections,>{ "Get " }</button> <ul> { for movies.iter().map(|movie| view_movie(movie.title.clone())) } </ul> <p> { &format!("Error status : {:?}", &self.error) } </p> </div> } } }
//! Static Single Assignment (SSA) Transformation use crate::graph::*; use crate::il; use crate::Error; use std::collections::{HashMap, HashSet, VecDeque}; /// Transform the IL function into SSA form. pub fn ssa_transformation(function: &il::Function) -> Result<il::Function, Error> { let mut ssa_function = function.clone(); insert_phi_nodes(&mut ssa_function)?; rename_scalars(&mut ssa_function)?; Ok(ssa_function) } /// Inserts phi nodes where necessary. /// /// Implements the algorithm for constructing Semi-Pruned SSA form, /// see Algorithm 3.1 in "SSA-based Compiler Design" book for more details. fn insert_phi_nodes(function: &mut il::Function) -> Result<(), Error> { let cfg = function.control_flow_graph(); let entry = cfg.entry().ok_or("CFG entry must be set")?; let dominance_frontiers = cfg.graph().compute_dominance_frontiers(entry)?; let non_local_scalars = compute_non_local_scalars(cfg); for (scalar, defs) in scalars_mutated_in_blocks(cfg) { if !non_local_scalars.contains(&scalar) { continue; // ignore local scalars } let mut phi_insertions: HashSet<usize> = HashSet::new(); let mut queue: VecDeque<usize> = defs.iter().cloned().collect(); while let Some(block_index) = queue.pop_front() { for df_index in &dominance_frontiers[&block_index] { if phi_insertions.contains(df_index) { continue; } let phi_node = { let mut phi_node = il::PhiNode::new(scalar.clone()); let cfg = function.control_flow_graph(); for predecessor in cfg.predecessor_indices(*df_index)? { phi_node.add_incoming(scalar.clone(), predecessor); } if *df_index == entry { phi_node.set_entry_scalar(scalar.clone()); } phi_node }; let cfg = function.control_flow_graph_mut(); let df_block = cfg.block_mut(*df_index)?; df_block.add_phi_node(phi_node); phi_insertions.insert(*df_index); if !defs.contains(df_index) { queue.push_back(*df_index); } } } } Ok(()) } /// Get the set of scalars which are mutated in the given block. fn scalars_mutated_in_block(block: &il::Block) -> HashSet<&il::Scalar> { block .instructions() .iter() .flat_map(|inst| inst.scalars_written().unwrap_or_default()) .collect() } /// Get a mapping from scalars to a set of blocks (indices) in which they are mutated. fn scalars_mutated_in_blocks(cfg: &il::ControlFlowGraph) -> HashMap<il::Scalar, HashSet<usize>> { let mut mutated_in = HashMap::new(); for block in cfg.blocks() { for scalar in scalars_mutated_in_block(block) { if !mutated_in.contains_key(scalar) { mutated_in.insert(scalar.clone(), HashSet::new()); } mutated_in.get_mut(scalar).unwrap().insert(block.index()); } } mutated_in } // Computes the set of scalars that are live on entry of at least one block. // Such scalars are denoted as "non locals" in the algorithm for Semi-Pruned SSA. fn compute_non_local_scalars(cfg: &il::ControlFlowGraph) -> HashSet<il::Scalar> { let mut non_locals = HashSet::new(); for block in cfg.blocks() { let mut killed = HashSet::new(); block.instructions().iter().for_each(|inst| { inst.scalars_read() .unwrap_or_default() .into_iter() .filter(|scalar| !killed.contains(scalar)) .for_each(|scalar| { non_locals.insert(scalar.clone()); }); inst.scalars_written() .unwrap_or_default() .into_iter() .for_each(|scalar| { killed.insert(scalar); }); }); } non_locals } fn rename_scalars(function: &mut il::Function) -> Result<(), Error> { let mut versioning = ScalarVersioning::new(); function.rename_scalars(&mut versioning) } struct ScalarVersioning { counter: HashMap<String, usize>, scoped_versions: Vec<HashMap<String, usize>>, } impl ScalarVersioning { pub fn new() -> Self { Self { counter: HashMap::new(), scoped_versions: Vec::new(), } } pub fn start_new_scope(&mut self) { let scope = match self.scoped_versions.last() { Some(parent_scope) => parent_scope.clone(), None => HashMap::new(), }; self.scoped_versions.push(scope); } pub fn end_scope(&mut self) { self.scoped_versions.pop(); } fn get_version(&mut self, scalar: &il::Scalar) -> Option<usize> { self.scoped_versions .last() .and_then(|versions| versions.get(scalar.name())) .copied() } fn new_version(&mut self, scalar: &il::Scalar) -> usize { let count = self.counter.entry(scalar.name().to_string()).or_insert(1); let version = *count; *count += 1; let versions = self.scoped_versions.last_mut().unwrap(); versions.insert(scalar.name().to_string(), version); version } } trait SsaRename { fn rename_scalars(&mut self, versioning: &mut ScalarVersioning) -> Result<(), Error>; } impl SsaRename for il::Expression { fn rename_scalars(&mut self, versioning: &mut ScalarVersioning) -> Result<(), Error> { for scalar in self.scalars_mut() { scalar.set_ssa(versioning.get_version(scalar)); } Ok(()) } } impl SsaRename for il::Instruction { fn rename_scalars(&mut self, versioning: &mut ScalarVersioning) -> Result<(), Error> { // rename all read scalars if let Some(mut scalars_read) = self.scalars_read_mut() { for scalar in scalars_read.iter_mut() { scalar.set_ssa(versioning.get_version(scalar)); } } // introduce new SSA names for written scalars if let Some(mut scalar_written) = self.scalar_written_mut() { for scalar in scalar_written.iter_mut() { scalar.set_ssa(Some(versioning.new_version(scalar))); } } Ok(()) } } impl SsaRename for il::Block { fn rename_scalars(&mut self, versioning: &mut ScalarVersioning) -> Result<(), Error> { // introduce new SSA names for phi node outputs for phi_node in self.phi_nodes_mut() { let scalar = phi_node.out_mut(); scalar.set_ssa(Some(versioning.new_version(scalar))); } for inst in self.instructions_mut() { inst.rename_scalars(versioning)?; } Ok(()) } } impl SsaRename for il::ControlFlowGraph { fn rename_scalars(&mut self, versioning: &mut ScalarVersioning) -> Result<(), Error> { let entry = self.entry().ok_or("CFG entry must be set")?; type DominatorTree = Graph<NullVertex, NullEdge>; let dominator_tree = self.graph().compute_dominator_tree(entry)?; fn dominator_tree_dfs_pre_order_traverse( cfg: &mut il::ControlFlowGraph, dominator_tree: &DominatorTree, node: usize, versioning: &mut ScalarVersioning, ) -> Result<(), Error> { versioning.start_new_scope(); let block = cfg.block_mut(node)?; block.rename_scalars(versioning)?; let immediate_successors = cfg.successor_indices(node)?; for successor_index in immediate_successors { // rename scalars in conditions of all outgoing edges let edge = cfg.edge_mut(node, successor_index)?; if let Some(condition) = edge.condition_mut() { condition.rename_scalars(versioning)? } // rename all scalars of successor phi nodes which originate from this block let successor_block = cfg.block_mut(successor_index)?; for phi_node in successor_block.phi_nodes_mut() { if let Some(incoming_scalar) = phi_node.incoming_scalar_mut(node) { incoming_scalar.set_ssa(versioning.get_version(incoming_scalar)); } } } for successor in dominator_tree.successors(node)? { dominator_tree_dfs_pre_order_traverse( cfg, dominator_tree, successor.index(), versioning, )?; } versioning.end_scope(); Ok(()) } dominator_tree_dfs_pre_order_traverse(self, &dominator_tree, entry, versioning) } } impl SsaRename for il::Function { fn rename_scalars(&mut self, versioning: &mut ScalarVersioning) -> Result<(), Error> { self.control_flow_graph_mut().rename_scalars(versioning) } } #[cfg(test)] mod tests { use super::*; pub fn scalar_ssa<S>(name: S, bits: usize, ssa: usize) -> il::Scalar where S: Into<String>, { let mut scalar = il::Scalar::new(name, bits); scalar.set_ssa(Some(ssa)); scalar } pub fn expr_scalar_ssa<S>(name: S, bits: usize, ssa: usize) -> il::Expression where S: Into<String>, { il::Expression::scalar(scalar_ssa(name, bits, ssa)) } #[test] fn test_scalars_mutated_in_block() { let block = { let mut block = il::Block::new(0); block.assign(il::scalar("x", 64), il::expr_const(1, 64)); block.load(il::scalar("y", 64), il::expr_scalar("z", 64)); block.assign(il::scalar("x", 64), il::expr_scalar("y", 64)); block.nop(); block }; assert_eq!( scalars_mutated_in_block(&block), vec![&il::scalar("x", 64), &il::scalar("y", 64)] .into_iter() .collect() ); } #[test] fn test_scalars_mutated_in_blocks() { let cfg = { let mut cfg = il::ControlFlowGraph::new(); let block0 = cfg.new_block().unwrap(); block0.assign(il::scalar("x", 64), il::expr_const(1, 64)); let block1 = cfg.new_block().unwrap(); block1.load(il::scalar("y", 64), il::expr_scalar("z", 64)); let block2 = cfg.new_block().unwrap(); block2.assign(il::scalar("x", 64), il::expr_scalar("y", 64)); cfg }; let mutated_in_blocks = scalars_mutated_in_blocks(&cfg); assert_eq!( mutated_in_blocks[&il::scalar("x", 64)], vec![0, 2].into_iter().collect() ); assert_eq!( mutated_in_blocks[&il::scalar("y", 64)], vec![1].into_iter().collect() ); } #[test] fn test_compute_non_local_scalars() { let cfg = { let mut cfg = il::ControlFlowGraph::new(); let block0 = cfg.new_block().unwrap(); block0.assign(il::scalar("x", 64), il::expr_const(1, 64)); let block1 = cfg.new_block().unwrap(); block1.assign(il::scalar("tmp", 64), il::expr_const(1, 64)); block1.assign(il::scalar("x", 64), il::expr_scalar("tmp", 64)); let block2 = cfg.new_block().unwrap(); block2.load(il::scalar("y", 64), il::expr_scalar("x", 64)); cfg }; assert_eq!( compute_non_local_scalars(&cfg), vec![il::scalar("x", 64)].into_iter().collect() ); } #[test] fn test_renaming_of_expression() { // Given: x + y * x let mut expression = il::Expression::add( il::expr_scalar("x", 64), il::Expression::mul(il::expr_scalar("y", 64), il::expr_scalar("x", 64)).unwrap(), ) .unwrap(); let mut versioning = ScalarVersioning::new(); versioning.start_new_scope(); versioning.new_version(&il::scalar("x", 64)); versioning.new_version(&il::scalar("y", 64)); expression.rename_scalars(&mut versioning).unwrap(); // Expected: x_1 + y_1 * x_1 assert_eq!( expression, il::Expression::add( expr_scalar_ssa("x", 64, 1), il::Expression::mul(expr_scalar_ssa("y", 64, 1), expr_scalar_ssa("x", 64, 1)) .unwrap(), ) .unwrap() ); } #[test] fn test_renaming_of_nop_instruction() { // Given: nop let mut instruction = il::Instruction::nop(0); let mut versioning = ScalarVersioning::new(); versioning.start_new_scope(); instruction.rename_scalars(&mut versioning).unwrap(); // Expected: nop assert_eq!(instruction, il::Instruction::nop(0)); } #[test] fn test_renaming_of_assign_instruction() { // Given: x := x let mut instruction = il::Instruction::assign(0, il::scalar("x", 64), il::expr_scalar("x", 64)); let mut versioning = ScalarVersioning::new(); versioning.start_new_scope(); versioning.new_version(&il::scalar("x", 64)); instruction.rename_scalars(&mut versioning).unwrap(); // Expected: x_2 := x_1 assert_eq!( instruction, il::Instruction::assign(0, scalar_ssa("x", 64, 2), expr_scalar_ssa("x", 64, 1),) ); } #[test] fn test_renaming_of_load_instruction() { // Given: x := [x] let mut instruction = il::Instruction::load(0, il::scalar("x", 64), il::expr_scalar("x", 64)); let mut versioning = ScalarVersioning::new(); versioning.start_new_scope(); versioning.new_version(&il::scalar("x", 64)); instruction.rename_scalars(&mut versioning).unwrap(); // Expected: x_2 := [x_1] assert_eq!( instruction, il::Instruction::load(0, scalar_ssa("x", 64, 2), expr_scalar_ssa("x", 64, 1)) ); } #[test] fn test_renaming_of_store_instruction() { // Given: [x] := x let mut instruction = il::Instruction::store(0, il::expr_scalar("x", 64), il::expr_scalar("x", 64)); let mut versioning = ScalarVersioning::new(); versioning.start_new_scope(); versioning.new_version(&il::scalar("x", 64)); instruction.rename_scalars(&mut versioning).unwrap(); // Expected: [x_1] := x_1 assert_eq!( instruction, il::Instruction::store(0, expr_scalar_ssa("x", 64, 1), expr_scalar_ssa("x", 64, 1)) ); } #[test] fn test_renaming_of_branch_instruction() { // Given: brc x let mut instruction = il::Instruction::branch(0, il::expr_scalar("x", 64)); let mut versioning = ScalarVersioning::new(); versioning.start_new_scope(); versioning.new_version(&il::scalar("x", 64)); instruction.rename_scalars(&mut versioning).unwrap(); // Expected: brc x_1 assert_eq!( instruction, il::Instruction::branch(0, expr_scalar_ssa("x", 64, 1)) ); } #[test] fn test_renaming_of_block() { // Given: // y = phi [] // x = y // y = [x] // x = y // z = x let mut block = il::Block::new(0); block.add_phi_node(il::PhiNode::new(il::scalar("y", 64))); block.assign(il::scalar("x", 64), il::expr_scalar("y", 64)); block.load(il::scalar("y", 64), il::expr_scalar("x", 64)); block.assign(il::scalar("x", 64), il::expr_scalar("y", 64)); block.assign(il::scalar("z", 64), il::expr_scalar("x", 64)); let mut versioning = ScalarVersioning::new(); versioning.start_new_scope(); block.rename_scalars(&mut versioning).unwrap(); // Expected: // y_1 = phi [] // x_1 = 1 // y_2 = [x_1] // x_2 = y_2 // z_1 = x_2 assert_eq!( block.phi_node(0).unwrap(), &il::PhiNode::new(scalar_ssa("y", 64, 1)) ); assert_eq!( block.instruction(0).unwrap().operation(), &il::Operation::assign(scalar_ssa("x", 64, 1), expr_scalar_ssa("y", 64, 1)) ); assert_eq!( block.instruction(1).unwrap().operation(), &il::Operation::load(scalar_ssa("y", 64, 2), expr_scalar_ssa("x", 64, 1)) ); assert_eq!( block.instruction(2).unwrap().operation(), &il::Operation::assign(scalar_ssa("x", 64, 2), expr_scalar_ssa("y", 64, 2)) ); assert_eq!( block.instruction(3).unwrap().operation(), &il::Operation::assign(scalar_ssa("z", 64, 1), expr_scalar_ssa("x", 64, 2)) ); } #[test] fn test_renaming_of_conditional_edges() { // Given: // x = 1 // nop +---+ // ----- | (x) // x = x <---+ // nop +---+ // ----- | (x) // x = x <---+ let mut cfg = il::ControlFlowGraph::new(); let block0 = cfg.new_block().unwrap(); block0.assign(il::scalar("x", 64), il::expr_const(1, 64)); block0.nop(); let block1 = cfg.new_block().unwrap(); block1.assign(il::scalar("x", 64), il::expr_scalar("x", 64)); block1.nop(); let block2 = cfg.new_block().unwrap(); block2.assign(il::scalar("x", 64), il::expr_scalar("x", 64)); cfg.set_entry(0).unwrap(); cfg.conditional_edge(0, 1, il::expr_scalar("x", 64)) .unwrap(); cfg.conditional_edge(1, 2, il::expr_scalar("x", 64)) .unwrap(); let mut versioning = ScalarVersioning::new(); versioning.start_new_scope(); cfg.rename_scalars(&mut versioning).unwrap(); // Expected: // x_1 = 1 // nop +---+ // --------- | (x_1) // x_2 = x_1 <---+ // nop +---+ // --------- | (x_2) // x_3 = x_2 <---+ let ssa_block0 = cfg.block(0).unwrap(); assert_eq!( ssa_block0.instruction(0).unwrap().operation(), &il::Operation::assign(scalar_ssa("x", 64, 1), il::expr_const(1, 64)) ); let ssa_block1 = cfg.block(1).unwrap(); assert_eq!( ssa_block1.instruction(0).unwrap().operation(), &il::Operation::assign(scalar_ssa("x", 64, 2), expr_scalar_ssa("x", 64, 1)) ); let ssa_block2 = cfg.block(2).unwrap(); assert_eq!( ssa_block2.instruction(0).unwrap().operation(), &il::Operation::assign(scalar_ssa("x", 64, 3), expr_scalar_ssa("x", 64, 2)) ); let ssa_edge01 = cfg.edge(0, 1).unwrap(); assert_eq!( ssa_edge01.condition().unwrap(), &expr_scalar_ssa("x", 64, 1) ); let ssa_edge12 = cfg.edge(1, 2).unwrap(); assert_eq!( ssa_edge12.condition().unwrap(), &expr_scalar_ssa("x", 64, 2) ); } #[test] fn test_renaming_of_incoming_edges_in_phi_nodes() { // Given: // block 0 // +---+ y = 1 +---+ // | | // v v // block 1 block 2 // x = 2 x = 4 // y = 3 + // | | // +-------+-------+ // | // v // block 3 // x = phi [x, 1] [x, 2] // y = phi [y, 1] [y, 2] let mut cfg = il::ControlFlowGraph::new(); let block0 = cfg.new_block().unwrap(); block0.assign(il::scalar("y", 64), il::expr_const(1, 64)); let block1 = cfg.new_block().unwrap(); block1.assign(il::scalar("x", 64), il::expr_const(2, 64)); block1.assign(il::scalar("y", 64), il::expr_const(3, 64)); let block2 = cfg.new_block().unwrap(); block2.assign(il::scalar("x", 64), il::expr_const(4, 64)); let mut phi_node_x = il::PhiNode::new(il::scalar("x", 64)); phi_node_x.add_incoming(il::scalar("x", 64), 1); phi_node_x.add_incoming(il::scalar("x", 64), 2); let mut phi_node_y = il::PhiNode::new(il::scalar("y", 64)); phi_node_y.add_incoming(il::scalar("y", 64), 1); phi_node_y.add_incoming(il::scalar("y", 64), 2); let block3 = cfg.new_block().unwrap(); block3.add_phi_node(phi_node_x); block3.add_phi_node(phi_node_y); cfg.set_entry(0).unwrap(); cfg.unconditional_edge(0, 1).unwrap(); cfg.unconditional_edge(0, 2).unwrap(); cfg.unconditional_edge(1, 3).unwrap(); cfg.unconditional_edge(2, 3).unwrap(); let mut versioning = ScalarVersioning::new(); versioning.start_new_scope(); cfg.rename_scalars(&mut versioning).unwrap(); // Expected: // block 0 // +---+ y_1 = 1 +---+ // | | // v v // block 1 block 2 // x_1 = 2 x_2 = 4 // y_2 = 3 + // | | // +--------+--------+ // | // v // block 3 // x_3 = phi [x_1, 1] [x_2, 2] // y_3 = phi [y_2, 1] [y_1, 2] let ssa_block3 = cfg.block(3).unwrap(); let ssa_phi_node_x = ssa_block3.phi_node(0).unwrap(); assert_eq!(ssa_phi_node_x.out(), &scalar_ssa("x", 64, 3)); assert_eq!( ssa_phi_node_x.incoming_scalar(1).unwrap(), &scalar_ssa("x", 64, 1) ); assert_eq!( ssa_phi_node_x.incoming_scalar(2).unwrap(), &scalar_ssa("x", 64, 2) ); let ssa_phi_node_y = ssa_block3.phi_node(1).unwrap(); assert_eq!(ssa_phi_node_y.out(), &scalar_ssa("y", 64, 3)); assert_eq!( ssa_phi_node_y.incoming_scalar(1).unwrap(), &scalar_ssa("y", 64, 2) ); assert_eq!( ssa_phi_node_y.incoming_scalar(2).unwrap(), &scalar_ssa("y", 64, 1) ); } #[test] fn test_insert_phi_nodes() { // Given: // | // v // +-------> block 0 // | | // | +---+---+ // | | | // | v v // | block 1 block 2 +---+ // | x = 0 | | // | | | | // | +---+---+ | // | | | // | v | // +------+ block 3 | // | | // v | // block 4 <-------+ // y = x let mut function = { let mut cfg = il::ControlFlowGraph::new(); // block0 { cfg.new_block().unwrap(); } // block1 { let block = cfg.new_block().unwrap(); block.assign(il::scalar("x", 64), il::expr_const(0, 64)); } // block2 { cfg.new_block().unwrap(); } // block3 { cfg.new_block().unwrap(); } // block4 { let block = cfg.new_block().unwrap(); block.assign(il::scalar("y", 64), il::expr_scalar("x", 64)); } cfg.unconditional_edge(0, 1).unwrap(); cfg.unconditional_edge(0, 2).unwrap(); cfg.unconditional_edge(1, 3).unwrap(); cfg.unconditional_edge(2, 3).unwrap(); cfg.unconditional_edge(2, 4).unwrap(); cfg.unconditional_edge(3, 0).unwrap(); cfg.unconditional_edge(3, 4).unwrap(); cfg.set_entry(0).unwrap(); il::Function::new(0, cfg) }; insert_phi_nodes(&mut function).unwrap(); // Expected: // | // v // +-------> block 0 // | x = phi [x, 3] [x, entry] // | | // | +---+---+ // | | | // | v v // | block 1 block 2 +---+ // | | | | // | +---+---+ | // | | | // | v | // +------+ block 3 | // x = phi [x, 1] [x, 2] | // | | // v | // block 4 <-------+ // x = phi [x, 3] [x, 2] let block0 = function.block(0).unwrap(); let block1 = function.block(1).unwrap(); let block2 = function.block(2).unwrap(); let block3 = function.block(3).unwrap(); let block4 = function.block(4).unwrap(); assert_eq!(block0.phi_nodes().len(), 1); assert_eq!(block1.phi_nodes().len(), 0); assert_eq!(block2.phi_nodes().len(), 0); assert_eq!(block3.phi_nodes().len(), 1); assert_eq!(block4.phi_nodes().len(), 1); let phi_node_block0 = block0.phi_node(0).unwrap(); assert_eq!(phi_node_block0.out(), &il::scalar("x", 64)); assert_eq!( phi_node_block0.incoming_scalar(3).unwrap(), &il::scalar("x", 64) ); assert_eq!( phi_node_block0.entry_scalar().unwrap(), &il::scalar("x", 64) ); let phi_node_block3 = block3.phi_node(0).unwrap(); assert_eq!(phi_node_block3.out(), &il::scalar("x", 64)); assert_eq!( phi_node_block3.incoming_scalar(1).unwrap(), &il::scalar("x", 64) ); assert_eq!( phi_node_block3.incoming_scalar(2).unwrap(), &il::scalar("x", 64) ); let phi_node_block4 = block4.phi_node(0).unwrap(); assert_eq!(phi_node_block4.out(), &il::scalar("x", 64)); assert_eq!( phi_node_block4.incoming_scalar(3).unwrap(), &il::scalar("x", 64) ); assert_eq!( phi_node_block4.incoming_scalar(2).unwrap(), &il::scalar("x", 64) ); } #[test] fn test_complete_ssa_transformation() { // Given: // | // v // +-------> block 0 // | | // | +---+---+ // | | | // | v v // | block 1 block 2 +---+ // | x = 0 tmp = x | // | | x = tmp | // | | | | // | +---+---+ | // | | | // | v | // +------+ block 3 | // x = x + x | // | | // v | // block 4 <-------+ // res = x let function = { let mut cfg = il::ControlFlowGraph::new(); // block0 { cfg.new_block().unwrap(); } // block1 { let block = cfg.new_block().unwrap(); block.assign(il::scalar("x", 64), il::expr_const(0, 64)); } // block2 { let block = cfg.new_block().unwrap(); block.assign(il::scalar("tmp", 64), il::expr_scalar("x", 64)); block.assign(il::scalar("x", 64), il::expr_scalar("tmp", 64)); } // block3 { let block = cfg.new_block().unwrap(); block.assign( il::scalar("x", 64), il::Expression::add(il::expr_scalar("x", 64), il::expr_scalar("x", 64)) .unwrap(), ); } // block4 { let block = cfg.new_block().unwrap(); block.assign(il::scalar("res", 64), il::expr_scalar("x", 64)); } cfg.unconditional_edge(0, 1).unwrap(); cfg.unconditional_edge(0, 2).unwrap(); cfg.unconditional_edge(1, 3).unwrap(); cfg.unconditional_edge(2, 3).unwrap(); cfg.unconditional_edge(2, 4).unwrap(); cfg.unconditional_edge(3, 0).unwrap(); cfg.unconditional_edge(3, 4).unwrap(); cfg.set_entry(0).unwrap(); il::Function::new(0, cfg) }; let ssa_function = ssa_transformation(&function).unwrap(); // Expected: // | // v // +-------> block 0 // | x1 = phi [x5, 3] [x, entry] // | | // | +---+---+ // | | | // | v v // | block 1 block 2 +---+ // | x2 = 0 tmp1 = x1 | // | | x3 = tmp1 | // | | | | // | +---+---+ | // | | | // | v | // +------+ block 3 | // x4 = phi [x2, 1] [x3, 2] | // x5 = x4 + x4 | // | | // v | // block 4 <-------+ // x6 = phi [x5, 3] [x3, 2] // res1 = x6 let expected_function = { let mut cfg = il::ControlFlowGraph::new(); // block0 { let block = cfg.new_block().unwrap(); block.add_phi_node({ let mut phi_node = il::PhiNode::new(scalar_ssa("x", 64, 1)); phi_node.add_incoming(scalar_ssa("x", 64, 5), 3); phi_node.set_entry_scalar(il::scalar("x", 64)); phi_node }); } // block1 { let block = cfg.new_block().unwrap(); block.assign(scalar_ssa("x", 64, 2), il::expr_const(0, 64)); } // block2 { let block = cfg.new_block().unwrap(); block.assign(scalar_ssa("tmp", 64, 1), expr_scalar_ssa("x", 64, 1)); block.assign(scalar_ssa("x", 64, 3), expr_scalar_ssa("tmp", 64, 1)); } // block3 { let block = cfg.new_block().unwrap(); block.assign( scalar_ssa("x", 64, 5), il::Expression::add(expr_scalar_ssa("x", 64, 4), expr_scalar_ssa("x", 64, 4)) .unwrap(), ); block.add_phi_node({ let mut phi_node = il::PhiNode::new(scalar_ssa("x", 64, 4)); phi_node.add_incoming(scalar_ssa("x", 64, 2), 1); phi_node.add_incoming(scalar_ssa("x", 64, 3), 2); phi_node }); } // block4 { let block = cfg.new_block().unwrap(); block.assign(scalar_ssa("res", 64, 1), expr_scalar_ssa("x", 64, 6)); block.add_phi_node({ let mut phi_node = il::PhiNode::new(scalar_ssa("x", 64, 6)); phi_node.add_incoming(scalar_ssa("x", 64, 5), 3); phi_node.add_incoming(scalar_ssa("x", 64, 3), 2); phi_node }); } cfg.unconditional_edge(0, 1).unwrap(); cfg.unconditional_edge(0, 2).unwrap(); cfg.unconditional_edge(1, 3).unwrap(); cfg.unconditional_edge(2, 3).unwrap(); cfg.unconditional_edge(2, 4).unwrap(); cfg.unconditional_edge(3, 0).unwrap(); cfg.unconditional_edge(3, 4).unwrap(); cfg.set_entry(0).unwrap(); il::Function::new(0, cfg) }; assert_eq!(ssa_function, expected_function); } }
use crate::schema::atividades_administrativas; use chrono::NaiveDateTime; #[derive(Serialize, Deserialize, Queryable)] pub struct AtividadesAdministrativas { pub id: i32, pub id_professor: i32, pub atividade: String, pub numero_portaria: i32, pub ano_portaria: i32, pub created_at: NaiveDateTime, pub updated_at: NaiveDateTime, } #[derive(Deserialize, Insertable)] #[table_name = "atividades_administrativas"] pub struct InsertableAtividadeAdministrativa { pub id_professor: i32, pub atividade: String, pub numero_portaria: i32, pub ano_portaria: i32, } /* atividades_administrativas (id) { id -> Integer, id_professor -> Integer, atividade -> Varchar, numero_portaria -> Integer, ano_portaria -> Integer, created_at -> Datetime, updated_at -> Datetime, } */
//! Account commitment managment #[cfg(not(feature = "std"))] use alloc::vec::Vec; #[cfg(not(feature = "std"))] use alloc::{collections::btree_map as map, collections::BTreeMap as Map, collections::BTreeSet as Set}; use bigint::{Address, M256, U256}; #[cfg(not(feature = "std"))] use core::cell::RefCell; #[cfg(feature = "std")] use std::cell::RefCell; #[cfg(feature = "std")] use std::collections::{hash_map as map, HashMap as Map, HashSet as Set}; #[cfg(not(feature = "std"))] use alloc::rc::Rc; #[cfg(feature = "std")] use std::rc::Rc; use crate::{ errors::{CommitError, RequireError}, AccountPatch, }; /// Internal representation of an account storage. It will return a /// `RequireError` if trying to access non-existing storage. #[derive(Debug, Clone)] pub struct Storage { partial: bool, address: Address, storage: Map<U256, M256>, } impl Into<Map<U256, M256>> for Storage { fn into(self) -> Map<U256, M256> { self.storage } } impl Storage { /// Create a new storage. fn new(address: Address, partial: bool) -> Self { Storage { partial, address, storage: Map::new(), } } /// Commit a value into the storage. fn commit(&mut self, index: U256, value: M256) -> Result<(), CommitError> { if !self.partial { return Err(CommitError::InvalidCommitment); } if self.storage.contains_key(&index) { return Err(CommitError::AlreadyCommitted); } self.storage.insert(index, value); Ok(()) } /// Read a value from the storage. pub fn read(&self, index: U256) -> Result<M256, RequireError> { match self.storage.get(&index) { Some(&v) => Ok(v), None => { if self.partial { Err(RequireError::AccountStorage(self.address, index)) } else { Ok(M256::zero()) } } } } /// Write a value into the storage. pub fn write(&mut self, index: U256, value: M256) -> Result<(), RequireError> { if !self.storage.contains_key(&index) && self.partial { return Err(RequireError::AccountStorage(self.address, index)); } self.storage.insert(index, value); Ok(()) } /// Return the number of changed/full items in storage. #[inline] pub fn len(&self) -> usize { self.storage.len() } /// Return true if storage is empty, false otherwise #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } } #[derive(Debug, Clone)] /// A single account commitment. pub enum AccountCommitment { /// Full account commitment. The client that committed account /// should not change the account in other EVMs if it decides to /// accept the result. Full { /// Nonce of the account. nonce: U256, /// Account address. address: Address, /// Account balance. balance: U256, /// Code associated with this account. code: Rc<Vec<u8>>, }, /// Commit only code of the account. The client can keep changing /// it in other EVMs if the code remains unchanged. Code { /// Account address. address: Address, /// Code associated with this account. code: Rc<Vec<u8>>, }, /// Commit a storage. Must be used given a full account. Storage { /// Account address. address: Address, /// Account storage index. index: U256, /// Value at the given account storage index. value: M256, }, /// Indicate that an account does not exist, or is a suicided /// account. Nonexist(Address), } impl AccountCommitment { /// Address of this account commitment. pub fn address(&self) -> Address { match *self { AccountCommitment::Full { address, .. } => address, AccountCommitment::Code { address, .. } => address, AccountCommitment::Storage { address, .. } => address, AccountCommitment::Nonexist(address) => address, } } } #[derive(Debug, Clone)] /// Represents an account. This is usually returned by the EVM. pub enum AccountChange { /// A full account. The client is expected to replace its own account state with this. Full { /// Account nonce. nonce: U256, /// Account address. address: Address, /// Account balance. balance: U256, /// Change storage with given indexes and values. changing_storage: Storage, /// Code associated with this account. code: Rc<Vec<u8>>, }, /// Only balance is changed, and it is increasing for this address. IncreaseBalance(Address, U256), /// Create or delete a (new) account. Create { /// Account nonce. nonce: U256, /// Account address. address: Address, /// Account balance. balance: U256, /// All storage values of this account, with given indexes and values. storage: Storage, /// Code associated with this account. code: Rc<Vec<u8>>, }, /// The account should remain nonexist, or should be deleted if /// exists. Nonexist(Address), } impl AccountChange { /// Address of this account. pub fn address(&self) -> Address { match *self { AccountChange::Full { address, .. } => address, AccountChange::IncreaseBalance(address, _) => address, AccountChange::Create { address, .. } => address, AccountChange::Nonexist(address) => address, } } } #[derive(Debug)] /// A struct that manages the current account state for one EVM. pub struct AccountState<'a, A: AccountPatch> { accounts: Map<Address, AccountChange>, orig_storage: RefCell<Map<Address, Storage>>, codes: Map<Address, Rc<Vec<u8>>>, account_patch: &'a A, } impl<'a, A: AccountPatch> AccountState<'a, A> { /// Create new AccountState configured with AccountPatch pub fn new(account_patch: &'a A) -> Self { Self { accounts: Map::new(), codes: Map::new(), orig_storage: RefCell::new(Map::new()), account_patch, } } /// Clone with new AccountPatch pub fn derive_from<'b>(account_patch: &'a A, prev: &AccountState<'b, A>) -> Self { Self { accounts: prev.accounts.clone(), orig_storage: prev.orig_storage.clone(), codes: prev.codes.clone(), account_patch, } } } impl<'a, A: AccountPatch> Clone for AccountState<'a, A> { fn clone(&self) -> Self { Self { accounts: self.accounts.clone(), orig_storage: self.orig_storage.clone(), codes: self.codes.clone(), account_patch: self.account_patch, } } } fn is_empty(nonce: U256, balance: U256, code: &[u8]) -> bool { nonce == U256::zero() && balance == U256::zero() && code.is_empty() } impl<'a, A: AccountPatch> AccountState<'a, A> { fn insert_account(&mut self, account: AccountChange) { match account { AccountChange::Full { nonce, address, balance, changing_storage, code, } => { if (!self.account_patch.empty_considered_exists()) && is_empty(nonce, balance, &code) { self.accounts.insert(address, AccountChange::Nonexist(address)); } else { self.accounts.insert( address, AccountChange::Full { nonce, address, balance, changing_storage, code, }, ); } } AccountChange::Create { nonce, address, balance, storage, code, } => { if (!self.account_patch.empty_considered_exists()) && is_empty(nonce, balance, &code) { self.accounts.insert(address, AccountChange::Nonexist(address)); } else { self.accounts.insert( address, AccountChange::Create { nonce, address, balance, storage, code, }, ); } } AccountChange::Nonexist(address) => { self.accounts.insert(address, AccountChange::Nonexist(address)); } AccountChange::IncreaseBalance(address, balance) => { if self.account_patch.allow_partial_change() { self.accounts .insert(address, AccountChange::IncreaseBalance(address, balance)); } else { panic!() } } } } /// Returns all fetched or modified addresses. pub fn used_addresses(&self) -> Set<Address> { let mut set = Set::new(); for account in self.accounts() { set.insert(account.address()); } for address in self.codes.keys() { set.insert(*address); } set } /// Returns all accounts right now in this account state. pub fn accounts(&self) -> map::Values<Address, AccountChange> { self.accounts.values() } /// Returns Ok(()) if a full account is in this account /// state. Otherwise raise a `RequireError`. pub fn require(&self, address: Address) -> Result<(), RequireError> { match self.accounts.get(&address) { Some(&AccountChange::Full { .. }) | Some(&AccountChange::Create { .. }) | Some(&AccountChange::Nonexist(_)) => Ok(()), _ => Err(RequireError::Account(address)), } } /// Returns Ok(()) if either a full account or a partial code /// account is in this account state. Otherwise raise a /// `RequireError`. pub fn require_code(&self, address: Address) -> Result<(), RequireError> { if self.codes.contains_key(&address) { Ok(()) } else { match self.accounts.get(&address) { Some(&AccountChange::Full { .. }) | Some(&AccountChange::Create { .. }) | Some(&AccountChange::Nonexist(_)) => Ok(()), _ => Err(RequireError::AccountCode(address)), } } } /// Returns Ok(()) if the storage exists in the VM. Otherwise /// raise a `RequireError`. pub fn require_storage(&self, address: Address, index: U256) -> Result<(), RequireError> { self.storage_read(address, index).and_then(|_| Ok(())) } /// Commit an account commitment into this account state. pub fn commit(&mut self, commitment: AccountCommitment) -> Result<(), CommitError> { match commitment { AccountCommitment::Full { nonce, address, balance, code, } => { let account = if self.accounts.contains_key(&address) { match self.accounts.remove(&address).unwrap() { AccountChange::Full { .. } | AccountChange::Create { .. } | AccountChange::Nonexist(_) => { return Err(CommitError::AlreadyCommitted); } AccountChange::IncreaseBalance(address, topup) => AccountChange::Full { nonce, address, balance: balance + topup, changing_storage: Storage::new(address, true), code, }, } } else { AccountChange::Full { nonce, address, balance, changing_storage: Storage::new(address, true), code, } }; self.insert_account(account); self.codes.remove(&address); } AccountCommitment::Code { address, code } => { if self.accounts.contains_key(&address) || self.codes.contains_key(&address) { return Err(CommitError::AlreadyCommitted); } self.codes.insert(address, code); } AccountCommitment::Storage { address, index, value } => { match self.accounts.get_mut(&address) { Some(&mut AccountChange::Full { ref mut changing_storage, .. }) => { changing_storage.commit(index, value)?; } _ => { return Err(CommitError::InvalidCommitment); } } self.orig_storage .borrow_mut() .entry(address) .or_insert_with(|| Storage::new(address, true)) .commit(index, value)? } AccountCommitment::Nonexist(address) => { let account = if self.accounts.contains_key(&address) { match self.accounts.remove(&address).unwrap() { AccountChange::Full { .. } | AccountChange::Create { .. } | AccountChange::Nonexist(_) => { return Err(CommitError::AlreadyCommitted); } AccountChange::IncreaseBalance(address, topup) => AccountChange::Create { nonce: self.account_patch.initial_nonce(), address, balance: topup, storage: Storage::new(address, false), code: Rc::new(Vec::new()), }, } } else { AccountChange::Nonexist(address) }; self.insert_account(account); self.codes.remove(&address); } } Ok(()) } /// Test whether an account at given address is considered /// existing. pub fn exists(&self, address: Address) -> Result<bool, RequireError> { match self.accounts.get(&address) { Some(&AccountChange::Create { nonce, balance, ref code, .. }) => Ok(if self.account_patch.empty_considered_exists() { true } else { !is_empty(nonce, balance, code) }), Some(&AccountChange::Full { nonce, balance, ref code, .. }) => Ok(if self.account_patch.empty_considered_exists() { true } else { !is_empty(nonce, balance, code) }), Some(&AccountChange::Nonexist(_)) => Ok(false), Some(&AccountChange::IncreaseBalance(address, topup)) => { if self.account_patch.empty_considered_exists() || topup > U256::zero() { Ok(true) } else { Err(RequireError::Account(address)) } } _ => Err(RequireError::Account(address)), } } /// Find code by its address in this account state. If the search /// failed, returns a `RequireError`. pub fn code(&self, address: Address) -> Result<Rc<Vec<u8>>, RequireError> { self.code_opt_nonexist(address) .map(|opt_code| opt_code.unwrap_or_else(|| Rc::new(Vec::new()))) } /// Find code of account that may not exist. If search /// failed, returns a `RequireError` pub fn code_opt_nonexist(&self, address: Address) -> Result<Option<Rc<Vec<u8>>>, RequireError> { if self.accounts.contains_key(&address) { match self.accounts[&address] { AccountChange::Full { ref code, .. } | AccountChange::Create { ref code, .. } => { return Ok(Some(code.clone())); } AccountChange::Nonexist(_) => return Ok(None), AccountChange::IncreaseBalance(_, _) => (), } } if self.codes.contains_key(&address) { Ok(Some(self.codes[&address].clone())) } else { Err(RequireError::AccountCode(address)) } } /// Find nonce by its address in this account state. If the search /// failed, returns a `RequireError`. pub fn nonce(&self, address: Address) -> Result<U256, RequireError> { if self.accounts.contains_key(&address) { match self.accounts[&address] { AccountChange::Full { nonce, .. } => return Ok(nonce), AccountChange::Create { nonce, .. } => return Ok(nonce), AccountChange::Nonexist(_) => { return Ok(self.account_patch.initial_nonce()); } _ => (), } } Err(RequireError::Account(address)) } /// Find balance by its address in this account state. If the /// search failed, returns a `RequireError`. pub fn balance(&self, address: Address) -> Result<U256, RequireError> { if self.accounts.contains_key(&address) { match self.accounts[&address] { AccountChange::Full { balance, .. } => return Ok(balance), AccountChange::Create { balance, .. } => return Ok(balance), AccountChange::Nonexist(_) => { return Ok(U256::zero()); } _ => (), } } Err(RequireError::Account(address)) } /// Read a value from an account storage. pub fn storage_read(&self, address: Address, index: U256) -> Result<M256, RequireError> { if self.accounts.contains_key(&address) { match self.accounts[&address] { AccountChange::Full { ref changing_storage, .. } => return changing_storage.read(index), AccountChange::Create { ref storage, .. } => return storage.read(index), AccountChange::Nonexist(_) => return Ok(M256::zero()), _ => (), } } Err(RequireError::Account(address)) } /// Read an original (pre-execution) value from an account storage pub fn storage_read_orig(&self, address: Address, index: U256) -> Result<M256, RequireError> { let mut orig_storage = self.orig_storage.borrow_mut(); let orig_account_storage = orig_storage .entry(address) .or_insert_with(|| Storage::new(address, true)); orig_account_storage.read(index) } /// Write a value from an account storage. The account will be /// created if it is nonexist. pub fn storage_write(&mut self, address: Address, index: U256, value: M256) -> Result<(), RequireError> { if self.accounts.contains_key(&address) { match self.accounts.get_mut(&address).unwrap() { AccountChange::Full { ref mut changing_storage, .. } => return changing_storage.write(index, value), AccountChange::Create { ref mut storage, .. } => return storage.write(index, value), val => { let is_nonexist = match val { AccountChange::Nonexist(_) => true, _ => false, }; if is_nonexist { let mut storage = Storage::new(address, false); let ret = storage.write(index, value); *val = AccountChange::Create { nonce: self.account_patch.initial_nonce(), address, balance: U256::zero(), storage, code: Rc::new(Vec::new()), }; return ret; } } } } Err(RequireError::Account(address)) } /// Create a new account (that should not yet have existed /// before). pub fn create(&mut self, address: Address, topup: U256) -> Result<(), RequireError> { let account = if self.accounts.contains_key(&address) { match self.accounts.remove(&address).unwrap() { AccountChange::Full { balance, .. } => AccountChange::Create { address, code: Rc::new(Vec::new()), nonce: self.account_patch.initial_create_nonce(), balance: balance + topup, storage: Storage::new(address, false), }, AccountChange::Create { balance, .. } => AccountChange::Create { address, code: Rc::new(Vec::new()), nonce: self.account_patch.initial_create_nonce(), balance: balance + topup, storage: Storage::new(address, false), }, AccountChange::Nonexist(_) => AccountChange::Create { address, code: Rc::new(Vec::new()), nonce: self.account_patch.initial_create_nonce(), balance: topup, storage: Storage::new(address, false), }, _ => { // Although creation will clean up storage and // code, the balance will be added if it was // existing in prior. So if it is IncreaseBalance // or DecreaseBalance, we need to ask for the // account first. return Err(RequireError::Account(address)); } } } else { return Err(RequireError::Account(address)); }; self.codes.remove(&address); self.insert_account(account); Ok(()) } /// Deposit code in to a created account. Only usable in a newly /// created account. pub fn code_deposit(&mut self, address: Address, new_code: Rc<Vec<u8>>) { match self.accounts.get_mut(&address).unwrap() { AccountChange::Create { ref mut code, .. } => { *code = new_code; } _ => panic!(), } } /// Increase the balance of an account. The account will be /// created if it is nonexist in the beginning. pub fn increase_balance(&mut self, address: Address, topup: U256) { let account = match self.accounts.remove(&address) { Some(AccountChange::Full { address, balance, changing_storage, code, nonce, }) => AccountChange::Full { address, balance: balance + topup, changing_storage, code, nonce, }, Some(AccountChange::IncreaseBalance(address, balance)) => { AccountChange::IncreaseBalance(address, balance + topup) } Some(AccountChange::Create { address, balance, storage, code, nonce, }) => AccountChange::Create { address, balance: balance + topup, storage, code, nonce, }, Some(AccountChange::Nonexist(address)) => AccountChange::Create { nonce: self.account_patch.initial_nonce(), address, balance: topup, storage: Storage::new(address, false), code: Rc::new(Vec::new()), }, None => AccountChange::IncreaseBalance(address, topup), }; self.insert_account(account); } /// Decrease the balance of an account. The account will be /// created if it is nonexist in the beginning. pub fn decrease_balance(&mut self, address: Address, withdraw: U256) { let account = match self.accounts.remove(&address) { Some(AccountChange::Full { address, balance, changing_storage, code, nonce, }) => AccountChange::Full { address, balance: balance - withdraw, changing_storage, code, nonce, }, Some(AccountChange::Create { address, balance, storage, code, nonce, }) => AccountChange::Create { address, balance: balance - withdraw, storage, code, nonce, }, Some(AccountChange::IncreaseBalance(_, _)) => panic!(), Some(AccountChange::Nonexist(_)) => panic!(), None => panic!(), }; self.insert_account(account); } /// Set nonce of an account. If the account is not already /// commited, returns a `RequireError`. The account will be /// created if it is nonexist in the beginning. pub fn set_nonce(&mut self, address: Address, new_nonce: U256) -> Result<(), RequireError> { match self.accounts.get_mut(&address) { Some(&mut AccountChange::Full { ref mut nonce, .. }) => { *nonce = new_nonce; Ok(()) } Some(&mut AccountChange::Create { ref mut nonce, .. }) => { *nonce = new_nonce; Ok(()) } Some(val) => { let is_nonexist = match val { AccountChange::Nonexist(_) => true, _ => false, }; if is_nonexist { *val = AccountChange::Create { nonce: new_nonce, address, balance: U256::zero(), storage: Storage::new(address, false), code: Rc::new(Vec::new()), }; Ok(()) } else { Err(RequireError::Account(address)) } } None => Err(RequireError::Account(address)), } } /// Delete an account from this account state. The account is set /// to null. pub fn remove(&mut self, address: Address) -> Result<(), RequireError> { self.codes.remove(&address); self.insert_account(AccountChange::Nonexist(address)); Ok(()) } }
use cranelift_entity::{self as entity, entity_impl}; use firefly_diagnostics::SourceSpan; use firefly_syntax_base::Type; use super::{Block, Inst}; pub type ValueList = entity::EntityList<Value>; pub type ValueListPool = entity::ListPool<Value>; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Value(u32); entity_impl!(Value, "v"); #[derive(Debug, Clone)] pub enum ValueData { Inst { ty: Type, num: u16, inst: Inst, }, Param { ty: Type, num: u16, block: Block, span: SourceSpan, }, } impl ValueData { pub fn ty(&self) -> Type { match self { Self::Inst { ty, .. } | Self::Param { ty, .. } => ty.clone(), } } pub fn set_type(&mut self, ty: Type) { match self { Self::Inst { ty: ref mut prev_ty, .. } => *prev_ty = ty, Self::Param { ty: ref mut prev_ty, .. } => *prev_ty = ty, } } } pub struct Values<'a> { pub(super) inner: entity::Iter<'a, Value, ValueData>, } impl<'a> Iterator for Values<'a> { type Item = Value; fn next(&mut self) -> Option<Self::Item> { self.inner.by_ref().next().map(|kv| kv.0) } }
use std::path::Path; fn main() { assert_eq!(Path::new("/tmp/ok").exists(), false); }
extern crate ndarray; use ndarray::prelude::*; use std::time::Instant; #[derive(Debug)] struct WGraph { adj_matrix: ndarray::prelude::Array2<f64>, visited: ndarray::prelude::Array1<f64>, size: i32, } impl WGraph { fn add_biedge(&mut self, source: usize, destination: usize, weight: f64) { self.adj_matrix[[source - 1, destination - 1]] = weight; self.adj_matrix[[destination - 1, source - 1]] = weight; } fn find_nearest(&mut self, current: usize) -> usize { let mut min: f64 = 0.0; let mut index: usize = 0; let _size = self.size; for i in 0usize..(_size as usize) { if self.adj_matrix[[current, i]] != 0.0 { if min == 0.0 && self.visited[Ix1(i)] == 0.0 { min = self.adj_matrix[[current, i]]; index = i; } if self.adj_matrix[[current, i]] < min && self.visited[Ix1(i)] == 0.0 { min = self.adj_matrix[[current, i]]; index = i; } } } index } fn shortest_path(&mut self, source: usize, destination: usize) -> f64 { let mut current = source - 1; self.visited[current] = 1.0; let _size = self.size; let mut distances = ndarray::Array1::<f64>::zeros(Ix1(_size as usize)); for i in 0usize..(_size as usize) { if self.adj_matrix[[current, i]] != 0.0 { distances[Ix1(i)] = self.adj_matrix[[current, i]]; } } for _i in 0usize..(_size as usize) { for j in 0usize..(_size as usize) { if self.adj_matrix[[current, j]] != 0.0 { if distances[Ix1(j)] == 0.0 && self.visited[Ix1(j)] == 0.0 { distances[Ix1(j)] = self.adj_matrix[[current, j]] + distances[current]; self.visited[current] = 1.0; } if distances[Ix1(j)] != 0.0 && ((self.adj_matrix[[current, j]] + distances[Ix1(current)] < distances[Ix1(j)]) && self.visited[Ix1(j)] == 0.0) { distances[Ix1(j)] = self.adj_matrix[[current, j]] + distances[Ix1(current)]; self.visited[ndarray::Ix1(current)] = 1.0; } } } current = WGraph::find_nearest(self, current); } distances[ndarray::Ix1(destination - 1)] } } fn main() { let before = Instant::now(); let mut graph = WGraph { adj_matrix: ndarray::Array2::<f64>::zeros((5, 5)), visited: ndarray::Array1::<f64>::zeros(5), size: 5, }; graph.add_biedge(1, 2, 6.0); graph.add_biedge(1, 4, 1.0); graph.add_biedge(4, 2, 2.0); graph.add_biedge(4, 5, 1.0); graph.add_biedge(5, 2, 2.0); graph.add_biedge(3, 2, 5.0); graph.add_biedge(3, 5, 5.0); println!("{}", graph.shortest_path(1, 3)); println!("Elapsed time: {:.2?}", before.elapsed()); }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::labels::{NodeId, NodeLinkId}; use failure::Error; use std::collections::{BTreeMap, BinaryHeap}; use std::time::Duration; /// Describes a node in the overnet mesh #[derive(Debug)] pub struct NodeDescription { /// Services exposed by this node. pub services: Vec<String>, } impl Default for NodeDescription { fn default() -> Self { NodeDescription { services: Vec::new() } } } /// Collects all information about a node in one place #[derive(Debug)] struct Node { links: BTreeMap<NodeLinkId, Link>, desc: NodeDescription, established: bool, } /// During pathfinding, collects the shortest path so far to a node #[derive(Debug, Clone, Copy)] struct NodeProgress { round_trip_time: Duration, outgoing_link: NodeLinkId, } /// Describes the state of a link #[derive(Debug)] pub struct LinkDescription { /// Current round trip time estimate for this link pub round_trip_time: Duration, } /// Collects all information about one link on one node /// Links that are owned by NodeTable should remain owned (mutable references should not be given /// out) #[derive(Debug)] pub struct Link { /// Destination node for this link pub to: NodeId, /// Description of this link pub desc: LinkDescription, } /// Notification of a new version of the node table being available. pub trait NodeStateCallback { /// Called when the node state version is different to the one supplied at the initiation of /// monitoring. fn trigger(&mut self, new_version: u64, node_table: &NodeTable) -> Result<(), Error>; } /// Tracks the current version of the node table, and callbacks that would like to be informed when /// that changes. struct VersionTracker { version: u64, pending_callbacks: Vec<Box<dyn NodeStateCallback>>, triggered_callbacks: Vec<Box<dyn NodeStateCallback>>, } impl VersionTracker { /// New version tracker with an initial non-zero version stamp. fn new() -> Self { Self { pending_callbacks: Vec::new(), triggered_callbacks: Vec::new(), version: 1 } } /// Query for a new version (given the last version seen). /// Trigger on the next flush if last_version == self.version. fn post_query(&mut self, last_version: u64, cb: Box<dyn NodeStateCallback>) { if last_version < self.version { self.triggered_callbacks.push(cb); } else { self.pending_callbacks.push(cb); } } /// Move to the next version. fn incr_version(&mut self) { self.version += 1; self.triggered_callbacks.extend(self.pending_callbacks.drain(..)); } /// Returns the current version and the (now flushed) triggered callbacks fn take_triggered_callbacks(&mut self) -> (u64, Vec<Box<dyn NodeStateCallback>>) { let callbacks = std::mem::replace(&mut self.triggered_callbacks, Vec::new()); (self.version, callbacks) } } /// Table of all nodes (and links between them) known to an instance pub struct NodeTable { root_node: NodeId, nodes: BTreeMap<NodeId, Node>, version_tracker: VersionTracker, } impl NodeTable { /// Create a new node table rooted at `root_node` pub fn new(root_node: NodeId) -> NodeTable { let mut table = NodeTable { root_node, nodes: BTreeMap::new(), version_tracker: VersionTracker::new() }; table.get_or_create_node_mut(root_node).established = true; table } /// Convert the node table to a string representing a directed graph for graphviz visualization pub fn digraph_string(&self) -> String { let mut s = "digraph G {\n".to_string(); s += &format!(" {} [shape=diamond];\n", self.root_node.0); for (id, node) in self.nodes.iter() { for (link_id, link) in node.links.iter() { s += &format!( " {} -> {} [label=\"[{}] rtt={:?}\"];\n", id.0, link.to.0, link_id.0, link.desc.round_trip_time ); } } s += "}\n"; s } /// Query for a new version (given the last version seen). /// Trigger on the next flush if `last_version` == the current version. pub fn post_query(&mut self, last_version: u64, cb: Box<dyn NodeStateCallback>) { self.version_tracker.post_query(last_version, cb); } /// Execute any completed version watch callbacks. pub fn trigger_callbacks(&mut self) { let (version, callbacks) = self.version_tracker.take_triggered_callbacks(); for mut cb in callbacks { if let Err(e) = cb.trigger(version, &self) { log::warn!("Node state callback failed: {:?}", e); } } } fn get_or_create_node_mut(&mut self, node_id: NodeId) -> &mut Node { let version_tracker = &mut self.version_tracker; let mut was_new = false; let node = self.nodes.entry(node_id).or_insert_with(|| { version_tracker.incr_version(); was_new = true; Node { links: BTreeMap::new(), desc: NodeDescription::default(), established: false } }); node } /// Collates and returns all services available pub fn nodes(&self) -> impl Iterator<Item = NodeId> + '_ { self.nodes.iter().map(|(id, _)| *id) } /// Return the services supplied by some `node_id` pub fn node_services(&self, node_id: NodeId) -> &[String] { self.nodes.get(&node_id).map(|node| node.desc.services.as_slice()).unwrap_or(&[]) } /// Returns all links from a single node pub fn node_links( &self, node_id: NodeId, ) -> Option<impl Iterator<Item = (&NodeLinkId, &Link)> + '_> { self.nodes.get(&node_id).map(|node| node.links.iter()) } /// Update a single node pub fn update_node(&mut self, node_id: NodeId, desc: NodeDescription) { let node = self.get_or_create_node_mut(node_id); node.desc = desc; self.version_tracker.incr_version(); log::trace!("{}", self.digraph_string()); } /// Is a connection established to some node? pub fn is_established(&self, node_id: NodeId) -> bool { self.nodes.get(&node_id).map_or(false, |node| node.established) } /// Mark a node as being established pub fn mark_established(&mut self, node_id: NodeId) { log::trace!("{:?} mark node established: {:?}", self.root_node, node_id); let node = self.get_or_create_node_mut(node_id); if node.established { return; } node.established = true; self.version_tracker.incr_version(); } /// Mention that a node exists pub fn mention_node(&mut self, node_id: NodeId) { self.get_or_create_node_mut(node_id); } /// Update a single link on a node. pub fn update_link( &mut self, from: NodeId, to: NodeId, link_id: NodeLinkId, desc: LinkDescription, ) { log::trace!( "update_link: from:{:?} to:{:?} link_id:{:?} desc:{:?}", from, to, link_id, desc ); assert_ne!(from, to); self.get_or_create_node_mut(to); self.get_or_create_node_mut(from).links.insert(link_id, Link { to, desc }); log::trace!("{}", self.digraph_string()); } /// Build a routing table for our node based on current link data pub fn build_routes(&self) -> impl Iterator<Item = (NodeId, NodeLinkId)> { let mut todo = BinaryHeap::new(); let mut progress = BTreeMap::<NodeId, NodeProgress>::new(); for (link_id, link) in self.nodes.get(&self.root_node).unwrap().links.iter() { if link.to == self.root_node { continue; } todo.push(link.to); let new_progress = NodeProgress { round_trip_time: link.desc.round_trip_time, outgoing_link: *link_id, }; progress .entry(link.to) .and_modify(|p| { if p.round_trip_time > new_progress.round_trip_time { *p = new_progress; } }) .or_insert_with(|| new_progress); } log::trace!("BUILD START: progress={:?} todo={:?}", progress, todo); while let Some(from) = todo.pop() { log::trace!("STEP {:?}: progress={:?} todo={:?}", from, progress, todo); let progress_from = progress.get(&from).unwrap().clone(); for (_, link) in self.nodes.get(&from).unwrap().links.iter() { if link.to == self.root_node { continue; } let new_progress = NodeProgress { round_trip_time: progress_from.round_trip_time + link.desc.round_trip_time, outgoing_link: progress_from.outgoing_link, }; progress .entry(link.to) .and_modify(|p| { if p.round_trip_time > new_progress.round_trip_time { *p = new_progress; todo.push(link.to); } }) .or_insert_with(|| { todo.push(link.to); new_progress }); } } log::trace!("DONE: progress={:?} todo={:?}", progress, todo); progress .into_iter() .map(|(node_id, NodeProgress { outgoing_link: link_id, .. })| (node_id, link_id)) } } #[cfg(test)] mod test { use super::*; fn remove_item<T: Eq>(value: &T, from: &mut Vec<T>) -> bool { let len = from.len(); for i in 0..len { if from[i] == *value { from.remove(i); return true; } } return false; } fn construct_node_table_from_links(links: &[(u64, u64, u64, u64)]) -> NodeTable { let mut node_table = NodeTable::new(1.into()); for (from, to, link_id, rtt) in links { node_table.update_link( (*from).into(), (*to).into(), (*link_id).into(), LinkDescription { round_trip_time: Duration::from_millis(*rtt) }, ); } node_table } fn is_outcome(mut got: Vec<(NodeId, NodeLinkId)>, outcome: &[(u64, u64)]) -> bool { let mut result = true; for (node_id, link_id) in outcome { if !remove_item(&((*node_id).into(), (*link_id).into()), &mut got) { log::trace!("Expected outcome not found: {}#{}", node_id, link_id); result = false; } } for (node_id, link_id) in got { log::trace!("Unexpected outcome: {}#{}", node_id.0, link_id.0); result = false; } result } fn builds_route_ok(links: &[(u64, u64, u64, u64)], outcome: &[(u64, u64)]) -> bool { log::trace!("TEST: {:?} --> {:?}", links, outcome); let node_table = construct_node_table_from_links(links); let built: Vec<(NodeId, NodeLinkId)> = node_table.build_routes().collect(); let r = is_outcome(built.clone(), outcome); if !r { log::trace!("NODE_TABLE: {:?}", node_table.nodes); log::trace!("BUILT: {:?}", built); } r } #[test] fn test_build_routes() { assert!(builds_route_ok(&[(1, 2, 1, 10), (2, 1, 123, 5)], &[(2, 1)])); assert!(builds_route_ok( &[ (1, 2, 1, 10), (2, 1, 123, 5), (1, 3, 2, 10), (3, 1, 133, 1), (2, 3, 7, 88), (3, 2, 334, 23) ], &[(2, 1), (3, 2)] )); assert!(builds_route_ok( &[ (1, 2, 1, 10), (2, 1, 123, 5), (1, 3, 2, 1000), (3, 1, 133, 1), (2, 3, 7, 88), (3, 2, 334, 23) ], &[(2, 1), (3, 1)] )); } #[test] fn test_services() { let mut node_table = NodeTable::new(1.into()); node_table.update_node( 2.into(), NodeDescription { services: vec!["hello".to_string()], ..Default::default() }, ); assert_eq!(node_table.nodes().collect::<Vec<NodeId>>().as_slice(), [1.into(), 2.into()]); assert_eq!(node_table.node_services(2.into()), ["hello".to_string()]); assert_eq!(node_table.node_services(3.into()), Vec::<String>::new().as_slice()); } }
#[doc = "Reader of register FIFOCNT"] pub type R = crate::R<u32, super::FIFOCNT>; #[doc = "Reader of field `FIF0COUNT`"] pub type FIF0COUNT_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:23 - FIF0COUNT"] #[inline(always)] pub fn fif0count(&self) -> FIF0COUNT_R { FIF0COUNT_R::new((self.bits & 0x00ff_ffff) as u32) } }
use proc_macro::TokenStream; use quote::quote; use syn::{ ext::IdentExt, Block, Error, ImplItem, ItemImpl, ReturnType, Type, TypeImplTrait, TypeParamBound, }; use crate::{ args::{self, ComplexityType, RenameRuleExt, RenameTarget, SubscriptionField}, output_type::OutputType, utils::{ extract_input_args, gen_deprecation, generate_default, generate_guards, get_cfg_attrs, get_crate_name, get_rustdoc, get_type_path_and_name, parse_complexity_expr, parse_graphql_attrs, remove_graphql_attrs, visible_fn, GeneratorResult, }, }; pub fn generate( subscription_args: &args::Subscription, item_impl: &mut ItemImpl, ) -> GeneratorResult<TokenStream> { let crate_name = get_crate_name(subscription_args.internal); let (self_ty, self_name) = get_type_path_and_name(item_impl.self_ty.as_ref())?; let generics = &item_impl.generics; let where_clause = &item_impl.generics.where_clause; let extends = subscription_args.extends; let gql_typename = if !subscription_args.name_type { let name = subscription_args .name .clone() .unwrap_or_else(|| RenameTarget::Type.rename(self_name.clone())); quote!(::std::borrow::Cow::Borrowed(#name)) } else { quote!(<Self as #crate_name::TypeName>::type_name()) }; let desc = if subscription_args.use_type_description { quote! { ::std::option::Option::Some(::std::string::ToString::to_string(<Self as #crate_name::Description>::description())) } } else { get_rustdoc(&item_impl.attrs)? .map(|s| quote!(::std::option::Option::Some(::std::string::ToString::to_string(#s)))) .unwrap_or_else(|| quote!(::std::option::Option::None)) }; let mut create_stream = Vec::new(); let mut schema_fields = Vec::new(); for item in &mut item_impl.items { if let ImplItem::Method(method) = item { let field: SubscriptionField = parse_graphql_attrs(&method.attrs)?.unwrap_or_default(); if field.skip { remove_graphql_attrs(&mut method.attrs); continue; } let ident = method.sig.ident.clone(); let field_name = field.name.clone().unwrap_or_else(|| { subscription_args .rename_fields .rename(method.sig.ident.unraw().to_string(), RenameTarget::Field) }); let field_desc = get_rustdoc(&method.attrs)? .map(|s| quote! {::std::option::Option::Some(::std::string::ToString::to_string(#s))}) .unwrap_or_else(|| quote! {::std::option::Option::None}); let field_deprecation = gen_deprecation(&field.deprecation, &crate_name); let cfg_attrs = get_cfg_attrs(&method.attrs); if method.sig.asyncness.is_none() { return Err(Error::new_spanned( &method, "The subscription stream function must be asynchronous", ) .into()); } let mut schema_args = Vec::new(); let mut use_params = Vec::new(); let mut get_params = Vec::new(); let args = extract_input_args::<args::SubscriptionFieldArgument>(&crate_name, method)?; for ( ident, ty, args::SubscriptionFieldArgument { name, desc, default, default_with, validator, process_with, visible: arg_visible, secret, }, ) in &args { let name = name.clone().unwrap_or_else(|| { subscription_args .rename_args .rename(ident.ident.unraw().to_string(), RenameTarget::Argument) }); let desc = desc .as_ref() .map(|s| quote! {::std::option::Option::Some(::std::string::ToString::to_string(#s))}) .unwrap_or_else(|| quote! {::std::option::Option::None}); let default = generate_default(default, default_with)?; let schema_default = default .as_ref() .map(|value| { quote! { ::std::option::Option::Some(::std::string::ToString::to_string( &<#ty as #crate_name::InputType>::to_value(&#value) )) } }) .unwrap_or_else(|| quote! {::std::option::Option::None}); let visible = visible_fn(arg_visible); schema_args.push(quote! { args.insert(::std::borrow::ToOwned::to_owned(#name), #crate_name::registry::MetaInputValue { name: ::std::string::ToString::to_string(#name), description: #desc, ty: <#ty as #crate_name::InputType>::create_type_info(registry), default_value: #schema_default, visible: #visible, inaccessible: false, tags: ::std::default::Default::default(), is_secret: #secret, }); }); use_params.push(quote! { #ident }); let default = match default { Some(default) => { quote! { ::std::option::Option::Some(|| -> #ty { #default }) } } None => quote! { ::std::option::Option::None }, }; let param_ident = &ident.ident; let process_with = match process_with.as_ref() { Some(fn_path) => { let fn_path: syn::ExprPath = syn::parse_str(fn_path)?; quote! { #fn_path(&mut #param_ident); } } None => Default::default(), }; let validators = validator.clone().unwrap_or_default().create_validators( &crate_name, quote!(&#ident), Some(quote!(.map_err(|err| err.into_server_error(__pos)))), )?; let mut non_mut_ident = ident.clone(); non_mut_ident.mutability = None; get_params.push(quote! { #[allow(non_snake_case, unused_mut)] let (__pos, mut #non_mut_ident) = ctx.param_value::<#ty>(#name, #default)?; #process_with #validators #[allow(non_snake_case)] let #ident = #non_mut_ident; }); } let ty = match &method.sig.output { ReturnType::Type(_, ty) => OutputType::parse(ty)?, ReturnType::Default => { return Err(Error::new_spanned( &method.sig.output, "Resolver must have a return type", ) .into()) } }; let res_ty = ty.value_type(); let stream_ty = if let Type::ImplTrait(TypeImplTrait { bounds, .. }) = &res_ty { let mut r = None; for b in bounds { if let TypeParamBound::Trait(b) = b { r = Some(quote! { dyn #b }); } } quote! { #r } } else { quote! { #res_ty } }; if let OutputType::Value(inner_ty) = &ty { let block = &method.block; let new_block = quote!({ { let value = (move || { async move #block })().await; ::std::result::Result::Ok(value) } }); method.block = syn::parse2::<Block>(new_block).expect("invalid block"); method.sig.output = syn::parse2::<ReturnType>(quote! { -> #crate_name::Result<#inner_ty> }) .expect("invalid result type"); } let visible = visible_fn(&field.visible); let complexity = if let Some(complexity) = &field.complexity { match complexity { ComplexityType::Const(n) => { quote! { ::std::option::Option::Some(#crate_name::registry::ComplexityType::Const(#n)) } } ComplexityType::Fn(s) => { let (variables, expr) = parse_complexity_expr(s)?; let mut parse_args = Vec::new(); for variable in variables { if let Some(( ident, ty, args::SubscriptionFieldArgument { name, default, default_with, .. }, )) = args .iter() .find(|(pat_ident, _, _)| pat_ident.ident == variable) { let default = match generate_default(default, default_with)? { Some(default) => { quote! { ::std::option::Option::Some(|| -> #ty { #default }) } } None => quote! { ::std::option::Option::None }, }; let name = name.clone().unwrap_or_else(|| { subscription_args.rename_args.rename( ident.ident.unraw().to_string(), RenameTarget::Argument, ) }); parse_args.push(quote! { let #ident: #ty = __ctx.param_value(__variables_definition, __field, #name, #default)?; }); } } quote! { Some(#crate_name::registry::ComplexityType::Fn(|__ctx, __variables_definition, __field, child_complexity| { #(#parse_args)* ::std::result::Result::Ok(#expr) })) } } } } else { quote! { ::std::option::Option::None } }; schema_fields.push(quote! { #(#cfg_attrs)* fields.insert(::std::borrow::ToOwned::to_owned(#field_name), #crate_name::registry::MetaField { name: ::std::borrow::ToOwned::to_owned(#field_name), description: #field_desc, args: { let mut args = #crate_name::indexmap::IndexMap::new(); #(#schema_args)* args }, ty: <<#stream_ty as #crate_name::futures_util::stream::Stream>::Item as #crate_name::OutputType>::create_type_info(registry), deprecation: #field_deprecation, cache_control: ::std::default::Default::default(), external: false, requires: ::std::option::Option::None, provides: ::std::option::Option::None, shareable: false, override_from: ::std::option::Option::None, visible: #visible, inaccessible: false, tags: ::std::default::Default::default(), compute_complexity: #complexity, }); }); let create_field_stream = quote! { self.#ident(ctx, #(#use_params),*) .await .map_err(|err| { ::std::convert::Into::<#crate_name::Error>::into(err).into_server_error(ctx.item.pos) .with_path(::std::vec![#crate_name::PathSegment::Field(::std::borrow::ToOwned::to_owned(&*field_name))]) }) }; let guard_map_err = quote! { .map_err(|err| { err.into_server_error(ctx.item.pos) .with_path(::std::vec![#crate_name::PathSegment::Field(::std::borrow::ToOwned::to_owned(&*field_name))]) }) }; let guard = match field.guard.as_ref().or(subscription_args.guard.as_ref()) { Some(code) => Some(generate_guards(&crate_name, code, guard_map_err)?), None => None, }; let stream_fn = quote! { let field_name = ::std::clone::Clone::clone(&ctx.item.node.response_key().node); let field = ::std::sync::Arc::new(::std::clone::Clone::clone(&ctx.item)); let f = async { #(#get_params)* #guard #create_field_stream }; let stream = f.await.map_err(|err| ctx.set_error_path(err))?; let pos = ctx.item.pos; let schema_env = ::std::clone::Clone::clone(&ctx.schema_env); let query_env = ::std::clone::Clone::clone(&ctx.query_env); let stream = #crate_name::futures_util::stream::StreamExt::then(stream, { let field_name = ::std::clone::Clone::clone(&field_name); move |msg| { let schema_env = ::std::clone::Clone::clone(&schema_env); let query_env = ::std::clone::Clone::clone(&query_env); let field = ::std::clone::Clone::clone(&field); let field_name = ::std::clone::Clone::clone(&field_name); async move { let ctx_selection_set = query_env.create_context( &schema_env, ::std::option::Option::Some(#crate_name::QueryPathNode { parent: ::std::option::Option::None, segment: #crate_name::QueryPathSegment::Name(&field_name), }), &field.node.selection_set, ); let execute_fut = async { let parent_type = #gql_typename; #[allow(bare_trait_objects)] let ri = #crate_name::extensions::ResolveInfo { path_node: ctx_selection_set.path_node.as_ref().unwrap(), parent_type: &parent_type, return_type: &<<#stream_ty as #crate_name::futures_util::stream::Stream>::Item as #crate_name::OutputType>::qualified_type_name(), name: field.node.name.node.as_str(), alias: field.node.alias.as_ref().map(|alias| alias.node.as_str()), is_for_introspection: false, }; let resolve_fut = async { #crate_name::OutputType::resolve(&msg, &ctx_selection_set, &*field) .await .map(::std::option::Option::Some) }; #crate_name::futures_util::pin_mut!(resolve_fut); let mut resp = query_env.extensions.resolve(ri, &mut resolve_fut).await.map(|value| { let mut map = #crate_name::indexmap::IndexMap::new(); map.insert(::std::clone::Clone::clone(&field_name), value.unwrap_or_default()); #crate_name::Response::new(#crate_name::Value::Object(map)) }) .unwrap_or_else(|err| #crate_name::Response::from_errors(::std::vec![err])); use ::std::iter::Extend; resp.errors.extend(::std::mem::take(&mut *query_env.errors.lock().unwrap())); resp }; #crate_name::futures_util::pin_mut!(execute_fut); ::std::result::Result::Ok(query_env.extensions.execute(query_env.operation_name.as_deref(), &mut execute_fut).await) } } }); #crate_name::ServerResult::Ok(stream) }; create_stream.push(quote! { #(#cfg_attrs)* if ctx.item.node.name.node == #field_name { let stream = #crate_name::futures_util::stream::TryStreamExt::try_flatten( #crate_name::futures_util::stream::once((move || async move { #stream_fn })()) ); let stream = #crate_name::futures_util::StreamExt::map(stream, |res| match res { ::std::result::Result::Ok(resp) => resp, ::std::result::Result::Err(err) => #crate_name::Response::from_errors(::std::vec![err]), }); return ::std::option::Option::Some(::std::boxed::Box::pin(stream)); } }); remove_graphql_attrs(&mut method.attrs); } } if create_stream.is_empty() { return Err(Error::new_spanned( self_ty, "A GraphQL Object type must define one or more fields.", ) .into()); } let visible = visible_fn(&subscription_args.visible); let expanded = quote! { #item_impl #[allow(clippy::all, clippy::pedantic)] #[allow(unused_braces, unused_variables)] impl #generics #crate_name::SubscriptionType for #self_ty #where_clause { fn type_name() -> ::std::borrow::Cow<'static, ::std::primitive::str> { #gql_typename } #[allow(bare_trait_objects)] fn create_type_info(registry: &mut #crate_name::registry::Registry) -> ::std::string::String { registry.create_subscription_type::<Self, _>(|registry| #crate_name::registry::MetaType::Object { name: ::std::borrow::Cow::into_owned(#gql_typename), description: #desc, fields: { let mut fields = #crate_name::indexmap::IndexMap::new(); #(#schema_fields)* fields }, cache_control: ::std::default::Default::default(), extends: #extends, keys: ::std::option::Option::None, visible: #visible, shareable: false, inaccessible: false, tags: ::std::default::Default::default(), is_subscription: true, rust_typename: ::std::option::Option::Some(::std::any::type_name::<Self>()), }) } fn create_field_stream<'__life>( &'__life self, ctx: &'__life #crate_name::Context<'_>, ) -> ::std::option::Option<::std::pin::Pin<::std::boxed::Box<dyn #crate_name::futures_util::stream::Stream<Item = #crate_name::Response> + ::std::marker::Send + '__life>>> { #(#create_stream)* ::std::option::Option::None } } }; Ok(expanded.into()) }
//! https://github.com/lumen/otp/tree/lumen/lib/inets/src/http_server use super::*; test_compiles_lumen_otp!(httpd); test_compiles_lumen_otp!(httpd_acceptor); test_compiles_lumen_otp!(httpd_acceptor_sup); test_compiles_lumen_otp!(httpd_cgi); test_compiles_lumen_otp!(httpd_conf); test_compiles_lumen_otp!(httpd_connection_sup); test_compiles_lumen_otp!(httpd_custom); test_compiles_lumen_otp!(httpd_custom_api); test_compiles_lumen_otp!(httpd_esi); test_compiles_lumen_otp!(httpd_example); test_compiles_lumen_otp!(httpd_file); test_compiles_lumen_otp!(httpd_instance_sup imports "lib/inets/src/http_server/httpd_conf", "lib/inets/src/http_server/httpd_util", "lib/kernel/src/error_logger", "lib/stdlib/src/proplists", "lib/stdlib/src/supervisor"); test_compiles_lumen_otp!(httpd_log); test_compiles_lumen_otp!(httpd_logger); test_compiles_lumen_otp!(httpd_manager); test_compiles_lumen_otp!(httpd_misc_sup); test_compiles_lumen_otp!(httpd_request); test_compiles_lumen_otp!(httpd_request_handler); test_compiles_lumen_otp!(httpd_response); test_compiles_lumen_otp!(httpd_script_env); test_compiles_lumen_otp!(httpd_socket); test_compiles_lumen_otp!(httpd_sup); test_compiles_lumen_otp!(httpd_util); test_compiles_lumen_otp!(mod_actions); test_compiles_lumen_otp!(mod_alias); test_compiles_lumen_otp!(mod_auth); test_compiles_lumen_otp!(mod_auth_dets); test_compiles_lumen_otp!(mod_auth_mnesia); test_compiles_lumen_otp!(mod_auth_plain); test_compiles_lumen_otp!(mod_auth_server); test_compiles_lumen_otp!(mod_cgi); test_compiles_lumen_otp!(mod_dir); test_compiles_lumen_otp!(mod_disk_log); test_compiles_lumen_otp!(mod_esi); test_compiles_lumen_otp!(mod_get); test_compiles_lumen_otp!(mod_head imports "lib/inets/src/http_server/httpd_util", "lib/inets/src/http_server/mod_alias", "lib/kernel/src/file", "lib/stdlib/src/io_lib", "lib/stdlib/src/lists", "lib/stdlib/src/proplists"); test_compiles_lumen_otp!(mod_log); test_compiles_lumen_otp!(mod_range); test_compiles_lumen_otp!(mod_responsecontrol); test_compiles_lumen_otp!(mod_security); test_compiles_lumen_otp!(mod_security_server); test_compiles_lumen_otp!(mod_trace imports "lib/inets/src/http_server/httpd_socket", "lib/stdlib/src/lists", "lib/stdlib/src/proplists"); fn includes() -> Vec<&'static str> { let mut includes = super::includes(); includes.extend(vec![ "lib/inets/src/http_lib", "lib/inets/src/http_server", "lib/inets/src/inets_app", "lib/kernel/include", "lib/kernel/src", ]); includes } fn relative_directory_path() -> PathBuf { super::relative_directory_path().join("http_server") }
use examples_shared::{self as es, anyhow, ds, tokio, tracing}; #[tokio::main] async fn main() -> Result<(), anyhow::Error> { let client = es::make_client(ds::Subscriptions::ACTIVITY).await; let mut activity_events = client.wheel.activity(); tokio::task::spawn(async move { while let Ok(ae) = activity_events.0.recv().await { tracing::info!(event = ?ae, "received activity event"); } }); let rp = ds::activity::ActivityBuilder::default() .details("Fruit Tarts".to_owned()) .state("Pop Snacks".to_owned()) .assets( ds::activity::Assets::default() .large("the".to_owned(), Some("u mage".to_owned())) .small("the".to_owned(), Some("i mage".to_owned())), ); tracing::info!( "updated activity: {:?}", client.discord.update_activity(rp).await ); let mut r = String::new(); let _ = std::io::stdin().read_line(&mut r); tracing::info!( "cleared activity: {:?}", client.discord.clear_activity().await ); client.discord.disconnect().await; Ok(()) }
#[macro_export] macro_rules! ast { ( ($d:tt), $Path:ident ) => { macro_rules! path { ( $d ( $d e:expr),* ) => ( $Path::with_steps(vec![$d ($d e),*]) ); } }; ( $Neighborhood:ident, $Path:ident, $Step:ident, ($($start_lhs:tt)*) => $( ( $($rule:tt)* // $lhs:tt // ::= // $( // $rhs:tt // )|+ ); )* ) => ( ast!(($), $Path); struct $Neighborhood { paths: Vec<$Path>, runtime: $crate::NeighborhoodRuntime<$Step>, } struct $Path { steps: Vec<$Step>, } impl $Neighborhood { pub fn new() -> Self { let mut runtime = $crate::NeighborhoodRuntime::<$Step>::new(); $( runtime.rule( // rule!($lhs).lhs_then(rule!($($rhs)|+)) rule!(( $($rule)* )); ); )* runtime.process_rules(); $Neighborhood { paths: Vec::new(), runtime, } } pub fn with_paths(paths: Vec<$Path>) -> Self { let mut this = $Neighborhood::new(); this.paths = paths; this } pub fn validate(&self) -> bool { let mut valid = true; for path in &self.paths { valid = valid && self.runtime.validate_steps(&path.steps[..]); } valid } } impl $Path { pub fn new() -> Self { $Path { steps: Vec::new() } } pub fn with_steps(steps: Vec<$Step>) -> Self { $Path { steps } } } ) } // #[macro_export] // macro_rules! lhs { // ($lhs:ident) => { // $crate::Lhs::variant(stringify!($lhs)) // }; // (( $lhs:ident<$T:ty> )) => { // $crate::Lhs::apply(stringify!($lhs), stringify!($T)) // }; // (( for<$T:ident> $inner:tt )) => { // if let Lhs::Param { rhs, ty_param } = lhs!($inner) { // assert_eq!(ty_param, stringify!($T)); // $crate::Lhs::Param { rhs, ty_param } // } else { // panic!("invalid LHS"); // } // }; // } #[macro_export] macro_rules! rule { ($rhs:ident) => { $crate::Matcher::variant(stringify!($rhs)).into_neighborhood() }; (( $rhs:ident<$T:ty> )) => { $crate::Matcher::apply(stringify!($rhs), stringify!($T)).into_neighborhood() }; ((@m $pattern:pat )) => { $crate::Matcher::match_pattern(Box::new(|val| match val { &$pattern => true, _ => false })) .into_neighborhood() }; (( for<$T:ident> $rhs:tt )) => { rule!($rhs).introduce_param(stringify!($T)) }; (( $rhs:tt * )) => { rule!($rhs).repeat() }; (( $lhs:tt ::= $rhs:tt )) => { rule!($lhs).lhs_then(rule!($rhs)) }; (( /**/ $rhs0:tt $(^ $rhsN:tt)+ )) => { /***/ rule!($rhs0) $(.offshoot(rule!($rhsN)))+ }; (( $rhs0:tt $($rhsN:tt)* )) => { rule!($rhs0) $(.then(rule!($rhsN)))* }; ( /**/ $rhs0:tt $(| $rhsN:tt)+ ) => { /***/ rule!($rhs0) $(.or(rule!($rhsN)))+ }; }
use std::ops::{Deref, DerefMut}; use std::sync::{LockResult, Mutex, MutexGuard, PoisonError, TryLockError, TryLockResult}; pub struct RwMutex<T> { mutex: Mutex<T>, } pub struct RwMutexReadGuard<'a, T: ?Sized + 'a> { mutex_guard: MutexGuard<'a, T>, } pub struct RwMutexWriteGuard<'a, T: ?Sized + 'a> { mutex_guard: MutexGuard<'a, T>, } impl<T> RwMutex<T> { pub fn new(t: T) -> RwMutex<T> { RwMutex { mutex: Mutex::new(t), } } pub fn read(&self) -> LockResult<RwMutexReadGuard<T>> { self.lock(RwMutexReadGuard::new) } pub fn try_read(&self) -> TryLockResult<RwMutexReadGuard<T>> { self.try_lock(RwMutexReadGuard::new) } pub fn write(&self) -> LockResult<RwMutexWriteGuard<T>> { self.lock(RwMutexWriteGuard::new) } pub fn try_write(&self) -> TryLockResult<RwMutexWriteGuard<T>> { self.try_lock(RwMutexWriteGuard::new) } fn lock<'a, F: Copy + Fn(MutexGuard<'a, T>) -> R, R>(&'a self, f: F) -> LockResult<R> { self.mutex.lock() .map(f) .map_err(|e| PoisonError::new(f(e.into_inner()))) } fn try_lock<'a, F: Copy + Fn(MutexGuard<'a, T>) -> R, R>(&'a self, f: F) -> TryLockResult<R> { self.mutex.try_lock() .map(f) .map_err(|e| match e { TryLockError::WouldBlock => TryLockError::WouldBlock, TryLockError::Poisoned(e) => TryLockError::Poisoned(PoisonError::new(f(e.into_inner()))) }) } pub fn is_poisoned(&self) -> bool { self.mutex.is_poisoned() } } impl<'a, T: ?Sized> RwMutexReadGuard<'a, T> { fn new(mutex_guard: MutexGuard<'a, T>) -> RwMutexReadGuard<'a, T> { RwMutexReadGuard { mutex_guard: mutex_guard, } } } impl<'a, T: ?Sized> Deref for RwMutexReadGuard<'a, T> { type Target = T; fn deref(&self) -> &T { &*self.mutex_guard } } impl<'a, T: ?Sized> RwMutexWriteGuard<'a, T> { fn new(mutex_guard: MutexGuard<'a, T>) -> RwMutexWriteGuard<'a, T> { RwMutexWriteGuard { mutex_guard: mutex_guard, } } } impl<'a, T: ?Sized> Deref for RwMutexWriteGuard<'a, T> { type Target = T; fn deref(&self) -> &T { &*self.mutex_guard } } impl<'a, T: ?Sized> DerefMut for RwMutexWriteGuard<'a, T> { fn deref_mut(&mut self) -> &mut T { self.mutex_guard.deref_mut() } }
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass use std::slice::Iter; use std::io::{Error, ErrorKind, Result}; use std::vec::*; fn foo(it: &mut Iter<u8>) -> Result<u8> { Ok(*it.next().unwrap()) } fn bar() -> Result<u8> { let data: Vec<u8> = Vec::new(); if true { return Err(Error::new(ErrorKind::NotFound, "msg")); } let mut it = data.iter(); foo(&mut it) } fn main() { bar(); }
/* DeepSAFL - mutate operations ------------------------------------------------------ Written and maintained by Liang Jie <liangjie.mailbox.cn@google.com> Copyright 2018. All rights reserved. */ #![allow(unused)] use std; use std::cmp; use std::mem; use super::config; use rand; use rand::Rng; fn flipbit(origin_seed:&mut Vec<u8>, pos:u64) { let pos_byte = (pos >> 3) as usize; let pos_bit = pos & 7; origin_seed[pos_byte] ^= 128 >> pos_bit; } pub fn flip_one_bit(input_seed: &Vec<u8>, pos:u64)->Vec<u8> { let mut output_seed = input_seed.clone(); flipbit(&mut output_seed,pos); output_seed } pub fn flip_one_bit_option(input_seed: &Vec<u8>, pos:u64)->Option<Vec<u8>> { let mut output_seed = input_seed.clone(); flipbit(&mut output_seed,pos); Some(output_seed) } pub fn flip_two_bits(input_seed: &Vec<u8>, pos:u64)->Vec<u8> { let mut output_seed = input_seed.clone(); flipbit(&mut output_seed,pos); flipbit(&mut output_seed,pos+1); output_seed } pub fn flip_two_bits_option(input_seed: &Vec<u8>, pos:u64)->Option<Vec<u8>>{ let mut output_seed = input_seed.clone(); flipbit(&mut output_seed,pos); flipbit(&mut output_seed,pos+1); Some(output_seed) } pub fn flip_four_bits(input_seed: &Vec<u8>, pos:u64)->Vec<u8> { let mut output_seed = input_seed.clone(); flipbit(&mut output_seed,pos); flipbit(&mut output_seed,pos+1); flipbit(&mut output_seed,pos+2); flipbit(&mut output_seed,pos+3); output_seed } pub fn flip_four_bits_option(input_seed: &Vec<u8>, pos:u64)->Option<Vec<u8>>{ let mut output_seed = input_seed.clone(); flipbit(&mut output_seed,pos); flipbit(&mut output_seed,pos+1); flipbit(&mut output_seed,pos+2); flipbit(&mut output_seed,pos+3); Some(output_seed) } fn flipbyte(origin_seed:&mut Vec<u8>, pos:u64) { origin_seed[pos as usize] ^= 0xFF; } pub fn flip_one_byte(input_seed:&Vec<u8>, byte_pos:u64)->Vec<u8> { assert!(byte_pos < input_seed.len() as u64); let mut output_seed = input_seed.clone(); flipbyte(&mut output_seed,byte_pos); output_seed } pub fn flip_one_byte_option(input_seed:&Vec<u8>, byte_pos:u64)->Option<Vec<u8>>{ assert!(byte_pos < input_seed.len() as u64); let mut output_seed = input_seed.clone(); flipbyte(&mut output_seed,byte_pos); Some(output_seed) } fn set_one_byte(input_seed:&Vec<u8>, byte_pos:u64, byte_new:u8)->Vec<u8> { assert!(byte_pos < input_seed.len() as u64); assert!(byte_new != 0); let mut output_seed = input_seed.clone(); output_seed[byte_pos as usize] = byte_new; output_seed } pub fn flip_two_bytes(input_seed: &Vec<u8>, byte_pos:u64)->Vec<u8> { assert!(byte_pos < input_seed.len() as u64 -1); let mut output_seed = input_seed.clone(); flipbyte(&mut output_seed,byte_pos); flipbyte(&mut output_seed,byte_pos+1); output_seed } pub fn flip_two_bytes_option(input_seed: &Vec<u8>, byte_pos:u64)->Option<Vec<u8>> { assert!(byte_pos < input_seed.len() as u64 -1); let mut output_seed = input_seed.clone(); flipbyte(&mut output_seed,byte_pos); flipbyte(&mut output_seed,byte_pos+1); Some(output_seed) } pub fn flip_four_bytes(input_seed: &Vec<u8>, byte_pos:u64)->Vec<u8> { assert!(byte_pos < (input_seed.len() as u64) -3); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); flipbyte(&mut output_seed,byte_pos); flipbyte(&mut output_seed,byte_pos+1); flipbyte(&mut output_seed,byte_pos+2); flipbyte(&mut output_seed,byte_pos+3); output_seed } pub fn flip_four_bytes_option(input_seed: &Vec<u8>, byte_pos:u64)->Option<Vec<u8>> { assert!(byte_pos < (input_seed.len() as u64) -3); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); flipbyte(&mut output_seed,byte_pos); flipbyte(&mut output_seed,byte_pos+1); flipbyte(&mut output_seed,byte_pos+2); flipbyte(&mut output_seed,byte_pos+3); Some(output_seed) } fn could_be_bitflip(xor_val_orign: u32) -> bool { let mut sh:u32 = 0; let mut xor_val = xor_val_orign; if(xor_val == 0) { return true; } while((xor_val & 1) == 0) { sh+=1; xor_val >>= 1; } if(xor_val == 1 || xor_val == 3 || xor_val == 15) { return true; } if((sh & 7) != 0) { return false; } if(xor_val == 0xff || xor_val == 0xffff || xor_val == 0xffffffff) { return true; } false } // pub fn add_one_byte_could_be_bitflip(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u8)-> bool { // let orig = input_seed[byte_pos as usize]; // let xor_val = orig ^ (orig+arith_number); // could_be_bitflip(xor_val as u32) // } pub fn arithmetic_add_one_byte(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u8)->Vec<u8> { let mut output_seed = input_seed.clone(); let orig = output_seed[byte_pos as usize]; output_seed[byte_pos as usize] = orig+arith_number; output_seed } pub fn arithmetic_add_one_byte_option(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u8) -> Option<Vec<u8>> { let orig = input_seed[byte_pos as usize]; let xor_val = orig ^ (orig+arith_number); if could_be_bitflip(xor_val as u32) { None } else { let mut output_seed = input_seed.clone(); output_seed[byte_pos as usize] = orig+arith_number; Some(output_seed) } } pub fn sub_one_byte_could_be_bitflip(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u8)-> bool { let orig = input_seed[byte_pos as usize]; let xor_val = orig ^ (orig-arith_number); could_be_bitflip(xor_val as u32) } pub fn arithmetic_sub_one_byte(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u8)->Vec<u8> { let mut output_seed = input_seed.clone(); let orig = output_seed[byte_pos as usize]; output_seed[byte_pos as usize] = orig-arith_number; output_seed } pub fn arithmetic_sub_one_byte_option(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u8)-> Option<Vec<u8>> { let orig = input_seed[byte_pos as usize]; let xor_val = orig ^ (orig-arith_number); if could_be_bitflip(xor_val as u32) { None } else { let mut output_seed = input_seed.clone(); output_seed[byte_pos as usize] = orig-arith_number; Some(output_seed) } } // pub fn convert_string_into_two_bytes(pack_data: & String){ // let ptr :*const u8 = pack_data.as_ptr(); // let ptr :*const u16 = ptr as *const u16; // let s = unsafe{ *ptr}; // println!("{:?}", s); // } // pub fn cast_vec<T:Copy,U:Copy>(v:Vec<T>)->Vec<U>{ // use std::mem::size_of; // use std::mem::forget; // let (s_t, s_u) = (size_of::<T>(), size_of::<U>()); // let bytes_len = v.len() * s_t; // assert!( bytes_len % s_u == 0); // let mut v = v; // v.shrink_to_fit(); // let len = bytes_len / s_u; // let result; // unsafe{ // result = Vec::from_raw_parts(v.as_mut_ptr() as *mut U, len, len); // forget(v); // } // result // } //pub fn saturating_add(self, rhs: u16) -> u16 //pub fn saturating_sub(self, rhs: u16) -> u16 //pub fn wrapping_add(self, rhs: u16) -> u16 //pub fn wrapping_sub(self, rhs: u16) -> u16 //pub fn to_bytes(self) -> [u8; 2] let bytes = 0x1234_5678_u32.to_be().to_bytes(); //pub fn from_bytes(bytes: [u8; 2]) -> u16 let int = u32::from_be(u32::from_bytes([0x12, 0x34, 0x56, 0x78])); // We find repeat codes in following two functions, might be optimized? // pub fn add_two_bytes_could_be_bitflip(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u16)-> bool { // assert!(byte_pos < input_seed.len() as u64 -1); //Attention: You need to ensure the byte_pos is legal // let first_byte = input_seed[byte_pos as usize] as u16; // let second_byte = input_seed[(byte_pos+1) as usize] as u16; // let orig_old = first_byte.wrapping_shl(8) + second_byte; // let orig_new = orig_old + arith_number; // let xor_val = orig_old ^ orig_new; // could_be_bitflip(xor_val as u32) // } pub fn arithmetic_add_two_bytes(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u16)->Vec<u8> { assert!(byte_pos < input_seed.len() as u64 -1); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); let first_byte = output_seed[byte_pos as usize] as u16; let second_byte = output_seed[(byte_pos+1) as usize] as u16; let orig_old = first_byte.wrapping_shl(8) + second_byte; let orig_new = orig_old + arith_number; let first_byte_new = (orig_new >> 8) as u8; let second_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed } pub fn arithmetic_add_two_bytes_option(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u16) -> Option<Vec<u8>> { assert!(byte_pos < input_seed.len() as u64 -1); //Attention: You need to ensure the byte_pos is legal let first_byte = input_seed[byte_pos as usize] as u16; let second_byte = input_seed[(byte_pos+1) as usize] as u16; let orig_old = first_byte.wrapping_shl(8) + second_byte; let orig_new = orig_old + arith_number; let xor_val = orig_old ^ orig_new; if could_be_bitflip(xor_val as u32) { None } else { let mut output_seed = input_seed.clone(); let first_byte_new = (orig_new >> 8) as u8; let second_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; Some(output_seed) } } pub fn arithmetic_sub_two_bytes(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u16)->Vec<u8> { assert!(byte_pos < input_seed.len() as u64 -1); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); let first_byte = output_seed[byte_pos as usize] as u16; let second_byte = output_seed[(byte_pos+1) as usize] as u16; let orig_old = first_byte.wrapping_shl(8) + second_byte; let orig_new = orig_old - arith_number; let first_byte_new = (orig_new >> 8) as u8; let second_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed } pub fn arithmetic_sub_two_bytes_option(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u16)-> Option<Vec<u8>> { assert!(byte_pos < input_seed.len() as u64 -1); //Attention: You need to ensure the byte_pos is legal let first_byte = input_seed[byte_pos as usize] as u16; let second_byte = input_seed[(byte_pos+1) as usize] as u16; let orig_old = first_byte.wrapping_shl(8) + second_byte; let orig_new = orig_old - arith_number; let xor_val = orig_old ^ orig_new; if could_be_bitflip(xor_val as u32) { None } else { let mut output_seed = input_seed.clone(); let first_byte_new = (orig_new >> 8) as u8; let second_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; Some(output_seed) } } pub fn arithmetic_add_two_bytes_another_endian(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u16)->Vec<u8> { assert!(byte_pos < input_seed.len() as u64 -1); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); let second_byte = output_seed[byte_pos as usize] as u16; let first_byte = output_seed[(byte_pos+1) as usize] as u16; let orig_old = first_byte.wrapping_shl(8) + second_byte; let orig_new = orig_old + arith_number; let second_byte_new = (orig_new >> 8) as u8; let first_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed } pub fn arithmetic_add_two_bytes_another_endian_option(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u16)-> Option<Vec<u8>>{ assert!(byte_pos < input_seed.len() as u64 -1); //Attention: You need to ensure the byte_pos is legal let second_byte= input_seed[byte_pos as usize] as u16; let first_byte = input_seed[(byte_pos+1) as usize] as u16; let orig_old = first_byte.wrapping_shl(8) + second_byte; let orig_new = orig_old + arith_number; let xor_val = orig_old ^ orig_new; if could_be_bitflip(xor_val as u32) { None } else { let mut output_seed = input_seed.clone(); let second_byte_new = (orig_new >> 8) as u8; let first_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; Some(output_seed) } } pub fn arithmetic_sub_two_bytes_another_endian(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u16)->Vec<u8> { assert!(byte_pos < input_seed.len() as u64 -1); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); let second_byte = output_seed[byte_pos as usize] as u16; let first_byte = output_seed[(byte_pos+1) as usize] as u16; let orig_old = first_byte.wrapping_shl(8) + second_byte; let orig_new = orig_old - arith_number; let second_byte_new = (orig_new >> 8) as u8; let first_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed } pub fn arithmetic_sub_two_bytes_another_endian_option(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u16)-> Option<Vec<u8>>{ assert!(byte_pos < input_seed.len() as u64 -1); //Attention: You need to ensure the byte_pos is legal let second_byte= input_seed[byte_pos as usize] as u16; let first_byte = input_seed[(byte_pos+1) as usize] as u16; let orig_old = first_byte.wrapping_shl(8) + second_byte; let orig_new = orig_old - arith_number; let xor_val = orig_old ^ orig_new; if could_be_bitflip(xor_val as u32) { None } else { let mut output_seed = input_seed.clone(); let second_byte_new = (orig_new >> 8) as u8; let first_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; Some(output_seed) } } pub fn arithmetic_add_four_bytes(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u32)->Vec<u8> { assert!(byte_pos < (input_seed.len() as u64) -3); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); let first_byte = output_seed[byte_pos as usize] as u32; let second_byte = output_seed[(byte_pos+1) as usize] as u32; let third_byte = output_seed[(byte_pos+2) as usize] as u32; let fourth_byte = output_seed[(byte_pos+3) as usize] as u32; let orig_old = first_byte.wrapping_shl(24) + second_byte.wrapping_shl(16) +third_byte.wrapping_shl(8) + fourth_byte; let orig_new = orig_old + arith_number; let first_byte_new = (orig_new >> 24) as u8; let second_byte_new = (((orig_new >> 16) & 127).wrapping_shl(24)>>24) as u8; let third_byte_new = (((orig_new >> 8) & 127).wrapping_shl(24)>>24) as u8; let fourth_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed[(byte_pos+2) as usize] = third_byte_new; output_seed[(byte_pos+3) as usize] = fourth_byte_new; output_seed } pub fn arithmetic_add_four_bytes_option(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u32)-> Option<Vec<u8>> { assert!(byte_pos < (input_seed.len() as u64) -3); //Attention: You need to ensure the byte_pos is legal let first_byte = input_seed[byte_pos as usize] as u32; let second_byte = input_seed[(byte_pos+1) as usize] as u32; let third_byte = input_seed[(byte_pos+2) as usize] as u32; let fourth_byte = input_seed[(byte_pos+3) as usize] as u32; let orig_old = first_byte.wrapping_shl(24) + second_byte.wrapping_shl(16) +third_byte.wrapping_shl(8) + fourth_byte; let orig_new = orig_old + arith_number; let xor_val = orig_old ^ orig_new; if could_be_bitflip(xor_val) { None } else { let mut output_seed = input_seed.clone(); let first_byte_new = (orig_new >> 24) as u8; let second_byte_new = (((orig_new >> 16) & 127).wrapping_shl(24)>>24) as u8; let third_byte_new = (((orig_new >> 8) & 127).wrapping_shl(24)>>24) as u8; let fourth_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed[(byte_pos+2) as usize] = third_byte_new; output_seed[(byte_pos+3) as usize] = fourth_byte_new; Some(output_seed) } } pub fn arithmetic_sub_four_bytes(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u32)->Vec<u8> { assert!(byte_pos < (input_seed.len() as u64) -3); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); let first_byte = output_seed[byte_pos as usize] as u32; let second_byte = output_seed[(byte_pos+1) as usize] as u32; let third_byte = output_seed[(byte_pos+2) as usize] as u32; let fourth_byte = output_seed[(byte_pos+3) as usize] as u32; let orig_old = first_byte.wrapping_shl(24) + second_byte.wrapping_shl(16) +third_byte.wrapping_shl(8) + fourth_byte; let orig_new = orig_old - arith_number; let first_byte_new = (orig_new >> 24) as u8; let second_byte_new = (((orig_new >> 16) & 127).wrapping_shl(24)>>24) as u8; let third_byte_new = (((orig_new >> 8) & 127).wrapping_shl(24)>>24) as u8; let fourth_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed[(byte_pos+2) as usize] = third_byte_new; output_seed[(byte_pos+3) as usize] = fourth_byte_new; output_seed } pub fn arithmetic_sub_four_bytes_option(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u32)->Option<Vec<u8>> { assert!(byte_pos < (input_seed.len() as u64) -3); //Attention: You need to ensure the byte_pos is legal let first_byte = input_seed[byte_pos as usize] as u32; let second_byte = input_seed[(byte_pos+1) as usize] as u32; let third_byte = input_seed[(byte_pos+2) as usize] as u32; let fourth_byte = input_seed[(byte_pos+3) as usize] as u32; let orig_old = first_byte.wrapping_shl(24) + second_byte.wrapping_shl(16) +third_byte.wrapping_shl(8) + fourth_byte; let orig_new = orig_old - arith_number; let xor_val = orig_old ^ orig_new; if could_be_bitflip(xor_val) { None } else { let mut output_seed = input_seed.clone(); let first_byte_new = (orig_new >> 24) as u8; let second_byte_new = (((orig_new >> 16) & 127).wrapping_shl(24)>>24) as u8; let third_byte_new = (((orig_new >> 8) & 127).wrapping_shl(24)>>24) as u8; let fourth_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed[(byte_pos+2) as usize] = third_byte_new; output_seed[(byte_pos+3) as usize] = fourth_byte_new; Some(output_seed) } } pub fn arithmetic_add_four_bytes_another_endian(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u32)->Vec<u8> { assert!(byte_pos < (input_seed.len() as u64) -3); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); let fourth_byte = output_seed[byte_pos as usize] as u32; let third_byte = output_seed[(byte_pos+1) as usize] as u32; let second_byte = output_seed[(byte_pos+2) as usize] as u32; let first_byte = output_seed[(byte_pos+3) as usize] as u32; let orig_old = first_byte.wrapping_shl(24) + second_byte.wrapping_shl(16) +third_byte.wrapping_shl(8) + fourth_byte; let orig_new = orig_old + arith_number; let fourth_byte_new = (orig_new >> 24) as u8; let third_byte_new = (((orig_new >> 16) & 127).wrapping_shl(24)>>24) as u8; let second_byte_new = (((orig_new >> 8) & 127).wrapping_shl(24)>>24) as u8; let first_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed[(byte_pos+2) as usize] = third_byte_new; output_seed[(byte_pos+3) as usize] = fourth_byte_new; output_seed } pub fn arithmetic_add_four_bytes_another_endian_option(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u32)->Option<Vec<u8>> { assert!(byte_pos < (input_seed.len() as u64) -3); //Attention: You need to ensure the byte_pos is legal let fourth_byte = input_seed[byte_pos as usize] as u32; let third_byte = input_seed[(byte_pos+1) as usize] as u32; let second_byte = input_seed[(byte_pos+2) as usize] as u32; let first_byte = input_seed[(byte_pos+3) as usize] as u32; let orig_old = first_byte.wrapping_shl(24) + second_byte.wrapping_shl(16) +third_byte.wrapping_shl(8) + fourth_byte; let orig_new = orig_old + arith_number; let xor_val = orig_old ^ orig_new; if could_be_bitflip(xor_val) { None } else { let mut output_seed = input_seed.clone(); let fourth_byte_new = (orig_new >> 24) as u8; let third_byte_new = (((orig_new >> 16) & 127).wrapping_shl(24)>>24) as u8; let second_byte_new = (((orig_new >> 8) & 127).wrapping_shl(24)>>24) as u8; let first_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed[(byte_pos+2) as usize] = third_byte_new; output_seed[(byte_pos+3) as usize] = fourth_byte_new; Some(output_seed) } } pub fn arithmetic_sub_four_bytes_another_endian(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u32)->Vec<u8> { assert!(byte_pos < (input_seed.len() as u64) -3); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); let fourth_byte = output_seed[byte_pos as usize] as u32; let third_byte = output_seed[(byte_pos+1) as usize] as u32; let second_byte = output_seed[(byte_pos+2) as usize] as u32; let first_byte = output_seed[(byte_pos+3) as usize] as u32; let orig_old = first_byte.wrapping_shl(24) + second_byte.wrapping_shl(16) +third_byte.wrapping_shl(8) + fourth_byte; let orig_new = orig_old - arith_number; let fourth_byte_new = (orig_new >> 24) as u8; let third_byte_new = (((orig_new >> 16) & 127).wrapping_shl(24)>>24) as u8; let second_byte_new = (((orig_new >> 8) & 127).wrapping_shl(24)>>24) as u8; let first_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed[(byte_pos+2) as usize] = third_byte_new; output_seed[(byte_pos+3) as usize] = fourth_byte_new; output_seed } pub fn arithmetic_sub_four_bytes_another_endian_option(input_seed: &Vec<u8>, byte_pos:u64, arith_number:u32)->Option<Vec<u8>> { assert!(byte_pos < (input_seed.len() as u64) -3); //Attention: You need to ensure the byte_pos is legal let fourth_byte = input_seed[byte_pos as usize] as u32; let third_byte = input_seed[(byte_pos+1) as usize] as u32; let second_byte = input_seed[(byte_pos+2) as usize] as u32; let first_byte = input_seed[(byte_pos+3) as usize] as u32; let orig_old = first_byte.wrapping_shl(24) + second_byte.wrapping_shl(16) +third_byte.wrapping_shl(8) + fourth_byte; let orig_new = orig_old - arith_number; let xor_val = orig_old ^ orig_new; if could_be_bitflip(xor_val) { None } else { let mut output_seed = input_seed.clone(); let fourth_byte_new = (orig_new >> 24) as u8; let third_byte_new = (((orig_new >> 16) & 127).wrapping_shl(24)>>24) as u8; let second_byte_new = (((orig_new >> 8) & 127).wrapping_shl(24)>>24) as u8; let first_byte_new = (orig_new & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed[(byte_pos+2) as usize] = third_byte_new; output_seed[(byte_pos+3) as usize] = fourth_byte_new; Some(output_seed) } } // //Helper function to see if a particular value is reachable through // // arithmetic operations. // pub fn could_be_arith(old_val: u32, new_val: u32, byte_len: u8) -> bool { // let (mut ov, mut nv, mut diffs): (u32, u32, u32) = (0,0,0); // if(old_val == new_val) { // return 1; // } // for() // false // } pub fn interesting8_replace(input_seed: &Vec<u8>, byte_pos:u64, index_number:u8)->Vec<u8> { assert!(byte_pos < input_seed.len() as u64); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); assert!(index_number < config::INTERESTING_8_CNT); output_seed[byte_pos as usize] = config::INTERESTING_8[index_number as usize] as u8; output_seed } pub fn interesting16_replace(input_seed: &Vec<u8>, byte_pos:u64, index_number:u8)->Vec<u8> { assert!(byte_pos < input_seed.len() as u64 -1); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); assert!(index_number < config::INTERESTING_16_CNT); let replace_number = config::INTERESTING_16[index_number as usize]; let first_byte_new = (replace_number >> 8) as u8; let second_byte_new = (replace_number & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed } pub fn interesting16_replace_another_endian(input_seed: &Vec<u8>, byte_pos:u64, index_number:u8)->Vec<u8> { assert!(byte_pos < input_seed.len() as u64 -1); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); assert!(index_number < config::INTERESTING_16_CNT); let replace_number = config::INTERESTING_16[index_number as usize]; let second_byte_new = (replace_number >> 8) as u8; let first_byte_new = (replace_number & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed } pub fn interesting32_replace(input_seed: &Vec<u8>, byte_pos:u64, index_number:u8)->Vec<u8> { assert!(byte_pos < input_seed.len() as u64 -3); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); assert!(index_number < config::INTERESTING_32_CNT); //Attention: index should less than 32_cnt let replace_number = config::INTERESTING_32[index_number as usize]; let first_byte_new = (replace_number >> 24) as u8; let second_byte_new = (((replace_number >> 16) & 127).wrapping_shl(24)>>24) as u8; let third_byte_new = (((replace_number >> 8) & 127).wrapping_shl(24)>>24) as u8; let fourth_byte_new = (replace_number & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed[(byte_pos+2) as usize] = third_byte_new; output_seed[(byte_pos+3) as usize] = fourth_byte_new; output_seed } pub fn interesting32_replace_another_endian(input_seed: &Vec<u8>, byte_pos:u64, index_number:u8)->Vec<u8> { assert!(byte_pos < input_seed.len() as u64 -3); //Attention: You need to ensure the byte_pos is legal let mut output_seed = input_seed.clone(); assert!(index_number < config::INTERESTING_32_CNT); //Attention: index should less than 32_cnt let replace_number = config::INTERESTING_32[index_number as usize]; let fourth_byte_new = (replace_number >> 24) as u8; let third_byte_new = (((replace_number >> 16) & 127).wrapping_shl(24)>>24) as u8; let second_byte_new = (((replace_number >> 8) & 127).wrapping_shl(24)>>24) as u8; let first_byte_new = (replace_number & 127) as u8; output_seed[byte_pos as usize] = first_byte_new; output_seed[(byte_pos+1) as usize] = second_byte_new; output_seed[(byte_pos+2) as usize] = third_byte_new; output_seed[(byte_pos+3) as usize] = fourth_byte_new; output_seed } pub fn delete_byte(input_seed: &Vec<u8>, del_from:u64, del_len:u64)->Vec<u8> { assert!(del_from < input_seed.len() as u64); assert!(del_len >0); assert!(del_from + del_len -1 < input_seed.len() as u64);//del include del_from, del_end is del_from+del_len-1 let mut output_seed = input_seed.clone(); output_seed.drain((del_from as usize)..((del_from+del_len) as usize)); output_seed } //This function in AFL needs other information, //namely, 1.queue_cycle(cycles for passing the queue) 2.run_over10m(whether the fuzzer running for 10 minutes) //Here we first do not use these information, may be need update in future ... Why need? // Helper to choose random block len for block operations in fuzz_one(). // Doesn't return zero, provided that max_len is > 0. pub fn choose_block_len(limit:u64, rang:& mut rand::ThreadRng) -> u64 { let mut min_value:u64; let mut max_value:u64; let rlim = 3; //afl use MIN(queue_cycle, 3), here we simplify it to directly use 3 match rang.gen_range(0, rlim) { 0 => { min_value = 1; max_value = config::HAVOC_BLK_SMALL; }, 1 => { min_value = config::HAVOC_BLK_SMALL; max_value = config::HAVOC_BLK_MEDIUM; } _ => { if rang.gen_range(0,10) != 0 { min_value = config::HAVOC_BLK_MEDIUM; max_value = config::HAVOC_BLK_LARGE; } else { min_value = config::HAVOC_BLK_LARGE; max_value = config::HAVOC_BLK_XL; } } } if min_value >= limit { min_value = 1; } let interval = rang.gen_range(0, cmp::min(max_value, limit)-min_value+1); min_value + interval } pub fn insert_clone_bytes(input_seed: &Vec<u8>, rang:& mut rand::ThreadRng)->Vec<u8> { //We clone the input_seed from the clone_start_pos to clone_start_pos+clone_len-1 //We insert the clone bytes to the insert_pos assert!(input_seed.len() as u64 + config::HAVOC_BLK_XL < config::MAX_FILE);//how to let (clone_start_pos, clone_len, insert_pos):(usize, usize, usize); let len = input_seed.len() as u64; let mut output_seed = input_seed.clone(); //If is_clone_from_old_string does not equal to 0, we clone bytes from old string //else, we random set a block of bytes. let is_clone_from_old_string = rang.gen_range(0, 4); if(is_clone_from_old_string == 0) { clone_len = choose_block_len(config::HAVOC_BLK_XL, rang) as usize; clone_start_pos = 0; } else { clone_len = choose_block_len(len,rang) as usize; assert!(0 < len-(clone_len as u64)+1); clone_start_pos = rang.gen_range(0, len-(clone_len as u64)+1) as usize; } let insert = rang.gen_range(0, len) as usize; let mut temp_seed = input_seed.clone(); let insert_block: Vec<_>; if(is_clone_from_old_string == 0) { if(rang.gen_range(0,2) == 0) { let pad = rang.gen_range(0,256 as u16) as u8; insert_block = vec![pad;clone_len]; } else { let pad_pos = rang.gen_range(0,len) as usize; let pad = output_seed[pad_pos]; insert_block = vec![pad;clone_len]; } } else { insert_block = temp_seed.drain(clone_start_pos..clone_start_pos+clone_len).collect(); } output_seed.splice(insert..insert, insert_block.iter().cloned()); output_seed } // pub fn splice(input_seed: &Vec<u8>, random_input_seed: &Vec<u8>, rang:& mut rand::ThreadRng)->Vec<u8> { // assert!(output_seed.len() < 2); // output_seed = input_seed.clone(); // output_seed // } pub fn havoc_mutate(input_seed: &Vec<u8>, rang:& mut rand::ThreadRng)->Vec<u8> { // let mut random_value = rang.gen_range(0,config::HAVOC_WAY as u64); let len = input_seed.len() as u64; let max_random_value = match len{ 1 => { 9 } 2...3 => { 15 } _ => config::HAVOC_WAY as u32 }; let random_value = rang.gen_range(0,max_random_value); match random_value { //0--8 operations need one byte at least 0 => { //println!("we are using flipping bit"); flip_one_bit(input_seed, rang.gen_range(0,len.wrapping_shl(3))) }, 1 => { // println!("we are using flipping two bits"); let pos = rang.gen_range(0, len.wrapping_shl(3)-1); flip_two_bits(input_seed, pos) }, 2 => { // println!("we are using flipping four bits"); let pos = rang.gen_range(0, len.wrapping_shl(3)-3); flip_four_bits(input_seed, pos) }, 3 => { // println!("we are using flipping one byte"); let pos = rang.gen_range(0, len); flip_one_byte(input_seed, pos) }, 4 => { // println!("we are using arith_add_one_byte"); let pos = rang.gen_range(0, len); let arith_number = rang.gen_range(0, config::ARITH_MAX); arithmetic_add_one_byte(input_seed, pos, arith_number) }, 5 => { // println!("we are using arith_sub_one_byte"); let pos = rang.gen_range(0, len); let arith_number = rang.gen_range(0, config::ARITH_MAX); arithmetic_sub_one_byte(input_seed, pos, arith_number) }, 6 => { // println!("we are using interesting8"); let pos = rang.gen_range(0,len); let index_number = rang.gen_range(0,config::INTERESTING_8_CNT); interesting8_replace(input_seed, pos, index_number) }, 7 => { // println!("We are setting a random byte with a random value"); let pos = rang.gen_range(0, len); let random_byte_value = 1 + rang.gen_range(0,255); set_one_byte(input_seed, pos, random_byte_value) }, 8 => { //afl-fuzz 13 Extra-large blocks, selected very rarely (<5% of the time) if input_seed.len() as u64 + config::HAVOC_BLK_XL < config::MAX_FILE { // println!("We are inserting the clone bytes"); insert_clone_bytes(input_seed, rang) } else { //not a good solution when the length is too long, but we first deal with it in this way //need a more elegant way in the second edition (like return a Result and deal with Err in lib.rs) let pos = rang.gen_range(0, len); let random_byte_value = 1 + rang.gen_range(0,255); set_one_byte(input_seed, pos, random_byte_value) } }, //9--14 operations need two bytes at least 9 => { // println!("we are using flipping two bytes"); let pos = rang.gen_range(0, len-1); flip_two_bytes(input_seed, pos) }, 10 => { // println!("we are using arithmetic_add_two_bytes, randomly choose endian"); let pos = rang.gen_range(0, len-1); let arith_number = rang.gen_range(0, config::ARITH_MAX); let use_another = rang.gen_range(0,2); if use_another == 1 { arithmetic_add_two_bytes_another_endian(input_seed, pos, arith_number as u16) } else { arithmetic_add_two_bytes(input_seed, pos, arith_number as u16) } }, 11 => { // println!("we are using arithmetic_sub_two_bytes, randomly choose endian"); let pos = rang.gen_range(0, len-1); let arith_number = rang.gen_range(0, config::ARITH_MAX); let use_another = rang.gen_range(0,2); if use_another == 1 { arithmetic_sub_two_bytes_another_endian(input_seed, pos, arith_number as u16) } else { arithmetic_sub_two_bytes(input_seed, pos, arith_number as u16) } }, 12 => { // println!("we are using interesting16, randomly choose endian"); let pos = rang.gen_range(0, len-1); let index_number = rang.gen_range(0,config::INTERESTING_16_CNT); let use_another = rang.gen_range(0,2); if use_another == 1 { interesting16_replace(input_seed, pos, index_number) } else { interesting16_replace_another_endian(input_seed, pos, index_number) } }, 13 ...14 => { //need least two bytes // println!("we try to delete bytes"); let mut del_from:u64; let mut del_len:u64; del_len = choose_block_len(len-1, rang); del_from = rang.gen_range(0, len - del_len + 1); delete_byte(input_seed, del_from, del_len) }, //15--18 operations need four bytes at least 15 => { // println!("we are using flipping four bytes"); let pos = rang.gen_range(0, len-3); flip_four_bytes(input_seed, pos) }, 16 => { // println!("we are using arithmetic_add_four_bytes, randomly choose endian"); let pos = rang.gen_range(0, len-3); let arith_number = rang.gen_range(0, config::ARITH_MAX); let use_another = rang.gen_range(0,2); if use_another == 1 { arithmetic_add_four_bytes_another_endian(input_seed, pos, arith_number as u32) } else { arithmetic_add_four_bytes(input_seed, pos, arith_number as u32) } }, 17 => { // println!("we are using arithmetic_sub_four_bytes, randomly choose endian"); let pos = rang.gen_range(0, len-3); let arith_number = rang.gen_range(0, config::ARITH_MAX); let use_another = rang.gen_range(0,2); if use_another == 1 { arithmetic_sub_four_bytes_another_endian(input_seed, pos, arith_number as u32) } else { arithmetic_sub_four_bytes(input_seed, pos, arith_number as u32) } }, 18 => { // println!("we are using interesting32, randomly choose endian"); let pos = rang.gen_range(0, len-3); let index_number = rang.gen_range(0,config::INTERESTING_32_CNT); let use_another = rang.gen_range(0,2); if use_another == 1 { interesting32_replace(input_seed, pos, index_number) } else { interesting32_replace_another_endian(input_seed, pos, index_number) } }, 19 => { //afl-case 14 input_seed.clone() }, _ => input_seed.clone() } }
use std::time::Duration; use crate::error::{RotatorResult, RotatorError}; use crate::passwd::get_random_password; use crate::config::Config; use crate::iam::{ CredentialStatus, list_service_specific_credentials, create_service_specific_credential, reset_service_specific_credential, update_service_specific_credential, }; use crate::value::{ Secret, SecretValue, }; const MAX_SERVICE_SPECIFIC_CREDENTIALS: usize = 2; pub trait Resource { fn create_new_password(&self, current_value: SecretValue) -> RotatorResult<Secret>; fn set_password(&self, s: Secret) -> RotatorResult<()>; fn test_password(&self, s: Secret) -> RotatorResult<()>; } pub struct GenericResource { } impl GenericResource { #[allow(dead_code)] pub fn new() -> Self { GenericResource {} } } impl Resource for GenericResource { fn create_new_password(&self, _current_value: SecretValue) -> RotatorResult<Secret> { let timeout = Duration::from_secs(2); let password = get_random_password(timeout)?; Ok(Secret { password: Some(password), ..Default::default() }) } fn set_password(&self, _s: Secret) -> RotatorResult<()> { unimplemented!() } fn test_password(&self, _s: Secret) -> RotatorResult<()> { unimplemented!() } } #[derive(Debug, Clone)] pub struct ServiceSpecificCredentialResource { secret_id: String, user_name: String, service_name: String, } impl ServiceSpecificCredentialResource { pub fn new(cfg: &Config) -> RotatorResult<Self> { let service_name = cfg.service_name.as_ref().ok_or_else(|| RotatorError::InvalidConfig { secret_id: cfg.secret_id.to_string(), message: format!("missing service name for service specific credential"), })?; let user_name = cfg.user_name.as_ref().ok_or_else(|| RotatorError::InvalidConfig { secret_id: cfg.secret_id.to_string(), message: format!("missing resource arn for service specific credential"), })?; Ok(ServiceSpecificCredentialResource { secret_id: cfg.secret_id.to_string(), user_name: user_name.to_string(), service_name: service_name.to_string(), }) } } impl Resource for ServiceSpecificCredentialResource { fn create_new_password(&self, current_value: SecretValue) -> RotatorResult<Secret> { let timeout = Duration::from_secs(2); let creds = list_service_specific_credentials(Some(&self.user_name), Some(&self.service_name), timeout) .map_err(|err| RotatorError::IamError { secret_id: self.secret_id.to_string(), message: format!("list service specific credential error: {:?}", err), })?; info!("found {} service specific credentials: {:?}", creds.len(), creds); let mut cred; if creds.len() < MAX_SERVICE_SPECIFIC_CREDENTIALS { info!("creating service specific credential user_name={} service_name={}", self.user_name, self.service_name); cred = create_service_specific_credential(&self.user_name, &self.service_name, timeout) .map_err(|err| RotatorError::IamError { secret_id: self.secret_id.to_string(), message: format!("create service specific credential error: {:?}", err) })?; } else { let cred_to_reset = if let Some(credential_id) = current_value.secret.as_ref() .and_then(|secret| secret.service_specific_credential_id.as_ref()) { creds.iter().find(|cred| &cred.service_specific_credential_id != credential_id) } else { creds.get(0) }; if let Some(cred_to_reset) = cred_to_reset { info!("reseting service specific credential id={} user_name={}", cred_to_reset.service_specific_credential_id, cred_to_reset.service_user_name); cred = reset_service_specific_credential(&cred_to_reset.service_specific_credential_id, Some(&self.user_name), timeout) .map_err(|err| RotatorError::IamError { secret_id: self.secret_id.to_string(), message: format!("reset service specific credential error: {:?}", err) })?; if cred.status == CredentialStatus::Inactive { info!("activating service specific credential id={} user_name={}", cred.service_specific_credential_id, cred.service_user_name); update_service_specific_credential(&cred.service_specific_credential_id, Some(&self.user_name), CredentialStatus::Active, timeout) .map_err(|err| RotatorError::IamError { secret_id: self.secret_id.to_string(), message: format!("update service specific credential error: {:?}", err) })?; cred.status = CredentialStatus::Active; } } else { // shouldn't get here. there should be at least one credential that isn't current return Err(RotatorError::Other { message: format!("no empty credential slots to rotate") }); } } let mut secret = current_value.secret.clone().unwrap_or(Secret::default()); secret.username = Some(cred.service_user_name); secret.password = Some(cred.service_password); secret.service_specific_credential_id = Some(cred.service_specific_credential_id); Ok(secret) } fn set_password(&self, _s: Secret) -> RotatorResult<()> { info!("nothing to do to set password"); Ok(()) } fn test_password(&self, _s: Secret) -> RotatorResult<()> { info!("test_password unimplemented"); Ok(()) } }
fn main() { proconio::input!{n:u64,x:u64,t:u64} println!("{}", (n+x-1)/x*t); }
use crate::snapshot_comparison::Language; use crate::{ check_flight_error, run_influxql, run_sql, snapshot_comparison, try_run_influxql, try_run_sql, MiniCluster, }; use arrow::record_batch::RecordBatch; use arrow_util::assert_batches_sorted_eq; use futures::future::BoxFuture; use http::StatusCode; use observability_deps::tracing::info; use std::{path::PathBuf, time::Duration}; use test_helpers::assert_contains; const MAX_QUERY_RETRY_TIME_SEC: u64 = 20; /// Test harness for end to end tests that are comprised of several steps pub struct StepTest<'a, S> { cluster: &'a mut MiniCluster, /// The test steps to perform steps: Box<dyn Iterator<Item = S> + Send + Sync + 'a>, } /// The test state that is passed to custom steps pub struct StepTestState<'a> { /// The mini cluster cluster: &'a mut MiniCluster, /// How many Parquet files the catalog service knows about for the mini cluster's namespace, /// for tracking when persistence has happened. If this is `None`, we haven't ever checked with /// the catalog service. num_parquet_files: Option<usize>, } impl<'a> StepTestState<'a> { /// Get a reference to the step test state's cluster. #[must_use] pub fn cluster(&self) -> &&'a mut MiniCluster { &self.cluster } /// Get a reference to the step test state's cluster. #[must_use] pub fn cluster_mut(&mut self) -> &mut &'a mut MiniCluster { &mut self.cluster } /// Store the number of Parquet files the catalog has for the mini cluster's namespace. /// Call this before a write to be able to tell when a write has been persisted by checking for /// a change in this count. pub async fn record_num_parquet_files(&mut self) { let num_parquet_files = self.get_num_parquet_files().await; info!( "Recorded count of Parquet files for namespace {}: {num_parquet_files}", self.cluster.namespace() ); self.num_parquet_files = Some(num_parquet_files); } /// Wait for a change (up to a timeout) in the number of Parquet files the catalog has for the /// mini cluster's namespacee since the last time the number of Parquet files was recorded, /// which indicates persistence has taken place. pub async fn wait_for_num_parquet_file_change(&mut self, expected_increase: usize) { let retry_duration = Duration::from_secs(MAX_QUERY_RETRY_TIME_SEC); let num_parquet_files = self.num_parquet_files.expect( "No previous number of Parquet files recorded! \ Use `Step::RecordNumParquetFiles` before `Step::WaitForPersisted`.", ); let expected_count = num_parquet_files + expected_increase; tokio::time::timeout(retry_duration, async move { let mut interval = tokio::time::interval(Duration::from_millis(1000)); loop { let current_count = self.get_num_parquet_files().await; if current_count >= expected_count { info!( "Success; Parquet file count is now {current_count} \ which is at least {expected_count}" ); // Reset the saved value to require recording before waiting again self.num_parquet_files = None; return; } info!( "Retrying; Parquet file count is still {current_count} \ which is less than {expected_count}" ); interval.tick().await; } }) .await .expect("did not get additional Parquet files in the catalog"); } /// Ask the catalog service how many Parquet files it has for the mini cluster's namespace. async fn get_num_parquet_files(&self) -> usize { let connection = self.cluster.router().router_grpc_connection(); let mut catalog_client = influxdb_iox_client::catalog::Client::new(connection); catalog_client .get_parquet_files_by_namespace(self.cluster.namespace()) .await .map(|parquet_files| parquet_files.len()) .unwrap_or_default() } } /// Function used for custom [`Step`]s. /// /// It is an async function that receives a mutable reference to [`StepTestState`]. /// /// Example of creating one (note the `boxed()` call): /// ``` /// use futures::FutureExt; /// use futures::future::BoxFuture; /// use test_helpers_end_to_end::{FCustom, StepTestState}; /// /// let custom_function: FCustom = Box::new(|state: &mut StepTestState| { /// async move { /// // access the cluster: /// let cluster = state.cluster(); /// // Your potentially async code here /// }.boxed() /// }); /// ``` pub type FCustom = Box<dyn for<'b> Fn(&'b mut StepTestState) -> BoxFuture<'b, ()> + Send + Sync>; /// Function to do custom validation on metrics. Expected to panic on validation failure. pub type MetricsValidationFn = Box<dyn Fn(&mut StepTestState, String) + Send + Sync>; /// Possible test steps that a test can perform pub enum Step { /// Writes the specified line protocol to the `/api/v2/write` /// endpoint, assert the data was written successfully WriteLineProtocol(String), /// Writes the specified line protocol to the `/api/v2/write` endpoint; assert the request /// returned an error with the given code WriteLineProtocolExpectingError { line_protocol: String, expected_error_code: StatusCode, }, /// Writes the specified line protocol to the `/api/v2/write` endpoint /// using the specified authorization header, assert the data was /// written successfully. WriteLineProtocolWithAuthorization { line_protocol: String, authorization: String, }, /// Ask the catalog service how many Parquet files it has for this cluster's namespace. Do this /// before a write where you're interested in when the write has been persisted to Parquet; /// then after the write use `WaitForPersisted` to observe the change in the number of Parquet /// files from the value this step recorded. RecordNumParquetFiles, /// Query the catalog service for how many parquet files it has for this /// cluster's namespace, asserting the value matches expected. AssertNumParquetFiles { expected: usize }, /// Ask the ingester to persist immediately through the persist service gRPC API Persist, /// Wait for all previously written data to be persisted by observing an increase in the number /// of Parquet files in the catalog as specified for this cluster's namespace. WaitForPersisted { expected_increase: usize }, /// Set the namespace retention interval to a retention period, /// specified in ns relative to `now()`. `None` represents infinite retention /// (i.e. never drop data). SetRetention(Option<i64>), /// Run one compaction operation and wait for it to finish, expecting success. Compact, /// Run one compaction operation and wait for it to finish, expecting an error that matches /// the specified message. CompactExpectingError { expected_message: String }, /// Run a SQL query using the FlightSQL interface and verify that the /// results match the expected results using the /// `assert_batches_eq!` macro Query { sql: String, expected: Vec<&'static str>, }, /// Read the SQL queries in the specified file and verify that the results match the expected /// results in the corresponding expected file QueryAndCompare { input_path: PathBuf, setup_name: String, contents: String, }, /// Run a SQL query that's expected to fail using the FlightSQL interface and verify that the /// request returns the expected error code and message QueryExpectingError { sql: String, expected_error_code: tonic::Code, expected_message: String, }, /// Run a SQL query using the FlightSQL interface authorized by the /// authorization header. Verify that the /// results match the expected results using the `assert_batches_eq!` /// macro QueryWithAuthorization { sql: String, authorization: String, expected: Vec<&'static str>, }, /// Run a SQL query using the FlightSQL interface with the `iox-debug` header set. /// Verify that the /// results match the expected results using the `assert_batches_eq!` /// macro QueryWithDebug { sql: String, expected: Vec<&'static str>, }, /// Run a SQL query using the FlightSQL interface, and then verifies /// the results using the provided validation function on the /// results. /// /// The validation function is expected to panic on validation /// failure. VerifiedQuery { sql: String, verify: Box<dyn Fn(Vec<RecordBatch>) + Send + Sync>, }, /// Run an InfluxQL query using the FlightSQL interface and verify that the /// results match the expected results using the /// `assert_batches_eq!` macro InfluxQLQuery { query: String, expected: Vec<&'static str>, }, /// Read the InfluxQL queries in the specified file and verify that the results match the /// expected results in the corresponding expected file InfluxQLQueryAndCompare { input_path: PathBuf, setup_name: String, contents: String, }, /// Run an InfluxQL query that's expected to fail using the FlightSQL interface and verify that /// the request returns the expected error code and message InfluxQLExpectingError { query: String, expected_error_code: tonic::Code, expected_message: String, }, /// Run an InfluxQL query using the FlightSQL interface including an /// authorization header. Verify that the results match the expected /// results using the `assert_batches_eq!` macro. InfluxQLQueryWithAuthorization { query: String, authorization: String, expected: Vec<&'static str>, }, /// Read and verify partition keys for a given table PartitionKeys { table_name: String, namespace_name: Option<String>, expected: Vec<&'static str>, }, /// Attempt to gracefully shutdown all running ingester instances. /// /// This step blocks until all ingesters have gracefully stopped, or at /// least [`GRACEFUL_SERVER_STOP_TIMEOUT`] elapses before they are killed. /// /// [`GRACEFUL_SERVER_STOP_TIMEOUT`]: /// crate::server_fixture::GRACEFUL_SERVER_STOP_TIMEOUT GracefulStopIngesters, /// Retrieve the metrics and verify the results using the provided /// validation function. /// /// The validation function is expected to panic on validation /// failure. VerifiedMetrics(MetricsValidationFn), /// A custom step that can be used to implement special cases that /// are only used once. Custom(FCustom), } impl AsRef<Step> for Step { fn as_ref(&self) -> &Step { self } } impl<'a, S> StepTest<'a, S> where S: AsRef<Step>, { /// Create a new test that runs each `step`, in sequence, against /// `cluster` panic'ing if any step fails pub fn new<I>(cluster: &'a mut MiniCluster, steps: I) -> Self where I: IntoIterator<Item = S> + Send + Sync + 'a, <I as IntoIterator>::IntoIter: Send + Sync, { Self { cluster, steps: Box::new(steps.into_iter()), } } /// run the test. pub async fn run(self) { let Self { cluster, steps } = self; let mut state = StepTestState { cluster, num_parquet_files: Default::default(), }; for (i, step) in steps.enumerate() { info!("**** Begin step {} *****", i); match step.as_ref() { Step::WriteLineProtocol(line_protocol) => { info!( "====Begin writing line protocol to v2 HTTP API:\n{}", line_protocol ); let response = state.cluster.write_to_router(line_protocol, None).await; let status = response.status(); let body = hyper::body::to_bytes(response.into_body()) .await .expect("reading response body"); assert!( status == StatusCode::NO_CONTENT, "Invalid response code while writing line protocol:\n\nLine Protocol:\n{}\n\nExpected Status: {}\nActual Status: {}\n\nBody:\n{:?}", line_protocol, StatusCode::NO_CONTENT, status, body, ); info!("====Done writing line protocol"); } Step::WriteLineProtocolExpectingError { line_protocol, expected_error_code, } => { info!( "====Begin writing line protocol expecting error to v2 HTTP API:\n{}", line_protocol ); let response = state.cluster.write_to_router(line_protocol, None).await; assert_eq!(response.status(), *expected_error_code); info!("====Done writing line protocol expecting error"); } Step::WriteLineProtocolWithAuthorization { line_protocol, authorization, } => { info!( "====Begin writing line protocol (authenticated) to v2 HTTP API:\n{}", line_protocol ); let response = state .cluster .write_to_router(line_protocol, Some(authorization)) .await; assert_eq!(response.status(), StatusCode::NO_CONTENT); info!("====Done writing line protocol"); } // Get the current number of Parquet files in the cluster's namespace before // starting a new write so we can observe a change when waiting for persistence. Step::RecordNumParquetFiles => { state.record_num_parquet_files().await; } Step::AssertNumParquetFiles { expected } => { let have_files = state.get_num_parquet_files().await; assert_eq!(have_files, *expected); } // Ask the ingesters to persist immediately through the persist service gRPC API Step::Persist => { state.cluster().persist_ingesters().await; } Step::WaitForPersisted { expected_increase } => { info!("====Begin waiting for a change in the number of Parquet files"); state .wait_for_num_parquet_file_change(*expected_increase) .await; info!("====Done waiting for a change in the number of Parquet files"); } Step::Compact => { info!("====Begin running compaction"); state.cluster.run_compaction().unwrap(); info!("====Done running compaction"); } Step::CompactExpectingError { expected_message } => { info!("====Begin running compaction expected to error"); let err = state.cluster.run_compaction().unwrap_err(); assert_contains!(err, expected_message); info!("====Done running"); } Step::SetRetention(retention_period_ns) => { info!("====Begin setting retention period to {retention_period_ns:?}"); let namespace = state.cluster().namespace(); let router_connection = state.cluster().router().router_grpc_connection(); let mut client = influxdb_iox_client::namespace::Client::new(router_connection); client .update_namespace_retention(namespace, *retention_period_ns) .await .expect("Error updating retention period"); info!("====Done setting retention period"); } Step::Query { sql, expected } => { info!("====Begin running SQL query: {}", sql); // run query let (mut batches, schema) = run_sql( sql, state.cluster.namespace(), state.cluster.querier().querier_grpc_connection(), None, false, ) .await; batches.push(RecordBatch::new_empty(schema)); assert_batches_sorted_eq!(expected, &batches); info!("====Done running"); } Step::QueryAndCompare { input_path, setup_name, contents, } => { info!( "====Begin running SQL queries in file {}", input_path.display() ); snapshot_comparison::run( state.cluster, input_path.into(), setup_name.into(), contents.into(), Language::Sql, ) .await .unwrap(); info!("====Done running SQL queries"); } Step::QueryExpectingError { sql, expected_error_code, expected_message, } => { info!("====Begin running SQL query expected to error: {}", sql); let err = try_run_sql( sql, state.cluster().namespace(), state.cluster().querier().querier_grpc_connection(), None, false, ) .await .unwrap_err(); check_flight_error(err, *expected_error_code, Some(expected_message)); info!("====Done running"); } Step::QueryWithAuthorization { sql, authorization, expected, } => { info!("====Begin running SQL query (authenticated): {}", sql); // run query let (mut batches, schema) = run_sql( sql, state.cluster.namespace(), state.cluster().querier().querier_grpc_connection(), Some(authorization.as_str()), false, ) .await; batches.push(RecordBatch::new_empty(schema)); assert_batches_sorted_eq!(expected, &batches); info!("====Done running"); } Step::QueryWithDebug { sql, expected } => { info!("====Begin running SQL query (w/ iox-debug): {}", sql); // run query let (mut batches, schema) = run_sql( sql, state.cluster.namespace(), state.cluster().querier().querier_grpc_connection(), None, true, ) .await; batches.push(RecordBatch::new_empty(schema)); assert_batches_sorted_eq!(expected, &batches); info!("====Done running"); } Step::VerifiedQuery { sql, verify } => { info!("====Begin running SQL verified query: {}", sql); // run query let (batches, _schema) = run_sql( sql, state.cluster.namespace(), state.cluster.querier().querier_grpc_connection(), None, true, ) .await; verify(batches); info!("====Done running"); } Step::InfluxQLQuery { query, expected } => { info!("====Begin running InfluxQL query: {}", query); // run query let (mut batches, schema) = run_influxql( query, state.cluster.namespace(), state.cluster.querier().querier_grpc_connection(), None, ) .await; batches.push(RecordBatch::new_empty(schema)); assert_batches_sorted_eq!(expected, &batches); info!("====Done running"); } Step::InfluxQLQueryAndCompare { input_path, setup_name, contents, } => { info!( "====Begin running InfluxQL queries in file {}", input_path.display() ); snapshot_comparison::run( state.cluster, input_path.into(), setup_name.into(), contents.into(), Language::InfluxQL, ) .await .unwrap(); info!("====Done running InfluxQL queries"); } Step::InfluxQLExpectingError { query, expected_error_code, expected_message, } => { info!( "====Begin running InfluxQL query expected to error: {}", query ); let err = try_run_influxql( query, state.cluster().namespace(), state.cluster().querier().querier_grpc_connection(), None, ) .await .unwrap_err(); check_flight_error(err, *expected_error_code, Some(expected_message)); info!("====Done running"); } Step::InfluxQLQueryWithAuthorization { query, authorization, expected, } => { info!("====Begin running InfluxQL query: {}", query); // run query let (mut batches, schema) = run_influxql( query, state.cluster.namespace(), state.cluster.querier().querier_grpc_connection(), Some(authorization), ) .await; batches.push(RecordBatch::new_empty(schema)); assert_batches_sorted_eq!(expected, &batches); info!("====Done running"); } Step::PartitionKeys { table_name, namespace_name, expected, } => { info!("====Begin reading partition keys for table: {}", table_name); let partition_keys = state .cluster() .partition_keys(table_name, namespace_name.clone()) .await; // order the partition keys so that we can compare them let mut partition_keys = partition_keys; partition_keys.sort(); assert_eq!(partition_keys, *expected); info!("====Done reading partition keys"); } Step::GracefulStopIngesters => { info!("====Gracefully stop all ingesters"); state.cluster_mut().gracefully_stop_ingesters(); } Step::VerifiedMetrics(verify) => { info!("====Begin validating metrics"); let cluster = state.cluster(); let http_base = cluster.router().router_http_base(); let url = format!("{http_base}/metrics"); let client = reqwest::Client::new(); let metrics = client.get(&url).send().await.unwrap().text().await.unwrap(); verify(&mut state, metrics); info!("====Done validating metrics"); } Step::Custom(f) => { info!("====Begin custom step"); f(&mut state).await; info!("====Done custom step"); } } } } }
use clap; use crate::clients::{Parameters, VoteClient, VoteClientConstructor}; use memcached; use memcached::proto::{MultiOperation, ProtoType}; pub struct Constructor(String, bool); pub struct Client(memcached::Client, bool); impl VoteClientConstructor for Constructor { type Instance = Client; fn new(params: &Parameters, args: &clap::ArgMatches) -> Self { let addr = args.value_of("address").unwrap(); let fast = args.is_present("fast"); if params.prime { // prepop let mut c = memcached::Client::connect(&[(&format!("tcp://{}", addr), 1)], ProtoType::Binary) .unwrap(); let mut aid = 1; let bs = 1000; assert_eq!(params.articles % bs, 0); for _ in 0..params.articles / bs { use std::collections::BTreeMap; let articles: Vec<_> = (0..bs) .map(|i| { let article_id = aid + i; ( format!("article_{}", article_id), format!("Article #{}", article_id), format!("article_{}_vc", article_id), b"0", ) }) .collect(); let mut m = BTreeMap::new(); for &(ref tkey, ref title, ref vck, ref vc) in &articles { m.insert(tkey.as_bytes(), (title.as_bytes(), 0, 0)); m.insert(vck.as_bytes(), (&vc[..], 0, 0)); } c.set_multi(m).unwrap(); aid += bs; } } Constructor(addr.to_string(), fast) } fn make(&mut self) -> Self::Instance { memcached::Client::connect(&[(&format!("tcp://{}", self.0), 1)], ProtoType::Binary) .map(|c| Client(c, self.1)) .unwrap() } } impl VoteClient for Client { fn handle_writes(&mut self, ids: &[i32]) { use std::collections::HashMap; let keys: Vec<_> = ids .into_iter() .map(|article_id| format!("article_{}_vc", article_id)) .collect(); let ids: HashMap<_, _> = keys.iter().map(|key| (key.as_bytes(), (1, 0, 0))).collect(); //self.set_raw(&format!("voted_{}_{}", user, id), b"1", 0, 0).unwrap(); drop(self.0.increment_multi(ids)); } fn handle_reads(&mut self, ids: &[i32]) { let mut rows = 0; if self.1 { // fast -- don't fetch titles let keys: Vec<_> = ids .into_iter() .flat_map(|article_id| vec![format!("article_{}_vc", article_id)]) .collect(); let keys: Vec<_> = keys.iter().map(|k| k.as_bytes()).collect(); let vals = self.0.get_multi(&keys[..]).unwrap(); for key in keys { if vals.get(key).is_some() { rows += 1; } } } else { // slow -- also fetch titles let keys: Vec<_> = ids .into_iter() .flat_map(|article_id| { vec![ format!("article_{}", article_id), format!("article_{}_vc", article_id), ] }) .collect(); let keys: Vec<_> = keys.iter().map(|k| k.as_bytes()).collect(); let vals = self.0.get_multi(&keys[..]).unwrap(); for (i, key) in keys.iter().enumerate() { if i % 2 == 1 { // already read continue; } // title (vc has key i+1) match (vals.get(&**key), vals.get(keys[i + 1])) { (Some(_), Some(_)) => { rows += 1; } _ => {} } } } assert_eq!(rows, ids.len()); } }
//! HTTP and websocket server providing RPC calls to clients //! //! This is the main server application. It uses the `database`, `music_container` and `sync` crate //! to manage the music and provides further routines to upload or download music from the server. //! The server actually consists of three different server. A HTTP server provides the frontend to //! clients, the websocket server wraps function calls to the database and parses them and the sync //! server synchronizes the database between peers. Each has its own port, as set in the //! configuration, and the HTTP server as well as the sync server are disabled by default. To //! enable them, they have to be in the configuration file: //! //! ```toml //! host = "127.0.0.1" //! //! [webserver] //! path = "../frontend/build/" //! port = 8081 //! //! [sync] //! port = 8004 //! name = "Peer" //! sync_all = true //! ``` //! //! and can then be passed as an argument. (e.g. `./target/release/hex_server conf.toml`) #[macro_use] extern crate log; #[macro_use] extern crate futures; #[macro_use] extern crate serde_derive; mod error; mod webserver; mod acousticid; mod convert; mod server; mod state; use std::thread; use std::path::PathBuf; use std::net::SocketAddr; /// Main function spinning up all server fn main() { env_logger::init(); let (conf, path) = match hex_conf::Conf::new() { Ok(x) => x, Err(err) => { eprintln!("Error: Could not load configuration {:?}", err); (hex_conf::Conf::default(), PathBuf::from("/opt/music/")) } }; println!("Configuration: {:#?}", conf); // start the webserver in a seperate thread if it is mentioned in the configuration if let Some(webserver) = conf.webserver.clone() { let data_path = path.join("data"); let addr = SocketAddr::new(conf.host.clone(), webserver.port); thread::spawn(move || { webserver::create_webserver(addr, webserver.path.clone(), data_path.clone()); }); } // start the websocket server in the main thread server::start(conf, path) }
use proconio::input; fn main() { input! { n: usize, p: u64, q: u64, r: u64, a: [u64; n], }; let mut cum = vec![0; n + 1]; for i in 0..n { cum[i + 1] = cum[i] + a[i]; } for w in 1..=n { let s = cum[w]; if s >= r && cum.binary_search(&(s - r)).is_ok() { if s - r >= q && cum.binary_search(&(s - r - q)).is_ok() { if s - r - q >= p && cum.binary_search(&(s - r - q - p)).is_ok() { println!("Yes"); return; } } } } println!("No"); }
#![recursion_limit = "1024"] #[macro_use] extern crate error_chain; #[macro_use] extern crate lazy_static; extern crate openssl; extern crate regex; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate url; pub mod httpstream; pub mod tcp; pub mod unix; pub mod tls; pub mod errors; pub mod types; pub mod network; pub mod utils; pub mod queryparameters; pub mod engine; pub mod images; pub mod containers; // Export main types to top level of the crate pub use queryparameters::QueryFilter; pub use queryparameters::QueryParameters; pub use types::Client;
use super::entity::Entity; use super::resource_registry::ResourceRegistry; use super::shape::EntityShape; use anymap::AnyMap; use glutin::event::Event; use std::any::TypeId; pub type Resources = AnyMap; type SystemFn = fn(&mut Entity, resourceRegistry: &mut ResourceRegistry, value: &RunSystemPhase); type ServiceFn = fn(resourceRegistry: &mut ResourceRegistry, value: &RunSystemPhase); pub enum ServicePhase { Before, After, } pub enum SystemPhase { Update, Event, Tick, Render, } #[derive(Clone)] pub enum RunSystemPhase { Update(TypeId), Event(Event<'static, ()>), Tick, Render, } pub struct Service { pub(crate) phase: SystemPhase, pub(crate) calls: ServiceFn, pub(crate) update_key: Option<TypeId>, } impl Service { pub fn at_update<T: 'static>(_update_key: T, calls: ServiceFn) -> Self { Self { phase: SystemPhase::Update, calls, update_key: Some(TypeId::of::<T>()), } } pub fn at_event(calls: ServiceFn) -> Self { Self { phase: SystemPhase::Event, calls, update_key: None, } } pub fn at_tick(calls: ServiceFn) -> Self { Self { phase: SystemPhase::Tick, calls, update_key: None, } } pub fn at_render(calls: ServiceFn) -> Self { Self { phase: SystemPhase::Render, calls, update_key: None, } } } pub struct System { pub(crate) phase: SystemPhase, pub(crate) query: EntityShape, pub(crate) calls: SystemFn, pub(crate) update_key: Option<TypeId>, } impl System { pub fn at_update<T: 'static>(_event_key: T, query: EntityShape, calls: SystemFn) -> Self { Self { phase: SystemPhase::Update, query, calls, update_key: Some(TypeId::of::<T>()), } } pub fn at_event(query: EntityShape, calls: SystemFn) -> Self { Self { phase: SystemPhase::Event, query, calls, update_key: None, } } pub fn at_tick(query: EntityShape, calls: SystemFn) -> Self { Self { phase: SystemPhase::Tick, query, calls, update_key: None, } } pub fn at_render(query: EntityShape, calls: SystemFn) -> Self { Self { phase: SystemPhase::Render, query, calls, update_key: None, } } } pub struct SystemRunner { pub(crate) update: Vec<System>, pub(crate) before_update: Vec<Service>, pub(crate) after_update: Vec<Service>, pub(crate) tick: Vec<System>, pub(crate) before_tick: Vec<Service>, pub(crate) after_tick: Vec<Service>, pub(crate) render: Vec<System>, pub(crate) before_render: Vec<Service>, pub(crate) after_render: Vec<Service>, pub(crate) event: Vec<System>, pub(crate) before_event: Vec<Service>, pub(crate) after_event: Vec<Service>, } impl SystemRunner { pub fn new() -> Self { Self { update: Vec::new(), before_update: Vec::new(), after_update: Vec::new(), tick: Vec::new(), before_tick: Vec::new(), after_tick: Vec::new(), render: Vec::new(), before_render: Vec::new(), after_render: Vec::new(), event: Vec::new(), before_event: Vec::new(), after_event: Vec::new(), } } pub fn add(&mut self, system: System) { match system.phase { SystemPhase::Update => self.update.push(system), SystemPhase::Event => self.event.push(system), SystemPhase::Tick => self.tick.push(system), SystemPhase::Render => self.render.push(system), } } pub fn add_service(&mut self, service: Service, phase: ServicePhase) { match phase { ServicePhase::Before => match service.phase { SystemPhase::Update => self.before_update.push(service), SystemPhase::Event => self.before_event.push(service), SystemPhase::Tick => self.before_tick.push(service), SystemPhase::Render => self.before_render.push(service), }, ServicePhase::After => match service.phase { SystemPhase::Update => self.after_update.push(service), SystemPhase::Event => self.after_event.push(service), SystemPhase::Tick => self.after_tick.push(service), SystemPhase::Render => self.after_render.push(service), }, } } }
use super::{parse_zeek_timestamp, TryFromZeekRecord, PROTO_ICMP, PROTO_TCP, PROTO_UDP}; use anyhow::{anyhow, Context, Result}; use giganto_client::ingest::network::{Conn, DceRpc, Dns, Http, Kerberos, Ntlm, Rdp, Smtp, Ssh}; use num_traits::ToPrimitive; use std::net::IpAddr; impl TryFromZeekRecord for Conn { #[allow(clippy::too_many_lines)] fn try_from_zeek_record(rec: &csv::StringRecord) -> Result<(Self, i64)> { let time = if let Some(timestamp) = rec.get(0) { parse_zeek_timestamp(timestamp)?.timestamp_nanos() } else { return Err(anyhow!("missing timestamp")); }; let orig_addr = if let Some(orig_addr) = rec.get(2) { orig_addr .parse::<IpAddr>() .context("invalid source address")? } else { return Err(anyhow!("missing source address")); }; let orig_port = if let Some(orig_port) = rec.get(3) { orig_port.parse::<u16>().context("invalid source port")? } else { return Err(anyhow!("missing source port")); }; let resp_addr = if let Some(resp_addr) = rec.get(4) { resp_addr .parse::<IpAddr>() .context("invalid destination address")? } else { return Err(anyhow!("missing destination address")); }; let resp_port = if let Some(resp_port) = rec.get(5) { resp_port .parse::<u16>() .context("invalid destination port")? } else { return Err(anyhow!("missing destination port")); }; let proto = if let Some(proto) = rec.get(6) { match proto { "tcp" => PROTO_TCP, "udp" => PROTO_UDP, "icmp" => PROTO_ICMP, _ => 0, } } else { return Err(anyhow!("missing protocol")); }; let service = if let Some(service) = rec.get(7) { service.to_string() } else { return Err(anyhow!("missing service")); }; let duration = if let Some(duration) = rec.get(8) { if duration.eq("-") { 0 } else { ((duration.parse::<f64>().context("invalid duration")? * 1_000_000_000.0).round()) .to_i64() .expect("valid") } } else { return Err(anyhow!("missing duration")); }; let orig_bytes = if let Some(orig_bytes) = rec.get(9) { if orig_bytes.eq("-") { 0 } else { orig_bytes.parse::<u64>().context("invalid source bytes")? } } else { return Err(anyhow!("missing source bytes")); }; let resp_bytes = if let Some(resp_bytes) = rec.get(10) { if resp_bytes.eq("-") { 0 } else { resp_bytes .parse::<u64>() .context("invalid destination bytes")? } } else { return Err(anyhow!("missing destination bytes")); }; let orig_pkts = if let Some(orig_pkts) = rec.get(16) { if orig_pkts.eq("-") { 0 } else { orig_pkts.parse::<u64>().context("invalid source packets")? } } else { return Err(anyhow!("missing source packets")); }; let resp_pkts = if let Some(resp_pkts) = rec.get(18) { if resp_pkts.eq("-") { 0 } else { resp_pkts .parse::<u64>() .context("invalid destination packets")? } } else { return Err(anyhow!("missing destination packets")); }; Ok(( Self { orig_addr, orig_port, resp_addr, resp_port, proto, duration, service, orig_bytes, resp_bytes, orig_pkts, resp_pkts, }, time, )) } } impl TryFromZeekRecord for Dns { #[allow( clippy::similar_names, clippy::cast_possible_truncation, clippy::too_many_lines )] fn try_from_zeek_record(rec: &csv::StringRecord) -> Result<(Self, i64)> { let time = if let Some(timestamp) = rec.get(0) { parse_zeek_timestamp(timestamp)?.timestamp_nanos() } else { return Err(anyhow!("missing timestamp")); }; let orig_addr = if let Some(orig_addr) = rec.get(2) { orig_addr .parse::<IpAddr>() .context("invalid source address")? } else { return Err(anyhow!("missing source address")); }; let orig_port = if let Some(orig_port) = rec.get(3) { orig_port.parse::<u16>().context("invalid source port")? } else { return Err(anyhow!("missing source port")); }; let resp_addr = if let Some(resp_addr) = rec.get(4) { resp_addr .parse::<IpAddr>() .context("invalid destination address")? } else { return Err(anyhow!("missing destination address")); }; let resp_port = if let Some(resp_port) = rec.get(5) { resp_port .parse::<u16>() .context("invalid destination port")? } else { return Err(anyhow!("missing destination port")); }; let proto = if let Some(proto) = rec.get(6) { match proto { "tcp" => PROTO_TCP, "udp" => PROTO_UDP, "icmp" => PROTO_ICMP, _ => 0, } } else { return Err(anyhow!("missing protocol")); }; let query = if let Some(query) = rec.get(9) { query.to_string() } else { return Err(anyhow!("missing query")); }; let answer = if let Some(answer) = rec.get(21) { answer .split(',') .map(std::string::ToString::to_string) .collect() } else { return Err(anyhow!("missing answer")); }; let trans_id = if let Some(trans_id) = rec.get(7) { if trans_id.eq("-") { 0 } else { trans_id.parse::<u16>().context("invalid trans_id")? } } else { return Err(anyhow!("missing trans_id")); }; let rtt = if let Some(rtt) = rec.get(8) { if rtt.eq("-") { 0 } else { parse_zeek_timestamp(rtt)?.timestamp_nanos() } } else { return Err(anyhow!("missing rtt")); }; let qclass = if let Some(qclass) = rec.get(10) { if qclass.eq("-") { 0 } else { qclass.parse::<u16>().context("invalid qclass")? } } else { return Err(anyhow!("missing qclass")); }; let qtype = if let Some(qtype) = rec.get(12) { if qtype.eq("-") { 0 } else { qtype.parse::<u16>().context("invalid qtype")? } } else { return Err(anyhow!("missing qtype")); }; let rcode = if let Some(rcode) = rec.get(14) { if rcode.eq("-") { 0 } else { rcode.parse::<u16>().context("rcode")? } } else { return Err(anyhow!("missing rcode")); }; let aa_flag = if let Some(aa) = rec.get(16) { if aa.eq("T") { true } else if aa.eq("F") { false } else { return Err(anyhow!("invalid aa_flag")); } } else { return Err(anyhow!("missing aa_flag")); }; let tc_flag = if let Some(tc) = rec.get(17) { if tc.eq("T") { true } else if tc.eq("F") { false } else { return Err(anyhow!("invalid tc_flag")); } } else { return Err(anyhow!("missing tc_flag")); }; let rd_flag = if let Some(rd) = rec.get(18) { if rd.eq("T") { true } else if rd.eq("F") { false } else { return Err(anyhow!("invalid rd_flag")); } } else { return Err(anyhow!("missing rd_flag")); }; let ra_flag = if let Some(ra) = rec.get(19) { if ra.eq("T") { true } else if ra.eq("F") { false } else { return Err(anyhow!("invalid ra_flag")); } } else { return Err(anyhow!("missing ra_flag")); }; let ttl = if let Some(ttl) = rec.get(22) { if ttl.eq("-") { vec![0] } else { ttl.split(',') .map(|t| t.parse::<f32>().unwrap() as i32) .collect() } } else { return Err(anyhow!("missing ttl")); }; Ok(( Self { orig_addr, orig_port, resp_addr, resp_port, proto, last_time: rtt, query, answer, trans_id, rtt, qclass, qtype, rcode, aa_flag, tc_flag, rd_flag, ra_flag, ttl, }, time, )) } } impl TryFromZeekRecord for Http { #[allow(clippy::too_many_lines)] fn try_from_zeek_record(rec: &csv::StringRecord) -> Result<(Self, i64)> { let time = if let Some(timestamp) = rec.get(0) { parse_zeek_timestamp(timestamp)?.timestamp_nanos() } else { return Err(anyhow!("missing timestamp")); }; let orig_addr = if let Some(orig_addr) = rec.get(2) { orig_addr .parse::<IpAddr>() .context("invalid source address")? } else { return Err(anyhow!("missing source address")); }; let orig_port = if let Some(orig_port) = rec.get(3) { orig_port.parse::<u16>().context("invalid source port")? } else { return Err(anyhow!("missing source port")); }; let resp_addr = if let Some(resp_addr) = rec.get(4) { resp_addr .parse::<IpAddr>() .context("invalid destination address")? } else { return Err(anyhow!("missing destination address")); }; let resp_port = if let Some(resp_port) = rec.get(5) { resp_port .parse::<u16>() .context("invalid destination port")? } else { return Err(anyhow!("missing destination port")); }; let method = if let Some(method) = rec.get(7) { method.to_string() } else { return Err(anyhow!("missing method")); }; let host = if let Some(host) = rec.get(8) { host.to_string() } else { return Err(anyhow!("missing host")); }; let uri = if let Some(uri) = rec.get(9) { uri.to_string() } else { return Err(anyhow!("missing uri")); }; let referrer = if let Some(referrer) = rec.get(10) { referrer.to_string() } else { return Err(anyhow!("missing referrer")); }; let version = if let Some(version) = rec.get(11) { version.to_string() } else { return Err(anyhow!("missing version")); }; let user_agent = if let Some(user_agent) = rec.get(12) { user_agent.to_string() } else { return Err(anyhow!("missing user_agent")); }; let request_len = if let Some(request_len) = rec.get(14) { if request_len.eq("-") { 0 } else { request_len .parse::<usize>() .context("invalid request_len")? } } else { return Err(anyhow!("missing request_len")); }; let response_len = if let Some(response_len) = rec.get(15) { if response_len.eq("-") { 0 } else { response_len .parse::<usize>() .context("invalid response_len")? } } else { return Err(anyhow!("missing request_len")); }; let status_code = if let Some(status_code) = rec.get(16) { if status_code.eq("-") { 0 } else { status_code.parse::<u16>().context("invalid status code")? } } else { return Err(anyhow!("missing status code")); }; let status_msg = if let Some(status_msg) = rec.get(17) { status_msg.to_string() } else { return Err(anyhow!("missing status_msg")); }; let username = if let Some(username) = rec.get(21) { username.to_string() } else { return Err(anyhow!("missing username")); }; let password = if let Some(password) = rec.get(22) { password.to_string() } else { return Err(anyhow!("missing password")); }; Ok(( Self { orig_addr, orig_port, resp_addr, resp_port, proto: 0, last_time: 0, method, host, uri, referrer, version, user_agent, request_len, response_len, status_code, status_msg, username, password, cookie: String::from("-"), content_encoding: String::from("-"), content_type: String::from("-"), cache_control: String::from("-"), }, time, )) } } #[allow(clippy::too_many_lines)] impl TryFromZeekRecord for Kerberos { fn try_from_zeek_record(rec: &csv::StringRecord) -> Result<(Self, i64)> { let time = if let Some(timestamp) = rec.get(0) { parse_zeek_timestamp(timestamp)?.timestamp_nanos() } else { return Err(anyhow!("missing timestamp")); }; let orig_addr = if let Some(orig_addr) = rec.get(2) { orig_addr .parse::<IpAddr>() .context("invalid source address")? } else { return Err(anyhow!("missing source address")); }; let orig_port = if let Some(orig_port) = rec.get(3) { orig_port.parse::<u16>().context("invalid source port")? } else { return Err(anyhow!("missing source port")); }; let resp_addr = if let Some(resp_addr) = rec.get(4) { resp_addr .parse::<IpAddr>() .context("invalid destination address")? } else { return Err(anyhow!("missing destination address")); }; let resp_port = if let Some(resp_port) = rec.get(5) { resp_port .parse::<u16>() .context("invalid destination port")? } else { return Err(anyhow!("missing destination port")); }; let request_type = if let Some(request_type) = rec.get(6) { request_type.to_string() } else { return Err(anyhow!("missing request_type")); }; let client = if let Some(client) = rec.get(7) { client.to_string() } else { return Err(anyhow!("missing client")); }; let service = if let Some(service) = rec.get(8) { service.to_string() } else { return Err(anyhow!("missing service")); }; let success = if let Some(success) = rec.get(9) { success.to_string() } else { return Err(anyhow!("missing success")); }; let error_msg = if let Some(error_msg) = rec.get(10) { error_msg.to_string() } else { return Err(anyhow!("missing error_msg")); }; let from = if let Some(from) = rec.get(11) { if from.eq("-") { 0 } else { parse_zeek_timestamp(from)?.timestamp_nanos() } } else { return Err(anyhow!("missing from")); }; let till = if let Some(till) = rec.get(12) { if till.eq("-") { 0 } else { parse_zeek_timestamp(till)?.timestamp_nanos() } } else { return Err(anyhow!("missing till")); }; let cipher = if let Some(cipher) = rec.get(13) { cipher.to_string() } else { return Err(anyhow!("missing cipher")); }; let forwardable = if let Some(forwardable) = rec.get(14) { forwardable.to_string() } else { return Err(anyhow!("missing forwardable")); }; let renewable = if let Some(renewable) = rec.get(15) { renewable.to_string() } else { return Err(anyhow!("missing renewable")); }; let client_cert_subject = if let Some(client_cert_subject) = rec.get(16) { client_cert_subject.to_string() } else { return Err(anyhow!("missing client_cert_subject")); }; let server_cert_subject = if let Some(server_cert_subject) = rec.get(18) { server_cert_subject.to_string() } else { return Err(anyhow!("missing server_cert_subject")); }; Ok(( Self { orig_addr, orig_port, resp_addr, resp_port, proto: 0, last_time: 0, request_type, client, service, success, error_msg, from, till, cipher, forwardable, renewable, client_cert_subject, server_cert_subject, }, time, )) } } impl TryFromZeekRecord for Ntlm { fn try_from_zeek_record(rec: &csv::StringRecord) -> Result<(Self, i64)> { let time = if let Some(timestamp) = rec.get(0) { parse_zeek_timestamp(timestamp)?.timestamp_nanos() } else { return Err(anyhow!("missing timestamp")); }; let orig_addr = if let Some(orig_addr) = rec.get(2) { orig_addr .parse::<IpAddr>() .context("invalid source address")? } else { return Err(anyhow!("missing source address")); }; let orig_port = if let Some(orig_port) = rec.get(3) { orig_port.parse::<u16>().context("invalid source port")? } else { return Err(anyhow!("missing source port")); }; let resp_addr = if let Some(resp_addr) = rec.get(4) { resp_addr .parse::<IpAddr>() .context("invalid destination address")? } else { return Err(anyhow!("missing destination address")); }; let resp_port = if let Some(resp_port) = rec.get(5) { resp_port .parse::<u16>() .context("invalid destination port")? } else { return Err(anyhow!("missing destination port")); }; let username = if let Some(username) = rec.get(6) { username.to_string() } else { return Err(anyhow!("missing username")); }; let hostname = if let Some(hostname) = rec.get(7) { hostname.to_string() } else { return Err(anyhow!("missing hostname")); }; let domainname = if let Some(domainname) = rec.get(8) { domainname.to_string() } else { return Err(anyhow!("missing domainname")); }; let server_nb_computer_name = if let Some(server_nb_computer_name) = rec.get(9) { server_nb_computer_name.to_string() } else { return Err(anyhow!("missing server_nb_computer_name")); }; let server_dns_computer_name = if let Some(server_dns_computer_name) = rec.get(10) { server_dns_computer_name.to_string() } else { return Err(anyhow!("missing server_dns_computer_name")); }; let server_tree_name = if let Some(server_tree_name) = rec.get(11) { server_tree_name.to_string() } else { return Err(anyhow!("missing server_tree_name")); }; let success = if let Some(success) = rec.get(12) { success.to_string() } else { return Err(anyhow!("missing success")); }; Ok(( Self { orig_addr, orig_port, resp_addr, resp_port, proto: 0, last_time: 0, username, hostname, domainname, server_nb_computer_name, server_dns_computer_name, server_tree_name, success, }, time, )) } } impl TryFromZeekRecord for Rdp { fn try_from_zeek_record(rec: &csv::StringRecord) -> Result<(Self, i64)> { let time = if let Some(timestamp) = rec.get(0) { parse_zeek_timestamp(timestamp)?.timestamp_nanos() } else { return Err(anyhow!("missing timestamp")); }; let orig_addr = if let Some(orig_addr) = rec.get(2) { orig_addr .parse::<IpAddr>() .context("invalid source address")? } else { return Err(anyhow!("missing source address")); }; let orig_port = if let Some(orig_port) = rec.get(3) { orig_port.parse::<u16>().context("invalid source port")? } else { return Err(anyhow!("missing source port")); }; let resp_addr = if let Some(resp_addr) = rec.get(4) { resp_addr .parse::<IpAddr>() .context("invalid destination address")? } else { return Err(anyhow!("missing destination address")); }; let resp_port = if let Some(resp_port) = rec.get(5) { resp_port .parse::<u16>() .context("invalid destination port")? } else { return Err(anyhow!("missing destination port")); }; let cookie = if let Some(cookie) = rec.get(6) { cookie.to_string() } else { return Err(anyhow!("missing cookie")); }; Ok(( Self { orig_addr, orig_port, resp_addr, resp_port, proto: 0, last_time: 0, cookie, }, time, )) } } impl TryFromZeekRecord for Smtp { fn try_from_zeek_record(rec: &csv::StringRecord) -> Result<(Self, i64)> { let time = if let Some(timestamp) = rec.get(0) { parse_zeek_timestamp(timestamp)?.timestamp_nanos() } else { return Err(anyhow!("missing timestamp")); }; let orig_addr = if let Some(orig_addr) = rec.get(2) { orig_addr .parse::<IpAddr>() .context("invalid source address")? } else { return Err(anyhow!("missing source address")); }; let orig_port = if let Some(orig_port) = rec.get(3) { orig_port.parse::<u16>().context("invalid source port")? } else { return Err(anyhow!("missing source port")); }; let resp_addr = if let Some(resp_addr) = rec.get(4) { resp_addr .parse::<IpAddr>() .context("invalid destination address")? } else { return Err(anyhow!("missing destination address")); }; let resp_port = if let Some(resp_port) = rec.get(5) { resp_port .parse::<u16>() .context("invalid destination port")? } else { return Err(anyhow!("missing destination port")); }; let mailfrom = if let Some(mailfrom) = rec.get(8) { mailfrom.to_string() } else { return Err(anyhow!("missing mailfrom")); }; let date = if let Some(date) = rec.get(10) { date.to_string() } else { return Err(anyhow!("missing date")); }; let from = if let Some(from) = rec.get(11) { from.to_string() } else { return Err(anyhow!("missing from")); }; let to = if let Some(to) = rec.get(12) { to.to_string() } else { return Err(anyhow!("missing to")); }; let subject = if let Some(subject) = rec.get(17) { subject.to_string() } else { return Err(anyhow!("missing subject")); }; let agent = if let Some(agent) = rec.get(23) { agent.to_string() } else { return Err(anyhow!("missing agent")); }; Ok(( Self { orig_addr, orig_port, resp_addr, resp_port, proto: 0, last_time: 0, mailfrom, date, from, to, subject, agent, }, time, )) } } #[allow(clippy::too_many_lines)] impl TryFromZeekRecord for Ssh { fn try_from_zeek_record(rec: &csv::StringRecord) -> Result<(Self, i64)> { let time = if let Some(timestamp) = rec.get(0) { parse_zeek_timestamp(timestamp)?.timestamp_nanos() } else { return Err(anyhow!("missing timestamp")); }; let orig_addr = if let Some(orig_addr) = rec.get(2) { orig_addr .parse::<IpAddr>() .context("invalid source address")? } else { return Err(anyhow!("missing source address")); }; let orig_port = if let Some(orig_port) = rec.get(3) { orig_port.parse::<u16>().context("invalid source port")? } else { return Err(anyhow!("missing source port")); }; let resp_addr = if let Some(resp_addr) = rec.get(4) { resp_addr .parse::<IpAddr>() .context("invalid destination address")? } else { return Err(anyhow!("missing destination address")); }; let resp_port = if let Some(resp_port) = rec.get(5) { resp_port .parse::<u16>() .context("invalid destination port")? } else { return Err(anyhow!("missing destination port")); }; let version = if let Some(version) = rec.get(6) { if version.eq("-") { 0 } else { version.parse::<i64>().context("invalid version")? } } else { return Err(anyhow!("missing version")); }; let auth_success = if let Some(auth_success) = rec.get(7) { auth_success.to_string() } else { return Err(anyhow!("missing auth_success")); }; let auth_attempts = if let Some(auth_attempts) = rec.get(8) { if auth_attempts.eq("-") { 0 } else { auth_attempts .parse::<i64>() .context("invalid auth_attempts")? } } else { return Err(anyhow!("missing auth_attempts")); }; let direction = if let Some(direction) = rec.get(9) { direction.to_string() } else { return Err(anyhow!("missing direction")); }; let client = if let Some(client) = rec.get(10) { client.to_string() } else { return Err(anyhow!("missing client")); }; let server = if let Some(server) = rec.get(11) { server.to_string() } else { return Err(anyhow!("missing server")); }; let cipher_alg = if let Some(cipher_alg) = rec.get(12) { cipher_alg.to_string() } else { return Err(anyhow!("missing cipher_alg")); }; let mac_alg = if let Some(mac_alg) = rec.get(13) { mac_alg.to_string() } else { return Err(anyhow!("missing mac_alg")); }; let compression_alg = if let Some(compression_alg) = rec.get(14) { compression_alg.to_string() } else { return Err(anyhow!("missing compression_alg")); }; let kex_alg = if let Some(kex_alg) = rec.get(15) { kex_alg.to_string() } else { return Err(anyhow!("missing kex_alg")); }; let host_key_alg = if let Some(host_key_alg) = rec.get(16) { host_key_alg.to_string() } else { return Err(anyhow!("missing host_key_alg")); }; let host_key = if let Some(host_key) = rec.get(17) { host_key.to_string() } else { return Err(anyhow!("missing host_key")); }; Ok(( Self { orig_addr, orig_port, resp_addr, resp_port, proto: 0, last_time: 0, version, auth_success, auth_attempts, direction, client, server, cipher_alg, mac_alg, compression_alg, kex_alg, host_key_alg, host_key, }, time, )) } } impl TryFromZeekRecord for DceRpc { fn try_from_zeek_record(rec: &csv::StringRecord) -> Result<(Self, i64)> { let time = if let Some(timestamp) = rec.get(0) { parse_zeek_timestamp(timestamp)?.timestamp_nanos() } else { return Err(anyhow!("missing timestamp")); }; let orig_addr = if let Some(orig_addr) = rec.get(2) { orig_addr .parse::<IpAddr>() .context("invalid source address")? } else { return Err(anyhow!("missing source address")); }; let orig_port = if let Some(orig_port) = rec.get(3) { orig_port.parse::<u16>().context("invalid source port")? } else { return Err(anyhow!("missing source port")); }; let resp_addr = if let Some(resp_addr) = rec.get(4) { resp_addr .parse::<IpAddr>() .context("invalid destination address")? } else { return Err(anyhow!("missing destination address")); }; let resp_port = if let Some(resp_port) = rec.get(5) { resp_port .parse::<u16>() .context("invalid destination port")? } else { return Err(anyhow!("missing destination port")); }; let rtt = if let Some(rtt) = rec.get(6) { if rtt.eq("-") { 0 } else { parse_zeek_timestamp(rtt)?.timestamp_nanos() } } else { return Err(anyhow!("missing rtt")); }; let named_pipe = if let Some(named_pipe) = rec.get(7) { named_pipe.to_string() } else { return Err(anyhow!("missing named_pipe")); }; let endpoint = if let Some(endpoint) = rec.get(8) { endpoint.to_string() } else { return Err(anyhow!("missing endpoint")); }; let operation = if let Some(operation) = rec.get(9) { operation.to_string() } else { return Err(anyhow!("missing operation")); }; Ok(( Self { orig_addr, orig_port, resp_addr, resp_port, proto: 0, last_time: 0, rtt, named_pipe, endpoint, operation, }, time, )) } }
use async_std::task; use futures; use futures::executor::block_on; use std::thread::sleep; use std::time::Duration; #[derive(Debug)] struct Song { lyrics: String, } async fn learn_song() { task::sleep(Duration::new(5, 0)).await; println!("I'm learnding!") } async fn sing_song() { let song: Song = Song { lyrics: String::from("Whateva whateva, yea yea yea") }; println!("{:#?}", song); } async fn dance() { println!("I'm gonna dance!"); } //async fn learn_song() -> Song { } //async fn sing_song(song: Song) { } //async fn dance() { } async fn learn_and_sing() { // Wait until the song has been learned before singing it. // We use `.await` here rather than `block_on` to prevent blocking the // thread, which makes it possible to `dance` at the same time. // note what happens to elision if you remove learn_song's .await... let song = learn_song().await; sing_song().await; } async fn async_main() { // note what happens to elision if you remove learn_and_sing's .await... let f1 = learn_and_sing(); let f2 = dance(); // `join!` is like `.await` but can wait for multiple futures concurrently. // If we're temporarily blocked in the `learn_and_sing` future, the `dance` // future will take over the current thread. If `dance` becomes blocked, // `learn_and_sing` can take back over. If both futures are blocked, then // `async_main` is blocked and will yield to the executor. futures::join!(f1, f2); } fn main() { block_on(async_main()) }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IMicrosoftAccountMultiFactorAuthenticationManager(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMicrosoftAccountMultiFactorAuthenticationManager { type Vtable = IMicrosoftAccountMultiFactorAuthenticationManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0fd340a5_f574_4320_a08e_0a19a82322aa); } #[repr(C)] #[doc(hidden)] pub struct IMicrosoftAccountMultiFactorAuthenticationManager_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, useraccountid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, codelength: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, useraccountid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, authenticationtoken: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, wnschannelid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, useraccountid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, useraccountid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, channeluri: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, useraccountidlist: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, useraccountidlist: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sessionauthentictionstatus: MicrosoftAccountMultiFactorSessionAuthenticationStatus, authenticationsessioninfo: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sessionauthentictionstatus: MicrosoftAccountMultiFactorSessionAuthenticationStatus, useraccountid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessionid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessionauthenticationtype: MicrosoftAccountMultiFactorAuthenticationType, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, authenticationsessioninfo: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, useraccountid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessionid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessionauthenticationtype: MicrosoftAccountMultiFactorAuthenticationType, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMicrosoftAccountMultiFactorAuthenticatorStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMicrosoftAccountMultiFactorAuthenticatorStatics { type Vtable = IMicrosoftAccountMultiFactorAuthenticatorStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd964c2e6_f446_4c71_8b79_6ea4024aa9b8); } #[repr(C)] #[doc(hidden)] pub struct IMicrosoftAccountMultiFactorAuthenticatorStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMicrosoftAccountMultiFactorGetSessionsResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMicrosoftAccountMultiFactorGetSessionsResult { type Vtable = IMicrosoftAccountMultiFactorGetSessionsResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4e23a9a0_e9fa_497a_95de_6d5747bf974c); } #[repr(C)] #[doc(hidden)] pub struct IMicrosoftAccountMultiFactorGetSessionsResult_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MicrosoftAccountMultiFactorServiceResponse) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMicrosoftAccountMultiFactorOneTimeCodedInfo(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMicrosoftAccountMultiFactorOneTimeCodedInfo { type Vtable = IMicrosoftAccountMultiFactorOneTimeCodedInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x82ba264b_d87c_4668_a976_40cfae547d08); } #[repr(C)] #[doc(hidden)] pub struct IMicrosoftAccountMultiFactorOneTimeCodedInfo_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MicrosoftAccountMultiFactorServiceResponse) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IMicrosoftAccountMultiFactorSessionInfo(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMicrosoftAccountMultiFactorSessionInfo { type Vtable = IMicrosoftAccountMultiFactorSessionInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5f7eabb4_a278_4635_b765_b494eb260af4); } #[repr(C)] #[doc(hidden)] pub struct IMicrosoftAccountMultiFactorSessionInfo_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MicrosoftAccountMultiFactorSessionApprovalStatus) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MicrosoftAccountMultiFactorAuthenticationType) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo { type Vtable = IMicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaa7ec5fb_da3f_4088_a20d_5618afadb2e5); } #[repr(C)] #[doc(hidden)] pub struct IMicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MicrosoftAccountMultiFactorServiceResponse) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MicrosoftAccountMultiFactorAuthenticationManager(pub ::windows::core::IInspectable); impl MicrosoftAccountMultiFactorAuthenticationManager { #[cfg(feature = "Foundation")] pub fn GetOneTimePassCodeAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, useraccountid: Param0, codelength: u32) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorOneTimeCodedInfo>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), useraccountid.into_param().abi(), codelength, &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorOneTimeCodedInfo>>(result__) } } #[cfg(feature = "Foundation")] pub fn AddDeviceAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, useraccountid: Param0, authenticationtoken: Param1, wnschannelid: Param2) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), useraccountid.into_param().abi(), authenticationtoken.into_param().abi(), wnschannelid.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveDeviceAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, useraccountid: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), useraccountid.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>>(result__) } } #[cfg(feature = "Foundation")] pub fn UpdateWnsChannelAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, useraccountid: Param0, channeluri: Param1) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), useraccountid.into_param().abi(), channeluri.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetSessionsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(&self, useraccountidlist: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorGetSessionsResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), useraccountidlist.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorGetSessionsResult>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetSessionsAndUnregisteredAccountsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(&self, useraccountidlist: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), useraccountidlist.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo>>(result__) } } #[cfg(feature = "Foundation")] pub fn ApproveSessionUsingAuthSessionInfoAsync<'a, Param1: ::windows::core::IntoParam<'a, MicrosoftAccountMultiFactorSessionInfo>>(&self, sessionauthentictionstatus: MicrosoftAccountMultiFactorSessionAuthenticationStatus, authenticationsessioninfo: Param1) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), sessionauthentictionstatus, authenticationsessioninfo.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>>(result__) } } #[cfg(feature = "Foundation")] pub fn ApproveSessionAsync<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( &self, sessionauthentictionstatus: MicrosoftAccountMultiFactorSessionAuthenticationStatus, useraccountid: Param1, sessionid: Param2, sessionauthenticationtype: MicrosoftAccountMultiFactorAuthenticationType, ) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), sessionauthentictionstatus, useraccountid.into_param().abi(), sessionid.into_param().abi(), sessionauthenticationtype, &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>>(result__) } } #[cfg(feature = "Foundation")] pub fn DenySessionUsingAuthSessionInfoAsync<'a, Param0: ::windows::core::IntoParam<'a, MicrosoftAccountMultiFactorSessionInfo>>(&self, authenticationsessioninfo: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), authenticationsessioninfo.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>>(result__) } } #[cfg(feature = "Foundation")] pub fn DenySessionAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, useraccountid: Param0, sessionid: Param1, sessionauthenticationtype: MicrosoftAccountMultiFactorAuthenticationType) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), useraccountid.into_param().abi(), sessionid.into_param().abi(), sessionauthenticationtype, &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<MicrosoftAccountMultiFactorServiceResponse>>(result__) } } pub fn Current() -> ::windows::core::Result<MicrosoftAccountMultiFactorAuthenticationManager> { Self::IMicrosoftAccountMultiFactorAuthenticatorStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MicrosoftAccountMultiFactorAuthenticationManager>(result__) }) } pub fn IMicrosoftAccountMultiFactorAuthenticatorStatics<R, F: FnOnce(&IMicrosoftAccountMultiFactorAuthenticatorStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MicrosoftAccountMultiFactorAuthenticationManager, IMicrosoftAccountMultiFactorAuthenticatorStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MicrosoftAccountMultiFactorAuthenticationManager { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorAuthenticationManager;{0fd340a5-f574-4320-a08e-0a19a82322aa})"); } unsafe impl ::windows::core::Interface for MicrosoftAccountMultiFactorAuthenticationManager { type Vtable = IMicrosoftAccountMultiFactorAuthenticationManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0fd340a5_f574_4320_a08e_0a19a82322aa); } impl ::windows::core::RuntimeName for MicrosoftAccountMultiFactorAuthenticationManager { const NAME: &'static str = "Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorAuthenticationManager"; } impl ::core::convert::From<MicrosoftAccountMultiFactorAuthenticationManager> for ::windows::core::IUnknown { fn from(value: MicrosoftAccountMultiFactorAuthenticationManager) -> Self { value.0 .0 } } impl ::core::convert::From<&MicrosoftAccountMultiFactorAuthenticationManager> for ::windows::core::IUnknown { fn from(value: &MicrosoftAccountMultiFactorAuthenticationManager) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MicrosoftAccountMultiFactorAuthenticationManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MicrosoftAccountMultiFactorAuthenticationManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MicrosoftAccountMultiFactorAuthenticationManager> for ::windows::core::IInspectable { fn from(value: MicrosoftAccountMultiFactorAuthenticationManager) -> Self { value.0 } } impl ::core::convert::From<&MicrosoftAccountMultiFactorAuthenticationManager> for ::windows::core::IInspectable { fn from(value: &MicrosoftAccountMultiFactorAuthenticationManager) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MicrosoftAccountMultiFactorAuthenticationManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MicrosoftAccountMultiFactorAuthenticationManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MicrosoftAccountMultiFactorAuthenticationManager {} unsafe impl ::core::marker::Sync for MicrosoftAccountMultiFactorAuthenticationManager {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MicrosoftAccountMultiFactorAuthenticationType(pub i32); impl MicrosoftAccountMultiFactorAuthenticationType { pub const User: MicrosoftAccountMultiFactorAuthenticationType = MicrosoftAccountMultiFactorAuthenticationType(0i32); pub const Device: MicrosoftAccountMultiFactorAuthenticationType = MicrosoftAccountMultiFactorAuthenticationType(1i32); } impl ::core::convert::From<i32> for MicrosoftAccountMultiFactorAuthenticationType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MicrosoftAccountMultiFactorAuthenticationType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MicrosoftAccountMultiFactorAuthenticationType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorAuthenticationType;i4)"); } impl ::windows::core::DefaultType for MicrosoftAccountMultiFactorAuthenticationType { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MicrosoftAccountMultiFactorGetSessionsResult(pub ::windows::core::IInspectable); impl MicrosoftAccountMultiFactorGetSessionsResult { #[cfg(feature = "Foundation_Collections")] pub fn Sessions(&self) -> ::windows::core::Result<super::super::super::super::Foundation::Collections::IVectorView<MicrosoftAccountMultiFactorSessionInfo>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Foundation::Collections::IVectorView<MicrosoftAccountMultiFactorSessionInfo>>(result__) } } pub fn ServiceResponse(&self) -> ::windows::core::Result<MicrosoftAccountMultiFactorServiceResponse> { let this = self; unsafe { let mut result__: MicrosoftAccountMultiFactorServiceResponse = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MicrosoftAccountMultiFactorServiceResponse>(result__) } } } unsafe impl ::windows::core::RuntimeType for MicrosoftAccountMultiFactorGetSessionsResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorGetSessionsResult;{4e23a9a0-e9fa-497a-95de-6d5747bf974c})"); } unsafe impl ::windows::core::Interface for MicrosoftAccountMultiFactorGetSessionsResult { type Vtable = IMicrosoftAccountMultiFactorGetSessionsResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4e23a9a0_e9fa_497a_95de_6d5747bf974c); } impl ::windows::core::RuntimeName for MicrosoftAccountMultiFactorGetSessionsResult { const NAME: &'static str = "Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorGetSessionsResult"; } impl ::core::convert::From<MicrosoftAccountMultiFactorGetSessionsResult> for ::windows::core::IUnknown { fn from(value: MicrosoftAccountMultiFactorGetSessionsResult) -> Self { value.0 .0 } } impl ::core::convert::From<&MicrosoftAccountMultiFactorGetSessionsResult> for ::windows::core::IUnknown { fn from(value: &MicrosoftAccountMultiFactorGetSessionsResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MicrosoftAccountMultiFactorGetSessionsResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MicrosoftAccountMultiFactorGetSessionsResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MicrosoftAccountMultiFactorGetSessionsResult> for ::windows::core::IInspectable { fn from(value: MicrosoftAccountMultiFactorGetSessionsResult) -> Self { value.0 } } impl ::core::convert::From<&MicrosoftAccountMultiFactorGetSessionsResult> for ::windows::core::IInspectable { fn from(value: &MicrosoftAccountMultiFactorGetSessionsResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MicrosoftAccountMultiFactorGetSessionsResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MicrosoftAccountMultiFactorGetSessionsResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MicrosoftAccountMultiFactorGetSessionsResult {} unsafe impl ::core::marker::Sync for MicrosoftAccountMultiFactorGetSessionsResult {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MicrosoftAccountMultiFactorOneTimeCodedInfo(pub ::windows::core::IInspectable); impl MicrosoftAccountMultiFactorOneTimeCodedInfo { pub fn Code(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn TimeInterval(&self) -> ::windows::core::Result<super::super::super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Foundation")] pub fn TimeToLive(&self) -> ::windows::core::Result<super::super::super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Foundation::TimeSpan>(result__) } } pub fn ServiceResponse(&self) -> ::windows::core::Result<MicrosoftAccountMultiFactorServiceResponse> { let this = self; unsafe { let mut result__: MicrosoftAccountMultiFactorServiceResponse = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MicrosoftAccountMultiFactorServiceResponse>(result__) } } } unsafe impl ::windows::core::RuntimeType for MicrosoftAccountMultiFactorOneTimeCodedInfo { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorOneTimeCodedInfo;{82ba264b-d87c-4668-a976-40cfae547d08})"); } unsafe impl ::windows::core::Interface for MicrosoftAccountMultiFactorOneTimeCodedInfo { type Vtable = IMicrosoftAccountMultiFactorOneTimeCodedInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x82ba264b_d87c_4668_a976_40cfae547d08); } impl ::windows::core::RuntimeName for MicrosoftAccountMultiFactorOneTimeCodedInfo { const NAME: &'static str = "Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorOneTimeCodedInfo"; } impl ::core::convert::From<MicrosoftAccountMultiFactorOneTimeCodedInfo> for ::windows::core::IUnknown { fn from(value: MicrosoftAccountMultiFactorOneTimeCodedInfo) -> Self { value.0 .0 } } impl ::core::convert::From<&MicrosoftAccountMultiFactorOneTimeCodedInfo> for ::windows::core::IUnknown { fn from(value: &MicrosoftAccountMultiFactorOneTimeCodedInfo) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MicrosoftAccountMultiFactorOneTimeCodedInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MicrosoftAccountMultiFactorOneTimeCodedInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MicrosoftAccountMultiFactorOneTimeCodedInfo> for ::windows::core::IInspectable { fn from(value: MicrosoftAccountMultiFactorOneTimeCodedInfo) -> Self { value.0 } } impl ::core::convert::From<&MicrosoftAccountMultiFactorOneTimeCodedInfo> for ::windows::core::IInspectable { fn from(value: &MicrosoftAccountMultiFactorOneTimeCodedInfo) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MicrosoftAccountMultiFactorOneTimeCodedInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MicrosoftAccountMultiFactorOneTimeCodedInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MicrosoftAccountMultiFactorOneTimeCodedInfo {} unsafe impl ::core::marker::Sync for MicrosoftAccountMultiFactorOneTimeCodedInfo {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MicrosoftAccountMultiFactorServiceResponse(pub i32); impl MicrosoftAccountMultiFactorServiceResponse { pub const Success: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(0i32); pub const Error: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(1i32); pub const NoNetworkConnection: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(2i32); pub const ServiceUnavailable: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(3i32); pub const TotpSetupDenied: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(4i32); pub const NgcNotSetup: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(5i32); pub const SessionAlreadyDenied: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(6i32); pub const SessionAlreadyApproved: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(7i32); pub const SessionExpired: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(8i32); pub const NgcNonceExpired: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(9i32); pub const InvalidSessionId: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(10i32); pub const InvalidSessionType: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(11i32); pub const InvalidOperation: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(12i32); pub const InvalidStateTransition: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(13i32); pub const DeviceNotFound: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(14i32); pub const FlowDisabled: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(15i32); pub const SessionNotApproved: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(16i32); pub const OperationCanceledByUser: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(17i32); pub const NgcDisabledByServer: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(18i32); pub const NgcKeyNotFoundOnServer: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(19i32); pub const UIRequired: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(20i32); pub const DeviceIdChanged: MicrosoftAccountMultiFactorServiceResponse = MicrosoftAccountMultiFactorServiceResponse(21i32); } impl ::core::convert::From<i32> for MicrosoftAccountMultiFactorServiceResponse { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MicrosoftAccountMultiFactorServiceResponse { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MicrosoftAccountMultiFactorServiceResponse { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorServiceResponse;i4)"); } impl ::windows::core::DefaultType for MicrosoftAccountMultiFactorServiceResponse { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MicrosoftAccountMultiFactorSessionApprovalStatus(pub i32); impl MicrosoftAccountMultiFactorSessionApprovalStatus { pub const Pending: MicrosoftAccountMultiFactorSessionApprovalStatus = MicrosoftAccountMultiFactorSessionApprovalStatus(0i32); pub const Approved: MicrosoftAccountMultiFactorSessionApprovalStatus = MicrosoftAccountMultiFactorSessionApprovalStatus(1i32); pub const Denied: MicrosoftAccountMultiFactorSessionApprovalStatus = MicrosoftAccountMultiFactorSessionApprovalStatus(2i32); } impl ::core::convert::From<i32> for MicrosoftAccountMultiFactorSessionApprovalStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MicrosoftAccountMultiFactorSessionApprovalStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MicrosoftAccountMultiFactorSessionApprovalStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorSessionApprovalStatus;i4)"); } impl ::windows::core::DefaultType for MicrosoftAccountMultiFactorSessionApprovalStatus { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MicrosoftAccountMultiFactorSessionAuthenticationStatus(pub i32); impl MicrosoftAccountMultiFactorSessionAuthenticationStatus { pub const Authenticated: MicrosoftAccountMultiFactorSessionAuthenticationStatus = MicrosoftAccountMultiFactorSessionAuthenticationStatus(0i32); pub const Unauthenticated: MicrosoftAccountMultiFactorSessionAuthenticationStatus = MicrosoftAccountMultiFactorSessionAuthenticationStatus(1i32); } impl ::core::convert::From<i32> for MicrosoftAccountMultiFactorSessionAuthenticationStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MicrosoftAccountMultiFactorSessionAuthenticationStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for MicrosoftAccountMultiFactorSessionAuthenticationStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorSessionAuthenticationStatus;i4)"); } impl ::windows::core::DefaultType for MicrosoftAccountMultiFactorSessionAuthenticationStatus { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MicrosoftAccountMultiFactorSessionInfo(pub ::windows::core::IInspectable); impl MicrosoftAccountMultiFactorSessionInfo { pub fn UserAccountId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SessionId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn DisplaySessionId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn ApprovalStatus(&self) -> ::windows::core::Result<MicrosoftAccountMultiFactorSessionApprovalStatus> { let this = self; unsafe { let mut result__: MicrosoftAccountMultiFactorSessionApprovalStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MicrosoftAccountMultiFactorSessionApprovalStatus>(result__) } } pub fn AuthenticationType(&self) -> ::windows::core::Result<MicrosoftAccountMultiFactorAuthenticationType> { let this = self; unsafe { let mut result__: MicrosoftAccountMultiFactorAuthenticationType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MicrosoftAccountMultiFactorAuthenticationType>(result__) } } #[cfg(feature = "Foundation")] pub fn RequestTime(&self) -> ::windows::core::Result<super::super::super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Foundation::DateTime>(result__) } } #[cfg(feature = "Foundation")] pub fn ExpirationTime(&self) -> ::windows::core::Result<super::super::super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Foundation::DateTime>(result__) } } } unsafe impl ::windows::core::RuntimeType for MicrosoftAccountMultiFactorSessionInfo { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorSessionInfo;{5f7eabb4-a278-4635-b765-b494eb260af4})"); } unsafe impl ::windows::core::Interface for MicrosoftAccountMultiFactorSessionInfo { type Vtable = IMicrosoftAccountMultiFactorSessionInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5f7eabb4_a278_4635_b765_b494eb260af4); } impl ::windows::core::RuntimeName for MicrosoftAccountMultiFactorSessionInfo { const NAME: &'static str = "Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorSessionInfo"; } impl ::core::convert::From<MicrosoftAccountMultiFactorSessionInfo> for ::windows::core::IUnknown { fn from(value: MicrosoftAccountMultiFactorSessionInfo) -> Self { value.0 .0 } } impl ::core::convert::From<&MicrosoftAccountMultiFactorSessionInfo> for ::windows::core::IUnknown { fn from(value: &MicrosoftAccountMultiFactorSessionInfo) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MicrosoftAccountMultiFactorSessionInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MicrosoftAccountMultiFactorSessionInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MicrosoftAccountMultiFactorSessionInfo> for ::windows::core::IInspectable { fn from(value: MicrosoftAccountMultiFactorSessionInfo) -> Self { value.0 } } impl ::core::convert::From<&MicrosoftAccountMultiFactorSessionInfo> for ::windows::core::IInspectable { fn from(value: &MicrosoftAccountMultiFactorSessionInfo) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MicrosoftAccountMultiFactorSessionInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MicrosoftAccountMultiFactorSessionInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MicrosoftAccountMultiFactorSessionInfo {} unsafe impl ::core::marker::Sync for MicrosoftAccountMultiFactorSessionInfo {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo(pub ::windows::core::IInspectable); impl MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo { #[cfg(feature = "Foundation_Collections")] pub fn Sessions(&self) -> ::windows::core::Result<super::super::super::super::Foundation::Collections::IVectorView<MicrosoftAccountMultiFactorSessionInfo>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Foundation::Collections::IVectorView<MicrosoftAccountMultiFactorSessionInfo>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn UnregisteredAccounts(&self) -> ::windows::core::Result<super::super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } pub fn ServiceResponse(&self) -> ::windows::core::Result<MicrosoftAccountMultiFactorServiceResponse> { let this = self; unsafe { let mut result__: MicrosoftAccountMultiFactorServiceResponse = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MicrosoftAccountMultiFactorServiceResponse>(result__) } } } unsafe impl ::windows::core::RuntimeType for MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo;{aa7ec5fb-da3f-4088-a20d-5618afadb2e5})"); } unsafe impl ::windows::core::Interface for MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo { type Vtable = IMicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaa7ec5fb_da3f_4088_a20d_5618afadb2e5); } impl ::windows::core::RuntimeName for MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo { const NAME: &'static str = "Windows.Security.Authentication.Identity.Core.MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo"; } impl ::core::convert::From<MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo> for ::windows::core::IUnknown { fn from(value: MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo) -> Self { value.0 .0 } } impl ::core::convert::From<&MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo> for ::windows::core::IUnknown { fn from(value: &MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo> for ::windows::core::IInspectable { fn from(value: MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo) -> Self { value.0 } } impl ::core::convert::From<&MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo> for ::windows::core::IInspectable { fn from(value: &MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo {} unsafe impl ::core::marker::Sync for MicrosoftAccountMultiFactorUnregisteredAccountsAndSessionInfo {}
use std::vec::Vec; use std::cmp::Ordering; use std::mem; // courtesy of https://stackoverflow.com/a/28294764 fn swap<T>(x: &mut Vec<T>, i: usize, j: usize) { let (lo, hi) = match i.cmp(&j) { // no swapping necessary Ordering::Equal => return, // get the smallest and largest of the two indices Ordering::Less => (i, j), Ordering::Greater => (j ,i), }; let (init, tail) = x.split_at_mut(hi); mem::swap(&mut init[lo], &mut tail[0]); } // Implements Johnson-Trotter algorithm for generating permutations // Input: A positive integer n // Output: A list of all permutations of {1, ..., n} fn johnson_trotter(n: u8) { let mut a = Vec::<(u8, bool)>::new(); // initialize first permutation with all arrows pointing left print!("\t"); for i in 1..(n+1) { a.push((i, false)); print!("{}", i); } print!("\n"); // while the last permutation has a mobile element loop { let k = find_largest_mobile_element(&a); if k.1 { // no more mobile elements break; } // swap k with the adjacent element k's arrow points to let k_val = a[k.0].0; if a[k.0].1 { swap::<(u8, bool)>(&mut a, k.0, k.0 + 1); } else { swap::<(u8, bool)>(&mut a, k.0, k.0 - 1); } // reverse the direction of all the elements that are larger than k for i in 0..a.len() { if a[i].0 > k_val { a[i].1 ^= !a[i].1; } } // add the new permutation to the list print!("\t"); for j in 0..a.len() { print!("{}", a[j].0); } print!("\n"); } } fn find_largest_mobile_element(a: &Vec<(u8, bool)>) -> (usize, bool) { // find the permutation's largest mobile element k let mut k_val: u8 = 0; let mut k: usize = 0; for i in 0..a.len() { if a[i].0 > k_val { if a[i].1 { // arrow pointing to the right if (i != (a.len() - 1)) && a[i].0 > a[i + 1].0 { k = i; k_val = a[i].0; } } else { // arrow pointing to the left if (i != 0) && a[i].0 > a[i - 1].0 { k = i; k_val = a[i].0; } } } } // if k_val == 0, no mobile elements remain (k, k_val == 0) } fn main() { println!("Johnson-Trotter permutations for n = 4:"); johnson_trotter(4); }
#![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { if let Ok(s) = std::str::from_utf8(data) { if s.len() > 30 && &s[0..10] == "hardtofind" { println!("panic url:{}", s); panic!("BOOM"); } } });
use std::{ collections::HashMap, path::{Path, PathBuf}, time::{Duration, SystemTime}, }; use tokio::io::AsyncWriteExt; pub(crate) struct DeletionTracker { log_path: PathBuf, } const FOURTEEN_DAYS_AS_SECS: u64 = 7 * 24 * 60 * 60; #[cfg(not(windows))] const LINE_ENDING: &str = "\n"; #[cfg(windows)] const LINE_ENDING: &str = "\r\n"; impl DeletionTracker { pub fn new(alias_root_path: &Path) -> Self { DeletionTracker { log_path: alias_root_path.join(".ironcarrier"), } } pub async fn get_files(&self) -> crate::Result<HashMap<PathBuf, SystemTime>> { if !self.log_path.exists() { log::debug!("deletion log doesn't exist"); return Ok(HashMap::new()); } log::debug!("reading deletion log content"); let contents = tokio::fs::read(&self.log_path).await?; let contents = std::str::from_utf8(&contents)?; log::debug!("parsing deletiong log"); let log_entries = self.parse_log(&contents); return self.clean_and_rewrite(log_entries).await; } async fn clean_and_rewrite( &self, mut log_entries: HashMap<PathBuf, SystemTime>, ) -> crate::Result<HashMap<PathBuf, SystemTime>> { let count_before = log_entries.len(); let limit_date = SystemTime::now() - Duration::from_secs(FOURTEEN_DAYS_AS_SECS); log_entries.retain(|_, v| *v >= limit_date); if log_entries.len() == 0 { log::debug!( "dropped {} entries from log file, removing log file", count_before ); tokio::fs::remove_file(&self.log_path).await?; } else if count_before != log_entries.len() { log::debug!( "dropping {} entries from log file, recreating log", count_before - log_entries.len() ); let mut log_file = tokio::fs::File::create(&self.log_path).await?; for (path, time) in &log_entries { log_file .write_all(&self.create_line(&path, &time).as_bytes()) .await?; } log_file.flush().await?; } Ok(log_entries) } fn create_line(&self, path: &Path, time: &SystemTime) -> String { let time = time.duration_since(SystemTime::UNIX_EPOCH).unwrap(); format!("{},{}{}", path.display(), time.as_secs(), LINE_ENDING) } fn parse_line(&self, log_line: &str) -> Option<(PathBuf, SystemTime)> { let mut line = log_line.split(','); let d_path = line.next()?; let d_time: u64 = line.next().and_then(|v| v.parse::<u64>().ok())?; Some(( PathBuf::from(d_path), SystemTime::UNIX_EPOCH + Duration::from_secs(d_time), )) } fn parse_log(&self, log_content: &str) -> HashMap<PathBuf, SystemTime> { log_content .lines() .filter_map(|line| self.parse_line(line)) .collect() } pub async fn add_entry(&self, path: &Path) -> crate::Result<()> { log::debug!("adding entry to log file: {:?}", path); let mut log_file = tokio::fs::OpenOptions::new() .append(true) .create(true) .open(&self.log_path) .await?; log_file .write_all(&self.create_line(path, &SystemTime::now()).as_bytes()) .await?; log_file.flush().await?; Ok(()) } pub async fn remove_entry(&self, path: &Path) -> crate::Result<()> { if !self.log_path.exists() { return Ok(()); } log::debug!("removing entry {:?} from log", path); let mut log_file = tokio::fs::OpenOptions::new() .append(true) .open(&self.log_path) .await?; log_file .write_all(&self.create_line(path, &SystemTime::UNIX_EPOCH).as_bytes()) .await?; log_file.flush().await?; Ok(()) } }
use super::*; #[test] fn with_invalid_unit_errors_badarg() { with_process(|process| { assert_badarg!(result(process, atom!("invalid")), SUPPORTED_UNITS); }); } #[test] fn with_second_increases_after_2_seconds() { with_process(|process| { let unit = Atom::str_to_term("second"); let start_monotonic = monotonic::freeze(); let first = result(process, unit).unwrap(); monotonic::freeze_at(start_monotonic + Duration::from_secs(2)); let second = result(process, unit).unwrap(); assert!(first < second); }); } #[test] fn with_millisecond_increases_after_2_milliseconds() { with_process(|process| { let unit = Atom::str_to_term("millisecond"); let start_monotonic = monotonic::freeze(); let first = result(process, unit).unwrap(); monotonic::freeze_at(start_monotonic + Milliseconds(2)); let second = result(process, unit).unwrap(); assert!(first < second); }); } #[test] fn with_microsecond_increases_after_2_milliseconds() { with_process(|process| { let unit = Atom::str_to_term("microsecond"); let start_monotonic = monotonic::freeze(); let first = result(process, unit).unwrap(); monotonic::freeze_at(start_monotonic + Milliseconds(2)); let second = result(process, unit).unwrap(); assert!(first < second); }); } #[test] fn with_nanosecond_increases_after_2_milliseconds() { with_process(|process| { let unit = Atom::str_to_term("nanosecond"); let start_monotonic = monotonic::freeze(); let first = result(process, unit).unwrap(); monotonic::freeze_at(start_monotonic + Milliseconds(2)); let second = result(process, unit).unwrap(); assert!(first < second); }); } #[test] fn with_native_increases_after_2_native_time_units() { with_process(|process| { let unit = Atom::str_to_term("native"); let start_monotonic = monotonic::freeze(); let first = result(process, unit).unwrap(); monotonic::freeze_at(start_monotonic + Milliseconds(2)); let second = result(process, unit).unwrap(); assert!(first < second); }); } #[test] fn with_perf_counter_increases_after_2_perf_counter_ticks() { with_process(|process| { let unit = Atom::str_to_term("perf_counter"); let start_monotonic = monotonic::freeze(); let first = result(process, unit).unwrap(); monotonic::freeze_at(start_monotonic + Milliseconds(2)); let second = result(process, unit).unwrap(); assert!(first < second); }); }
use nalgebra::{Vector3, Point3, UnitQuaternion, Quaternion, Rotation3}; const JOINT_COUNT: usize = k4a::joint_id::K4ABT_JOINT_COUNT as usize; #[derive(Debug, Clone)] pub struct SmoothParams { smoothing: f64, correction: f64, prediction: f64, jitter_radius: f64, max_deviation_radius: f64, } impl Default for SmoothParams { fn default() -> Self { Self { smoothing: 0.25, correction: 0.25, prediction: 0.25, jitter_radius: 0.03, max_deviation_radius: 0.05, //jitter_angle: } } } #[derive(Debug, Clone)] pub struct FilteredJoint { pub raw_position: Point3<f64>, pub filtered_position: Point3<f64>, pub trend: Vector3<f64>, pub predicted_position: Point3<f64>, pub raw_orientation: UnitQuaternion<f64>, pub filtered_orientation: UnitQuaternion<f64>, pub orientation_trend: Rotation3<f64>, pub predicted_orientation: UnitQuaternion<f64>, pub frame_count: u64, } impl Default for FilteredJoint { fn default() -> Self { Self { raw_position: Point3::origin(), filtered_position: Point3::origin(), trend: Vector3::zeros(), predicted_position: Point3::origin(), raw_orientation: UnitQuaternion::identity(), filtered_orientation: UnitQuaternion::identity(), orientation_trend: Rotation3::identity(), predicted_orientation: UnitQuaternion::identity(), frame_count: 0, } } } impl FilteredJoint { pub fn update(&mut self, mut params: SmoothParams, joint: &k4a::Joint) { if joint.confidence_level.0 == 1 { params.jitter_radius *= 2.; params.max_deviation_radius *= 2.; } if joint.confidence_level.0 == 0 { self.frame_count = 0; } let prev_filtered_position: Point3<_> = self.filtered_position; let prev_trend: Vector3<_> = self.trend; let prev_raw_position: Point3<_> = self.raw_position; let prev_filtered_orientation = self.filtered_orientation; let prev_orientation_trend = self.orientation_trend; let prev_raw_orientation = self.raw_orientation; let raw_position: Point3<_> = k4a_float3_to_vector3f64(&joint.position).into(); let raw_orientation: UnitQuaternion<_> = k4a_quaternion_to_unit_quaternion_f64(&joint.orientation); if self.frame_count == 0 { self.filtered_position = raw_position; self.trend = Vector3::zeros(); self.filtered_orientation = raw_orientation; self.orientation_trend = Rotation3::identity(); self.frame_count += 1; } else if self.frame_count == 1 { self.filtered_position = nalgebra::center(&raw_position, &prev_raw_position); let diff = self.filtered_position.coords - prev_filtered_position.coords; self.trend = diff.lerp(&prev_trend, params.correction); self.filtered_orientation = raw_orientation.nlerp(&prev_raw_orientation, 0.5); let rot_to: UnitQuaternion<f64> = prev_filtered_orientation.rotation_to(&self.filtered_orientation); self.orientation_trend = rot_to.nlerp(&prev_orientation_trend.into(), params.correction).into(); self.frame_count += 1; } else { let jitter: f64 = nalgebra::distance(&raw_position, &prev_filtered_position); if jitter <= params.jitter_radius { self.filtered_position = raw_position.coords.lerp( &prev_filtered_position.coords, jitter / params.jitter_radius ).into(); } else { self.filtered_position = raw_position; } self.filtered_position = self.filtered_position.coords.lerp( &prev_filtered_position.coords, params.smoothing ).into(); let diff = self.filtered_position.coords - prev_filtered_position.coords; self.trend = diff.lerp(&prev_trend, params.correction); // no jitter filter for orientation self.filtered_orientation = raw_orientation; self.filtered_orientation = self.filtered_orientation.slerp( &prev_filtered_orientation, params.smoothing ); let rot_to: UnitQuaternion<f64> = prev_filtered_orientation.rotation_to(&self.filtered_orientation); self.orientation_trend = rot_to.nlerp(&prev_orientation_trend.into(), params.correction).into(); } self.predicted_position = ( self.filtered_position.coords + self.trend * params.prediction ).into(); let deviation: f64 = nalgebra::distance(&self.predicted_position, &raw_position); if deviation > params.max_deviation_radius { self.predicted_position = self.predicted_position.coords.lerp( &raw_position.coords, params.max_deviation_radius / deviation ).into(); } self.predicted_orientation = self.orientation_trend.powf(params.prediction) * self.filtered_orientation; self.raw_position = raw_position; self.raw_orientation = raw_orientation; } } #[derive(Debug, Clone)] pub struct KinectJointFilter { params: SmoothParams, pub joints: [FilteredJoint; JOINT_COUNT], } impl KinectJointFilter { pub fn new(params: SmoothParams) -> Self { Self { params, joints: Default::default(), } } pub fn update(&mut self, skeleton: &k4a::Skeleton) { for (idx, joint) in skeleton.joints.iter().enumerate() { self.joints[idx].update(self.params.clone(), joint); } } } fn k4a_float3_to_vector3f64(k4a_float3: &k4a::Float3) -> Vector3<f64> { Vector3::new( k4a_float3.x as f64, k4a_float3.y as f64, k4a_float3.z as f64, ) } fn k4a_quaternion_to_unit_quaternion_f64(k4a_q: &k4a::Quaternion) -> UnitQuaternion<f64> { UnitQuaternion::from_quaternion(Quaternion::new( k4a_q.w as f64, k4a_q.x as f64, k4a_q.y as f64, k4a_q.z as f64, )) }
use crate::state::mouse::MouseButton; use keyboard_types::{Code, Key}; #[derive(Debug, Clone, Copy, PartialEq)] pub enum CursorIcon { Arrow, NResize, EResize, } #[derive(Debug, Clone, PartialEq)] pub enum WindowEvent { WindowClose, WindowResize(f32, f32), MouseDown(MouseButton), MouseUp(MouseButton), MouseMove(f32, f32), MouseScroll(f32, f32), MouseOver, MouseOut, CharInput(char), KeyDown(Code, Option<Key>), KeyUp(Code, Option<Key>), SetCursor(CursorIcon), MouseCaptureEvent, MouseCaptureOutEvent, GeometryChanged, Redraw, Restyle, Relayout, }
pub struct Expr {}
//! Parse and compile crontab syntax, not needed for on-chain code. use std::str::FromStr; use crate::bitset::{BitSetIndex, NonEmptyBitSet}; use crate::cron::CronCompiled; #[derive(Clone, PartialEq, Debug)] pub enum CronItem { Range { /// inclusive start: BitSetIndex, /// inclusive end: BitSetIndex, step: BitSetIndex, }, Value(BitSetIndex), } impl CronItem { pub fn compile(&self) -> Option<NonEmptyBitSet> { match self { Self::Value(value) => Some(NonEmptyBitSet::new(*value)), Self::Range { start, end, step } => { NonEmptyBitSet::from_items((start.get()..=end.get()).step_by(step.get())) } } } } #[derive(Debug, PartialEq, Eq)] pub enum CronError { Empty, OutOfRange, } #[derive(Clone, PartialEq, Debug)] pub struct CronSpec { pub minute: Vec<CronItem>, pub hour: Vec<CronItem>, pub mday: Vec<CronItem>, pub month: Vec<CronItem>, pub wday: Vec<CronItem>, } impl CronSpec { pub fn compile(&self) -> Result<CronCompiled, CronError> { let minute = compile_component(&self.minute).ok_or(CronError::Empty)?; if minute.max().get() > 59 { return Err(CronError::OutOfRange); } let hour = compile_component(&self.hour).ok_or(CronError::Empty)?; if hour.max().get() > 23 { return Err(CronError::OutOfRange); } let mday = compile_component(&self.mday).ok_or(CronError::Empty)?; if mday.max().get() > 31 { return Err(CronError::OutOfRange); } if mday.min().get() < 1 { return Err(CronError::OutOfRange); } let month = compile_component(&self.month).ok_or(CronError::Empty)?; if month.max().get() > 12 { return Err(CronError::OutOfRange); } if month.min().get() < 1 { return Err(CronError::OutOfRange); } let wday = compile_component(&self.wday).ok_or(CronError::Empty)?; if wday.max().get() > 6 { return Err(CronError::OutOfRange); } Ok(CronCompiled { minute, hour, mday, month, wday, }) } } fn compile_component(items: &[CronItem]) -> Option<NonEmptyBitSet> { NonEmptyBitSet::from_bitsets(items.iter().map(|item| item.compile()).flatten()) } impl FromStr for CronSpec { type Err = &'static str; fn from_str(v: &str) -> Result<Self, Self::Err> { let parts: Vec<&str> = v.split(' ').collect(); if parts.len() != 5 { return Err("wrong number of cron components"); } Ok(CronSpec { minute: parse_component( parts[0], BitSetIndex::new(0).unwrap(), BitSetIndex::new(59).unwrap(), )?, hour: parse_component( parts[1], BitSetIndex::new(0).unwrap(), BitSetIndex::new(23).unwrap(), )?, mday: parse_component( parts[2], BitSetIndex::new(1).unwrap(), BitSetIndex::new(31).unwrap(), )?, month: parse_component( parts[3], BitSetIndex::new(1).unwrap(), BitSetIndex::new(12).unwrap(), )?, wday: parse_component( parts[4], BitSetIndex::new(0).unwrap(), BitSetIndex::new(6).unwrap(), )?, }) } } fn parse_component( v: &str, min: BitSetIndex, max: BitSetIndex, ) -> Result<Vec<CronItem>, &'static str> { let mut result = Vec::new(); for item in v.split(',') { let parts: Vec<&str> = item.split('/').collect(); if parts.len() == 1 || parts.len() == 2 { let step = parse_number(parts.get(1).unwrap_or(&"1"))?; let parts: Vec<&str> = parts[0].split('-').collect(); if parts.len() == 1 { if parts[0] == "*" { // any result.push(CronItem::Range { start: min, end: max, step, }); } else { // value result.push(CronItem::Value(parse_number(parts[0])?)); } } else if parts.len() == 2 { // range result.push(CronItem::Range { start: parse_number(parts[0])?, end: parse_number(parts[1])?, step, }); } else { return Err("wrong range syntax in cron"); } } else { return Err("wrong step syntax in cron"); } } Ok(result) } fn parse_number(v: &str) -> Result<BitSetIndex, &'static str> { let n = v.parse::<usize>().map_err(|_| "invalid cron number")?; BitSetIndex::new(n).ok_or("cron number out of range") } #[cfg(test)] mod tests { use super::*; #[test] fn cron_compile() { const FULL_CRON: CronCompiled = CronCompiled { minute: NonEmptyBitSet::from_range(0, 59), hour: NonEmptyBitSet::from_range(0, 23), mday: NonEmptyBitSet::from_range(1, 31), wday: NonEmptyBitSet::from_range(0, 6), month: NonEmptyBitSet::from_range(1, 12), }; let full = "* * * * *".parse::<CronSpec>().unwrap(); assert_eq!(full.compile().unwrap(), FULL_CRON); let empty = "2-1 * * * *".parse::<CronSpec>().unwrap(); assert_eq!(empty.compile().unwrap_err(), CronError::Empty); let steps = "*/2,*/3 1-10/3 * * *".parse::<CronSpec>().unwrap(); steps.compile().unwrap(); } }
use protocols::*; use types::*; use gates::*; use circuit::{BoolCircuit, BoolCircuitDesc, Output}; use std::collections::HashMap; // Debug Protocol pub struct DebugProtocol { this_party: u32, } impl ProtocolDesc for DebugProtocol { type VarType = bool; type CDescType = BoolCircuitDesc; fn new(party: u32)->Self { DebugProtocol { this_party: party } } fn get_party(&self)->u32{ self.this_party } fn exec_circuit(&self, circuit: &BoolCircuitDesc)->Vec<(Output, bool)> { let mut obliv_inputs = HashMap::new(); let mut outputs = Vec::new(); for &(ref input, ref b) in &circuit.inputs { obliv_inputs.insert(input.clone(), DebugOBool::feed(self, b.clone())); } outputs } } // Debug Bool #[derive(Clone)] pub struct DebugOBool { is_public: bool, know_value: bool, } #[allow(unused_variables)] impl OblivVar for DebugOBool { type Input = bool; type Output = Self; type PD = DebugProtocol; fn feed(pd: &DebugProtocol, src: bool)->Self { DebugOBool { is_public: false, know_value: src } } fn reveal(&self, pd: &DebugProtocol)->bool { self.know_value } fn is_public(&self)->bool { self.is_public } } impl OblivBool for DebugOBool { } #[allow(unused_variables)] impl OXor for DebugOBool { type PD = DebugProtocol; type OType = DebugOBool; fn o_xor(&self, pd: &DebugProtocol, other: &DebugOBool)->DebugOBool { DebugOBool {is_public: false, know_value: self.know_value ^ other.know_value} } } #[allow(unused_variables)] impl OAnd for DebugOBool { type PD = DebugProtocol; type OType = DebugOBool; fn o_and(&self, pd: &DebugProtocol, other: &DebugOBool)->DebugOBool { DebugOBool {is_public: false, know_value: self.know_value & other.know_value} } } #[allow(unused_variables)] impl OOr for DebugOBool { type PD = DebugProtocol; type OType = DebugOBool; fn o_or(&self, pd: &DebugProtocol, other: &DebugOBool)->DebugOBool { DebugOBool {is_public: false, know_value: self.know_value | other.know_value} } } #[allow(unused_variables)] impl ONot for DebugOBool { type PD = DebugProtocol; type OType = DebugOBool; fn o_not(&self, pd: &DebugProtocol)->DebugOBool { let mut temp = self.clone(); temp.know_value = !temp.know_value; temp } fn o_not_inplace(&mut self, pd: &DebugProtocol) { self.know_value = !self.know_value; } } #[cfg(test)] mod test { use super::{DebugProtocol, DebugOBool}; use circuit::*; use types::*; use protocols::*; use gates::*; #[test] fn test_new_protocol() { let pd = DebugProtocol::new(1); assert_eq!(pd.get_party(), 1); } #[test] fn test_feed_bool() { let pd = DebugProtocol::new(1); let a = DebugOBool::feed(&pd, true); assert_eq!(a.reveal(&pd), true); } #[test] fn test_gates_bool(){ let pd = DebugProtocol::new(1); let a = DebugOBool::feed(&pd, true); let mut b = DebugOBool::feed(&pd, false); assert_eq!(b.o_xor(&pd, &a).reveal(&pd), a.know_value ^ b.know_value); assert_eq!(b.o_and(&pd, &a).reveal(&pd), a.know_value & b.know_value); assert_eq!(b.o_or(&pd, &a).reveal(&pd), a.know_value | b.know_value); assert_eq!(b.o_not(&pd).reveal(&pd), !b.know_value); let temp = b.clone(); b.o_not_inplace(&pd); assert_eq!(b.reveal(&pd), !temp.know_value); } #[test] fn test_exec_circuit(){ let mut circuit = BoolCircuit::new(); circuit.feed(&Label(2), true); circuit.feed(&Label(3), false); circuit.feed(&Label(4), true); circuit.feed(&Label(5), false); circuit.xor(&Label(6), &Label(0), &Label(1)); circuit.and(&Label(7), &Label(2), &Label(3)); circuit.or(&Label(8), &Label(4), &Label(5)); circuit.xor(&Label(9), &Label(6), &Label(7)); circuit.not(&Label(10), &Label(8)); circuit.xor(&Label(11), &Label(9), &Label(10)); circuit.reveal(&Label(11)); circuit.debug_show_circuit(); } }
use std::path::Path; use std::fs::{File, OpenOptions}; use std::io::{Read, Cursor, Seek, SeekFrom}; use bytes::{Bytes, Buf}; use crate::reader::Reader; use anyhow::{Result, bail, anyhow, Error}; use crate::io; use crate::util; use std::cmp::min; use std::os::unix::io::{AsRawFd, RawFd}; use derivative::Derivative; use nix::unistd::Whence; use std::string::FromUtf8Error; use std::ffi::CString; pub const LOG_FLUSH_FLAG: u64 = 1 << 0; pub const LOG_FUA_FLAG: u64 = 1 << 1; pub const LOG_DISCARD_FLAG: u64 = 1 << 2; pub const LOG_MARK_FLAG: u64 = 1 << 3; pub const LOG_METADATA_FLAG: u64 = 1 << 4; pub const WRITE_LOG_VERSION: u64 = 1; pub const WRITE_LOG_MAGIC: u64 = 0x6a736677736872; #[derive(Debug, Copy, Clone)] pub struct LogWriteSuper { pub magic: u64, pub version: u64, pub nr_entries: u64, pub sector_size: u32, } impl From<[u8; 32]> for LogWriteSuper { fn from(buf: [u8; 32]) -> Self { let mut rdr = Reader::from(buf.to_vec()); let magic = rdr.read_u64_le(); let version = rdr.read_u64_le(); let nr_entries = rdr.read_u64_le(); let sector_size = rdr.read_u64_le() as u32; Self { magic, version, nr_entries, sector_size, } } } impl Default for LogWriteSuper { fn default() -> Self { Self { magic: 0, version: 0, nr_entries: 0, sector_size: 0, } } } pub struct FlagsToStrEntry { flags: u64, str: String, } macro_rules! log_flags_str_entry { ($f : ident, $s : expr ) => { FlagsToStrEntry { flags : $f, str : $s.to_string() } }; } #[inline] fn log_flags_table() -> Vec<FlagsToStrEntry> { vec![ log_flags_str_entry!(LOG_FLUSH_FLAG, "FLUSH"), log_flags_str_entry!(LOG_FUA_FLAG, "FUA"), log_flags_str_entry!(LOG_DISCARD_FLAG, "DISCARD"), log_flags_str_entry!(LOG_MARK_FLAG, "MARK"), log_flags_str_entry!(LOG_METADATA_FLAG, "METADATA") ] } #[derive(Debug)] pub struct LogWriteEntry { pub sector: u64, pub nr_sectors: u64, pub flags: u64, pub data_len: u64, pub cmd : String } impl From<Vec<u8>> for LogWriteEntry { fn from(buf: Vec<u8>) -> Self { let mut buf = buf; let header : Vec<_> = buf.drain(..Self::mem_size()).collect(); let mut rdr = Reader::from(header); let sector = rdr.read_u64_le(); let nr_sectors = rdr.read_u64_le(); let flags = rdr.read_u64_le(); let data_len = rdr.read_u64_le(); let mut valid_str = Vec::new(); for i in buf { if i > 0 { valid_str.push(i) }else { break } } let mut cmd = String::from_utf8(valid_str).unwrap_or_default(); Self { sector, nr_sectors, flags, data_len, cmd } } } // memory size of sector,nr_sector,flags,data_len) // (8 + 8 + 8 + 8) = 32 const LOG_WRITE_ENTRY_SIZE : usize = 32; impl MemSize for LogWriteEntry { fn mem_size() -> usize { LOG_WRITE_ENTRY_SIZE } } pub const LOG_IGNORE_DISCARD: u64 = 1 << 0; pub const LOG_DISCARD_NOT_SUPP: u64 = 1 << 1; pub const LOG_FLAGS_BUF_SIZE: usize = 128; #[derive(Derivative)] #[derivative(Debug)] pub struct Log { #[derivative(Debug="ignore")] pub log_file: File, #[derivative(Debug="ignore")] pub replay_file: File, pub flags: u64, pub nr_entries: u64, pub sector_size: u32, pub cur_entry: u64, pub max_zero_size: u64, pub cur_pos: u64, } pub trait MemSize { fn mem_size() -> usize; } pub fn entry_flags_to_str(flags: u64, buf: &mut String) { let mut flags = flags; let log_flags_table = log_flags_table(); let mut empty = true; for i in log_flags_table { if (flags & i.flags) > 0 { if !empty { util::strncat(buf, "|".to_string(), LOG_FLAGS_BUF_SIZE); } empty = false; util::strncat(buf, i.str, LOG_FLAGS_BUF_SIZE); flags &= !i.flags; } } if flags > 0 { if !empty { util::strncat(buf, "|".to_string(), LOG_FLAGS_BUF_SIZE); } empty = false; let left_len = LOG_FLAGS_BUF_SIZE - min(buf.len(), LOG_FLAGS_BUF_SIZE); if left_len > 0 { println!("UNKNOWN.{}", flags) } } if empty { buf.clear(); buf.push_str("None"); } } impl Log { pub fn fsync_replay_file(&self) -> Result<()> { self.replay_file.sync_all().map_err(|error| { anyhow!("IO Error {}", error) }) } fn discard_range(&mut self, start : u64, len : u64) -> i32 { let range : [u64;2] = [start, len]; let ret = unsafe { ioctls::blkdiscard(self.replay_file.as_raw_fd(), &range) }; if ret < 0 { println!("replay device doesn't support discard, switching to writing zeros"); self.flags |= LOG_DISCARD_NOT_SUPP; } return 0 } fn zero_range(&mut self, start : u64, len : u64) -> i32 { let mut start = start as usize; let mut len = len as usize; let mut ret : usize = 0; let mut bufsize : usize = len; if self.max_zero_size < len as u64{ println!("discard len {} larger than max {}", len, self.max_zero_size); return 0; } let mut buf : Vec<u8> = Vec::with_capacity(len); if buf.capacity() != len as usize { eprintln!("Couldn't allocate zero buffer"); return -1; } buf.fill(0); while len > 0 { ret = match io::pwrite(&self.replay_file, buf.as_slice(), start as i64){ Ok(ret) => { ret } Err(error) => { eprintln!("Error zeroing file {}", error); return -1 } }; if ret != bufsize { eprintln!("Error zeroing file"); return -1; } len -= ret; start += ret; } return 0; } fn discard(&mut self, entry: &LogWriteEntry) -> Result<()> { let mut start = entry.sector * self.sector_size as u64; let mut size = entry.nr_sectors * self.sector_size as u64; let max_chunk: u64 = 1 * 1024 * 1024 * 1024; if (self.flags & LOG_DISCARD_FLAG) != 0 { return Ok(()); } while size > 0 { let len = min(max_chunk, size); let mut ret : i32 = 0; if (self.flags & LOG_DISCARD_NOT_SUPP) <= 0 { ret = self.discard_range(start, len) } if (self.flags & LOG_DISCARD_NOT_SUPP) > 0 { ret = self.zero_range(start, len) } if ret > 0 { bail!("Discard error") } size -= len; start += len; } Ok(()) } pub fn open<P: AsRef<Path>>(log_file_path: P, replay_file_path: P) -> Result<Self> { let mut log_file = OpenOptions::new().read(true).write(false).open(log_file_path)?; let replay_file = OpenOptions::new().write(true).read(false).open(replay_file_path)?; let mut buf = [0_u8; 32]; io::read(&log_file, &mut buf)?; let log_super = LogWriteSuper::from(buf); println!("{:?}", log_super); if log_super.magic != WRITE_LOG_MAGIC { bail!("Magic doesn't match") } // Seek to first log entry io::lseek(&log_file, (log_super.sector_size as i64 - std::mem::size_of_val(&log_super) as i64), Whence::SeekCur).map_err(|error| { anyhow!("Error seeking to first entry: {}", error) })?; Ok(Self { log_file, replay_file, flags: 0, nr_entries: log_super.nr_entries, sector_size: log_super.sector_size, cur_entry: 0, max_zero_size: 128 * 1024 * 1024, cur_pos: 0, }) } pub fn replay_next_entry(&mut self, read_data: bool) -> Result<Option<LogWriteEntry>> { let read_size = if read_data { self.sector_size as usize } else { LogWriteEntry::mem_size() }; let mut raw_log_entry = vec![0_u8; read_size]; if self.cur_entry >= self.nr_entries { println!("{:?}", self); return Ok(None); } let mut ret = io::read(&self.log_file, &mut raw_log_entry)?; if ret != read_size as usize { bail!("Error reading entry: {}", ret) } let entry = LogWriteEntry::from(raw_log_entry); self.cur_entry += 1; let size = (entry.nr_sectors * self.sector_size as u64) as usize; if read_size < self.sector_size as usize { println!("Seeking.."); io::lseek(&self.log_file, (self.sector_size as i64 - LogWriteEntry::mem_size() as i64), Whence::SeekCur)?; //self.log_file.seek(SeekFrom::Current(LogWriteEntry::mem_size() as i64))?; } let mut flag_buf = String::new(); let flags = entry.flags; entry_flags_to_str(flags, &mut flag_buf); println!("replaying {}: sector {}, size {}, flags {}({})", self.cur_entry - 1, entry.sector, size, flags, flag_buf); if size < 0 { return Ok(None); } if (flags & LOG_DISCARD_FLAG) > 0 { self.discard(&entry); return Ok(Some(entry)) } let mut buf: Vec<u8> = Vec::with_capacity(size); if buf.capacity() != size { bail!("Error allocating buffer {} entry {}", size, self.cur_entry - 1); } unsafe { buf.set_len(size); } ret = io::read(&self.log_file, &mut buf).unwrap(); if ret != size as usize { println!("{:?}", buf); bail!("Error reading data[X]: {}", ret) } let offset = entry.sector * self.sector_size as u64; ret = io::pwrite(&self.replay_file, buf.as_slice(), offset as i64)?; drop(buf); if ret != size as usize { bail!("Error reading data[Y]: {}", ret) } Ok(Some(entry)) } } #[cfg(test)] mod tests { use crate::log_writes::{LogWriteSuper, log_flags_table}; use std::fs::OpenOptions; use std::io::Read; #[test] fn test_rust_struct_size() {} }
use crate::{Point, Ray, Vec3}; pub struct Camera { origin: Point, lower_left: Point, horizontal: Vec3, vertical: Vec3, u: Vec3, v: Vec3, lens_radius: f64, } impl Camera { pub fn new( lookfrom: Point, lookat: Point, vup: Vec3, vert_fov: f64, aspect_ratio: f64, aperture: f64, focus_dist: f64, ) -> Self { let theta = vert_fov.to_radians(); let h = (theta / 2.0).tan(); let viewport_height = 2.0 * h; let viewport_width = aspect_ratio * viewport_height; let w = (lookfrom - lookat).unit_vector(); let u = vup.cross(w).unit_vector(); let v = w.cross(u); let origin = lookfrom; let horizontal = u * viewport_width * focus_dist; let vertical = v * viewport_height * focus_dist; let lower_left = origin - horizontal / 2.0 - vertical / 2.0 - w * focus_dist; let lens_radius = aperture / 2.0; Self { origin, lower_left, horizontal, vertical, u, v, lens_radius, } } pub fn get_ray(&self, s: f64, t: f64) -> Ray { let rd = Vec3::random_in_unit_disk() * self.lens_radius; let offset = self.u * rd.x() + self.v * rd.y(); Ray::new( self.origin + offset, self.lower_left + self.horizontal * s + self.vertical * t - self.origin - offset, ) } }
#[macro_use] extern crate lazy_static; mod tokenizer; mod ast; mod runtime; mod util; fn main() { println!("Running Joey-Script 1.0"); let input = String::from(include_str!("main.js")); let tokens = tokenizer::tokenize(&input); let ast = ast::parse(&tokens); runtime::run(&ast); }
use std::convert::TryInto; use std::io::{ErrorKind, Read}; use std::net::{Ipv4Addr, SocketAddrV4}; use std::os::unix::io::AsRawFd; use std::process::exit; use anyhow::{anyhow, Context, Result}; use nix::ioctl_write_ptr; use nix::sys::select::{select, FdSet}; use nix::sys::time::{TimeSpec, TimeValLike}; use nix::sys::timerfd::{ClockId, Expiration, TimerFd, TimerFlags, TimerSetTimeFlags}; use socket2::{Domain, SockAddr, Socket, Type}; use tun_tap::{Iface, Mode}; const GRE_PROTOCOL: i32 = 47; const TUN_IOC_MAGIC: u8 = b'T'; const TUN_IOC_TUNSETCARRIER: u8 = 226; ioctl_write_ptr!( ioctl_tun_set_carrier, TUN_IOC_MAGIC, TUN_IOC_TUNSETCARRIER, i32 ); fn tun_set_carrier(tun: &Iface, carrier: bool) -> Result<()> { let fd = tun.as_raw_fd(); let carrier = carrier.into(); unsafe { ioctl_tun_set_carrier(fd, &carrier)?; } Ok(()) } pub struct TunnelConfig { local: Option<Ipv4Addr>, remote: Ipv4Addr, tunnel_id: u16, tap_name: Option<String>, keepalive_interval: Option<u64>, recv_timeout: Option<u64>, } impl TunnelConfig { pub fn new( local: Option<Ipv4Addr>, remote: Ipv4Addr, tunnel_id: u16, tap_name: Option<String>, keepalive_interval: Option<u64>, recv_timeout: Option<u64>, ) -> Self { TunnelConfig { local, remote, tunnel_id, tap_name, keepalive_interval, recv_timeout, } } } pub struct Eoip { config: TunnelConfig, remote_sa: SockAddr, tap: Iface, socket: Socket, timer_tx: Option<TimerFd>, timer_rx: Option<TimerFd>, dead: bool, } impl Eoip { pub fn new(config: TunnelConfig) -> Result<Self> { let tap_name = config.tap_name.as_deref().unwrap_or(""); let tap = Iface::without_packet_info(tap_name, Mode::Tap)?; let socket = Socket::new(Domain::IPV4, Type::RAW, Some(GRE_PROTOCOL.into()))?; let mut timer_tx = None; let mut timer_rx = None; let mut dead = false; if config.keepalive_interval.is_some() { timer_tx = Some(TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty())?); } if config.recv_timeout.is_some() { timer_rx = Some(TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty())?); dead = true; } let remote_sa = SockAddr::from(SocketAddrV4::new(config.remote, 0)); Ok(Eoip { config, remote_sa, tap, socket, timer_tx, timer_rx, dead, }) } pub fn run(&mut self) -> ! { match self._run() { Ok(_) => exit(0), Err(e) => { eprintln!("{}", e); exit(1) } } } fn _run(&mut self) -> Result<()> { eprintln!("Running on {}", self.tap.name()); // Consider moving this to new() if let Some(local) = self.config.local { self.socket .bind(&SockAddr::from(SocketAddrV4::new(local, 0)))?; } if let Some(tfd) = &self.timer_tx { tfd.set( Expiration::Interval(TimeSpec::seconds( self.config.keepalive_interval.unwrap() as i64 )), TimerSetTimeFlags::empty(), )?; self.send_keepalive()?; } if self.dead { tun_set_carrier(&self.tap, false)?; } let mut read_fds = FdSet::new(); loop { read_fds.insert(self.tap.as_raw_fd()); read_fds.insert(self.socket.as_raw_fd()); if let Some(ref tfd) = self.timer_tx { read_fds.insert(tfd.as_raw_fd()); } if let Some(ref tfd) = self.timer_rx { read_fds.insert(tfd.as_raw_fd()); } select(None, &mut read_fds, None, None, None)?; if read_fds.contains(self.tap.as_raw_fd()) { let mut buf = vec![0u8; 65536]; match self.tap.recv(&mut buf[8..]) { Ok(n) => match self.process_from_tap(n, &mut buf[..n + 8]) { Err(ref e) => eprintln!("process_from_tap: {:#}", e), Ok(_) => {} }, Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => panic!("tap.recv: {}", e), }; } if read_fds.contains(self.socket.as_raw_fd()) { let mut buf = vec![0u8; 65536]; match self.socket.read(buf.as_mut_slice()) { Ok(n) => { match self.process_from_sock(&buf[..n]) { Err(ref e) => eprintln!("process_from_sock: {:#}", e), Ok(_) => {} }; } Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => panic!("socket.read: {}", e), }; } if let Some(ref tfd) = self.timer_tx { if read_fds.contains(tfd.as_raw_fd()) { tfd.wait()?; self.send_keepalive()?; } } if let Some(ref tfd) = self.timer_rx { if read_fds.contains(tfd.as_raw_fd()) { tfd.wait()?; self.dead = true; tun_set_carrier(&self.tap, false)?; } } } } fn send_keepalive(&mut self) -> Result<()> { let mut buf = [32, 1, 100, 0, 0, 0, 0, 0]; buf[6..8].copy_from_slice(&(self.config.tunnel_id as u16).to_le_bytes()); self.socket.send_to(&buf, &self.remote_sa)?; Ok(()) } fn keepalive_rcvd(&mut self) -> Result<()> { if let Some(ref t) = self.timer_rx { if self.dead == true { tun_set_carrier(&self.tap, true)?; self.dead = false; } t.set( Expiration::OneShot(TimeSpec::seconds(self.config.recv_timeout.unwrap() as i64)), TimerSetTimeFlags::empty(), )?; } Ok(()) } fn process_from_tap(&mut self, length: usize, buf: &mut [u8]) -> Result<()> { if self.dead { return Ok(()); } buf[..4].copy_from_slice(&[32, 1, 100, 0]); buf[4..6].copy_from_slice(&(length as u16).to_be_bytes()); buf[6..8].copy_from_slice(&(self.config.tunnel_id as u16).to_le_bytes()); self.socket.send_to(&buf, &self.remote_sa)?; Ok(()) } fn process_from_sock(&mut self, packet: &[u8]) -> Result<()> { if packet.len() < 28 { return Err(anyhow!("Too short packet received!")); } let _ip_hdr = &packet[0..19]; let gre_hdr = &packet[20..24]; if &gre_hdr[2..] != &[0x64, 0x00] { // type not mikrotik eoip return Ok(()); } if &gre_hdr[..2] != &[0x20, 0x01] { return Err(anyhow!("Unexpected GRE flags: {:?}", &gre_hdr[..2])); } let tunnel_id = u16::from_le_bytes(packet[26..28].try_into().unwrap()); if tunnel_id != self.config.tunnel_id { return Ok(()); } let data_len_header = u16::from_be_bytes(packet[24..26].try_into().unwrap()) as usize; let data_len = packet.len() - 20 - 8; if data_len_header != data_len { return Err(anyhow!("Data length mismatch!")); } self.keepalive_rcvd().context("keepalive_rcvd")?; if data_len == 0 { return Ok(()); } let data = &packet[28..]; match self.tap.send(data) { Ok(_) => Ok(()), Err(ref e) if matches!(e.raw_os_error(), Some(5)) => Ok(()), Err(e) => Err(anyhow!("Failed to send to TAP interface: {}", e)), } } }
//! Полилинии use crate::sig::HasWrite; use nom::{ bytes::complete::take, number::complete::{le_i16, le_u16, le_u32, le_u8}, IResult, }; use std::fmt; #[derive(Debug)] pub struct Poly { poly_type: u16, //тип полилинии 0=контур элемента, 16=отверстие node_from: u16, //С узла N node_to: u16, //По узел N node_num: u16, //Количество узлов poly_prev: i16, //N предыдущей пололинии в элементе. -1=эта первая poly_next: i16, //N следующей пололинии в элементе. -1=эта первая sig_type: u8, //Тип конструкривного элемента, который образует полилиния sig_num: u32, //N конструкривного элемента, который образует полилиния (u64?) //6b ws: Vec<u8>, //6b } impl HasWrite for Poly { fn write(&self) -> Vec<u8> { let mut out: Vec<u8> = vec![]; out.extend(&self.poly_type.to_le_bytes()); out.extend(&self.node_from.to_le_bytes()); out.extend(&self.node_to.to_le_bytes()); out.extend(&self.node_num.to_le_bytes()); out.extend(&self.poly_prev.to_le_bytes()); out.extend(&self.poly_next.to_le_bytes()); out.extend(&self.sig_type.to_le_bytes()); out.extend(&self.sig_num.to_le_bytes()); out.extend(&self.ws[0..6]); out } fn name(&self) -> &str { "" } } impl fmt::Display for Poly { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "poly type: {}, |{} -> {}| ({}), element type: {}, element №{}", &self.poly_type, &self.node_from, &self.node_to, &self.node_num, &self.sig_type, &self.sig_num ) } } pub fn read_poly(i: &[u8]) -> IResult<&[u8], Poly> { let (i, poly_type) = le_u16(i)?; let (i, node_from) = le_u16(i)?; let (i, node_to) = le_u16(i)?; let (i, node_num) = le_u16(i)?; let (i, poly_prev) = le_i16(i)?; let (i, poly_next) = le_i16(i)?; let (i, sig_type) = le_u8(i)?; let (i, sig_num) = le_u32(i)?; let (i, ws1) = take(6u8)(i)?; let ws = ws1.to_vec(); Ok(( i, Poly { poly_type, node_from, node_to, node_num, poly_prev, poly_next, sig_type, sig_num, ws, }, )) } #[cfg(test)] fn test_poly(path_str: &str) { use crate::tests::rab_e_sig_test::read_test_sig; let original_in = read_test_sig(path_str); let (_, poly) = read_poly(&original_in).expect("couldn't read_poly"); assert_eq!(original_in, poly.write()); } #[test] fn poly_slab_1_test() { test_poly("test_sig/polys/poly_slab_1.test"); } #[test] fn poly_slab_3angle_test() { test_poly("test_sig/polys/poly_slab_3angle.test"); } #[test] fn poly_slab_dabble_1_test() { test_poly("test_sig/polys/poly_slab_dabble_1.test"); } #[test] fn poly_slab_dabble_2_test() { test_poly("test_sig/polys/poly_slab_dabble_2.test"); } #[test] fn poly_slab_opening4_1_test() { test_poly("test_sig/polys/poly_slab_opening4_1.test"); } #[test] fn poly_slab_opening4_2_test() { test_poly("test_sig/polys/poly_slab_opening4_2.test"); } #[test] fn poly_slab_opening4_3_test() { test_poly("test_sig/polys/poly_slab_opening4_3.test"); } #[test] fn poly_slab_opening4_4_test() { test_poly("test_sig/polys/poly_slab_opening4_4.test"); } #[test] fn poly_slab_opening4_5_test() { test_poly("test_sig/polys/poly_slab_opening4_5.test"); } #[test] fn poly_slab_opening_1_test() { test_poly("test_sig/polys/poly_slab_opening_1.test"); } #[test] fn poly_slab_opening_2_test() { test_poly("test_sig/polys/poly_slab_opening_2.test"); } #[test] fn s_poly_slab_test() { test_poly("test_sig/polys/s_poly_slab.test"); } #[test] fn s_poly_full_value_test() { use crate::tests::rab_e_sig_test::read_test_sig; let original_in = read_test_sig("test_sig/polys/s_poly_slab.test"); let (_, poly) = read_poly(&original_in).expect("couldn't read_poly"); let mut ws = vec![]; for i in 1..=6 { ws.push(i); } let c_poly = Poly { poly_type: 16u16, node_from: 12u16, node_to: 15u16, node_num: 4u16, poly_prev: 2i16, poly_next: 4i16, sig_type: 4u8, sig_num: 0u32, ws, }; assert_eq!(poly.write(), c_poly.write()) }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![warn(missing_docs)] //! `timekeeper` is responsible for external time synchronization in Fuchsia. use { chrono::prelude::*, failure::{Error, ResultExt}, fidl_fuchsia_net as fnet, fidl_fuchsia_time as ftime, fidl_fuchsia_timezone as ftz, fuchsia_async::{self as fasync, DurationExt}, fuchsia_component::server::ServiceFs, fuchsia_zircon as zx, futures::{StreamExt, TryStreamExt}, log::{debug, error, info, warn}, parking_lot::Mutex, std::{path::Path, sync::Arc}, }; mod diagnostics; #[fasync::run_singlethreaded] async fn main() -> Result<(), Error> { diagnostics::init(); let mut fs = ServiceFs::new(); info!("diagnostics initialized, connecting notifier to servicefs."); diagnostics::INSPECTOR.export(&mut fs); let source = initial_utc_source("/config/build-info/minimum-utc-stamp".as_ref())?; let notifier = Notifier::new(source); info!("connecting to external update service"); let time_service = fuchsia_component::client::connect_to_service::<ftz::TimeServiceMarker>().unwrap(); let connectivity_service = fuchsia_component::client::connect_to_service::<fnet::ConnectivityMarker>().unwrap(); fasync::spawn(maintain_utc(notifier.clone(), time_service, connectivity_service)); fs.dir("svc").add_fidl_service(move |requests: ftime::UtcRequestStream| { notifier.handle_request_stream(requests); }); info!("added notifier, serving servicefs"); fs.take_and_serve_directory_handle()?; let () = fs.collect().await; Ok(()) } fn backstop_time(path: &Path) -> Result<DateTime<Utc>, Error> { let file_contents = std::fs::read_to_string(path).context("reading backstop time from disk")?; let parsed_offset = NaiveDateTime::parse_from_str(file_contents.trim(), "%s")?; let utc = DateTime::from_utc(parsed_offset, Utc); Ok(utc) } fn initial_utc_source(backstop_path: &Path) -> Result<Option<ftime::UtcSource>, Error> { let expected_minimum = backstop_time(backstop_path)?; let current_utc = Utc::now(); Ok(if current_utc > expected_minimum { Some(ftime::UtcSource::Backstop) } else { warn!( "latest known-past UTC time ({}) should be earlier than current system time ({})", expected_minimum, current_utc, ); None }) } /// The top-level control loop for time synchronization. /// /// Checks for network connectivity before attempting any time updates. /// /// Actual updates are performed by calls to `fuchsia.timezone.TimeService` which we plan /// to deprecate. async fn maintain_utc( notifs: Notifier, time_service: ftz::TimeServiceProxy, connectivity: fnet::ConnectivityProxy, ) { // wait for the network to come up before we start checking for time let mut conn_events = connectivity.take_event_stream(); loop { if let Ok(Some(fnet::ConnectivityEvent::OnNetworkReachable { reachable: true })) = conn_events.try_next().await { break; } } for i in 0.. { match time_service.update(1).await { Ok(true) => { let monotonic_before = zx::Time::get(zx::ClockId::Monotonic).into_nanos(); let utc_now = Utc::now().timestamp_nanos(); let monotonic_after = zx::Time::get(zx::ClockId::Monotonic).into_nanos(); info!( "CF-884:monotonic_before={}:utc={}:monotonic_after={}", monotonic_before, utc_now, monotonic_after, ); notifs.0.lock().set_source(ftime::UtcSource::External, monotonic_before); break; } Ok(false) => { debug!("failed to update time, probably a network error. retrying."); } Err(why) => { error!("couldn't make request to update time: {:?}", why); } } let sleep_duration = zx::Duration::from_seconds(2i64.pow(i)); // exponential backoff fasync::Timer::new(sleep_duration.after_now()).await; } } /// Notifies waiting clients when the clock has been updated, wrapped in a lock to allow /// sharing between tasks. #[derive(Clone, Debug)] struct Notifier(Arc<Mutex<NotifyInner>>); impl Notifier { fn new(source: Option<ftime::UtcSource>) -> Self { Notifier(Arc::new(Mutex::new(NotifyInner { source, clients: Vec::new() }))) } /// Spawns an async task to handle requests on this channel. fn handle_request_stream(&self, requests: ftime::UtcRequestStream) { let notifier = self.clone(); fasync::spawn(async move { info!("listening for UTC requests"); let mut counted_requests = requests.enumerate(); let mut last_seen_state = notifier.0.lock().source; while let Some((request_count, Ok(ftime::UtcRequest::WatchState { responder }))) = counted_requests.next().await { let mut n = notifier.0.lock(); // we return immediately if this is the first request on this channel, but if // the backstop time hasn't been set yet then we can't say anything if n.source.is_some() && (request_count == 0 || last_seen_state != n.source) { n.reply(responder, zx::Time::get(zx::ClockId::Monotonic).into_nanos()); } else { n.register(responder); } last_seen_state = n.source; } }); } } /// Notifies waiting clients when the clock has been updated. #[derive(Debug)] struct NotifyInner { /// The current source for our UTC approximation. source: Option<ftime::UtcSource>, /// All clients waiting for an update to UTC's time. clients: Vec<ftime::UtcWatchStateResponder>, } impl NotifyInner { /// Reply to a client with the current UtcState. fn reply(&self, responder: ftime::UtcWatchStateResponder, update_time: i64) { if let Err(why) = responder.send(ftime::UtcState { timestamp: Some(update_time), source: self.source }) { warn!("failed to notify a client of an update: {:?}", why); } } /// Registers a client to be later notified that a clock update has occurred. fn register(&mut self, responder: ftime::UtcWatchStateResponder) { info!("registering a client for notifications"); self.clients.push(responder); } /// Increases the revision counter by 1 and notifies any clients waiting on updates from /// previous revisions. fn set_source(&mut self, source: ftime::UtcSource, update_time: i64) { if self.source != Some(source) { self.source = Some(source); let clients = std::mem::replace(&mut self.clients, vec![]); info!("UTC source changed to {:?}, notifying {} clients", source, clients.len()); for responder in clients { self.reply(responder, update_time); } } else { info!("received UTC source update but the actual source didn't change."); } } } #[cfg(test)] mod tests { #[allow(unused)] use { super::*, chrono::{offset::TimeZone, NaiveDate}, fuchsia_zircon as zx, std::{ future::Future, pin::Pin, task::{Context, Poll, Waker}, }, }; #[test] fn fixed_backstop_check() { let y2k_backstop = "/pkg/data/y2k"; let test_backstop = backstop_time(y2k_backstop.as_ref()).unwrap(); let test_source = initial_utc_source(y2k_backstop.as_ref()).unwrap(); let before_test_backstop = Utc.from_utc_datetime(&NaiveDate::from_ymd(1999, 1, 1).and_hms(0, 0, 0)); let after_test_backstop = Utc.from_utc_datetime(&NaiveDate::from_ymd(2001, 1, 1).and_hms(0, 0, 0)); assert!(test_backstop > before_test_backstop); assert!(test_backstop < after_test_backstop); assert_eq!(test_source, Some(ftime::UtcSource::Backstop)); } #[test] fn fallible_backstop_check() { assert_eq!(initial_utc_source("/pkg/data/end-of-unix-time".as_ref()).unwrap(), None); } #[fasync::run_singlethreaded(test)] async fn single_client() { diagnostics::init(); info!("starting single notification test"); let (utc, utc_requests) = fidl::endpoints::create_proxy_and_stream::<ftime::UtcMarker>().unwrap(); let (time_service, mut time_requests) = fidl::endpoints::create_proxy_and_stream::<ftz::TimeServiceMarker>().unwrap(); let (reachability, reachability_server) = fidl::endpoints::create_proxy::<fnet::ConnectivityMarker>().unwrap(); // the "network" the time sync server uses is de facto reachable here let (_, reachability_control) = reachability_server.into_stream_and_control_handle().unwrap(); reachability_control.send_on_network_reachable(true).unwrap(); let notifier = Notifier::new(Some(ftime::UtcSource::Backstop)); let (mut allow_update, mut wait_for_update) = futures::channel::mpsc::channel(1); info!("spawning test notifier"); notifier.handle_request_stream(utc_requests); fasync::spawn(maintain_utc(notifier.clone(), time_service, reachability)); fasync::spawn(async move { while let Some(Ok(ftz::TimeServiceRequest::Update { responder, .. })) = time_requests.next().await { let () = wait_for_update.next().await.unwrap(); responder.send(true).unwrap(); } }); info!("checking that the time source has not been externally initialized yet"); assert_eq!(utc.watch_state().await.unwrap().source.unwrap(), ftime::UtcSource::Backstop); let task_waker = futures::future::poll_fn(|cx| Poll::Ready(cx.waker().clone())).await; let mut cx = Context::from_waker(&task_waker); let mut hanging = Box::pin(utc.watch_state()); assert!( hanging.as_mut().poll(&mut cx).is_pending(), "hanging get should not return before time updated event has been emitted" ); info!("sending network update event"); allow_update.try_send(()).unwrap(); info!("waiting for time source update"); assert_eq!(hanging.await.unwrap().source.unwrap(), ftime::UtcSource::External); } }
extern crate hsl; extern crate rand; extern crate sdl2; use sdl2::audio::{AudioCVT, AudioSpecDesired, AudioSpecWAV, AudioQueue}; use sdl2::event::Event; use sdl2::image::{INIT_PNG, LoadSurface}; use sdl2::gfx::rotozoom::RotozoomSurface; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::{TextureQuery}; use sdl2::surface::Surface; use sdl2::video::FullscreenType; use hsl::HSL; use rand::{thread_rng, Rng}; use std::collections::{HashSet, HashMap}; use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::time::Duration; macro_rules! rect( ($x:expr, $y:expr, $w:expr, $h:expr) => ( Rect::new($x as i32, $y as i32, $w as u32, $h as u32) ) ); trait PositionStrategy { fn next_position(&mut self, rect: Rect, within_rect: Rect) -> Rect; fn reset(&mut self) { } } struct RandomPositionStrategy {} impl PositionStrategy for RandomPositionStrategy { // Return a random position that fits rect within rect fn next_position(&mut self, rect: Rect, within_rect: Rect) -> Rect { let rx: f64 = thread_rng().gen(); let ry: f64 = thread_rng().gen(); let posx = rx * (within_rect.width() - 1 * rect.width()) as f64; let posy = ry * (within_rect.height() - 1 * rect.height()) as f64; rect!(posx as f64, posy as f64, rect.width(), rect.height()) } } struct LeftToRightStrategy { next_x: u32, next_y: u32, } impl PositionStrategy for LeftToRightStrategy { fn next_position(&mut self, rect: Rect, within_rect: Rect) -> Rect { if self.next_x > within_rect.right() as u32 { self.next_x = 0; self.next_y = self.next_y + rect.height() as u32; } if self.next_y > within_rect.bottom() as u32 { self.next_y = 0; } let y = self.next_y; let x = self.next_x; self.next_x = x + rect.width(); rect!(x, y, rect.width(), rect.height()) } fn reset(&mut self) { self.next_x = 0; self.next_y = 0; } } fn random_colour(c: Color) -> Color { let not_near_hsl = HSL::from_rgb(&[c.r, c.g, c.b]); let mut generated = not_near_hsl.clone(); while (generated.h - not_near_hsl.h).abs() < 40. { let h: f64 = thread_rng().gen(); generated = HSL { h: h * 360.0, s: 1_f64, l: 0.5_f64, }; } let rgb = generated.to_rgb(); return Color::RGB(rgb.0, rgb.1, rgb.2); } fn load_sound(note: &str) -> AudioSpecWAV { // Load a sound let filename = format!("{}.wav", note); let path: PathBuf = ["./sounds", &filename].iter().collect(); let wav_file: Cow<'static, Path> = Cow::from(path); AudioSpecWAV::load_wav(wav_file.clone()) .expect("Could not load test WAV file") } fn load_image(fname: &str) -> Surface { // Load an image let filename = format!("{}.png", fname); let path: PathBuf = ["./images", &filename].iter().collect(); let image_file: Cow<'static, Path> = Cow::from(path); Surface::from_file(image_file.clone()) .expect("Could not load image file") } pub fn main() { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let audio_subsystem = sdl_context.audio().unwrap(); let _image_context = sdl2::image::init(INIT_PNG); let (window_width, window_height) = (800, 600); let mut window = video_subsystem .window("Bish Bash Bosh", window_width, window_height) .position_centered() .opengl() .build() .unwrap(); window.set_fullscreen(FullscreenType::Desktop).unwrap(); window.set_grab(true); let (window_width, window_height) = window.size(); let mut canvas = window.into_canvas().build().unwrap(); let texture_creator = canvas.texture_creator(); let mut event_pump = sdl_context.event_pump().unwrap(); let ttf_context = sdl2::ttf::init().unwrap(); // Load a font let mut font = ttf_context.load_font("DejaVuSans-Bold.ttf", 112).unwrap(); font.set_style(sdl2::ttf::STYLE_BOLD); let desired_spec = AudioSpecDesired { freq: Some(44_100), channels: Some(1), // mono samples: None, // default }; let audio_queue: AudioQueue<u8> = audio_subsystem .open_queue(None, &desired_spec) .unwrap(); // let mut position_strategy = RandomPositionStrategy { }; let mut position_strategy = LeftToRightStrategy { next_x: 0 , next_y: window_height / 3}; canvas.set_draw_color(Color::RGB(255, 0, 0)); canvas.clear(); canvas.present(); // Keep track of all displayed characters, and their postitions let mut drawables = vec![]; let drawable_keys: HashSet<String> = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ].iter() .map(|s| s.to_string()) .collect(); let noisy_keys: HashMap<String, String> = [ ("F1", "37a"), ("F2", "38b"), ("F3", "39bb"), ("F4", "40c"), ("F5", "41c"), ("F6", "42d"), ("F7", "43e"), ("F8", "44eb"), ("F9", "45f"), ("F10", "46f"), ("F11", "47g"), ("F12", "48g"), ("A", "alpha-a"), ("B", "alpha-b"), ("C", "alpha-c"), ("D", "alpha-d"), ("E", "alpha-e"), ("F", "alpha-f"), ("G", "alpha-g"), ("H", "alpha-h"), ("I", "alpha-i"), ("J", "alpha-j"), ("K", "alpha-k"), ("L", "alpha-l"), ("M", "alpha-m"), ("N", "alpha-n"), ("O", "alpha-o"), ("P", "alpha-p"), ("Q", "alpha-q"), ("R", "alpha-r"), ("S", "alpha-s"), ("T", "alpha-t"), ("U", "alpha-u"), ("V", "alpha-v"), ("W", "alpha-w"), ("X", "alpha-x"), ("Y", "alpha-y"), ("Z", "alpha-z"), ].iter() .map(|(s1, s2)| (s1.to_string(), s2.to_string())) .collect(); let images: HashMap<String, String> = [ ("T", "T"), ("B", "buzz"), ("C", "chase"), ("D", "dumbo"), ("G", "geo"), ("H", "harrison"), ("I", "igglepiggle"), ("M", "mickey"), ("P", "peppa"), ("S", "simba"), ("U", "upsiedaisy"), ("W", "woody"), ].iter() .map(|(s1, s2)| (s1.to_string(), s2.to_string())) .collect(); let mut background_color = random_colour(Color::RGB(255, 255, 255)); 'running: loop { for event in event_pump.poll_iter() { match event { Event::Quit { .. } | Event::KeyDown { keycode: Some(Keycode::Escape), repeat: true, .. } => break 'running, Event::KeyDown { keycode: Some(Keycode::Return), repeat: false, .. } => { position_strategy.reset(); drawables.clear(); background_color = random_colour(Color::RGB(255, 255, 255)); } Event::KeyDown { keycode: Some(key), repeat: false, .. } => { if drawable_keys.contains(&key.name()) { let colour = random_colour(background_color); let surface = font.render(&key.name()).blended(colour).unwrap(); let texture = texture_creator .create_texture_from_surface(&surface) .unwrap(); let TextureQuery { width, height, .. } = texture.query(); let target = position_strategy.next_position( rect!(0, 0, width, height), rect!(0, 0, window_width, window_height), ); //rect!(150, 150, width, height); drawables.push((texture, target)); } if let Some(note) = noisy_keys.get(&key.name()) { let wav = load_sound(&note); let spec = audio_queue.spec(); let cvt = AudioCVT::new( wav.format, wav.channels, wav.freq, spec.format, spec.channels, spec.freq, ).expect("Could not convert WAV file"); let data = cvt.convert(wav.buffer().to_vec()); audio_queue.clear(); audio_queue.queue(&data); // Start playback audio_queue.resume(); } if let Some(filename) = images.get(&key.name()) { let mut surface = load_image(&filename); let sf = (100f64 / surface.height() as f64); println!("{}", sf ); let surface = surface.rotozoom(0f64, sf, false).unwrap(); let texture = texture_creator .create_texture_from_surface(&surface) .unwrap(); let TextureQuery { width, height, .. } = texture.query(); let target = position_strategy.next_position( rect!(0, 0, width, height), rect!(0, 0, window_width, window_height), ); drawables.push((texture, target)); } } _ => {} } } // Draw the chars canvas.set_draw_color(background_color); canvas.clear(); for &(ref texture, target) in drawables.iter() { canvas.copy(&texture, None, Some(target.clone())).unwrap(); } canvas.present(); ::std::thread::sleep(Duration::new(0, 1_000_000_000u32 / 60)); } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub const CLSID_VdsLoader: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9c38ed61_d565_4728_aeee_c80952f0ecde); pub const CLSID_VdsService: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7d1933cb_86f6_4a98_8628_01be94c9a575); pub const GPT_PARTITION_NAME_LENGTH: u32 = 36u32; #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IEnumVdsObject(pub ::windows::core::IUnknown); impl IEnumVdsObject { pub unsafe fn Next(&self, celt: u32, ppobjectarray: *mut ::core::option::Option<::windows::core::IUnknown>, pcfetched: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(celt), ::core::mem::transmute(ppobjectarray), ::core::mem::transmute(pcfetched)).ok() } pub unsafe fn Skip(&self, celt: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(celt)).ok() } pub unsafe fn Reset(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Clone(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } } unsafe impl ::windows::core::Interface for IEnumVdsObject { type Vtable = IEnumVdsObject_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x118610b7_8d94_4030_b5b8_500889788e4e); } impl ::core::convert::From<IEnumVdsObject> for ::windows::core::IUnknown { fn from(value: IEnumVdsObject) -> Self { value.0 } } impl ::core::convert::From<&IEnumVdsObject> for ::windows::core::IUnknown { fn from(value: &IEnumVdsObject) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IEnumVdsObject { 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 IEnumVdsObject { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IEnumVdsObject_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, celt: u32, ppobjectarray: *mut ::windows::core::RawPtr, pcfetched: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, celt: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsAdmin(pub ::windows::core::IUnknown); impl IVdsAdmin { #[cfg(feature = "Win32_Foundation")] pub unsafe fn RegisterProvider<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param5: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param6: ::windows::core::IntoParam<'a, ::windows::core::GUID>>( &self, providerid: Param0, providerclsid: Param1, pwszname: Param2, r#type: VDS_PROVIDER_TYPE, pwszmachinename: Param4, pwszversion: Param5, guidversionid: Param6, ) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), providerid.into_param().abi(), providerclsid.into_param().abi(), pwszname.into_param().abi(), ::core::mem::transmute(r#type), pwszmachinename.into_param().abi(), pwszversion.into_param().abi(), guidversionid.into_param().abi()).ok() } pub unsafe fn UnregisterProvider<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, providerid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), providerid.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IVdsAdmin { type Vtable = IVdsAdmin_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd188e97d_85aa_4d33_abc6_26299a10ffc1); } impl ::core::convert::From<IVdsAdmin> for ::windows::core::IUnknown { fn from(value: IVdsAdmin) -> Self { value.0 } } impl ::core::convert::From<&IVdsAdmin> for ::windows::core::IUnknown { fn from(value: &IVdsAdmin) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsAdmin { 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 IVdsAdmin { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsAdmin_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, providerid: ::windows::core::GUID, providerclsid: ::windows::core::GUID, pwszname: super::super::Foundation::PWSTR, r#type: VDS_PROVIDER_TYPE, pwszmachinename: super::super::Foundation::PWSTR, pwszversion: super::super::Foundation::PWSTR, guidversionid: ::windows::core::GUID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, providerid: ::windows::core::GUID) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsAdviseSink(pub ::windows::core::IUnknown); impl IVdsAdviseSink { pub unsafe fn OnNotify(&self, lnumberofnotifications: i32, pnotificationarray: *const VDS_NOTIFICATION) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(lnumberofnotifications), ::core::mem::transmute(pnotificationarray)).ok() } } unsafe impl ::windows::core::Interface for IVdsAdviseSink { type Vtable = IVdsAdviseSink_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8326cd1d_cf59_4936_b786_5efc08798e25); } impl ::core::convert::From<IVdsAdviseSink> for ::windows::core::IUnknown { fn from(value: IVdsAdviseSink) -> Self { value.0 } } impl ::core::convert::From<&IVdsAdviseSink> for ::windows::core::IUnknown { fn from(value: &IVdsAdviseSink) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsAdviseSink { 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 IVdsAdviseSink { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsAdviseSink_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, lnumberofnotifications: i32, pnotificationarray: *const VDS_NOTIFICATION) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsAsync(pub ::windows::core::IUnknown); impl IVdsAsync { pub unsafe fn Cancel(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Wait(&self, phrresult: *mut ::windows::core::HRESULT, pasyncout: *mut VDS_ASYNC_OUTPUT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(phrresult), ::core::mem::transmute(pasyncout)).ok() } pub unsafe fn QueryStatus(&self, phrresult: *mut ::windows::core::HRESULT, pulpercentcompleted: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(phrresult), ::core::mem::transmute(pulpercentcompleted)).ok() } } unsafe impl ::windows::core::Interface for IVdsAsync { type Vtable = IVdsAsync_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd5d23b6d_5a55_4492_9889_397a3c2d2dbc); } impl ::core::convert::From<IVdsAsync> for ::windows::core::IUnknown { fn from(value: IVdsAsync) -> Self { value.0 } } impl ::core::convert::From<&IVdsAsync> for ::windows::core::IUnknown { fn from(value: &IVdsAsync) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsAsync { 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 IVdsAsync { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsAsync_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, phrresult: *mut ::windows::core::HRESULT, pasyncout: *mut ::core::mem::ManuallyDrop<VDS_ASYNC_OUTPUT>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, phrresult: *mut ::windows::core::HRESULT, pulpercentcompleted: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsController(pub ::windows::core::IUnknown); impl IVdsController { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetProperties(&self) -> ::windows::core::Result<VDS_CONTROLLER_PROP> { let mut result__: <VDS_CONTROLLER_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_CONTROLLER_PROP>(result__) } pub unsafe fn GetSubSystem(&self) -> ::windows::core::Result<IVdsSubSystem> { let mut result__: <IVdsSubSystem as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsSubSystem>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPortProperties(&self, sportnumber: i16) -> ::windows::core::Result<VDS_PORT_PROP> { let mut result__: <VDS_PORT_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(sportnumber), &mut result__).from_abi::<VDS_PORT_PROP>(result__) } pub unsafe fn FlushCache(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn InvalidateCache(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Reset(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn QueryAssociatedLuns(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn SetStatus(&self, status: VDS_CONTROLLER_STATUS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(status)).ok() } } unsafe impl ::windows::core::Interface for IVdsController { type Vtable = IVdsController_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcb53d96e_dffb_474a_a078_790d1e2bc082); } impl ::core::convert::From<IVdsController> for ::windows::core::IUnknown { fn from(value: IVdsController) -> Self { value.0 } } impl ::core::convert::From<&IVdsController> for ::windows::core::IUnknown { fn from(value: &IVdsController) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsController { 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 IVdsController { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsController_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, pcontrollerprop: *mut VDS_CONTROLLER_PROP) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppsubsystem: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sportnumber: i16, pportprop: *mut VDS_PORT_PROP) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, status: VDS_CONTROLLER_STATUS) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsControllerControllerPort(pub ::windows::core::IUnknown); impl IVdsControllerControllerPort { pub unsafe fn QueryControllerPorts(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } } unsafe impl ::windows::core::Interface for IVdsControllerControllerPort { type Vtable = IVdsControllerControllerPort_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xca5d735f_6bae_42c0_b30e_f2666045ce71); } impl ::core::convert::From<IVdsControllerControllerPort> for ::windows::core::IUnknown { fn from(value: IVdsControllerControllerPort) -> Self { value.0 } } impl ::core::convert::From<&IVdsControllerControllerPort> for ::windows::core::IUnknown { fn from(value: &IVdsControllerControllerPort) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsControllerControllerPort { 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 IVdsControllerControllerPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsControllerControllerPort_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, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsControllerPort(pub ::windows::core::IUnknown); impl IVdsControllerPort { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetProperties(&self) -> ::windows::core::Result<VDS_PORT_PROP> { let mut result__: <VDS_PORT_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_PORT_PROP>(result__) } pub unsafe fn GetController(&self) -> ::windows::core::Result<IVdsController> { let mut result__: <IVdsController as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsController>(result__) } pub unsafe fn QueryAssociatedLuns(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn Reset(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn SetStatus(&self, status: VDS_PORT_STATUS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(status)).ok() } } unsafe impl ::windows::core::Interface for IVdsControllerPort { type Vtable = IVdsControllerPort_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x18691d0d_4e7f_43e8_92e4_cf44beeed11c); } impl ::core::convert::From<IVdsControllerPort> for ::windows::core::IUnknown { fn from(value: IVdsControllerPort) -> Self { value.0 } } impl ::core::convert::From<&IVdsControllerPort> for ::windows::core::IUnknown { fn from(value: &IVdsControllerPort) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsControllerPort { 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 IVdsControllerPort { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsControllerPort_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, pportprop: *mut VDS_PORT_PROP) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppcontroller: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, status: VDS_PORT_STATUS) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsDrive(pub ::windows::core::IUnknown); impl IVdsDrive { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetProperties(&self) -> ::windows::core::Result<VDS_DRIVE_PROP> { let mut result__: <VDS_DRIVE_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_DRIVE_PROP>(result__) } pub unsafe fn GetSubSystem(&self) -> ::windows::core::Result<IVdsSubSystem> { let mut result__: <IVdsSubSystem as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsSubSystem>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn QueryExtents(&self, ppextentarray: *mut *mut VDS_DRIVE_EXTENT, plnumberofextents: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(ppextentarray), ::core::mem::transmute(plnumberofextents)).ok() } pub unsafe fn SetFlags(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn ClearFlags(&self, ulflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags)).ok() } pub unsafe fn SetStatus(&self, status: VDS_DRIVE_STATUS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(status)).ok() } } unsafe impl ::windows::core::Interface for IVdsDrive { type Vtable = IVdsDrive_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xff24efa4_aade_4b6b_898b_eaa6a20887c7); } impl ::core::convert::From<IVdsDrive> for ::windows::core::IUnknown { fn from(value: IVdsDrive) -> Self { value.0 } } impl ::core::convert::From<&IVdsDrive> for ::windows::core::IUnknown { fn from(value: &IVdsDrive) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsDrive { 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 IVdsDrive { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsDrive_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, pdriveprop: *mut VDS_DRIVE_PROP) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppsubsystem: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppextentarray: *mut *mut VDS_DRIVE_EXTENT, plnumberofextents: *mut i32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] 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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, status: VDS_DRIVE_STATUS) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsDrive2(pub ::windows::core::IUnknown); impl IVdsDrive2 { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetProperties2(&self) -> ::windows::core::Result<VDS_DRIVE_PROP2> { let mut result__: <VDS_DRIVE_PROP2 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_DRIVE_PROP2>(result__) } } unsafe impl ::windows::core::Interface for IVdsDrive2 { type Vtable = IVdsDrive2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x60b5a730_addf_4436_8ca7_5769e2d1ffa4); } impl ::core::convert::From<IVdsDrive2> for ::windows::core::IUnknown { fn from(value: IVdsDrive2) -> Self { value.0 } } impl ::core::convert::From<&IVdsDrive2> for ::windows::core::IUnknown { fn from(value: &IVdsDrive2) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsDrive2 { 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 IVdsDrive2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsDrive2_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, pdriveprop2: *mut VDS_DRIVE_PROP2) -> ::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 IVdsHwProvider(pub ::windows::core::IUnknown); impl IVdsHwProvider { pub unsafe fn QuerySubSystems(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn Reenumerate(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Refresh(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok() } } unsafe impl ::windows::core::Interface for IVdsHwProvider { type Vtable = IVdsHwProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd99bdaae_b13a_4178_9fdb_e27f16b4603e); } impl ::core::convert::From<IVdsHwProvider> for ::windows::core::IUnknown { fn from(value: IVdsHwProvider) -> Self { value.0 } } impl ::core::convert::From<&IVdsHwProvider> for ::windows::core::IUnknown { fn from(value: &IVdsHwProvider) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsHwProvider { 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 IVdsHwProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsHwProvider_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, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsHwProviderPrivate(pub ::windows::core::IUnknown); impl IVdsHwProviderPrivate { #[cfg(feature = "Win32_Foundation")] pub unsafe fn QueryIfCreatedLun<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, pwszdevicepath: Param0, pvdsluninformation: *const VDS_LUN_INFORMATION) -> ::windows::core::Result<::windows::core::GUID> { let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pwszdevicepath.into_param().abi(), ::core::mem::transmute(pvdsluninformation), &mut result__).from_abi::<::windows::core::GUID>(result__) } } unsafe impl ::windows::core::Interface for IVdsHwProviderPrivate { type Vtable = IVdsHwProviderPrivate_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x98f17bf3_9f33_4f12_8714_8b4075092c2e); } impl ::core::convert::From<IVdsHwProviderPrivate> for ::windows::core::IUnknown { fn from(value: IVdsHwProviderPrivate) -> Self { value.0 } } impl ::core::convert::From<&IVdsHwProviderPrivate> for ::windows::core::IUnknown { fn from(value: &IVdsHwProviderPrivate) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsHwProviderPrivate { 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 IVdsHwProviderPrivate { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsHwProviderPrivate_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, pwszdevicepath: super::super::Foundation::PWSTR, pvdsluninformation: *const VDS_LUN_INFORMATION, plunid: *mut ::windows::core::GUID) -> ::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 IVdsHwProviderPrivateMpio(pub ::windows::core::IUnknown); impl IVdsHwProviderPrivateMpio { pub unsafe fn SetAllPathStatusesFromHbaPort<'a, Param0: ::windows::core::IntoParam<'a, VDS_HBAPORT_PROP>>(&self, hbaportprop: Param0, status: VDS_PATH_STATUS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), hbaportprop.into_param().abi(), ::core::mem::transmute(status)).ok() } } unsafe impl ::windows::core::Interface for IVdsHwProviderPrivateMpio { type Vtable = IVdsHwProviderPrivateMpio_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x310a7715_ac2b_4c6f_9827_3d742f351676); } impl ::core::convert::From<IVdsHwProviderPrivateMpio> for ::windows::core::IUnknown { fn from(value: IVdsHwProviderPrivateMpio) -> Self { value.0 } } impl ::core::convert::From<&IVdsHwProviderPrivateMpio> for ::windows::core::IUnknown { fn from(value: &IVdsHwProviderPrivateMpio) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsHwProviderPrivateMpio { 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 IVdsHwProviderPrivateMpio { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsHwProviderPrivateMpio_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, hbaportprop: VDS_HBAPORT_PROP, status: VDS_PATH_STATUS) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsHwProviderStoragePools(pub ::windows::core::IUnknown); impl IVdsHwProviderStoragePools { #[cfg(feature = "Win32_Foundation")] pub unsafe fn QueryStoragePools(&self, ulflags: u32, ullremainingfreespace: u64, ppoolattributes: *const VDS_POOL_ATTRIBUTES) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulflags), ::core::mem::transmute(ullremainingfreespace), ::core::mem::transmute(ppoolattributes), &mut result__).from_abi::<IEnumVdsObject>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn CreateLunInStoragePool<'a, Param2: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, r#type: VDS_LUN_TYPE, ullsizeinbytes: u64, storagepoolid: Param2, pwszunmaskinglist: Param3, phints2: *const VDS_HINTS2) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(r#type), ::core::mem::transmute(ullsizeinbytes), storagepoolid.into_param().abi(), pwszunmaskinglist.into_param().abi(), ::core::mem::transmute(phints2), &mut result__).from_abi::<IVdsAsync>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn QueryMaxLunCreateSizeInStoragePool<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, r#type: VDS_LUN_TYPE, storagepoolid: Param1, phints2: *const VDS_HINTS2) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(r#type), storagepoolid.into_param().abi(), ::core::mem::transmute(phints2), &mut result__).from_abi::<u64>(result__) } } unsafe impl ::windows::core::Interface for IVdsHwProviderStoragePools { type Vtable = IVdsHwProviderStoragePools_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd5b5937a_f188_4c79_b86c_11c920ad11b8); } impl ::core::convert::From<IVdsHwProviderStoragePools> for ::windows::core::IUnknown { fn from(value: IVdsHwProviderStoragePools) -> Self { value.0 } } impl ::core::convert::From<&IVdsHwProviderStoragePools> for ::windows::core::IUnknown { fn from(value: &IVdsHwProviderStoragePools) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsHwProviderStoragePools { 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 IVdsHwProviderStoragePools { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsHwProviderStoragePools_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, ulflags: u32, ullremainingfreespace: u64, ppoolattributes: *const VDS_POOL_ATTRIBUTES, ppenum: *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, r#type: VDS_LUN_TYPE, ullsizeinbytes: u64, storagepoolid: ::windows::core::GUID, pwszunmaskinglist: super::super::Foundation::PWSTR, phints2: *const VDS_HINTS2, ppasync: *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, r#type: VDS_LUN_TYPE, storagepoolid: ::windows::core::GUID, phints2: *const VDS_HINTS2, pullmaxlunsize: *mut u64) -> ::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 IVdsHwProviderType(pub ::windows::core::IUnknown); impl IVdsHwProviderType { pub unsafe fn GetProviderType(&self) -> ::windows::core::Result<VDS_HWPROVIDER_TYPE> { let mut result__: <VDS_HWPROVIDER_TYPE as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_HWPROVIDER_TYPE>(result__) } } unsafe impl ::windows::core::Interface for IVdsHwProviderType { type Vtable = IVdsHwProviderType_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3e0f5166_542d_4fc6_947a_012174240b7e); } impl ::core::convert::From<IVdsHwProviderType> for ::windows::core::IUnknown { fn from(value: IVdsHwProviderType) -> Self { value.0 } } impl ::core::convert::From<&IVdsHwProviderType> for ::windows::core::IUnknown { fn from(value: &IVdsHwProviderType) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsHwProviderType { 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 IVdsHwProviderType { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsHwProviderType_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, ptype: *mut VDS_HWPROVIDER_TYPE) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsHwProviderType2(pub ::windows::core::IUnknown); impl IVdsHwProviderType2 { pub unsafe fn GetProviderType2(&self) -> ::windows::core::Result<VDS_HWPROVIDER_TYPE> { let mut result__: <VDS_HWPROVIDER_TYPE as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_HWPROVIDER_TYPE>(result__) } } unsafe impl ::windows::core::Interface for IVdsHwProviderType2 { type Vtable = IVdsHwProviderType2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8190236f_c4d0_4e81_8011_d69512fcc984); } impl ::core::convert::From<IVdsHwProviderType2> for ::windows::core::IUnknown { fn from(value: IVdsHwProviderType2) -> Self { value.0 } } impl ::core::convert::From<&IVdsHwProviderType2> for ::windows::core::IUnknown { fn from(value: &IVdsHwProviderType2) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsHwProviderType2 { 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 IVdsHwProviderType2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsHwProviderType2_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, ptype: *mut VDS_HWPROVIDER_TYPE) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsIscsiPortal(pub ::windows::core::IUnknown); impl IVdsIscsiPortal { pub unsafe fn GetProperties(&self) -> ::windows::core::Result<VDS_ISCSI_PORTAL_PROP> { let mut result__: <VDS_ISCSI_PORTAL_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_ISCSI_PORTAL_PROP>(result__) } pub unsafe fn GetSubSystem(&self) -> ::windows::core::Result<IVdsSubSystem> { let mut result__: <IVdsSubSystem as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsSubSystem>(result__) } pub unsafe fn QueryAssociatedPortalGroups(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn SetStatus(&self, status: VDS_ISCSI_PORTAL_STATUS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(status)).ok() } pub unsafe fn SetIpsecTunnelAddress(&self, ptunneladdress: *const VDS_IPADDRESS, pdestinationaddress: *const VDS_IPADDRESS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ptunneladdress), ::core::mem::transmute(pdestinationaddress)).ok() } pub unsafe fn GetIpsecSecurity(&self, pinitiatorportaladdress: *const VDS_IPADDRESS) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(pinitiatorportaladdress), &mut result__).from_abi::<u64>(result__) } pub unsafe fn SetIpsecSecurity(&self, pinitiatorportaladdress: *const VDS_IPADDRESS, ullsecurityflags: u64, pipseckey: *const VDS_ISCSI_IPSEC_KEY) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(pinitiatorportaladdress), ::core::mem::transmute(ullsecurityflags), ::core::mem::transmute(pipseckey)).ok() } } unsafe impl ::windows::core::Interface for IVdsIscsiPortal { type Vtable = IVdsIscsiPortal_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7fa1499d_ec85_4a8a_a47b_ff69201fcd34); } impl ::core::convert::From<IVdsIscsiPortal> for ::windows::core::IUnknown { fn from(value: IVdsIscsiPortal) -> Self { value.0 } } impl ::core::convert::From<&IVdsIscsiPortal> for ::windows::core::IUnknown { fn from(value: &IVdsIscsiPortal) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsIscsiPortal { 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 IVdsIscsiPortal { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsIscsiPortal_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, pportalprop: *mut VDS_ISCSI_PORTAL_PROP) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppsubsystem: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, status: VDS_ISCSI_PORTAL_STATUS) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ptunneladdress: *const VDS_IPADDRESS, pdestinationaddress: *const VDS_IPADDRESS) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pinitiatorportaladdress: *const VDS_IPADDRESS, pullsecurityflags: *mut u64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pinitiatorportaladdress: *const VDS_IPADDRESS, ullsecurityflags: u64, pipseckey: *const VDS_ISCSI_IPSEC_KEY) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsIscsiPortalGroup(pub ::windows::core::IUnknown); impl IVdsIscsiPortalGroup { pub unsafe fn GetProperties(&self) -> ::windows::core::Result<VDS_ISCSI_PORTALGROUP_PROP> { let mut result__: <VDS_ISCSI_PORTALGROUP_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_ISCSI_PORTALGROUP_PROP>(result__) } pub unsafe fn GetTarget(&self) -> ::windows::core::Result<IVdsIscsiTarget> { let mut result__: <IVdsIscsiTarget as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsIscsiTarget>(result__) } pub unsafe fn QueryAssociatedPortals(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn AddPortal<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, portalid: Param0) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), portalid.into_param().abi(), &mut result__).from_abi::<IVdsAsync>(result__) } pub unsafe fn RemovePortal<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, portalid: Param0) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), portalid.into_param().abi(), &mut result__).from_abi::<IVdsAsync>(result__) } pub unsafe fn Delete(&self) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsAsync>(result__) } } unsafe impl ::windows::core::Interface for IVdsIscsiPortalGroup { type Vtable = IVdsIscsiPortalGroup_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfef5f89d_a3dd_4b36_bf28_e7dde045c593); } impl ::core::convert::From<IVdsIscsiPortalGroup> for ::windows::core::IUnknown { fn from(value: IVdsIscsiPortalGroup) -> Self { value.0 } } impl ::core::convert::From<&IVdsIscsiPortalGroup> for ::windows::core::IUnknown { fn from(value: &IVdsIscsiPortalGroup) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsIscsiPortalGroup { 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 IVdsIscsiPortalGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsIscsiPortalGroup_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, pportalgroupprop: *mut VDS_ISCSI_PORTALGROUP_PROP) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pptarget: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, portalid: ::windows::core::GUID, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, portalid: ::windows::core::GUID, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsIscsiTarget(pub ::windows::core::IUnknown); impl IVdsIscsiTarget { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetProperties(&self) -> ::windows::core::Result<VDS_ISCSI_TARGET_PROP> { let mut result__: <VDS_ISCSI_TARGET_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_ISCSI_TARGET_PROP>(result__) } pub unsafe fn GetSubSystem(&self) -> ::windows::core::Result<IVdsSubSystem> { let mut result__: <IVdsSubSystem as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsSubSystem>(result__) } pub unsafe fn QueryPortalGroups(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn QueryAssociatedLuns(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn CreatePortalGroup(&self) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsAsync>(result__) } pub unsafe fn Delete(&self) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsAsync>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetFriendlyName<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, pwszfriendlyname: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), pwszfriendlyname.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetSharedSecret<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, ptargetsharedsecret: *const VDS_ISCSI_SHARED_SECRET, pwszinitiatorname: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(ptargetsharedsecret), pwszinitiatorname.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn RememberInitiatorSharedSecret<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, pwszinitiatorname: Param0, pinitiatorsharedsecret: *const VDS_ISCSI_SHARED_SECRET) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), pwszinitiatorname.into_param().abi(), ::core::mem::transmute(pinitiatorsharedsecret)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetConnectedInitiators(&self, pppwszinitiatorlist: *mut *mut super::super::Foundation::PWSTR, plnumberofinitiators: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(pppwszinitiatorlist), ::core::mem::transmute(plnumberofinitiators)).ok() } } unsafe impl ::windows::core::Interface for IVdsIscsiTarget { type Vtable = IVdsIscsiTarget_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaa8f5055_83e5_4bcc_aa73_19851a36a849); } impl ::core::convert::From<IVdsIscsiTarget> for ::windows::core::IUnknown { fn from(value: IVdsIscsiTarget) -> Self { value.0 } } impl ::core::convert::From<&IVdsIscsiTarget> for ::windows::core::IUnknown { fn from(value: &IVdsIscsiTarget) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsIscsiTarget { 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 IVdsIscsiTarget { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsIscsiTarget_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, ptargetprop: *mut VDS_ISCSI_TARGET_PROP) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppsubsystem: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszfriendlyname: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ptargetsharedsecret: *const VDS_ISCSI_SHARED_SECRET, pwszinitiatorname: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszinitiatorname: super::super::Foundation::PWSTR, pinitiatorsharedsecret: *const VDS_ISCSI_SHARED_SECRET) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pppwszinitiatorlist: *mut *mut super::super::Foundation::PWSTR, plnumberofinitiators: *mut i32) -> ::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 IVdsLun(pub ::windows::core::IUnknown); impl IVdsLun { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetProperties(&self) -> ::windows::core::Result<VDS_LUN_PROP> { let mut result__: <VDS_LUN_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_LUN_PROP>(result__) } pub unsafe fn GetSubSystem(&self) -> ::windows::core::Result<IVdsSubSystem> { let mut result__: <IVdsSubSystem as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsSubSystem>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIdentificationData(&self) -> ::windows::core::Result<VDS_LUN_INFORMATION> { let mut result__: <VDS_LUN_INFORMATION as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_LUN_INFORMATION>(result__) } pub unsafe fn QueryActiveControllers(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn Extend(&self, ullnumberofbytestoadd: u64, pdriveidarray: *const ::windows::core::GUID, lnumberofdrives: i32) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(ullnumberofbytestoadd), ::core::mem::transmute(pdriveidarray), ::core::mem::transmute(lnumberofdrives), &mut result__).from_abi::<IVdsAsync>(result__) } pub unsafe fn Shrink(&self, ullnumberofbytestoremove: u64) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(ullnumberofbytestoremove), &mut result__).from_abi::<IVdsAsync>(result__) } pub unsafe fn QueryPlexes(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn AddPlex<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, lunid: Param0) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), lunid.into_param().abi(), &mut result__).from_abi::<IVdsAsync>(result__) } pub unsafe fn RemovePlex<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, plexid: Param0) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), plexid.into_param().abi(), &mut result__).from_abi::<IVdsAsync>(result__) } pub unsafe fn Recover(&self) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsAsync>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetMask<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, pwszunmaskinglist: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), pwszunmaskinglist.into_param().abi()).ok() } pub unsafe fn Delete(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn AssociateControllers(&self, pactivecontrolleridarray: *const ::windows::core::GUID, lnumberofactivecontrollers: i32, pinactivecontrolleridarray: *const ::windows::core::GUID, lnumberofinactivecontrollers: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(pactivecontrolleridarray), ::core::mem::transmute(lnumberofactivecontrollers), ::core::mem::transmute(pinactivecontrolleridarray), ::core::mem::transmute(lnumberofinactivecontrollers)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn QueryHints(&self) -> ::windows::core::Result<VDS_HINTS> { let mut result__: <VDS_HINTS as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_HINTS>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn ApplyHints(&self, phints: *const VDS_HINTS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(phints)).ok() } pub unsafe fn SetStatus(&self, status: VDS_LUN_STATUS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(status)).ok() } pub unsafe fn QueryMaxLunExtendSize(&self, pdriveidarray: *const ::windows::core::GUID, lnumberofdrives: i32) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdriveidarray), ::core::mem::transmute(lnumberofdrives), &mut result__).from_abi::<u64>(result__) } } unsafe impl ::windows::core::Interface for IVdsLun { type Vtable = IVdsLun_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3540a9c7_e60f_4111_a840_8bba6c2c83d8); } impl ::core::convert::From<IVdsLun> for ::windows::core::IUnknown { fn from(value: IVdsLun) -> Self { value.0 } } impl ::core::convert::From<&IVdsLun> for ::windows::core::IUnknown { fn from(value: &IVdsLun) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsLun { 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 IVdsLun { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsLun_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, plunprop: *mut VDS_LUN_PROP) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppsubsystem: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pluninfo: *mut VDS_LUN_INFORMATION) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ullnumberofbytestoadd: u64, pdriveidarray: *const ::windows::core::GUID, lnumberofdrives: i32, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ullnumberofbytestoremove: u64, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lunid: ::windows::core::GUID, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, plexid: ::windows::core::GUID, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszunmaskinglist: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pactivecontrolleridarray: *const ::windows::core::GUID, lnumberofactivecontrollers: i32, pinactivecontrolleridarray: *const ::windows::core::GUID, lnumberofinactivecontrollers: i32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, phints: *mut VDS_HINTS) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, phints: *const VDS_HINTS) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, status: VDS_LUN_STATUS) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdriveidarray: *const ::windows::core::GUID, lnumberofdrives: i32, pullmaxbytestobeadded: *mut u64) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsLun2(pub ::windows::core::IUnknown); impl IVdsLun2 { #[cfg(feature = "Win32_Foundation")] pub unsafe fn QueryHints2(&self) -> ::windows::core::Result<VDS_HINTS2> { let mut result__: <VDS_HINTS2 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_HINTS2>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn ApplyHints2(&self, phints2: *const VDS_HINTS2) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(phints2)).ok() } } unsafe impl ::windows::core::Interface for IVdsLun2 { type Vtable = IVdsLun2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe5b3a735_9efb_499a_8071_4394d9ee6fcb); } impl ::core::convert::From<IVdsLun2> for ::windows::core::IUnknown { fn from(value: IVdsLun2) -> Self { value.0 } } impl ::core::convert::From<&IVdsLun2> for ::windows::core::IUnknown { fn from(value: &IVdsLun2) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsLun2 { 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 IVdsLun2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsLun2_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, phints2: *mut VDS_HINTS2) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, phints2: *const VDS_HINTS2) -> ::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 IVdsLunControllerPorts(pub ::windows::core::IUnknown); impl IVdsLunControllerPorts { pub unsafe fn AssociateControllerPorts(&self, pactivecontrollerportidarray: *const ::windows::core::GUID, lnumberofactivecontrollerports: i32, pinactivecontrollerportidarray: *const ::windows::core::GUID, lnumberofinactivecontrollerports: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pactivecontrollerportidarray), ::core::mem::transmute(lnumberofactivecontrollerports), ::core::mem::transmute(pinactivecontrollerportidarray), ::core::mem::transmute(lnumberofinactivecontrollerports)).ok() } pub unsafe fn QueryActiveControllerPorts(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } } unsafe impl ::windows::core::Interface for IVdsLunControllerPorts { type Vtable = IVdsLunControllerPorts_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x451fe266_da6d_406a_bb60_82e534f85aeb); } impl ::core::convert::From<IVdsLunControllerPorts> for ::windows::core::IUnknown { fn from(value: IVdsLunControllerPorts) -> Self { value.0 } } impl ::core::convert::From<&IVdsLunControllerPorts> for ::windows::core::IUnknown { fn from(value: &IVdsLunControllerPorts) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsLunControllerPorts { 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 IVdsLunControllerPorts { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsLunControllerPorts_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, pactivecontrollerportidarray: *const ::windows::core::GUID, lnumberofactivecontrollerports: i32, pinactivecontrollerportidarray: *const ::windows::core::GUID, lnumberofinactivecontrollerports: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsLunIscsi(pub ::windows::core::IUnknown); impl IVdsLunIscsi { pub unsafe fn AssociateTargets(&self, ptargetidarray: *const ::windows::core::GUID, lnumberoftargets: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(ptargetidarray), ::core::mem::transmute(lnumberoftargets)).ok() } pub unsafe fn QueryAssociatedTargets(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } } unsafe impl ::windows::core::Interface for IVdsLunIscsi { type Vtable = IVdsLunIscsi_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0d7c1e64_b59b_45ae_b86a_2c2cc6a42067); } impl ::core::convert::From<IVdsLunIscsi> for ::windows::core::IUnknown { fn from(value: IVdsLunIscsi) -> Self { value.0 } } impl ::core::convert::From<&IVdsLunIscsi> for ::windows::core::IUnknown { fn from(value: &IVdsLunIscsi) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsLunIscsi { 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 IVdsLunIscsi { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsLunIscsi_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, ptargetidarray: *const ::windows::core::GUID, lnumberoftargets: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsLunMpio(pub ::windows::core::IUnknown); impl IVdsLunMpio { pub unsafe fn GetPathInfo(&self, pppaths: *mut *mut VDS_PATH_INFO, plnumberofpaths: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pppaths), ::core::mem::transmute(plnumberofpaths)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetLoadBalancePolicy(&self, ppolicy: *mut VDS_LOADBALANCE_POLICY_ENUM, pppaths: *mut *mut VDS_PATH_POLICY, plnumberofpaths: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ppolicy), ::core::mem::transmute(pppaths), ::core::mem::transmute(plnumberofpaths)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetLoadBalancePolicy(&self, policy: VDS_LOADBALANCE_POLICY_ENUM, ppaths: *const VDS_PATH_POLICY, lnumberofpaths: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(policy), ::core::mem::transmute(ppaths), ::core::mem::transmute(lnumberofpaths)).ok() } pub unsafe fn GetSupportedLbPolicies(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } } unsafe impl ::windows::core::Interface for IVdsLunMpio { type Vtable = IVdsLunMpio_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7c5fbae3_333a_48a1_a982_33c15788cde3); } impl ::core::convert::From<IVdsLunMpio> for ::windows::core::IUnknown { fn from(value: IVdsLunMpio) -> Self { value.0 } } impl ::core::convert::From<&IVdsLunMpio> for ::windows::core::IUnknown { fn from(value: &IVdsLunMpio) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsLunMpio { 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 IVdsLunMpio { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsLunMpio_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, pppaths: *mut *mut VDS_PATH_INFO, plnumberofpaths: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppolicy: *mut VDS_LOADBALANCE_POLICY_ENUM, pppaths: *mut *mut VDS_PATH_POLICY, plnumberofpaths: *mut i32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, policy: VDS_LOADBALANCE_POLICY_ENUM, ppaths: *const VDS_PATH_POLICY, lnumberofpaths: i32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pullbflags: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsLunNaming(pub ::windows::core::IUnknown); impl IVdsLunNaming { #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetFriendlyName<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, pwszfriendlyname: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pwszfriendlyname.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IVdsLunNaming { type Vtable = IVdsLunNaming_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x907504cb_6b4e_4d88_a34d_17ba661fbb06); } impl ::core::convert::From<IVdsLunNaming> for ::windows::core::IUnknown { fn from(value: IVdsLunNaming) -> Self { value.0 } } impl ::core::convert::From<&IVdsLunNaming> for ::windows::core::IUnknown { fn from(value: &IVdsLunNaming) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsLunNaming { 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 IVdsLunNaming { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsLunNaming_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, pwszfriendlyname: super::super::Foundation::PWSTR) -> ::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 IVdsLunNumber(pub ::windows::core::IUnknown); impl IVdsLunNumber { pub unsafe fn GetLunNumber(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } } unsafe impl ::windows::core::Interface for IVdsLunNumber { type Vtable = IVdsLunNumber_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd3f95e46_54b3_41f9_b678_0f1871443a08); } impl ::core::convert::From<IVdsLunNumber> for ::windows::core::IUnknown { fn from(value: IVdsLunNumber) -> Self { value.0 } } impl ::core::convert::From<&IVdsLunNumber> for ::windows::core::IUnknown { fn from(value: &IVdsLunNumber) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsLunNumber { 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 IVdsLunNumber { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsLunNumber_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, pullunnumber: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsLunPlex(pub ::windows::core::IUnknown); impl IVdsLunPlex { pub unsafe fn GetProperties(&self) -> ::windows::core::Result<VDS_LUN_PLEX_PROP> { let mut result__: <VDS_LUN_PLEX_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_LUN_PLEX_PROP>(result__) } pub unsafe fn GetLun(&self) -> ::windows::core::Result<IVdsLun> { let mut result__: <IVdsLun as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsLun>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn QueryExtents(&self, ppextentarray: *mut *mut VDS_DRIVE_EXTENT, plnumberofextents: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(ppextentarray), ::core::mem::transmute(plnumberofextents)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn QueryHints(&self) -> ::windows::core::Result<VDS_HINTS> { let mut result__: <VDS_HINTS as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_HINTS>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn ApplyHints(&self, phints: *const VDS_HINTS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(phints)).ok() } } unsafe impl ::windows::core::Interface for IVdsLunPlex { type Vtable = IVdsLunPlex_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0ee1a790_5d2e_4abb_8c99_c481e8be2138); } impl ::core::convert::From<IVdsLunPlex> for ::windows::core::IUnknown { fn from(value: IVdsLunPlex) -> Self { value.0 } } impl ::core::convert::From<&IVdsLunPlex> for ::windows::core::IUnknown { fn from(value: &IVdsLunPlex) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsLunPlex { 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 IVdsLunPlex { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsLunPlex_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, pplexprop: *mut VDS_LUN_PLEX_PROP) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pplun: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppextentarray: *mut *mut VDS_DRIVE_EXTENT, plnumberofextents: *mut i32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, phints: *mut VDS_HINTS) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, phints: *const VDS_HINTS) -> ::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 IVdsMaintenance(pub ::windows::core::IUnknown); impl IVdsMaintenance { pub unsafe fn StartMaintenance(&self, operation: VDS_MAINTENANCE_OPERATION) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(operation)).ok() } pub unsafe fn StopMaintenance(&self, operation: VDS_MAINTENANCE_OPERATION) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(operation)).ok() } pub unsafe fn PulseMaintenance(&self, operation: VDS_MAINTENANCE_OPERATION, ulcount: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(operation), ::core::mem::transmute(ulcount)).ok() } } unsafe impl ::windows::core::Interface for IVdsMaintenance { type Vtable = IVdsMaintenance_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdaebeef3_8523_47ed_a2b9_05cecce2a1ae); } impl ::core::convert::From<IVdsMaintenance> for ::windows::core::IUnknown { fn from(value: IVdsMaintenance) -> Self { value.0 } } impl ::core::convert::From<&IVdsMaintenance> for ::windows::core::IUnknown { fn from(value: &IVdsMaintenance) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsMaintenance { 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 IVdsMaintenance { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsMaintenance_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, operation: VDS_MAINTENANCE_OPERATION) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, operation: VDS_MAINTENANCE_OPERATION) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, operation: VDS_MAINTENANCE_OPERATION, ulcount: u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsProvider(pub ::windows::core::IUnknown); impl IVdsProvider { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetProperties(&self) -> ::windows::core::Result<VDS_PROVIDER_PROP> { let mut result__: <VDS_PROVIDER_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_PROVIDER_PROP>(result__) } } unsafe impl ::windows::core::Interface for IVdsProvider { type Vtable = IVdsProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x10c5e575_7984_4e81_a56b_431f5f92ae42); } impl ::core::convert::From<IVdsProvider> for ::windows::core::IUnknown { fn from(value: IVdsProvider) -> Self { value.0 } } impl ::core::convert::From<&IVdsProvider> for ::windows::core::IUnknown { fn from(value: &IVdsProvider) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsProvider { 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 IVdsProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsProvider_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, pproviderprop: *mut VDS_PROVIDER_PROP) -> ::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 IVdsProviderPrivate(pub ::windows::core::IUnknown); impl IVdsProviderPrivate { pub unsafe fn GetObject<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, objectid: Param0, r#type: VDS_OBJECT_TYPE) -> ::windows::core::Result<::windows::core::IUnknown> { let mut result__: <::windows::core::IUnknown as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), objectid.into_param().abi(), ::core::mem::transmute(r#type), &mut result__).from_abi::<::windows::core::IUnknown>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn OnLoad<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, pwszmachinename: Param0, pcallbackobject: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), pwszmachinename.into_param().abi(), pcallbackobject.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn OnUnload<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, bforceunload: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), bforceunload.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IVdsProviderPrivate { type Vtable = IVdsProviderPrivate_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x11f3cd41_b7e8_48ff_9472_9dff018aa292); } impl ::core::convert::From<IVdsProviderPrivate> for ::windows::core::IUnknown { fn from(value: IVdsProviderPrivate) -> Self { value.0 } } impl ::core::convert::From<&IVdsProviderPrivate> for ::windows::core::IUnknown { fn from(value: &IVdsProviderPrivate) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsProviderPrivate { 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 IVdsProviderPrivate { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsProviderPrivate_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, objectid: ::windows::core::GUID, r#type: VDS_OBJECT_TYPE, ppobjectunk: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszmachinename: super::super::Foundation::PWSTR, pcallbackobject: ::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, bforceunload: super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsProviderSupport(pub ::windows::core::IUnknown); impl IVdsProviderSupport { pub unsafe fn GetVersionSupport(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } } unsafe impl ::windows::core::Interface for IVdsProviderSupport { type Vtable = IVdsProviderSupport_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1732be13_e8f9_4a03_bfbc_5f616aa66ce1); } impl ::core::convert::From<IVdsProviderSupport> for ::windows::core::IUnknown { fn from(value: IVdsProviderSupport) -> Self { value.0 } } impl ::core::convert::From<&IVdsProviderSupport> for ::windows::core::IUnknown { fn from(value: &IVdsProviderSupport) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsProviderSupport { 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 IVdsProviderSupport { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsProviderSupport_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, ulversionsupport: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsStoragePool(pub ::windows::core::IUnknown); impl IVdsStoragePool { pub unsafe fn GetProvider(&self) -> ::windows::core::Result<IVdsProvider> { let mut result__: <IVdsProvider as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsProvider>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetProperties(&self) -> ::windows::core::Result<VDS_STORAGE_POOL_PROP> { let mut result__: <VDS_STORAGE_POOL_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_STORAGE_POOL_PROP>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetAttributes(&self) -> ::windows::core::Result<VDS_POOL_ATTRIBUTES> { let mut result__: <VDS_POOL_ATTRIBUTES as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_POOL_ATTRIBUTES>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn QueryDriveExtents(&self, ppextentarray: *mut *mut VDS_STORAGE_POOL_DRIVE_EXTENT, plnumberofextents: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(ppextentarray), ::core::mem::transmute(plnumberofextents)).ok() } pub unsafe fn QueryAllocatedLuns(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn QueryAllocatedStoragePools(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } } unsafe impl ::windows::core::Interface for IVdsStoragePool { type Vtable = IVdsStoragePool_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x932ca8cf_0eb3_4ba8_9620_22665d7f8450); } impl ::core::convert::From<IVdsStoragePool> for ::windows::core::IUnknown { fn from(value: IVdsStoragePool) -> Self { value.0 } } impl ::core::convert::From<&IVdsStoragePool> for ::windows::core::IUnknown { fn from(value: &IVdsStoragePool) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsStoragePool { 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 IVdsStoragePool { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsStoragePool_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, ppprovider: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pstoragepoolprop: *mut VDS_STORAGE_POOL_PROP) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pstoragepoolattributes: *mut VDS_POOL_ATTRIBUTES) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppextentarray: *mut *mut VDS_STORAGE_POOL_DRIVE_EXTENT, plnumberofextents: *mut i32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsSubSystem(pub ::windows::core::IUnknown); impl IVdsSubSystem { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetProperties(&self) -> ::windows::core::Result<VDS_SUB_SYSTEM_PROP> { let mut result__: <VDS_SUB_SYSTEM_PROP as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_SUB_SYSTEM_PROP>(result__) } pub unsafe fn GetProvider(&self) -> ::windows::core::Result<IVdsProvider> { let mut result__: <IVdsProvider as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IVdsProvider>(result__) } pub unsafe fn QueryControllers(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn QueryLuns(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn QueryDrives(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn GetDrive(&self, sbusnumber: i16, sslotnumber: i16) -> ::windows::core::Result<IVdsDrive> { let mut result__: <IVdsDrive as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(sbusnumber), ::core::mem::transmute(sslotnumber), &mut result__).from_abi::<IVdsDrive>(result__) } pub unsafe fn Reenumerate(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn SetControllerStatus(&self, ponlinecontrolleridarray: *const ::windows::core::GUID, lnumberofonlinecontrollers: i32, pofflinecontrolleridarray: *const ::windows::core::GUID, lnumberofofflinecontrollers: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(ponlinecontrolleridarray), ::core::mem::transmute(lnumberofonlinecontrollers), ::core::mem::transmute(pofflinecontrolleridarray), ::core::mem::transmute(lnumberofofflinecontrollers)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn CreateLun<'a, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, r#type: VDS_LUN_TYPE, ullsizeinbytes: u64, pdriveidarray: *const ::windows::core::GUID, lnumberofdrives: i32, pwszunmaskinglist: Param4, phints: *const VDS_HINTS) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(r#type), ::core::mem::transmute(ullsizeinbytes), ::core::mem::transmute(pdriveidarray), ::core::mem::transmute(lnumberofdrives), pwszunmaskinglist.into_param().abi(), ::core::mem::transmute(phints), &mut result__).from_abi::<IVdsAsync>(result__) } pub unsafe fn ReplaceDrive<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, drivetobereplaced: Param0, replacementdrive: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), drivetobereplaced.into_param().abi(), replacementdrive.into_param().abi()).ok() } pub unsafe fn SetStatus(&self, status: VDS_SUB_SYSTEM_STATUS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(status)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn QueryMaxLunCreateSize(&self, r#type: VDS_LUN_TYPE, pdriveidarray: *const ::windows::core::GUID, lnumberofdrives: i32, phints: *const VDS_HINTS) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(r#type), ::core::mem::transmute(pdriveidarray), ::core::mem::transmute(lnumberofdrives), ::core::mem::transmute(phints), &mut result__).from_abi::<u64>(result__) } } unsafe impl ::windows::core::Interface for IVdsSubSystem { type Vtable = IVdsSubSystem_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6fcee2d3_6d90_4f91_80e2_a5c7caaca9d8); } impl ::core::convert::From<IVdsSubSystem> for ::windows::core::IUnknown { fn from(value: IVdsSubSystem) -> Self { value.0 } } impl ::core::convert::From<&IVdsSubSystem> for ::windows::core::IUnknown { fn from(value: &IVdsSubSystem) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsSubSystem { 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 IVdsSubSystem { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsSubSystem_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, psubsystemprop: *mut VDS_SUB_SYSTEM_PROP) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppprovider: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sbusnumber: i16, sslotnumber: i16, ppdrive: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ponlinecontrolleridarray: *const ::windows::core::GUID, lnumberofonlinecontrollers: i32, pofflinecontrolleridarray: *const ::windows::core::GUID, lnumberofofflinecontrollers: i32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, r#type: VDS_LUN_TYPE, ullsizeinbytes: u64, pdriveidarray: *const ::windows::core::GUID, lnumberofdrives: i32, pwszunmaskinglist: super::super::Foundation::PWSTR, phints: *const VDS_HINTS, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, drivetobereplaced: ::windows::core::GUID, replacementdrive: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, status: VDS_SUB_SYSTEM_STATUS) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, r#type: VDS_LUN_TYPE, pdriveidarray: *const ::windows::core::GUID, lnumberofdrives: i32, phints: *const VDS_HINTS, pullmaxlunsize: *mut u64) -> ::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 IVdsSubSystem2(pub ::windows::core::IUnknown); impl IVdsSubSystem2 { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetProperties2(&self) -> ::windows::core::Result<VDS_SUB_SYSTEM_PROP2> { let mut result__: <VDS_SUB_SYSTEM_PROP2 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<VDS_SUB_SYSTEM_PROP2>(result__) } pub unsafe fn GetDrive2(&self, sbusnumber: i16, sslotnumber: i16, ulenclosurenumber: u32) -> ::windows::core::Result<IVdsDrive> { let mut result__: <IVdsDrive as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(sbusnumber), ::core::mem::transmute(sslotnumber), ::core::mem::transmute(ulenclosurenumber), &mut result__).from_abi::<IVdsDrive>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn CreateLun2<'a, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, r#type: VDS_LUN_TYPE, ullsizeinbytes: u64, pdriveidarray: *const ::windows::core::GUID, lnumberofdrives: i32, pwszunmaskinglist: Param4, phints2: *const VDS_HINTS2) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(r#type), ::core::mem::transmute(ullsizeinbytes), ::core::mem::transmute(pdriveidarray), ::core::mem::transmute(lnumberofdrives), pwszunmaskinglist.into_param().abi(), ::core::mem::transmute(phints2), &mut result__).from_abi::<IVdsAsync>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn QueryMaxLunCreateSize2(&self, r#type: VDS_LUN_TYPE, pdriveidarray: *const ::windows::core::GUID, lnumberofdrives: i32, phints2: *const VDS_HINTS2) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(r#type), ::core::mem::transmute(pdriveidarray), ::core::mem::transmute(lnumberofdrives), ::core::mem::transmute(phints2), &mut result__).from_abi::<u64>(result__) } } unsafe impl ::windows::core::Interface for IVdsSubSystem2 { type Vtable = IVdsSubSystem2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbe666735_7800_4a77_9d9c_40f85b87e292); } impl ::core::convert::From<IVdsSubSystem2> for ::windows::core::IUnknown { fn from(value: IVdsSubSystem2) -> Self { value.0 } } impl ::core::convert::From<&IVdsSubSystem2> for ::windows::core::IUnknown { fn from(value: &IVdsSubSystem2) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsSubSystem2 { 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 IVdsSubSystem2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsSubSystem2_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, psubsystemprop2: *mut VDS_SUB_SYSTEM_PROP2) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sbusnumber: i16, sslotnumber: i16, ulenclosurenumber: u32, ppdrive: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, r#type: VDS_LUN_TYPE, ullsizeinbytes: u64, pdriveidarray: *const ::windows::core::GUID, lnumberofdrives: i32, pwszunmaskinglist: super::super::Foundation::PWSTR, phints2: *const VDS_HINTS2, ppasync: *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, r#type: VDS_LUN_TYPE, pdriveidarray: *const ::windows::core::GUID, lnumberofdrives: i32, phints2: *const VDS_HINTS2, pullmaxlunsize: *mut u64) -> ::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 IVdsSubSystemInterconnect(pub ::windows::core::IUnknown); impl IVdsSubSystemInterconnect { pub unsafe fn GetSupportedInterconnects(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } } unsafe impl ::windows::core::Interface for IVdsSubSystemInterconnect { type Vtable = IVdsSubSystemInterconnect_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9e6fa560_c141_477b_83ba_0b6c38f7febf); } impl ::core::convert::From<IVdsSubSystemInterconnect> for ::windows::core::IUnknown { fn from(value: IVdsSubSystemInterconnect) -> Self { value.0 } } impl ::core::convert::From<&IVdsSubSystemInterconnect> for ::windows::core::IUnknown { fn from(value: &IVdsSubSystemInterconnect) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsSubSystemInterconnect { 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 IVdsSubSystemInterconnect { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsSubSystemInterconnect_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, pulsupportedinterconnectsflag: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsSubSystemIscsi(pub ::windows::core::IUnknown); impl IVdsSubSystemIscsi { pub unsafe fn QueryTargets(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } pub unsafe fn QueryPortals(&self) -> ::windows::core::Result<IEnumVdsObject> { let mut result__: <IEnumVdsObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumVdsObject>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn CreateTarget<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, pwsziscsiname: Param0, pwszfriendlyname: Param1) -> ::windows::core::Result<IVdsAsync> { let mut result__: <IVdsAsync as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), pwsziscsiname.into_param().abi(), pwszfriendlyname.into_param().abi(), &mut result__).from_abi::<IVdsAsync>(result__) } pub unsafe fn SetIpsecGroupPresharedKey(&self, pipseckey: *const VDS_ISCSI_IPSEC_KEY) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pipseckey)).ok() } } unsafe impl ::windows::core::Interface for IVdsSubSystemIscsi { type Vtable = IVdsSubSystemIscsi_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0027346f_40d0_4b45_8cec_5906dc0380c8); } impl ::core::convert::From<IVdsSubSystemIscsi> for ::windows::core::IUnknown { fn from(value: IVdsSubSystemIscsi) -> Self { value.0 } } impl ::core::convert::From<&IVdsSubSystemIscsi> for ::windows::core::IUnknown { fn from(value: &IVdsSubSystemIscsi) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsSubSystemIscsi { 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 IVdsSubSystemIscsi { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsSubSystemIscsi_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, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwsziscsiname: super::super::Foundation::PWSTR, pwszfriendlyname: super::super::Foundation::PWSTR, ppasync: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pipseckey: *const VDS_ISCSI_IPSEC_KEY) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVdsSubSystemNaming(pub ::windows::core::IUnknown); impl IVdsSubSystemNaming { #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetFriendlyName<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, pwszfriendlyname: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pwszfriendlyname.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IVdsSubSystemNaming { type Vtable = IVdsSubSystemNaming_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0d70faa3_9cd4_4900_aa20_6981b6aafc75); } impl ::core::convert::From<IVdsSubSystemNaming> for ::windows::core::IUnknown { fn from(value: IVdsSubSystemNaming) -> Self { value.0 } } impl ::core::convert::From<&IVdsSubSystemNaming> for ::windows::core::IUnknown { fn from(value: &IVdsSubSystemNaming) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVdsSubSystemNaming { 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 IVdsSubSystemNaming { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVdsSubSystemNaming_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, pwszfriendlyname: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); pub const MAX_FS_ALLOWED_CLUSTER_SIZES_SIZE: u32 = 32u32; pub const MAX_FS_FORMAT_SUPPORT_NAME_SIZE: u32 = 32u32; pub const MAX_FS_NAME_SIZE: u32 = 8u32; impl ::core::clone::Clone for VDS_ASYNC_OUTPUT { fn clone(&self) -> Self { unimplemented!() } } #[repr(C)] pub struct VDS_ASYNC_OUTPUT { pub r#type: VDS_ASYNC_OUTPUT_TYPE, pub Anonymous: VDS_ASYNC_OUTPUT_0, } impl VDS_ASYNC_OUTPUT {} impl ::core::default::Default for VDS_ASYNC_OUTPUT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VDS_ASYNC_OUTPUT { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VDS_ASYNC_OUTPUT {} unsafe impl ::windows::core::Abi for VDS_ASYNC_OUTPUT { type Abi = ::core::mem::ManuallyDrop<Self>; } impl ::core::clone::Clone for VDS_ASYNC_OUTPUT_0 { fn clone(&self) -> Self { unimplemented!() } } #[repr(C)] pub union VDS_ASYNC_OUTPUT_0 { pub cp: VDS_ASYNC_OUTPUT_0_2, pub cv: ::core::mem::ManuallyDrop<VDS_ASYNC_OUTPUT_0_5>, pub bvp: ::core::mem::ManuallyDrop<VDS_ASYNC_OUTPUT_0_0>, pub sv: VDS_ASYNC_OUTPUT_0_7, pub cl: ::core::mem::ManuallyDrop<VDS_ASYNC_OUTPUT_0_1>, pub ct: ::core::mem::ManuallyDrop<VDS_ASYNC_OUTPUT_0_4>, pub cpg: ::core::mem::ManuallyDrop<VDS_ASYNC_OUTPUT_0_3>, pub cvd: ::core::mem::ManuallyDrop<VDS_ASYNC_OUTPUT_0_6>, } impl VDS_ASYNC_OUTPUT_0 {} impl ::core::default::Default for VDS_ASYNC_OUTPUT_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VDS_ASYNC_OUTPUT_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VDS_ASYNC_OUTPUT_0 {} unsafe impl ::windows::core::Abi for VDS_ASYNC_OUTPUT_0 { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: clone :: Clone)] #[repr(C)] pub struct VDS_ASYNC_OUTPUT_0_0 { pub pVolumeUnk: ::core::option::Option<::windows::core::IUnknown>, } impl VDS_ASYNC_OUTPUT_0_0 {} impl ::core::default::Default for VDS_ASYNC_OUTPUT_0_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ASYNC_OUTPUT_0_0 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_bvp").field("pVolumeUnk", &self.pVolumeUnk).finish() } } impl ::core::cmp::PartialEq for VDS_ASYNC_OUTPUT_0_0 { fn eq(&self, other: &Self) -> bool { self.pVolumeUnk == other.pVolumeUnk } } impl ::core::cmp::Eq for VDS_ASYNC_OUTPUT_0_0 {} unsafe impl ::windows::core::Abi for VDS_ASYNC_OUTPUT_0_0 { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: clone :: Clone)] #[repr(C)] pub struct VDS_ASYNC_OUTPUT_0_1 { pub pLunUnk: ::core::option::Option<::windows::core::IUnknown>, } impl VDS_ASYNC_OUTPUT_0_1 {} impl ::core::default::Default for VDS_ASYNC_OUTPUT_0_1 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ASYNC_OUTPUT_0_1 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_cl").field("pLunUnk", &self.pLunUnk).finish() } } impl ::core::cmp::PartialEq for VDS_ASYNC_OUTPUT_0_1 { fn eq(&self, other: &Self) -> bool { self.pLunUnk == other.pLunUnk } } impl ::core::cmp::Eq for VDS_ASYNC_OUTPUT_0_1 {} unsafe impl ::windows::core::Abi for VDS_ASYNC_OUTPUT_0_1 { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_ASYNC_OUTPUT_0_2 { pub ullOffset: u64, pub volumeId: ::windows::core::GUID, } impl VDS_ASYNC_OUTPUT_0_2 {} impl ::core::default::Default for VDS_ASYNC_OUTPUT_0_2 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ASYNC_OUTPUT_0_2 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_cp").field("ullOffset", &self.ullOffset).field("volumeId", &self.volumeId).finish() } } impl ::core::cmp::PartialEq for VDS_ASYNC_OUTPUT_0_2 { fn eq(&self, other: &Self) -> bool { self.ullOffset == other.ullOffset && self.volumeId == other.volumeId } } impl ::core::cmp::Eq for VDS_ASYNC_OUTPUT_0_2 {} unsafe impl ::windows::core::Abi for VDS_ASYNC_OUTPUT_0_2 { type Abi = Self; } #[derive(:: core :: clone :: Clone)] #[repr(C)] pub struct VDS_ASYNC_OUTPUT_0_3 { pub pPortalGroupUnk: ::core::option::Option<::windows::core::IUnknown>, } impl VDS_ASYNC_OUTPUT_0_3 {} impl ::core::default::Default for VDS_ASYNC_OUTPUT_0_3 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ASYNC_OUTPUT_0_3 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_cpg").field("pPortalGroupUnk", &self.pPortalGroupUnk).finish() } } impl ::core::cmp::PartialEq for VDS_ASYNC_OUTPUT_0_3 { fn eq(&self, other: &Self) -> bool { self.pPortalGroupUnk == other.pPortalGroupUnk } } impl ::core::cmp::Eq for VDS_ASYNC_OUTPUT_0_3 {} unsafe impl ::windows::core::Abi for VDS_ASYNC_OUTPUT_0_3 { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: clone :: Clone)] #[repr(C)] pub struct VDS_ASYNC_OUTPUT_0_4 { pub pTargetUnk: ::core::option::Option<::windows::core::IUnknown>, } impl VDS_ASYNC_OUTPUT_0_4 {} impl ::core::default::Default for VDS_ASYNC_OUTPUT_0_4 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ASYNC_OUTPUT_0_4 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_ct").field("pTargetUnk", &self.pTargetUnk).finish() } } impl ::core::cmp::PartialEq for VDS_ASYNC_OUTPUT_0_4 { fn eq(&self, other: &Self) -> bool { self.pTargetUnk == other.pTargetUnk } } impl ::core::cmp::Eq for VDS_ASYNC_OUTPUT_0_4 {} unsafe impl ::windows::core::Abi for VDS_ASYNC_OUTPUT_0_4 { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: clone :: Clone)] #[repr(C)] pub struct VDS_ASYNC_OUTPUT_0_5 { pub pVolumeUnk: ::core::option::Option<::windows::core::IUnknown>, } impl VDS_ASYNC_OUTPUT_0_5 {} impl ::core::default::Default for VDS_ASYNC_OUTPUT_0_5 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ASYNC_OUTPUT_0_5 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_cv").field("pVolumeUnk", &self.pVolumeUnk).finish() } } impl ::core::cmp::PartialEq for VDS_ASYNC_OUTPUT_0_5 { fn eq(&self, other: &Self) -> bool { self.pVolumeUnk == other.pVolumeUnk } } impl ::core::cmp::Eq for VDS_ASYNC_OUTPUT_0_5 {} unsafe impl ::windows::core::Abi for VDS_ASYNC_OUTPUT_0_5 { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: clone :: Clone)] #[repr(C)] pub struct VDS_ASYNC_OUTPUT_0_6 { pub pVDiskUnk: ::core::option::Option<::windows::core::IUnknown>, } impl VDS_ASYNC_OUTPUT_0_6 {} impl ::core::default::Default for VDS_ASYNC_OUTPUT_0_6 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ASYNC_OUTPUT_0_6 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_cvd").field("pVDiskUnk", &self.pVDiskUnk).finish() } } impl ::core::cmp::PartialEq for VDS_ASYNC_OUTPUT_0_6 { fn eq(&self, other: &Self) -> bool { self.pVDiskUnk == other.pVDiskUnk } } impl ::core::cmp::Eq for VDS_ASYNC_OUTPUT_0_6 {} unsafe impl ::windows::core::Abi for VDS_ASYNC_OUTPUT_0_6 { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_ASYNC_OUTPUT_0_7 { pub ullReclaimedBytes: u64, } impl VDS_ASYNC_OUTPUT_0_7 {} impl ::core::default::Default for VDS_ASYNC_OUTPUT_0_7 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ASYNC_OUTPUT_0_7 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_sv").field("ullReclaimedBytes", &self.ullReclaimedBytes).finish() } } impl ::core::cmp::PartialEq for VDS_ASYNC_OUTPUT_0_7 { fn eq(&self, other: &Self) -> bool { self.ullReclaimedBytes == other.ullReclaimedBytes } } impl ::core::cmp::Eq for VDS_ASYNC_OUTPUT_0_7 {} unsafe impl ::windows::core::Abi for VDS_ASYNC_OUTPUT_0_7 { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_ASYNC_OUTPUT_TYPE(pub i32); pub const VDS_ASYNCOUT_UNKNOWN: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(0i32); pub const VDS_ASYNCOUT_CREATEVOLUME: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(1i32); pub const VDS_ASYNCOUT_EXTENDVOLUME: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(2i32); pub const VDS_ASYNCOUT_SHRINKVOLUME: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(3i32); pub const VDS_ASYNCOUT_ADDVOLUMEPLEX: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(4i32); pub const VDS_ASYNCOUT_BREAKVOLUMEPLEX: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(5i32); pub const VDS_ASYNCOUT_REMOVEVOLUMEPLEX: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(6i32); pub const VDS_ASYNCOUT_REPAIRVOLUMEPLEX: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(7i32); pub const VDS_ASYNCOUT_RECOVERPACK: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(8i32); pub const VDS_ASYNCOUT_REPLACEDISK: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(9i32); pub const VDS_ASYNCOUT_CREATEPARTITION: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(10i32); pub const VDS_ASYNCOUT_CLEAN: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(11i32); pub const VDS_ASYNCOUT_CREATELUN: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(50i32); pub const VDS_ASYNCOUT_ADDLUNPLEX: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(52i32); pub const VDS_ASYNCOUT_REMOVELUNPLEX: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(53i32); pub const VDS_ASYNCOUT_EXTENDLUN: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(54i32); pub const VDS_ASYNCOUT_SHRINKLUN: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(55i32); pub const VDS_ASYNCOUT_RECOVERLUN: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(56i32); pub const VDS_ASYNCOUT_LOGINTOTARGET: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(60i32); pub const VDS_ASYNCOUT_LOGOUTFROMTARGET: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(61i32); pub const VDS_ASYNCOUT_CREATETARGET: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(62i32); pub const VDS_ASYNCOUT_CREATEPORTALGROUP: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(63i32); pub const VDS_ASYNCOUT_DELETETARGET: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(64i32); pub const VDS_ASYNCOUT_ADDPORTAL: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(65i32); pub const VDS_ASYNCOUT_REMOVEPORTAL: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(66i32); pub const VDS_ASYNCOUT_DELETEPORTALGROUP: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(67i32); pub const VDS_ASYNCOUT_FORMAT: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(101i32); pub const VDS_ASYNCOUT_CREATE_VDISK: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(200i32); pub const VDS_ASYNCOUT_ATTACH_VDISK: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(201i32); pub const VDS_ASYNCOUT_COMPACT_VDISK: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(202i32); pub const VDS_ASYNCOUT_MERGE_VDISK: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(203i32); pub const VDS_ASYNCOUT_EXPAND_VDISK: VDS_ASYNC_OUTPUT_TYPE = VDS_ASYNC_OUTPUT_TYPE(204i32); impl ::core::convert::From<i32> for VDS_ASYNC_OUTPUT_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_ASYNC_OUTPUT_TYPE { type Abi = Self; } pub const VDS_ATTACH_VIRTUAL_DISK_FLAG_USE_FILE_ACL: u32 = 1u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_CONTROLLER_NOTIFICATION { pub ulEvent: VDS_NF_CONTROLLER, pub controllerId: ::windows::core::GUID, } impl VDS_CONTROLLER_NOTIFICATION {} impl ::core::default::Default for VDS_CONTROLLER_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_CONTROLLER_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_CONTROLLER_NOTIFICATION").field("ulEvent", &self.ulEvent).field("controllerId", &self.controllerId).finish() } } impl ::core::cmp::PartialEq for VDS_CONTROLLER_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.controllerId == other.controllerId } } impl ::core::cmp::Eq for VDS_CONTROLLER_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_CONTROLLER_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_CONTROLLER_PROP { pub id: ::windows::core::GUID, pub pwszFriendlyName: super::super::Foundation::PWSTR, pub pwszIdentification: super::super::Foundation::PWSTR, pub status: VDS_CONTROLLER_STATUS, pub health: VDS_HEALTH, pub sNumberOfPorts: i16, } #[cfg(feature = "Win32_Foundation")] impl VDS_CONTROLLER_PROP {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_CONTROLLER_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_CONTROLLER_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_CONTROLLER_PROP").field("id", &self.id).field("pwszFriendlyName", &self.pwszFriendlyName).field("pwszIdentification", &self.pwszIdentification).field("status", &self.status).field("health", &self.health).field("sNumberOfPorts", &self.sNumberOfPorts).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_CONTROLLER_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.pwszFriendlyName == other.pwszFriendlyName && self.pwszIdentification == other.pwszIdentification && self.status == other.status && self.health == other.health && self.sNumberOfPorts == other.sNumberOfPorts } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_CONTROLLER_PROP {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_CONTROLLER_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_CONTROLLER_STATUS(pub i32); pub const VDS_CS_UNKNOWN: VDS_CONTROLLER_STATUS = VDS_CONTROLLER_STATUS(0i32); pub const VDS_CS_ONLINE: VDS_CONTROLLER_STATUS = VDS_CONTROLLER_STATUS(1i32); pub const VDS_CS_NOT_READY: VDS_CONTROLLER_STATUS = VDS_CONTROLLER_STATUS(2i32); pub const VDS_CS_OFFLINE: VDS_CONTROLLER_STATUS = VDS_CONTROLLER_STATUS(4i32); pub const VDS_CS_FAILED: VDS_CONTROLLER_STATUS = VDS_CONTROLLER_STATUS(5i32); pub const VDS_CS_REMOVED: VDS_CONTROLLER_STATUS = VDS_CONTROLLER_STATUS(8i32); impl ::core::convert::From<i32> for VDS_CONTROLLER_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_CONTROLLER_STATUS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_DISK_NOTIFICATION { pub ulEvent: VDS_NF_DISK, pub diskId: ::windows::core::GUID, } impl VDS_DISK_NOTIFICATION {} impl ::core::default::Default for VDS_DISK_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_DISK_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_DISK_NOTIFICATION").field("ulEvent", &self.ulEvent).field("diskId", &self.diskId).finish() } } impl ::core::cmp::PartialEq for VDS_DISK_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.diskId == other.diskId } } impl ::core::cmp::Eq for VDS_DISK_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_DISK_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_DRIVE_EXTENT { pub id: ::windows::core::GUID, pub LunId: ::windows::core::GUID, pub ullSize: u64, pub bUsed: super::super::Foundation::BOOL, } #[cfg(feature = "Win32_Foundation")] impl VDS_DRIVE_EXTENT {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_DRIVE_EXTENT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_DRIVE_EXTENT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_DRIVE_EXTENT").field("id", &self.id).field("LunId", &self.LunId).field("ullSize", &self.ullSize).field("bUsed", &self.bUsed).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_DRIVE_EXTENT { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.LunId == other.LunId && self.ullSize == other.ullSize && self.bUsed == other.bUsed } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_DRIVE_EXTENT {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_DRIVE_EXTENT { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_DRIVE_FLAG(pub i32); pub const VDS_DRF_HOTSPARE: VDS_DRIVE_FLAG = VDS_DRIVE_FLAG(1i32); pub const VDS_DRF_ASSIGNED: VDS_DRIVE_FLAG = VDS_DRIVE_FLAG(2i32); pub const VDS_DRF_UNASSIGNED: VDS_DRIVE_FLAG = VDS_DRIVE_FLAG(4i32); pub const VDS_DRF_HOTSPARE_IN_USE: VDS_DRIVE_FLAG = VDS_DRIVE_FLAG(8i32); pub const VDS_DRF_HOTSPARE_STANDBY: VDS_DRIVE_FLAG = VDS_DRIVE_FLAG(16i32); impl ::core::convert::From<i32> for VDS_DRIVE_FLAG { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_DRIVE_FLAG { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_DRIVE_LETTER_NOTIFICATION { pub ulEvent: u32, pub wcLetter: u16, pub volumeId: ::windows::core::GUID, } impl VDS_DRIVE_LETTER_NOTIFICATION {} impl ::core::default::Default for VDS_DRIVE_LETTER_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_DRIVE_LETTER_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_DRIVE_LETTER_NOTIFICATION").field("ulEvent", &self.ulEvent).field("wcLetter", &self.wcLetter).field("volumeId", &self.volumeId).finish() } } impl ::core::cmp::PartialEq for VDS_DRIVE_LETTER_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.wcLetter == other.wcLetter && self.volumeId == other.volumeId } } impl ::core::cmp::Eq for VDS_DRIVE_LETTER_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_DRIVE_LETTER_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_DRIVE_NOTIFICATION { pub ulEvent: VDS_NF_DRIVE, pub driveId: ::windows::core::GUID, } impl VDS_DRIVE_NOTIFICATION {} impl ::core::default::Default for VDS_DRIVE_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_DRIVE_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_DRIVE_NOTIFICATION").field("ulEvent", &self.ulEvent).field("driveId", &self.driveId).finish() } } impl ::core::cmp::PartialEq for VDS_DRIVE_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.driveId == other.driveId } } impl ::core::cmp::Eq for VDS_DRIVE_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_DRIVE_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_DRIVE_PROP { pub id: ::windows::core::GUID, pub ullSize: u64, pub pwszFriendlyName: super::super::Foundation::PWSTR, pub pwszIdentification: super::super::Foundation::PWSTR, pub ulFlags: u32, pub status: VDS_DRIVE_STATUS, pub health: VDS_HEALTH, pub sInternalBusNumber: i16, pub sSlotNumber: i16, } #[cfg(feature = "Win32_Foundation")] impl VDS_DRIVE_PROP {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_DRIVE_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_DRIVE_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_DRIVE_PROP") .field("id", &self.id) .field("ullSize", &self.ullSize) .field("pwszFriendlyName", &self.pwszFriendlyName) .field("pwszIdentification", &self.pwszIdentification) .field("ulFlags", &self.ulFlags) .field("status", &self.status) .field("health", &self.health) .field("sInternalBusNumber", &self.sInternalBusNumber) .field("sSlotNumber", &self.sSlotNumber) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_DRIVE_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.ullSize == other.ullSize && self.pwszFriendlyName == other.pwszFriendlyName && self.pwszIdentification == other.pwszIdentification && self.ulFlags == other.ulFlags && self.status == other.status && self.health == other.health && self.sInternalBusNumber == other.sInternalBusNumber && self.sSlotNumber == other.sSlotNumber } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_DRIVE_PROP {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_DRIVE_PROP { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_DRIVE_PROP2 { pub id: ::windows::core::GUID, pub ullSize: u64, pub pwszFriendlyName: super::super::Foundation::PWSTR, pub pwszIdentification: super::super::Foundation::PWSTR, pub ulFlags: u32, pub status: VDS_DRIVE_STATUS, pub health: VDS_HEALTH, pub sInternalBusNumber: i16, pub sSlotNumber: i16, pub ulEnclosureNumber: u32, pub busType: VDS_STORAGE_BUS_TYPE, pub ulSpindleSpeed: u32, } #[cfg(feature = "Win32_Foundation")] impl VDS_DRIVE_PROP2 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_DRIVE_PROP2 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_DRIVE_PROP2 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_DRIVE_PROP2") .field("id", &self.id) .field("ullSize", &self.ullSize) .field("pwszFriendlyName", &self.pwszFriendlyName) .field("pwszIdentification", &self.pwszIdentification) .field("ulFlags", &self.ulFlags) .field("status", &self.status) .field("health", &self.health) .field("sInternalBusNumber", &self.sInternalBusNumber) .field("sSlotNumber", &self.sSlotNumber) .field("ulEnclosureNumber", &self.ulEnclosureNumber) .field("busType", &self.busType) .field("ulSpindleSpeed", &self.ulSpindleSpeed) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_DRIVE_PROP2 { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.ullSize == other.ullSize && self.pwszFriendlyName == other.pwszFriendlyName && self.pwszIdentification == other.pwszIdentification && self.ulFlags == other.ulFlags && self.status == other.status && self.health == other.health && self.sInternalBusNumber == other.sInternalBusNumber && self.sSlotNumber == other.sSlotNumber && self.ulEnclosureNumber == other.ulEnclosureNumber && self.busType == other.busType && self.ulSpindleSpeed == other.ulSpindleSpeed } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_DRIVE_PROP2 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_DRIVE_PROP2 { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_DRIVE_STATUS(pub i32); pub const VDS_DRS_UNKNOWN: VDS_DRIVE_STATUS = VDS_DRIVE_STATUS(0i32); pub const VDS_DRS_ONLINE: VDS_DRIVE_STATUS = VDS_DRIVE_STATUS(1i32); pub const VDS_DRS_NOT_READY: VDS_DRIVE_STATUS = VDS_DRIVE_STATUS(2i32); pub const VDS_DRS_OFFLINE: VDS_DRIVE_STATUS = VDS_DRIVE_STATUS(4i32); pub const VDS_DRS_FAILED: VDS_DRIVE_STATUS = VDS_DRIVE_STATUS(5i32); pub const VDS_DRS_REMOVED: VDS_DRIVE_STATUS = VDS_DRIVE_STATUS(8i32); impl ::core::convert::From<i32> for VDS_DRIVE_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_DRIVE_STATUS { type Abi = Self; } pub const VDS_E_ACCESS_DENIED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212249i32 as _); pub const VDS_E_ACTIVE_PARTITION: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212232i32 as _); pub const VDS_E_ADDRESSES_INCOMPLETELY_SET: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211517i32 as _); pub const VDS_E_ALIGN_BEYOND_FIRST_CYLINDER: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211949i32 as _); pub const VDS_E_ALIGN_IS_ZERO: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211888i32 as _); pub const VDS_E_ALIGN_NOT_A_POWER_OF_TWO: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211889i32 as _); pub const VDS_E_ALIGN_NOT_SECTOR_SIZE_MULTIPLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211948i32 as _); pub const VDS_E_ALIGN_NOT_ZERO: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211947i32 as _); pub const VDS_E_ALREADY_REGISTERED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212285i32 as _); pub const VDS_E_ANOTHER_CALL_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212284i32 as _); pub const VDS_E_ASSOCIATED_LUNS_EXIST: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211509i32 as _); pub const VDS_E_ASSOCIATED_PORTALS_EXIST: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211508i32 as _); pub const VDS_E_ASYNC_OBJECT_FAILURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212210i32 as _); pub const VDS_E_BAD_BOOT_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211898i32 as _); pub const VDS_E_BAD_COOKIE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212271i32 as _); pub const VDS_E_BAD_LABEL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212247i32 as _); pub const VDS_E_BAD_PNP_MESSAGE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212017i32 as _); pub const VDS_E_BAD_PROVIDER_DATA: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212223i32 as _); pub const VDS_E_BAD_REVISION_NUMBER: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211880i32 as _); pub const VDS_E_BLOCK_CLUSTERED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210749i32 as _); pub const VDS_E_BOOT_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211257i32 as _); pub const VDS_E_BOOT_PAGEFILE_DRIVE_LETTER: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210994i32 as _); pub const VDS_E_BOOT_PARTITION_NUMBER_CHANGE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212234i32 as _); pub const VDS_E_CACHE_CORRUPT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211946i32 as _); pub const VDS_E_CANCEL_TOO_LATE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212276i32 as _); pub const VDS_E_CANNOT_CLEAR_VOLUME_FLAG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211945i32 as _); pub const VDS_E_CANNOT_EXTEND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212274i32 as _); pub const VDS_E_CANNOT_SHRINK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212002i32 as _); pub const VDS_E_CANT_INVALIDATE_FVE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211886i32 as _); pub const VDS_E_CANT_QUICK_FORMAT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212246i32 as _); pub const VDS_E_CLEAN_WITH_BOOTBACKING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210743i32 as _); pub const VDS_E_CLEAN_WITH_CRITICAL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210990i32 as _); pub const VDS_E_CLEAN_WITH_DATA: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210992i32 as _); pub const VDS_E_CLEAN_WITH_OEM: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210991i32 as _); pub const VDS_E_CLUSTER_COUNT_BEYOND_32BITS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212240i32 as _); pub const VDS_E_CLUSTER_SIZE_TOO_BIG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212241i32 as _); pub const VDS_E_CLUSTER_SIZE_TOO_SMALL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212242i32 as _); pub const VDS_E_COMPRESSION_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210984i32 as _); pub const VDS_E_CONFIG_LIMIT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211976i32 as _); pub const VDS_E_CORRUPT_EXTENT_INFO: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212021i32 as _); pub const VDS_E_CORRUPT_NOTIFICATION_INFO: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211990i32 as _); pub const VDS_E_CORRUPT_PARTITION_INFO: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212023i32 as _); pub const VDS_E_CORRUPT_VOLUME_INFO: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212029i32 as _); pub const VDS_E_CRASHDUMP_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211250i32 as _); pub const VDS_E_CRITICAL_PLEX: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211906i32 as _); pub const VDS_E_DELETE_WITH_BOOTBACKING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210745i32 as _); pub const VDS_E_DELETE_WITH_CRITICAL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210993i32 as _); pub const VDS_E_DEVICE_IN_USE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212269i32 as _); pub const VDS_E_DISK_BEING_CLEANED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211944i32 as _); pub const VDS_E_DISK_CONFIGURATION_CORRUPTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211975i32 as _); pub const VDS_E_DISK_CONFIGURATION_NOT_IN_SYNC: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211974i32 as _); pub const VDS_E_DISK_CONFIGURATION_UPDATE_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211973i32 as _); pub const VDS_E_DISK_DYNAMIC: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211972i32 as _); pub const VDS_E_DISK_HAS_BANDS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210748i32 as _); pub const VDS_E_DISK_IN_USE_BY_VOLUME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212212i32 as _); pub const VDS_E_DISK_IO_FAILING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211968i32 as _); pub const VDS_E_DISK_IS_OFFLINE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211254i32 as _); pub const VDS_E_DISK_IS_READ_ONLY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211253i32 as _); pub const VDS_E_DISK_LAYOUT_PARTITIONS_TOO_SMALL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211969i32 as _); pub const VDS_E_DISK_NOT_CONVERTIBLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211943i32 as _); pub const VDS_E_DISK_NOT_CONVERTIBLE_SIZE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210971i32 as _); pub const VDS_E_DISK_NOT_EMPTY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212268i32 as _); pub const VDS_E_DISK_NOT_FOUND_IN_PACK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211987i32 as _); pub const VDS_E_DISK_NOT_IMPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212206i32 as _); pub const VDS_E_DISK_NOT_INITIALIZED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212265i32 as _); pub const VDS_E_DISK_NOT_LOADED_TO_CACHE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212217i32 as _); pub const VDS_E_DISK_NOT_MISSING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212031i32 as _); pub const VDS_E_DISK_NOT_OFFLINE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211883i32 as _); pub const VDS_E_DISK_NOT_ONLINE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212213i32 as _); pub const VDS_E_DISK_PNP_REG_CORRUPT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212203i32 as _); pub const VDS_E_DISK_REMOVEABLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211942i32 as _); pub const VDS_E_DISK_REMOVEABLE_NOT_EMPTY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211941i32 as _); pub const VDS_E_DISTINCT_VOLUME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211909i32 as _); pub const VDS_E_DMADMIN_CORRUPT_NOTIFICATION: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212252i32 as _); pub const VDS_E_DMADMIN_METHOD_CALL_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212256i32 as _); pub const VDS_E_DMADMIN_SERVICE_CONNECTION_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212261i32 as _); pub const VDS_E_DRIVER_INTERNAL_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212027i32 as _); pub const VDS_E_DRIVER_INVALID_PARAM: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212004i32 as _); pub const VDS_E_DRIVER_NO_PACK_NAME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212019i32 as _); pub const VDS_E_DRIVER_OBJECT_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211971i32 as _); pub const VDS_E_DRIVE_LETTER_NOT_FREE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211940i32 as _); pub const VDS_E_DUPLICATE_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211986i32 as _); pub const VDS_E_DUP_EMPTY_PACK_GUID: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212020i32 as _); pub const VDS_E_DYNAMIC_DISKS_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211967i32 as _); pub const VDS_E_EXTEND_FILE_SYSTEM_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212186i32 as _); pub const VDS_E_EXTEND_MULTIPLE_DISKS_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211939i32 as _); pub const VDS_E_EXTEND_TOO_MANY_CLUSTERS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210968i32 as _); pub const VDS_E_EXTEND_UNKNOWN_FILESYSTEM: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210967i32 as _); pub const VDS_E_EXTENT_EXCEEDS_DISK_FREE_SPACE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212011i32 as _); pub const VDS_E_EXTENT_SIZE_LESS_THAN_MIN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212237i32 as _); pub const VDS_E_FAILED_TO_OFFLINE_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211881i32 as _); pub const VDS_E_FAILED_TO_ONLINE_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211882i32 as _); pub const VDS_E_FAT32_FORMAT_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210987i32 as _); pub const VDS_E_FAT_FORMAT_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210986i32 as _); pub const VDS_E_FAULT_TOLERANT_DISKS_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211966i32 as _); pub const VDS_E_FLAG_ALREADY_SET: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211911i32 as _); pub const VDS_E_FORMAT_CRITICAL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210989i32 as _); pub const VDS_E_FORMAT_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210985i32 as _); pub const VDS_E_FORMAT_WITH_BOOTBACKING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210744i32 as _); pub const VDS_E_FS_NOT_DETERMINED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211885i32 as _); pub const VDS_E_GET_SAN_POLICY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211259i32 as _); pub const VDS_E_GPT_ATTRIBUTES_INVALID: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211965i32 as _); pub const VDS_E_HIBERNATION_FILE_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211251i32 as _); pub const VDS_E_IA64_BOOT_MIRRORED_TO_MBR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212198i32 as _); pub const VDS_E_IMPORT_SET_INCOMPLETE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212207i32 as _); pub const VDS_E_INCOMPATIBLE_FILE_SYSTEM: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212251i32 as _); pub const VDS_E_INCOMPATIBLE_MEDIA: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212250i32 as _); pub const VDS_E_INCORRECT_BOOT_VOLUME_EXTENT_INFO: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211260i32 as _); pub const VDS_E_INCORRECT_SYSTEM_VOLUME_EXTENT_INFO: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211248i32 as _); pub const VDS_E_INITIALIZED_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212287i32 as _); pub const VDS_E_INITIALIZE_NOT_CALLED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212286i32 as _); pub const VDS_E_INITIATOR_ADAPTER_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211008i32 as _); pub const VDS_E_INITIATOR_SPECIFIC_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211513i32 as _); pub const VDS_E_INTERNAL_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212216i32 as _); pub const VDS_E_INVALID_BLOCK_SIZE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211982i32 as _); pub const VDS_E_INVALID_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212007i32 as _); pub const VDS_E_INVALID_DISK_COUNT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211994i32 as _); pub const VDS_E_INVALID_DRIVE_LETTER: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211938i32 as _); pub const VDS_E_INVALID_DRIVE_LETTER_COUNT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211937i32 as _); pub const VDS_E_INVALID_ENUMERATOR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212028i32 as _); pub const VDS_E_INVALID_EXTENT_COUNT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211993i32 as _); pub const VDS_E_INVALID_FS_FLAG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211936i32 as _); pub const VDS_E_INVALID_FS_TYPE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211935i32 as _); pub const VDS_E_INVALID_IP_ADDRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210997i32 as _); pub const VDS_E_INVALID_ISCSI_PATH: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210980i32 as _); pub const VDS_E_INVALID_ISCSI_TARGET_NAME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211005i32 as _); pub const VDS_E_INVALID_MEMBER_COUNT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211998i32 as _); pub const VDS_E_INVALID_MEMBER_ORDER: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211996i32 as _); pub const VDS_E_INVALID_OBJECT_TYPE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211934i32 as _); pub const VDS_E_INVALID_OPERATION: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212267i32 as _); pub const VDS_E_INVALID_PACK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212006i32 as _); pub const VDS_E_INVALID_PARTITION_LAYOUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211933i32 as _); pub const VDS_E_INVALID_PARTITION_STYLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211932i32 as _); pub const VDS_E_INVALID_PARTITION_TYPE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211931i32 as _); pub const VDS_E_INVALID_PATH: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210981i32 as _); pub const VDS_E_INVALID_PLEX_BLOCK_SIZE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211978i32 as _); pub const VDS_E_INVALID_PLEX_COUNT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211999i32 as _); pub const VDS_E_INVALID_PLEX_GUID: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211988i32 as _); pub const VDS_E_INVALID_PLEX_ORDER: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211997i32 as _); pub const VDS_E_INVALID_PLEX_TYPE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211979i32 as _); pub const VDS_E_INVALID_PORT_PATH: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211006i32 as _); pub const VDS_E_INVALID_PROVIDER_CLSID: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211930i32 as _); pub const VDS_E_INVALID_PROVIDER_ID: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211929i32 as _); pub const VDS_E_INVALID_PROVIDER_NAME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211928i32 as _); pub const VDS_E_INVALID_PROVIDER_TYPE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211927i32 as _); pub const VDS_E_INVALID_PROVIDER_VERSION_GUID: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211926i32 as _); pub const VDS_E_INVALID_PROVIDER_VERSION_STRING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211925i32 as _); pub const VDS_E_INVALID_QUERY_PROVIDER_FLAG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211924i32 as _); pub const VDS_E_INVALID_SECTOR_SIZE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211984i32 as _); pub const VDS_E_INVALID_SERVICE_FLAG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211923i32 as _); pub const VDS_E_INVALID_SHRINK_SIZE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211241i32 as _); pub const VDS_E_INVALID_SPACE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212282i32 as _); pub const VDS_E_INVALID_STATE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210747i32 as _); pub const VDS_E_INVALID_STRIPE_SIZE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211995i32 as _); pub const VDS_E_INVALID_VOLUME_FLAG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211922i32 as _); pub const VDS_E_INVALID_VOLUME_LENGTH: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211954i32 as _); pub const VDS_E_INVALID_VOLUME_TYPE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211899i32 as _); pub const VDS_E_IO_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212245i32 as _); pub const VDS_E_ISCSI_CHAP_SECRET: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210998i32 as _); pub const VDS_E_ISCSI_GET_IKE_INFO: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211003i32 as _); pub const VDS_E_ISCSI_GROUP_PRESHARE_KEY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210999i32 as _); pub const VDS_E_ISCSI_INITIATOR_NODE_NAME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211000i32 as _); pub const VDS_E_ISCSI_LOGIN_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211512i32 as _); pub const VDS_E_ISCSI_LOGOUT_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211511i32 as _); pub const VDS_E_ISCSI_LOGOUT_INCOMPLETE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211504i32 as _); pub const VDS_E_ISCSI_SESSION_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211510i32 as _); pub const VDS_E_ISCSI_SET_IKE_INFO: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211002i32 as _); pub const VDS_E_LAST_VALID_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211985i32 as _); pub const VDS_E_LBN_REMAP_ENABLED_FLAG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212202i32 as _); pub const VDS_E_LDM_TIMEOUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212191i32 as _); pub const VDS_E_LEGACY_VOLUME_FORMAT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212230i32 as _); pub const VDS_E_LOG_UPDATE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211897i32 as _); pub const VDS_E_LUN_DISK_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211239i32 as _); pub const VDS_E_LUN_DISK_MISSING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211240i32 as _); pub const VDS_E_LUN_DISK_NOT_READY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211238i32 as _); pub const VDS_E_LUN_DISK_NO_MEDIA: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211237i32 as _); pub const VDS_E_LUN_DISK_READ_ONLY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210978i32 as _); pub const VDS_E_LUN_DYNAMIC: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210976i32 as _); pub const VDS_E_LUN_DYNAMIC_OFFLINE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210975i32 as _); pub const VDS_E_LUN_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211234i32 as _); pub const VDS_E_LUN_NOT_READY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211236i32 as _); pub const VDS_E_LUN_OFFLINE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211235i32 as _); pub const VDS_E_LUN_SHRINK_GPT_HEADER: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210974i32 as _); pub const VDS_E_LUN_UPDATE_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210977i32 as _); pub const VDS_E_MAX_USABLE_MBR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212184i32 as _); pub const VDS_E_MEDIA_WRITE_PROTECTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212248i32 as _); pub const VDS_E_MEMBER_IS_HEALTHY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211964i32 as _); pub const VDS_E_MEMBER_MISSING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211958i32 as _); pub const VDS_E_MEMBER_REGENERATING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211963i32 as _); pub const VDS_E_MEMBER_SIZE_INVALID: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212010i32 as _); pub const VDS_E_MIGRATE_OPEN_VOLUME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212228i32 as _); pub const VDS_E_MIRROR_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210973i32 as _); pub const VDS_E_MISSING_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212204i32 as _); pub const VDS_E_MULTIPLE_DISCOVERY_DOMAINS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211506i32 as _); pub const VDS_E_MULTIPLE_PACKS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212001i32 as _); pub const VDS_E_NAME_NOT_UNIQUE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211519i32 as _); pub const VDS_E_NON_CONTIGUOUS_DATA_PARTITIONS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212229i32 as _); pub const VDS_E_NOT_AN_UNALLOCATED_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212264i32 as _); pub const VDS_E_NOT_ENOUGH_DRIVE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212272i32 as _); pub const VDS_E_NOT_ENOUGH_SPACE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212273i32 as _); pub const VDS_E_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212288i32 as _); pub const VDS_E_NO_DISCOVERY_DOMAIN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211507i32 as _); pub const VDS_E_NO_DISKS_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212258i32 as _); pub const VDS_E_NO_DISK_PATHNAME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211505i32 as _); pub const VDS_E_NO_DRIVELETTER_FLAG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212201i32 as _); pub const VDS_E_NO_EXTENTS_FOR_PLEX: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211980i32 as _); pub const VDS_E_NO_EXTENTS_FOR_VOLUME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212218i32 as _); pub const VDS_E_NO_FREE_SPACE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212233i32 as _); pub const VDS_E_NO_HEALTHY_DISKS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211977i32 as _); pub const VDS_E_NO_IMPORT_TARGET: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211501i32 as _); pub const VDS_E_NO_MAINTENANCE_MODE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210750i32 as _); pub const VDS_E_NO_MEDIA: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212270i32 as _); pub const VDS_E_NO_PNP_DISK_ARRIVE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212016i32 as _); pub const VDS_E_NO_PNP_DISK_REMOVE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212014i32 as _); pub const VDS_E_NO_PNP_VOLUME_ARRIVE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212015i32 as _); pub const VDS_E_NO_PNP_VOLUME_REMOVE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212013i32 as _); pub const VDS_E_NO_POOL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210752i32 as _); pub const VDS_E_NO_POOL_CREATED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210751i32 as _); pub const VDS_E_NO_SOFTWARE_PROVIDERS_LOADED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212032i32 as _); pub const VDS_E_NO_VALID_LOG_COPIES: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211894i32 as _); pub const VDS_E_NO_VOLUME_LAYOUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212030i32 as _); pub const VDS_E_NO_VOLUME_PATHNAME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211503i32 as _); pub const VDS_E_NTFS_FORMAT_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210988i32 as _); pub const VDS_E_OBJECT_DELETED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212277i32 as _); pub const VDS_E_OBJECT_EXISTS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212259i32 as _); pub const VDS_E_OBJECT_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212283i32 as _); pub const VDS_E_OBJECT_OUT_OF_SYNC: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212205i32 as _); pub const VDS_E_OBJECT_STATUS_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212239i32 as _); pub const VDS_E_OFFLINE_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210970i32 as _); pub const VDS_E_ONE_EXTENT_PER_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211983i32 as _); pub const VDS_E_ONLINE_PACK_EXISTS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212188i32 as _); pub const VDS_E_OPERATION_CANCELED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212275i32 as _); pub const VDS_E_OPERATION_DENIED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212278i32 as _); pub const VDS_E_OPERATION_PENDING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212279i32 as _); pub const VDS_E_PACK_NAME_INVALID: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211962i32 as _); pub const VDS_E_PACK_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212208i32 as _); pub const VDS_E_PACK_OFFLINE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212220i32 as _); pub const VDS_E_PACK_ONLINE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212000i32 as _); pub const VDS_E_PAGEFILE_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211252i32 as _); pub const VDS_E_PARTITION_LDM: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211891i32 as _); pub const VDS_E_PARTITION_LIMIT_REACHED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212281i32 as _); pub const VDS_E_PARTITION_MSR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211892i32 as _); pub const VDS_E_PARTITION_NON_DATA: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211907i32 as _); pub const VDS_E_PARTITION_NOT_CYLINDER_ALIGNED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211970i32 as _); pub const VDS_E_PARTITION_NOT_EMPTY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212280i32 as _); pub const VDS_E_PARTITION_NOT_OEM: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211921i32 as _); pub const VDS_E_PARTITION_OF_UNKNOWN_TYPE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212231i32 as _); pub const VDS_E_PARTITION_PROTECTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211920i32 as _); pub const VDS_E_PARTITION_STYLE_MISMATCH: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211919i32 as _); pub const VDS_E_PATH_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212266i32 as _); pub const VDS_E_PLEX_IS_HEALTHY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211961i32 as _); pub const VDS_E_PLEX_LAST_ACTIVE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211960i32 as _); pub const VDS_E_PLEX_MISSING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211959i32 as _); pub const VDS_E_PLEX_NOT_LOADED_TO_CACHE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211893i32 as _); pub const VDS_E_PLEX_REGENERATING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211957i32 as _); pub const VDS_E_PLEX_SIZE_INVALID: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211981i32 as _); pub const VDS_E_PROVIDER_CACHE_CORRUPT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212257i32 as _); pub const VDS_E_PROVIDER_CACHE_OUTOFSYNC: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211502i32 as _); pub const VDS_E_PROVIDER_EXITING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212012i32 as _); pub const VDS_E_PROVIDER_FAILURE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212222i32 as _); pub const VDS_E_PROVIDER_INITIALIZATION_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212260i32 as _); pub const VDS_E_PROVIDER_INTERNAL_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211918i32 as _); pub const VDS_E_PROVIDER_TYPE_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212214i32 as _); pub const VDS_E_PROVIDER_VOL_DEVICE_NAME_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212254i32 as _); pub const VDS_E_PROVIDER_VOL_OPEN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212253i32 as _); pub const VDS_E_RAID5_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210972i32 as _); pub const VDS_E_READONLY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211900i32 as _); pub const VDS_E_REBOOT_REQUIRED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210996i32 as _); pub const VDS_E_REFS_FORMAT_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210746i32 as _); pub const VDS_E_REPAIR_VOLUMESTATE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212192i32 as _); pub const VDS_E_REQUIRES_CONTIGUOUS_DISK_SPACE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212224i32 as _); pub const VDS_E_RETRY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212189i32 as _); pub const VDS_E_REVERT_ON_CLOSE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212200i32 as _); pub const VDS_E_REVERT_ON_CLOSE_MISMATCH: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212190i32 as _); pub const VDS_E_REVERT_ON_CLOSE_SET: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212199i32 as _); pub const VDS_E_SECTOR_SIZE_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211229i32 as _); pub const VDS_E_SECURITY_INCOMPLETELY_SET: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211515i32 as _); pub const VDS_E_SET_SAN_POLICY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211258i32 as _); pub const VDS_E_SET_TUNNEL_MODE_OUTER_ADDRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211004i32 as _); pub const VDS_E_SHRINK_DIRTY_VOLUME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211878i32 as _); pub const VDS_E_SHRINK_EXTEND_UNALIGNED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210496i32 as _); pub const VDS_E_SHRINK_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211887i32 as _); pub const VDS_E_SHRINK_LUN_NOT_UNMASKED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210979i32 as _); pub const VDS_E_SHRINK_OVER_DATA: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211242i32 as _); pub const VDS_E_SHRINK_SIZE_LESS_THAN_MIN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211917i32 as _); pub const VDS_E_SHRINK_SIZE_TOO_BIG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211916i32 as _); pub const VDS_E_SHRINK_UNKNOWN_FILESYSTEM: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210966i32 as _); pub const VDS_E_SHRINK_USER_CANCELLED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211879i32 as _); pub const VDS_E_SOURCE_IS_TARGET_PACK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211992i32 as _); pub const VDS_E_SUBSYSTEM_ID_IS_NULL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211001i32 as _); pub const VDS_E_SYSTEM_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211247i32 as _); pub const VDS_E_TARGET_PACK_NOT_EMPTY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212003i32 as _); pub const VDS_E_TARGET_PORTAL_NOT_FOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211007i32 as _); pub const VDS_E_TARGET_SPECIFIC_NOT_SUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211514i32 as _); pub const VDS_E_TIMEOUT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212193i32 as _); pub const VDS_E_UNABLE_TO_FIND_BOOT_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211261i32 as _); pub const VDS_E_UNABLE_TO_FIND_SYSTEM_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211249i32 as _); pub const VDS_E_UNEXPECTED_DISK_LAYOUT_CHANGE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211955i32 as _); pub const VDS_E_UNRECOVERABLE_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212263i32 as _); pub const VDS_E_UNRECOVERABLE_PROVIDER_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211915i32 as _); pub const VDS_E_VDISK_INVALID_OP_STATE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210982i32 as _); pub const VDS_E_VDISK_NOT_OPEN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210983i32 as _); pub const VDS_E_VDISK_PATHNAME_INVALID: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210969i32 as _); pub const VDS_E_VD_ALREADY_ATTACHED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210956i32 as _); pub const VDS_E_VD_ALREADY_COMPACTING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210958i32 as _); pub const VDS_E_VD_ALREADY_DETACHED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210955i32 as _); pub const VDS_E_VD_ALREADY_MERGING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210957i32 as _); pub const VDS_E_VD_DISK_ALREADY_EXPANDING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210959i32 as _); pub const VDS_E_VD_DISK_ALREADY_OPEN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210960i32 as _); pub const VDS_E_VD_DISK_IS_COMPACTING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210963i32 as _); pub const VDS_E_VD_DISK_IS_EXPANDING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210964i32 as _); pub const VDS_E_VD_DISK_IS_MERGING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210962i32 as _); pub const VDS_E_VD_DISK_NOT_OPEN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210965i32 as _); pub const VDS_E_VD_IS_ATTACHED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210961i32 as _); pub const VDS_E_VD_IS_BEING_ATTACHED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210953i32 as _); pub const VDS_E_VD_IS_BEING_DETACHED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210952i32 as _); pub const VDS_E_VD_NOT_ATTACHED_READONLY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210954i32 as _); pub const VDS_E_VOLUME_DISK_COUNT_MAX_EXCEEDED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211991i32 as _); pub const VDS_E_VOLUME_EXTEND_FVE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211230i32 as _); pub const VDS_E_VOLUME_EXTEND_FVE_CORRUPT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211232i32 as _); pub const VDS_E_VOLUME_EXTEND_FVE_LOCKED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211233i32 as _); pub const VDS_E_VOLUME_EXTEND_FVE_RECOVERY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211231i32 as _); pub const VDS_E_VOLUME_GUID_PATHNAME_NOT_ALLOWED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147210995i32 as _); pub const VDS_E_VOLUME_HAS_PATH: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212194i32 as _); pub const VDS_E_VOLUME_HIDDEN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211914i32 as _); pub const VDS_E_VOLUME_INCOMPLETE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212238i32 as _); pub const VDS_E_VOLUME_INVALID_NAME: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212025i32 as _); pub const VDS_E_VOLUME_LENGTH_NOT_SECTOR_SIZE_MULTIPLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211953i32 as _); pub const VDS_E_VOLUME_MIRRORED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211896i32 as _); pub const VDS_E_VOLUME_NOT_A_MIRROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212219i32 as _); pub const VDS_E_VOLUME_NOT_FOUND_IN_PACK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211908i32 as _); pub const VDS_E_VOLUME_NOT_HEALTHY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212226i32 as _); pub const VDS_E_VOLUME_NOT_MOUNTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212209i32 as _); pub const VDS_E_VOLUME_NOT_ONLINE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212227i32 as _); pub const VDS_E_VOLUME_NOT_RETAINED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211952i32 as _); pub const VDS_E_VOLUME_ON_DISK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212005i32 as _); pub const VDS_E_VOLUME_PERMANENTLY_DISMOUNTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212195i32 as _); pub const VDS_E_VOLUME_REGENERATING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211904i32 as _); pub const VDS_E_VOLUME_RETAINED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211951i32 as _); pub const VDS_E_VOLUME_SHRINK_FVE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211243i32 as _); pub const VDS_E_VOLUME_SHRINK_FVE_CORRUPT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211245i32 as _); pub const VDS_E_VOLUME_SHRINK_FVE_LOCKED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211246i32 as _); pub const VDS_E_VOLUME_SHRINK_FVE_RECOVERY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211244i32 as _); pub const VDS_E_VOLUME_SIMPLE_SPANNED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211895i32 as _); pub const VDS_E_VOLUME_SPANS_DISKS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212225i32 as _); pub const VDS_E_VOLUME_SYNCHRONIZING: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147211905i32 as _); pub const VDS_E_VOLUME_TEMPORARILY_DISMOUNTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212196i32 as _); pub const VDS_E_VOLUME_TOO_BIG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212243i32 as _); pub const VDS_E_VOLUME_TOO_SMALL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212244i32 as _); #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_FILE_SYSTEM_NOTIFICATION { pub ulEvent: VDS_NF_FILE_SYSTEM, pub volumeId: ::windows::core::GUID, pub dwPercentCompleted: u32, } impl VDS_FILE_SYSTEM_NOTIFICATION {} impl ::core::default::Default for VDS_FILE_SYSTEM_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_FILE_SYSTEM_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_FILE_SYSTEM_NOTIFICATION").field("ulEvent", &self.ulEvent).field("volumeId", &self.volumeId).field("dwPercentCompleted", &self.dwPercentCompleted).finish() } } impl ::core::cmp::PartialEq for VDS_FILE_SYSTEM_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.volumeId == other.volumeId && self.dwPercentCompleted == other.dwPercentCompleted } } impl ::core::cmp::Eq for VDS_FILE_SYSTEM_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_FILE_SYSTEM_NOTIFICATION { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_FILE_SYSTEM_TYPE(pub i32); pub const VDS_FST_UNKNOWN: VDS_FILE_SYSTEM_TYPE = VDS_FILE_SYSTEM_TYPE(0i32); pub const VDS_FST_RAW: VDS_FILE_SYSTEM_TYPE = VDS_FILE_SYSTEM_TYPE(1i32); pub const VDS_FST_FAT: VDS_FILE_SYSTEM_TYPE = VDS_FILE_SYSTEM_TYPE(2i32); pub const VDS_FST_FAT32: VDS_FILE_SYSTEM_TYPE = VDS_FILE_SYSTEM_TYPE(3i32); pub const VDS_FST_NTFS: VDS_FILE_SYSTEM_TYPE = VDS_FILE_SYSTEM_TYPE(4i32); pub const VDS_FST_CDFS: VDS_FILE_SYSTEM_TYPE = VDS_FILE_SYSTEM_TYPE(5i32); pub const VDS_FST_UDF: VDS_FILE_SYSTEM_TYPE = VDS_FILE_SYSTEM_TYPE(6i32); pub const VDS_FST_EXFAT: VDS_FILE_SYSTEM_TYPE = VDS_FILE_SYSTEM_TYPE(7i32); pub const VDS_FST_CSVFS: VDS_FILE_SYSTEM_TYPE = VDS_FILE_SYSTEM_TYPE(8i32); pub const VDS_FST_REFS: VDS_FILE_SYSTEM_TYPE = VDS_FILE_SYSTEM_TYPE(9i32); impl ::core::convert::From<i32> for VDS_FILE_SYSTEM_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_FILE_SYSTEM_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_HBAPORT_PROP { pub id: ::windows::core::GUID, pub wwnNode: VDS_WWN, pub wwnPort: VDS_WWN, pub r#type: VDS_HBAPORT_TYPE, pub status: VDS_HBAPORT_STATUS, pub ulPortSpeed: u32, pub ulSupportedPortSpeed: u32, } impl VDS_HBAPORT_PROP {} impl ::core::default::Default for VDS_HBAPORT_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_HBAPORT_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_HBAPORT_PROP").field("id", &self.id).field("wwnNode", &self.wwnNode).field("wwnPort", &self.wwnPort).field("r#type", &self.r#type).field("status", &self.status).field("ulPortSpeed", &self.ulPortSpeed).field("ulSupportedPortSpeed", &self.ulSupportedPortSpeed).finish() } } impl ::core::cmp::PartialEq for VDS_HBAPORT_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.wwnNode == other.wwnNode && self.wwnPort == other.wwnPort && self.r#type == other.r#type && self.status == other.status && self.ulPortSpeed == other.ulPortSpeed && self.ulSupportedPortSpeed == other.ulSupportedPortSpeed } } impl ::core::cmp::Eq for VDS_HBAPORT_PROP {} unsafe impl ::windows::core::Abi for VDS_HBAPORT_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_HBAPORT_SPEED_FLAG(pub i32); pub const VDS_HSF_UNKNOWN: VDS_HBAPORT_SPEED_FLAG = VDS_HBAPORT_SPEED_FLAG(0i32); pub const VDS_HSF_1GBIT: VDS_HBAPORT_SPEED_FLAG = VDS_HBAPORT_SPEED_FLAG(1i32); pub const VDS_HSF_2GBIT: VDS_HBAPORT_SPEED_FLAG = VDS_HBAPORT_SPEED_FLAG(2i32); pub const VDS_HSF_10GBIT: VDS_HBAPORT_SPEED_FLAG = VDS_HBAPORT_SPEED_FLAG(4i32); pub const VDS_HSF_4GBIT: VDS_HBAPORT_SPEED_FLAG = VDS_HBAPORT_SPEED_FLAG(8i32); pub const VDS_HSF_NOT_NEGOTIATED: VDS_HBAPORT_SPEED_FLAG = VDS_HBAPORT_SPEED_FLAG(32768i32); impl ::core::convert::From<i32> for VDS_HBAPORT_SPEED_FLAG { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_HBAPORT_SPEED_FLAG { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_HBAPORT_STATUS(pub i32); pub const VDS_HPS_UNKNOWN: VDS_HBAPORT_STATUS = VDS_HBAPORT_STATUS(1i32); pub const VDS_HPS_ONLINE: VDS_HBAPORT_STATUS = VDS_HBAPORT_STATUS(2i32); pub const VDS_HPS_OFFLINE: VDS_HBAPORT_STATUS = VDS_HBAPORT_STATUS(3i32); pub const VDS_HPS_BYPASSED: VDS_HBAPORT_STATUS = VDS_HBAPORT_STATUS(4i32); pub const VDS_HPS_DIAGNOSTICS: VDS_HBAPORT_STATUS = VDS_HBAPORT_STATUS(5i32); pub const VDS_HPS_LINKDOWN: VDS_HBAPORT_STATUS = VDS_HBAPORT_STATUS(6i32); pub const VDS_HPS_ERROR: VDS_HBAPORT_STATUS = VDS_HBAPORT_STATUS(7i32); pub const VDS_HPS_LOOPBACK: VDS_HBAPORT_STATUS = VDS_HBAPORT_STATUS(8i32); impl ::core::convert::From<i32> for VDS_HBAPORT_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_HBAPORT_STATUS { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_HBAPORT_TYPE(pub i32); pub const VDS_HPT_UNKNOWN: VDS_HBAPORT_TYPE = VDS_HBAPORT_TYPE(1i32); pub const VDS_HPT_OTHER: VDS_HBAPORT_TYPE = VDS_HBAPORT_TYPE(2i32); pub const VDS_HPT_NOTPRESENT: VDS_HBAPORT_TYPE = VDS_HBAPORT_TYPE(3i32); pub const VDS_HPT_NPORT: VDS_HBAPORT_TYPE = VDS_HBAPORT_TYPE(5i32); pub const VDS_HPT_NLPORT: VDS_HBAPORT_TYPE = VDS_HBAPORT_TYPE(6i32); pub const VDS_HPT_FLPORT: VDS_HBAPORT_TYPE = VDS_HBAPORT_TYPE(7i32); pub const VDS_HPT_FPORT: VDS_HBAPORT_TYPE = VDS_HBAPORT_TYPE(8i32); pub const VDS_HPT_EPORT: VDS_HBAPORT_TYPE = VDS_HBAPORT_TYPE(9i32); pub const VDS_HPT_GPORT: VDS_HBAPORT_TYPE = VDS_HBAPORT_TYPE(10i32); pub const VDS_HPT_LPORT: VDS_HBAPORT_TYPE = VDS_HBAPORT_TYPE(20i32); pub const VDS_HPT_PTP: VDS_HBAPORT_TYPE = VDS_HBAPORT_TYPE(21i32); impl ::core::convert::From<i32> for VDS_HBAPORT_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_HBAPORT_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_HEALTH(pub i32); pub const VDS_H_UNKNOWN: VDS_HEALTH = VDS_HEALTH(0i32); pub const VDS_H_HEALTHY: VDS_HEALTH = VDS_HEALTH(1i32); pub const VDS_H_REBUILDING: VDS_HEALTH = VDS_HEALTH(2i32); pub const VDS_H_STALE: VDS_HEALTH = VDS_HEALTH(3i32); pub const VDS_H_FAILING: VDS_HEALTH = VDS_HEALTH(4i32); pub const VDS_H_FAILING_REDUNDANCY: VDS_HEALTH = VDS_HEALTH(5i32); pub const VDS_H_FAILED_REDUNDANCY: VDS_HEALTH = VDS_HEALTH(6i32); pub const VDS_H_FAILED_REDUNDANCY_FAILING: VDS_HEALTH = VDS_HEALTH(7i32); pub const VDS_H_FAILED: VDS_HEALTH = VDS_HEALTH(8i32); pub const VDS_H_REPLACED: VDS_HEALTH = VDS_HEALTH(9i32); pub const VDS_H_PENDING_FAILURE: VDS_HEALTH = VDS_HEALTH(10i32); pub const VDS_H_DEGRADED: VDS_HEALTH = VDS_HEALTH(11i32); impl ::core::convert::From<i32> for VDS_HEALTH { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_HEALTH { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_HINTS { pub ullHintMask: u64, pub ullExpectedMaximumSize: u64, pub ulOptimalReadSize: u32, pub ulOptimalReadAlignment: u32, pub ulOptimalWriteSize: u32, pub ulOptimalWriteAlignment: u32, pub ulMaximumDriveCount: u32, pub ulStripeSize: u32, pub bFastCrashRecoveryRequired: super::super::Foundation::BOOL, pub bMostlyReads: super::super::Foundation::BOOL, pub bOptimizeForSequentialReads: super::super::Foundation::BOOL, pub bOptimizeForSequentialWrites: super::super::Foundation::BOOL, pub bRemapEnabled: super::super::Foundation::BOOL, pub bReadBackVerifyEnabled: super::super::Foundation::BOOL, pub bWriteThroughCachingEnabled: super::super::Foundation::BOOL, pub bHardwareChecksumEnabled: super::super::Foundation::BOOL, pub bIsYankable: super::super::Foundation::BOOL, pub sRebuildPriority: i16, } #[cfg(feature = "Win32_Foundation")] impl VDS_HINTS {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_HINTS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_HINTS { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_HINTS") .field("ullHintMask", &self.ullHintMask) .field("ullExpectedMaximumSize", &self.ullExpectedMaximumSize) .field("ulOptimalReadSize", &self.ulOptimalReadSize) .field("ulOptimalReadAlignment", &self.ulOptimalReadAlignment) .field("ulOptimalWriteSize", &self.ulOptimalWriteSize) .field("ulOptimalWriteAlignment", &self.ulOptimalWriteAlignment) .field("ulMaximumDriveCount", &self.ulMaximumDriveCount) .field("ulStripeSize", &self.ulStripeSize) .field("bFastCrashRecoveryRequired", &self.bFastCrashRecoveryRequired) .field("bMostlyReads", &self.bMostlyReads) .field("bOptimizeForSequentialReads", &self.bOptimizeForSequentialReads) .field("bOptimizeForSequentialWrites", &self.bOptimizeForSequentialWrites) .field("bRemapEnabled", &self.bRemapEnabled) .field("bReadBackVerifyEnabled", &self.bReadBackVerifyEnabled) .field("bWriteThroughCachingEnabled", &self.bWriteThroughCachingEnabled) .field("bHardwareChecksumEnabled", &self.bHardwareChecksumEnabled) .field("bIsYankable", &self.bIsYankable) .field("sRebuildPriority", &self.sRebuildPriority) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_HINTS { fn eq(&self, other: &Self) -> bool { self.ullHintMask == other.ullHintMask && self.ullExpectedMaximumSize == other.ullExpectedMaximumSize && self.ulOptimalReadSize == other.ulOptimalReadSize && self.ulOptimalReadAlignment == other.ulOptimalReadAlignment && self.ulOptimalWriteSize == other.ulOptimalWriteSize && self.ulOptimalWriteAlignment == other.ulOptimalWriteAlignment && self.ulMaximumDriveCount == other.ulMaximumDriveCount && self.ulStripeSize == other.ulStripeSize && self.bFastCrashRecoveryRequired == other.bFastCrashRecoveryRequired && self.bMostlyReads == other.bMostlyReads && self.bOptimizeForSequentialReads == other.bOptimizeForSequentialReads && self.bOptimizeForSequentialWrites == other.bOptimizeForSequentialWrites && self.bRemapEnabled == other.bRemapEnabled && self.bReadBackVerifyEnabled == other.bReadBackVerifyEnabled && self.bWriteThroughCachingEnabled == other.bWriteThroughCachingEnabled && self.bHardwareChecksumEnabled == other.bHardwareChecksumEnabled && self.bIsYankable == other.bIsYankable && self.sRebuildPriority == other.sRebuildPriority } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_HINTS {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_HINTS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_HINTS2 { pub ullHintMask: u64, pub ullExpectedMaximumSize: u64, pub ulOptimalReadSize: u32, pub ulOptimalReadAlignment: u32, pub ulOptimalWriteSize: u32, pub ulOptimalWriteAlignment: u32, pub ulMaximumDriveCount: u32, pub ulStripeSize: u32, pub ulReserved1: u32, pub ulReserved2: u32, pub ulReserved3: u32, pub bFastCrashRecoveryRequired: super::super::Foundation::BOOL, pub bMostlyReads: super::super::Foundation::BOOL, pub bOptimizeForSequentialReads: super::super::Foundation::BOOL, pub bOptimizeForSequentialWrites: super::super::Foundation::BOOL, pub bRemapEnabled: super::super::Foundation::BOOL, pub bReadBackVerifyEnabled: super::super::Foundation::BOOL, pub bWriteThroughCachingEnabled: super::super::Foundation::BOOL, pub bHardwareChecksumEnabled: super::super::Foundation::BOOL, pub bIsYankable: super::super::Foundation::BOOL, pub bAllocateHotSpare: super::super::Foundation::BOOL, pub bUseMirroredCache: super::super::Foundation::BOOL, pub bReadCachingEnabled: super::super::Foundation::BOOL, pub bWriteCachingEnabled: super::super::Foundation::BOOL, pub bMediaScanEnabled: super::super::Foundation::BOOL, pub bConsistencyCheckEnabled: super::super::Foundation::BOOL, pub BusType: VDS_STORAGE_BUS_TYPE, pub bReserved1: super::super::Foundation::BOOL, pub bReserved2: super::super::Foundation::BOOL, pub bReserved3: super::super::Foundation::BOOL, pub sRebuildPriority: i16, } #[cfg(feature = "Win32_Foundation")] impl VDS_HINTS2 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_HINTS2 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_HINTS2 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_HINTS2") .field("ullHintMask", &self.ullHintMask) .field("ullExpectedMaximumSize", &self.ullExpectedMaximumSize) .field("ulOptimalReadSize", &self.ulOptimalReadSize) .field("ulOptimalReadAlignment", &self.ulOptimalReadAlignment) .field("ulOptimalWriteSize", &self.ulOptimalWriteSize) .field("ulOptimalWriteAlignment", &self.ulOptimalWriteAlignment) .field("ulMaximumDriveCount", &self.ulMaximumDriveCount) .field("ulStripeSize", &self.ulStripeSize) .field("ulReserved1", &self.ulReserved1) .field("ulReserved2", &self.ulReserved2) .field("ulReserved3", &self.ulReserved3) .field("bFastCrashRecoveryRequired", &self.bFastCrashRecoveryRequired) .field("bMostlyReads", &self.bMostlyReads) .field("bOptimizeForSequentialReads", &self.bOptimizeForSequentialReads) .field("bOptimizeForSequentialWrites", &self.bOptimizeForSequentialWrites) .field("bRemapEnabled", &self.bRemapEnabled) .field("bReadBackVerifyEnabled", &self.bReadBackVerifyEnabled) .field("bWriteThroughCachingEnabled", &self.bWriteThroughCachingEnabled) .field("bHardwareChecksumEnabled", &self.bHardwareChecksumEnabled) .field("bIsYankable", &self.bIsYankable) .field("bAllocateHotSpare", &self.bAllocateHotSpare) .field("bUseMirroredCache", &self.bUseMirroredCache) .field("bReadCachingEnabled", &self.bReadCachingEnabled) .field("bWriteCachingEnabled", &self.bWriteCachingEnabled) .field("bMediaScanEnabled", &self.bMediaScanEnabled) .field("bConsistencyCheckEnabled", &self.bConsistencyCheckEnabled) .field("BusType", &self.BusType) .field("bReserved1", &self.bReserved1) .field("bReserved2", &self.bReserved2) .field("bReserved3", &self.bReserved3) .field("sRebuildPriority", &self.sRebuildPriority) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_HINTS2 { fn eq(&self, other: &Self) -> bool { self.ullHintMask == other.ullHintMask && self.ullExpectedMaximumSize == other.ullExpectedMaximumSize && self.ulOptimalReadSize == other.ulOptimalReadSize && self.ulOptimalReadAlignment == other.ulOptimalReadAlignment && self.ulOptimalWriteSize == other.ulOptimalWriteSize && self.ulOptimalWriteAlignment == other.ulOptimalWriteAlignment && self.ulMaximumDriveCount == other.ulMaximumDriveCount && self.ulStripeSize == other.ulStripeSize && self.ulReserved1 == other.ulReserved1 && self.ulReserved2 == other.ulReserved2 && self.ulReserved3 == other.ulReserved3 && self.bFastCrashRecoveryRequired == other.bFastCrashRecoveryRequired && self.bMostlyReads == other.bMostlyReads && self.bOptimizeForSequentialReads == other.bOptimizeForSequentialReads && self.bOptimizeForSequentialWrites == other.bOptimizeForSequentialWrites && self.bRemapEnabled == other.bRemapEnabled && self.bReadBackVerifyEnabled == other.bReadBackVerifyEnabled && self.bWriteThroughCachingEnabled == other.bWriteThroughCachingEnabled && self.bHardwareChecksumEnabled == other.bHardwareChecksumEnabled && self.bIsYankable == other.bIsYankable && self.bAllocateHotSpare == other.bAllocateHotSpare && self.bUseMirroredCache == other.bUseMirroredCache && self.bReadCachingEnabled == other.bReadCachingEnabled && self.bWriteCachingEnabled == other.bWriteCachingEnabled && self.bMediaScanEnabled == other.bMediaScanEnabled && self.bConsistencyCheckEnabled == other.bConsistencyCheckEnabled && self.BusType == other.BusType && self.bReserved1 == other.bReserved1 && self.bReserved2 == other.bReserved2 && self.bReserved3 == other.bReserved3 && self.sRebuildPriority == other.sRebuildPriority } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_HINTS2 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_HINTS2 { type Abi = Self; } pub const VDS_HINT_ALLOCATEHOTSPARE: i32 = 512i32; pub const VDS_HINT_BUSTYPE: i32 = 1024i32; pub const VDS_HINT_CONSISTENCYCHECKENABLED: i32 = 32768i32; pub const VDS_HINT_FASTCRASHRECOVERYREQUIRED: i32 = 1i32; pub const VDS_HINT_HARDWARECHECKSUMENABLED: i32 = 128i32; pub const VDS_HINT_ISYANKABLE: i32 = 256i32; pub const VDS_HINT_MEDIASCANENABLED: i32 = 16384i32; pub const VDS_HINT_MOSTLYREADS: i32 = 2i32; pub const VDS_HINT_OPTIMIZEFORSEQUENTIALREADS: i32 = 4i32; pub const VDS_HINT_OPTIMIZEFORSEQUENTIALWRITES: i32 = 8i32; pub const VDS_HINT_READBACKVERIFYENABLED: i32 = 16i32; pub const VDS_HINT_READCACHINGENABLED: i32 = 4096i32; pub const VDS_HINT_REMAPENABLED: i32 = 32i32; pub const VDS_HINT_USEMIRROREDCACHE: i32 = 2048i32; pub const VDS_HINT_WRITECACHINGENABLED: i32 = 8192i32; pub const VDS_HINT_WRITETHROUGHCACHINGENABLED: i32 = 64i32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_HWPROVIDER_TYPE(pub i32); pub const VDS_HWT_UNKNOWN: VDS_HWPROVIDER_TYPE = VDS_HWPROVIDER_TYPE(0i32); pub const VDS_HWT_PCI_RAID: VDS_HWPROVIDER_TYPE = VDS_HWPROVIDER_TYPE(1i32); pub const VDS_HWT_FIBRE_CHANNEL: VDS_HWPROVIDER_TYPE = VDS_HWPROVIDER_TYPE(2i32); pub const VDS_HWT_ISCSI: VDS_HWPROVIDER_TYPE = VDS_HWPROVIDER_TYPE(3i32); pub const VDS_HWT_SAS: VDS_HWPROVIDER_TYPE = VDS_HWPROVIDER_TYPE(4i32); pub const VDS_HWT_HYBRID: VDS_HWPROVIDER_TYPE = VDS_HWPROVIDER_TYPE(5i32); impl ::core::convert::From<i32> for VDS_HWPROVIDER_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_HWPROVIDER_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_INTERCONNECT { pub m_addressType: VDS_INTERCONNECT_ADDRESS_TYPE, pub m_cbPort: u32, pub m_pbPort: *mut u8, pub m_cbAddress: u32, pub m_pbAddress: *mut u8, } impl VDS_INTERCONNECT {} impl ::core::default::Default for VDS_INTERCONNECT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_INTERCONNECT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_INTERCONNECT").field("m_addressType", &self.m_addressType).field("m_cbPort", &self.m_cbPort).field("m_pbPort", &self.m_pbPort).field("m_cbAddress", &self.m_cbAddress).field("m_pbAddress", &self.m_pbAddress).finish() } } impl ::core::cmp::PartialEq for VDS_INTERCONNECT { fn eq(&self, other: &Self) -> bool { self.m_addressType == other.m_addressType && self.m_cbPort == other.m_cbPort && self.m_pbPort == other.m_pbPort && self.m_cbAddress == other.m_cbAddress && self.m_pbAddress == other.m_pbAddress } } impl ::core::cmp::Eq for VDS_INTERCONNECT {} unsafe impl ::windows::core::Abi for VDS_INTERCONNECT { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_INTERCONNECT_ADDRESS_TYPE(pub i32); pub const VDS_IA_UNKNOWN: VDS_INTERCONNECT_ADDRESS_TYPE = VDS_INTERCONNECT_ADDRESS_TYPE(0i32); pub const VDS_IA_FCFS: VDS_INTERCONNECT_ADDRESS_TYPE = VDS_INTERCONNECT_ADDRESS_TYPE(1i32); pub const VDS_IA_FCPH: VDS_INTERCONNECT_ADDRESS_TYPE = VDS_INTERCONNECT_ADDRESS_TYPE(2i32); pub const VDS_IA_FCPH3: VDS_INTERCONNECT_ADDRESS_TYPE = VDS_INTERCONNECT_ADDRESS_TYPE(3i32); pub const VDS_IA_MAC: VDS_INTERCONNECT_ADDRESS_TYPE = VDS_INTERCONNECT_ADDRESS_TYPE(4i32); pub const VDS_IA_SCSI: VDS_INTERCONNECT_ADDRESS_TYPE = VDS_INTERCONNECT_ADDRESS_TYPE(5i32); impl ::core::convert::From<i32> for VDS_INTERCONNECT_ADDRESS_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_INTERCONNECT_ADDRESS_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_INTERCONNECT_FLAG(pub i32); pub const VDS_ITF_PCI_RAID: VDS_INTERCONNECT_FLAG = VDS_INTERCONNECT_FLAG(1i32); pub const VDS_ITF_FIBRE_CHANNEL: VDS_INTERCONNECT_FLAG = VDS_INTERCONNECT_FLAG(2i32); pub const VDS_ITF_ISCSI: VDS_INTERCONNECT_FLAG = VDS_INTERCONNECT_FLAG(4i32); pub const VDS_ITF_SAS: VDS_INTERCONNECT_FLAG = VDS_INTERCONNECT_FLAG(8i32); impl ::core::convert::From<i32> for VDS_INTERCONNECT_FLAG { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_INTERCONNECT_FLAG { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_IPADDRESS { pub r#type: VDS_IPADDRESS_TYPE, pub ipv4Address: u32, pub ipv6Address: [u8; 16], pub ulIpv6FlowInfo: u32, pub ulIpv6ScopeId: u32, pub wszTextAddress: [u16; 257], pub ulPort: u32, } impl VDS_IPADDRESS {} impl ::core::default::Default for VDS_IPADDRESS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_IPADDRESS { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_IPADDRESS") .field("r#type", &self.r#type) .field("ipv4Address", &self.ipv4Address) .field("ipv6Address", &self.ipv6Address) .field("ulIpv6FlowInfo", &self.ulIpv6FlowInfo) .field("ulIpv6ScopeId", &self.ulIpv6ScopeId) .field("wszTextAddress", &self.wszTextAddress) .field("ulPort", &self.ulPort) .finish() } } impl ::core::cmp::PartialEq for VDS_IPADDRESS { fn eq(&self, other: &Self) -> bool { self.r#type == other.r#type && self.ipv4Address == other.ipv4Address && self.ipv6Address == other.ipv6Address && self.ulIpv6FlowInfo == other.ulIpv6FlowInfo && self.ulIpv6ScopeId == other.ulIpv6ScopeId && self.wszTextAddress == other.wszTextAddress && self.ulPort == other.ulPort } } impl ::core::cmp::Eq for VDS_IPADDRESS {} unsafe impl ::windows::core::Abi for VDS_IPADDRESS { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_IPADDRESS_TYPE(pub i32); pub const VDS_IPT_TEXT: VDS_IPADDRESS_TYPE = VDS_IPADDRESS_TYPE(0i32); pub const VDS_IPT_IPV4: VDS_IPADDRESS_TYPE = VDS_IPADDRESS_TYPE(1i32); pub const VDS_IPT_IPV6: VDS_IPADDRESS_TYPE = VDS_IPADDRESS_TYPE(2i32); pub const VDS_IPT_EMPTY: VDS_IPADDRESS_TYPE = VDS_IPADDRESS_TYPE(3i32); impl ::core::convert::From<i32> for VDS_IPADDRESS_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_IPADDRESS_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_ISCSI_AUTH_TYPE(pub i32); pub const VDS_IAT_NONE: VDS_ISCSI_AUTH_TYPE = VDS_ISCSI_AUTH_TYPE(0i32); pub const VDS_IAT_CHAP: VDS_ISCSI_AUTH_TYPE = VDS_ISCSI_AUTH_TYPE(1i32); pub const VDS_IAT_MUTUAL_CHAP: VDS_ISCSI_AUTH_TYPE = VDS_ISCSI_AUTH_TYPE(2i32); impl ::core::convert::From<i32> for VDS_ISCSI_AUTH_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_ISCSI_AUTH_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_ISCSI_INITIATOR_ADAPTER_PROP { pub id: ::windows::core::GUID, pub pwszName: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl VDS_ISCSI_INITIATOR_ADAPTER_PROP {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_ISCSI_INITIATOR_ADAPTER_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_ISCSI_INITIATOR_ADAPTER_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_ISCSI_INITIATOR_ADAPTER_PROP").field("id", &self.id).field("pwszName", &self.pwszName).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_ISCSI_INITIATOR_ADAPTER_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.pwszName == other.pwszName } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_ISCSI_INITIATOR_ADAPTER_PROP {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_ISCSI_INITIATOR_ADAPTER_PROP { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_ISCSI_INITIATOR_PORTAL_PROP { pub id: ::windows::core::GUID, pub address: VDS_IPADDRESS, pub ulPortIndex: u32, } impl VDS_ISCSI_INITIATOR_PORTAL_PROP {} impl ::core::default::Default for VDS_ISCSI_INITIATOR_PORTAL_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ISCSI_INITIATOR_PORTAL_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_ISCSI_INITIATOR_PORTAL_PROP").field("id", &self.id).field("address", &self.address).field("ulPortIndex", &self.ulPortIndex).finish() } } impl ::core::cmp::PartialEq for VDS_ISCSI_INITIATOR_PORTAL_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.address == other.address && self.ulPortIndex == other.ulPortIndex } } impl ::core::cmp::Eq for VDS_ISCSI_INITIATOR_PORTAL_PROP {} unsafe impl ::windows::core::Abi for VDS_ISCSI_INITIATOR_PORTAL_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_ISCSI_IPSEC_FLAG(pub i32); pub const VDS_IIF_VALID: VDS_ISCSI_IPSEC_FLAG = VDS_ISCSI_IPSEC_FLAG(1i32); pub const VDS_IIF_IKE: VDS_ISCSI_IPSEC_FLAG = VDS_ISCSI_IPSEC_FLAG(2i32); pub const VDS_IIF_MAIN_MODE: VDS_ISCSI_IPSEC_FLAG = VDS_ISCSI_IPSEC_FLAG(4i32); pub const VDS_IIF_AGGRESSIVE_MODE: VDS_ISCSI_IPSEC_FLAG = VDS_ISCSI_IPSEC_FLAG(8i32); pub const VDS_IIF_PFS_ENABLE: VDS_ISCSI_IPSEC_FLAG = VDS_ISCSI_IPSEC_FLAG(16i32); pub const VDS_IIF_TRANSPORT_MODE_PREFERRED: VDS_ISCSI_IPSEC_FLAG = VDS_ISCSI_IPSEC_FLAG(32i32); pub const VDS_IIF_TUNNEL_MODE_PREFERRED: VDS_ISCSI_IPSEC_FLAG = VDS_ISCSI_IPSEC_FLAG(64i32); impl ::core::convert::From<i32> for VDS_ISCSI_IPSEC_FLAG { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_ISCSI_IPSEC_FLAG { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_ISCSI_IPSEC_KEY { pub pKey: *mut u8, pub ulKeySize: u32, } impl VDS_ISCSI_IPSEC_KEY {} impl ::core::default::Default for VDS_ISCSI_IPSEC_KEY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ISCSI_IPSEC_KEY { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_ISCSI_IPSEC_KEY").field("pKey", &self.pKey).field("ulKeySize", &self.ulKeySize).finish() } } impl ::core::cmp::PartialEq for VDS_ISCSI_IPSEC_KEY { fn eq(&self, other: &Self) -> bool { self.pKey == other.pKey && self.ulKeySize == other.ulKeySize } } impl ::core::cmp::Eq for VDS_ISCSI_IPSEC_KEY {} unsafe impl ::windows::core::Abi for VDS_ISCSI_IPSEC_KEY { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_ISCSI_LOGIN_FLAG(pub i32); pub const VDS_ILF_REQUIRE_IPSEC: VDS_ISCSI_LOGIN_FLAG = VDS_ISCSI_LOGIN_FLAG(1i32); pub const VDS_ILF_MULTIPATH_ENABLED: VDS_ISCSI_LOGIN_FLAG = VDS_ISCSI_LOGIN_FLAG(2i32); impl ::core::convert::From<i32> for VDS_ISCSI_LOGIN_FLAG { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_ISCSI_LOGIN_FLAG { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_ISCSI_LOGIN_TYPE(pub i32); pub const VDS_ILT_MANUAL: VDS_ISCSI_LOGIN_TYPE = VDS_ISCSI_LOGIN_TYPE(0i32); pub const VDS_ILT_PERSISTENT: VDS_ISCSI_LOGIN_TYPE = VDS_ISCSI_LOGIN_TYPE(1i32); pub const VDS_ILT_BOOT: VDS_ISCSI_LOGIN_TYPE = VDS_ISCSI_LOGIN_TYPE(2i32); impl ::core::convert::From<i32> for VDS_ISCSI_LOGIN_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_ISCSI_LOGIN_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_ISCSI_PORTALGROUP_PROP { pub id: ::windows::core::GUID, pub tag: u16, } impl VDS_ISCSI_PORTALGROUP_PROP {} impl ::core::default::Default for VDS_ISCSI_PORTALGROUP_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ISCSI_PORTALGROUP_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_ISCSI_PORTALGROUP_PROP").field("id", &self.id).field("tag", &self.tag).finish() } } impl ::core::cmp::PartialEq for VDS_ISCSI_PORTALGROUP_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.tag == other.tag } } impl ::core::cmp::Eq for VDS_ISCSI_PORTALGROUP_PROP {} unsafe impl ::windows::core::Abi for VDS_ISCSI_PORTALGROUP_PROP { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_ISCSI_PORTAL_PROP { pub id: ::windows::core::GUID, pub address: VDS_IPADDRESS, pub status: VDS_ISCSI_PORTAL_STATUS, } impl VDS_ISCSI_PORTAL_PROP {} impl ::core::default::Default for VDS_ISCSI_PORTAL_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ISCSI_PORTAL_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_ISCSI_PORTAL_PROP").field("id", &self.id).field("address", &self.address).field("status", &self.status).finish() } } impl ::core::cmp::PartialEq for VDS_ISCSI_PORTAL_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.address == other.address && self.status == other.status } } impl ::core::cmp::Eq for VDS_ISCSI_PORTAL_PROP {} unsafe impl ::windows::core::Abi for VDS_ISCSI_PORTAL_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_ISCSI_PORTAL_STATUS(pub i32); pub const VDS_IPS_UNKNOWN: VDS_ISCSI_PORTAL_STATUS = VDS_ISCSI_PORTAL_STATUS(0i32); pub const VDS_IPS_ONLINE: VDS_ISCSI_PORTAL_STATUS = VDS_ISCSI_PORTAL_STATUS(1i32); pub const VDS_IPS_NOT_READY: VDS_ISCSI_PORTAL_STATUS = VDS_ISCSI_PORTAL_STATUS(2i32); pub const VDS_IPS_OFFLINE: VDS_ISCSI_PORTAL_STATUS = VDS_ISCSI_PORTAL_STATUS(4i32); pub const VDS_IPS_FAILED: VDS_ISCSI_PORTAL_STATUS = VDS_ISCSI_PORTAL_STATUS(5i32); impl ::core::convert::From<i32> for VDS_ISCSI_PORTAL_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_ISCSI_PORTAL_STATUS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_ISCSI_SHARED_SECRET { pub pSharedSecret: *mut u8, pub ulSharedSecretSize: u32, } impl VDS_ISCSI_SHARED_SECRET {} impl ::core::default::Default for VDS_ISCSI_SHARED_SECRET { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_ISCSI_SHARED_SECRET { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_ISCSI_SHARED_SECRET").field("pSharedSecret", &self.pSharedSecret).field("ulSharedSecretSize", &self.ulSharedSecretSize).finish() } } impl ::core::cmp::PartialEq for VDS_ISCSI_SHARED_SECRET { fn eq(&self, other: &Self) -> bool { self.pSharedSecret == other.pSharedSecret && self.ulSharedSecretSize == other.ulSharedSecretSize } } impl ::core::cmp::Eq for VDS_ISCSI_SHARED_SECRET {} unsafe impl ::windows::core::Abi for VDS_ISCSI_SHARED_SECRET { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_ISCSI_TARGET_PROP { pub id: ::windows::core::GUID, pub pwszIscsiName: super::super::Foundation::PWSTR, pub pwszFriendlyName: super::super::Foundation::PWSTR, pub bChapEnabled: super::super::Foundation::BOOL, } #[cfg(feature = "Win32_Foundation")] impl VDS_ISCSI_TARGET_PROP {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_ISCSI_TARGET_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_ISCSI_TARGET_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_ISCSI_TARGET_PROP").field("id", &self.id).field("pwszIscsiName", &self.pwszIscsiName).field("pwszFriendlyName", &self.pwszFriendlyName).field("bChapEnabled", &self.bChapEnabled).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_ISCSI_TARGET_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.pwszIscsiName == other.pwszIscsiName && self.pwszFriendlyName == other.pwszFriendlyName && self.bChapEnabled == other.bChapEnabled } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_ISCSI_TARGET_PROP {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_ISCSI_TARGET_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_LOADBALANCE_POLICY_ENUM(pub i32); pub const VDS_LBP_UNKNOWN: VDS_LOADBALANCE_POLICY_ENUM = VDS_LOADBALANCE_POLICY_ENUM(0i32); pub const VDS_LBP_FAILOVER: VDS_LOADBALANCE_POLICY_ENUM = VDS_LOADBALANCE_POLICY_ENUM(1i32); pub const VDS_LBP_ROUND_ROBIN: VDS_LOADBALANCE_POLICY_ENUM = VDS_LOADBALANCE_POLICY_ENUM(2i32); pub const VDS_LBP_ROUND_ROBIN_WITH_SUBSET: VDS_LOADBALANCE_POLICY_ENUM = VDS_LOADBALANCE_POLICY_ENUM(3i32); pub const VDS_LBP_DYN_LEAST_QUEUE_DEPTH: VDS_LOADBALANCE_POLICY_ENUM = VDS_LOADBALANCE_POLICY_ENUM(4i32); pub const VDS_LBP_WEIGHTED_PATHS: VDS_LOADBALANCE_POLICY_ENUM = VDS_LOADBALANCE_POLICY_ENUM(5i32); pub const VDS_LBP_LEAST_BLOCKS: VDS_LOADBALANCE_POLICY_ENUM = VDS_LOADBALANCE_POLICY_ENUM(6i32); pub const VDS_LBP_VENDOR_SPECIFIC: VDS_LOADBALANCE_POLICY_ENUM = VDS_LOADBALANCE_POLICY_ENUM(7i32); impl ::core::convert::From<i32> for VDS_LOADBALANCE_POLICY_ENUM { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_LOADBALANCE_POLICY_ENUM { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_LUN_FLAG(pub i32); pub const VDS_LF_LBN_REMAP_ENABLED: VDS_LUN_FLAG = VDS_LUN_FLAG(1i32); pub const VDS_LF_READ_BACK_VERIFY_ENABLED: VDS_LUN_FLAG = VDS_LUN_FLAG(2i32); pub const VDS_LF_WRITE_THROUGH_CACHING_ENABLED: VDS_LUN_FLAG = VDS_LUN_FLAG(4i32); pub const VDS_LF_HARDWARE_CHECKSUM_ENABLED: VDS_LUN_FLAG = VDS_LUN_FLAG(8i32); pub const VDS_LF_READ_CACHE_ENABLED: VDS_LUN_FLAG = VDS_LUN_FLAG(16i32); pub const VDS_LF_WRITE_CACHE_ENABLED: VDS_LUN_FLAG = VDS_LUN_FLAG(32i32); pub const VDS_LF_MEDIA_SCAN_ENABLED: VDS_LUN_FLAG = VDS_LUN_FLAG(64i32); pub const VDS_LF_CONSISTENCY_CHECK_ENABLED: VDS_LUN_FLAG = VDS_LUN_FLAG(128i32); pub const VDS_LF_SNAPSHOT: VDS_LUN_FLAG = VDS_LUN_FLAG(256i32); impl ::core::convert::From<i32> for VDS_LUN_FLAG { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_LUN_FLAG { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_LUN_INFORMATION { pub m_version: u32, pub m_DeviceType: u8, pub m_DeviceTypeModifier: u8, pub m_bCommandQueueing: super::super::Foundation::BOOL, pub m_BusType: VDS_STORAGE_BUS_TYPE, pub m_szVendorId: *mut u8, pub m_szProductId: *mut u8, pub m_szProductRevision: *mut u8, pub m_szSerialNumber: *mut u8, pub m_diskSignature: ::windows::core::GUID, pub m_deviceIdDescriptor: VDS_STORAGE_DEVICE_ID_DESCRIPTOR, pub m_cInterconnects: u32, pub m_rgInterconnects: *mut VDS_INTERCONNECT, } #[cfg(feature = "Win32_Foundation")] impl VDS_LUN_INFORMATION {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_LUN_INFORMATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_LUN_INFORMATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_LUN_INFORMATION") .field("m_version", &self.m_version) .field("m_DeviceType", &self.m_DeviceType) .field("m_DeviceTypeModifier", &self.m_DeviceTypeModifier) .field("m_bCommandQueueing", &self.m_bCommandQueueing) .field("m_BusType", &self.m_BusType) .field("m_szVendorId", &self.m_szVendorId) .field("m_szProductId", &self.m_szProductId) .field("m_szProductRevision", &self.m_szProductRevision) .field("m_szSerialNumber", &self.m_szSerialNumber) .field("m_diskSignature", &self.m_diskSignature) .field("m_deviceIdDescriptor", &self.m_deviceIdDescriptor) .field("m_cInterconnects", &self.m_cInterconnects) .field("m_rgInterconnects", &self.m_rgInterconnects) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_LUN_INFORMATION { fn eq(&self, other: &Self) -> bool { self.m_version == other.m_version && self.m_DeviceType == other.m_DeviceType && self.m_DeviceTypeModifier == other.m_DeviceTypeModifier && self.m_bCommandQueueing == other.m_bCommandQueueing && self.m_BusType == other.m_BusType && self.m_szVendorId == other.m_szVendorId && self.m_szProductId == other.m_szProductId && self.m_szProductRevision == other.m_szProductRevision && self.m_szSerialNumber == other.m_szSerialNumber && self.m_diskSignature == other.m_diskSignature && self.m_deviceIdDescriptor == other.m_deviceIdDescriptor && self.m_cInterconnects == other.m_cInterconnects && self.m_rgInterconnects == other.m_rgInterconnects } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_LUN_INFORMATION {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_LUN_INFORMATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_LUN_NOTIFICATION { pub ulEvent: VDS_NF_LUN, pub LunId: ::windows::core::GUID, } impl VDS_LUN_NOTIFICATION {} impl ::core::default::Default for VDS_LUN_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_LUN_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_LUN_NOTIFICATION").field("ulEvent", &self.ulEvent).field("LunId", &self.LunId).finish() } } impl ::core::cmp::PartialEq for VDS_LUN_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.LunId == other.LunId } } impl ::core::cmp::Eq for VDS_LUN_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_LUN_NOTIFICATION { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_LUN_PLEX_FLAG(pub i32); pub const VDS_LPF_LBN_REMAP_ENABLED: VDS_LUN_PLEX_FLAG = VDS_LUN_PLEX_FLAG(1i32); impl ::core::convert::From<i32> for VDS_LUN_PLEX_FLAG { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_LUN_PLEX_FLAG { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_LUN_PLEX_PROP { pub id: ::windows::core::GUID, pub ullSize: u64, pub r#type: VDS_LUN_PLEX_TYPE, pub status: VDS_LUN_PLEX_STATUS, pub health: VDS_HEALTH, pub TransitionState: VDS_TRANSITION_STATE, pub ulFlags: u32, pub ulStripeSize: u32, pub sRebuildPriority: i16, } impl VDS_LUN_PLEX_PROP {} impl ::core::default::Default for VDS_LUN_PLEX_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_LUN_PLEX_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_LUN_PLEX_PROP") .field("id", &self.id) .field("ullSize", &self.ullSize) .field("r#type", &self.r#type) .field("status", &self.status) .field("health", &self.health) .field("TransitionState", &self.TransitionState) .field("ulFlags", &self.ulFlags) .field("ulStripeSize", &self.ulStripeSize) .field("sRebuildPriority", &self.sRebuildPriority) .finish() } } impl ::core::cmp::PartialEq for VDS_LUN_PLEX_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.ullSize == other.ullSize && self.r#type == other.r#type && self.status == other.status && self.health == other.health && self.TransitionState == other.TransitionState && self.ulFlags == other.ulFlags && self.ulStripeSize == other.ulStripeSize && self.sRebuildPriority == other.sRebuildPriority } } impl ::core::cmp::Eq for VDS_LUN_PLEX_PROP {} unsafe impl ::windows::core::Abi for VDS_LUN_PLEX_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_LUN_PLEX_STATUS(pub i32); pub const VDS_LPS_UNKNOWN: VDS_LUN_PLEX_STATUS = VDS_LUN_PLEX_STATUS(0i32); pub const VDS_LPS_ONLINE: VDS_LUN_PLEX_STATUS = VDS_LUN_PLEX_STATUS(1i32); pub const VDS_LPS_NOT_READY: VDS_LUN_PLEX_STATUS = VDS_LUN_PLEX_STATUS(2i32); pub const VDS_LPS_OFFLINE: VDS_LUN_PLEX_STATUS = VDS_LUN_PLEX_STATUS(4i32); pub const VDS_LPS_FAILED: VDS_LUN_PLEX_STATUS = VDS_LUN_PLEX_STATUS(5i32); impl ::core::convert::From<i32> for VDS_LUN_PLEX_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_LUN_PLEX_STATUS { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_LUN_PLEX_TYPE(pub i32); pub const VDS_LPT_UNKNOWN: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(0i32); pub const VDS_LPT_SIMPLE: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(10i32); pub const VDS_LPT_SPAN: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(11i32); pub const VDS_LPT_STRIPE: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(12i32); pub const VDS_LPT_PARITY: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(14i32); pub const VDS_LPT_RAID2: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(15i32); pub const VDS_LPT_RAID3: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(16i32); pub const VDS_LPT_RAID4: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(17i32); pub const VDS_LPT_RAID5: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(18i32); pub const VDS_LPT_RAID6: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(19i32); pub const VDS_LPT_RAID03: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(21i32); pub const VDS_LPT_RAID05: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(22i32); pub const VDS_LPT_RAID10: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(23i32); pub const VDS_LPT_RAID15: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(24i32); pub const VDS_LPT_RAID30: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(25i32); pub const VDS_LPT_RAID50: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(26i32); pub const VDS_LPT_RAID53: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(28i32); pub const VDS_LPT_RAID60: VDS_LUN_PLEX_TYPE = VDS_LUN_PLEX_TYPE(29i32); impl ::core::convert::From<i32> for VDS_LUN_PLEX_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_LUN_PLEX_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_LUN_PROP { pub id: ::windows::core::GUID, pub ullSize: u64, pub pwszFriendlyName: super::super::Foundation::PWSTR, pub pwszIdentification: super::super::Foundation::PWSTR, pub pwszUnmaskingList: super::super::Foundation::PWSTR, pub ulFlags: u32, pub r#type: VDS_LUN_TYPE, pub status: VDS_LUN_STATUS, pub health: VDS_HEALTH, pub TransitionState: VDS_TRANSITION_STATE, pub sRebuildPriority: i16, } #[cfg(feature = "Win32_Foundation")] impl VDS_LUN_PROP {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_LUN_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_LUN_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_LUN_PROP") .field("id", &self.id) .field("ullSize", &self.ullSize) .field("pwszFriendlyName", &self.pwszFriendlyName) .field("pwszIdentification", &self.pwszIdentification) .field("pwszUnmaskingList", &self.pwszUnmaskingList) .field("ulFlags", &self.ulFlags) .field("r#type", &self.r#type) .field("status", &self.status) .field("health", &self.health) .field("TransitionState", &self.TransitionState) .field("sRebuildPriority", &self.sRebuildPriority) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_LUN_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.ullSize == other.ullSize && self.pwszFriendlyName == other.pwszFriendlyName && self.pwszIdentification == other.pwszIdentification && self.pwszUnmaskingList == other.pwszUnmaskingList && self.ulFlags == other.ulFlags && self.r#type == other.r#type && self.status == other.status && self.health == other.health && self.TransitionState == other.TransitionState && self.sRebuildPriority == other.sRebuildPriority } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_LUN_PROP {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_LUN_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_LUN_STATUS(pub i32); pub const VDS_LS_UNKNOWN: VDS_LUN_STATUS = VDS_LUN_STATUS(0i32); pub const VDS_LS_ONLINE: VDS_LUN_STATUS = VDS_LUN_STATUS(1i32); pub const VDS_LS_NOT_READY: VDS_LUN_STATUS = VDS_LUN_STATUS(2i32); pub const VDS_LS_OFFLINE: VDS_LUN_STATUS = VDS_LUN_STATUS(4i32); pub const VDS_LS_FAILED: VDS_LUN_STATUS = VDS_LUN_STATUS(5i32); impl ::core::convert::From<i32> for VDS_LUN_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_LUN_STATUS { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_LUN_TYPE(pub i32); pub const VDS_LT_UNKNOWN: VDS_LUN_TYPE = VDS_LUN_TYPE(0i32); pub const VDS_LT_DEFAULT: VDS_LUN_TYPE = VDS_LUN_TYPE(1i32); pub const VDS_LT_FAULT_TOLERANT: VDS_LUN_TYPE = VDS_LUN_TYPE(2i32); pub const VDS_LT_NON_FAULT_TOLERANT: VDS_LUN_TYPE = VDS_LUN_TYPE(3i32); pub const VDS_LT_SIMPLE: VDS_LUN_TYPE = VDS_LUN_TYPE(10i32); pub const VDS_LT_SPAN: VDS_LUN_TYPE = VDS_LUN_TYPE(11i32); pub const VDS_LT_STRIPE: VDS_LUN_TYPE = VDS_LUN_TYPE(12i32); pub const VDS_LT_MIRROR: VDS_LUN_TYPE = VDS_LUN_TYPE(13i32); pub const VDS_LT_PARITY: VDS_LUN_TYPE = VDS_LUN_TYPE(14i32); pub const VDS_LT_RAID2: VDS_LUN_TYPE = VDS_LUN_TYPE(15i32); pub const VDS_LT_RAID3: VDS_LUN_TYPE = VDS_LUN_TYPE(16i32); pub const VDS_LT_RAID4: VDS_LUN_TYPE = VDS_LUN_TYPE(17i32); pub const VDS_LT_RAID5: VDS_LUN_TYPE = VDS_LUN_TYPE(18i32); pub const VDS_LT_RAID6: VDS_LUN_TYPE = VDS_LUN_TYPE(19i32); pub const VDS_LT_RAID01: VDS_LUN_TYPE = VDS_LUN_TYPE(20i32); pub const VDS_LT_RAID03: VDS_LUN_TYPE = VDS_LUN_TYPE(21i32); pub const VDS_LT_RAID05: VDS_LUN_TYPE = VDS_LUN_TYPE(22i32); pub const VDS_LT_RAID10: VDS_LUN_TYPE = VDS_LUN_TYPE(23i32); pub const VDS_LT_RAID15: VDS_LUN_TYPE = VDS_LUN_TYPE(24i32); pub const VDS_LT_RAID30: VDS_LUN_TYPE = VDS_LUN_TYPE(25i32); pub const VDS_LT_RAID50: VDS_LUN_TYPE = VDS_LUN_TYPE(26i32); pub const VDS_LT_RAID51: VDS_LUN_TYPE = VDS_LUN_TYPE(27i32); pub const VDS_LT_RAID53: VDS_LUN_TYPE = VDS_LUN_TYPE(28i32); pub const VDS_LT_RAID60: VDS_LUN_TYPE = VDS_LUN_TYPE(29i32); pub const VDS_LT_RAID61: VDS_LUN_TYPE = VDS_LUN_TYPE(30i32); impl ::core::convert::From<i32> for VDS_LUN_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_LUN_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_MAINTENANCE_OPERATION(pub i32); pub const BlinkLight: VDS_MAINTENANCE_OPERATION = VDS_MAINTENANCE_OPERATION(1i32); pub const BeepAlarm: VDS_MAINTENANCE_OPERATION = VDS_MAINTENANCE_OPERATION(2i32); pub const SpinDown: VDS_MAINTENANCE_OPERATION = VDS_MAINTENANCE_OPERATION(3i32); pub const SpinUp: VDS_MAINTENANCE_OPERATION = VDS_MAINTENANCE_OPERATION(4i32); pub const Ping: VDS_MAINTENANCE_OPERATION = VDS_MAINTENANCE_OPERATION(5i32); impl ::core::convert::From<i32> for VDS_MAINTENANCE_OPERATION { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_MAINTENANCE_OPERATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_MOUNT_POINT_NOTIFICATION { pub ulEvent: u32, pub volumeId: ::windows::core::GUID, } impl VDS_MOUNT_POINT_NOTIFICATION {} impl ::core::default::Default for VDS_MOUNT_POINT_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_MOUNT_POINT_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_MOUNT_POINT_NOTIFICATION").field("ulEvent", &self.ulEvent).field("volumeId", &self.volumeId).finish() } } impl ::core::cmp::PartialEq for VDS_MOUNT_POINT_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.volumeId == other.volumeId } } impl ::core::cmp::Eq for VDS_MOUNT_POINT_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_MOUNT_POINT_NOTIFICATION { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_NF_CONTROLLER(pub u32); pub const VDS_NF_CONTROLLER_ARRIVE: VDS_NF_CONTROLLER = VDS_NF_CONTROLLER(103u32); pub const VDS_NF_CONTROLLER_DEPART: VDS_NF_CONTROLLER = VDS_NF_CONTROLLER(104u32); pub const VDS_NF_CONTROLLER_MODIFY: VDS_NF_CONTROLLER = VDS_NF_CONTROLLER(350u32); pub const VDS_NF_CONTROLLER_REMOVED: VDS_NF_CONTROLLER = VDS_NF_CONTROLLER(351u32); impl ::core::convert::From<u32> for VDS_NF_CONTROLLER { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_NF_CONTROLLER { type Abi = Self; } impl ::core::ops::BitOr for VDS_NF_CONTROLLER { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for VDS_NF_CONTROLLER { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for VDS_NF_CONTROLLER { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for VDS_NF_CONTROLLER { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for VDS_NF_CONTROLLER { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_NF_DISK(pub u32); pub const VDS_NF_DISK_ARRIVE: VDS_NF_DISK = VDS_NF_DISK(8u32); pub const VDS_NF_DISK_DEPART: VDS_NF_DISK = VDS_NF_DISK(9u32); pub const VDS_NF_DISK_MODIFY: VDS_NF_DISK = VDS_NF_DISK(10u32); impl ::core::convert::From<u32> for VDS_NF_DISK { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_NF_DISK { type Abi = Self; } impl ::core::ops::BitOr for VDS_NF_DISK { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for VDS_NF_DISK { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for VDS_NF_DISK { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for VDS_NF_DISK { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for VDS_NF_DISK { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_NF_DRIVE(pub u32); pub const VDS_NF_DRIVE_ARRIVE: VDS_NF_DRIVE = VDS_NF_DRIVE(105u32); pub const VDS_NF_DRIVE_DEPART: VDS_NF_DRIVE = VDS_NF_DRIVE(106u32); pub const VDS_NF_DRIVE_MODIFY: VDS_NF_DRIVE = VDS_NF_DRIVE(107u32); pub const VDS_NF_DRIVE_REMOVED: VDS_NF_DRIVE = VDS_NF_DRIVE(354u32); impl ::core::convert::From<u32> for VDS_NF_DRIVE { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_NF_DRIVE { type Abi = Self; } impl ::core::ops::BitOr for VDS_NF_DRIVE { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for VDS_NF_DRIVE { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for VDS_NF_DRIVE { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for VDS_NF_DRIVE { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for VDS_NF_DRIVE { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } pub const VDS_NF_DRIVE_LETTER_ASSIGN: u32 = 202u32; pub const VDS_NF_DRIVE_LETTER_FREE: u32 = 201u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_NF_FILE_SYSTEM(pub u32); pub const VDS_NF_FILE_SYSTEM_MODIFY: VDS_NF_FILE_SYSTEM = VDS_NF_FILE_SYSTEM(203u32); pub const VDS_NF_FILE_SYSTEM_FORMAT_PROGRESS: VDS_NF_FILE_SYSTEM = VDS_NF_FILE_SYSTEM(204u32); impl ::core::convert::From<u32> for VDS_NF_FILE_SYSTEM { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_NF_FILE_SYSTEM { type Abi = Self; } impl ::core::ops::BitOr for VDS_NF_FILE_SYSTEM { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for VDS_NF_FILE_SYSTEM { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for VDS_NF_FILE_SYSTEM { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for VDS_NF_FILE_SYSTEM { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for VDS_NF_FILE_SYSTEM { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } pub const VDS_NF_FILE_SYSTEM_SHRINKING_PROGRESS: u32 = 206u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_NF_LUN(pub u32); pub const VDS_NF_LUN_ARRIVE: VDS_NF_LUN = VDS_NF_LUN(108u32); pub const VDS_NF_LUN_DEPART: VDS_NF_LUN = VDS_NF_LUN(109u32); pub const VDS_NF_LUN_MODIFY: VDS_NF_LUN = VDS_NF_LUN(110u32); impl ::core::convert::From<u32> for VDS_NF_LUN { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_NF_LUN { type Abi = Self; } impl ::core::ops::BitOr for VDS_NF_LUN { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for VDS_NF_LUN { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for VDS_NF_LUN { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for VDS_NF_LUN { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for VDS_NF_LUN { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } pub const VDS_NF_MOUNT_POINTS_CHANGE: u32 = 205u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_NF_PACK(pub u32); pub const VDS_NF_PACK_ARRIVE: VDS_NF_PACK = VDS_NF_PACK(1u32); pub const VDS_NF_PACK_DEPART: VDS_NF_PACK = VDS_NF_PACK(2u32); pub const VDS_NF_PACK_MODIFY: VDS_NF_PACK = VDS_NF_PACK(3u32); impl ::core::convert::From<u32> for VDS_NF_PACK { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_NF_PACK { type Abi = Self; } impl ::core::ops::BitOr for VDS_NF_PACK { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for VDS_NF_PACK { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for VDS_NF_PACK { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for VDS_NF_PACK { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for VDS_NF_PACK { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } pub const VDS_NF_PARTITION_ARRIVE: u32 = 11u32; pub const VDS_NF_PARTITION_DEPART: u32 = 12u32; pub const VDS_NF_PARTITION_MODIFY: u32 = 13u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_NF_PORT(pub u32); pub const VDS_NF_PORT_ARRIVE: VDS_NF_PORT = VDS_NF_PORT(121u32); pub const VDS_NF_PORT_DEPART: VDS_NF_PORT = VDS_NF_PORT(122u32); pub const VDS_NF_PORT_MODIFY: VDS_NF_PORT = VDS_NF_PORT(352u32); pub const VDS_NF_PORT_REMOVED: VDS_NF_PORT = VDS_NF_PORT(353u32); impl ::core::convert::From<u32> for VDS_NF_PORT { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_NF_PORT { type Abi = Self; } impl ::core::ops::BitOr for VDS_NF_PORT { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for VDS_NF_PORT { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for VDS_NF_PORT { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for VDS_NF_PORT { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for VDS_NF_PORT { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } pub const VDS_NF_PORTAL_ARRIVE: u32 = 123u32; pub const VDS_NF_PORTAL_DEPART: u32 = 124u32; pub const VDS_NF_PORTAL_GROUP_ARRIVE: u32 = 129u32; pub const VDS_NF_PORTAL_GROUP_DEPART: u32 = 130u32; pub const VDS_NF_PORTAL_GROUP_MODIFY: u32 = 131u32; pub const VDS_NF_PORTAL_MODIFY: u32 = 125u32; pub const VDS_NF_SERVICE_OUT_OF_SYNC: u32 = 301u32; pub const VDS_NF_SUB_SYSTEM_ARRIVE: u32 = 101u32; pub const VDS_NF_SUB_SYSTEM_DEPART: u32 = 102u32; pub const VDS_NF_SUB_SYSTEM_MODIFY: u32 = 151u32; pub const VDS_NF_TARGET_ARRIVE: u32 = 126u32; pub const VDS_NF_TARGET_DEPART: u32 = 127u32; pub const VDS_NF_TARGET_MODIFY: u32 = 128u32; pub const VDS_NF_VOLUME_ARRIVE: u32 = 4u32; pub const VDS_NF_VOLUME_DEPART: u32 = 5u32; pub const VDS_NF_VOLUME_MODIFY: u32 = 6u32; pub const VDS_NF_VOLUME_REBUILDING_PROGRESS: u32 = 7u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_NOTIFICATION { pub objectType: VDS_NOTIFICATION_TARGET_TYPE, pub Anonymous: VDS_NOTIFICATION_0, } impl VDS_NOTIFICATION {} impl ::core::default::Default for VDS_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VDS_NOTIFICATION { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VDS_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub union VDS_NOTIFICATION_0 { pub Pack: VDS_PACK_NOTIFICATION, pub Disk: VDS_DISK_NOTIFICATION, pub Volume: VDS_VOLUME_NOTIFICATION, pub Partition: VDS_PARTITION_NOTIFICATION, pub Letter: VDS_DRIVE_LETTER_NOTIFICATION, pub FileSystem: VDS_FILE_SYSTEM_NOTIFICATION, pub MountPoint: VDS_MOUNT_POINT_NOTIFICATION, pub SubSystem: VDS_SUB_SYSTEM_NOTIFICATION, pub Controller: VDS_CONTROLLER_NOTIFICATION, pub Drive: VDS_DRIVE_NOTIFICATION, pub Lun: VDS_LUN_NOTIFICATION, pub Port: VDS_PORT_NOTIFICATION, pub Portal: VDS_PORTAL_NOTIFICATION, pub Target: VDS_TARGET_NOTIFICATION, pub PortalGroup: VDS_PORTAL_GROUP_NOTIFICATION, pub Service: VDS_SERVICE_NOTIFICATION, } impl VDS_NOTIFICATION_0 {} impl ::core::default::Default for VDS_NOTIFICATION_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VDS_NOTIFICATION_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VDS_NOTIFICATION_0 {} unsafe impl ::windows::core::Abi for VDS_NOTIFICATION_0 { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_NOTIFICATION_TARGET_TYPE(pub i32); pub const VDS_NTT_UNKNOWN: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(0i32); pub const VDS_NTT_PACK: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(10i32); pub const VDS_NTT_VOLUME: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(11i32); pub const VDS_NTT_DISK: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(13i32); pub const VDS_NTT_PARTITION: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(60i32); pub const VDS_NTT_DRIVE_LETTER: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(61i32); pub const VDS_NTT_FILE_SYSTEM: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(62i32); pub const VDS_NTT_MOUNT_POINT: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(63i32); pub const VDS_NTT_SUB_SYSTEM: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(30i32); pub const VDS_NTT_CONTROLLER: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(31i32); pub const VDS_NTT_DRIVE: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(32i32); pub const VDS_NTT_LUN: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(33i32); pub const VDS_NTT_PORT: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(35i32); pub const VDS_NTT_PORTAL: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(36i32); pub const VDS_NTT_TARGET: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(37i32); pub const VDS_NTT_PORTAL_GROUP: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(38i32); pub const VDS_NTT_SERVICE: VDS_NOTIFICATION_TARGET_TYPE = VDS_NOTIFICATION_TARGET_TYPE(200i32); impl ::core::convert::From<i32> for VDS_NOTIFICATION_TARGET_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_NOTIFICATION_TARGET_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_OBJECT_TYPE(pub i32); pub const VDS_OT_UNKNOWN: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(0i32); pub const VDS_OT_PROVIDER: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(1i32); pub const VDS_OT_PACK: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(10i32); pub const VDS_OT_VOLUME: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(11i32); pub const VDS_OT_VOLUME_PLEX: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(12i32); pub const VDS_OT_DISK: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(13i32); pub const VDS_OT_SUB_SYSTEM: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(30i32); pub const VDS_OT_CONTROLLER: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(31i32); pub const VDS_OT_DRIVE: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(32i32); pub const VDS_OT_LUN: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(33i32); pub const VDS_OT_LUN_PLEX: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(34i32); pub const VDS_OT_PORT: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(35i32); pub const VDS_OT_PORTAL: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(36i32); pub const VDS_OT_TARGET: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(37i32); pub const VDS_OT_PORTAL_GROUP: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(38i32); pub const VDS_OT_STORAGE_POOL: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(39i32); pub const VDS_OT_HBAPORT: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(90i32); pub const VDS_OT_INIT_ADAPTER: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(91i32); pub const VDS_OT_INIT_PORTAL: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(92i32); pub const VDS_OT_ASYNC: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(100i32); pub const VDS_OT_ENUM: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(101i32); pub const VDS_OT_VDISK: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(200i32); pub const VDS_OT_OPEN_VDISK: VDS_OBJECT_TYPE = VDS_OBJECT_TYPE(201i32); impl ::core::convert::From<i32> for VDS_OBJECT_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_OBJECT_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_PACK_NOTIFICATION { pub ulEvent: VDS_NF_PACK, pub packId: ::windows::core::GUID, } impl VDS_PACK_NOTIFICATION {} impl ::core::default::Default for VDS_PACK_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_PACK_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_PACK_NOTIFICATION").field("ulEvent", &self.ulEvent).field("packId", &self.packId).finish() } } impl ::core::cmp::PartialEq for VDS_PACK_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.packId == other.packId } } impl ::core::cmp::Eq for VDS_PACK_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_PACK_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_PARTITION_NOTIFICATION { pub ulEvent: u32, pub diskId: ::windows::core::GUID, pub ullOffset: u64, } impl VDS_PARTITION_NOTIFICATION {} impl ::core::default::Default for VDS_PARTITION_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_PARTITION_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_PARTITION_NOTIFICATION").field("ulEvent", &self.ulEvent).field("diskId", &self.diskId).field("ullOffset", &self.ullOffset).finish() } } impl ::core::cmp::PartialEq for VDS_PARTITION_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.diskId == other.diskId && self.ullOffset == other.ullOffset } } impl ::core::cmp::Eq for VDS_PARTITION_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_PARTITION_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_PATH_ID { pub ullSourceId: u64, pub ullPathId: u64, } impl VDS_PATH_ID {} impl ::core::default::Default for VDS_PATH_ID { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_PATH_ID { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_PATH_ID").field("ullSourceId", &self.ullSourceId).field("ullPathId", &self.ullPathId).finish() } } impl ::core::cmp::PartialEq for VDS_PATH_ID { fn eq(&self, other: &Self) -> bool { self.ullSourceId == other.ullSourceId && self.ullPathId == other.ullPathId } } impl ::core::cmp::Eq for VDS_PATH_ID {} unsafe impl ::windows::core::Abi for VDS_PATH_ID { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_PATH_INFO { pub pathId: VDS_PATH_ID, pub r#type: VDS_HWPROVIDER_TYPE, pub status: VDS_PATH_STATUS, pub Anonymous1: VDS_PATH_INFO_0, pub Anonymous2: VDS_PATH_INFO_1, pub Anonymous3: VDS_PATH_INFO_2, } impl VDS_PATH_INFO {} impl ::core::default::Default for VDS_PATH_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VDS_PATH_INFO { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VDS_PATH_INFO {} unsafe impl ::windows::core::Abi for VDS_PATH_INFO { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub union VDS_PATH_INFO_0 { pub controllerPortId: ::windows::core::GUID, pub targetPortalId: ::windows::core::GUID, } impl VDS_PATH_INFO_0 {} impl ::core::default::Default for VDS_PATH_INFO_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VDS_PATH_INFO_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VDS_PATH_INFO_0 {} unsafe impl ::windows::core::Abi for VDS_PATH_INFO_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub union VDS_PATH_INFO_1 { pub hbaPortId: ::windows::core::GUID, pub initiatorAdapterId: ::windows::core::GUID, } impl VDS_PATH_INFO_1 {} impl ::core::default::Default for VDS_PATH_INFO_1 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VDS_PATH_INFO_1 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VDS_PATH_INFO_1 {} unsafe impl ::windows::core::Abi for VDS_PATH_INFO_1 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub union VDS_PATH_INFO_2 { pub pHbaPortProp: *mut VDS_HBAPORT_PROP, pub pInitiatorPortalIpAddr: *mut VDS_IPADDRESS, } impl VDS_PATH_INFO_2 {} impl ::core::default::Default for VDS_PATH_INFO_2 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VDS_PATH_INFO_2 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VDS_PATH_INFO_2 {} unsafe impl ::windows::core::Abi for VDS_PATH_INFO_2 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_PATH_POLICY { pub pathId: VDS_PATH_ID, pub bPrimaryPath: super::super::Foundation::BOOL, pub ulWeight: u32, } #[cfg(feature = "Win32_Foundation")] impl VDS_PATH_POLICY {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_PATH_POLICY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_PATH_POLICY { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_PATH_POLICY").field("pathId", &self.pathId).field("bPrimaryPath", &self.bPrimaryPath).field("ulWeight", &self.ulWeight).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_PATH_POLICY { fn eq(&self, other: &Self) -> bool { self.pathId == other.pathId && self.bPrimaryPath == other.bPrimaryPath && self.ulWeight == other.ulWeight } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_PATH_POLICY {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_PATH_POLICY { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_PATH_STATUS(pub i32); pub const VDS_MPS_UNKNOWN: VDS_PATH_STATUS = VDS_PATH_STATUS(0i32); pub const VDS_MPS_ONLINE: VDS_PATH_STATUS = VDS_PATH_STATUS(1i32); pub const VDS_MPS_FAILED: VDS_PATH_STATUS = VDS_PATH_STATUS(5i32); pub const VDS_MPS_STANDBY: VDS_PATH_STATUS = VDS_PATH_STATUS(7i32); impl ::core::convert::From<i32> for VDS_PATH_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_PATH_STATUS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_POOL_ATTRIBUTES { pub ullAttributeMask: u64, pub raidType: VDS_RAID_TYPE, pub busType: VDS_STORAGE_BUS_TYPE, pub pwszIntendedUsage: super::super::Foundation::PWSTR, pub bSpinDown: super::super::Foundation::BOOL, pub bIsThinProvisioned: super::super::Foundation::BOOL, pub ullProvisionedSpace: u64, pub bNoSinglePointOfFailure: super::super::Foundation::BOOL, pub ulDataRedundancyMax: u32, pub ulDataRedundancyMin: u32, pub ulDataRedundancyDefault: u32, pub ulPackageRedundancyMax: u32, pub ulPackageRedundancyMin: u32, pub ulPackageRedundancyDefault: u32, pub ulStripeSize: u32, pub ulStripeSizeMax: u32, pub ulStripeSizeMin: u32, pub ulDefaultStripeSize: u32, pub ulNumberOfColumns: u32, pub ulNumberOfColumnsMax: u32, pub ulNumberOfColumnsMin: u32, pub ulDefaultNumberofColumns: u32, pub ulDataAvailabilityHint: u32, pub ulAccessRandomnessHint: u32, pub ulAccessDirectionHint: u32, pub ulAccessSizeHint: u32, pub ulAccessLatencyHint: u32, pub ulAccessBandwidthWeightHint: u32, pub ulStorageCostHint: u32, pub ulStorageEfficiencyHint: u32, pub ulNumOfCustomAttributes: u32, pub pPoolCustomAttributes: *mut VDS_POOL_CUSTOM_ATTRIBUTES, pub bReserved1: super::super::Foundation::BOOL, pub bReserved2: super::super::Foundation::BOOL, pub ulReserved1: u32, pub ulReserved2: u32, pub ullReserved1: u64, pub ullReserved2: u64, } #[cfg(feature = "Win32_Foundation")] impl VDS_POOL_ATTRIBUTES {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_POOL_ATTRIBUTES { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_POOL_ATTRIBUTES { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_POOL_ATTRIBUTES") .field("ullAttributeMask", &self.ullAttributeMask) .field("raidType", &self.raidType) .field("busType", &self.busType) .field("pwszIntendedUsage", &self.pwszIntendedUsage) .field("bSpinDown", &self.bSpinDown) .field("bIsThinProvisioned", &self.bIsThinProvisioned) .field("ullProvisionedSpace", &self.ullProvisionedSpace) .field("bNoSinglePointOfFailure", &self.bNoSinglePointOfFailure) .field("ulDataRedundancyMax", &self.ulDataRedundancyMax) .field("ulDataRedundancyMin", &self.ulDataRedundancyMin) .field("ulDataRedundancyDefault", &self.ulDataRedundancyDefault) .field("ulPackageRedundancyMax", &self.ulPackageRedundancyMax) .field("ulPackageRedundancyMin", &self.ulPackageRedundancyMin) .field("ulPackageRedundancyDefault", &self.ulPackageRedundancyDefault) .field("ulStripeSize", &self.ulStripeSize) .field("ulStripeSizeMax", &self.ulStripeSizeMax) .field("ulStripeSizeMin", &self.ulStripeSizeMin) .field("ulDefaultStripeSize", &self.ulDefaultStripeSize) .field("ulNumberOfColumns", &self.ulNumberOfColumns) .field("ulNumberOfColumnsMax", &self.ulNumberOfColumnsMax) .field("ulNumberOfColumnsMin", &self.ulNumberOfColumnsMin) .field("ulDefaultNumberofColumns", &self.ulDefaultNumberofColumns) .field("ulDataAvailabilityHint", &self.ulDataAvailabilityHint) .field("ulAccessRandomnessHint", &self.ulAccessRandomnessHint) .field("ulAccessDirectionHint", &self.ulAccessDirectionHint) .field("ulAccessSizeHint", &self.ulAccessSizeHint) .field("ulAccessLatencyHint", &self.ulAccessLatencyHint) .field("ulAccessBandwidthWeightHint", &self.ulAccessBandwidthWeightHint) .field("ulStorageCostHint", &self.ulStorageCostHint) .field("ulStorageEfficiencyHint", &self.ulStorageEfficiencyHint) .field("ulNumOfCustomAttributes", &self.ulNumOfCustomAttributes) .field("pPoolCustomAttributes", &self.pPoolCustomAttributes) .field("bReserved1", &self.bReserved1) .field("bReserved2", &self.bReserved2) .field("ulReserved1", &self.ulReserved1) .field("ulReserved2", &self.ulReserved2) .field("ullReserved1", &self.ullReserved1) .field("ullReserved2", &self.ullReserved2) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_POOL_ATTRIBUTES { fn eq(&self, other: &Self) -> bool { self.ullAttributeMask == other.ullAttributeMask && self.raidType == other.raidType && self.busType == other.busType && self.pwszIntendedUsage == other.pwszIntendedUsage && self.bSpinDown == other.bSpinDown && self.bIsThinProvisioned == other.bIsThinProvisioned && self.ullProvisionedSpace == other.ullProvisionedSpace && self.bNoSinglePointOfFailure == other.bNoSinglePointOfFailure && self.ulDataRedundancyMax == other.ulDataRedundancyMax && self.ulDataRedundancyMin == other.ulDataRedundancyMin && self.ulDataRedundancyDefault == other.ulDataRedundancyDefault && self.ulPackageRedundancyMax == other.ulPackageRedundancyMax && self.ulPackageRedundancyMin == other.ulPackageRedundancyMin && self.ulPackageRedundancyDefault == other.ulPackageRedundancyDefault && self.ulStripeSize == other.ulStripeSize && self.ulStripeSizeMax == other.ulStripeSizeMax && self.ulStripeSizeMin == other.ulStripeSizeMin && self.ulDefaultStripeSize == other.ulDefaultStripeSize && self.ulNumberOfColumns == other.ulNumberOfColumns && self.ulNumberOfColumnsMax == other.ulNumberOfColumnsMax && self.ulNumberOfColumnsMin == other.ulNumberOfColumnsMin && self.ulDefaultNumberofColumns == other.ulDefaultNumberofColumns && self.ulDataAvailabilityHint == other.ulDataAvailabilityHint && self.ulAccessRandomnessHint == other.ulAccessRandomnessHint && self.ulAccessDirectionHint == other.ulAccessDirectionHint && self.ulAccessSizeHint == other.ulAccessSizeHint && self.ulAccessLatencyHint == other.ulAccessLatencyHint && self.ulAccessBandwidthWeightHint == other.ulAccessBandwidthWeightHint && self.ulStorageCostHint == other.ulStorageCostHint && self.ulStorageEfficiencyHint == other.ulStorageEfficiencyHint && self.ulNumOfCustomAttributes == other.ulNumOfCustomAttributes && self.pPoolCustomAttributes == other.pPoolCustomAttributes && self.bReserved1 == other.bReserved1 && self.bReserved2 == other.bReserved2 && self.ulReserved1 == other.ulReserved1 && self.ulReserved2 == other.ulReserved2 && self.ullReserved1 == other.ullReserved1 && self.ullReserved2 == other.ullReserved2 } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_POOL_ATTRIBUTES {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_POOL_ATTRIBUTES { type Abi = Self; } pub const VDS_POOL_ATTRIB_ACCS_BDW_WT_HINT: i32 = 16777216i32; pub const VDS_POOL_ATTRIB_ACCS_DIR_HINT: i32 = 2097152i32; pub const VDS_POOL_ATTRIB_ACCS_LTNCY_HINT: i32 = 8388608i32; pub const VDS_POOL_ATTRIB_ACCS_RNDM_HINT: i32 = 1048576i32; pub const VDS_POOL_ATTRIB_ACCS_SIZE_HINT: i32 = 4194304i32; pub const VDS_POOL_ATTRIB_ALLOW_SPINDOWN: i32 = 4i32; pub const VDS_POOL_ATTRIB_BUSTYPE: i32 = 2i32; pub const VDS_POOL_ATTRIB_CUSTOM_ATTRIB: i32 = 134217728i32; pub const VDS_POOL_ATTRIB_DATA_AVL_HINT: i32 = 524288i32; pub const VDS_POOL_ATTRIB_DATA_RDNCY_DEF: i32 = 128i32; pub const VDS_POOL_ATTRIB_DATA_RDNCY_MAX: i32 = 32i32; pub const VDS_POOL_ATTRIB_DATA_RDNCY_MIN: i32 = 64i32; pub const VDS_POOL_ATTRIB_NO_SINGLE_POF: i32 = 16i32; pub const VDS_POOL_ATTRIB_NUM_CLMNS: i32 = 32768i32; pub const VDS_POOL_ATTRIB_NUM_CLMNS_DEF: i32 = 262144i32; pub const VDS_POOL_ATTRIB_NUM_CLMNS_MAX: i32 = 65536i32; pub const VDS_POOL_ATTRIB_NUM_CLMNS_MIN: i32 = 131072i32; pub const VDS_POOL_ATTRIB_PKG_RDNCY_DEF: i32 = 1024i32; pub const VDS_POOL_ATTRIB_PKG_RDNCY_MAX: i32 = 256i32; pub const VDS_POOL_ATTRIB_PKG_RDNCY_MIN: i32 = 512i32; pub const VDS_POOL_ATTRIB_RAIDTYPE: i32 = 1i32; pub const VDS_POOL_ATTRIB_STOR_COST_HINT: i32 = 33554432i32; pub const VDS_POOL_ATTRIB_STOR_EFFCY_HINT: i32 = 67108864i32; pub const VDS_POOL_ATTRIB_STRIPE_SIZE: i32 = 2048i32; pub const VDS_POOL_ATTRIB_STRIPE_SIZE_DEF: i32 = 16384i32; pub const VDS_POOL_ATTRIB_STRIPE_SIZE_MAX: i32 = 4096i32; pub const VDS_POOL_ATTRIB_STRIPE_SIZE_MIN: i32 = 8192i32; pub const VDS_POOL_ATTRIB_THIN_PROVISION: i32 = 8i32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_POOL_CUSTOM_ATTRIBUTES { pub pwszName: super::super::Foundation::PWSTR, pub pwszValue: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl VDS_POOL_CUSTOM_ATTRIBUTES {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_POOL_CUSTOM_ATTRIBUTES { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_POOL_CUSTOM_ATTRIBUTES { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_POOL_CUSTOM_ATTRIBUTES").field("pwszName", &self.pwszName).field("pwszValue", &self.pwszValue).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_POOL_CUSTOM_ATTRIBUTES { fn eq(&self, other: &Self) -> bool { self.pwszName == other.pwszName && self.pwszValue == other.pwszValue } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_POOL_CUSTOM_ATTRIBUTES {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_POOL_CUSTOM_ATTRIBUTES { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_PORTAL_GROUP_NOTIFICATION { pub ulEvent: u32, pub portalGroupId: ::windows::core::GUID, } impl VDS_PORTAL_GROUP_NOTIFICATION {} impl ::core::default::Default for VDS_PORTAL_GROUP_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_PORTAL_GROUP_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_PORTAL_GROUP_NOTIFICATION").field("ulEvent", &self.ulEvent).field("portalGroupId", &self.portalGroupId).finish() } } impl ::core::cmp::PartialEq for VDS_PORTAL_GROUP_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.portalGroupId == other.portalGroupId } } impl ::core::cmp::Eq for VDS_PORTAL_GROUP_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_PORTAL_GROUP_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_PORTAL_NOTIFICATION { pub ulEvent: u32, pub portalId: ::windows::core::GUID, } impl VDS_PORTAL_NOTIFICATION {} impl ::core::default::Default for VDS_PORTAL_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_PORTAL_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_PORTAL_NOTIFICATION").field("ulEvent", &self.ulEvent).field("portalId", &self.portalId).finish() } } impl ::core::cmp::PartialEq for VDS_PORTAL_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.portalId == other.portalId } } impl ::core::cmp::Eq for VDS_PORTAL_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_PORTAL_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_PORT_NOTIFICATION { pub ulEvent: VDS_NF_PORT, pub portId: ::windows::core::GUID, } impl VDS_PORT_NOTIFICATION {} impl ::core::default::Default for VDS_PORT_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_PORT_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_PORT_NOTIFICATION").field("ulEvent", &self.ulEvent).field("portId", &self.portId).finish() } } impl ::core::cmp::PartialEq for VDS_PORT_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.portId == other.portId } } impl ::core::cmp::Eq for VDS_PORT_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_PORT_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_PORT_PROP { pub id: ::windows::core::GUID, pub pwszFriendlyName: super::super::Foundation::PWSTR, pub pwszIdentification: super::super::Foundation::PWSTR, pub status: VDS_PORT_STATUS, } #[cfg(feature = "Win32_Foundation")] impl VDS_PORT_PROP {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_PORT_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_PORT_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_PORT_PROP").field("id", &self.id).field("pwszFriendlyName", &self.pwszFriendlyName).field("pwszIdentification", &self.pwszIdentification).field("status", &self.status).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_PORT_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.pwszFriendlyName == other.pwszFriendlyName && self.pwszIdentification == other.pwszIdentification && self.status == other.status } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_PORT_PROP {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_PORT_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_PORT_STATUS(pub i32); pub const VDS_PRS_UNKNOWN: VDS_PORT_STATUS = VDS_PORT_STATUS(0i32); pub const VDS_PRS_ONLINE: VDS_PORT_STATUS = VDS_PORT_STATUS(1i32); pub const VDS_PRS_NOT_READY: VDS_PORT_STATUS = VDS_PORT_STATUS(2i32); pub const VDS_PRS_OFFLINE: VDS_PORT_STATUS = VDS_PORT_STATUS(4i32); pub const VDS_PRS_FAILED: VDS_PORT_STATUS = VDS_PORT_STATUS(5i32); pub const VDS_PRS_REMOVED: VDS_PORT_STATUS = VDS_PORT_STATUS(8i32); impl ::core::convert::From<i32> for VDS_PORT_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_PORT_STATUS { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_PROVIDER_FLAG(pub i32); pub const VDS_PF_DYNAMIC: VDS_PROVIDER_FLAG = VDS_PROVIDER_FLAG(1i32); pub const VDS_PF_INTERNAL_HARDWARE_PROVIDER: VDS_PROVIDER_FLAG = VDS_PROVIDER_FLAG(2i32); pub const VDS_PF_ONE_DISK_ONLY_PER_PACK: VDS_PROVIDER_FLAG = VDS_PROVIDER_FLAG(4i32); pub const VDS_PF_ONE_PACK_ONLINE_ONLY: VDS_PROVIDER_FLAG = VDS_PROVIDER_FLAG(8i32); pub const VDS_PF_VOLUME_SPACE_MUST_BE_CONTIGUOUS: VDS_PROVIDER_FLAG = VDS_PROVIDER_FLAG(16i32); pub const VDS_PF_SUPPORT_DYNAMIC: VDS_PROVIDER_FLAG = VDS_PROVIDER_FLAG(-2147483648i32); pub const VDS_PF_SUPPORT_FAULT_TOLERANT: VDS_PROVIDER_FLAG = VDS_PROVIDER_FLAG(1073741824i32); pub const VDS_PF_SUPPORT_DYNAMIC_1394: VDS_PROVIDER_FLAG = VDS_PROVIDER_FLAG(536870912i32); pub const VDS_PF_SUPPORT_MIRROR: VDS_PROVIDER_FLAG = VDS_PROVIDER_FLAG(32i32); pub const VDS_PF_SUPPORT_RAID5: VDS_PROVIDER_FLAG = VDS_PROVIDER_FLAG(64i32); impl ::core::convert::From<i32> for VDS_PROVIDER_FLAG { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_PROVIDER_FLAG { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_PROVIDER_LBSUPPORT_FLAG(pub i32); pub const VDS_LBF_FAILOVER: VDS_PROVIDER_LBSUPPORT_FLAG = VDS_PROVIDER_LBSUPPORT_FLAG(1i32); pub const VDS_LBF_ROUND_ROBIN: VDS_PROVIDER_LBSUPPORT_FLAG = VDS_PROVIDER_LBSUPPORT_FLAG(2i32); pub const VDS_LBF_ROUND_ROBIN_WITH_SUBSET: VDS_PROVIDER_LBSUPPORT_FLAG = VDS_PROVIDER_LBSUPPORT_FLAG(4i32); pub const VDS_LBF_DYN_LEAST_QUEUE_DEPTH: VDS_PROVIDER_LBSUPPORT_FLAG = VDS_PROVIDER_LBSUPPORT_FLAG(8i32); pub const VDS_LBF_WEIGHTED_PATHS: VDS_PROVIDER_LBSUPPORT_FLAG = VDS_PROVIDER_LBSUPPORT_FLAG(16i32); pub const VDS_LBF_LEAST_BLOCKS: VDS_PROVIDER_LBSUPPORT_FLAG = VDS_PROVIDER_LBSUPPORT_FLAG(32i32); pub const VDS_LBF_VENDOR_SPECIFIC: VDS_PROVIDER_LBSUPPORT_FLAG = VDS_PROVIDER_LBSUPPORT_FLAG(64i32); impl ::core::convert::From<i32> for VDS_PROVIDER_LBSUPPORT_FLAG { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_PROVIDER_LBSUPPORT_FLAG { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_PROVIDER_PROP { pub id: ::windows::core::GUID, pub pwszName: super::super::Foundation::PWSTR, pub guidVersionId: ::windows::core::GUID, pub pwszVersion: super::super::Foundation::PWSTR, pub r#type: VDS_PROVIDER_TYPE, pub ulFlags: u32, pub ulStripeSizeFlags: u32, pub sRebuildPriority: i16, } #[cfg(feature = "Win32_Foundation")] impl VDS_PROVIDER_PROP {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_PROVIDER_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_PROVIDER_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_PROVIDER_PROP") .field("id", &self.id) .field("pwszName", &self.pwszName) .field("guidVersionId", &self.guidVersionId) .field("pwszVersion", &self.pwszVersion) .field("r#type", &self.r#type) .field("ulFlags", &self.ulFlags) .field("ulStripeSizeFlags", &self.ulStripeSizeFlags) .field("sRebuildPriority", &self.sRebuildPriority) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_PROVIDER_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.pwszName == other.pwszName && self.guidVersionId == other.guidVersionId && self.pwszVersion == other.pwszVersion && self.r#type == other.r#type && self.ulFlags == other.ulFlags && self.ulStripeSizeFlags == other.ulStripeSizeFlags && self.sRebuildPriority == other.sRebuildPriority } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_PROVIDER_PROP {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_PROVIDER_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_PROVIDER_TYPE(pub i32); pub const VDS_PT_UNKNOWN: VDS_PROVIDER_TYPE = VDS_PROVIDER_TYPE(0i32); pub const VDS_PT_SOFTWARE: VDS_PROVIDER_TYPE = VDS_PROVIDER_TYPE(1i32); pub const VDS_PT_HARDWARE: VDS_PROVIDER_TYPE = VDS_PROVIDER_TYPE(2i32); pub const VDS_PT_VIRTUALDISK: VDS_PROVIDER_TYPE = VDS_PROVIDER_TYPE(3i32); pub const VDS_PT_MAX: VDS_PROVIDER_TYPE = VDS_PROVIDER_TYPE(4i32); impl ::core::convert::From<i32> for VDS_PROVIDER_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_PROVIDER_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_RAID_TYPE(pub i32); pub const VDS_RT_UNKNOWN: VDS_RAID_TYPE = VDS_RAID_TYPE(0i32); pub const VDS_RT_RAID0: VDS_RAID_TYPE = VDS_RAID_TYPE(10i32); pub const VDS_RT_RAID1: VDS_RAID_TYPE = VDS_RAID_TYPE(11i32); pub const VDS_RT_RAID2: VDS_RAID_TYPE = VDS_RAID_TYPE(12i32); pub const VDS_RT_RAID3: VDS_RAID_TYPE = VDS_RAID_TYPE(13i32); pub const VDS_RT_RAID4: VDS_RAID_TYPE = VDS_RAID_TYPE(14i32); pub const VDS_RT_RAID5: VDS_RAID_TYPE = VDS_RAID_TYPE(15i32); pub const VDS_RT_RAID6: VDS_RAID_TYPE = VDS_RAID_TYPE(16i32); pub const VDS_RT_RAID01: VDS_RAID_TYPE = VDS_RAID_TYPE(17i32); pub const VDS_RT_RAID03: VDS_RAID_TYPE = VDS_RAID_TYPE(18i32); pub const VDS_RT_RAID05: VDS_RAID_TYPE = VDS_RAID_TYPE(19i32); pub const VDS_RT_RAID10: VDS_RAID_TYPE = VDS_RAID_TYPE(20i32); pub const VDS_RT_RAID15: VDS_RAID_TYPE = VDS_RAID_TYPE(21i32); pub const VDS_RT_RAID30: VDS_RAID_TYPE = VDS_RAID_TYPE(22i32); pub const VDS_RT_RAID50: VDS_RAID_TYPE = VDS_RAID_TYPE(23i32); pub const VDS_RT_RAID51: VDS_RAID_TYPE = VDS_RAID_TYPE(24i32); pub const VDS_RT_RAID53: VDS_RAID_TYPE = VDS_RAID_TYPE(25i32); pub const VDS_RT_RAID60: VDS_RAID_TYPE = VDS_RAID_TYPE(26i32); pub const VDS_RT_RAID61: VDS_RAID_TYPE = VDS_RAID_TYPE(27i32); impl ::core::convert::From<i32> for VDS_RAID_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_RAID_TYPE { type Abi = Self; } pub const VDS_REBUILD_PRIORITY_MAX: u32 = 16u32; pub const VDS_REBUILD_PRIORITY_MIN: u32 = 0u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_RECOVER_ACTION(pub i32); pub const VDS_RA_UNKNOWN: VDS_RECOVER_ACTION = VDS_RECOVER_ACTION(0i32); pub const VDS_RA_REFRESH: VDS_RECOVER_ACTION = VDS_RECOVER_ACTION(1i32); pub const VDS_RA_RESTART: VDS_RECOVER_ACTION = VDS_RECOVER_ACTION(2i32); impl ::core::convert::From<i32> for VDS_RECOVER_ACTION { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_RECOVER_ACTION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_SERVICE_NOTIFICATION { pub ulEvent: u32, pub action: VDS_RECOVER_ACTION, } impl VDS_SERVICE_NOTIFICATION {} impl ::core::default::Default for VDS_SERVICE_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_SERVICE_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_SERVICE_NOTIFICATION").field("ulEvent", &self.ulEvent).field("action", &self.action).finish() } } impl ::core::cmp::PartialEq for VDS_SERVICE_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.action == other.action } } impl ::core::cmp::Eq for VDS_SERVICE_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_SERVICE_NOTIFICATION { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_STORAGE_BUS_TYPE(pub i32); pub const VDSBusTypeUnknown: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(0i32); pub const VDSBusTypeScsi: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(1i32); pub const VDSBusTypeAtapi: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(2i32); pub const VDSBusTypeAta: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(3i32); pub const VDSBusType1394: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(4i32); pub const VDSBusTypeSsa: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(5i32); pub const VDSBusTypeFibre: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(6i32); pub const VDSBusTypeUsb: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(7i32); pub const VDSBusTypeRAID: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(8i32); pub const VDSBusTypeiScsi: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(9i32); pub const VDSBusTypeSas: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(10i32); pub const VDSBusTypeSata: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(11i32); pub const VDSBusTypeSd: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(12i32); pub const VDSBusTypeMmc: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(13i32); pub const VDSBusTypeMax: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(14i32); pub const VDSBusTypeVirtual: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(14i32); pub const VDSBusTypeFileBackedVirtual: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(15i32); pub const VDSBusTypeSpaces: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(16i32); pub const VDSBusTypeNVMe: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(17i32); pub const VDSBusTypeScm: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(18i32); pub const VDSBusTypeUfs: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(19i32); pub const VDSBusTypeMaxReserved: VDS_STORAGE_BUS_TYPE = VDS_STORAGE_BUS_TYPE(127i32); impl ::core::convert::From<i32> for VDS_STORAGE_BUS_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_STORAGE_BUS_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_STORAGE_DEVICE_ID_DESCRIPTOR { pub m_version: u32, pub m_cIdentifiers: u32, pub m_rgIdentifiers: *mut VDS_STORAGE_IDENTIFIER, } impl VDS_STORAGE_DEVICE_ID_DESCRIPTOR {} impl ::core::default::Default for VDS_STORAGE_DEVICE_ID_DESCRIPTOR { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_STORAGE_DEVICE_ID_DESCRIPTOR { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_STORAGE_DEVICE_ID_DESCRIPTOR").field("m_version", &self.m_version).field("m_cIdentifiers", &self.m_cIdentifiers).field("m_rgIdentifiers", &self.m_rgIdentifiers).finish() } } impl ::core::cmp::PartialEq for VDS_STORAGE_DEVICE_ID_DESCRIPTOR { fn eq(&self, other: &Self) -> bool { self.m_version == other.m_version && self.m_cIdentifiers == other.m_cIdentifiers && self.m_rgIdentifiers == other.m_rgIdentifiers } } impl ::core::cmp::Eq for VDS_STORAGE_DEVICE_ID_DESCRIPTOR {} unsafe impl ::windows::core::Abi for VDS_STORAGE_DEVICE_ID_DESCRIPTOR { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_STORAGE_IDENTIFIER { pub m_CodeSet: VDS_STORAGE_IDENTIFIER_CODE_SET, pub m_Type: VDS_STORAGE_IDENTIFIER_TYPE, pub m_cbIdentifier: u32, pub m_rgbIdentifier: *mut u8, } impl VDS_STORAGE_IDENTIFIER {} impl ::core::default::Default for VDS_STORAGE_IDENTIFIER { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_STORAGE_IDENTIFIER { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_STORAGE_IDENTIFIER").field("m_CodeSet", &self.m_CodeSet).field("m_Type", &self.m_Type).field("m_cbIdentifier", &self.m_cbIdentifier).field("m_rgbIdentifier", &self.m_rgbIdentifier).finish() } } impl ::core::cmp::PartialEq for VDS_STORAGE_IDENTIFIER { fn eq(&self, other: &Self) -> bool { self.m_CodeSet == other.m_CodeSet && self.m_Type == other.m_Type && self.m_cbIdentifier == other.m_cbIdentifier && self.m_rgbIdentifier == other.m_rgbIdentifier } } impl ::core::cmp::Eq for VDS_STORAGE_IDENTIFIER {} unsafe impl ::windows::core::Abi for VDS_STORAGE_IDENTIFIER { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_STORAGE_IDENTIFIER_CODE_SET(pub i32); pub const VDSStorageIdCodeSetReserved: VDS_STORAGE_IDENTIFIER_CODE_SET = VDS_STORAGE_IDENTIFIER_CODE_SET(0i32); pub const VDSStorageIdCodeSetBinary: VDS_STORAGE_IDENTIFIER_CODE_SET = VDS_STORAGE_IDENTIFIER_CODE_SET(1i32); pub const VDSStorageIdCodeSetAscii: VDS_STORAGE_IDENTIFIER_CODE_SET = VDS_STORAGE_IDENTIFIER_CODE_SET(2i32); pub const VDSStorageIdCodeSetUtf8: VDS_STORAGE_IDENTIFIER_CODE_SET = VDS_STORAGE_IDENTIFIER_CODE_SET(3i32); impl ::core::convert::From<i32> for VDS_STORAGE_IDENTIFIER_CODE_SET { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_STORAGE_IDENTIFIER_CODE_SET { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_STORAGE_IDENTIFIER_TYPE(pub i32); pub const VDSStorageIdTypeVendorSpecific: VDS_STORAGE_IDENTIFIER_TYPE = VDS_STORAGE_IDENTIFIER_TYPE(0i32); pub const VDSStorageIdTypeVendorId: VDS_STORAGE_IDENTIFIER_TYPE = VDS_STORAGE_IDENTIFIER_TYPE(1i32); pub const VDSStorageIdTypeEUI64: VDS_STORAGE_IDENTIFIER_TYPE = VDS_STORAGE_IDENTIFIER_TYPE(2i32); pub const VDSStorageIdTypeFCPHName: VDS_STORAGE_IDENTIFIER_TYPE = VDS_STORAGE_IDENTIFIER_TYPE(3i32); pub const VDSStorageIdTypePortRelative: VDS_STORAGE_IDENTIFIER_TYPE = VDS_STORAGE_IDENTIFIER_TYPE(4i32); pub const VDSStorageIdTypeTargetPortGroup: VDS_STORAGE_IDENTIFIER_TYPE = VDS_STORAGE_IDENTIFIER_TYPE(5i32); pub const VDSStorageIdTypeLogicalUnitGroup: VDS_STORAGE_IDENTIFIER_TYPE = VDS_STORAGE_IDENTIFIER_TYPE(6i32); pub const VDSStorageIdTypeMD5LogicalUnitIdentifier: VDS_STORAGE_IDENTIFIER_TYPE = VDS_STORAGE_IDENTIFIER_TYPE(7i32); pub const VDSStorageIdTypeScsiNameString: VDS_STORAGE_IDENTIFIER_TYPE = VDS_STORAGE_IDENTIFIER_TYPE(8i32); impl ::core::convert::From<i32> for VDS_STORAGE_IDENTIFIER_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_STORAGE_IDENTIFIER_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_STORAGE_POOL_DRIVE_EXTENT { pub id: ::windows::core::GUID, pub ullSize: u64, pub bUsed: super::super::Foundation::BOOL, } #[cfg(feature = "Win32_Foundation")] impl VDS_STORAGE_POOL_DRIVE_EXTENT {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_STORAGE_POOL_DRIVE_EXTENT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_STORAGE_POOL_DRIVE_EXTENT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_STORAGE_POOL_DRIVE_EXTENT").field("id", &self.id).field("ullSize", &self.ullSize).field("bUsed", &self.bUsed).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_STORAGE_POOL_DRIVE_EXTENT { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.ullSize == other.ullSize && self.bUsed == other.bUsed } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_STORAGE_POOL_DRIVE_EXTENT {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_STORAGE_POOL_DRIVE_EXTENT { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_STORAGE_POOL_PROP { pub id: ::windows::core::GUID, pub status: VDS_STORAGE_POOL_STATUS, pub health: VDS_HEALTH, pub r#type: VDS_STORAGE_POOL_TYPE, pub pwszName: super::super::Foundation::PWSTR, pub pwszDescription: super::super::Foundation::PWSTR, pub ullTotalConsumedSpace: u64, pub ullTotalManagedSpace: u64, pub ullRemainingFreeSpace: u64, } #[cfg(feature = "Win32_Foundation")] impl VDS_STORAGE_POOL_PROP {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_STORAGE_POOL_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_STORAGE_POOL_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_STORAGE_POOL_PROP") .field("id", &self.id) .field("status", &self.status) .field("health", &self.health) .field("r#type", &self.r#type) .field("pwszName", &self.pwszName) .field("pwszDescription", &self.pwszDescription) .field("ullTotalConsumedSpace", &self.ullTotalConsumedSpace) .field("ullTotalManagedSpace", &self.ullTotalManagedSpace) .field("ullRemainingFreeSpace", &self.ullRemainingFreeSpace) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_STORAGE_POOL_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.status == other.status && self.health == other.health && self.r#type == other.r#type && self.pwszName == other.pwszName && self.pwszDescription == other.pwszDescription && self.ullTotalConsumedSpace == other.ullTotalConsumedSpace && self.ullTotalManagedSpace == other.ullTotalManagedSpace && self.ullRemainingFreeSpace == other.ullRemainingFreeSpace } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_STORAGE_POOL_PROP {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_STORAGE_POOL_PROP { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_STORAGE_POOL_STATUS(pub i32); pub const VDS_SPS_UNKNOWN: VDS_STORAGE_POOL_STATUS = VDS_STORAGE_POOL_STATUS(0i32); pub const VDS_SPS_ONLINE: VDS_STORAGE_POOL_STATUS = VDS_STORAGE_POOL_STATUS(1i32); pub const VDS_SPS_NOT_READY: VDS_STORAGE_POOL_STATUS = VDS_STORAGE_POOL_STATUS(2i32); pub const VDS_SPS_OFFLINE: VDS_STORAGE_POOL_STATUS = VDS_STORAGE_POOL_STATUS(4i32); impl ::core::convert::From<i32> for VDS_STORAGE_POOL_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_STORAGE_POOL_STATUS { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_STORAGE_POOL_TYPE(pub i32); pub const VDS_SPT_UNKNOWN: VDS_STORAGE_POOL_TYPE = VDS_STORAGE_POOL_TYPE(0i32); pub const VDS_SPT_PRIMORDIAL: VDS_STORAGE_POOL_TYPE = VDS_STORAGE_POOL_TYPE(1i32); pub const VDS_SPT_CONCRETE: VDS_STORAGE_POOL_TYPE = VDS_STORAGE_POOL_TYPE(2i32); impl ::core::convert::From<i32> for VDS_STORAGE_POOL_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_STORAGE_POOL_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_SUB_SYSTEM_FLAG(pub i32); pub const VDS_SF_LUN_MASKING_CAPABLE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(1i32); pub const VDS_SF_LUN_PLEXING_CAPABLE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(2i32); pub const VDS_SF_LUN_REMAPPING_CAPABLE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(4i32); pub const VDS_SF_DRIVE_EXTENT_CAPABLE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(8i32); pub const VDS_SF_HARDWARE_CHECKSUM_CAPABLE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(16i32); pub const VDS_SF_RADIUS_CAPABLE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(32i32); pub const VDS_SF_READ_BACK_VERIFY_CAPABLE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(64i32); pub const VDS_SF_WRITE_THROUGH_CACHING_CAPABLE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(128i32); pub const VDS_SF_SUPPORTS_FAULT_TOLERANT_LUNS: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(512i32); pub const VDS_SF_SUPPORTS_NON_FAULT_TOLERANT_LUNS: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(1024i32); pub const VDS_SF_SUPPORTS_SIMPLE_LUNS: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(2048i32); pub const VDS_SF_SUPPORTS_SPAN_LUNS: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(4096i32); pub const VDS_SF_SUPPORTS_STRIPE_LUNS: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(8192i32); pub const VDS_SF_SUPPORTS_MIRROR_LUNS: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(16384i32); pub const VDS_SF_SUPPORTS_PARITY_LUNS: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(32768i32); pub const VDS_SF_SUPPORTS_AUTH_CHAP: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(65536i32); pub const VDS_SF_SUPPORTS_AUTH_MUTUAL_CHAP: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(131072i32); pub const VDS_SF_SUPPORTS_SIMPLE_TARGET_CONFIG: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(262144i32); pub const VDS_SF_SUPPORTS_LUN_NUMBER: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(524288i32); pub const VDS_SF_SUPPORTS_MIRRORED_CACHE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(1048576i32); pub const VDS_SF_READ_CACHING_CAPABLE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(2097152i32); pub const VDS_SF_WRITE_CACHING_CAPABLE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(4194304i32); pub const VDS_SF_MEDIA_SCAN_CAPABLE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(8388608i32); pub const VDS_SF_CONSISTENCY_CHECK_CAPABLE: VDS_SUB_SYSTEM_FLAG = VDS_SUB_SYSTEM_FLAG(16777216i32); impl ::core::convert::From<i32> for VDS_SUB_SYSTEM_FLAG { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_SUB_SYSTEM_FLAG { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_SUB_SYSTEM_NOTIFICATION { pub ulEvent: u32, pub subSystemId: ::windows::core::GUID, } impl VDS_SUB_SYSTEM_NOTIFICATION {} impl ::core::default::Default for VDS_SUB_SYSTEM_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_SUB_SYSTEM_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_SUB_SYSTEM_NOTIFICATION").field("ulEvent", &self.ulEvent).field("subSystemId", &self.subSystemId).finish() } } impl ::core::cmp::PartialEq for VDS_SUB_SYSTEM_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.subSystemId == other.subSystemId } } impl ::core::cmp::Eq for VDS_SUB_SYSTEM_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_SUB_SYSTEM_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_SUB_SYSTEM_PROP { pub id: ::windows::core::GUID, pub pwszFriendlyName: super::super::Foundation::PWSTR, pub pwszIdentification: super::super::Foundation::PWSTR, pub ulFlags: u32, pub ulStripeSizeFlags: u32, pub status: VDS_SUB_SYSTEM_STATUS, pub health: VDS_HEALTH, pub sNumberOfInternalBuses: i16, pub sMaxNumberOfSlotsEachBus: i16, pub sMaxNumberOfControllers: i16, pub sRebuildPriority: i16, } #[cfg(feature = "Win32_Foundation")] impl VDS_SUB_SYSTEM_PROP {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_SUB_SYSTEM_PROP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_SUB_SYSTEM_PROP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_SUB_SYSTEM_PROP") .field("id", &self.id) .field("pwszFriendlyName", &self.pwszFriendlyName) .field("pwszIdentification", &self.pwszIdentification) .field("ulFlags", &self.ulFlags) .field("ulStripeSizeFlags", &self.ulStripeSizeFlags) .field("status", &self.status) .field("health", &self.health) .field("sNumberOfInternalBuses", &self.sNumberOfInternalBuses) .field("sMaxNumberOfSlotsEachBus", &self.sMaxNumberOfSlotsEachBus) .field("sMaxNumberOfControllers", &self.sMaxNumberOfControllers) .field("sRebuildPriority", &self.sRebuildPriority) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_SUB_SYSTEM_PROP { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.pwszFriendlyName == other.pwszFriendlyName && self.pwszIdentification == other.pwszIdentification && self.ulFlags == other.ulFlags && self.ulStripeSizeFlags == other.ulStripeSizeFlags && self.status == other.status && self.health == other.health && self.sNumberOfInternalBuses == other.sNumberOfInternalBuses && self.sMaxNumberOfSlotsEachBus == other.sMaxNumberOfSlotsEachBus && self.sMaxNumberOfControllers == other.sMaxNumberOfControllers && self.sRebuildPriority == other.sRebuildPriority } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_SUB_SYSTEM_PROP {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_SUB_SYSTEM_PROP { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct VDS_SUB_SYSTEM_PROP2 { pub id: ::windows::core::GUID, pub pwszFriendlyName: super::super::Foundation::PWSTR, pub pwszIdentification: super::super::Foundation::PWSTR, pub ulFlags: u32, pub ulStripeSizeFlags: u32, pub ulSupportedRaidTypeFlags: u32, pub status: VDS_SUB_SYSTEM_STATUS, pub health: VDS_HEALTH, pub sNumberOfInternalBuses: i16, pub sMaxNumberOfSlotsEachBus: i16, pub sMaxNumberOfControllers: i16, pub sRebuildPriority: i16, pub ulNumberOfEnclosures: u32, } #[cfg(feature = "Win32_Foundation")] impl VDS_SUB_SYSTEM_PROP2 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for VDS_SUB_SYSTEM_PROP2 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for VDS_SUB_SYSTEM_PROP2 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_SUB_SYSTEM_PROP2") .field("id", &self.id) .field("pwszFriendlyName", &self.pwszFriendlyName) .field("pwszIdentification", &self.pwszIdentification) .field("ulFlags", &self.ulFlags) .field("ulStripeSizeFlags", &self.ulStripeSizeFlags) .field("ulSupportedRaidTypeFlags", &self.ulSupportedRaidTypeFlags) .field("status", &self.status) .field("health", &self.health) .field("sNumberOfInternalBuses", &self.sNumberOfInternalBuses) .field("sMaxNumberOfSlotsEachBus", &self.sMaxNumberOfSlotsEachBus) .field("sMaxNumberOfControllers", &self.sMaxNumberOfControllers) .field("sRebuildPriority", &self.sRebuildPriority) .field("ulNumberOfEnclosures", &self.ulNumberOfEnclosures) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for VDS_SUB_SYSTEM_PROP2 { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.pwszFriendlyName == other.pwszFriendlyName && self.pwszIdentification == other.pwszIdentification && self.ulFlags == other.ulFlags && self.ulStripeSizeFlags == other.ulStripeSizeFlags && self.ulSupportedRaidTypeFlags == other.ulSupportedRaidTypeFlags && self.status == other.status && self.health == other.health && self.sNumberOfInternalBuses == other.sNumberOfInternalBuses && self.sMaxNumberOfSlotsEachBus == other.sMaxNumberOfSlotsEachBus && self.sMaxNumberOfControllers == other.sMaxNumberOfControllers && self.sRebuildPriority == other.sRebuildPriority && self.ulNumberOfEnclosures == other.ulNumberOfEnclosures } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for VDS_SUB_SYSTEM_PROP2 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for VDS_SUB_SYSTEM_PROP2 { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_SUB_SYSTEM_STATUS(pub i32); pub const VDS_SSS_UNKNOWN: VDS_SUB_SYSTEM_STATUS = VDS_SUB_SYSTEM_STATUS(0i32); pub const VDS_SSS_ONLINE: VDS_SUB_SYSTEM_STATUS = VDS_SUB_SYSTEM_STATUS(1i32); pub const VDS_SSS_NOT_READY: VDS_SUB_SYSTEM_STATUS = VDS_SUB_SYSTEM_STATUS(2i32); pub const VDS_SSS_OFFLINE: VDS_SUB_SYSTEM_STATUS = VDS_SUB_SYSTEM_STATUS(4i32); pub const VDS_SSS_FAILED: VDS_SUB_SYSTEM_STATUS = VDS_SUB_SYSTEM_STATUS(5i32); pub const VDS_SSS_PARTIALLY_MANAGED: VDS_SUB_SYSTEM_STATUS = VDS_SUB_SYSTEM_STATUS(9i32); impl ::core::convert::From<i32> for VDS_SUB_SYSTEM_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_SUB_SYSTEM_STATUS { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(pub i32); pub const VDS_SF_SUPPORTS_RAID2_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(1i32); pub const VDS_SF_SUPPORTS_RAID3_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(2i32); pub const VDS_SF_SUPPORTS_RAID4_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(4i32); pub const VDS_SF_SUPPORTS_RAID5_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(8i32); pub const VDS_SF_SUPPORTS_RAID6_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(16i32); pub const VDS_SF_SUPPORTS_RAID01_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(32i32); pub const VDS_SF_SUPPORTS_RAID03_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(64i32); pub const VDS_SF_SUPPORTS_RAID05_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(128i32); pub const VDS_SF_SUPPORTS_RAID10_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(256i32); pub const VDS_SF_SUPPORTS_RAID15_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(512i32); pub const VDS_SF_SUPPORTS_RAID30_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(1024i32); pub const VDS_SF_SUPPORTS_RAID50_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(2048i32); pub const VDS_SF_SUPPORTS_RAID51_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(4096i32); pub const VDS_SF_SUPPORTS_RAID53_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(8192i32); pub const VDS_SF_SUPPORTS_RAID60_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(16384i32); pub const VDS_SF_SUPPORTS_RAID61_LUNS: VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG = VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG(32768i32); impl ::core::convert::From<i32> for VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_SUB_SYSTEM_SUPPORTED_RAID_TYPE_FLAG { type Abi = Self; } pub const VDS_S_ACCESS_PATH_NOT_DELETED: ::windows::core::HRESULT = ::windows::core::HRESULT(279108i32 as _); pub const VDS_S_ALREADY_EXISTS: ::windows::core::HRESULT = ::windows::core::HRESULT(272148i32 as _); pub const VDS_S_BOOT_PARTITION_NUMBER_CHANGE: ::windows::core::HRESULT = ::windows::core::HRESULT(271414i32 as _); pub const VDS_S_DEFAULT_PLEX_MEMBER_IDS: ::windows::core::HRESULT = ::windows::core::HRESULT(271640i32 as _); pub const VDS_S_DISK_DISMOUNT_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(272393i32 as _); pub const VDS_S_DISK_IS_MISSING: ::windows::core::HRESULT = ::windows::core::HRESULT(271624i32 as _); pub const VDS_S_DISK_MOUNT_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(272392i32 as _); pub const VDS_S_DISK_PARTIALLY_CLEANED: ::windows::core::HRESULT = ::windows::core::HRESULT(271386i32 as _); pub const VDS_S_DISMOUNT_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(271735i32 as _); pub const VDS_S_EXTEND_FILE_SYSTEM_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(271461i32 as _); pub const VDS_S_FS_LOCK: ::windows::core::HRESULT = ::windows::core::HRESULT(271747i32 as _); pub const VDS_S_GPT_BOOT_MIRRORED_TO_MBR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147212183i32 as _); pub const VDS_S_IA64_BOOT_MIRRORED_TO_MBR: ::windows::core::HRESULT = ::windows::core::HRESULT(271450i32 as _); pub const VDS_S_IN_PROGRESS: ::windows::core::HRESULT = ::windows::core::HRESULT(271437i32 as _); pub const VDS_S_ISCSI_LOGIN_ALREAD_EXISTS: ::windows::core::HRESULT = ::windows::core::HRESULT(272386i32 as _); pub const VDS_S_ISCSI_PERSISTENT_LOGIN_MAY_NOT_BE_REMOVED: ::windows::core::HRESULT = ::windows::core::HRESULT(272385i32 as _); pub const VDS_S_ISCSI_SESSION_NOT_FOUND_PERSISTENT_LOGIN_REMOVED: ::windows::core::HRESULT = ::windows::core::HRESULT(272384i32 as _); pub const VDS_S_MBR_BOOT_MIRRORED_TO_GPT: ::windows::core::HRESULT = ::windows::core::HRESULT(271463i32 as _); pub const VDS_S_NAME_TRUNCATED: ::windows::core::HRESULT = ::windows::core::HRESULT(272128i32 as _); pub const VDS_S_NONCONFORMANT_PARTITION_INFO: ::windows::core::HRESULT = ::windows::core::HRESULT(271626i32 as _); pub const VDS_S_NO_NOTIFICATION: ::windows::core::HRESULT = ::windows::core::HRESULT(271639i32 as _); pub const VDS_S_PLEX_NOT_LOADED_TO_CACHE: ::windows::core::HRESULT = ::windows::core::HRESULT(271755i32 as _); pub const VDS_S_PROPERTIES_INCOMPLETE: ::windows::core::HRESULT = ::windows::core::HRESULT(272149i32 as _); pub const VDS_S_PROVIDER_ERROR_LOADING_CACHE: ::windows::core::HRESULT = ::windows::core::HRESULT(271393i32 as _); pub const VDS_S_REMOUNT_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(271736i32 as _); pub const VDS_S_RESYNC_NOTIFICATION_TASK_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(271738i32 as _); pub const VDS_S_STATUSES_INCOMPLETELY_SET: ::windows::core::HRESULT = ::windows::core::HRESULT(272130i32 as _); pub const VDS_S_SYSTEM_PARTITION: ::windows::core::HRESULT = ::windows::core::HRESULT(271630i32 as _); pub const VDS_S_UNABLE_TO_GET_GPT_ATTRIBUTES: ::windows::core::HRESULT = ::windows::core::HRESULT(271451i32 as _); pub const VDS_S_UPDATE_BOOTFILE_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(271412i32 as _); pub const VDS_S_VOLUME_COMPRESS_FAILED: ::windows::core::HRESULT = ::windows::core::HRESULT(271427i32 as _); pub const VDS_S_VSS_FLUSH_AND_HOLD_WRITES: ::windows::core::HRESULT = ::windows::core::HRESULT(271745i32 as _); pub const VDS_S_VSS_RELEASE_WRITES: ::windows::core::HRESULT = ::windows::core::HRESULT(271746i32 as _); pub const VDS_S_WINPE_BOOTENTRY: ::windows::core::HRESULT = ::windows::core::HRESULT(271758i32 as _); #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_TARGET_NOTIFICATION { pub ulEvent: u32, pub targetId: ::windows::core::GUID, } impl VDS_TARGET_NOTIFICATION {} impl ::core::default::Default for VDS_TARGET_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_TARGET_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_TARGET_NOTIFICATION").field("ulEvent", &self.ulEvent).field("targetId", &self.targetId).finish() } } impl ::core::cmp::PartialEq for VDS_TARGET_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.targetId == other.targetId } } impl ::core::cmp::Eq for VDS_TARGET_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_TARGET_NOTIFICATION { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_TRANSITION_STATE(pub i32); pub const VDS_TS_UNKNOWN: VDS_TRANSITION_STATE = VDS_TRANSITION_STATE(0i32); pub const VDS_TS_STABLE: VDS_TRANSITION_STATE = VDS_TRANSITION_STATE(1i32); pub const VDS_TS_EXTENDING: VDS_TRANSITION_STATE = VDS_TRANSITION_STATE(2i32); pub const VDS_TS_SHRINKING: VDS_TRANSITION_STATE = VDS_TRANSITION_STATE(3i32); pub const VDS_TS_RECONFIGING: VDS_TRANSITION_STATE = VDS_TRANSITION_STATE(4i32); pub const VDS_TS_RESTRIPING: VDS_TRANSITION_STATE = VDS_TRANSITION_STATE(5i32); impl ::core::convert::From<i32> for VDS_TRANSITION_STATE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_TRANSITION_STATE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct VDS_VERSION_SUPPORT_FLAG(pub i32); pub const VDS_VSF_1_0: VDS_VERSION_SUPPORT_FLAG = VDS_VERSION_SUPPORT_FLAG(1i32); pub const VDS_VSF_1_1: VDS_VERSION_SUPPORT_FLAG = VDS_VERSION_SUPPORT_FLAG(2i32); pub const VDS_VSF_2_0: VDS_VERSION_SUPPORT_FLAG = VDS_VERSION_SUPPORT_FLAG(4i32); pub const VDS_VSF_2_1: VDS_VERSION_SUPPORT_FLAG = VDS_VERSION_SUPPORT_FLAG(8i32); pub const VDS_VSF_3_0: VDS_VERSION_SUPPORT_FLAG = VDS_VERSION_SUPPORT_FLAG(16i32); impl ::core::convert::From<i32> for VDS_VERSION_SUPPORT_FLAG { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for VDS_VERSION_SUPPORT_FLAG { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_VOLUME_NOTIFICATION { pub ulEvent: u32, pub volumeId: ::windows::core::GUID, pub plexId: ::windows::core::GUID, pub ulPercentCompleted: u32, } impl VDS_VOLUME_NOTIFICATION {} impl ::core::default::Default for VDS_VOLUME_NOTIFICATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_VOLUME_NOTIFICATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_VOLUME_NOTIFICATION").field("ulEvent", &self.ulEvent).field("volumeId", &self.volumeId).field("plexId", &self.plexId).field("ulPercentCompleted", &self.ulPercentCompleted).finish() } } impl ::core::cmp::PartialEq for VDS_VOLUME_NOTIFICATION { fn eq(&self, other: &Self) -> bool { self.ulEvent == other.ulEvent && self.volumeId == other.volumeId && self.plexId == other.plexId && self.ulPercentCompleted == other.ulPercentCompleted } } impl ::core::cmp::Eq for VDS_VOLUME_NOTIFICATION {} unsafe impl ::windows::core::Abi for VDS_VOLUME_NOTIFICATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VDS_WWN { pub rguchWwn: [u8; 8], } impl VDS_WWN {} impl ::core::default::Default for VDS_WWN { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VDS_WWN { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VDS_WWN").field("rguchWwn", &self.rguchWwn).finish() } } impl ::core::cmp::PartialEq for VDS_WWN { fn eq(&self, other: &Self) -> bool { self.rguchWwn == other.rguchWwn } } impl ::core::cmp::Eq for VDS_WWN {} unsafe impl ::windows::core::Abi for VDS_WWN { type Abi = Self; } pub const VER_VDS_LUN_INFORMATION: u32 = 1u32;
use std::{path::Path, sync::Arc}; use criterion::{ criterion_group, criterion_main, measurement::WallTime, BatchSize, BenchmarkGroup, BenchmarkId, Criterion, Throughput, }; use data_types::{ partition_template::{NamespacePartitionTemplateOverride, TablePartitionTemplateOverride}, NamespaceId, NamespaceName, NamespaceSchema, TableId, }; use generated_types::influxdata::iox::partition_template::v1 as proto; use hashbrown::HashMap; use once_cell::sync::Lazy; use router::dml_handlers::{DmlHandler, Partitioner}; use tokio::runtime::Runtime; static NAMESPACE: Lazy<NamespaceName<'static>> = Lazy::new(|| "bananas".try_into().unwrap()); fn runtime() -> Runtime { tokio::runtime::Builder::new_current_thread() .build() .unwrap() } fn partitioner_benchmarks(c: &mut Criterion) { let mut group = c.benchmark_group("partitioner"); //////////////////////////////////////////////////////////////////////////// // A medium batch. bench( &mut group, "tag_hit", vec![proto::TemplatePart { part: Some(proto::template_part::Part::TagValue("env".to_string())), }], "test_fixtures/lineproto/prometheus.lp", ); bench( &mut group, "tag_miss", vec![proto::TemplatePart { part: Some(proto::template_part::Part::TagValue("bananas".to_string())), }], "test_fixtures/lineproto/prometheus.lp", ); bench( &mut group, "YYYY-MM-DD strftime", vec![proto::TemplatePart { part: Some(proto::template_part::Part::TimeFormat( "%Y-%m-%d".to_string(), )), }], "test_fixtures/lineproto/prometheus.lp", ); bench( &mut group, "long strftime", vec![proto::TemplatePart { part: Some(proto::template_part::Part::TimeFormat("%Y-%C-%y-%m-%b-%B-%h-%d-%e-%a-%A-%w-%u-%U-%W-%G-%g-%V-%j-%D-%x-%F-%v-%H-%k-%I-%l-%P-%p-%M-%S-%f-%.f-%.3f-%.6f-%.9f-%3f-%6f-%9f-%R-%T-%X-%r-%Z-%z-%:z-%::z-%:::z-%c-%+-%s-%t-%n-%%".to_string())), }], "test_fixtures/lineproto/prometheus.lp", ); //////////////////////////////////////////////////////////////////////////// // A large batch. bench( &mut group, "tag_hit", vec![proto::TemplatePart { part: Some(proto::template_part::Part::TagValue("host".to_string())), }], "test_fixtures/lineproto/metrics.lp", ); bench( &mut group, "tag_miss", vec![proto::TemplatePart { part: Some(proto::template_part::Part::TagValue("bananas".to_string())), }], "test_fixtures/lineproto/metrics.lp", ); bench( &mut group, "YYYY-MM-DD strftime", vec![proto::TemplatePart { part: Some(proto::template_part::Part::TimeFormat( "%Y-%m-%d".to_string(), )), }], "test_fixtures/lineproto/metrics.lp", ); bench( &mut group, "long strftime", vec![proto::TemplatePart { part: Some(proto::template_part::Part::TimeFormat("%Y-%C-%y-%m-%b-%B-%h-%d-%e-%a-%A-%w-%u-%U-%W-%G-%g-%V-%j-%D-%x-%F-%v-%H-%k-%I-%l-%P-%p-%M-%S-%f-%.f-%.3f-%.6f-%.9f-%3f-%6f-%9f-%R-%T-%X-%r-%Z-%z-%:z-%::z-%:::z-%c-%+-%s-%t-%n-%%".to_string())), }], "test_fixtures/lineproto/metrics.lp", ); //////////////////////////////////////////////////////////////////////////// // A small batch. bench( &mut group, "tag_hit", vec![proto::TemplatePart { part: Some(proto::template_part::Part::TagValue("location".to_string())), }], "test_fixtures/lineproto/temperature.lp", ); bench( &mut group, "tag_miss", vec![proto::TemplatePart { part: Some(proto::template_part::Part::TagValue("bananas".to_string())), }], "test_fixtures/lineproto/temperature.lp", ); bench( &mut group, "YYYY-MM-DD strftime", vec![proto::TemplatePart { part: Some(proto::template_part::Part::TimeFormat( "%Y-%m-%d".to_string(), )), }], "test_fixtures/lineproto/temperature.lp", ); bench( &mut group, "long strftime", vec![proto::TemplatePart { part: Some(proto::template_part::Part::TimeFormat("%Y-%C-%y-%m-%b-%B-%h-%d-%e-%a-%A-%w-%u-%U-%W-%G-%g-%V-%j-%D-%x-%F-%v-%H-%k-%I-%l-%P-%p-%M-%S-%f-%.f-%.3f-%.6f-%.9f-%3f-%6f-%9f-%R-%T-%X-%r-%Z-%z-%:z-%::z-%:::z-%c-%+-%s-%t-%n-%%".to_string())), }], "test_fixtures/lineproto/temperature.lp", ); group.finish(); } fn bench( group: &mut BenchmarkGroup<WallTime>, template_name: &str, partition_template: Vec<proto::TemplatePart>, file_path: &str, // Relative to the crate root ) { // Un-normalise the path, adjusting back to the crate root. let file_path = format!("{}/../{}", env!("CARGO_MANIFEST_DIR"), file_path); let path = Path::new(&file_path); let partition_template = NamespacePartitionTemplateOverride::try_from(proto::PartitionTemplate { parts: partition_template, }) .unwrap(); let schema = Arc::new(NamespaceSchema { id: NamespaceId::new(42), tables: Default::default(), max_columns_per_table: 1000, max_tables: 1000, retention_period_ns: None, partition_template: partition_template.clone(), }); // Read the benchmark data let data = std::fs::read_to_string(path).unwrap(); let row_count = data.chars().filter(|&v| v == '\n').count(); // Initialise the partitioner let partitioner = Partitioner::default(); // Generate the partitioner input let input = mutable_batch_lp::lines_to_batches(&data, 42) .unwrap() .into_iter() .enumerate() .map(|(i, (name, payload))| { ( TableId::new(i as _), ( name, TablePartitionTemplateOverride::try_new(None, &partition_template).unwrap(), payload, ), ) }) .collect::<HashMap<_, _>>(); group.throughput(Throughput::Elements(row_count as _)); group.bench_function( BenchmarkId::new(template_name, path.file_name().unwrap().to_str().unwrap()), |b| { b.to_async(runtime()).iter_batched( || input.clone(), |input| partitioner.write(&NAMESPACE, Arc::clone(&schema), input, None), BatchSize::NumIterations(1), ) }, ); } criterion_group!(benches, partitioner_benchmarks); criterion_main!(benches);
use crate::bucket::DailyBucket; use crate::hotspotmap::HotspotMap; use crate::msg::QueryAnswer; use crate::pointer::{Pointer, Pointers, ONE_DAY}; use cosmwasm_std::{ to_binary, Api, Env, Extern, HandleResponse, Querier, QueryResult, StdResult, Storage, }; pub fn query_dates<S: Storage, A: Api, Q: Querier>(deps: &Extern<S, A, Q>) -> QueryResult { let pointers = Pointers::load(&deps.storage)?; let to = pointers.first().unwrap().end_time; let from = pointers.last().unwrap().start_time; return to_binary(&QueryAnswer::DateRange { from, to }); } pub fn new_day<S: Storage, A: Api, Q: Querier>( deps: &mut Extern<S, A, Q>, _env: Env, ) -> StdResult<HandleResponse> { let mut pointers = Pointers::load(&deps.storage)?; let old_day = pointers.pop().unwrap(); let old_bucket = DailyBucket::load(&deps.storage, &old_day.bucket)?; let new_day = Pointer { start_time: pointers.first().unwrap().end_time, end_time: pointers.first().unwrap().end_time + ONE_DAY, bucket: old_day.bucket, }; let bucket = DailyBucket::default(); bucket.store(&mut deps.storage, &old_day.bucket)?; pointers.insert(new_day); let mut hotspots = HotspotMap::load(&deps.storage)?; // might be better to create a trie per day, and aggregate it instead of doing it like this? // either way this only happens once per day, so might be acceptable to take a little more time // but still optimize for fast query for (loc, _) in old_bucket.locations.iter() { hotspots.remove_data_point(loc) } Ok(HandleResponse::default()) }
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved // use std::path::Path; extern crate wasm_bindgen; use wasm_bindgen::prelude::*; use serde_derive::{Deserialize, Serialize}; use crate::{Error, Tag, WorkAsset}; /// The Metadata struct & accessor methods pub mod metadata; pub use metadata::Metadata; /// Compatibility methods for the WebAssembly build pub mod wasm; /// The primary API data structure. /// /// The key property is a glTF asset in binary form (which will always implement /// the `KHR_materials_variants` extension), along with various useful metadata for /// the benefit of clients. /// /// The key method melds one variational asset into another: /// ``` /// extern crate assets; /// use std::path::Path; /// use gltf_variant_meld::{Tag, VariationalAsset}; /// /// let (matte_tag, shiny_tag) = (Tag::from("matte"), Tag::from("shiny")); /// let pinecone_matte = VariationalAsset::from_file( /// &Path::new(assets::ASSET_PINECONE_MATTE()), /// Some(&matte_tag), /// ).expect("Eek! Couldn't create matte pinecone VariationalAsset."); /// /// let pinecone_shiny = VariationalAsset::from_file( /// &Path::new(assets::ASSET_PINECONE_SHINY()), /// Some(&shiny_tag), /// ).expect("Eek! Couldn't create shiny pinecone VariationalAsset."); /// /// let result = VariationalAsset::meld( /// &pinecone_matte, /// &pinecone_shiny /// ).expect("Erk. Failed to meld two pinecones."); /// /// assert!(result.metadata().tags().contains(&matte_tag)); /// assert!(result.metadata().tags().contains(&shiny_tag)); /// assert_eq!(result.metadata().tags().len(), 2); ///``` #[wasm_bindgen] #[derive(Debug, Clone)] pub struct VariationalAsset { /// The generated glTF for this asset. Will always implement `KHR_materials_variants` /// and is always in binary (GLB) form. pub(crate) glb: Vec<u8>, /// The tag that stands in for any default material references in the asset glTF. pub(crate) default_tag: Tag, /// All the metadata generated for this asset. pub(crate) metadata: Metadata, } /// A summary of a mesh primitive's byte size requirements; currently textures only. #[wasm_bindgen] #[derive(Debug, Copy, Clone, Serialize, Deserialize)] pub struct AssetSizes { /// Byte count for texture image data, in its raw encoded form. pub texture_bytes: usize, } // methods that wasm_bindgen can't cope with in their preferred form impl VariationalAsset { /// Generates a new `VariationalAsset` from a glTF file. /// /// If the provided asset implements `KHR_materials_variants`, then `default_tag` must /// either be empty or match the default tag within the asset. /// /// If the asset doesn't implement `KHR_materials_variants`, then the argument /// `default_tag` must be non-empty. If it does, then `default_tag` must either match /// what's in the asset, or else be empty. pub fn from_file(file: &Path, default_tag: Option<&Tag>) -> Result<VariationalAsset, Error> { let loaded = WorkAsset::from_file(file, default_tag)?; loaded.export() } /// Generates a new `VariationalAsset` from a byte slice of glTF. /// /// If the provided asset implements `KHR_materials_variants`, then `default_tag` must /// either be empty or match the default tag within the asset. /// /// If the asset doesn't implement `KHR_materials_variants`, then the argument /// `default_tag` must be non-empty. If it does, then `default_tag` must either match /// what's in the asset, or else be empty. pub fn from_slice( gltf: &[u8], default_tag: Option<&Tag>, base_dir: Option<&Path>, ) -> Result<VariationalAsset, Error> { let loaded = WorkAsset::from_slice(gltf, default_tag, base_dir)?; loaded.export() } /// The generated glTF for this asset. Will always implement `KHR_materials_variants` /// and is always in binary (GLB) form. pub fn glb(&self) -> &[u8] { self.glb.as_slice() } /// The tag that stands in for any default material references in the asset glTF. pub fn default_tag(&self) -> &Tag { &self.default_tag } /// All the metadata generated for this asset. pub fn metadata(&self) -> &Metadata { &self.metadata } /// Melds one variational asset into another, combining material-switching tags /// on a per-mesh, per-primitive basis. /// /// Note that logically identical glTF objects may be bitwise quite different, e.g. /// because glTF array order is undefined, floating-point values are only equal to /// within some epsilon, the final global position of a vector can be the end /// result of very different transformations, and so on. /// /// Further, the whole point of this tool is to identify shared pieces of data /// between the two assets, keep only one, and redirect all references to it. /// pub fn meld<'a>( base: &'a VariationalAsset, other: &'a VariationalAsset, ) -> Result<VariationalAsset, Error> { let base = &WorkAsset::from_slice(base.glb(), Some(base.default_tag()), None)?; let other = &WorkAsset::from_slice(other.glb(), Some(other.default_tag()), None)?; let meld = WorkAsset::meld(base, other)?; meld.export() } } impl AssetSizes { /// Instantiate a new `AssetSizes` with the given texture byte count. pub fn new(texture_bytes: usize) -> AssetSizes { AssetSizes { texture_bytes } } /// Byte count for texture image data, in its raw encoded form. pub fn texture_bytes(&self) -> usize { self.texture_bytes } }
fn main() { println!("Hello 100 Days of Code"); }
pub struct Solution; impl Solution { pub fn max_profit(prices: Vec<i32>) -> i32 { let mut a = std::i32::MIN; let mut b = std::i32::MIN; let mut c = std::i32::MIN; let mut d = std::i32::MIN; for p in prices { a = a.max(-p); b = b.max(a + p); c = c.max(b - p); d = d.max(c + p); } 0.max(b).max(d) } } #[test] fn test0123() { assert_eq!(Solution::max_profit(vec![3, 3, 5, 0, 0, 3, 1, 4]), 6); assert_eq!(Solution::max_profit(vec![1, 2, 3, 4, 5]), 4); assert_eq!(Solution::max_profit(vec![7, 6, 4, 3, 1]), 0); assert_eq!(Solution::max_profit(vec![]), 0); assert_eq!(Solution::max_profit(vec![2, 1, 2, 0, 1]), 2); assert_eq!(Solution::max_profit(vec![6, 1, 3, 2, 4, 7]), 7); }
//! This crate provides various matcher algorithms for line oriented search given the query string. //! //! The matcher result consists of the score and the indices of matched items. //! //! Matching flow: //! //! // arc<dyn ClapItem> //! // | //! // ↓ //! // +----------------------+ //! // | InverseMatcher | //! // +----------------------+ //! // | //! // ↓ //! // +----------------------+ //! // | WordMatcher | //! // +----------------------+ //! // | //! // ↓ //! // +----------------------+ //! // | ExactMatcher | //! // +----------------------+ //! // | //! // ↓ //! // +----------------------+ //! // | FuzzyMatcher | //! // +----------------------+ //! // | MatchScope: extract the content to match. //! // | FuzzyAlgorithm: run the match algorithm on FuzzyText. //! // ↓ //! // +----------------------+ //! // | BonusMatcher | //! // +----------------------+ //! // | //! // ↓ //! // MatchResult { score, indices } //! mod algo; mod matchers; #[cfg(test)] mod tests; pub use self::algo::{substring, FuzzyAlgorithm}; pub use self::matchers::{ Bonus, BonusMatcher, ExactMatcher, FuzzyMatcher, InverseMatcher, WordMatcher, }; use std::path::Path; use std::sync::Arc; use types::{CaseMatching, ClapItem, FuzzyText, MatchedItem, Rank, RankCalculator, RankCriterion}; // Re-export types pub use types::{MatchResult, MatchScope, Query, Score}; #[derive(Debug, Clone, Default)] pub struct MatcherBuilder { bonuses: Vec<Bonus>, fuzzy_algo: FuzzyAlgorithm, match_scope: MatchScope, case_matching: CaseMatching, rank_criteria: Vec<RankCriterion>, } impl MatcherBuilder { /// Create a new matcher builder with a default configuration. pub fn new() -> Self { Self::default() } pub fn bonuses(mut self, bonuses: Vec<Bonus>) -> Self { self.bonuses = bonuses; self } pub fn fuzzy_algo(mut self, algo: FuzzyAlgorithm) -> Self { self.fuzzy_algo = algo; self } pub fn match_scope(mut self, match_scope: MatchScope) -> Self { self.match_scope = match_scope; self } pub fn case_matching(mut self, case_matching: CaseMatching) -> Self { self.case_matching = case_matching; self } pub fn rank_criteria(mut self, sort_criteria: Vec<RankCriterion>) -> Self { self.rank_criteria = sort_criteria; self } pub fn build(self, query: Query) -> Matcher { let Self { bonuses, fuzzy_algo, match_scope, case_matching, rank_criteria, } = self; let Query { word_terms, fuzzy_terms, exact_terms, inverse_terms, } = query; let inverse_matcher = InverseMatcher::new(inverse_terms); let word_matcher = WordMatcher::new(word_terms); let exact_matcher = ExactMatcher::new(exact_terms, case_matching); let fuzzy_matcher = FuzzyMatcher::new(match_scope, fuzzy_algo, fuzzy_terms, case_matching); let bonus_matcher = BonusMatcher::new(bonuses); let rank_calculator = if rank_criteria.is_empty() { RankCalculator::default() } else { RankCalculator::new(rank_criteria) }; Matcher { inverse_matcher, word_matcher, exact_matcher, fuzzy_matcher, bonus_matcher, rank_calculator, } } } #[derive(Debug, Clone, Default)] pub struct Matcher { inverse_matcher: InverseMatcher, word_matcher: WordMatcher, exact_matcher: ExactMatcher, fuzzy_matcher: FuzzyMatcher, bonus_matcher: BonusMatcher, rank_calculator: RankCalculator, } impl Matcher { // TODO: refactor this. pub fn match_scope(&self) -> MatchScope { self.fuzzy_matcher.match_scope } /// Actually performs the matching algorithm. pub fn match_item(&self, item: Arc<dyn ClapItem>) -> Option<MatchedItem> { let match_text = item.match_text(); if match_text.is_empty() { return None; } // Try the inverse terms against the full search line. if self.inverse_matcher.match_any(match_text) { return None; } let (word_score, word_indices) = if !self.word_matcher.is_empty() { self.word_matcher.find_matches(match_text)? } else { (Score::default(), Vec::new()) }; let (exact_score, mut exact_indices) = self.exact_matcher.find_matches(match_text)?; let (fuzzy_score, mut fuzzy_indices) = self.fuzzy_matcher.find_matches(&item)?; // Merge the results from multi matchers. let mut match_result = if fuzzy_indices.is_empty() { exact_indices.sort_unstable(); exact_indices.dedup(); let bonus_score = self.bonus_matcher .calc_item_bonus(&item, exact_score, &exact_indices); MatchResult::new(exact_score + bonus_score, exact_indices) } else { fuzzy_indices.sort_unstable(); fuzzy_indices.dedup(); let bonus_score = self.bonus_matcher .calc_item_bonus(&item, fuzzy_score, &fuzzy_indices); let mut indices = exact_indices; indices.extend(fuzzy_indices); indices.sort_unstable(); indices.dedup(); MatchResult::new(exact_score + bonus_score + fuzzy_score, indices) }; if !word_indices.is_empty() { match_result.add_score(word_score); match_result.extend_indices(word_indices); } let MatchResult { score, indices } = item.match_result_callback(match_result); let begin = indices.first().copied().unwrap_or(0); let end = indices.last().copied().unwrap_or(0); let length = item.raw_text().len(); let rank = self .rank_calculator .calculate_rank(score, begin, end, length); Some(MatchedItem::new(item, rank, indices)) } /// Actually performs the matching algorithm. pub fn match_file_result(&self, path: &Path, line: &str) -> Option<MatchedFileResult> { if line.is_empty() { return None; } let path = path.to_str()?; // Try the inverse terms against the full search line. if self.inverse_matcher.match_any(line) || self.inverse_matcher.match_any(path) { return None; } let (word_score, word_indices) = if !self.word_matcher.is_empty() { self.word_matcher.find_matches(line)? } else { (Score::default(), Vec::new()) }; let ((exact_score, exact_indices), exact_indices_in_path) = match self.exact_matcher.find_matches(path) { Some((score, indices)) => ((score, indices), true), None => (self.exact_matcher.find_matches(line)?, false), }; let fuzzy_text = FuzzyText::new(line, 0); let (mut fuzzy_score, mut fuzzy_indices) = self.fuzzy_matcher.match_fuzzy_text(&fuzzy_text)?; // Apply the word matcher against the line content. if !word_indices.is_empty() { fuzzy_score += word_score; fuzzy_indices.extend(word_indices) } // Merge the results from multi matchers. let (score, exact_indices, fuzzy_indices) = if fuzzy_indices.is_empty() { let bonus_score = self .bonus_matcher .calc_text_bonus(line, exact_score, &exact_indices); let mut exact_indices = exact_indices; exact_indices.sort_unstable(); exact_indices.dedup(); let score = exact_score + bonus_score; if exact_indices_in_path { (score, exact_indices, Vec::new()) } else { (score, Vec::new(), exact_indices) } } else { fuzzy_indices.sort_unstable(); fuzzy_indices.dedup(); let bonus_score = self .bonus_matcher .calc_text_bonus(line, fuzzy_score, &fuzzy_indices); let score = exact_score + bonus_score + fuzzy_score; if exact_indices_in_path { (score, exact_indices, fuzzy_indices) } else { let mut indices = exact_indices; indices.extend_from_slice(fuzzy_indices.as_slice()); indices.sort_unstable(); indices.dedup(); (score, Vec::new(), indices) } }; let begin = exact_indices .first() .copied() .unwrap_or_else(|| fuzzy_indices.first().copied().unwrap_or(0)); let end = fuzzy_indices .last() .copied() .unwrap_or_else(|| exact_indices.last().copied().unwrap_or(0)); let length = line.len(); let rank = self .rank_calculator .calculate_rank(score, begin, end, length); Some(MatchedFileResult { rank, exact_indices, fuzzy_indices, }) } } #[derive(Debug)] pub struct MatchedFileResult { pub rank: Rank, pub exact_indices: Vec<usize>, pub fuzzy_indices: Vec<usize>, }
use telegram_bot::*; pub type Coord = (usize, usize); pub struct InteractResult { pub update_text: Option<String>, pub update_board: Option<InlineKeyboardMarkup>, pub game_end: bool, } pub trait Game { fn interact(&mut self, coord: Coord, user: &User) -> Option<InteractResult>; } impl InteractResult { pub async fn reply_to(self, api: &Api, message: &Message) -> Result<(), Error> { if let Some(text) = self.update_text { if let Some(board) = self.update_board { api.send(message.edit_text(text).reply_markup(board)).await.map(|_| ()) } else { api.send(message.edit_text(text)).await.map(|_| ()) } } else { if let Some(board) = self.update_board { api.send(message.edit_reply_markup(Some(board))).await.map(|_| ()) } else { Ok(()) } } } }
/* A reduced test case for Issue #506, provided by Rob Arnold. */ native "rust" mod rustrt { fn task_yield(); } fn main() { spawn rustrt::task_yield(); }
#![allow(unused)] extern crate hackscanner_lib; use hackscanner_lib::file_finder::FileFinderTrait; use hackscanner_lib::*; use std::path::Path; use std::thread; pub fn get_test_dir() -> String { format!("{}/tests", env!("CARGO_MANIFEST_DIR")) } pub fn get_rules_multiple_results() -> Vec<Rule> { vec![Rule::new( "1", Severity::NOTICE, RawPath::with_path("tx_mocfilemanager"), None, ) .unwrap()] } pub fn get_rules_single_result() -> Vec<Rule> { vec![Rule::new( "2", Severity::NOTICE, RawPath::with_regex(r"\.tx_mocfilemanager"), None, ) .unwrap()] } pub fn assert_multiple_paths<D: DirEntryTrait>(matches: Vec<D>) { assert!(contains_path( &matches, format!( "{}{}", env!("CARGO_MANIFEST_DIR"), "/tests/resources/files/something.tx_mocfilemanager.php" ), )); assert!(contains_path( &matches, format!( "{}{}", env!("CARGO_MANIFEST_DIR"), "/tests/resources/files/tx_mocfilemanager.php" ), )); assert!(contains_path( &matches, format!( "{}{}", env!("CARGO_MANIFEST_DIR"), "/tests/resources/files/tx_mocfilemanager-test.sh" ), )); } pub fn assert_single_path<D: DirEntryTrait>(matches: Vec<D>) { assert_eq!(1, matches.len()); assert!(contains_path( &matches, format!( "{}{}", env!("CARGO_MANIFEST_DIR"), "/tests/resources/files/something.tx_mocfilemanager.php" ), )); assert!(!contains_path( &matches, format!( "{}{}", env!("CARGO_MANIFEST_DIR"), "/tests/resources/files/tx_mocfilemanager.php" ), )); assert!(!contains_path( &matches, format!( "{}{}", env!("CARGO_MANIFEST_DIR"), "/tests/resources/files/tx_mocfilemanager-test.sh" ), )); } pub fn test_multi_threading<D, F>(file_finder: F) where D: DirEntryTrait, F: FileFinderTrait<DirEntry = D> + 'static + ::std::marker::Send + Clone, { let mut threads = vec![]; for _ in 0..4 { let file_finder = file_finder.clone(); let handle = thread::spawn(move || { let rules = get_rules_single_result(); let matches = file_finder.find(get_test_dir(), &rules); assert_single_path(matches); }); threads.push(handle); } for thread in threads { let _ = thread.join(); } } pub fn contains_path<E: DirEntryTrait>(paths: &[E], test_path: String) -> bool { paths .iter() .find(|entry| { let path_as_string = entry.path().to_string_lossy().into_owned(); path_as_string == test_path }) .is_some() } pub fn get_entry_for_path<E: DirEntryTrait>(paths: &[E], test_path: String) -> Option<&E> { paths.iter().find(|entry| { let path_as_string = entry.path().to_string_lossy().into_owned(); path_as_string == test_path }) } //pub fn contains_path_ref<E: DirEntryTrait + ::std::marker::Sized>(paths: &Vec<&E>, test_path: String) -> bool { // paths.into_iter() // .find(|entry| { // let path_as_string = entry.path().to_string_lossy().into_owned(); // // path_as_string == test_path // }) // .is_some() //}
use std::io::{self, Read}; use minesweeper::{Configuration, check_configuration, ProbeResult}; fn main() -> io::Result<()> { println!("A Minesweeper board configuration consists of `_` (unknown), `?` (probe), number (number of mines around)."); println!("Enter a consistent Minesweeper board configuration with one probe (ending with EOF):"); let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer)?; let raw_conf = buffer.trim().to_string(); let conf = Configuration::from(raw_conf); let probe_result = match check_configuration(conf) { ProbeResult::Safe => "safe", ProbeResult::Unsafe => "unsafe", ProbeResult::Unknown => "unknown" }; println!("The probe is {}", probe_result); Ok(()) }
use crate::Error; pub fn register_app(app: super::Application) -> Result<(), Error> { use super::LaunchCommand; fn inner(app: super::Application) -> anyhow::Result<()> { use anyhow::Context as _; let mut desktop_path = app_dirs2::get_data_root(app_dirs2::AppDataType::UserData) .context("Unable to get the user data path")?; desktop_path.push("applications"); std::fs::create_dir_all(&desktop_path) .with_context(|| format!("unable to create \"{}\"", desktop_path.display()))?; { let md = std::fs::metadata(&desktop_path) .with_context(|| format!("unable to locate \"{}\"", desktop_path.display()))?; anyhow::ensure!( md.is_dir(), "\"{}\" was found, but it's not a directory", desktop_path.display() ); } desktop_path.push(format!("discord-{}.desktop", app.id)); let id = app.id; let name = app.name.unwrap_or_else(|| id.to_string()); std::fs::write( &desktop_path, &format!( r#"[Desktop Entry] Name={name} Exec={cmd} Type=Application NoDisplay=true Categories=Discord;Games; MimeType=x-scheme-handler/discord-{id}; "#, name = name, cmd = match app.command { LaunchCommand::Url(url) => format!("xdg-open {}", url), LaunchCommand::Bin { path, args } => { // So the docs say we can just use normal quoting rules for // the Exec command https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#exec-variables // but...https://askubuntu.com/questions/189822/how-to-escape-spaces-in-desktop-files-exec-line // seems to indicate things are "more complicated" but we'll // just go with what the spec says for now. Also paths with // spaces are wrong, so just don't do that. ;) super::create_command(path, args, "%u") } LaunchCommand::Steam(steam_id) => { format!("xdg-open steam://rungameid/{}", steam_id) } }, id = id, ), ) .context("unable to write desktop entry")?; // TODO: Would really rather not shell out to a separate program, // ideally would implement this in Rust, C code is located in https://gitlab.freedesktop.org/xdg/desktop-file-utils match std::process::Command::new("update-desktop-database") .arg(format!("{}", desktop_path.parent().unwrap().display())) .status() .context("failed to run update-desktop-database")? .code() { Some(0) => {} Some(e) => anyhow::bail!("failed to run update-desktop-database: {}", e), None => anyhow::bail!("failed to run update-desktop-database, interrupted by signal!"), } // Register the mime type with XDG, we do it manually rather than via // xdg-mime shelling out is lame...ignore the above // // ~/.config/mimeapps.list user overrides // /etc/xdg/mimeapps.list system-wide overrides // ~/.local/share/applications/mimeapps.list (deprecated) user overrides // /usr/local/share/applications/mimeapps.list // /usr/share/applications/mimeapps.list let mut mime_list_path = app_dirs2::data_root(app_dirs2::AppDataType::UserConfig) .context("unable to acquire user config directory")?; mime_list_path.push("mimeapps.list"); let discord_scheme = format!( "x-scheme-handler/discord-{id}=discord-{id}.desktop\n", id = app.id ); let new_list = if mime_list_path.exists() { let mut list = std::fs::read_to_string(&mime_list_path) .with_context(|| format!("unable to read {}", mime_list_path.display()))?; // Only add the scheme if it doesn't already exist if !list.contains(&discord_scheme) { list.find("[Default Applications]\n").map(|ind| { list.insert_str(ind + 23, &discord_scheme); list }) } else { None } } else { Some(format!("[Default Applications]\n{}", discord_scheme)) }; if let Some(new_list) = new_list { std::fs::write(&mime_list_path, new_list).with_context(|| { format!( "unable to add discord scheme to {}", mime_list_path.display() ) })?; } Ok(()) } inner(app).map_err(Error::AppRegistration) }
#[derive(Debug)] struct Token { value: i32 } pub fn fv_run() { println!("-------------------- {} --------------------", file!()); let incoming_tokens: Vec<Token> = vec![ Token { value: 5 }, Token { value: 10 }, Token { value: 12 }, Token { value: -3 }, Token { value: -4 }, Token { value: 2 }, Token { value: 0 }, ]; let is_odd = |t: &Token| -> bool { t.value % 2 == 0 }; let is_negative = |t: &Token| -> bool { t.value < 0 }; let odd_tokens: Vec<Token> = incoming_tokens.into_iter() .filter(|t| is_odd(t)) .collect(); println!("{:?}", &odd_tokens); let neg_tokens: Vec<Token> = odd_tokens.into_iter() .filter(|t| is_negative(t)) .collect(); println!("{:?}", &neg_tokens); }
use crate::types::GrinboxError; use crate::utils::bech32::CodingError; use failure::Fail; #[derive(Clone, Debug, Eq, Fail, PartialEq, Serialize, Deserialize)] pub enum ErrorKind { #[fail(display = "\x1b[31;1merror:\x1b[0m {}", 0)] GenericError(String), #[fail(display = "\x1b[31;1merror:\x1b[0m secp error")] SecpError, #[fail(display = "\x1b[31;1merror:\x1b[0m invalid chain type!")] InvalidChainType, #[fail(display = "\x1b[31;1merror:\x1b[0m invalid key!")] InvalidBech32Key, #[fail(display = "\x1b[31;1merror:\x1b[0m could not parse number from string!")] NumberParsingError, #[fail( display = "\x1b[31;1merror:\x1b[0m could not parse `{}` to a grinrelay address!", 0 )] GrinboxAddressParsingError(String), #[fail(display = "\x1b[31;1merror:\x1b[0m unable to encrypt message")] Encryption, #[fail(display = "\x1b[31;1merror:\x1b[0m unable to decrypt message")] Decryption, #[fail(display = "\x1b[31;1merror:\x1b[0m unable to verify proof")] VerifyProof, #[fail(display = "\x1b[31;1merror:\x1b[0m grinrelay websocket terminated unexpectedly!")] GrinboxWebsocketAbnormalTermination, #[fail(display = "\x1b[31;1merror:\x1b[0m grinrelay protocol error `{}`", 0)] GrinboxProtocolError(GrinboxError), #[fail(display = "\x1b[31;1merror:\x1b[0m bech32 coding error `{}`", 0)] Bech32Error(CodingError), }
//! Module providing the search capability using BAM/BAI files //! use std::{fs::File, path::Path}; use bam::bai::index::reference_sequence::bin::Chunk; use noodles_bam::{self as bam, bai}; use noodles_bgzf::VirtualPosition; use noodles_sam::{self as sam}; use crate::{ htsget::{Format, HtsGetError, Query, Response, Result, Url}, storage::{BytesRange, GetOptions, Storage, UrlOptions}, }; trait VirtualPositionExt { const MAX_BLOCK_SIZE: u64 = 65536; /// Get the starting bytes for a compressed BGZF block. fn bytes_range_start(&self) -> u64; /// Get the ending bytes for a compressed BGZF block. fn bytes_range_end(&self) -> u64; fn to_string(&self) -> String; } impl VirtualPositionExt for VirtualPosition { /// This is just an alias to compressed. Kept for consistency. fn bytes_range_start(&self) -> u64 { self.compressed() } /// The compressed part refers always to the beginning of a BGZF block. /// But when we need to translate it into a byte range, we need to make sure /// the reads falling inside that block are also included, which requires to know /// where that block ends, which is not trivial nor possible for the last block. /// The simple solution goes through adding the maximum BGZF block size, /// so we don't loose any read (although adding extra unneeded reads to the query results). fn bytes_range_end(&self) -> u64 { self.compressed() + Self::MAX_BLOCK_SIZE } fn to_string(&self) -> String { format!("{}/{}", self.compressed(), self.uncompressed()) } } pub(crate) struct BamSearch<'a, S> { storage: &'a S, } impl<'a, S> BamSearch<'a, S> where S: Storage + 'a, { /// 1 Mb const DEFAULT_BAM_HEADER_LENGTH: u64 = 1024 * 1024; // TODO find a number that makes more sense const MIN_SEQ_POSITION: u32 = 1; // 1-based pub fn new(storage: &'a S) -> Self { Self { storage } } pub fn search(&self, query: Query) -> Result<Response> { // TODO check class, for now we assume it is None or "body" let (bam_key, bai_key) = self.get_keys_from_id(query.id.as_str()); let bai_path = self.storage.get(&bai_key, GetOptions::default())?; let bai_index = bai::read(bai_path).map_err(|_| HtsGetError::io_error("Reading BAI"))?; let byte_ranges = match query.reference_name.as_ref() { None => self.get_byte_ranges_for_all_reads(bam_key.as_str(), &bai_index)?, Some(reference_name) if reference_name.as_str() == "*" => { self.get_byte_ranges_for_unmapped_reads(bam_key.as_str(), &bai_index)? } Some(reference_name) => self.get_byte_ranges_for_reference_name( bam_key.as_str(), reference_name, &bai_index, &query, )?, }; let urls = byte_ranges .into_iter() .map(|range| { let options = UrlOptions::default().with_range(range); self .storage .url(&bam_key, options) .map_err(HtsGetError::from) }) .collect::<Result<Vec<Url>>>()?; let format = query.format.unwrap_or(Format::Bam); Ok(Response::new(format, urls)) } /// Generate a key for the storage object from an ID /// This may involve a more complex transformation in the future, /// or even require custom implementations depending on the organizational structure /// For now there is a 1:1 mapping to the underlying files fn get_keys_from_id(&self, id: &str) -> (String, String) { let bam_key = format!("{}.bam", id); let bai_key = format!("{}.bai", bam_key); (bam_key, bai_key) } /// This returns mapped and placed unmapped ranges fn get_byte_ranges_for_all_reads( &self, bam_key: &str, bai_index: &bai::Index, ) -> Result<Vec<BytesRange>> { let mut byte_ranges: Vec<BytesRange> = Vec::new(); for reference_sequence in bai_index.reference_sequences() { if let Some(metadata) = reference_sequence.metadata() { let start_vpos = metadata.start_position(); let end_vpos = metadata.end_position(); byte_ranges.push( BytesRange::default() .with_start(start_vpos.bytes_range_start()) .with_end(end_vpos.bytes_range_end()), ); } } let unmapped_byte_ranges = self.get_byte_ranges_for_unmapped_reads(bam_key, bai_index)?; byte_ranges.extend(unmapped_byte_ranges.into_iter()); Ok(BytesRange::merge_all(byte_ranges)) } /// This returns only unplaced unmapped ranges fn get_byte_ranges_for_unmapped_reads( &self, bam_key: &str, bai_index: &bai::Index, ) -> Result<Vec<BytesRange>> { let last_interval = bai_index .reference_sequences() .iter() .rev() .find_map(|rs| rs.intervals().last().cloned()); let start = match last_interval { Some(start) => start, None => { let get_options = GetOptions::default().with_max_length(Self::DEFAULT_BAM_HEADER_LENGTH); let bam_path = self.storage.get(bam_key, get_options)?; let (bam_reader, _) = Self::read_bam_header(&bam_path)?; bam_reader.virtual_position() } }; // TODO get the end of the range from the BAM size (will require a new call in the Storage interface) Ok(vec![ BytesRange::default().with_start(start.bytes_range_start()) ]) } /// This returns reads for a given reference name and an optional sequence range fn get_byte_ranges_for_reference_name( &self, bam_key: &str, reference_name: &str, bai_index: &bai::Index, query: &Query, ) -> Result<Vec<BytesRange>> { let get_options = GetOptions::default().with_max_length(Self::DEFAULT_BAM_HEADER_LENGTH); let bam_path = self.storage.get(bam_key, get_options)?; let (_, bam_header) = Self::read_bam_header(&bam_path)?; let maybe_bam_ref_seq = bam_header.reference_sequences().get_full(reference_name); let byte_ranges = match maybe_bam_ref_seq { None => Err(HtsGetError::not_found(format!( "Reference name not found: {}", reference_name ))), Some((bam_ref_seq_idx, _, bam_ref_seq)) => { let seq_start = query.start.map(|start| start as i32); let seq_end = query.end.map(|end| end as i32); Self::get_byte_ranges_for_reference_sequence( bam_ref_seq, bam_ref_seq_idx, bai_index, seq_start, seq_end, ) } }?; Ok(byte_ranges) } fn read_bam_header<P: AsRef<Path>>(path: P) -> Result<(bam::Reader<File>, sam::Header)> { let mut bam_reader = File::open(path.as_ref()) .map(bam::Reader::new) .map_err(|_| HtsGetError::io_error("Reading BAM"))?; let bam_header = bam_reader .read_header() .map_err(|_| HtsGetError::io_error("Reading BAM header"))? .parse() .map_err(|_| HtsGetError::io_error("Parsing BAM header"))?; Ok((bam_reader, bam_header)) } fn get_byte_ranges_for_reference_sequence( bam_ref_seq: &sam::header::ReferenceSequence, bam_ref_seq_idx: usize, bai_index: &bai::Index, seq_start: Option<i32>, seq_end: Option<i32>, ) -> Result<Vec<BytesRange>> { let seq_start = seq_start.unwrap_or(Self::MIN_SEQ_POSITION as i32); let seq_end = seq_end.unwrap_or_else(|| bam_ref_seq.len()); let bai_ref_seq = bai_index .reference_sequences() .get(bam_ref_seq_idx) .ok_or_else(|| { HtsGetError::not_found(format!( "Reference not found in the BAI file: {} ({})", bam_ref_seq.name(), bam_ref_seq_idx )) })?; let chunks: Vec<Chunk> = bai_ref_seq .query(seq_start, seq_end) .into_iter() .flat_map(|bin| bin.chunks()) .cloned() .collect(); let min_offset = bai_ref_seq.min_offset(seq_start); let byte_ranges = bai::optimize_chunks(&chunks, min_offset) .into_iter() .map(|chunk| { BytesRange::default() .with_start(chunk.start().bytes_range_start()) .with_end(chunk.end().bytes_range_end()) }) .collect(); Ok(BytesRange::merge_all(byte_ranges)) } } #[cfg(test)] pub mod tests { use super::*; use crate::htsget::Headers; use crate::storage::local::LocalStorage; #[test] fn search_all_reads() { with_local_storage(|storage| { let search = BamSearch::new(&storage); let query = Query::new("htsnexus_test_NA12878"); let response = search.search(query); println!("{:#?}", response); let expected_response = Ok(Response::new( Format::Bam, vec![Url::new(expected_url(&storage)) .with_headers(Headers::default().with_header("Range", "bytes=4668-"))], )); assert_eq!(response, expected_response) }); } #[test] fn search_unmapped_reads() { with_local_storage(|storage| { let search = BamSearch::new(&storage); let query = Query::new("htsnexus_test_NA12878").with_reference_name("*"); let response = search.search(query); println!("{:#?}", response); let expected_response = Ok(Response::new( Format::Bam, vec![Url::new(expected_url(&storage)) .with_headers(Headers::default().with_header("Range", "bytes=2060795-"))], )); assert_eq!(response, expected_response) }); } #[test] fn search_reference_name_without_seq_range() { with_local_storage(|storage| { let search = BamSearch::new(&storage); let query = Query::new("htsnexus_test_NA12878").with_reference_name("20"); let response = search.search(query); println!("{:#?}", response); let expected_response = Ok(Response::new( Format::Bam, vec![Url::new(expected_url(&storage)) .with_headers(Headers::default().with_header("Range", "bytes=977196-2177677"))], )); assert_eq!(response, expected_response) }); } #[test] fn search_reference_name_with_seq_range() { with_local_storage(|storage| { let search = BamSearch::new(&storage); let query = Query::new("htsnexus_test_NA12878") .with_reference_name("11") .with_start(5015000) .with_end(5050000); let response = search.search(query); println!("{:#?}", response); let expected_response = Ok(Response::new( Format::Bam, vec![ Url::new(expected_url(&storage)) .with_headers(Headers::default().with_header("Range", "bytes=256721-693523")), Url::new(expected_url(&storage)) .with_headers(Headers::default().with_header("Range", "bytes=824361-889897")), Url::new(expected_url(&storage)) .with_headers(Headers::default().with_header("Range", "bytes=977196-1042732")), ], )); assert_eq!(response, expected_response) }); } pub fn with_local_storage(test: impl Fn(LocalStorage)) { let base_path = std::env::current_dir() .unwrap() .parent() .unwrap() .join("data"); test(LocalStorage::new(base_path).unwrap()) } pub fn expected_url(storage: &LocalStorage) -> String { format!( "file://{}", storage .base_path() .join("htsnexus_test_NA12878.bam") .to_string_lossy() ) } }
use std::cell::RefCell; use std::rc::Rc; extern crate rustyline; use rustyline::error::ReadlineError; use rustyline::Editor; #[macro_use] extern crate log; use ::lispy_rs::lispy::*; use ::lispy_rs::parser::*; use ::lispy_rs::*; /// Loads and evaluates files supplied in `files` /// TODO think of a better name. This one is inspired by Emacs. fn headless(files: Vec<String>, env: &mut Rc<RefCell<LEnv>>) -> Result<()> { for file in files.iter() { Lval::sexpr() .add(Lval::symbol("load")) .add(Lval::string(&file)) .eval(env) .map(|_| ())?; } Ok(()) } /// Enters a Lispy REPL fn repl(env: &mut Rc<RefCell<LEnv>>) -> Result<()> { info!("Lispy version {}", env!("CARGO_PKG_VERSION")); info!("Press Ctrl-C to Exit"); let mut rl = Editor::<()>::new(); if rl.load_history("history.txt").is_err() { info!("No previous history."); } loop { // We should first check if were interrupted by the user // and treat it as a special non-error case let line = { let read = rl.readline("lispy> "); match read { Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => break, _ => read, } }?; rl.add_history_entry(line.as_str()); // Ignore empty inputs if line.is_empty() { continue; } let result = parse(line.as_str()).and_then(|result| result.eval(env)); // We can't use ? operator because we don't want to treat evaluation errors as // fatal. We don't want to terminate the REPL, if eval() fails - we want to // print the error and continue. match result { Ok(result) => match result { Lval::Exit => break, _ => println!("{}", result), }, Err(e) => error!("{}", e), } } rl.save_history("history.txt")?; Ok(()) } fn main() -> Result<()> { env_logger::init(); // Initialize environment let mut env = Rc::new(RefCell::new(LEnv::default())); // Register built-in functions and types add_builtins(&mut env.borrow_mut()); // Check if user supplied any files to evaluate. If no - enter the REPL // if yes - evaluate them one by one and exit; let files = std::env::args().skip(1).collect::<Vec<String>>(); if files.is_empty() { repl(&mut env) } else { headless(files, &mut env) } }
use serde::{Deserialize, Serialize}; use serde_json; use crate::clients::client_utils::UrlHelper; use super::client_utils::error_conversion; #[allow(non_snake_case)] #[derive(Debug, Serialize, Deserialize)] pub struct CollectionOptions { disableMeta: bool, asyncListeners: bool, disableDeltaChangesApi: bool, disableChangesApi: bool, autoupdate: bool, disableFreeze: bool, clone: bool, removeIndices: bool, } #[allow(non_snake_case)] #[derive(Debug, Serialize, Deserialize)] pub struct Collection { pub name: String, pub options: CollectionOptions, pub cloneObjects: bool, pub maxId: u128, pub isIncremental: bool, } #[derive(Debug, Clone)] pub struct CollectionClient { url_helper: UrlHelper, } impl CollectionClient { pub fn new(hostname: String) -> Self { return CollectionClient { url_helper: UrlHelper::new(hostname) }; } pub fn list(&self, database: &str) -> Result<Vec<Collection>, String> { let url = self.url_helper.get_collection_url(database); let response = reqwest::blocking::get(url).map_err(|e| e.to_string())?; response.error_for_status_ref().map_err(error_conversion())?; return response .json::<Vec<Collection>>().map_err(error_conversion()); } pub fn create(&self, database: &str, collection_name: &str) -> Result<Collection, String> { let url = self.url_helper.get_name_collection_url(database, collection_name); let client = reqwest::blocking::Client::new(); let result = client.post(url) .send().map_err(error_conversion())?; result.error_for_status_ref().map_err(error_conversion())?; return result.json::<Collection>().map_err(error_conversion()); } pub fn delete(&self, database: &str, collection_name: &str) -> Result<Collection, String> { let url = self.url_helper.get_name_collection_url(database, collection_name); let client = reqwest::blocking::Client::new(); let response = client.post(url) .send() .map_err(error_conversion())?; response .error_for_status_ref() .map_err(error_conversion())?; return response .json::<Collection>() .map_err(error_conversion()); } pub fn get(&self, database: &str, collection_name: &str) -> Result<Collection, String> { let url = self.url_helper.get_name_collection_url(database, collection_name); let client = reqwest::blocking::Client::new(); let response = client.get(url) .send() .map_err(error_conversion())?; response .error_for_status_ref() .map_err(error_conversion())?; return response .json::<Collection>() .map_err(error_conversion()); } pub fn get_data(&self, database: &str, collection_name: &str) -> Result<Vec<serde_json::Value>, String> { let url = self.url_helper.get_data_url(database, collection_name); let client = reqwest::blocking::Client::new(); let response = client.get(url).send() .map_err(error_conversion())?; response .error_for_status_ref() .map_err(error_conversion())?; return response .json::<Vec<serde_json::Value>>() .map_err(error_conversion()); } pub fn get_by_thorid(&self, database: &str, collection_name: &str, thorid : &str) -> Result<serde_json::Value, String> { let url = format!("{}/{}", self.url_helper.get_data_url(database, collection_name), thorid); let client = reqwest::blocking::Client::new(); let response = client.get(url).send() .map_err(error_conversion())?; response .error_for_status_ref() .map_err(error_conversion())?; return response .json::<serde_json::Value>() .map_err(error_conversion()); } pub fn count(&self, database: &str, collection_name: &str) -> Result<u128, String> { let url = format!("{}/count", self.url_helper.get_name_collection_url(database, collection_name)); let client = reqwest::blocking::Client::new(); let response = client.get(url).send() .map_err(error_conversion())?; response .error_for_status_ref() .map_err(error_conversion())?; return response .json::<u128>() .map_err(error_conversion()); } pub fn insert_one(&self, database: &str, collection_name: &str, body: &str) -> Result<serde_json::Value, String> { let url = self.url_helper.get_data_url(database, collection_name); let b = serde_json::from_str::<serde_json::Value>(body) .map_err(|e| e.to_string())?; let response = reqwest::blocking::Client::new().post(url) .json(&b) .send() .map_err(error_conversion())?; response.error_for_status_ref().map_err(error_conversion())?; return response.json::<serde_json::Value>().map_err(error_conversion()); } pub fn clear(&self, database: &str, collection_name: &str) -> Result<Vec<serde_json::Value>, String> { let url = self.url_helper.get_data_url(database, collection_name); let response = reqwest::blocking::Client::new().delete(url) .send() .map_err(error_conversion())?; response.error_for_status_ref().map_err(error_conversion())?; return response.json::<Vec<serde_json::Value>>().map_err(error_conversion()); } pub fn insert(&self, database: &str, collection_name: &str, body: &str) -> Result<Vec<serde_json::Value>, String> { let url = format!("{}/insert", self.url_helper.get_name_collection_url(database, collection_name)); let b = serde_json::from_str::<Vec<serde_json::Value>>(body) .map_err(|e| e.to_string())?; let response = reqwest::blocking::Client::new().post(url) .json(&b) .send() .map_err(error_conversion())?; response.error_for_status_ref().map_err(error_conversion())?; return response.json::<Vec<serde_json::Value>>().map_err(error_conversion()); } }
#[test] fn test_vec_create() { let v = vec![1, 2, 3, 4, 5]; } #[test] fn test_vec_repeating() { let v = vec![0; 10]; // ten zeros } #[test] fn test_vec_access() { let v = vec![1, 2, 3, 4, 5]; let i: usize = 0; let j: i32 = 0; // indexing must be done with usize v[i]; // doesn't compile //v[j]; } #[test] #[should_panic] fn test_out_of_bounds() { let v = vec![1, 2, 3]; // should panic due to out of bounds println!("Item 7 is {}", v[7]); } #[test] fn test_handle_out_of_bounds() { let v = vec![1, 2, 3]; match v.get(7) { Some(x) => println!("Item 7 is {}", x), None => println!("Sorry, this vector is too short.") } } #[test] fn test_iteration() { let mut v = vec![1, 2, 3, 4, 5]; for i in &v { println!("A reference to {}", i); } for i in &mut v { println!("A mutable reference to {}", i); } for i in v { println!("Take ownership of the vector and its element {}", i); } }
// This file is part of syslog2. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog2/master/COPYRIGHT. No part of syslog2, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2016 The developers of syslog2. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog2/master/COPYRIGHT. extern crate libc; use std::default::Default; #[cfg(not(target_os = "windows"))] bitflags! { pub flags LogOptions: ::libc::c_int { const LOG_PID = ::libc::LOG_PID, const LOG_CONS = ::libc::LOG_CONS, const LOG_ODELAY = ::libc::LOG_ODELAY, const LOG_NDELAY = ::libc::LOG_NDELAY, const LOG_NOWAIT = ::libc::LOG_NOWAIT, #[cfg(not(target_os = "solaris"))] const LOG_PERROR = ::libc::LOG_PERROR, } } /// Windows flags are fakes to allow some compatibility. They are set to match the values on Linux. #[cfg(target_os = "windows")] bitflags! { pub flags LogOptions: libc::c_int { const LOG_PID = 0x01, const LOG_CONS = 0x02, const LOG_ODELAY = 0x04, const LOG_NDELAY = 0x08, const LOG_NOWAIT = 0x10, const LOG_PERROR = 0x20, } } impl LogOptions { pub fn clear(&mut self) { self.bits = 0; } /// Log also to standard error. Not supported on Solaris (will panic if yes is true) #[cfg(not(target_os = "solaris"))] pub fn logToStandardErrorAsWell(&mut self, yes: bool) { if yes { self.insert(LOG_PERROR); } else { self.remove(LOG_PERROR); } } } impl Default for LogOptions { /// Defaults to `LOG_CONS`, `LOG_NDELAY` and `LOG_PID` #[cfg(not(target_os = "android"))] #[inline(always)] fn default() -> LogOptions { LOG_CONS | LOG_NDELAY | LOG_PID } /// Android only supports LOG_PID and LOG_PERROR #[cfg(target_os = "android")] #[inline(always)] fn default() -> LogOptions { LOG_PID } }
#[doc = "Reader of register AHBRSTR"] pub type R = crate::R<u32, super::AHBRSTR>; #[doc = "Writer for register AHBRSTR"] pub type W = crate::W<u32, super::AHBRSTR>; #[doc = "Register AHBRSTR `reset()`'s with value 0"] impl crate::ResetValue for super::AHBRSTR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DMARST`"] pub type DMARST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMARST`"] pub struct DMARST_W<'a> { w: &'a mut W, } impl<'a> DMARST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `FLASHRST`"] pub type FLASHRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLASHRST`"] pub struct FLASHRST_W<'a> { w: &'a mut W, } impl<'a> FLASHRST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `CRCRST`"] pub type CRCRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CRCRST`"] pub struct CRCRST_W<'a> { w: &'a mut W, } impl<'a> CRCRST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `AESRST`"] pub type AESRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AESRST`"] pub struct AESRST_W<'a> { w: &'a mut W, } impl<'a> AESRST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `RNGRST`"] pub type RNGRST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RNGRST`"] pub struct RNGRST_W<'a> { w: &'a mut W, } impl<'a> RNGRST_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } impl R { #[doc = "Bit 0 - DMA1 reset"] #[inline(always)] pub fn dmarst(&self) -> DMARST_R { DMARST_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 8 - FLITF reset"] #[inline(always)] pub fn flashrst(&self) -> FLASHRST_R { FLASHRST_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 12 - CRC reset"] #[inline(always)] pub fn crcrst(&self) -> CRCRST_R { CRCRST_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 16 - AES hardware accelerator reset"] #[inline(always)] pub fn aesrst(&self) -> AESRST_R { AESRST_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 18 - Random number generator reset"] #[inline(always)] pub fn rngrst(&self) -> RNGRST_R { RNGRST_R::new(((self.bits >> 18) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - DMA1 reset"] #[inline(always)] pub fn dmarst(&mut self) -> DMARST_W { DMARST_W { w: self } } #[doc = "Bit 8 - FLITF reset"] #[inline(always)] pub fn flashrst(&mut self) -> FLASHRST_W { FLASHRST_W { w: self } } #[doc = "Bit 12 - CRC reset"] #[inline(always)] pub fn crcrst(&mut self) -> CRCRST_W { CRCRST_W { w: self } } #[doc = "Bit 16 - AES hardware accelerator reset"] #[inline(always)] pub fn aesrst(&mut self) -> AESRST_W { AESRST_W { w: self } } #[doc = "Bit 18 - Random number generator reset"] #[inline(always)] pub fn rngrst(&mut self) -> RNGRST_W { RNGRST_W { w: self } } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Data_Html")] pub mod Html; #[cfg(feature = "Data_Json")] pub mod Json; #[cfg(feature = "Data_Pdf")] pub mod Pdf; #[cfg(feature = "Data_Text")] pub mod Text; #[cfg(feature = "Data_Xml")] pub mod Xml;
use std::num::Wrapping; use crate::brainfuck_lexer::BFT; #[derive(Debug, Clone)] pub enum LoopCacheStatus { NotAvailable, Available(usize), Unknown } pub fn loop_cache_control(caching_reference: &mut Vec<LoopCacheStatus>, code_pointer: &mut usize, code: &[BFT], caching_data: &mut Vec<LoopCacheMeta>, memory: &mut Vec<Wrapping<i128>>, memory_pointer: &mut usize) { let current_cache_status = &caching_reference[*code_pointer]; match current_cache_status { LoopCacheStatus::Unknown => { caching_reference[*code_pointer] = LoopCacheStatus::NotAvailable; let mut code_pointer_local = *code_pointer + 1; let mut current_cache: LoopCacheMeta = LoopCacheMeta::new(); let mut code_char = code[code_pointer_local].to_owned(); let mut able_to_be_cached: bool = true; let starting_position = code_pointer_local; caching_reference[starting_position] = LoopCacheStatus::NotAvailable; while able_to_be_cached { match code_char { BFT::Move(count) => current_cache.memory_pointer += count as i128, BFT::MemChange(count) => current_cache.change_memory(count as i128), _ => { able_to_be_cached = false; } } code_pointer_local += 1; code_char = code[code_pointer_local].to_owned(); if let BFT::LoopEnd(_) = code_char { break; } } current_cache.control_pointer = current_cache.memory_pointer as i128; if current_cache.control_pointer != 0 { able_to_be_cached = false; } if able_to_be_cached { current_cache.code_pointer = code_pointer_local as i128; current_cache.loop_starting_loc = starting_position as i128; caching_data.push(current_cache.clone()); caching_reference[starting_position - 1] = LoopCacheStatus::Available(caching_data.len()); //One more than actual index use_loop_cache( &caching_data[caching_data.len() as usize - 1], memory, memory_pointer, code_pointer, ); } }, LoopCacheStatus::Available(x) => { use_loop_cache( &caching_data[x - 1], memory, memory_pointer, code_pointer, ); }, _ => {} } } fn use_loop_cache( caching_data: &LoopCacheMeta, memory: &mut Vec<Wrapping<i128>>, memory_pointer: &mut usize, code_pointer: &mut usize, ) { let mut i: usize = 0; let control_memory = memory[*memory_pointer + caching_data.control_pointer as usize]; while i < caching_data.instructions.len() { while (caching_data.instructions[i].0 + *memory_pointer as i128) as usize >= memory.len() - 1 { memory.push(Wrapping(0)); } memory[(caching_data.instructions[i].0 + *memory_pointer as i128) as usize] += Wrapping(caching_data.instructions[i].1 as i128 * control_memory.0); i += 1; } memory[*memory_pointer + caching_data.control_pointer as usize] = Wrapping(0); *memory_pointer += caching_data.memory_pointer as usize; *code_pointer = caching_data.code_pointer as usize; } #[derive(Debug, Clone)] pub struct LoopCacheMeta { //Data Obj for the loop cache algorithm instructions: Vec<(i128, i128)>, control_pointer: i128, code_pointer: i128, memory_pointer: i128, loop_starting_loc: i128, } impl LoopCacheMeta { pub fn change_memory(&mut self, amount: i128) { self.instructions.push((self.memory_pointer, amount)); } pub fn new() -> LoopCacheMeta { LoopCacheMeta { instructions: vec![], code_pointer: 0, control_pointer: 0, memory_pointer: 0, loop_starting_loc: 0, } } } impl Default for LoopCacheMeta { fn default() -> Self { LoopCacheMeta::new() } }