text
stringlengths
8
4.13M
#[doc = "Reader of register MISR"] pub type R = crate::R<u32, super::MISR>; #[doc = "Reader of field `ISEM0`"] pub type ISEM0_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM1`"] pub type ISEM1_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM2`"] pub type ISEM2_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM3`"] pub type ISEM3_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM4`"] pub type ISEM4_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM5`"] pub type ISEM5_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM6`"] pub type ISEM6_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM7`"] pub type ISEM7_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM8`"] pub type ISEM8_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM9`"] pub type ISEM9_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM10`"] pub type ISEM10_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM11`"] pub type ISEM11_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM12`"] pub type ISEM12_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM13`"] pub type ISEM13_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM14`"] pub type ISEM14_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM15`"] pub type ISEM15_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM16`"] pub type ISEM16_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM17`"] pub type ISEM17_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM18`"] pub type ISEM18_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM19`"] pub type ISEM19_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM20`"] pub type ISEM20_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM21`"] pub type ISEM21_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM22`"] pub type ISEM22_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM23`"] pub type ISEM23_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM24`"] pub type ISEM24_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM25`"] pub type ISEM25_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM26`"] pub type ISEM26_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM27`"] pub type ISEM27_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM28`"] pub type ISEM28_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM29`"] pub type ISEM29_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM30`"] pub type ISEM30_R = crate::R<bool, bool>; #[doc = "Reader of field `ISEM31`"] pub type ISEM31_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem0(&self) -> ISEM0_R { ISEM0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem1(&self) -> ISEM1_R { ISEM1_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem2(&self) -> ISEM2_R { ISEM2_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem3(&self) -> ISEM3_R { ISEM3_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem4(&self) -> ISEM4_R { ISEM4_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem5(&self) -> ISEM5_R { ISEM5_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem6(&self) -> ISEM6_R { ISEM6_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem7(&self) -> ISEM7_R { ISEM7_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem8(&self) -> ISEM8_R { ISEM8_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem9(&self) -> ISEM9_R { ISEM9_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem10(&self) -> ISEM10_R { ISEM10_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem11(&self) -> ISEM11_R { ISEM11_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem12(&self) -> ISEM12_R { ISEM12_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem13(&self) -> ISEM13_R { ISEM13_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem14(&self) -> ISEM14_R { ISEM14_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem15(&self) -> ISEM15_R { ISEM15_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem16(&self) -> ISEM16_R { ISEM16_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem17(&self) -> ISEM17_R { ISEM17_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem18(&self) -> ISEM18_R { ISEM18_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem19(&self) -> ISEM19_R { ISEM19_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem20(&self) -> ISEM20_R { ISEM20_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem21(&self) -> ISEM21_R { ISEM21_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem22(&self) -> ISEM22_R { ISEM22_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem23(&self) -> ISEM23_R { ISEM23_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem24(&self) -> ISEM24_R { ISEM24_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem25(&self) -> ISEM25_R { ISEM25_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem26(&self) -> ISEM26_R { ISEM26_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem27(&self) -> ISEM27_R { ISEM27_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 28 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem28(&self) -> ISEM28_R { ISEM28_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem29(&self) -> ISEM29_R { ISEM29_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem30(&self) -> ISEM30_R { ISEM30_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - masked interrupt(N) semaphore n status bit after enable (mask)"] #[inline(always)] pub fn isem31(&self) -> ISEM31_R { ISEM31_R::new(((self.bits >> 31) & 0x01) != 0) } }
fn main() { let text = "YELLOW SUBMARINE"; println!("{:?}",pad(text.as_bytes().to_vec(),10)); } fn pad(text: Vec<u8>, length: u8) -> Vec<u8>{ let mut padded = text.clone(); let mut i = 1; while (length as i8*i-text.len() as i8) <0 { i += 1; } let padding = length*i as u8-text.len() as u8; for i in text.len()..(padding as usize +text.len()){ padded.push(padding); } padded }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use libc::*; use super::super::qlib::linux::time; use super::super::qlib::common::*; pub struct HostTime {} impl HostTime { pub fn Realtime() -> Result<i64> { let ts = time::Timespec::default(); let res = unsafe { clock_gettime(CLOCK_REALTIME, &ts as *const _ as u64 as *mut timespec) as i64 }; if res == -1 { return Err(Error::SysError(errno::errno().0)) } return Ok(ts.ToNs()?) } pub fn Monotime() -> Result<i64> { let ts = time::Timespec::default(); let res = unsafe { clock_gettime(CLOCK_MONOTONIC, &ts as *const _ as u64 as *mut timespec) as i64 }; if res == -1 { return Err(Error::SysError(errno::errno().0)) } return Ok(ts.ToNs()?) } }
use eventual::{Future, Async, Complete}; use mio::{Token, EventLoop, Sender, TryRead, TryWrite, EventSet}; use mio::tcp::TcpStream; use mio::util::Slab; use mio; use std::net::{SocketAddr,IpAddr,Ipv4Addr}; use std::collections::BTreeMap; use std::borrow::Cow; use std::error::Error; use def::CqlEvent; use error::{RCResult,RCError,RCErrorType}; use error::RCErrorType::*; use connection::{Connection,CqlMsg,connect}; pub struct ConnectionPool { token_by_ip: BTreeMap<IpAddr,Token>, connections: Slab<Connection>, event_handler: Sender<CqlEvent> } impl ConnectionPool { pub fn new(event_handler: Sender<CqlEvent>) -> ConnectionPool { ConnectionPool { token_by_ip: BTreeMap::new(), connections: Slab::new_starting_at(Token(1), 32768), event_handler: event_handler } } fn get_connection_with_ip(&mut self,event_loop: &mut EventLoop<ConnectionPool>,address:&IpAddr) -> Result<&mut Connection,&'static str>{ //println!("[ConnectionPool::get_connection_with_ip]"); if !self.exists_connection_by_ip(address){ //let token = self.create_connection(event_loop,address).unwrap(); //return self.find_connection_by_token(token) return Err("Connection doesn't exist") } else { self.find_connection_by_ip(address) } } fn create_connection(&mut self,event_loop: &mut EventLoop<ConnectionPool>,address:&IpAddr) -> RCResult<Token>{ //println!("[ConnectionPool::create_connection]"); let mut conn = try_rc!(connect(SocketAddr::new(address.clone(),9042), None, event_loop, self.event_handler.clone()),"Failed connecting"); let token = try_rc!(self.add_connection(address.clone(),conn),"Failed adding a new connection"); Ok(token) } fn add_connection(&mut self, address:IpAddr,connection: Connection)-> RCResult<Token>{ //println!("[ConnectionPool::add_connection]"); let result = self.connections.insert(connection); match result{ Ok(token) => { { let conn = self.find_connection_by_token(token).ok().expect("Couldn't unwrap the connection"); //println!("Setting token {:?}",token); conn.set_token(token); } self.token_by_ip.insert(address,token); Ok(token) }, Err(err) => { Err(RCError::new("Credential should be provided for authentication", ReadError)) } } } fn exists_connection_by_ip(&mut self,address:&IpAddr) -> bool{ self.token_by_ip.contains_key(address) } fn exists_connection_by_token(&mut self,token: Token) -> bool{ self.connections.contains(token) } fn find_connection_by_ip(&mut self,address:&IpAddr) -> Result<&mut Connection,&'static str>{ //println!("[ConnectionPool::find_connection_by_ip]"); if !self.connections.is_empty() { // Needs to be improved let conn = Ok(self.connections.get_mut(self.token_by_ip .get(address).unwrap().clone() ).unwrap()); //println!("{:?}",conn ); return conn; } Err("There is no connection found") } fn find_connection_by_token(&mut self,token: Token) -> Result<&mut Connection,&'static str>{ //println!("[ConnectionPool::find_connection_by_token]"); if !self.connections.is_empty() { let conn = Ok(self.connections.get_mut(token).unwrap()); //println!("Connection with {:?} -> {:?}",token,conn ); return conn; } Err("There is no connection found") } } impl mio::Handler for ConnectionPool { type Timeout = (); // Left one is the internal Handler message type and // right one is our defined type type Message = CqlMsg; // Push pending messages to be send across the event // loop. Only change state in case it is waiting fn notify(&mut self, event_loop: &mut EventLoop<ConnectionPool>, msg: CqlMsg) { //println!("[ConnectionPool::notify]"); //self.show_connections(); let ip = &msg.get_ip(); //let complete = msg.get_complete(); match msg { CqlMsg::Request{..} => { let mut result = self.get_connection_with_ip(event_loop,ip); // Here is where we should do create a new connection if it doesn't exist. // Connect, then send_startup with the queue_message match result { Ok(conn) =>{ match conn.insert_request(msg){ Ok(_) => conn.reregister(event_loop,EventSet::writable()), Err(err) => (), } }, Err(err) =>{ //TO-DO //Complete all requests with connection error } } }, CqlMsg::Connect{..} => { let mut result = self.create_connection(event_loop,ip); match result { Ok(token) =>{ let conn = self.find_connection_by_ip(ip).unwrap(); conn.insert_request(msg); conn.reregister(event_loop,EventSet::writable()); }, Err(ref err) =>{ msg.complete((Err(RCError::new("Couldn't connect to host", RCErrorType::ConnectionError)))); } } }, CqlMsg::Shutdown => { event_loop.shutdown(); }, } } fn ready(&mut self, event_loop: &mut EventLoop<ConnectionPool>, token: Token, events: EventSet) { //println!("[Connection::ready]"); //println!("Assigned token is: {:?}",token); //println!("Events: {:?}",events); let mut connection = self.find_connection_by_token(token).ok().expect("Couldn't get connection"); if events.is_readable() { //println!(" connection-EventSet::Readable"); connection.read(event_loop); let pair = connection.read_cql_response(); let response = pair.0; let is_event = pair.1; //println!("Response from event_loop: {:?}",response); //println!("Handling response.."); connection.handle_response(response,event_loop,is_event); connection.reset_response(); } if events.is_writable() && connection.are_pendings_send(){ //println!(" connection-EventSet::Writable"); connection.write(event_loop); } //println!("[Connection::Ended ready]"); } }
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use crate::lexer::preprocessor::context::PreprocContext; use crate::lexer::{Lexer, LocToken, Token}; use crate::parser::attributes::{Attributes, AttributesParser}; use bitflags::bitflags; use super::super::r#type::CVQualifier; use super::decl::{NoPtrDeclaratorParser, TypeDeclarator}; use super::specifier::Specifier; use crate::parser::r#type::{BaseType, Type}; bitflags! { pub struct MSModifier: u8 { const RESTRICT = 0b1; const UPTR = 0b10; const SPTR = 0b100; const UNALIGNED = 0b1000; } } impl MSModifier { pub(crate) fn from_tok(&mut self, tok: &Token) -> bool { match tok { Token::MSRestrict => { *self |= MSModifier::RESTRICT; true } Token::MSUptr => { *self |= MSModifier::UPTR; true } Token::MSSptr => { *self |= MSModifier::SPTR; true } Token::MSUnaligned | Token::MS1Unaligned => { *self |= MSModifier::UNALIGNED; true } _ => false, } } } #[derive(Clone, Debug, PartialEq)] pub enum PtrKind { Pointer, Reference, RValue, } impl PtrKind { pub(crate) fn from_tok(tok: &Token) -> Option<Self> { match tok { Token::Star => Some(PtrKind::Pointer), Token::And => Some(PtrKind::Reference), Token::AndAnd => Some(PtrKind::RValue), _ => None, } } pub(crate) fn is_ptr(tok: &Token) -> bool { match tok { Token::Star | Token::And | Token::AndAnd => true, _ => false, } } } #[derive(Clone, Debug, PartialEq)] pub struct Pointer { pub kind: PtrKind, pub attributes: Option<Attributes>, pub cv: CVQualifier, pub ms: MSModifier, } pub type Pointers = Vec<Pointer>; pub struct PointerDeclaratorParser<'a, 'b, PC: PreprocContext> { lexer: &'b mut Lexer<'a, PC>, } impl<'a, 'b, PC: PreprocContext> PointerDeclaratorParser<'a, 'b, PC> { pub(crate) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self { Self { lexer } } pub(crate) fn parse( self, tok: Option<LocToken>, hint: Option<PtrKind>, ) -> (Option<LocToken>, Option<Pointers>) { let tok = tok.unwrap_or_else(|| self.lexer.next_useful()); let mut ptrs = Vec::new(); let mut kind = if let Some(hint) = hint { hint } else { let kind = PtrKind::from_tok(&tok.tok); if let Some(kind) = kind { kind } else { return (Some(tok), None); } }; let tok = loop { let ap = AttributesParser::new(self.lexer); let (tok, attributes) = ap.parse(None); let mut tok = tok.unwrap_or_else(|| self.lexer.next_useful()); let mut cv = CVQualifier::empty(); let mut ms = MSModifier::empty(); while cv.from_tok(&tok.tok) || ms.from_tok(&tok.tok) { tok = self.lexer.next_useful(); } ptrs.push(Pointer { kind, attributes, cv, ms, }); kind = if let Some(kind) = PtrKind::from_tok(&tok.tok) { kind } else { break tok; }; }; (Some(tok), Some(ptrs)) } } pub struct ParenPointerDeclaratorParser<'a, 'b, PC: PreprocContext> { lexer: &'b mut Lexer<'a, PC>, } impl<'a, 'b, PC: PreprocContext> ParenPointerDeclaratorParser<'a, 'b, PC> { pub(super) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self { Self { lexer } } pub(super) fn parse( self, tok: Option<LocToken>, ) -> (Option<LocToken>, (Option<TypeDeclarator>, bool)) { let tok = tok.unwrap_or_else(|| self.lexer.next_useful()); if tok.tok != Token::LeftParen { return (Some(tok), (None, false)); } // The previous token was a parenthesis // so we can have some params (function type, e.g. int * (int, int))) // or a function/array pointer let pdp = PointerDeclaratorParser::new(self.lexer); let (tok, pointers) = pdp.parse(None, None); if pointers.is_some() { let npp = NoPtrDeclaratorParser::new(self.lexer); let typ = Type { base: BaseType::None, cv: CVQualifier::empty(), pointers, }; let (tok, decl) = npp.parse(tok, typ, Specifier::empty(), false); let tok = tok.unwrap_or_else(|| self.lexer.next_useful()); if tok.tok != Token::RightParen { unreachable!("Invalid token in function pointer: {:?}", tok); } (None, (decl, false)) } else { // we've function params (tok, (None, true)) } } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type CompositionConditionalValue = *mut ::core::ffi::c_void; pub type CompositionInteractionSourceCollection = *mut ::core::ffi::c_void; pub type ICompositionInteractionSource = *mut ::core::ffi::c_void; pub type IInteractionTrackerOwner = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct InteractionBindingAxisModes(pub u32); impl InteractionBindingAxisModes { pub const None: Self = Self(0u32); pub const PositionX: Self = Self(1u32); pub const PositionY: Self = Self(2u32); pub const Scale: Self = Self(4u32); } impl ::core::marker::Copy for InteractionBindingAxisModes {} impl ::core::clone::Clone for InteractionBindingAxisModes { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct InteractionChainingMode(pub i32); impl InteractionChainingMode { pub const Auto: Self = Self(0i32); pub const Always: Self = Self(1i32); pub const Never: Self = Self(2i32); } impl ::core::marker::Copy for InteractionChainingMode {} impl ::core::clone::Clone for InteractionChainingMode { fn clone(&self) -> Self { *self } } pub type InteractionSourceConfiguration = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct InteractionSourceMode(pub i32); impl InteractionSourceMode { pub const Disabled: Self = Self(0i32); pub const EnabledWithInertia: Self = Self(1i32); pub const EnabledWithoutInertia: Self = Self(2i32); } impl ::core::marker::Copy for InteractionSourceMode {} impl ::core::clone::Clone for InteractionSourceMode { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct InteractionSourceRedirectionMode(pub i32); impl InteractionSourceRedirectionMode { pub const Disabled: Self = Self(0i32); pub const Enabled: Self = Self(1i32); } impl ::core::marker::Copy for InteractionSourceRedirectionMode {} impl ::core::clone::Clone for InteractionSourceRedirectionMode { fn clone(&self) -> Self { *self } } pub type InteractionTracker = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct InteractionTrackerClampingOption(pub i32); impl InteractionTrackerClampingOption { pub const Auto: Self = Self(0i32); pub const Disabled: Self = Self(1i32); } impl ::core::marker::Copy for InteractionTrackerClampingOption {} impl ::core::clone::Clone for InteractionTrackerClampingOption { fn clone(&self) -> Self { *self } } pub type InteractionTrackerCustomAnimationStateEnteredArgs = *mut ::core::ffi::c_void; pub type InteractionTrackerIdleStateEnteredArgs = *mut ::core::ffi::c_void; pub type InteractionTrackerInertiaModifier = *mut ::core::ffi::c_void; pub type InteractionTrackerInertiaMotion = *mut ::core::ffi::c_void; pub type InteractionTrackerInertiaNaturalMotion = *mut ::core::ffi::c_void; pub type InteractionTrackerInertiaRestingValue = *mut ::core::ffi::c_void; pub type InteractionTrackerInertiaStateEnteredArgs = *mut ::core::ffi::c_void; pub type InteractionTrackerInteractingStateEnteredArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct InteractionTrackerPositionUpdateOption(pub i32); impl InteractionTrackerPositionUpdateOption { pub const Default: Self = Self(0i32); pub const AllowActiveCustomScaleAnimation: Self = Self(1i32); } impl ::core::marker::Copy for InteractionTrackerPositionUpdateOption {} impl ::core::clone::Clone for InteractionTrackerPositionUpdateOption { fn clone(&self) -> Self { *self } } pub type InteractionTrackerRequestIgnoredArgs = *mut ::core::ffi::c_void; pub type InteractionTrackerValuesChangedArgs = *mut ::core::ffi::c_void; pub type InteractionTrackerVector2InertiaModifier = *mut ::core::ffi::c_void; pub type InteractionTrackerVector2InertiaNaturalMotion = *mut ::core::ffi::c_void; pub type VisualInteractionSource = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct VisualInteractionSourceRedirectionMode(pub i32); impl VisualInteractionSourceRedirectionMode { pub const Off: Self = Self(0i32); pub const CapableTouchpadOnly: Self = Self(1i32); pub const PointerWheelOnly: Self = Self(2i32); pub const CapableTouchpadAndPointerWheel: Self = Self(3i32); } impl ::core::marker::Copy for VisualInteractionSourceRedirectionMode {} impl ::core::clone::Clone for VisualInteractionSourceRedirectionMode { fn clone(&self) -> Self { *self } }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use std::vec; use common_catalog::table::Table; use common_catalog::table_context::TableContext; use common_exception::Result; use common_expression::types::number::UInt64Type; use common_expression::types::NumberDataType; use common_expression::types::StringType; use common_expression::utils::FromData; use common_expression::DataBlock; use common_expression::FromOptData; use common_expression::TableDataType; use common_expression::TableField; use common_expression::TableSchemaRefExt; use common_meta_app::principal::StageType; use common_meta_app::schema::TableIdent; use common_meta_app::schema::TableInfo; use common_meta_app::schema::TableMeta; use common_users::UserApiProvider; use crate::table::AsyncOneBlockSystemTable; use crate::table::AsyncSystemTable; pub struct StagesTable { table_info: TableInfo, } #[async_trait::async_trait] impl AsyncSystemTable for StagesTable { const NAME: &'static str = "system.stages"; fn get_table_info(&self) -> &TableInfo { &self.table_info } async fn get_full_data(&self, ctx: Arc<dyn TableContext>) -> Result<DataBlock> { let tenant = ctx.get_tenant(); let stages = UserApiProvider::instance().get_stages(&tenant).await?; let mut name: Vec<Vec<u8>> = Vec::with_capacity(stages.len()); let mut stage_type: Vec<Vec<u8>> = Vec::with_capacity(stages.len()); let mut stage_params: Vec<Vec<u8>> = Vec::with_capacity(stages.len()); let mut copy_options: Vec<Vec<u8>> = Vec::with_capacity(stages.len()); let mut file_format_options: Vec<Vec<u8>> = Vec::with_capacity(stages.len()); let mut comment: Vec<Vec<u8>> = Vec::with_capacity(stages.len()); let mut number_of_files: Vec<Option<u64>> = Vec::with_capacity(stages.len()); let mut creator: Vec<Option<Vec<u8>>> = Vec::with_capacity(stages.len()); for stage in stages.into_iter() { name.push(stage.stage_name.clone().into_bytes()); stage_type.push(stage.stage_type.clone().to_string().into_bytes()); stage_params.push(format!("{:?}", stage.stage_params).into_bytes()); copy_options.push(format!("{:?}", stage.copy_options).into_bytes()); file_format_options.push(format!("{:?}", stage.file_format_options).into_bytes()); // TODO(xuanwo): we will remove this line. match stage.stage_type { StageType::LegacyInternal | StageType::Internal | StageType::User => { number_of_files.push(Some(stage.number_of_files)); } StageType::External => { number_of_files.push(None); } }; match stage.creator { Some(c) => { creator.push(Some(c.to_string().into_bytes().to_vec())); } None => { creator.push(None); } } comment.push(stage.comment.clone().into_bytes()); } Ok(DataBlock::new_from_columns(vec![ StringType::from_data(name), StringType::from_data(stage_type), StringType::from_data(stage_params), StringType::from_data(copy_options), StringType::from_data(file_format_options), UInt64Type::from_opt_data(number_of_files), StringType::from_opt_data(creator), StringType::from_data(comment), ])) } } impl StagesTable { pub fn create(table_id: u64) -> Arc<dyn Table> { let schema = TableSchemaRefExt::create(vec![ TableField::new("name", TableDataType::String), TableField::new("stage_type", TableDataType::String), TableField::new("stage_params", TableDataType::String), TableField::new("copy_options", TableDataType::String), TableField::new("file_format_options", TableDataType::String), // NULL for external stage TableField::new( "number_of_files", TableDataType::Nullable(Box::new(TableDataType::Number(NumberDataType::UInt64))), ), TableField::new( "creator", TableDataType::Nullable(Box::new(TableDataType::String)), ), TableField::new("comment", TableDataType::String), ]); let table_info = TableInfo { desc: "'system'.'stages'".to_string(), name: "stages".to_string(), ident: TableIdent::new(table_id, 0), meta: TableMeta { schema, engine: "SystemStages".to_string(), ..Default::default() }, ..Default::default() }; AsyncOneBlockSystemTable::create(StagesTable { table_info }) } }
#![allow(non_camel_case_types)] #![allow(unused_unsafe)] use crate::ctx::WasiCtx; use crate::fdentry::Descriptor; use crate::host; use crate::sys::errno_from_host; use crate::sys::host_impl; use std::fs::File; use std::os::windows::prelude::{AsRawHandle, FromRawHandle}; use std::path::{Component, Path}; /// Normalizes a path to ensure that the target path is located under the directory provided. pub(crate) fn path_get( wasi_ctx: &WasiCtx, dirfd: host::__wasi_fd_t, _dirflags: host::__wasi_lookupflags_t, path: &str, needed_base: host::__wasi_rights_t, needed_inheriting: host::__wasi_rights_t, needs_final_component: bool, ) -> Result<(File, String), host::__wasi_errno_t> { if path.contains("\0") { // if contains NUL, return EILSEQ return Err(host::__WASI_EILSEQ); } let dirfe = wasi_ctx.get_fd_entry(dirfd, needed_base, needed_inheriting)?; let dirfd = match &*dirfe.fd_object.descriptor { Descriptor::File(f) => f.try_clone().map_err(|err| { err.raw_os_error() .map_or(host::__WASI_EBADF, errno_from_host) })?, _ => return Err(host::__WASI_EBADF), }; // Stack of directory handles. Index 0 always corresponds with the directory provided // to this function. Entering a directory causes a handle to be pushed, while handling // ".." entries causes an entry to be popped. Index 0 cannot be popped, as this would imply // escaping the base directory. let mut dir_stack = vec![dirfd]; // Stack of paths left to process. This is initially the `path` argument to this function, but // any symlinks we encounter are processed by pushing them on the stack. let mut path_stack = vec![path.to_owned()]; loop { match path_stack.pop() { Some(cur_path) => { // dbg!(&cur_path); let ends_with_slash = cur_path.ends_with("/"); let mut components = Path::new(&cur_path).components(); let head = match components.next() { None => return Err(host::__WASI_ENOENT), Some(p) => p, }; let tail = components.as_path(); if tail.components().next().is_some() { let mut tail = host_impl::path_from_host(tail.as_os_str())?; if ends_with_slash { tail.push_str("/"); } path_stack.push(tail); } match head { Component::Prefix(_) | Component::RootDir => { // path is absolute! return Err(host::__WASI_ENOTCAPABLE); } Component::CurDir => { // "." so skip continue; } Component::ParentDir => { // ".." so pop a dir let _ = dir_stack.pop().ok_or(host::__WASI_ENOTCAPABLE)?; // we're not allowed to pop past the original directory if dir_stack.is_empty() { return Err(host::__WASI_ENOTCAPABLE); } } Component::Normal(head) => { let mut head = host_impl::path_from_host(head)?; if ends_with_slash { // preserve trailing slash head.push_str("/"); } // should the component be a directory? it should if there is more path left to process, or // if it has a trailing slash and `needs_final_component` is not set if !path_stack.is_empty() || (ends_with_slash && !needs_final_component) { match winx::file::openat( dir_stack .last() .ok_or(host::__WASI_ENOTCAPABLE)? .as_raw_handle(), head.as_str(), winx::file::AccessRight::FILE_GENERIC_READ, winx::file::CreationDisposition::OPEN_EXISTING, winx::file::FlagsAndAttributes::FILE_FLAG_BACKUP_SEMANTICS, ) { Ok(new_dir) => { dir_stack.push(unsafe { File::from_raw_handle(new_dir) }); continue; } Err(e) => { return Err(host_impl::errno_from_win(e)); } } } else { // we're done return Ok((dir_stack.pop().ok_or(host::__WASI_ENOTCAPABLE)?, head)); } } } } None => { // no further components to process. means we've hit a case like "." or "a/..", or if the // input path has trailing slashes and `needs_final_component` is not set return Ok(( dir_stack.pop().ok_or(host::__WASI_ENOTCAPABLE)?, String::from("."), )); } } } }
use rocket_contrib::json::JsonValue; use crate::db; use crate::util; pub fn start_server() { log::info!("Starting HTTP service..."); rocket::ignite() .mount("/", routes![init_sh, pubkey_users]) .launch(); } /// curl -H "Content-Type: text/plain" http://127.0.0.1:8000/init.sh #[get("/init.sh")] fn init_sh() -> String { log::debug!("init_sh() entering..."); let server_base_url: String = util::get_env_var("SLACKRYPT_BASE_URL", "127.0.0.1:8000"); util::get_init_sh_cmd(format!("https://{}", &server_base_url).as_str()) } /// curl -H "Content-Type: application/json" http://127.0.0.1:8000/pubkey/users #[get("/pubkey/users")] fn pubkey_users() -> Option<JsonValue> { log::debug!("pubkey_users() entering..."); let users: Vec<String> = db::get_users_all().unwrap(); if users.is_empty() { None } else { Some(json!(users)) } }
pub fn count_primes(n: i32) -> i32 { let mut acc = 0; if n <= 1 { return acc; } let mut n = n; while n > 1 { if n % 2 != 0 { acc += 1; } n -= 1; } acc } #[cfg(test)] mod count_primes_tests { use super::*; #[test] fn count_primes_tests_one() { // arrange let test = 10; // act let result = count_primes(test); // assert assert_eq!(result, 4); } }
use std::borrow::Cow; use crate::spec::TargetOptions; use Arch::*; #[allow(dead_code, non_camel_case_types)] #[derive(Copy, Clone)] pub enum Arch { Armv7, Armv7s, Arm64, I386, X86_64, X86_64_macabi, Arm64_macabi, Arm64_sim, } fn target_abi(arch: Arch) -> &'static str { match arch { Armv7 | Armv7s | Arm64 | I386 | X86_64 => "", X86_64_macabi | Arm64_macabi => "macabi", Arm64_sim => "sim", } } fn target_cpu(arch: Arch) -> &'static str { match arch { Armv7 => "cortex-a8", // iOS7 is supported on iPhone 4 and higher Armv7s => "cortex-a9", Arm64 => "apple-a7", I386 => "yonah", X86_64 => "core2", X86_64_macabi => "core2", Arm64_macabi => "apple-a12", Arm64_sim => "apple-a12", } } fn link_env_remove(arch: Arch) -> Vec<Cow<'static, str>> { match arch { Armv7 | Armv7s | Arm64 | I386 | X86_64 | Arm64_sim => { vec!["MACOSX_DEPLOYMENT_TARGET".into()] } X86_64_macabi | Arm64_macabi => vec!["IPHONEOS_DEPLOYMENT_TARGET".into()], } } pub fn opts(os: &'static str, arch: Arch) -> TargetOptions { TargetOptions { abi: target_abi(arch).into(), cpu: target_cpu(arch).into(), dynamic_linking: false, link_env_remove: link_env_remove(arch), has_thread_local: false, ..super::apple_base::opts(os) } }
#[doc = "Reader of register CSR"] pub type R = crate::R<u32, super::CSR>; #[doc = "Writer for register CSR"] pub type W = crate::W<u32, super::CSR>; #[doc = "Register CSR `reset()`'s with value 0"] impl crate::ResetValue for super::CSR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TSUSP`"] pub type TSUSP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TSUSP`"] pub struct TSUSP_W<'a> { w: &'a mut W, } impl<'a> TSUSP_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 << 31)) | (((value as u32) & 0x01) << 31); self.w } } #[doc = "Reader of field `CAIF`"] pub type CAIF_R = crate::R<bool, bool>; #[doc = "Reader of field `CAIE`"] pub type CAIE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CAIE`"] pub struct CAIE_W<'a> { w: &'a mut W, } impl<'a> CAIE_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 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `RCH13`"] pub type RCH13_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RCH13`"] pub struct RCH13_W<'a> { w: &'a mut W, } impl<'a> RCH13_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 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `FCH8`"] pub type FCH8_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FCH8`"] pub struct FCH8_W<'a> { w: &'a mut W, } impl<'a> FCH8_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 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `FCH3`"] pub type FCH3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FCH3`"] pub struct FCH3_W<'a> { w: &'a mut W, } impl<'a> FCH3_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 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `OUTSEL`"] pub type OUTSEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `OUTSEL`"] pub struct OUTSEL_W<'a> { w: &'a mut W, } impl<'a> OUTSEL_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 & !(0x07 << 21)) | (((value as u32) & 0x07) << 21); self.w } } #[doc = "Reader of field `INSEL`"] pub type INSEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `INSEL`"] pub struct INSEL_W<'a> { w: &'a mut W, } impl<'a> INSEL_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 & !(0x07 << 18)) | (((value as u32) & 0x07) << 18); self.w } } #[doc = "Reader of field `WNDWE`"] pub type WNDWE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WNDWE`"] pub struct WNDWE_W<'a> { w: &'a mut W, } impl<'a> WNDWE_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 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `VREFOUTEN`"] pub type VREFOUTEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `VREFOUTEN`"] pub struct VREFOUTEN_W<'a> { w: &'a mut W, } impl<'a> VREFOUTEN_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 `CMP2OUT`"] pub type CMP2OUT_R = crate::R<bool, bool>; #[doc = "Reader of field `SPEED`"] pub type SPEED_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SPEED`"] pub struct SPEED_W<'a> { w: &'a mut W, } impl<'a> SPEED_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 `CMP1OUT`"] pub type CMP1OUT_R = crate::R<bool, bool>; #[doc = "Reader of field `SW1`"] pub type SW1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SW1`"] pub struct SW1_W<'a> { w: &'a mut W, } impl<'a> SW1_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 } } #[doc = "Reader of field `CMP1EN`"] pub type CMP1EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CMP1EN`"] pub struct CMP1EN_W<'a> { w: &'a mut W, } impl<'a> CMP1EN_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 `PD400K`"] pub type PD400K_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PD400K`"] pub struct PD400K_W<'a> { w: &'a mut W, } impl<'a> PD400K_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 `PD10K`"] pub type PD10K_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PD10K`"] pub struct PD10K_W<'a> { w: &'a mut W, } impl<'a> PD10K_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 `PU400K`"] pub type PU400K_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PU400K`"] pub struct PU400K_W<'a> { w: &'a mut W, } impl<'a> PU400K_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `PU10K`"] pub type PU10K_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PU10K`"] pub struct PU10K_W<'a> { w: &'a mut W, } impl<'a> PU10K_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 } } impl R { #[doc = "Bit 31 - Suspend Timer Mode"] #[inline(always)] pub fn tsusp(&self) -> TSUSP_R { TSUSP_R::new(((self.bits >> 31) & 0x01) != 0) } #[doc = "Bit 30 - Channel acquisition interrupt flag"] #[inline(always)] pub fn caif(&self) -> CAIF_R { CAIF_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 29 - Channel Acquisition Interrupt Enable / Clear"] #[inline(always)] pub fn caie(&self) -> CAIE_R { CAIE_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 28 - Select GPIO port PC3 as re-routed ADC input channel CH13."] #[inline(always)] pub fn rch13(&self) -> RCH13_R { RCH13_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 27 - Select GPIO port PB0 as fast ADC input channel CH8."] #[inline(always)] pub fn fch8(&self) -> FCH8_R { FCH8_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 26 - Select GPIO port PA3 as fast ADC input channel CH3."] #[inline(always)] pub fn fch3(&self) -> FCH3_R { FCH3_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bits 21:23 - Comparator 2 output selection"] #[inline(always)] pub fn outsel(&self) -> OUTSEL_R { OUTSEL_R::new(((self.bits >> 21) & 0x07) as u8) } #[doc = "Bits 18:20 - Inverted input selection"] #[inline(always)] pub fn insel(&self) -> INSEL_R { INSEL_R::new(((self.bits >> 18) & 0x07) as u8) } #[doc = "Bit 17 - Window mode enable"] #[inline(always)] pub fn wndwe(&self) -> WNDWE_R { WNDWE_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - VREFINT output enable"] #[inline(always)] pub fn vrefouten(&self) -> VREFOUTEN_R { VREFOUTEN_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 13 - Comparator 2 output"] #[inline(always)] pub fn cmp2out(&self) -> CMP2OUT_R { CMP2OUT_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 12 - Comparator 2 speed mode"] #[inline(always)] pub fn speed(&self) -> SPEED_R { SPEED_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 7 - Comparator 1 output"] #[inline(always)] pub fn cmp1out(&self) -> CMP1OUT_R { CMP1OUT_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 5 - SW1 analog switch enable"] #[inline(always)] pub fn sw1(&self) -> SW1_R { SW1_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - Comparator 1 enable"] #[inline(always)] pub fn cmp1en(&self) -> CMP1EN_R { CMP1EN_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - 400 kO pull-down resistor"] #[inline(always)] pub fn pd400k(&self) -> PD400K_R { PD400K_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - 10 kO pull-down resistor"] #[inline(always)] pub fn pd10k(&self) -> PD10K_R { PD10K_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - 400 kO pull-up resistor"] #[inline(always)] pub fn pu400k(&self) -> PU400K_R { PU400K_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - 10 kO pull-up resistor"] #[inline(always)] pub fn pu10k(&self) -> PU10K_R { PU10K_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 31 - Suspend Timer Mode"] #[inline(always)] pub fn tsusp(&mut self) -> TSUSP_W { TSUSP_W { w: self } } #[doc = "Bit 29 - Channel Acquisition Interrupt Enable / Clear"] #[inline(always)] pub fn caie(&mut self) -> CAIE_W { CAIE_W { w: self } } #[doc = "Bit 28 - Select GPIO port PC3 as re-routed ADC input channel CH13."] #[inline(always)] pub fn rch13(&mut self) -> RCH13_W { RCH13_W { w: self } } #[doc = "Bit 27 - Select GPIO port PB0 as fast ADC input channel CH8."] #[inline(always)] pub fn fch8(&mut self) -> FCH8_W { FCH8_W { w: self } } #[doc = "Bit 26 - Select GPIO port PA3 as fast ADC input channel CH3."] #[inline(always)] pub fn fch3(&mut self) -> FCH3_W { FCH3_W { w: self } } #[doc = "Bits 21:23 - Comparator 2 output selection"] #[inline(always)] pub fn outsel(&mut self) -> OUTSEL_W { OUTSEL_W { w: self } } #[doc = "Bits 18:20 - Inverted input selection"] #[inline(always)] pub fn insel(&mut self) -> INSEL_W { INSEL_W { w: self } } #[doc = "Bit 17 - Window mode enable"] #[inline(always)] pub fn wndwe(&mut self) -> WNDWE_W { WNDWE_W { w: self } } #[doc = "Bit 16 - VREFINT output enable"] #[inline(always)] pub fn vrefouten(&mut self) -> VREFOUTEN_W { VREFOUTEN_W { w: self } } #[doc = "Bit 12 - Comparator 2 speed mode"] #[inline(always)] pub fn speed(&mut self) -> SPEED_W { SPEED_W { w: self } } #[doc = "Bit 5 - SW1 analog switch enable"] #[inline(always)] pub fn sw1(&mut self) -> SW1_W { SW1_W { w: self } } #[doc = "Bit 4 - Comparator 1 enable"] #[inline(always)] pub fn cmp1en(&mut self) -> CMP1EN_W { CMP1EN_W { w: self } } #[doc = "Bit 3 - 400 kO pull-down resistor"] #[inline(always)] pub fn pd400k(&mut self) -> PD400K_W { PD400K_W { w: self } } #[doc = "Bit 2 - 10 kO pull-down resistor"] #[inline(always)] pub fn pd10k(&mut self) -> PD10K_W { PD10K_W { w: self } } #[doc = "Bit 1 - 400 kO pull-up resistor"] #[inline(always)] pub fn pu400k(&mut self) -> PU400K_W { PU400K_W { w: self } } #[doc = "Bit 0 - 10 kO pull-up resistor"] #[inline(always)] pub fn pu10k(&mut self) -> PU10K_W { PU10K_W { w: self } } }
pub mod aot_generator; pub mod code_builder; pub mod compile; pub mod context; pub mod gcc;
#![feature(box_syntax)] #[cfg(test)] extern crate quickcheck; #[cfg(test)] #[macro_use(quickcheck)] extern crate quickcheck_macros; use std::cell::RefCell; use std::cmp::Ordering; use std::rc::Rc; use leetcode_rust::bst::BinarySearchTree; // Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub parent: Option<Rc<RefCell<TreeNode>>>, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { pub fn new(val: i32) -> Self { TreeNode { val, parent: None, left: None, right: None, } } } #[derive(Debug, PartialEq, Eq)] struct SimpleBinarySearchTree { root: Option<Rc<RefCell<TreeNode>>>, } impl SimpleBinarySearchTree { fn new() -> Self { SimpleBinarySearchTree { root: None } } } impl BinarySearchTree for SimpleBinarySearchTree { fn add(&mut self, item: i32) -> Result<(), &str> { let mut node: &mut _ = &mut self.root; loop { match node { None => { std::mem::replace(node, Some(Rc::new(RefCell::new(TreeNode::new(item))))); return Ok(()); } Some(n) => { let ordering = n.borrow().val.cmp(&item); node = match ordering { Ordering::Less => unsafe { &mut (*n.as_ptr()).right }, Ordering::Greater => unsafe { &mut (*n.as_ptr()).left }, Ordering::Equal => { return Err("不能插入一样的值2"); } } } } } } fn remove(&mut self, item: i32) -> bool { fn remove_node(node: &mut Option<Rc<RefCell<TreeNode>>>) { let n = node.as_mut().unwrap(); if n.borrow_mut().left.is_none() { let right = std::mem::replace(&mut n.borrow_mut().right, None); std::mem::replace(node, right); } else if n.borrow_mut().right.is_none() { let left = std::mem::replace(&mut n.borrow_mut().left, None); std::mem::replace(node, left); } else { let i = n.borrow().left.as_ref().unwrap().borrow().val; n.borrow_mut().val = i; remove_node(&mut n.borrow_mut().left); } } fn remove(node: &mut Option<Rc<RefCell<TreeNode>>>, val: i32) -> bool { match node { Some(n) => { let ordering = n.borrow().val.cmp(&val); match ordering { Ordering::Less => remove(&mut n.borrow_mut().right, val), Ordering::Greater => remove(&mut n.borrow_mut().left, val), Ordering::Equal => { remove_node(node); true } } } None => false, } } remove(&mut self.root, item) } fn find(&self, item: i32) -> bool { fn find(node: &Option<Rc<RefCell<TreeNode>>>, val: i32) -> bool { match node { Some(n) => match n.borrow().val.cmp(&val) { Ordering::Less => find(&n.borrow().right, val), Ordering::Greater => find(&n.borrow().left, val), Ordering::Equal => true, }, None => false, } } let node: &Option<Rc<RefCell<TreeNode>>> = &self.root; find(node, item) } } fn main() { let mut tree: Box<dyn BinarySearchTree> = box SimpleBinarySearchTree::new(); tree.add(2).unwrap(); tree.add(1).unwrap(); tree.add(3).unwrap(); assert_eq!(true, tree.find(2)); dbg!(&tree); tree.remove(2); dbg!(&tree); assert_eq!(false, tree.find(2)); tree.add(2); dbg!(&tree); assert_eq!(true, tree.find(2)); } #[cfg(test)] mod tests { use leetcode_rust::bst::BinarySearchTree; use test_case::test_case; use crate::SimpleBinarySearchTree; #[test_case(0, 0)] #[test_case(1, 1)] #[test_case(2, 1)] #[test_case(3, 2)] #[test_case(4, 3)] #[test_case(5, 5)] #[test_case(6, 8)] #[test_case(7, 13)] #[test_case(8, 21)] fn fibonacci_test(input: u32, expected: u32) { let _a = 0; fn fibonacci(n: u32) -> u32 { if n >= 30 { return 0; } match n { 0 => 0, 1 => 1, _ => fibonacci(n - 1) + fibonacci(n - 2), } } println!("{} --> {}", input, fibonacci(input)); assert_eq!(expected, fibonacci(input)) } #[test] fn test() { let mut tree: Box<dyn BinarySearchTree> = box SimpleBinarySearchTree::new(); assert_eq!(false, tree.find(1)); assert_eq!(false, tree.find(2)); assert_eq!(false, tree.find(3)); assert_eq!(false, tree.find(0)); tree.add(1).unwrap(); assert_eq!(true, tree.find(1)); tree.add(2).unwrap(); assert_eq!(true, tree.find(2)); tree.add(3).unwrap(); assert_eq!(true, tree.find(3)); assert_eq!(true, tree.find(1)); assert_eq!(true, tree.find(2)); assert_eq!(true, tree.find(3)); tree.remove(1); assert_eq!(false, tree.find(1)); tree.remove(2); assert_eq!(false, tree.find(2)); tree.remove(3); assert_eq!(false, tree.find(3)); assert_eq!(false, tree.find(0)); } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[cfg(feature = "Gaming_Input")] pub mod Input; #[cfg(feature = "Gaming_Preview")] pub mod Preview; #[cfg(feature = "Gaming_UI")] pub mod UI; #[cfg(feature = "Gaming_XboxLive")] pub mod XboxLive;
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use failure::{err_msg, format_err, Error}; pub fn expect_eq<T>(expected: &T, actual: &T) -> Result<(), Error> where T: std::fmt::Debug + std::cmp::PartialEq, { if *expected == *actual { Ok(()) } else { Err(err_msg(format!("failed - expected '{:#?}', found: '{:#?}'", expected, actual))) } } /// Converts any Result type into a Result that returns an Error type that can be tried. This is /// useful for many FIDL messages that have error reply types that don't derive Fail. pub fn expect_ok<T, E>(result: Result<T, E>, msg: &str) -> Result<T, Error> where E: std::fmt::Debug, { result.map_err(|e| format_err!("{}: {:?}", msg, e)) } macro_rules! expect_eq { ($expected:expr, $actual:expr) => { expect_eq(&$expected, &$actual) }; } macro_rules! expect_true { ($condition:expr) => { if $condition { Ok(()) } else { Err(err_msg(format!("condition is not true: {}", stringify!($condition)))) } as Result<(), Error> } }
pub mod add; pub mod apply; pub mod current; pub mod edit; pub mod init; pub mod list; pub mod remove; pub mod show;
pub mod redis_cache_decorators; pub use redis_cache_decorators::*;
use crate::*; use std::cell::RefCell; mod control_test; use control_test::*; mod thread_test; use thread_test::*; mod freeing_test; use freeing_test::*; mod other; #[derive(Default)] pub struct TestControlPanel { window: Window, layout: FlexboxLayout, controls_test_button: Button, thread_test_button: Button, free_test_button: Button, controls_tests: ControlsTest, thread_tests: ThreadTest, freeing_tests: FreeingTest, } mod test_control_panel_ui { use super::*; use crate::{NativeUi, NwgError}; use std::rc::Rc; use std::ops::Deref; pub struct TestControlPanelUi { inner: Rc<TestControlPanel>, default_handler: RefCell<Vec<EventHandler>> } impl NativeUi<TestControlPanelUi> for TestControlPanel { fn build_ui(mut data: TestControlPanel) -> Result<TestControlPanelUi, NwgError> { use crate::Event as E; // Controls Window::builder() .flags(WindowFlags::WINDOW) .size((200, 200)) .position((1100, 300)) .title("Tests Control Panel") .build(&mut data.window)?; Button::builder() .text("Control tests") .focus(true) .parent(&data.window) .build(&mut data.controls_test_button)?; Button::builder() .text("Thread tests") .parent(&data.window) .build(&mut data.thread_test_button)?; Button::builder() .text("Freeing") .parent(&data.window) .build(&mut data.free_test_button)?; // Partials ControlsTest::build_partial(&mut data.controls_tests, Some(&data.window))?; ThreadTest::build_partial(&mut data.thread_tests, Some(&data.window))?; FreeingTest::build_partial(&mut data.freeing_tests, Some(&data.window))?; // Wrap-up let ui = TestControlPanelUi { inner: Rc::new(data), default_handler: Default::default() }; // Events let mut window_handles = vec![&ui.window.handle]; window_handles.append(&mut ui.controls_tests.handles()); window_handles.append(&mut ui.thread_tests.handles()); window_handles.append(&mut ui.freeing_tests.handles()); for handle in window_handles.iter() { let evt_ui = Rc::downgrade(&ui.inner); let handle_events = move |evt, evt_data, handle| { if let Some(evt_ui) = evt_ui.upgrade() { evt_ui.controls_tests.process_event(evt, &evt_data, handle); evt_ui.thread_tests.process_event(evt, &evt_data, handle); evt_ui.freeing_tests.process_event(evt, &evt_data, handle); match evt { E::OnButtonClick => if &handle == &evt_ui.controls_test_button { show_control_test(&evt_ui); } else if &handle == &evt_ui.thread_test_button { show_thread_test(&evt_ui); } else if &handle == &evt_ui.free_test_button { show_freeing_test(&evt_ui); }, E::OnInit => if handle == evt_ui.window.handle { show(&evt_ui); }, E::OnWindowClose => if handle == evt_ui.window.handle { close(); }, _ => {} } } }; let handler = full_bind_event_handler(handle, handle_events); ui.default_handler.borrow_mut().push(handler); } // Layouts FlexboxLayout::builder() .parent(&ui.window) .flex_direction(stretch::style::FlexDirection::Column) .child(&ui.controls_test_button) .child(&ui.thread_test_button) .child(&ui.free_test_button) .build(&ui.layout)?; Ok(ui) } } impl Drop for TestControlPanelUi { fn drop(&mut self) { self.freeing_tests.destroy(); let mut handlers = self.default_handler.borrow_mut(); let handlers_count = handlers.len(); for handler in handlers.drain(0..handlers_count) { unbind_event_handler(&handler); } } } impl Deref for TestControlPanelUi { type Target = TestControlPanel; fn deref(&self) -> &TestControlPanel { &self.inner } } } fn show_control_test(app: &TestControlPanel) { app.controls_tests.window.set_visible(true); app.controls_tests.panel.set_visible(true); app.controls_tests.window.set_focus(); } fn show_thread_test(app: &TestControlPanel) { app.thread_tests.window.set_visible(true); app.thread_tests.window.set_focus(); } fn show_freeing_test(app: &TestControlPanel) { app.freeing_tests.window.set_visible(true); app.freeing_tests.window.set_focus(); } fn show(app: &TestControlPanel) { let text = "Hello World from Native windows GUI!"; Clipboard::set_data_text(&app.window, text); assert!(Some(text) == Clipboard::data_text(&app.window).as_ref().map(|s| s as &str)); app.window.set_visible(true); } fn close() { stop_thread_dispatch(); } #[test] fn everything() { #[cfg(feature = "high-dpi")] { unsafe { crate::win32::high_dpi::set_dpi_awareness(); } } init().expect("Failed to init Native Windows GUI"); Font::set_global_family("Segoe UI").expect("Failed to set default font"); let app = TestControlPanel::build_ui(Default::default()).expect("Failed to build UI"); app.window.set_focus(); dispatch_thread_events(); }
#[derive(Debug,Clone,Copy,PartialEq,Eq,Hash)] pub struct Health { pub hp: usize, pub max_hp: usize, pub temp_hp: usize, } impl Health { pub fn take_damage(&mut self, mut amount: usize) { if self.temp_hp > 0 { if amount > self.temp_hp { amount -= self.temp_hp; self.temp_hp = 0; } else { self.temp_hp -= amount; return; } } self.hp = self.hp.saturating_sub(amount); } pub fn take_healing(&mut self, amount: usize) { self.hp = std::cmp::min(self.hp + amount, self.max_hp); } pub fn take_temp_hp(&mut self, amount: usize) { self.temp_hp = std::cmp::max(self.temp_hp, amount); } pub fn damaged(&self, amount: usize) -> Health { let mut res = self.clone(); res.take_damage(amount); res } pub fn healed(&self, amount: usize) -> Health { let mut res = self.clone(); res.take_healing(amount); res } pub fn with_temp_hp(&self, amount: usize) -> Health { let mut res = self.clone(); res.take_temp_hp(amount); res } pub fn is_down(&self) -> bool { // The latter SHOULD imply the former, but... self.hp == 0 && self.temp_hp == 0 } }
use yew::prelude::*; use yewdux::prelude::*; use yewtil::NeqAssign; use yew_router::components::RouterAnchor; use crate::app::AppRoute; use yew::services::storage::{ StorageService, Area, }; use crate::store::reducer_account::{ AppDispatch, DataAccountAction, // DataAccount, }; use crate::types::{ ResponseLogin, }; pub struct LandingPageNavTop { dispatch: AppDispatch, } pub enum Msg {} const KEY: &str = "telkom-domain"; impl Component for LandingPageNavTop { type Message = Msg; type Properties = AppDispatch; fn create(dispatch: Self::Properties, _: ComponentLink<Self>) -> Self { LandingPageNavTop { dispatch } } fn update(&mut self, _msg: Self::Message) -> ShouldRender { true } fn change(&mut self, dispatch: Self::Properties) -> ShouldRender { self.dispatch.neq_assign(dispatch) // false } fn view(&self) -> Html { let signup = self.dispatch.callback(|_| { let newdata = ResponseLogin { username: String::from("Batman"), email: String::from("bat@mail.com"), token: String::from("token-batman"), }; // SET LOCALSTORAGE let mut storage = StorageService::new(Area::Local).expect("storage was disabled"); let localstorage_data: Result<String, anyhow::Error> = Ok(String::from("datafromnavbar")); storage.store(KEY, localstorage_data); DataAccountAction::Update(newdata) }); type Anchor = RouterAnchor<AppRoute>; html! { <div> <div class="d-flex justify-content-between bg-dark" style="padding:0 7rem; font-size: 13px;" > <div class="d-flex" > <a class="py-3 text-decoration-none text-light" > <span> {"Okta Completes Acquisition of Auth0"} </span> <span class="ms-3" > {"Learn more"} <i class="bi bi-arrow-right" style="font-size: 13px;"></i> </span> </a> </div> <div class="d-flex justify-content-between align-items-center" > <Anchor route=AppRoute::LoginPage classes="text-decoration-none text-light px-2 link-primary pe-auto" > {"Login"} </Anchor> <a class="dropdown-toggle text-decoration-none text-light px-2 d-flex align-items-center" href="#" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <i class="bi bi-globe me-2 fs-5"></i> {"Language"} </a> <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink"> <li><a class="dropdown-item" href="#">{"Deutsch"}</a></li> <li><a class="dropdown-item" href="#">{"English"}</a></li> <li><a class="dropdown-item" href="#">{"Français"}</a></li> <li><a class="dropdown-item" href="#">{"日本語"}</a></li> </ul> </div> </div> <div class="d-flex justify-content-between border-bottom" style="padding:0 7rem; font-size: 13px;" > <div class="nav-item justify-content-center my-auto py-4 d-flex align-items-center"> <div class="bg-white p-1 pt-0 rounded me-1 navtop-logo d-inline"> <img class="" src="https://i.stack.imgur.com/3Stuq.png" style="width: 23px;" /> </div> <span class="fs-4 fw-bold" >{"Telkom Domain"}</span> </div> <div class="d-flex justify-content-between align-items-center" > <button onclick=signup type="button" class="btn btn-outline-dark">{"Sign Up"}</button> </div> </div> </div> } } }
use std::fs::read_to_string; use std::path::Path; use itertools::Itertools; use lazy_static::lazy_static lazy_static! { static ref REGEXP: Regex = Regex::new(r"(?P<x>\d+)-(?P<y>\d+) (?P<letter>[a-z]): (?P<password>[a-z]+)").unwrap(); } fn parse_input(input: &str) -> Vec<i32> { input.lines() .filter_map(|n| n.parse::<i32>().ok()) .collect() } #[cfg(test)] mod tests { use super::*; fn common_solution(k_combinations: usize) { let input = parse_input(include_str!("../input/day01.txt")); match combination_summing_to_n(&input, k_combinations, 2020) { Some(s) => println!("Solution: {}", s.iter().product::<i32>()), None => println!("No solution found"), } } #[test] fn part_1() { common_solution(2) } #[test] fn part_2() { common_solution(3) } }
extern crate base64; mod hamming; mod utils; use std::fs::File; use std::io::prelude::*; use hamming::*; use utils::*; fn main() { println!("reading file..."); let text1 = get_text_from_file("/home/zeegomo/Documents/hack/cryptopals/set1/challenge6/src/data.txt"); println!("decoding base64..."); let text1_bytes = base64::decode(&text1).unwrap(); println!("guessing key length..."); let best_key = hamming::guess_key_lenght(2,40,&text1_bytes); println!("guessed key length: {}, {}, {}",best_key.0,best_key.2,best_key.4); let blocks1 = hamming::get_blocks(&text1_bytes,best_key.0); let blocks2 = hamming::get_blocks(&text1_bytes,best_key.2); let blocks3 = hamming::get_blocks(&text1_bytes,best_key.4); println!("generating probable keys..."); let keys1 = hamming::gen_keys(blocks1); let keys2 = hamming::gen_keys(blocks2); let keys3 = hamming::gen_keys(blocks3); println!("decrypting..."); let plaintext1 = hamming::encrypt_repeating_xor(&text1_bytes,&keys1); let plaintext2 = hamming::encrypt_repeating_xor(&text1_bytes,&keys2); let plaintext3 = hamming::encrypt_repeating_xor(&text1_bytes,&keys3); println!("PROBABLE MATCH FOUND: {}", String::from_utf8(plaintext1).unwrap()); println!(); println!(); println!("PROBABLE MATCH FOUND: {}", String::from_utf8(plaintext2).unwrap()); println!(); println!(); println!("PROBABLE MATCH FOUND: {}", String::from_utf8(plaintext3).unwrap()); }
use std::str; use std::thread::sleep; use std::time::{Duration, SystemTime}; use quick_xml::de::from_str; use reqwest::Client; use crate::errors::NSError; use crate::nation::Nation; use crate::region::Region; const NS_API_URL: &str = "https://www.nationstates.net/cgi-bin/api.cgi"; const RATE_LIMIT: usize = 49; const NS_API_VERSION: &str = "11"; pub struct NSClient { client: Client, calls: Vec<SystemTime>, } impl NSClient { pub fn new(user_agent: &str) -> Result<NSClient, NSError> { let client = Client::builder().user_agent(user_agent).build(); match client { Ok(client) => Ok(NSClient { client, calls: vec![], }), Err(error) => Err(NSError::HTTPClient(error)), } } fn make_call(&mut self) -> bool { // TODO Add check for hard rate limit // Remove calls that happened more than 30 seconds before self.calls .retain(|&call| SystemTime::now().duration_since(call).unwrap().as_secs() >= 30); if self.calls.len() < RATE_LIMIT { self.calls.push(SystemTime::now()); return true; } false } pub async fn get_nation(&mut self, nation: &str) -> Result<Nation, NSError> { while !self.make_call() { sleep(Duration::from_secs(5)); } let res = self .client .get(NS_API_URL) .query(&[("nation", nation), ("v", NS_API_VERSION)]) .send() .await .map_err(NSError::HTTPClient)?; // Get text from the response or return an error let data = res.text().await.map_err(NSError::HTTPClient)?; // Deserialization from_str(data.as_str()).map_err(NSError::Deserializer) } pub async fn get_region(&mut self, region: &str) -> Result<Region, NSError> { while !self.make_call() { sleep(Duration::from_secs(5)); } let res = self .client .get(NS_API_URL) .query(&[("region", region), ("v", NS_API_VERSION)]) .send() .await .map_err(NSError::HTTPClient)?; // Get text from the response or return an error let data = res.text().await.map_err(NSError::HTTPClient)?; // Deserialization from_str(data.as_str()).map_err(NSError::Deserializer) } pub async fn verify(&mut self, nation: &str, checksum: &str) -> Result<bool, NSError> { self.handle_verification(nation, checksum, Option::None) .await } pub async fn verify_with_token( &mut self, nation: &str, checksum: &str, token: &str, ) -> Result<bool, NSError> { self.handle_verification(nation, checksum, Option::Some(token)) .await } async fn handle_verification( &mut self, nation: &str, checksum: &str, token: Option<&str>, ) -> Result<bool, NSError> { while !self.make_call() { sleep(Duration::from_secs(5)); } let mut req = self.client.get(NS_API_URL).query(&[ ("a", "verify"), ("nation", nation), ("checksum", checksum), ("v", NS_API_VERSION), ]); if let Some(site_token) = token { req = req.query(&[("token", site_token)]); } let res = req.send().await.map_err(NSError::HTTPClient)?; // Get text from the response or return an error let data = res.text().await.map_err(NSError::HTTPClient)?; Ok(data.contains('1')) } }
//! A module providing the wrapping driver for a custom runner. use std::env; use std::ffi::OsString; use std::io; use std::path::Path; use std::process::Command; /// The prefix line for the target host output. const HOST_PREFIX: &[u8] = b"host: "; /// Act as a driver for `cargo run`/`cargo test`, but with special runner. /// /// This function returns `Ok(true)` if all subprograms were successfully /// executed, or `Ok(false)` if there was a non-successful subcommand. /// /// # Errors /// This function returns an I/O error, if a subprocess could not be spawned or /// executed. pub fn driver() -> io::Result<bool> { /* get path of `rustc` */ let cargo = env::var_os("CARGO").expect("CARGO environment variable is not set"); let rustc = Path::new(&cargo).with_file_name("rustc"); /* get the output of `rustc -vV` */ let rustc_info = Command::new(rustc).arg("-vV").output()?.stdout; /* get the host information (all after the "host: ..." line) */ let host = rustc_info .windows(HOST_PREFIX.len()) .position(|window| window == HOST_PREFIX) .expect("Host information not present in `rustc -vV`"); let host: String = rustc_info .into_iter() .skip(host) .skip(HOST_PREFIX.len()) .take_while(|&x| x != b'\n') .map(char::from) .collect(); /* convert to runner env variable */ let host = host.replace('-', "_").replace('.', "_").to_uppercase(); let runner = format!("CARGO_TARGET_{}_RUNNER", host); /* cargo run with a custom runner */ let cargo_valgrind = env::args_os() .next() .unwrap_or_else(|| OsString::from("cargo-valgrind")); Ok(Command::new(cargo) .args(env::args_os().skip(2)) .envs(env::vars_os()) .env(runner, cargo_valgrind) .spawn()? .wait()? .success()) }
use std::fmt::{Debug, Display}; use std::path::PathBuf; use crate::traits::{CorpusDelta, Pool, SaveToStatsFolder, Stats}; use crate::{CSVField, CompatibleWithObservations, PoolStorageIndex, ToCSV}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] struct Unit; struct Input { input_id: PoolStorageIndex, complexity: f64, } /// A pool that finds a single test case maximising a value given by a sensor. pub struct MaximiseObservationPool<T> { name: String, current_best: Option<(T, Input)>, } #[derive(Clone)] pub struct MaximiseObservationPoolStats<T> { name: String, best: T, } impl<T> Display for MaximiseObservationPoolStats<T> where T: Debug, { #[no_coverage] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}({:?})", self.name, self.best) } } impl<T> ToCSV for MaximiseObservationPoolStats<T> where T: Debug, { #[no_coverage] fn csv_headers(&self) -> Vec<CSVField> { vec![CSVField::String(self.name.clone())] } #[no_coverage] fn to_csv_record(&self) -> Vec<CSVField> { vec![CSVField::String(format!("{:?}", self.best))] } } impl<T> Stats for MaximiseObservationPoolStats<T> where T: Debug + Default + 'static {} impl<T> MaximiseObservationPool<T> { #[no_coverage] pub fn new(name: &str) -> Self { Self { name: name.to_string(), current_best: None, } } } impl<T> Pool for MaximiseObservationPool<T> where T: Clone + Debug + Default + 'static, { type Stats = MaximiseObservationPoolStats<T>; #[no_coverage] fn stats(&self) -> Self::Stats { MaximiseObservationPoolStats { name: self.name.clone(), best: self .current_best .as_ref() .map( #[no_coverage] |z| z.0.clone(), ) .unwrap_or_default(), } } #[no_coverage] fn get_random_index(&mut self) -> Option<PoolStorageIndex> { if let Some(best) = &self.current_best { Some(best.1.input_id) } else { None } } } impl<T> SaveToStatsFolder for MaximiseObservationPool<T> { #[no_coverage] fn save_to_stats_folder(&self) -> Vec<(PathBuf, Vec<u8>)> { vec![] } } impl<T> CompatibleWithObservations<T> for MaximiseObservationPool<T> where T: Clone + Debug + Default + PartialOrd + 'static, { #[no_coverage] fn process(&mut self, input_id: PoolStorageIndex, observations: &T, complexity: f64) -> Vec<CorpusDelta> { let observations = observations.clone(); let is_interesting = if let Some((counter, cur_input)) = &self.current_best { observations > *counter || (observations == *counter && cur_input.complexity > complexity) } else { true }; if !is_interesting { return vec![]; } let delta = CorpusDelta { path: PathBuf::new().join(&self.name), add: true, remove: if let Some(best) = &self.current_best { vec![best.1.input_id] } else { vec![] }, }; let new = Input { input_id, complexity }; self.current_best = Some((observations, new)); vec![delta] } }
/// Verify and extract login from an email address /// /// Validated that an email address is formatted correctly, and extracts /// everything before the @ symble. /// use errors::*; use regex::Regex; fn extract_login(input: &str) -> Option<&str> { lazy_static! { static ref RE: Regex = Regex::new(r"(?x) ^(?P<login>[^@\s]+)@ ([[:word:]]+\.)* [[:word:]]+$ ").unwrap(); } RE.captures(input).and_then(|cap| { cap.name("login").map(|login| login.as_str()) }) } pub fn run_email() { assert_eq!(extract_login(r"I❤email@example.com"), Some(r"I❤email")); assert_eq!( extract_login(r"sdf+sdsfsd.as.sdsd@jhkk.d.rl"), Some(r"sdf+sdsfsd.as.sdsd") ); assert_eq!(extract_login(r"More@Than@One@at.com"), None); assert_eq!(extract_login(r"Not an email@email"), None); } /// Extract a list of unique #Hashtags from a text /// /// Extracts a sorted and deduplicated list of hashtags from a text. The /// hashtag regex given here only catches Latin hashtags that start with a /// letter. The complete twitter hashtag regex is much more complicated. /// use std::collections::HashSet; fn extract_hashtags(text: &str) -> HashSet<&str> { lazy_static! { static ref HASHTAG_REGX: Regex = Regex::new( r"\#[a-zA-Z][0-9a-zA-Z]*" ).unwrap(); } HASHTAG_REGX.find_iter(text).map(|mat| mat.as_str()).collect() } pub fn run_hashtags() { let tweet = "Hey #world, I just got my new #dog, say hello to Till. #dog #forever #2 #_ "; let tags = extract_hashtags(tweet); for tag in tags { println!("{:?}", tag) } } /// Replace all occurrences of one text pattern with another pattern. /// /// Replaces all occurrences of the hyphenated British English date pattern /// `2013-01-15` with its equivalent slashed American English date pattern /// `01/15/2013`. The method Regex::replace_all replaces all occurrences of /// the whole regex. The `Replacer` trait helps to figure out the replacement /// string. This trait is implemented for `&str` and allows to use variables like /// `$abcde` to refer to corresponding named capture groups `(?P<abcde>REGEX)` /// from the search regex. See the `replacement string syntax for examples and /// information about escaping. /// use std::borrow::Cow; fn reformat_dates(before: &str) -> Cow<str> { lazy_static! { static ref ENGL_DATE_REGEX: Regex = Regex::new( r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})" ).unwrap(); } ENGL_DATE_REGEX.replace_all(before, "$m/$d/$y") } pub fn run_replace() { let before = "2012-03-14, 2013-01-01 and 2014-07-05"; let after = reformat_dates(before); println!("before: {:?}\nafter: {:?}", before, after); } /// Extract phone numbers from text /// /// Processes a string of text using `Regex::captures_iter` to capture multiple /// phone numbers. The example here is for US convention phone numbers. /// use std::fmt; struct PhoneNumber<'a> { area: &'a str, exchange: &'a str, subscriber: &'a str, } // Allows printing phone numbers based on country convention. impl<'a> fmt::Display for PhoneNumber<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "1 ({}) {}-{} ", self.area, self.exchange, self.subscriber) } } pub fn run_phone_number() -> Result<()>{ let phone_text = " +1 505 881 9292 (v) +1 505 778 2212 (c) +1 505 881 9297 (f) (202) 991 9534 Alex 5553920011 1 (800) 233-2010 1.299.339.1020"; let re = Regex::new( r#"(?x) (?:\+?1) # Country Code Optional [\s\.]? (([2-9]\d{2})|\(([2-9]\d{2})\)) # Area Code [\s\.\-]? ([2-9]\d{2}) # Exchange Code [\s\.\-] (\d{4}) # Subscriber Number"# )?; let phone_numbers = re.captures_iter(phone_text).filter_map(|cap|{ // Area code populates either capture group 2 or 3. // Group 1 contains optional parenthesis let groups = (cap.get(2).or(cap.get(3)), cap.get(4), cap.get(5)); match groups { (Some(area), Some(ext), Some(sub)) => Some(PhoneNumber { area: area.as_str(), exchange: ext.as_str(), subscriber: sub.as_str(), } ), _ => None, } }); let result = phone_numbers.map(|m| m.to_string()).collect::<Vec<_>>(); for r in result { println!("{}", r); } Ok(()) }
pub mod token; pub use token::*; pub mod commands; pub mod queries; // Holds specific repository contracts that aren't pulled from the generic ones in domain_patterns crates. pub mod repository_contracts;
mod connection; mod error; mod go_away; mod peer; mod ping_pong; mod settings; mod streams; pub(crate) use self::connection::{Config, Connection}; pub(crate) use self::error::Error; pub(crate) use self::peer::{Peer, Dyn as DynPeer}; pub(crate) use self::streams::{StreamRef, OpaqueStreamRef, Streams}; pub(crate) use self::streams::{PollReset, Prioritized, Open}; use codec::Codec; use self::go_away::GoAway; use self::ping_pong::PingPong; use self::settings::Settings; use frame::{self, Frame}; use futures::{task, Async, Poll}; use futures::task::Task; use bytes::Buf; use tokio_io::AsyncWrite; pub type PingPayload = [u8; 8]; pub type WindowSize = u32; // Constants pub const MAX_WINDOW_SIZE: WindowSize = (1 << 31) - 1; pub const DEFAULT_RESET_STREAM_MAX: usize = 10; pub const DEFAULT_RESET_STREAM_SECS: u64 = 30;
//! Probabilistic distributions. use rand::distributions::Distribution; use rand::Rng; use rand_distr::weighted::WeightedIndex; use std::collections::{HashMap, HashSet}; use std::hash::Hash; /// A distribution used for random assignments. pub struct AssignmentDistribution<T: Hash> { weights: HashMap<T, f32>, min: f32, } impl<T: Hash + Eq + Copy> AssignmentDistribution<T> { /// Constructs new distribution. #[must_use] pub fn new(weights: HashMap<T, f32>) -> Self { Self { weights, min: 0.0 } } /// Sample single value. pub fn sample<R: Rng + ?Sized>(&mut self, rng: &mut R, cost: f32, blacklist: &HashSet<T>) -> T { let mut resources: Vec<_> = self .weights .iter_mut() .filter(|(value, _)| !blacklist.contains(value)) .collect(); let shift = self.min; let dist = WeightedIndex::new(resources.iter().map(|(_, w)| **w - shift)) .expect("Distinct assignment infeasible"); let (elem, weight) = &mut resources[dist.sample(rng)]; **weight -= cost; **elem } } impl<T: Hash> Distribution<T> for AssignmentDistribution<T> { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T { let mut resources: Vec<_> = self .weights .iter_mut() .filter(|(value, _)| !blacklist.contains(value)) .collect(); let shift = self.min; let dist = WeightedIndex::new(resources.iter().map(|(_, w)| **w - shift)) .expect("Distinct assignment infeasible"); let (elem, weight) = &mut resources[dist.sample(rng)]; **weight -= cost; **elem } } struct FilteredWeightedIndex<T> { weights: HashMap<T, f32>, ignore: HashSet<T>, } // #[cfg(test)] // mod test { // use super::*; // use proptest::prelude::*; // use rand::SeedableRng; // use rand_chacha::ChaChaRng; // proptest! { // #[test] // fn test_assignment_distribution( // seed: u64, // weights in proptest::collection::vec(proptest::num::f32::POSITIVE, 10..20) // ) { // let replicas = 3; // let distr = AssignmentDistribution::new(weights.into_iter().enumerate().collect()); // let mut rng = ChaChaRng::seed_from_u64(seed); // distr.sample(&mut rng); // } // } // } // impl<A: Hash + Eq + Copy> std::iter::FromIterator<A> for AssignmentDistribution<A> { // fn from_iter<T>(iter: T) -> Self // where // T: IntoIterator<Item = A>, // { // let mut counts: HashMap<A, usize> = HashMap::default(); // for r in iter { // *counts.entry(r).or_default() += 1; // } // Self { counts } // } // }
use rust::prelude::*; use types::{uchar_t, char_t, int_t, size_t}; #[no_mangle] pub unsafe extern fn memcpy(dst: *mut char_t, src: *const char_t, n: size_t) -> *mut char_t { for i in range(0, n as isize).rev() { *offset_mut(dst, i) = *offset(src, i); } dst } #[no_mangle] pub unsafe extern fn memmove(dst: *mut char_t, src: *const char_t, n: size_t) -> *mut char_t { if (dst as usize) > (src as usize) { return memcpy(dst, src, n); } for i in range(0, n as isize) { *offset_mut(dst, i) = *offset(src, i); } dst } #[no_mangle] pub unsafe extern fn strcpy(dst: *mut char_t, src: *const char_t) -> *mut char_t { let mut i = 0; while *offset(src, i) != 0 { *offset_mut(dst, i) = *offset(src, i); i += 1; } *offset_mut(dst, i) = 0; dst } #[no_mangle] pub unsafe extern fn strncpy(dst: *mut char_t, src: *const char_t, n: size_t) -> *mut char_t { let n = n as isize; let mut i = 0; while i < n && *offset(src, i) != 0 { *offset_mut(dst, i) = *offset(src, i); i += 1; } while i < n { *offset_mut(dst, i) = 0; i += 1; } dst } #[no_mangle] pub unsafe extern fn strcat(dst: *mut char_t, src: *const char_t) -> *mut char_t { let base = strlen(dst as *const _) as isize; let mut i = 0; while *offset(src, i) != 0 { *offset_mut(dst, base+i) = *offset(src, i); i += 1; } *offset_mut(dst, base+i) = 0; dst } #[no_mangle] pub unsafe extern fn strncat(dst: *mut char_t, src: *const char_t, n: size_t) -> *mut char_t { let base = strlen(dst as *const _) as isize; for i in range(0, n as isize) { *offset_mut(dst, base+i) = *offset(src, i); if *offset(src, i) == 0 { break; } } dst } #[no_mangle] pub unsafe extern fn memcmp(m1: *const char_t, m2: *const char_t, n: size_t) -> int_t { let m1 = m1 as *const uchar_t; let m2 = m2 as *const uchar_t; for i in range(0, n as isize) { let v1 = *offset(m1, i) as isize; let v2 = *offset(m2, i) as isize; match v1 - v2 { j if j < 0 => return -1, j if j > 0 => return 1, _ => { }, } } 0 } #[no_mangle] pub unsafe extern fn strcmp(m1: *const char_t, m2: *const char_t) -> int_t { let m1 = m1 as *const uchar_t; let m2 = m2 as *const uchar_t; for i in count(0, 1) { let v1 = *offset(m1, i) as isize; let v2 = *offset(m2, i) as isize; match v1 - v2 { j if j < 0 => return -1, j if j > 0 => return 1, _ => { }, } if v1 == 0 { break; } } 0 } #[no_mangle] pub unsafe extern fn strcoll(m1: *const char_t, m2: *const char_t) -> int_t { strcmp(m1, m2) } #[no_mangle] pub unsafe extern fn strncmp(m1: *const char_t, m2: *const char_t, n: size_t) -> int_t { let m1 = m1 as *const uchar_t; let m2 = m2 as *const uchar_t; for i in range(0, n as isize) { let v1 = *offset(m1, i) as isize; let v2 = *offset(m2, i) as isize; match v1 - v2 { j if j < 0 => return -1, j if j > 0 => return 1, _ => { }, } if v1 == 0 { break; } } 0 } #[no_mangle] pub unsafe extern fn strxfrm(dst: *mut char_t, src: *const char_t, n: size_t) -> size_t { let len = strlen(src); if len < n { memcpy(dst, src, len+1); } len } #[no_mangle] pub unsafe extern fn memchr(s: *const char_t, c: int_t, n: size_t) -> *const char_t { let c = c as char_t; for i in range(0, n as isize) { if *offset(s, i) == c { return offset(s, i); } } 0 as *const char_t } #[no_mangle] pub unsafe extern fn strchr(s: *const char_t, c: int_t) -> *const char_t { if c == 0 { return offset(s, strlen(s) as isize); } let c = c as char_t; let mut i = 0; while *offset(s, i) != 0 { if *offset(s, i) == c { return offset(s, i); } i += 1; } 0 as *const char_t } #[no_mangle] pub unsafe extern fn strcspn(s1: *const char_t, s2: *const char_t) -> size_t { let len = strlen(s2); let mut i = 0; while *offset(s1, i) != 0 { if memchr(s2, *offset(s1, i) as int_t, len) as usize != 0 { break; } i += 1; } i as size_t } #[no_mangle] pub unsafe extern fn strpbrk(s1: *const char_t, s2: *const char_t) -> *const char_t { let len = strlen(s2); let mut i = 0; while *offset(s1, i) != 0 { if memchr(s2, *offset(s1, i) as int_t, len) as usize == 0 { return offset(s1, i); } i += 1; } 0 as *const char_t } #[no_mangle] pub unsafe extern fn strrchr(s: *const char_t, c: int_t) -> *const char_t { let mut last = -1; let mut i = 0; while *offset(s, i) != 0 { if *offset(s, i) as int_t == c { last = i; } i += 1; } match last { -1 => 0 as *const char_t, _ => offset(s, last) } } #[no_mangle] pub unsafe extern fn strspn(s1: *const char_t, s2: *const char_t) -> size_t { let len = strlen(s2); let mut i = 0; while *offset(s1, i) != 0 { if memchr(s2, *offset(s1, i) as int_t, len) as usize == 0 { break; } i += 1; } i as size_t } #[no_mangle] pub unsafe extern fn strstr(s1: *const char_t, s2: *const char_t) -> *const char_t { let len1 = strlen(s1) as isize; let len2 = strlen(s2) as isize; for i in range(0, len1 - len2) { if memcmp(offset(s1, i), s2, len2 as size_t) == 0 { return offset(s1, i); } } 0 as *const char_t } #[no_mangle] pub unsafe extern fn strtok(s1: *mut char_t, s2: *const char_t) -> *const char_t { static mut ss: *mut char_t = 0 as *mut char_t; static mut len: isize = 0; if s1 as usize != 0 { ss = s1; len = strlen(ss as *const _) as isize; } if ss as usize == 0 { return 0 as *const char_t; } let len2 = strlen(s2) as isize; let mut i = 0; while i < len { if memchr(s2, *offset_mut(ss, i) as int_t, len2 as size_t) as usize != 0 { break; } i += 1; } ss = offset_mut(ss, i); len -= i; if len == 0 { ss = 0 as *mut char_t; return 0 as *const char_t; } let mut i = 0; while i < len { if memchr(s2, *offset_mut(ss, i) as int_t, len2 as size_t) as usize == 0 { break; } i += 1; } if i == len { len = 0; let tmp = ss; ss = 0 as *mut char_t; return tmp as *const _; } *offset_mut(ss, i) = 0; let tmp = ss; ss = offset_mut(ss, i+1); len -= i+1; tmp as *const _ } #[no_mangle] pub unsafe extern fn memset(dst: *mut char_t, c: int_t, n: size_t) -> *mut char_t { let c = c as char_t; for i in range(0, n as isize).rev() { *offset_mut(dst, i) = c; } dst } #[no_mangle] pub unsafe extern fn strerror(_: int_t) -> *const char_t { cs!("u w0t m8?") } #[no_mangle] pub unsafe extern fn strlen(s: *const char_t) -> size_t { let mut len = 0; while *offset(s, len) != 0 { len += 1; } len as size_t } #[no_mangle] pub unsafe extern fn strnlen(s: *const char_t, n: size_t) -> size_t { let mut len: usize = 0; while *offset(s, len as isize) != 0 && len < (n as usize) { len += 1; } len as size_t }
use crate::beam::{Beam, BeamIntersect}; pub struct BeamIter { beam: Beam, } impl Beam { const fn iter(self) -> BeamIter { BeamIter { beam: self } } } impl Iterator for BeamIter { type Item = BeamIntersect; fn next(&mut self) -> Option<Self::Item> { self.beam.next_intersect() } } impl IntoIterator for Beam { type Item = BeamIntersect; type IntoIter = BeamIter; fn into_iter(self) -> Self::IntoIter { self.iter() } }
#![feature(test)] extern crate peg_syntax_ext; use peg_syntax_ext::peg_file; extern crate test; use test::Bencher; peg_file!(parser("expr.rustpeg")); #[bench] fn expr(b: &mut Bencher) { let bench_str = "1+2+3+4*5*6^7^8^(0^1*2+1)"; b.bytes = bench_str.len() as u64; b.iter(|| { parser::expr(bench_str).unwrap(); }); }
// Copyright (c) Calibra Research // SPDX-License-Identifier: Apache-2.0 use super::*; use std::collections::BTreeMap; #[cfg(test)] #[path = "unit_tests/configuration_tests.rs"] mod configuration_tests; impl EpochConfiguration { pub fn new(voting_rights: BTreeMap<Author, usize>) -> Self { let total_votes = voting_rights.iter().fold(0, |sum, (_, votes)| sum + *votes); EpochConfiguration { voting_rights, total_votes, } } pub fn weight(&self, author: &Author) -> usize { *self.voting_rights.get(author).unwrap_or(&0) } pub fn count_votes<'a, I>(&'a self, authors: I) -> usize where I: IntoIterator<Item = &'a Author>, { authors.into_iter().fold(0, |sum, author| { sum + self.voting_rights.get(author).unwrap_or(&0) }) } pub fn quorum_threshold(&self) -> usize { // If N = 3f + 1 + k (0 <= k < 3) // then (2 N + 3) / 3 = 2f + 1 + (2k + 2)/3 = 2f + 1 + k = N - f 2 * self.total_votes / 3 + 1 } pub fn validity_threshold(&self) -> usize { // If N = 3f + 1 + k (0 <= k < 3) // then (N + 2) / 3 = f + 1 + k/3 = f + 1 (self.total_votes + 2) / 3 } pub fn pick_author(&self, seed: u64) -> Author { // TODO: this is linear-time. let mut target = seed as usize % self.total_votes; for (author, votes) in &self.voting_rights { if *votes > target { return *author; } target -= *votes; } unreachable!() } }
//! A TCP proxy server. Forwards connections from port 8081 to port 8080. use futures::prelude::*; use futures::try_join; use runtime::net::{TcpListener, TcpStream}; #[runtime::main] async fn main() -> std::io::Result<()> { let mut listener = TcpListener::bind("127.0.0.1:8081")?; println!("Listening on {}", listener.local_addr()?); // accept connections and process them in parallel listener .incoming() .try_for_each_concurrent(None, |client| { async move { runtime::spawn(async move { let server = TcpStream::connect("127.0.0.1:8080").await?; println!( "Proxying {} to {}", client.peer_addr()?, server.peer_addr()? ); let (cr, cw) = &mut client.split(); let (sr, sw) = &mut server.split(); let a = cr.copy_into(sw); let b = sr.copy_into(cw); try_join!(a, b)?; Ok::<(), std::io::Error>(()) }) .await } }) .await?; Ok(()) }
use std::fs::File; use std::io::BufReader; use std::io::Read; use std::collections::HashSet; use regex::Regex; fn acc_instr(op : &str, val : i64) -> i64 { if op == "+" { return val; } else { return -val; } } fn jmp_instr(op : &str, val : i64, curr : usize) -> usize { let n : i64 = acc_instr(op, val); if n.is_negative() { return match curr.checked_sub(n.wrapping_abs() as usize) { Some(inner) => inner, None => 0, }; } else { return match curr.checked_add(val as usize) { Some(inner) => inner, None => 0, }; } } fn get_operands(line : &str) -> (&str, &str, i64) { let re = Regex::new(r"^(jmp|acc|nop){1} (\+|-){1}(\d+)$").unwrap(); let caps = match re.captures(line) { Some(inner) => inner, None => { println!("Failed to match: {}", line); return ("false", "false", -1); } }; let instruction : &str = caps.get(1).unwrap().as_str(); let op : &str = caps.get(2).unwrap().as_str(); let val : i64 = match caps.get(3) .unwrap().as_str().trim().parse() { Ok(num) => num, Err(_) => { println!("Failed to read number: {}", line); return ("false", "false", -1); } }; (instruction, op, val) } fn get_acc(lines : Vec<&str>) -> i64 { let mut i : usize = 0; let mut acc : i64 = 0; let mut visited : HashSet<usize>= HashSet::new(); while i < lines.len() { visited.insert(i); //println!("Executing: {}", lines[i]); let operands = get_operands(lines[i]); if operands == ("false", "false", -1) { break; } match operands.0 { "nop" => {i += 1}, "acc" => { acc += acc_instr(operands.1, operands.2); i += 1; }, "jmp" => { i = jmp_instr(operands.1, operands.2, i); } _ => { println!("Error reading line: {}", lines[i]); break; } }; if visited.contains(&i) { println!("Stopped at instruction {}: {}", i, lines[i]); break; } } acc } fn get_fixed_acc(lines : Vec<&str>) -> i64 { let mut i : usize = 0; let mut acc : i64 = 0; let mut visited : HashSet<usize> = HashSet::new(); while i < lines.len() { visited.insert(i); //println!("Executing: {}", lines[i]); let operands = get_operands(lines[i]); if operands == ("false", "false", -1) { break; } match operands.0 { "nop" => { let path_results : (bool, i64) = explore_path(lines.clone(), i, acc, visited.clone()); if path_results.0 { println!("Flipped instruction {}: {}", i, lines[i]); return path_results.1; } i += 1; }, "acc" => { acc += acc_instr(operands.1, operands.2); i += 1; }, "jmp" => { let path_results : (bool, i64) = explore_path(lines.clone(), i, acc, visited.clone()); if path_results.0 { println!("Flipped instruction {}: {}", i, lines[i]); return path_results.1; } i = jmp_instr(operands.1, operands.2, i); } _ => { println!("Error reading line: {}", lines[i]); break; } }; if visited.contains(&i) { println!("Stopped at instruction {}: {}", i, lines[i]); break; } } acc } fn explore_path(lines : Vec<&str>, mut i : usize, mut acc : i64, visited : HashSet<usize>) -> (bool, i64) { let mut visited_ : HashSet<usize> = visited.clone(); visited_.insert(i); let operands = get_operands(lines[i]); if operands == ("false", "false", -1) { return (false, 0); } match operands.0 { "nop" => { i = jmp_instr(operands.1, operands.2, i); }, "jmp" => { i += 1; }, _ => { println!("Error in exploring path"); return (false, 0); } }; while i < lines.len() { visited_.insert(i); //println!("Executing: {}", lines[i]); let operands = get_operands(lines[i]); if operands == ("false", "false", -1) { break; } match operands.0 { "nop" => {i += 1}, "acc" => { acc += acc_instr(operands.1, operands.2); i += 1; }, "jmp" => { i = jmp_instr(operands.1, operands.2, i); } _ => { println!("Error reading line: {}", lines[i]); break; } }; if visited_.contains(&i) { //println!("Stopped at instruction {}: {}", i, lines[i]); return (false, 0); } } (true, acc) } fn main() { let file = File::open("input").expect("Failed to read file input"); let mut buf_reader = BufReader::new(file); let mut contents = String::new(); buf_reader.read_to_string(&mut contents) .expect("Failed to bufferize file input"); let lines : Vec<&str> = contents.lines().collect(); println!("acc: {}", get_acc(lines.clone())); println!("fix acc: {}", get_fixed_acc(lines.clone())); }
// Copyright 2014-2018 Optimal Computing (NZ) Ltd. // Licensed under the MIT license. See LICENSE for details. use std::mem; use num_traits::NumCast; /// A trait for floating point numbers which computes the number of representable /// values or ULPs (Units of Least Precision) that separate the two given values. pub trait Ulps { type U: Copy + NumCast; /// The number of representable values or ULPs (Units of Least Precision) that /// separate `self` and `other`. The result `U` is an integral value, and will /// be zero if `self` and `other` are exactly equal. fn ulps(&self, other: &Self) -> <Self as Ulps>::U; } impl Ulps for f32 { type U = i32; fn ulps(&self, other: &f32) -> i32 { // IEEE754 defined floating point storage representation to // maintain their order when their bit patterns are interpreted as // integers. This is a huge boon to the task at hand, as we can // (unsafely) cast to integers to find out how many ULPs apart any // two floats are // Setup integer representations of the input let ai32: i32 = unsafe { mem::transmute::<f32,i32>(*self) }; let bi32: i32 = unsafe { mem::transmute::<f32,i32>(*other) }; ai32.wrapping_sub(bi32) } } #[test] fn f32_ulps_test1() { let x: f32 = 1000000_f32; let y: f32 = 1000000.1_f32; println!("DIST IS {}",x.ulps(&y)); assert!(x.ulps(&y) == -2); } #[test] fn f32_ulps_test2() { let pzero: f32 = unsafe { mem::transmute(0x00000000_u32) }; let nzero: f32 = unsafe { mem::transmute(0x80000000_u32) }; println!("DIST IS {}",pzero.ulps(&nzero)); assert!(pzero.ulps(&nzero) == -2147483648); } #[test] fn f32_ulps_test3() { let pinf: f32 = unsafe { mem::transmute(0x7f800000_u32) }; let ninf: f32 = unsafe { mem::transmute(0xff800000_u32) }; println!("DIST IS {}",pinf.ulps(&ninf)); assert!(pinf.ulps(&ninf) == -2147483648); } #[test] fn f32_ulps_test4() { let x: f32 = unsafe { mem::transmute(0x63a7f026_u32) }; let y: f32 = unsafe { mem::transmute(0x63a7f023_u32) }; println!("DIST IS {}",x.ulps(&y)); assert!(x.ulps(&y) == 3); } #[test] fn f32_ulps_test5() { let x: f32 = 2.0; let ulps: i32 = unsafe { mem::transmute(x) }; let x2: f32 = unsafe { mem::transmute(ulps) }; assert_eq!(x, x2); } impl Ulps for f64 { type U = i64; fn ulps(&self, other: &f64) -> i64 { // IEEE754 defined floating point storage representation to // maintain their order when their bit patterns are interpreted as // integers. This is a huge boon to the task at hand, as we can // (unsafely) cast to integers to find out how many ULPs apart any // two floats are // Setup integer representations of the input let ai64: i64 = unsafe { mem::transmute::<f64,i64>(*self) }; let bi64: i64 = unsafe { mem::transmute::<f64,i64>(*other) }; ai64.wrapping_sub(bi64) } } #[test] fn f64_ulps_test1() { let x: f64 = 1000000_f64; let y: f64 = 1000000.00000001_f64; println!("DIST IS {}",x.ulps(&y)); assert!(x.ulps(&y) == -86); } #[test] fn f64_ulps_test2() { let pzero: f64 = unsafe { mem::transmute(0x0000000000000000_u64) }; let nzero: f64 = unsafe { mem::transmute(0x8000000000000000_u64) }; println!("DIST IS {}",pzero.ulps(&nzero)); assert!(pzero.ulps(&nzero) == -9223372036854775808i64); } #[test] fn f64_ulps_test3() { let pinf: f64 = unsafe { mem::transmute(0x7f80000000000000_u64) }; let ninf: f64 = unsafe { mem::transmute(0xff80000000000000_u64) }; println!("DIST IS {}",pinf.ulps(&ninf)); assert!(pinf.ulps(&ninf) == -9223372036854775808i64); } #[test] fn f64_ulps_test4() { let x: f64 = unsafe { mem::transmute(0xd017f6cc63a7f026_u64) }; let y: f64 = unsafe { mem::transmute(0xd017f6cc63a7f023_u64) }; println!("DIST IS {}",x.ulps(&y)); assert!(x.ulps(&y) == 3); } #[test] fn f64_ulps_test5() { let x: f64 = 2.0; let ulps: i64 = unsafe { mem::transmute(x) }; let x2: f64 = unsafe { mem::transmute(ulps) }; assert_eq!(x, x2); }
use crate::{AbstractIndices, Buffer, BufferDataUsage, Context, RenderPrimitiveType}; /// Represents WebGL programs. /// /// This type should only be implemented by the [`Program`][super::Program] macro. pub trait Program: Sized { /// The struct generated for storing attributes. /// Always `#[repr(C)]`. type AttrStruct: AttrStruct; /// Compiles and links the program in the given [`Context`](struct.Context.html). fn create(context: &Context) -> Self { let p = Self::create_internally(context); p.compile_shaders(context); p.link_shaders(context); p } /// Creates an instance of the type. Allocate necessary resources like `gl.createShader()`. fn create_internally(gl: &Context) -> Self; /// Compiles the vertex and fragment shaders. fn compile_shaders(&self, gl: &Context); /// Attaches and links the vertex and fragment shaders. fn link_shaders(&self, gl: &Context); /// Prepares a buffer with the attributes in the vec. fn prepare_buffer( context: &Context, attrs: &[Self::AttrStruct], usage: BufferDataUsage, ) -> Buffer<Self::AttrStruct> { Buffer::from_slice(context, attrs, usage) } /// Calls the WebGL context to use the current program for draw calls. fn use_program(&self, gl: &Context); /// Runs the program with the given attributes indexed by `indices`. /// /// This method is identical to [`AbstractIndices::draw`][AbstractIndices::draw], /// except with different parameter order. /// /// This method does not reassign uniforms. /// Use the `with_uniforms` method (derived by the [`Program`][super::Program] macro) /// to draw with uniforms specified. fn draw( &self, context: &Context, mode: RenderPrimitiveType, buffer: &Buffer<Self::AttrStruct>, indices: impl AbstractIndices, ) { self.use_program(context); indices.draw(mode, context, self, buffer); } /// Applies the buffer ot the attributes in this program. fn apply_attrs(&self, context: &Context, buffer: &Buffer<Self::AttrStruct>); } /// The trait implemented by attribute structs. /// /// Methods in this struct describe the structure of the fields. pub trait AttrStruct { /// The number of fields in the struct fn fields_count() -> usize; /// The GLSL name of the attribute corresponding to field `i` fn field_gl_name(i: usize) -> &'static str; /// The offset of field `i` in the struct in bytes fn field_offset(i: usize) -> usize; /// The base type of field `i` in the struct with constants like `WebGlRenderingContext::BYTE` fn field_type(i: usize) -> u32; /// The number of components for the type in field `i` fn field_num_comps(i: usize) -> usize; /// Whether the field `i` should be normalized fn field_normalized(i: usize) -> bool; }
use crate::utils::StatefulList; use std::collections::{BTreeMap, HashMap}; use chrono::{ Date, DateTime, offset::Utc}; use std::error::Error; use ::reqwest::blocking::Client; use graphql_client::{reqwest::post_graphql_blocking as post_graphql, GraphQLQuery}; #[derive(Debug)] struct Transaction { amount: f64, timestamp: chrono::DateTime<Utc>, } #[derive(Debug)] struct DailyLiquidityFlow{ token0: String, token1: String, token0amount: f64, token1amount: f64, date: chrono::Date<Utc>, } #[derive(GraphQLQuery)] #[graphql( schema_path = "src/schema.json", query_path = "src/transfers_query.graphql", response_derives = "Debug", )] pub struct TransfersQuery; #[derive(GraphQLQuery)] #[graphql( schema_path = "src/schema.json", query_path = "src/price_query.graphql", response_derives = "Debug", )] pub struct PriceQuery; pub struct App { pub selected_tab: usize, pub wallet_list_state: StatefulList<String>, pub selected_token: String, pub total_holdings: BTreeMap<String, f64>, pub total_holdings_mv: HashMap<String, f64>, pub mwr_map: HashMap<String, f64>, pub daily_holdings_mv: BTreeMap<String, BTreeMap<Date<Utc>, f64>>, pub cost_bases: HashMap<String, Vec<(Date<Utc>, f64)>>, pub base_token: String, } impl App { pub fn new(account: String) -> App { let transactions = perform_query(&account).expect("Query failed for account id"); let mut daily_holdings = BTreeMap::new(); let mut total_holdings = BTreeMap::new(); let mut total_holdings_mv = HashMap::new(); let mut mwr_map = HashMap::new(); let mut daily_holdings_mv = BTreeMap::new(); let mut cost_bases = HashMap::new(); let base_token = "AUSD"; //get data from subquery generate_wallet_data(&transactions, &mut daily_holdings, &mut total_holdings, &mut total_holdings_mv, &mut mwr_map, &mut daily_holdings_mv, &mut cost_bases, &base_token); //get list of tokens let wallet_tokens = total_holdings.keys().map(|s| s.to_string()).collect(); let mut wallet_list_state = StatefulList::with_items(wallet_tokens); wallet_list_state.state.select(Some(0)); let selected_token = wallet_list_state.items.get(wallet_list_state.state.selected().unwrap()).unwrap().to_string(); //create tui app App { selected_tab : 0, wallet_list_state: wallet_list_state, selected_token: selected_token, total_holdings: total_holdings, total_holdings_mv: total_holdings_mv, mwr_map: mwr_map, daily_holdings_mv: daily_holdings_mv, cost_bases: cost_bases, base_token: base_token.to_string(), } } } fn perform_query(account_id: &String) -> Result<BTreeMap<String, Vec<Transaction>>, Box<dyn Error>> { let variables = transfers_query::Variables{ accountid: account_id.to_string(), }; let client = Client::new(); let response_body = post_graphql::<TransfersQuery, _>(&client, "https://api.subquery.network/sq/pparrott/prices-and-daily-liquidity-pool", variables).unwrap(); let response_data = &response_body.data.expect("missing response data"); let mut currency_map = BTreeMap::new(); //We are only looking at one account, so accounts will only have one account in its nodes vector if let Some(n) = &response_data.accounts.as_ref().expect("No transfers for account").nodes.iter().flat_map(|n| n.iter()).next() { for c in n.balances.nodes.iter().flat_map(|n| n.iter()) { //Now we want to iterate through the transactions made by the account let mut transactions = vec![]; for t in c.transfers.nodes.iter().flat_map(|n| n.iter()) { transactions.push( Transaction{ //Amount from API needs to be multiplied by factor of 10^-13 amount: t.amount.parse::<f64>().expect("Unable to parse transaction amount") * 10.0_f64.powi(-13), timestamp: chrono::DateTime::from_utc( //we receive Unix timestamp from Typescript, which is in milliseconds. chrono expects it in seconds instead, so need to divid by 1000 chrono::NaiveDateTime::from_timestamp(t.date.parse::<i64>().expect("Unable to parse integer representation of date")/1000, 0), Utc), } ) } currency_map.insert(c.currency.clone(), transactions); } } Ok(currency_map) } fn perform_price_query() -> Result<BTreeMap<(String, String), Vec<(chrono::Date<Utc>, (f64, f64))>>, Box<dyn Error>> { let variables = price_query::Variables{ }; let client = Client::new(); let response_body = post_graphql::<PriceQuery, _>(&client, "https://api.subquery.network/sq/pparrott/prices-and-daily-liquidity-pool", variables).unwrap(); let response_data = &response_body.data.expect("missing response data"); let mut flows = vec![]; for f in response_data.liquidity_daily_summaries.as_ref().expect("There should be at least one liquidity pool").nodes.iter().flat_map(|n| n.iter()) { flows.push( DailyLiquidityFlow { token0: f.token0.clone(), token1: f.token1.clone(), token0amount: f.token0_daily_total.parse::<f64>().expect("Error parsing liquidity flow amount"), token1amount: f.token1_daily_total.parse::<f64>().expect("Error parsing liquidity flow amount"), date: chrono::Date::from_utc(chrono::NaiveDate::parse_from_str(&f.date, "%Y%m%d").expect("Unable to parse string representation of date"),Utc) } ) } let mut currency_map: BTreeMap<(String, String), Vec<(chrono::Date<Utc>, (f64, f64))>> = BTreeMap::new(); for f in flows { let token_combo = (f.token0, f.token1); if let Some(p) = currency_map.get_mut(&token_combo) { p.push((f.date, (f.token0amount, f.token1amount))); } else { currency_map.insert(token_combo.clone(), vec![(f.date, (f.token0amount, f.token1amount))]); } } let mut final_map = BTreeMap::new(); for (k, v) in currency_map { let mut start_date = v.iter().next().expect("Pool must have at least one daily flow in order to have been grabbed").0; let end_date = v.iter().last().expect("Pool must have at least one daily flow in order to have been grabbed").0; let mut dates = vec![]; while start_date <= end_date { dates.push(start_date); start_date = start_date + chrono::Duration::days(1); } //Now generate a column where each date has the net amount transacted on that day let date_iter = dates.iter(); let flow_iter = v.iter(); let mut flows_map = BTreeMap::new(); for d in date_iter { flows_map.insert(*d, (0.0, 0.0)); } for t in flow_iter { flows_map.insert(t.0, t.1); } //Now create a column that will calculate the running total in the account let running_total: Vec<(f64, f64)> = flows_map.values().scan((0.0, 0.0), |state, x| {*state = (state.0 + x.0,state.1 + x.1); Some(*state)}).collect(); let running_total_dates: Vec<(chrono::Date<Utc>, (f64, f64))> = flows_map.keys().zip(running_total.iter()).map(|(d, a)| (*d, *a)).collect(); final_map.insert(k, running_total_dates); } Ok(final_map) } fn generate_wallet_data( transactions: &BTreeMap<String, Vec<Transaction>>, daily_holdings: &mut BTreeMap<String, BTreeMap<chrono::Date<Utc>, f64>>, total_holdings: &mut BTreeMap<String, f64>, total_holdings_mv: &mut HashMap<String, f64>, mwr_map: &mut HashMap<String, f64>, daily_holdings_mv: &mut BTreeMap<String, BTreeMap<Date<Utc>, f64>>, cost_bases: &mut HashMap<String, Vec<(Date<Utc>, f64)>>, base_token: &str) { //Concstruct a new map that contains the total amount for each token transactions.keys().zip(transactions.values()) .for_each( |(x, y)| { total_holdings.insert( x.to_string(), y.iter().fold(0.0, |s, x| s + x.amount)); } ); //Construct a new map that contains the daily holdings for each token for (token, tx) in transactions.keys().zip(transactions.values()) { daily_holdings.insert(token.clone(), calculate_daily_holdings(&tx, None, Some(Utc::now().date()))); } //Construct a map containing all exchange rates for tokens let prices = calculate_price(&perform_price_query().expect("Failed to pull price data")); //Construct market value of transactions let mut transactions_mv = BTreeMap::new(); for (k, v) in transactions.iter() { let mut mv = vec![]; for tx in v.iter() { if k == base_token { mv.push((tx.timestamp, tx.amount)); } else { let p = lookup_price(k, base_token, tx.timestamp.date(), &prices).expect(format!("No liquidity pool has been created between {} and the base token {}", k, base_token).as_str()); mv.push((tx.timestamp, tx.amount * p)); } } transactions_mv.insert(k.clone(), mv); } let mut daily_transactions_mv = BTreeMap::new(); //Construct daily aggregate of mv of transactions for (k, v) in transactions_mv.iter() { let mut m = BTreeMap::new(); for tx in v.iter() { m.entry(tx.0.date()) .and_modify(|mv| {*mv += tx.1}) .or_insert(tx.1); } daily_transactions_mv.insert(k.to_string(), m); } //Construct market value of running holdings for (k, v) in daily_holdings.iter() { let mut mv = BTreeMap::new(); for (d, a) in v.iter() { if k == base_token { mv.insert(*d, *a); } else { let p = lookup_price(k, base_token, *d, &prices).expect(format!("No liquidity pool has been created between {} and the base token {}", k, base_token).as_str()); mv.insert(*d, *a * p); } } daily_holdings_mv.insert(k.clone(), mv); } for (k, v) in daily_holdings_mv.iter() { total_holdings_mv.insert(k.clone(), *v.iter().last().unwrap().1); } for token in transactions.keys() { let mut mv_vec = vec![]; let mut date_vec = vec![]; for (t, mv) in daily_transactions_mv.get(token).expect("Token should have price") { mv_vec.push(-*mv); date_vec.push(*t); } //now insert the account value as of the last date let last_mv = total_holdings_mv .get(token) .expect("Token should have holdings data if there's a transaction"); let last_date = daily_holdings_mv.get(token).expect("Token should have holdings data if there's a transaction").keys().last().unwrap(); mv_vec.push(*last_mv); date_vec.push(*last_date); let payments: Vec<xirr::Payment> = mv_vec.iter().zip(date_vec.iter()).map(|(x, y)| xirr::Payment{date: y.naive_utc(), amount: *x}).collect(); mwr_map.insert(token.clone(), xirr::compute(&payments).unwrap()); } //generate cost bases for (token, txs) in transactions { if token == base_token { continue; } let start_date = txs.first().expect("Need at least one transaction to generate date").timestamp.date(); let dates = generate_dates(start_date, Utc::now().date()); let costs = calculate_cost_basis(token, base_token, txs, &prices); let mut costs_iter = costs.iter().peekable(); let mut cur_date = costs_iter.next(); let mut next_date = costs_iter.peek(); let mut daily_cost_basis = vec![]; for date in dates { if let Some(d) = next_date { if date < *d.0 { daily_cost_basis.push((date, *cur_date.unwrap().1)); } else { daily_cost_basis.push((date, *d.1)); cur_date = costs_iter.next(); next_date = costs_iter.peek(); } } else { //if next date doesn't exist, we're at the last transaction, so we can just use the cost basis as of this transaction daily_cost_basis.push((date, *cur_date.unwrap().1)); } } cost_bases.insert(token.to_string(), daily_cost_basis); } } fn generate_dates(mut start_date: Date<Utc>, end_date: Date<Utc>) -> Vec<Date<Utc>> { let mut dates = vec![]; while start_date <= end_date { dates.push(start_date); start_date = start_date + chrono::Duration::days(1); } dates } //function that calculates the daily token holding given the user's transactions, as well as the time frame fn calculate_daily_holdings(transactions: &Vec<Transaction>, start_window_date: Option<chrono::Date<Utc>>, end_window_date: Option<chrono::Date<Utc>>) -> BTreeMap<chrono::Date<Utc>, f64> { //First generate a column where we have a column of days from the first transaction to the last transaction let start_date = transactions.first().expect("Need at least one transaction to generate data").timestamp.date(); let end_date; //for end date, if there was a supplied end window date, use that as the end date. Otherwise, use the date of the last transaction. if let Some(d) = end_window_date { end_date = d; } else { end_date = transactions.last().expect("Need at least one transaction to generate data").timestamp.date(); } let dates = generate_dates(start_date, end_date); //Now generate a column where each date has the net amount transacted on that day let date_iter = dates.iter(); let transaction_iter = transactions.iter(); let mut transactions_map = BTreeMap::new(); for d in date_iter { transactions_map.insert(*d, 0.0); } for t in transaction_iter { if let Some(x) = transactions_map.get_mut(&t.timestamp.date()) { *x = *x + t.amount; } else { transactions_map.insert(t.timestamp.date(), t.amount); } } //Now create a column that will calculate the running total in the account let running_total: Vec<f64> = transactions_map.values().scan(0.0, |state, x| {*state = *state + x; Some(*state)}).collect(); let mut running_total_map = BTreeMap::new(); for (tx, a) in transactions_map.keys().zip(running_total.iter()) { running_total_map.insert(*tx, *a); } running_total_map } //Create a price entry //Structure of a price entry in the overall map is:: // (token, (date, (exchange token, ratio))) fn get_individual_price( pool: &(String, String), balance: &(chrono::Date<Utc>, (f64, f64)), m: &mut BTreeMap<String, BTreeMap<String, BTreeMap<chrono::Date<Utc>, f64>>>, token_index: usize) { let mut overall_token = &String::new(); let mut numerator = 0.0; let mut denominator = 1.0; let mut exchange_token = &String::new(); match token_index { 0 => { overall_token = &pool.0; numerator = balance.1.1; denominator = balance.1.0; exchange_token = &pool.1; }, 1 => { overall_token = &pool.1; numerator = balance.1.0; denominator = balance.1.1; exchange_token = &pool.0; }, _ => {} }; m.entry(overall_token.to_string()) .and_modify(|e| { e.entry(exchange_token.to_string()) .and_modify(|d| {d.insert(balance.0.clone(), numerator / denominator);}) .or_insert({ let mut map = BTreeMap::new(); map.insert(balance.0.clone(), numerator / denominator); map }); } ) .or_insert( { let mut t = BTreeMap::new(); let mut d = BTreeMap::new(); d.insert(balance.0.clone(), numerator / denominator); t.insert(exchange_token.to_string(), d.clone()); t } ); } fn calculate_price(pools: &BTreeMap<(String, String), Vec<(chrono::Date<Utc>, (f64, f64))>>) -> BTreeMap<String, BTreeMap<String, BTreeMap<chrono::Date<Utc>, f64>>> { let mut currency_map: BTreeMap<String, BTreeMap<String, BTreeMap<chrono::Date<Utc>, f64>>> = BTreeMap::new(); for (k, v) in pools { for balance in v.iter() { get_individual_price(k, balance, &mut currency_map, 0); get_individual_price(k, balance, &mut currency_map, 1); } } currency_map } //get price from the date or the closest date to it (in case current date doesn't have a price) fn lookup_price( token: &String, price_token: &str, date: chrono::Date<Utc>, prices: &BTreeMap<String, BTreeMap<String, BTreeMap<chrono::Date<Utc>, f64>>>) -> Option<f64> { let price_map = prices .get(token) .expect("Couldn't find prices for the token. If transaction exists a price must exist."); let exchange_map = price_map .get(price_token); if let Some(m) = exchange_map { //grab the latest date that is either the date itself, or preceding it if let Some(x) = m.iter().take_while(|d| *d.0 <= date).last() { Some(*x.1) } else { //if date we want is before any price data exists, //go backwards until we find the earliest date that follows the date we are looking for //this must return, because we have at least one date in our price map since the price map exists Some(*(m.iter().rev().take_while(|d| *d.0 > date).last().unwrap().1)) } } else { None } } fn calculate_cost_basis( token: &String, base_token: &str, transactions: &Vec<Transaction>, prices: &BTreeMap<String, BTreeMap<String, BTreeMap<chrono::Date<Utc>, f64>>>) -> BTreeMap<Date<Utc>, f64> { let mut cost_bases = Vec::<(Date<Utc>, f64, f64)>::new(); for tx in transactions { let last_cost_basis= cost_bases.iter().last(); //if transaction is a withdrawal, we simply deduct the number of tokens, CB hasn't changed if tx.amount < 0.0 { if let Some(x) = last_cost_basis { let last_n = x.1; let last_cost = x.2; cost_bases.push((tx.timestamp.date(), last_n + tx.amount, last_cost)); } } else { //if tx is a deposit, we need to find the new cost basis if let Some(x) = last_cost_basis { let n_tokens = x.1 + tx.amount; let price = lookup_price(&token, &base_token, tx.timestamp.date(), prices).expect(format!("No liquidity pool has been created between {} and the base token {}", token, base_token).as_str()); let new_cost = (x.1*x.2 + tx.amount * price) / n_tokens; cost_bases.push((tx.timestamp.date(), n_tokens, new_cost)); } else { let price = lookup_price(&token, &base_token, tx.timestamp.date(), prices).expect(format!("No liquidity pool has been created between {} and the base token {}", token, base_token).as_str()); cost_bases.push((tx.timestamp.date(), tx.amount, tx.amount * price)); } } } //now go through list of transactions, create an entry for each date. //since vector is in order, the last entry for a date will have the cost basis as of the end of the day let mut cost_map = BTreeMap::new(); for c in cost_bases { cost_map.insert(c.0, c.1 * c.2); } cost_map }
pub struct User { pub id: i32, pub data: UserData, } #[derive(Debug)] pub struct UserData { pub user_id: i64, pub name: String, }
use crate::{feed_generator::FeedGenerator, feed_worker::FeedWorker}; use actix_web::{middleware::Logger, App}; use log::error; use std::collections::BTreeMap; pub trait SourceBuilder { fn build_source() -> Source; } pub struct Source { pub prefix: &'static str, pub entries: BTreeMap<&'static str, FeedWorker>, } impl Source { pub fn new(prefix: &'static str) -> Self { Source { prefix, entries: BTreeMap::new(), } } pub fn register<T: FeedGenerator>(mut self, feed_generator: T) -> Self { let path = T::PATH; if self.entries.contains_key(path) { let error_message = format!( "duplicate path for {prefix}: {path}", prefix = self.prefix, path = path ); error!("{}", error_message); panic!(error_message); } let worker = FeedWorker::new(&self, feed_generator); self.entries.insert(path, worker); self } pub fn into_app(self) -> App { let mut result = App::new().prefix(self.prefix).middleware(Logger::default()); for i in self.entries.values() { let path = &i.path; let handler = i.clone().into_actix_web_handler(); result = result.resource(path, move |resource| resource.f(handler)); } result } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub const ATA_FLAGS_48BIT_COMMAND: u32 = 8u32; pub const ATA_FLAGS_DATA_IN: u32 = 2u32; pub const ATA_FLAGS_DATA_OUT: u32 = 4u32; pub const ATA_FLAGS_DRDY_REQUIRED: u32 = 1u32; pub const ATA_FLAGS_NO_MULTIPLE: u32 = 32u32; pub const ATA_FLAGS_USE_DMA: u32 = 16u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ATA_PASS_THROUGH_DIRECT { pub Length: u16, pub AtaFlags: u16, pub PathId: u8, pub TargetId: u8, pub Lun: u8, pub ReservedAsUchar: u8, pub DataTransferLength: u32, pub TimeOutValue: u32, pub ReservedAsUlong: u32, pub DataBuffer: *mut ::core::ffi::c_void, pub PreviousTaskFile: [u8; 8], pub CurrentTaskFile: [u8; 8], } impl ATA_PASS_THROUGH_DIRECT {} impl ::core::default::Default for ATA_PASS_THROUGH_DIRECT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ATA_PASS_THROUGH_DIRECT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ATA_PASS_THROUGH_DIRECT") .field("Length", &self.Length) .field("AtaFlags", &self.AtaFlags) .field("PathId", &self.PathId) .field("TargetId", &self.TargetId) .field("Lun", &self.Lun) .field("ReservedAsUchar", &self.ReservedAsUchar) .field("DataTransferLength", &self.DataTransferLength) .field("TimeOutValue", &self.TimeOutValue) .field("ReservedAsUlong", &self.ReservedAsUlong) .field("DataBuffer", &self.DataBuffer) .field("PreviousTaskFile", &self.PreviousTaskFile) .field("CurrentTaskFile", &self.CurrentTaskFile) .finish() } } impl ::core::cmp::PartialEq for ATA_PASS_THROUGH_DIRECT { fn eq(&self, other: &Self) -> bool { self.Length == other.Length && self.AtaFlags == other.AtaFlags && self.PathId == other.PathId && self.TargetId == other.TargetId && self.Lun == other.Lun && self.ReservedAsUchar == other.ReservedAsUchar && self.DataTransferLength == other.DataTransferLength && self.TimeOutValue == other.TimeOutValue && self.ReservedAsUlong == other.ReservedAsUlong && self.DataBuffer == other.DataBuffer && self.PreviousTaskFile == other.PreviousTaskFile && self.CurrentTaskFile == other.CurrentTaskFile } } impl ::core::cmp::Eq for ATA_PASS_THROUGH_DIRECT {} unsafe impl ::windows::core::Abi for ATA_PASS_THROUGH_DIRECT { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct ATA_PASS_THROUGH_DIRECT32 { pub Length: u16, pub AtaFlags: u16, pub PathId: u8, pub TargetId: u8, pub Lun: u8, pub ReservedAsUchar: u8, pub DataTransferLength: u32, pub TimeOutValue: u32, pub ReservedAsUlong: u32, pub DataBuffer: *mut ::core::ffi::c_void, pub PreviousTaskFile: [u8; 8], pub CurrentTaskFile: [u8; 8], } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ATA_PASS_THROUGH_DIRECT32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for ATA_PASS_THROUGH_DIRECT32 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for ATA_PASS_THROUGH_DIRECT32 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ATA_PASS_THROUGH_DIRECT32") .field("Length", &self.Length) .field("AtaFlags", &self.AtaFlags) .field("PathId", &self.PathId) .field("TargetId", &self.TargetId) .field("Lun", &self.Lun) .field("ReservedAsUchar", &self.ReservedAsUchar) .field("DataTransferLength", &self.DataTransferLength) .field("TimeOutValue", &self.TimeOutValue) .field("ReservedAsUlong", &self.ReservedAsUlong) .field("DataBuffer", &self.DataBuffer) .field("PreviousTaskFile", &self.PreviousTaskFile) .field("CurrentTaskFile", &self.CurrentTaskFile) .finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for ATA_PASS_THROUGH_DIRECT32 { fn eq(&self, other: &Self) -> bool { self.Length == other.Length && self.AtaFlags == other.AtaFlags && self.PathId == other.PathId && self.TargetId == other.TargetId && self.Lun == other.Lun && self.ReservedAsUchar == other.ReservedAsUchar && self.DataTransferLength == other.DataTransferLength && self.TimeOutValue == other.TimeOutValue && self.ReservedAsUlong == other.ReservedAsUlong && self.DataBuffer == other.DataBuffer && self.PreviousTaskFile == other.PreviousTaskFile && self.CurrentTaskFile == other.CurrentTaskFile } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for ATA_PASS_THROUGH_DIRECT32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for ATA_PASS_THROUGH_DIRECT32 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ATA_PASS_THROUGH_EX { pub Length: u16, pub AtaFlags: u16, pub PathId: u8, pub TargetId: u8, pub Lun: u8, pub ReservedAsUchar: u8, pub DataTransferLength: u32, pub TimeOutValue: u32, pub ReservedAsUlong: u32, pub DataBufferOffset: usize, pub PreviousTaskFile: [u8; 8], pub CurrentTaskFile: [u8; 8], } impl ATA_PASS_THROUGH_EX {} impl ::core::default::Default for ATA_PASS_THROUGH_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ATA_PASS_THROUGH_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ATA_PASS_THROUGH_EX") .field("Length", &self.Length) .field("AtaFlags", &self.AtaFlags) .field("PathId", &self.PathId) .field("TargetId", &self.TargetId) .field("Lun", &self.Lun) .field("ReservedAsUchar", &self.ReservedAsUchar) .field("DataTransferLength", &self.DataTransferLength) .field("TimeOutValue", &self.TimeOutValue) .field("ReservedAsUlong", &self.ReservedAsUlong) .field("DataBufferOffset", &self.DataBufferOffset) .field("PreviousTaskFile", &self.PreviousTaskFile) .field("CurrentTaskFile", &self.CurrentTaskFile) .finish() } } impl ::core::cmp::PartialEq for ATA_PASS_THROUGH_EX { fn eq(&self, other: &Self) -> bool { self.Length == other.Length && self.AtaFlags == other.AtaFlags && self.PathId == other.PathId && self.TargetId == other.TargetId && self.Lun == other.Lun && self.ReservedAsUchar == other.ReservedAsUchar && self.DataTransferLength == other.DataTransferLength && self.TimeOutValue == other.TimeOutValue && self.ReservedAsUlong == other.ReservedAsUlong && self.DataBufferOffset == other.DataBufferOffset && self.PreviousTaskFile == other.PreviousTaskFile && self.CurrentTaskFile == other.CurrentTaskFile } } impl ::core::cmp::Eq for ATA_PASS_THROUGH_EX {} unsafe impl ::windows::core::Abi for ATA_PASS_THROUGH_EX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct ATA_PASS_THROUGH_EX32 { pub Length: u16, pub AtaFlags: u16, pub PathId: u8, pub TargetId: u8, pub Lun: u8, pub ReservedAsUchar: u8, pub DataTransferLength: u32, pub TimeOutValue: u32, pub ReservedAsUlong: u32, pub DataBufferOffset: u32, pub PreviousTaskFile: [u8; 8], pub CurrentTaskFile: [u8; 8], } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ATA_PASS_THROUGH_EX32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for ATA_PASS_THROUGH_EX32 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for ATA_PASS_THROUGH_EX32 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ATA_PASS_THROUGH_EX32") .field("Length", &self.Length) .field("AtaFlags", &self.AtaFlags) .field("PathId", &self.PathId) .field("TargetId", &self.TargetId) .field("Lun", &self.Lun) .field("ReservedAsUchar", &self.ReservedAsUchar) .field("DataTransferLength", &self.DataTransferLength) .field("TimeOutValue", &self.TimeOutValue) .field("ReservedAsUlong", &self.ReservedAsUlong) .field("DataBufferOffset", &self.DataBufferOffset) .field("PreviousTaskFile", &self.PreviousTaskFile) .field("CurrentTaskFile", &self.CurrentTaskFile) .finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for ATA_PASS_THROUGH_EX32 { fn eq(&self, other: &Self) -> bool { self.Length == other.Length && self.AtaFlags == other.AtaFlags && self.PathId == other.PathId && self.TargetId == other.TargetId && self.Lun == other.Lun && self.ReservedAsUchar == other.ReservedAsUchar && self.DataTransferLength == other.DataTransferLength && self.TimeOutValue == other.TimeOutValue && self.ReservedAsUlong == other.ReservedAsUlong && self.DataBufferOffset == other.DataBufferOffset && self.PreviousTaskFile == other.PreviousTaskFile && self.CurrentTaskFile == other.CurrentTaskFile } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for ATA_PASS_THROUGH_EX32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for ATA_PASS_THROUGH_EX32 { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AddISNSServerA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(address: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AddISNSServerA(address: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(AddISNSServerA(address.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AddISNSServerW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(address: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AddISNSServerW(address: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(AddISNSServerW(address.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AddIScsiConnectionA<'a, Param7: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, reserved: *mut ::core::ffi::c_void, initiatorportnumber: u32, targetportal: *mut ISCSI_TARGET_PORTALA, securityflags: u64, loginoptions: *mut ISCSI_LOGIN_OPTIONS, keysize: u32, key: Param7, connectionid: *mut ISCSI_UNIQUE_SESSION_ID) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AddIScsiConnectionA(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, reserved: *mut ::core::ffi::c_void, initiatorportnumber: u32, targetportal: *mut ISCSI_TARGET_PORTALA, securityflags: u64, loginoptions: *mut ISCSI_LOGIN_OPTIONS, keysize: u32, key: super::super::Foundation::PSTR, connectionid: *mut ISCSI_UNIQUE_SESSION_ID) -> u32; } ::core::mem::transmute(AddIScsiConnectionA( ::core::mem::transmute(uniquesessionid), ::core::mem::transmute(reserved), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(targetportal), ::core::mem::transmute(securityflags), ::core::mem::transmute(loginoptions), ::core::mem::transmute(keysize), key.into_param().abi(), ::core::mem::transmute(connectionid), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AddIScsiConnectionW<'a, Param7: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, reserved: *mut ::core::ffi::c_void, initiatorportnumber: u32, targetportal: *mut ISCSI_TARGET_PORTALW, securityflags: u64, loginoptions: *mut ISCSI_LOGIN_OPTIONS, keysize: u32, key: Param7, connectionid: *mut ISCSI_UNIQUE_SESSION_ID) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AddIScsiConnectionW(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, reserved: *mut ::core::ffi::c_void, initiatorportnumber: u32, targetportal: *mut ISCSI_TARGET_PORTALW, securityflags: u64, loginoptions: *mut ISCSI_LOGIN_OPTIONS, keysize: u32, key: super::super::Foundation::PSTR, connectionid: *mut ISCSI_UNIQUE_SESSION_ID) -> u32; } ::core::mem::transmute(AddIScsiConnectionW( ::core::mem::transmute(uniquesessionid), ::core::mem::transmute(reserved), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(targetportal), ::core::mem::transmute(securityflags), ::core::mem::transmute(loginoptions), ::core::mem::transmute(keysize), key.into_param().abi(), ::core::mem::transmute(connectionid), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AddIScsiSendTargetPortalA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(initiatorinstance: Param0, initiatorportnumber: u32, loginoptions: *mut ISCSI_LOGIN_OPTIONS, securityflags: u64, portal: *mut ISCSI_TARGET_PORTALA) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AddIScsiSendTargetPortalA(initiatorinstance: super::super::Foundation::PSTR, initiatorportnumber: u32, loginoptions: *mut ISCSI_LOGIN_OPTIONS, securityflags: u64, portal: *mut ISCSI_TARGET_PORTALA) -> u32; } ::core::mem::transmute(AddIScsiSendTargetPortalA(initiatorinstance.into_param().abi(), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(loginoptions), ::core::mem::transmute(securityflags), ::core::mem::transmute(portal))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AddIScsiSendTargetPortalW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(initiatorinstance: Param0, initiatorportnumber: u32, loginoptions: *mut ISCSI_LOGIN_OPTIONS, securityflags: u64, portal: *mut ISCSI_TARGET_PORTALW) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AddIScsiSendTargetPortalW(initiatorinstance: super::super::Foundation::PWSTR, initiatorportnumber: u32, loginoptions: *mut ISCSI_LOGIN_OPTIONS, securityflags: u64, portal: *mut ISCSI_TARGET_PORTALW) -> u32; } ::core::mem::transmute(AddIScsiSendTargetPortalW(initiatorinstance.into_param().abi(), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(loginoptions), ::core::mem::transmute(securityflags), ::core::mem::transmute(portal))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AddIScsiStaticTargetA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>>(targetname: Param0, targetalias: Param1, targetflags: u32, persist: Param3, mappings: *mut ISCSI_TARGET_MAPPINGA, loginoptions: *mut ISCSI_LOGIN_OPTIONS, portalgroup: *mut ISCSI_TARGET_PORTAL_GROUPA) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AddIScsiStaticTargetA(targetname: super::super::Foundation::PSTR, targetalias: super::super::Foundation::PSTR, targetflags: u32, persist: super::super::Foundation::BOOLEAN, mappings: *mut ISCSI_TARGET_MAPPINGA, loginoptions: *mut ISCSI_LOGIN_OPTIONS, portalgroup: *mut ISCSI_TARGET_PORTAL_GROUPA) -> u32; } ::core::mem::transmute(AddIScsiStaticTargetA(targetname.into_param().abi(), targetalias.into_param().abi(), ::core::mem::transmute(targetflags), persist.into_param().abi(), ::core::mem::transmute(mappings), ::core::mem::transmute(loginoptions), ::core::mem::transmute(portalgroup))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AddIScsiStaticTargetW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>>(targetname: Param0, targetalias: Param1, targetflags: u32, persist: Param3, mappings: *mut ISCSI_TARGET_MAPPINGW, loginoptions: *mut ISCSI_LOGIN_OPTIONS, portalgroup: *mut ISCSI_TARGET_PORTAL_GROUPW) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AddIScsiStaticTargetW(targetname: super::super::Foundation::PWSTR, targetalias: super::super::Foundation::PWSTR, targetflags: u32, persist: super::super::Foundation::BOOLEAN, mappings: *mut ISCSI_TARGET_MAPPINGW, loginoptions: *mut ISCSI_LOGIN_OPTIONS, portalgroup: *mut ISCSI_TARGET_PORTAL_GROUPW) -> u32; } ::core::mem::transmute(AddIScsiStaticTargetW(targetname.into_param().abi(), targetalias.into_param().abi(), ::core::mem::transmute(targetflags), persist.into_param().abi(), ::core::mem::transmute(mappings), ::core::mem::transmute(loginoptions), ::core::mem::transmute(portalgroup))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AddPersistentIScsiDeviceA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(devicepath: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AddPersistentIScsiDeviceA(devicepath: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(AddPersistentIScsiDeviceA(devicepath.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AddPersistentIScsiDeviceW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(devicepath: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AddPersistentIScsiDeviceW(devicepath: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(AddPersistentIScsiDeviceW(devicepath.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AddRadiusServerA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(address: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AddRadiusServerA(address: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(AddRadiusServerA(address.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AddRadiusServerW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(address: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AddRadiusServerW(address: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(AddRadiusServerW(address.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ClearPersistentIScsiDevices() -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ClearPersistentIScsiDevices() -> u32; } ::core::mem::transmute(ClearPersistentIScsiDevices()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DSM_NOTIFICATION_REQUEST_BLOCK { pub Size: u32, pub Version: u32, pub NotifyFlags: u32, pub DataSetProfile: u32, pub Reserved: [u32; 3], pub DataSetRangesCount: u32, pub DataSetRanges: [MP_DEVICE_DATA_SET_RANGE; 1], } impl DSM_NOTIFICATION_REQUEST_BLOCK {} impl ::core::default::Default for DSM_NOTIFICATION_REQUEST_BLOCK { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DSM_NOTIFICATION_REQUEST_BLOCK { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DSM_NOTIFICATION_REQUEST_BLOCK") .field("Size", &self.Size) .field("Version", &self.Version) .field("NotifyFlags", &self.NotifyFlags) .field("DataSetProfile", &self.DataSetProfile) .field("Reserved", &self.Reserved) .field("DataSetRangesCount", &self.DataSetRangesCount) .field("DataSetRanges", &self.DataSetRanges) .finish() } } impl ::core::cmp::PartialEq for DSM_NOTIFICATION_REQUEST_BLOCK { fn eq(&self, other: &Self) -> bool { self.Size == other.Size && self.Version == other.Version && self.NotifyFlags == other.NotifyFlags && self.DataSetProfile == other.DataSetProfile && self.Reserved == other.Reserved && self.DataSetRangesCount == other.DataSetRangesCount && self.DataSetRanges == other.DataSetRanges } } impl ::core::cmp::Eq for DSM_NOTIFICATION_REQUEST_BLOCK {} unsafe impl ::windows::core::Abi for DSM_NOTIFICATION_REQUEST_BLOCK { type Abi = Self; } pub type DUMP_DEVICE_POWERON_ROUTINE = unsafe extern "system" fn(context: *const ::core::ffi::c_void) -> i32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DUMP_DRIVER { pub DumpDriverList: *mut ::core::ffi::c_void, pub DriverName: [u16; 15], pub BaseName: [u16; 15], } impl DUMP_DRIVER {} impl ::core::default::Default for DUMP_DRIVER { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DUMP_DRIVER { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DUMP_DRIVER").field("DumpDriverList", &self.DumpDriverList).field("DriverName", &self.DriverName).field("BaseName", &self.BaseName).finish() } } impl ::core::cmp::PartialEq for DUMP_DRIVER { fn eq(&self, other: &Self) -> bool { self.DumpDriverList == other.DumpDriverList && self.DriverName == other.DriverName && self.BaseName == other.BaseName } } impl ::core::cmp::Eq for DUMP_DRIVER {} unsafe impl ::windows::core::Abi for DUMP_DRIVER { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DUMP_DRIVER_EX { pub DumpDriverList: *mut ::core::ffi::c_void, pub DriverName: [u16; 15], pub BaseName: [u16; 15], pub DriverFullPath: NTSCSI_UNICODE_STRING, } #[cfg(feature = "Win32_Foundation")] impl DUMP_DRIVER_EX {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DUMP_DRIVER_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DUMP_DRIVER_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DUMP_DRIVER_EX").field("DumpDriverList", &self.DumpDriverList).field("DriverName", &self.DriverName).field("BaseName", &self.BaseName).field("DriverFullPath", &self.DriverFullPath).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DUMP_DRIVER_EX { fn eq(&self, other: &Self) -> bool { self.DumpDriverList == other.DumpDriverList && self.DriverName == other.DriverName && self.BaseName == other.BaseName && self.DriverFullPath == other.DriverFullPath } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DUMP_DRIVER_EX {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DUMP_DRIVER_EX { type Abi = Self; } pub const DUMP_DRIVER_NAME_LENGTH: u32 = 15u32; pub const DUMP_EX_FLAG_DRIVER_FULL_PATH_SUPPORT: u32 = 8u32; pub const DUMP_EX_FLAG_RESUME_SUPPORT: u32 = 4u32; pub const DUMP_EX_FLAG_SUPPORT_64BITMEMORY: u32 = 1u32; pub const DUMP_EX_FLAG_SUPPORT_DD_TELEMETRY: u32 = 2u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DUMP_POINTERS { pub AdapterObject: *mut _ADAPTER_OBJECT, pub MappedRegisterBase: *mut ::core::ffi::c_void, pub DumpData: *mut ::core::ffi::c_void, pub CommonBufferVa: *mut ::core::ffi::c_void, pub CommonBufferPa: i64, pub CommonBufferSize: u32, pub AllocateCommonBuffers: super::super::Foundation::BOOLEAN, pub UseDiskDump: super::super::Foundation::BOOLEAN, pub Spare1: [u8; 2], pub DeviceObject: *mut ::core::ffi::c_void, } #[cfg(feature = "Win32_Foundation")] impl DUMP_POINTERS {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DUMP_POINTERS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DUMP_POINTERS { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DUMP_POINTERS") .field("AdapterObject", &self.AdapterObject) .field("MappedRegisterBase", &self.MappedRegisterBase) .field("DumpData", &self.DumpData) .field("CommonBufferVa", &self.CommonBufferVa) .field("CommonBufferPa", &self.CommonBufferPa) .field("CommonBufferSize", &self.CommonBufferSize) .field("AllocateCommonBuffers", &self.AllocateCommonBuffers) .field("UseDiskDump", &self.UseDiskDump) .field("Spare1", &self.Spare1) .field("DeviceObject", &self.DeviceObject) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DUMP_POINTERS { fn eq(&self, other: &Self) -> bool { self.AdapterObject == other.AdapterObject && self.MappedRegisterBase == other.MappedRegisterBase && self.DumpData == other.DumpData && self.CommonBufferVa == other.CommonBufferVa && self.CommonBufferPa == other.CommonBufferPa && self.CommonBufferSize == other.CommonBufferSize && self.AllocateCommonBuffers == other.AllocateCommonBuffers && self.UseDiskDump == other.UseDiskDump && self.Spare1 == other.Spare1 && self.DeviceObject == other.DeviceObject } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DUMP_POINTERS {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DUMP_POINTERS { type Abi = Self; } #[derive(:: core :: clone :: Clone)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DUMP_POINTERS_EX { pub Header: DUMP_POINTERS_VERSION, pub DumpData: *mut ::core::ffi::c_void, pub CommonBufferVa: *mut ::core::ffi::c_void, pub CommonBufferSize: u32, pub AllocateCommonBuffers: super::super::Foundation::BOOLEAN, pub DeviceObject: *mut ::core::ffi::c_void, pub DriverList: *mut ::core::ffi::c_void, pub dwPortFlags: u32, pub MaxDeviceDumpSectionSize: u32, pub MaxDeviceDumpLevel: u32, pub MaxTransferSize: u32, pub AdapterObject: *mut ::core::ffi::c_void, pub MappedRegisterBase: *mut ::core::ffi::c_void, pub DeviceReady: *mut super::super::Foundation::BOOLEAN, pub DumpDevicePowerOn: ::core::option::Option<PDUMP_DEVICE_POWERON_ROUTINE>, pub DumpDevicePowerOnContext: *mut ::core::ffi::c_void, } #[cfg(feature = "Win32_Foundation")] impl DUMP_POINTERS_EX {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DUMP_POINTERS_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DUMP_POINTERS_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DUMP_POINTERS_EX") .field("Header", &self.Header) .field("DumpData", &self.DumpData) .field("CommonBufferVa", &self.CommonBufferVa) .field("CommonBufferSize", &self.CommonBufferSize) .field("AllocateCommonBuffers", &self.AllocateCommonBuffers) .field("DeviceObject", &self.DeviceObject) .field("DriverList", &self.DriverList) .field("dwPortFlags", &self.dwPortFlags) .field("MaxDeviceDumpSectionSize", &self.MaxDeviceDumpSectionSize) .field("MaxDeviceDumpLevel", &self.MaxDeviceDumpLevel) .field("MaxTransferSize", &self.MaxTransferSize) .field("AdapterObject", &self.AdapterObject) .field("MappedRegisterBase", &self.MappedRegisterBase) .field("DeviceReady", &self.DeviceReady) .field("DumpDevicePowerOnContext", &self.DumpDevicePowerOnContext) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DUMP_POINTERS_EX { fn eq(&self, other: &Self) -> bool { self.Header == other.Header && self.DumpData == other.DumpData && self.CommonBufferVa == other.CommonBufferVa && self.CommonBufferSize == other.CommonBufferSize && self.AllocateCommonBuffers == other.AllocateCommonBuffers && self.DeviceObject == other.DeviceObject && self.DriverList == other.DriverList && self.dwPortFlags == other.dwPortFlags && self.MaxDeviceDumpSectionSize == other.MaxDeviceDumpSectionSize && self.MaxDeviceDumpLevel == other.MaxDeviceDumpLevel && self.MaxTransferSize == other.MaxTransferSize && self.AdapterObject == other.AdapterObject && self.MappedRegisterBase == other.MappedRegisterBase && self.DeviceReady == other.DeviceReady && self.DumpDevicePowerOn.map(|f| f as usize) == other.DumpDevicePowerOn.map(|f| f as usize) && self.DumpDevicePowerOnContext == other.DumpDevicePowerOnContext } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DUMP_POINTERS_EX {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DUMP_POINTERS_EX { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DUMP_POINTERS_VERSION { pub Version: u32, pub Size: u32, } impl DUMP_POINTERS_VERSION {} impl ::core::default::Default for DUMP_POINTERS_VERSION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DUMP_POINTERS_VERSION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DUMP_POINTERS_VERSION").field("Version", &self.Version).field("Size", &self.Size).finish() } } impl ::core::cmp::PartialEq for DUMP_POINTERS_VERSION { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Size == other.Size } } impl ::core::cmp::Eq for DUMP_POINTERS_VERSION {} unsafe impl ::windows::core::Abi for DUMP_POINTERS_VERSION { type Abi = Self; } pub const DUMP_POINTERS_VERSION_1: u32 = 1u32; pub const DUMP_POINTERS_VERSION_2: u32 = 2u32; pub const DUMP_POINTERS_VERSION_3: u32 = 3u32; pub const DUMP_POINTERS_VERSION_4: u32 = 4u32; pub const FILE_DEVICE_SCSI: u32 = 27u32; pub const FIRMWARE_FUNCTION_ACTIVATE: u32 = 3u32; pub const FIRMWARE_FUNCTION_DOWNLOAD: u32 = 2u32; pub const FIRMWARE_FUNCTION_GET_INFO: u32 = 1u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct FIRMWARE_REQUEST_BLOCK { pub Version: u32, pub Size: u32, pub Function: u32, pub Flags: u32, pub DataBufferOffset: u32, pub DataBufferLength: u32, } impl FIRMWARE_REQUEST_BLOCK {} impl ::core::default::Default for FIRMWARE_REQUEST_BLOCK { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for FIRMWARE_REQUEST_BLOCK { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("FIRMWARE_REQUEST_BLOCK").field("Version", &self.Version).field("Size", &self.Size).field("Function", &self.Function).field("Flags", &self.Flags).field("DataBufferOffset", &self.DataBufferOffset).field("DataBufferLength", &self.DataBufferLength).finish() } } impl ::core::cmp::PartialEq for FIRMWARE_REQUEST_BLOCK { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Size == other.Size && self.Function == other.Function && self.Flags == other.Flags && self.DataBufferOffset == other.DataBufferOffset && self.DataBufferLength == other.DataBufferLength } } impl ::core::cmp::Eq for FIRMWARE_REQUEST_BLOCK {} unsafe impl ::windows::core::Abi for FIRMWARE_REQUEST_BLOCK { type Abi = Self; } pub const FIRMWARE_REQUEST_BLOCK_STRUCTURE_VERSION: u32 = 1u32; pub const FIRMWARE_REQUEST_FLAG_CONTROLLER: u32 = 1u32; pub const FIRMWARE_REQUEST_FLAG_FIRST_SEGMENT: u32 = 4u32; pub const FIRMWARE_REQUEST_FLAG_LAST_SEGMENT: u32 = 2u32; pub const FIRMWARE_REQUEST_FLAG_SWITCH_TO_EXISTING_FIRMWARE: u32 = 2147483648u32; pub const FIRMWARE_STATUS_COMMAND_ABORT: u32 = 133u32; pub const FIRMWARE_STATUS_CONTROLLER_ERROR: u32 = 16u32; pub const FIRMWARE_STATUS_DEVICE_ERROR: u32 = 64u32; pub const FIRMWARE_STATUS_END_OF_MEDIA: u32 = 134u32; pub const FIRMWARE_STATUS_ERROR: u32 = 1u32; pub const FIRMWARE_STATUS_ID_NOT_FOUND: u32 = 131u32; pub const FIRMWARE_STATUS_ILLEGAL_LENGTH: u32 = 135u32; pub const FIRMWARE_STATUS_ILLEGAL_REQUEST: u32 = 2u32; pub const FIRMWARE_STATUS_INPUT_BUFFER_TOO_BIG: u32 = 4u32; pub const FIRMWARE_STATUS_INTERFACE_CRC_ERROR: u32 = 128u32; pub const FIRMWARE_STATUS_INVALID_IMAGE: u32 = 7u32; pub const FIRMWARE_STATUS_INVALID_PARAMETER: u32 = 3u32; pub const FIRMWARE_STATUS_INVALID_SLOT: u32 = 6u32; pub const FIRMWARE_STATUS_MEDIA_CHANGE: u32 = 130u32; pub const FIRMWARE_STATUS_MEDIA_CHANGE_REQUEST: u32 = 132u32; pub const FIRMWARE_STATUS_OUTPUT_BUFFER_TOO_SMALL: u32 = 5u32; pub const FIRMWARE_STATUS_POWER_CYCLE_REQUIRED: u32 = 32u32; pub const FIRMWARE_STATUS_SUCCESS: u32 = 0u32; pub const FIRMWARE_STATUS_UNCORRECTABLE_DATA_ERROR: u32 = 129u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ioctl"))] #[inline] pub unsafe fn GetDevicesForIScsiSessionA(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, devicecount: *mut u32, devices: *mut ISCSI_DEVICE_ON_SESSIONA) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetDevicesForIScsiSessionA(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, devicecount: *mut u32, devices: *mut ISCSI_DEVICE_ON_SESSIONA) -> u32; } ::core::mem::transmute(GetDevicesForIScsiSessionA(::core::mem::transmute(uniquesessionid), ::core::mem::transmute(devicecount), ::core::mem::transmute(devices))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_System_Ioctl")] #[inline] pub unsafe fn GetDevicesForIScsiSessionW(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, devicecount: *mut u32, devices: *mut ISCSI_DEVICE_ON_SESSIONW) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetDevicesForIScsiSessionW(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, devicecount: *mut u32, devices: *mut ISCSI_DEVICE_ON_SESSIONW) -> u32; } ::core::mem::transmute(GetDevicesForIScsiSessionW(::core::mem::transmute(uniquesessionid), ::core::mem::transmute(devicecount), ::core::mem::transmute(devices))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetIScsiIKEInfoA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(initiatorname: Param0, initiatorportnumber: u32, reserved: *mut u32, authinfo: *mut IKE_AUTHENTICATION_INFORMATION) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetIScsiIKEInfoA(initiatorname: super::super::Foundation::PSTR, initiatorportnumber: u32, reserved: *mut u32, authinfo: *mut IKE_AUTHENTICATION_INFORMATION) -> u32; } ::core::mem::transmute(GetIScsiIKEInfoA(initiatorname.into_param().abi(), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(reserved), ::core::mem::transmute(authinfo))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetIScsiIKEInfoW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(initiatorname: Param0, initiatorportnumber: u32, reserved: *mut u32, authinfo: *mut IKE_AUTHENTICATION_INFORMATION) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetIScsiIKEInfoW(initiatorname: super::super::Foundation::PWSTR, initiatorportnumber: u32, reserved: *mut u32, authinfo: *mut IKE_AUTHENTICATION_INFORMATION) -> u32; } ::core::mem::transmute(GetIScsiIKEInfoW(initiatorname.into_param().abi(), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(reserved), ::core::mem::transmute(authinfo))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetIScsiInitiatorNodeNameA(initiatornodename: super::super::Foundation::PSTR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetIScsiInitiatorNodeNameA(initiatornodename: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(GetIScsiInitiatorNodeNameA(::core::mem::transmute(initiatornodename))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetIScsiInitiatorNodeNameW(initiatornodename: super::super::Foundation::PWSTR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetIScsiInitiatorNodeNameW(initiatornodename: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(GetIScsiInitiatorNodeNameW(::core::mem::transmute(initiatornodename))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetIScsiSessionListA(buffersize: *mut u32, sessioncount: *mut u32, sessioninfo: *mut ISCSI_SESSION_INFOA) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetIScsiSessionListA(buffersize: *mut u32, sessioncount: *mut u32, sessioninfo: *mut ISCSI_SESSION_INFOA) -> u32; } ::core::mem::transmute(GetIScsiSessionListA(::core::mem::transmute(buffersize), ::core::mem::transmute(sessioncount), ::core::mem::transmute(sessioninfo))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetIScsiSessionListEx(buffersize: *mut u32, sessioncountptr: *mut u32, sessioninfo: *mut ISCSI_SESSION_INFO_EX) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetIScsiSessionListEx(buffersize: *mut u32, sessioncountptr: *mut u32, sessioninfo: *mut ISCSI_SESSION_INFO_EX) -> u32; } ::core::mem::transmute(GetIScsiSessionListEx(::core::mem::transmute(buffersize), ::core::mem::transmute(sessioncountptr), ::core::mem::transmute(sessioninfo))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetIScsiSessionListW(buffersize: *mut u32, sessioncount: *mut u32, sessioninfo: *mut ISCSI_SESSION_INFOW) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetIScsiSessionListW(buffersize: *mut u32, sessioncount: *mut u32, sessioninfo: *mut ISCSI_SESSION_INFOW) -> u32; } ::core::mem::transmute(GetIScsiSessionListW(::core::mem::transmute(buffersize), ::core::mem::transmute(sessioncount), ::core::mem::transmute(sessioninfo))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetIScsiTargetInformationA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(targetname: Param0, discoverymechanism: Param1, infoclass: TARGET_INFORMATION_CLASS, buffersize: *mut u32, buffer: *mut ::core::ffi::c_void) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetIScsiTargetInformationA(targetname: super::super::Foundation::PSTR, discoverymechanism: super::super::Foundation::PSTR, infoclass: TARGET_INFORMATION_CLASS, buffersize: *mut u32, buffer: *mut ::core::ffi::c_void) -> u32; } ::core::mem::transmute(GetIScsiTargetInformationA(targetname.into_param().abi(), discoverymechanism.into_param().abi(), ::core::mem::transmute(infoclass), ::core::mem::transmute(buffersize), ::core::mem::transmute(buffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetIScsiTargetInformationW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(targetname: Param0, discoverymechanism: Param1, infoclass: TARGET_INFORMATION_CLASS, buffersize: *mut u32, buffer: *mut ::core::ffi::c_void) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetIScsiTargetInformationW(targetname: super::super::Foundation::PWSTR, discoverymechanism: super::super::Foundation::PWSTR, infoclass: TARGET_INFORMATION_CLASS, buffersize: *mut u32, buffer: *mut ::core::ffi::c_void) -> u32; } ::core::mem::transmute(GetIScsiTargetInformationW(targetname.into_param().abi(), discoverymechanism.into_param().abi(), ::core::mem::transmute(infoclass), ::core::mem::transmute(buffersize), ::core::mem::transmute(buffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn GetIScsiVersionInformation(versioninfo: *mut ISCSI_VERSION_INFO) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetIScsiVersionInformation(versioninfo: *mut ISCSI_VERSION_INFO) -> u32; } ::core::mem::transmute(GetIScsiVersionInformation(::core::mem::transmute(versioninfo))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct HYBRID_DEMOTE_BY_SIZE { pub Version: u32, pub Size: u32, pub SourcePriority: u8, pub TargetPriority: u8, pub Reserved0: u16, pub Reserved1: u32, pub LbaCount: u64, } impl HYBRID_DEMOTE_BY_SIZE {} impl ::core::default::Default for HYBRID_DEMOTE_BY_SIZE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for HYBRID_DEMOTE_BY_SIZE { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HYBRID_DEMOTE_BY_SIZE") .field("Version", &self.Version) .field("Size", &self.Size) .field("SourcePriority", &self.SourcePriority) .field("TargetPriority", &self.TargetPriority) .field("Reserved0", &self.Reserved0) .field("Reserved1", &self.Reserved1) .field("LbaCount", &self.LbaCount) .finish() } } impl ::core::cmp::PartialEq for HYBRID_DEMOTE_BY_SIZE { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Size == other.Size && self.SourcePriority == other.SourcePriority && self.TargetPriority == other.TargetPriority && self.Reserved0 == other.Reserved0 && self.Reserved1 == other.Reserved1 && self.LbaCount == other.LbaCount } } impl ::core::cmp::Eq for HYBRID_DEMOTE_BY_SIZE {} unsafe impl ::windows::core::Abi for HYBRID_DEMOTE_BY_SIZE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct HYBRID_DIRTY_THRESHOLDS { pub Version: u32, pub Size: u32, pub DirtyLowThreshold: u32, pub DirtyHighThreshold: u32, } impl HYBRID_DIRTY_THRESHOLDS {} impl ::core::default::Default for HYBRID_DIRTY_THRESHOLDS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for HYBRID_DIRTY_THRESHOLDS { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HYBRID_DIRTY_THRESHOLDS").field("Version", &self.Version).field("Size", &self.Size).field("DirtyLowThreshold", &self.DirtyLowThreshold).field("DirtyHighThreshold", &self.DirtyHighThreshold).finish() } } impl ::core::cmp::PartialEq for HYBRID_DIRTY_THRESHOLDS { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Size == other.Size && self.DirtyLowThreshold == other.DirtyLowThreshold && self.DirtyHighThreshold == other.DirtyHighThreshold } } impl ::core::cmp::Eq for HYBRID_DIRTY_THRESHOLDS {} unsafe impl ::windows::core::Abi for HYBRID_DIRTY_THRESHOLDS { type Abi = Self; } pub const HYBRID_FUNCTION_DEMOTE_BY_SIZE: u32 = 19u32; pub const HYBRID_FUNCTION_DISABLE_CACHING_MEDIUM: u32 = 16u32; pub const HYBRID_FUNCTION_ENABLE_CACHING_MEDIUM: u32 = 17u32; pub const HYBRID_FUNCTION_GET_INFO: u32 = 1u32; pub const HYBRID_FUNCTION_SET_DIRTY_THRESHOLD: u32 = 18u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HYBRID_INFORMATION { pub Version: u32, pub Size: u32, pub HybridSupported: super::super::Foundation::BOOLEAN, pub Status: NVCACHE_STATUS, pub CacheTypeEffective: NVCACHE_TYPE, pub CacheTypeDefault: NVCACHE_TYPE, pub FractionBase: u32, pub CacheSize: u64, pub Attributes: HYBRID_INFORMATION_0, pub Priorities: HYBRID_INFORMATION_1, } #[cfg(feature = "Win32_Foundation")] impl HYBRID_INFORMATION {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HYBRID_INFORMATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HYBRID_INFORMATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HYBRID_INFORMATION") .field("Version", &self.Version) .field("Size", &self.Size) .field("HybridSupported", &self.HybridSupported) .field("Status", &self.Status) .field("CacheTypeEffective", &self.CacheTypeEffective) .field("CacheTypeDefault", &self.CacheTypeDefault) .field("FractionBase", &self.FractionBase) .field("CacheSize", &self.CacheSize) .field("Attributes", &self.Attributes) .field("Priorities", &self.Priorities) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HYBRID_INFORMATION { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Size == other.Size && self.HybridSupported == other.HybridSupported && self.Status == other.Status && self.CacheTypeEffective == other.CacheTypeEffective && self.CacheTypeDefault == other.CacheTypeDefault && self.FractionBase == other.FractionBase && self.CacheSize == other.CacheSize && self.Attributes == other.Attributes && self.Priorities == other.Priorities } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HYBRID_INFORMATION {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HYBRID_INFORMATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HYBRID_INFORMATION_0 { pub _bitfield: u32, } #[cfg(feature = "Win32_Foundation")] impl HYBRID_INFORMATION_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HYBRID_INFORMATION_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HYBRID_INFORMATION_0 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_Attributes_e__Struct").field("_bitfield", &self._bitfield).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HYBRID_INFORMATION_0 { fn eq(&self, other: &Self) -> bool { self._bitfield == other._bitfield } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HYBRID_INFORMATION_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HYBRID_INFORMATION_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HYBRID_INFORMATION_1 { pub PriorityLevelCount: u8, pub MaxPriorityBehavior: super::super::Foundation::BOOLEAN, pub OptimalWriteGranularity: u8, pub Reserved: u8, pub DirtyThresholdLow: u32, pub DirtyThresholdHigh: u32, pub SupportedCommands: HYBRID_INFORMATION_1_0, pub Priority: [NVCACHE_PRIORITY_LEVEL_DESCRIPTOR; 1], } #[cfg(feature = "Win32_Foundation")] impl HYBRID_INFORMATION_1 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HYBRID_INFORMATION_1 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HYBRID_INFORMATION_1 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_Priorities_e__Struct") .field("PriorityLevelCount", &self.PriorityLevelCount) .field("MaxPriorityBehavior", &self.MaxPriorityBehavior) .field("OptimalWriteGranularity", &self.OptimalWriteGranularity) .field("Reserved", &self.Reserved) .field("DirtyThresholdLow", &self.DirtyThresholdLow) .field("DirtyThresholdHigh", &self.DirtyThresholdHigh) .field("SupportedCommands", &self.SupportedCommands) .field("Priority", &self.Priority) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HYBRID_INFORMATION_1 { fn eq(&self, other: &Self) -> bool { self.PriorityLevelCount == other.PriorityLevelCount && self.MaxPriorityBehavior == other.MaxPriorityBehavior && self.OptimalWriteGranularity == other.OptimalWriteGranularity && self.Reserved == other.Reserved && self.DirtyThresholdLow == other.DirtyThresholdLow && self.DirtyThresholdHigh == other.DirtyThresholdHigh && self.SupportedCommands == other.SupportedCommands && self.Priority == other.Priority } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HYBRID_INFORMATION_1 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HYBRID_INFORMATION_1 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HYBRID_INFORMATION_1_0 { pub _bitfield: u32, pub MaxEvictCommands: u32, pub MaxLbaRangeCountForEvict: u32, pub MaxLbaRangeCountForChangeLba: u32, } #[cfg(feature = "Win32_Foundation")] impl HYBRID_INFORMATION_1_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HYBRID_INFORMATION_1_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HYBRID_INFORMATION_1_0 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_SupportedCommands_e__Struct").field("_bitfield", &self._bitfield).field("MaxEvictCommands", &self.MaxEvictCommands).field("MaxLbaRangeCountForEvict", &self.MaxLbaRangeCountForEvict).field("MaxLbaRangeCountForChangeLba", &self.MaxLbaRangeCountForChangeLba).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HYBRID_INFORMATION_1_0 { fn eq(&self, other: &Self) -> bool { self._bitfield == other._bitfield && self.MaxEvictCommands == other.MaxEvictCommands && self.MaxLbaRangeCountForEvict == other.MaxLbaRangeCountForEvict && self.MaxLbaRangeCountForChangeLba == other.MaxLbaRangeCountForChangeLba } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HYBRID_INFORMATION_1_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HYBRID_INFORMATION_1_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct HYBRID_REQUEST_BLOCK { pub Version: u32, pub Size: u32, pub Function: u32, pub Flags: u32, pub DataBufferOffset: u32, pub DataBufferLength: u32, } impl HYBRID_REQUEST_BLOCK {} impl ::core::default::Default for HYBRID_REQUEST_BLOCK { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for HYBRID_REQUEST_BLOCK { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HYBRID_REQUEST_BLOCK").field("Version", &self.Version).field("Size", &self.Size).field("Function", &self.Function).field("Flags", &self.Flags).field("DataBufferOffset", &self.DataBufferOffset).field("DataBufferLength", &self.DataBufferLength).finish() } } impl ::core::cmp::PartialEq for HYBRID_REQUEST_BLOCK { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Size == other.Size && self.Function == other.Function && self.Flags == other.Flags && self.DataBufferOffset == other.DataBufferOffset && self.DataBufferLength == other.DataBufferLength } } impl ::core::cmp::Eq for HYBRID_REQUEST_BLOCK {} unsafe impl ::windows::core::Abi for HYBRID_REQUEST_BLOCK { type Abi = Self; } pub const HYBRID_REQUEST_BLOCK_STRUCTURE_VERSION: u32 = 1u32; pub const HYBRID_REQUEST_INFO_STRUCTURE_VERSION: u32 = 1u32; pub const HYBRID_STATUS_ENABLE_REFCOUNT_HOLD: u32 = 16u32; pub const HYBRID_STATUS_ILLEGAL_REQUEST: u32 = 1u32; pub const HYBRID_STATUS_INVALID_PARAMETER: u32 = 2u32; pub const HYBRID_STATUS_OUTPUT_BUFFER_TOO_SMALL: u32 = 3u32; pub const HYBRID_STATUS_SUCCESS: u32 = 0u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct IDE_IO_CONTROL { pub HeaderLength: u32, pub Signature: [u8; 8], pub Timeout: u32, pub ControlCode: u32, pub ReturnStatus: u32, pub DataLength: u32, } impl IDE_IO_CONTROL {} impl ::core::default::Default for IDE_IO_CONTROL { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for IDE_IO_CONTROL { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("IDE_IO_CONTROL").field("HeaderLength", &self.HeaderLength).field("Signature", &self.Signature).field("Timeout", &self.Timeout).field("ControlCode", &self.ControlCode).field("ReturnStatus", &self.ReturnStatus).field("DataLength", &self.DataLength).finish() } } impl ::core::cmp::PartialEq for IDE_IO_CONTROL { fn eq(&self, other: &Self) -> bool { self.HeaderLength == other.HeaderLength && self.Signature == other.Signature && self.Timeout == other.Timeout && self.ControlCode == other.ControlCode && self.ReturnStatus == other.ReturnStatus && self.DataLength == other.DataLength } } impl ::core::cmp::Eq for IDE_IO_CONTROL {} unsafe impl ::windows::core::Abi for IDE_IO_CONTROL { type Abi = Self; } pub const ID_FQDN: u32 = 2u32; pub const ID_IPV4_ADDR: u32 = 1u32; pub const ID_IPV6_ADDR: u32 = 5u32; pub const ID_USER_FQDN: u32 = 3u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct IKE_AUTHENTICATION_INFORMATION { pub AuthMethod: IKE_AUTHENTICATION_METHOD, pub Anonymous: IKE_AUTHENTICATION_INFORMATION_0, } impl IKE_AUTHENTICATION_INFORMATION {} impl ::core::default::Default for IKE_AUTHENTICATION_INFORMATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for IKE_AUTHENTICATION_INFORMATION { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for IKE_AUTHENTICATION_INFORMATION {} unsafe impl ::windows::core::Abi for IKE_AUTHENTICATION_INFORMATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub union IKE_AUTHENTICATION_INFORMATION_0 { pub PsKey: IKE_AUTHENTICATION_PRESHARED_KEY, } impl IKE_AUTHENTICATION_INFORMATION_0 {} impl ::core::default::Default for IKE_AUTHENTICATION_INFORMATION_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for IKE_AUTHENTICATION_INFORMATION_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for IKE_AUTHENTICATION_INFORMATION_0 {} unsafe impl ::windows::core::Abi for IKE_AUTHENTICATION_INFORMATION_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 IKE_AUTHENTICATION_METHOD(pub i32); pub const IKE_AUTHENTICATION_PRESHARED_KEY_METHOD: IKE_AUTHENTICATION_METHOD = IKE_AUTHENTICATION_METHOD(1i32); impl ::core::convert::From<i32> for IKE_AUTHENTICATION_METHOD { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for IKE_AUTHENTICATION_METHOD { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct IKE_AUTHENTICATION_PRESHARED_KEY { pub SecurityFlags: u64, pub IdType: u8, pub IdLengthInBytes: u32, pub Id: *mut u8, pub KeyLengthInBytes: u32, pub Key: *mut u8, } impl IKE_AUTHENTICATION_PRESHARED_KEY {} impl ::core::default::Default for IKE_AUTHENTICATION_PRESHARED_KEY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for IKE_AUTHENTICATION_PRESHARED_KEY { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("IKE_AUTHENTICATION_PRESHARED_KEY").field("SecurityFlags", &self.SecurityFlags).field("IdType", &self.IdType).field("IdLengthInBytes", &self.IdLengthInBytes).field("Id", &self.Id).field("KeyLengthInBytes", &self.KeyLengthInBytes).field("Key", &self.Key).finish() } } impl ::core::cmp::PartialEq for IKE_AUTHENTICATION_PRESHARED_KEY { fn eq(&self, other: &Self) -> bool { self.SecurityFlags == other.SecurityFlags && self.IdType == other.IdType && self.IdLengthInBytes == other.IdLengthInBytes && self.Id == other.Id && self.KeyLengthInBytes == other.KeyLengthInBytes && self.Key == other.Key } } impl ::core::cmp::Eq for IKE_AUTHENTICATION_PRESHARED_KEY {} unsafe impl ::windows::core::Abi for IKE_AUTHENTICATION_PRESHARED_KEY { type Abi = Self; } pub const IOCTL_ATA_MINIPORT: u32 = 315444u32; pub const IOCTL_ATA_PASS_THROUGH: u32 = 315436u32; pub const IOCTL_ATA_PASS_THROUGH_DIRECT: u32 = 315440u32; pub const IOCTL_IDE_PASS_THROUGH: u32 = 315432u32; pub const IOCTL_MINIPORT_PROCESS_SERVICE_IRP: u32 = 315448u32; pub const IOCTL_MPIO_PASS_THROUGH_PATH: u32 = 315452u32; pub const IOCTL_MPIO_PASS_THROUGH_PATH_DIRECT: u32 = 315456u32; pub const IOCTL_MPIO_PASS_THROUGH_PATH_DIRECT_EX: u32 = 315472u32; pub const IOCTL_MPIO_PASS_THROUGH_PATH_EX: u32 = 315468u32; pub const IOCTL_SCSI_BASE: u32 = 4u32; pub const IOCTL_SCSI_FREE_DUMP_POINTERS: u32 = 266276u32; pub const IOCTL_SCSI_GET_ADDRESS: u32 = 266264u32; pub const IOCTL_SCSI_GET_CAPABILITIES: u32 = 266256u32; pub const IOCTL_SCSI_GET_DUMP_POINTERS: u32 = 266272u32; pub const IOCTL_SCSI_GET_INQUIRY_DATA: u32 = 266252u32; pub const IOCTL_SCSI_MINIPORT: u32 = 315400u32; pub const IOCTL_SCSI_PASS_THROUGH: u32 = 315396u32; pub const IOCTL_SCSI_PASS_THROUGH_DIRECT: u32 = 315412u32; pub const IOCTL_SCSI_PASS_THROUGH_DIRECT_EX: u32 = 315464u32; pub const IOCTL_SCSI_PASS_THROUGH_EX: u32 = 315460u32; pub const IOCTL_SCSI_RESCAN_BUS: u32 = 266268u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct IO_SCSI_CAPABILITIES { pub Length: u32, pub MaximumTransferLength: u32, pub MaximumPhysicalPages: u32, pub SupportedAsynchronousEvents: u32, pub AlignmentMask: u32, pub TaggedQueuing: super::super::Foundation::BOOLEAN, pub AdapterScansDown: super::super::Foundation::BOOLEAN, pub AdapterUsesPio: super::super::Foundation::BOOLEAN, } #[cfg(feature = "Win32_Foundation")] impl IO_SCSI_CAPABILITIES {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for IO_SCSI_CAPABILITIES { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for IO_SCSI_CAPABILITIES { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("IO_SCSI_CAPABILITIES") .field("Length", &self.Length) .field("MaximumTransferLength", &self.MaximumTransferLength) .field("MaximumPhysicalPages", &self.MaximumPhysicalPages) .field("SupportedAsynchronousEvents", &self.SupportedAsynchronousEvents) .field("AlignmentMask", &self.AlignmentMask) .field("TaggedQueuing", &self.TaggedQueuing) .field("AdapterScansDown", &self.AdapterScansDown) .field("AdapterUsesPio", &self.AdapterUsesPio) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for IO_SCSI_CAPABILITIES { fn eq(&self, other: &Self) -> bool { self.Length == other.Length && self.MaximumTransferLength == other.MaximumTransferLength && self.MaximumPhysicalPages == other.MaximumPhysicalPages && self.SupportedAsynchronousEvents == other.SupportedAsynchronousEvents && self.AlignmentMask == other.AlignmentMask && self.TaggedQueuing == other.TaggedQueuing && self.AdapterScansDown == other.AdapterScansDown && self.AdapterUsesPio == other.AdapterUsesPio } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for IO_SCSI_CAPABILITIES {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for IO_SCSI_CAPABILITIES { 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 ISCSI_AUTH_TYPES(pub i32); pub const ISCSI_NO_AUTH_TYPE: ISCSI_AUTH_TYPES = ISCSI_AUTH_TYPES(0i32); pub const ISCSI_CHAP_AUTH_TYPE: ISCSI_AUTH_TYPES = ISCSI_AUTH_TYPES(1i32); pub const ISCSI_MUTUAL_CHAP_AUTH_TYPE: ISCSI_AUTH_TYPES = ISCSI_AUTH_TYPES(2i32); impl ::core::convert::From<i32> for ISCSI_AUTH_TYPES { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ISCSI_AUTH_TYPES { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct ISCSI_CONNECTION_INFOA { pub ConnectionId: ISCSI_UNIQUE_SESSION_ID, pub InitiatorAddress: super::super::Foundation::PSTR, pub TargetAddress: super::super::Foundation::PSTR, pub InitiatorSocket: u16, pub TargetSocket: u16, pub CID: [u8; 2], } #[cfg(feature = "Win32_Foundation")] impl ISCSI_CONNECTION_INFOA {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for ISCSI_CONNECTION_INFOA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for ISCSI_CONNECTION_INFOA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_CONNECTION_INFOA") .field("ConnectionId", &self.ConnectionId) .field("InitiatorAddress", &self.InitiatorAddress) .field("TargetAddress", &self.TargetAddress) .field("InitiatorSocket", &self.InitiatorSocket) .field("TargetSocket", &self.TargetSocket) .field("CID", &self.CID) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for ISCSI_CONNECTION_INFOA { fn eq(&self, other: &Self) -> bool { self.ConnectionId == other.ConnectionId && self.InitiatorAddress == other.InitiatorAddress && self.TargetAddress == other.TargetAddress && self.InitiatorSocket == other.InitiatorSocket && self.TargetSocket == other.TargetSocket && self.CID == other.CID } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for ISCSI_CONNECTION_INFOA {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for ISCSI_CONNECTION_INFOA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct ISCSI_CONNECTION_INFOW { pub ConnectionId: ISCSI_UNIQUE_SESSION_ID, pub InitiatorAddress: super::super::Foundation::PWSTR, pub TargetAddress: super::super::Foundation::PWSTR, pub InitiatorSocket: u16, pub TargetSocket: u16, pub CID: [u8; 2], } #[cfg(feature = "Win32_Foundation")] impl ISCSI_CONNECTION_INFOW {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for ISCSI_CONNECTION_INFOW { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for ISCSI_CONNECTION_INFOW { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_CONNECTION_INFOW") .field("ConnectionId", &self.ConnectionId) .field("InitiatorAddress", &self.InitiatorAddress) .field("TargetAddress", &self.TargetAddress) .field("InitiatorSocket", &self.InitiatorSocket) .field("TargetSocket", &self.TargetSocket) .field("CID", &self.CID) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for ISCSI_CONNECTION_INFOW { fn eq(&self, other: &Self) -> bool { self.ConnectionId == other.ConnectionId && self.InitiatorAddress == other.InitiatorAddress && self.TargetAddress == other.TargetAddress && self.InitiatorSocket == other.InitiatorSocket && self.TargetSocket == other.TargetSocket && self.CID == other.CID } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for ISCSI_CONNECTION_INFOW {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for ISCSI_CONNECTION_INFOW { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ISCSI_CONNECTION_INFO_EX { pub ConnectionId: ISCSI_UNIQUE_SESSION_ID, pub State: u8, pub Protocol: u8, pub HeaderDigest: u8, pub DataDigest: u8, pub MaxRecvDataSegmentLength: u32, pub AuthType: ISCSI_AUTH_TYPES, pub EstimatedThroughput: u64, pub MaxDatagramSize: u32, } impl ISCSI_CONNECTION_INFO_EX {} impl ::core::default::Default for ISCSI_CONNECTION_INFO_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ISCSI_CONNECTION_INFO_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_CONNECTION_INFO_EX") .field("ConnectionId", &self.ConnectionId) .field("State", &self.State) .field("Protocol", &self.Protocol) .field("HeaderDigest", &self.HeaderDigest) .field("DataDigest", &self.DataDigest) .field("MaxRecvDataSegmentLength", &self.MaxRecvDataSegmentLength) .field("AuthType", &self.AuthType) .field("EstimatedThroughput", &self.EstimatedThroughput) .field("MaxDatagramSize", &self.MaxDatagramSize) .finish() } } impl ::core::cmp::PartialEq for ISCSI_CONNECTION_INFO_EX { fn eq(&self, other: &Self) -> bool { self.ConnectionId == other.ConnectionId && self.State == other.State && self.Protocol == other.Protocol && self.HeaderDigest == other.HeaderDigest && self.DataDigest == other.DataDigest && self.MaxRecvDataSegmentLength == other.MaxRecvDataSegmentLength && self.AuthType == other.AuthType && self.EstimatedThroughput == other.EstimatedThroughput && self.MaxDatagramSize == other.MaxDatagramSize } } impl ::core::cmp::Eq for ISCSI_CONNECTION_INFO_EX {} unsafe impl ::windows::core::Abi for ISCSI_CONNECTION_INFO_EX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ioctl"))] pub struct ISCSI_DEVICE_ON_SESSIONA { pub InitiatorName: [super::super::Foundation::CHAR; 256], pub TargetName: [super::super::Foundation::CHAR; 224], pub ScsiAddress: SCSI_ADDRESS, pub DeviceInterfaceType: ::windows::core::GUID, pub DeviceInterfaceName: [super::super::Foundation::CHAR; 260], pub LegacyName: [super::super::Foundation::CHAR; 260], pub StorageDeviceNumber: super::super::System::Ioctl::STORAGE_DEVICE_NUMBER, pub DeviceInstance: u32, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ioctl"))] impl ISCSI_DEVICE_ON_SESSIONA {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ioctl"))] impl ::core::default::Default for ISCSI_DEVICE_ON_SESSIONA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ioctl"))] impl ::core::fmt::Debug for ISCSI_DEVICE_ON_SESSIONA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_DEVICE_ON_SESSIONA") .field("InitiatorName", &self.InitiatorName) .field("TargetName", &self.TargetName) .field("ScsiAddress", &self.ScsiAddress) .field("DeviceInterfaceType", &self.DeviceInterfaceType) .field("DeviceInterfaceName", &self.DeviceInterfaceName) .field("LegacyName", &self.LegacyName) .field("StorageDeviceNumber", &self.StorageDeviceNumber) .field("DeviceInstance", &self.DeviceInstance) .finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ioctl"))] impl ::core::cmp::PartialEq for ISCSI_DEVICE_ON_SESSIONA { fn eq(&self, other: &Self) -> bool { self.InitiatorName == other.InitiatorName && self.TargetName == other.TargetName && self.ScsiAddress == other.ScsiAddress && self.DeviceInterfaceType == other.DeviceInterfaceType && self.DeviceInterfaceName == other.DeviceInterfaceName && self.LegacyName == other.LegacyName && self.StorageDeviceNumber == other.StorageDeviceNumber && self.DeviceInstance == other.DeviceInstance } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ioctl"))] impl ::core::cmp::Eq for ISCSI_DEVICE_ON_SESSIONA {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ioctl"))] unsafe impl ::windows::core::Abi for ISCSI_DEVICE_ON_SESSIONA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_System_Ioctl")] pub struct ISCSI_DEVICE_ON_SESSIONW { pub InitiatorName: [u16; 256], pub TargetName: [u16; 224], pub ScsiAddress: SCSI_ADDRESS, pub DeviceInterfaceType: ::windows::core::GUID, pub DeviceInterfaceName: [u16; 260], pub LegacyName: [u16; 260], pub StorageDeviceNumber: super::super::System::Ioctl::STORAGE_DEVICE_NUMBER, pub DeviceInstance: u32, } #[cfg(feature = "Win32_System_Ioctl")] impl ISCSI_DEVICE_ON_SESSIONW {} #[cfg(feature = "Win32_System_Ioctl")] impl ::core::default::Default for ISCSI_DEVICE_ON_SESSIONW { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_System_Ioctl")] impl ::core::fmt::Debug for ISCSI_DEVICE_ON_SESSIONW { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_DEVICE_ON_SESSIONW") .field("InitiatorName", &self.InitiatorName) .field("TargetName", &self.TargetName) .field("ScsiAddress", &self.ScsiAddress) .field("DeviceInterfaceType", &self.DeviceInterfaceType) .field("DeviceInterfaceName", &self.DeviceInterfaceName) .field("LegacyName", &self.LegacyName) .field("StorageDeviceNumber", &self.StorageDeviceNumber) .field("DeviceInstance", &self.DeviceInstance) .finish() } } #[cfg(feature = "Win32_System_Ioctl")] impl ::core::cmp::PartialEq for ISCSI_DEVICE_ON_SESSIONW { fn eq(&self, other: &Self) -> bool { self.InitiatorName == other.InitiatorName && self.TargetName == other.TargetName && self.ScsiAddress == other.ScsiAddress && self.DeviceInterfaceType == other.DeviceInterfaceType && self.DeviceInterfaceName == other.DeviceInterfaceName && self.LegacyName == other.LegacyName && self.StorageDeviceNumber == other.StorageDeviceNumber && self.DeviceInstance == other.DeviceInstance } } #[cfg(feature = "Win32_System_Ioctl")] impl ::core::cmp::Eq for ISCSI_DEVICE_ON_SESSIONW {} #[cfg(feature = "Win32_System_Ioctl")] unsafe impl ::windows::core::Abi for ISCSI_DEVICE_ON_SESSIONW { 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 ISCSI_DIGEST_TYPES(pub i32); pub const ISCSI_DIGEST_TYPE_NONE: ISCSI_DIGEST_TYPES = ISCSI_DIGEST_TYPES(0i32); pub const ISCSI_DIGEST_TYPE_CRC32C: ISCSI_DIGEST_TYPES = ISCSI_DIGEST_TYPES(1i32); impl ::core::convert::From<i32> for ISCSI_DIGEST_TYPES { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ISCSI_DIGEST_TYPES { type Abi = Self; } pub const ISCSI_LOGIN_FLAG_ALLOW_PORTAL_HOPPING: u32 = 8u32; pub const ISCSI_LOGIN_FLAG_MULTIPATH_ENABLED: u32 = 2u32; pub const ISCSI_LOGIN_FLAG_REQUIRE_IPSEC: u32 = 1u32; pub const ISCSI_LOGIN_FLAG_RESERVED1: u32 = 4u32; pub const ISCSI_LOGIN_FLAG_USE_RADIUS_RESPONSE: u32 = 16u32; pub const ISCSI_LOGIN_FLAG_USE_RADIUS_VERIFICATION: u32 = 32u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ISCSI_LOGIN_OPTIONS { pub Version: u32, pub InformationSpecified: u32, pub LoginFlags: u32, pub AuthType: ISCSI_AUTH_TYPES, pub HeaderDigest: ISCSI_DIGEST_TYPES, pub DataDigest: ISCSI_DIGEST_TYPES, pub MaximumConnections: u32, pub DefaultTime2Wait: u32, pub DefaultTime2Retain: u32, pub UsernameLength: u32, pub PasswordLength: u32, pub Username: *mut u8, pub Password: *mut u8, } impl ISCSI_LOGIN_OPTIONS {} impl ::core::default::Default for ISCSI_LOGIN_OPTIONS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ISCSI_LOGIN_OPTIONS { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_LOGIN_OPTIONS") .field("Version", &self.Version) .field("InformationSpecified", &self.InformationSpecified) .field("LoginFlags", &self.LoginFlags) .field("AuthType", &self.AuthType) .field("HeaderDigest", &self.HeaderDigest) .field("DataDigest", &self.DataDigest) .field("MaximumConnections", &self.MaximumConnections) .field("DefaultTime2Wait", &self.DefaultTime2Wait) .field("DefaultTime2Retain", &self.DefaultTime2Retain) .field("UsernameLength", &self.UsernameLength) .field("PasswordLength", &self.PasswordLength) .field("Username", &self.Username) .field("Password", &self.Password) .finish() } } impl ::core::cmp::PartialEq for ISCSI_LOGIN_OPTIONS { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.InformationSpecified == other.InformationSpecified && self.LoginFlags == other.LoginFlags && self.AuthType == other.AuthType && self.HeaderDigest == other.HeaderDigest && self.DataDigest == other.DataDigest && self.MaximumConnections == other.MaximumConnections && self.DefaultTime2Wait == other.DefaultTime2Wait && self.DefaultTime2Retain == other.DefaultTime2Retain && self.UsernameLength == other.UsernameLength && self.PasswordLength == other.PasswordLength && self.Username == other.Username && self.Password == other.Password } } impl ::core::cmp::Eq for ISCSI_LOGIN_OPTIONS {} unsafe impl ::windows::core::Abi for ISCSI_LOGIN_OPTIONS { type Abi = Self; } pub const ISCSI_LOGIN_OPTIONS_AUTH_TYPE: u32 = 128u32; pub const ISCSI_LOGIN_OPTIONS_DATA_DIGEST: u32 = 2u32; pub const ISCSI_LOGIN_OPTIONS_DEFAULT_TIME_2_RETAIN: u32 = 16u32; pub const ISCSI_LOGIN_OPTIONS_DEFAULT_TIME_2_WAIT: u32 = 8u32; pub const ISCSI_LOGIN_OPTIONS_HEADER_DIGEST: u32 = 1u32; pub const ISCSI_LOGIN_OPTIONS_MAXIMUM_CONNECTIONS: u32 = 4u32; pub const ISCSI_LOGIN_OPTIONS_PASSWORD: u32 = 64u32; pub const ISCSI_LOGIN_OPTIONS_USERNAME: u32 = 32u32; pub const ISCSI_LOGIN_OPTIONS_VERSION: u32 = 0u32; pub const ISCSI_SECURITY_FLAG_AGGRESSIVE_MODE_ENABLED: u32 = 8u32; pub const ISCSI_SECURITY_FLAG_IKE_IPSEC_ENABLED: u32 = 2u32; pub const ISCSI_SECURITY_FLAG_MAIN_MODE_ENABLED: u32 = 4u32; pub const ISCSI_SECURITY_FLAG_PFS_ENABLED: u32 = 16u32; pub const ISCSI_SECURITY_FLAG_TRANSPORT_MODE_PREFERRED: u32 = 32u32; pub const ISCSI_SECURITY_FLAG_TUNNEL_MODE_PREFERRED: u32 = 64u32; pub const ISCSI_SECURITY_FLAG_VALID: u32 = 1u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct ISCSI_SESSION_INFOA { pub SessionId: ISCSI_UNIQUE_SESSION_ID, pub InitiatorName: super::super::Foundation::PSTR, pub TargetNodeName: super::super::Foundation::PSTR, pub TargetName: super::super::Foundation::PSTR, pub ISID: [u8; 6], pub TSID: [u8; 2], pub ConnectionCount: u32, pub Connections: *mut ISCSI_CONNECTION_INFOA, } #[cfg(feature = "Win32_Foundation")] impl ISCSI_SESSION_INFOA {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for ISCSI_SESSION_INFOA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for ISCSI_SESSION_INFOA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_SESSION_INFOA") .field("SessionId", &self.SessionId) .field("InitiatorName", &self.InitiatorName) .field("TargetNodeName", &self.TargetNodeName) .field("TargetName", &self.TargetName) .field("ISID", &self.ISID) .field("TSID", &self.TSID) .field("ConnectionCount", &self.ConnectionCount) .field("Connections", &self.Connections) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for ISCSI_SESSION_INFOA { fn eq(&self, other: &Self) -> bool { self.SessionId == other.SessionId && self.InitiatorName == other.InitiatorName && self.TargetNodeName == other.TargetNodeName && self.TargetName == other.TargetName && self.ISID == other.ISID && self.TSID == other.TSID && self.ConnectionCount == other.ConnectionCount && self.Connections == other.Connections } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for ISCSI_SESSION_INFOA {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for ISCSI_SESSION_INFOA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct ISCSI_SESSION_INFOW { pub SessionId: ISCSI_UNIQUE_SESSION_ID, pub InitiatorName: super::super::Foundation::PWSTR, pub TargetNodeName: super::super::Foundation::PWSTR, pub TargetName: super::super::Foundation::PWSTR, pub ISID: [u8; 6], pub TSID: [u8; 2], pub ConnectionCount: u32, pub Connections: *mut ISCSI_CONNECTION_INFOW, } #[cfg(feature = "Win32_Foundation")] impl ISCSI_SESSION_INFOW {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for ISCSI_SESSION_INFOW { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for ISCSI_SESSION_INFOW { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_SESSION_INFOW") .field("SessionId", &self.SessionId) .field("InitiatorName", &self.InitiatorName) .field("TargetNodeName", &self.TargetNodeName) .field("TargetName", &self.TargetName) .field("ISID", &self.ISID) .field("TSID", &self.TSID) .field("ConnectionCount", &self.ConnectionCount) .field("Connections", &self.Connections) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for ISCSI_SESSION_INFOW { fn eq(&self, other: &Self) -> bool { self.SessionId == other.SessionId && self.InitiatorName == other.InitiatorName && self.TargetNodeName == other.TargetNodeName && self.TargetName == other.TargetName && self.ISID == other.ISID && self.TSID == other.TSID && self.ConnectionCount == other.ConnectionCount && self.Connections == other.Connections } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for ISCSI_SESSION_INFOW {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for ISCSI_SESSION_INFOW { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct ISCSI_SESSION_INFO_EX { pub SessionId: ISCSI_UNIQUE_SESSION_ID, pub InitialR2t: super::super::Foundation::BOOLEAN, pub ImmediateData: super::super::Foundation::BOOLEAN, pub Type: u8, pub DataSequenceInOrder: super::super::Foundation::BOOLEAN, pub DataPduInOrder: super::super::Foundation::BOOLEAN, pub ErrorRecoveryLevel: u8, pub MaxOutstandingR2t: u32, pub FirstBurstLength: u32, pub MaxBurstLength: u32, pub MaximumConnections: u32, pub ConnectionCount: u32, pub Connections: *mut ISCSI_CONNECTION_INFO_EX, } #[cfg(feature = "Win32_Foundation")] impl ISCSI_SESSION_INFO_EX {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for ISCSI_SESSION_INFO_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for ISCSI_SESSION_INFO_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_SESSION_INFO_EX") .field("SessionId", &self.SessionId) .field("InitialR2t", &self.InitialR2t) .field("ImmediateData", &self.ImmediateData) .field("Type", &self.Type) .field("DataSequenceInOrder", &self.DataSequenceInOrder) .field("DataPduInOrder", &self.DataPduInOrder) .field("ErrorRecoveryLevel", &self.ErrorRecoveryLevel) .field("MaxOutstandingR2t", &self.MaxOutstandingR2t) .field("FirstBurstLength", &self.FirstBurstLength) .field("MaxBurstLength", &self.MaxBurstLength) .field("MaximumConnections", &self.MaximumConnections) .field("ConnectionCount", &self.ConnectionCount) .field("Connections", &self.Connections) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for ISCSI_SESSION_INFO_EX { fn eq(&self, other: &Self) -> bool { self.SessionId == other.SessionId && self.InitialR2t == other.InitialR2t && self.ImmediateData == other.ImmediateData && self.Type == other.Type && self.DataSequenceInOrder == other.DataSequenceInOrder && self.DataPduInOrder == other.DataPduInOrder && self.ErrorRecoveryLevel == other.ErrorRecoveryLevel && self.MaxOutstandingR2t == other.MaxOutstandingR2t && self.FirstBurstLength == other.FirstBurstLength && self.MaxBurstLength == other.MaxBurstLength && self.MaximumConnections == other.MaximumConnections && self.ConnectionCount == other.ConnectionCount && self.Connections == other.Connections } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for ISCSI_SESSION_INFO_EX {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for ISCSI_SESSION_INFO_EX { type Abi = Self; } pub const ISCSI_TARGET_FLAG_HIDE_STATIC_TARGET: u32 = 2u32; pub const ISCSI_TARGET_FLAG_MERGE_TARGET_INFORMATION: u32 = 4u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct ISCSI_TARGET_MAPPINGA { pub InitiatorName: [super::super::Foundation::CHAR; 256], pub TargetName: [super::super::Foundation::CHAR; 224], pub OSDeviceName: [super::super::Foundation::CHAR; 260], pub SessionId: ISCSI_UNIQUE_SESSION_ID, pub OSBusNumber: u32, pub OSTargetNumber: u32, pub LUNCount: u32, pub LUNList: *mut SCSI_LUN_LIST, } #[cfg(feature = "Win32_Foundation")] impl ISCSI_TARGET_MAPPINGA {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for ISCSI_TARGET_MAPPINGA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for ISCSI_TARGET_MAPPINGA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_TARGET_MAPPINGA") .field("InitiatorName", &self.InitiatorName) .field("TargetName", &self.TargetName) .field("OSDeviceName", &self.OSDeviceName) .field("SessionId", &self.SessionId) .field("OSBusNumber", &self.OSBusNumber) .field("OSTargetNumber", &self.OSTargetNumber) .field("LUNCount", &self.LUNCount) .field("LUNList", &self.LUNList) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for ISCSI_TARGET_MAPPINGA { fn eq(&self, other: &Self) -> bool { self.InitiatorName == other.InitiatorName && self.TargetName == other.TargetName && self.OSDeviceName == other.OSDeviceName && self.SessionId == other.SessionId && self.OSBusNumber == other.OSBusNumber && self.OSTargetNumber == other.OSTargetNumber && self.LUNCount == other.LUNCount && self.LUNList == other.LUNList } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for ISCSI_TARGET_MAPPINGA {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for ISCSI_TARGET_MAPPINGA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ISCSI_TARGET_MAPPINGW { pub InitiatorName: [u16; 256], pub TargetName: [u16; 224], pub OSDeviceName: [u16; 260], pub SessionId: ISCSI_UNIQUE_SESSION_ID, pub OSBusNumber: u32, pub OSTargetNumber: u32, pub LUNCount: u32, pub LUNList: *mut SCSI_LUN_LIST, } impl ISCSI_TARGET_MAPPINGW {} impl ::core::default::Default for ISCSI_TARGET_MAPPINGW { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ISCSI_TARGET_MAPPINGW { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_TARGET_MAPPINGW") .field("InitiatorName", &self.InitiatorName) .field("TargetName", &self.TargetName) .field("OSDeviceName", &self.OSDeviceName) .field("SessionId", &self.SessionId) .field("OSBusNumber", &self.OSBusNumber) .field("OSTargetNumber", &self.OSTargetNumber) .field("LUNCount", &self.LUNCount) .field("LUNList", &self.LUNList) .finish() } } impl ::core::cmp::PartialEq for ISCSI_TARGET_MAPPINGW { fn eq(&self, other: &Self) -> bool { self.InitiatorName == other.InitiatorName && self.TargetName == other.TargetName && self.OSDeviceName == other.OSDeviceName && self.SessionId == other.SessionId && self.OSBusNumber == other.OSBusNumber && self.OSTargetNumber == other.OSTargetNumber && self.LUNCount == other.LUNCount && self.LUNList == other.LUNList } } impl ::core::cmp::Eq for ISCSI_TARGET_MAPPINGW {} unsafe impl ::windows::core::Abi for ISCSI_TARGET_MAPPINGW { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct ISCSI_TARGET_PORTALA { pub SymbolicName: [super::super::Foundation::CHAR; 256], pub Address: [super::super::Foundation::CHAR; 256], pub Socket: u16, } #[cfg(feature = "Win32_Foundation")] impl ISCSI_TARGET_PORTALA {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for ISCSI_TARGET_PORTALA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for ISCSI_TARGET_PORTALA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_TARGET_PORTALA").field("SymbolicName", &self.SymbolicName).field("Address", &self.Address).field("Socket", &self.Socket).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for ISCSI_TARGET_PORTALA { fn eq(&self, other: &Self) -> bool { self.SymbolicName == other.SymbolicName && self.Address == other.Address && self.Socket == other.Socket } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for ISCSI_TARGET_PORTALA {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for ISCSI_TARGET_PORTALA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ISCSI_TARGET_PORTALW { pub SymbolicName: [u16; 256], pub Address: [u16; 256], pub Socket: u16, } impl ISCSI_TARGET_PORTALW {} impl ::core::default::Default for ISCSI_TARGET_PORTALW { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ISCSI_TARGET_PORTALW { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_TARGET_PORTALW").field("SymbolicName", &self.SymbolicName).field("Address", &self.Address).field("Socket", &self.Socket).finish() } } impl ::core::cmp::PartialEq for ISCSI_TARGET_PORTALW { fn eq(&self, other: &Self) -> bool { self.SymbolicName == other.SymbolicName && self.Address == other.Address && self.Socket == other.Socket } } impl ::core::cmp::Eq for ISCSI_TARGET_PORTALW {} unsafe impl ::windows::core::Abi for ISCSI_TARGET_PORTALW { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct ISCSI_TARGET_PORTAL_GROUPA { pub Count: u32, pub Portals: [ISCSI_TARGET_PORTALA; 1], } #[cfg(feature = "Win32_Foundation")] impl ISCSI_TARGET_PORTAL_GROUPA {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for ISCSI_TARGET_PORTAL_GROUPA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for ISCSI_TARGET_PORTAL_GROUPA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_TARGET_PORTAL_GROUPA").field("Count", &self.Count).field("Portals", &self.Portals).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for ISCSI_TARGET_PORTAL_GROUPA { fn eq(&self, other: &Self) -> bool { self.Count == other.Count && self.Portals == other.Portals } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for ISCSI_TARGET_PORTAL_GROUPA {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for ISCSI_TARGET_PORTAL_GROUPA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ISCSI_TARGET_PORTAL_GROUPW { pub Count: u32, pub Portals: [ISCSI_TARGET_PORTALW; 1], } impl ISCSI_TARGET_PORTAL_GROUPW {} impl ::core::default::Default for ISCSI_TARGET_PORTAL_GROUPW { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ISCSI_TARGET_PORTAL_GROUPW { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_TARGET_PORTAL_GROUPW").field("Count", &self.Count).field("Portals", &self.Portals).finish() } } impl ::core::cmp::PartialEq for ISCSI_TARGET_PORTAL_GROUPW { fn eq(&self, other: &Self) -> bool { self.Count == other.Count && self.Portals == other.Portals } } impl ::core::cmp::Eq for ISCSI_TARGET_PORTAL_GROUPW {} unsafe impl ::windows::core::Abi for ISCSI_TARGET_PORTAL_GROUPW { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct ISCSI_TARGET_PORTAL_INFOA { pub InitiatorName: [super::super::Foundation::CHAR; 256], pub InitiatorPortNumber: u32, pub SymbolicName: [super::super::Foundation::CHAR; 256], pub Address: [super::super::Foundation::CHAR; 256], pub Socket: u16, } #[cfg(feature = "Win32_Foundation")] impl ISCSI_TARGET_PORTAL_INFOA {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for ISCSI_TARGET_PORTAL_INFOA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for ISCSI_TARGET_PORTAL_INFOA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_TARGET_PORTAL_INFOA").field("InitiatorName", &self.InitiatorName).field("InitiatorPortNumber", &self.InitiatorPortNumber).field("SymbolicName", &self.SymbolicName).field("Address", &self.Address).field("Socket", &self.Socket).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for ISCSI_TARGET_PORTAL_INFOA { fn eq(&self, other: &Self) -> bool { self.InitiatorName == other.InitiatorName && self.InitiatorPortNumber == other.InitiatorPortNumber && self.SymbolicName == other.SymbolicName && self.Address == other.Address && self.Socket == other.Socket } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for ISCSI_TARGET_PORTAL_INFOA {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for ISCSI_TARGET_PORTAL_INFOA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ISCSI_TARGET_PORTAL_INFOW { pub InitiatorName: [u16; 256], pub InitiatorPortNumber: u32, pub SymbolicName: [u16; 256], pub Address: [u16; 256], pub Socket: u16, } impl ISCSI_TARGET_PORTAL_INFOW {} impl ::core::default::Default for ISCSI_TARGET_PORTAL_INFOW { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ISCSI_TARGET_PORTAL_INFOW { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_TARGET_PORTAL_INFOW").field("InitiatorName", &self.InitiatorName).field("InitiatorPortNumber", &self.InitiatorPortNumber).field("SymbolicName", &self.SymbolicName).field("Address", &self.Address).field("Socket", &self.Socket).finish() } } impl ::core::cmp::PartialEq for ISCSI_TARGET_PORTAL_INFOW { fn eq(&self, other: &Self) -> bool { self.InitiatorName == other.InitiatorName && self.InitiatorPortNumber == other.InitiatorPortNumber && self.SymbolicName == other.SymbolicName && self.Address == other.Address && self.Socket == other.Socket } } impl ::core::cmp::Eq for ISCSI_TARGET_PORTAL_INFOW {} unsafe impl ::windows::core::Abi for ISCSI_TARGET_PORTAL_INFOW { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct ISCSI_TARGET_PORTAL_INFO_EXA { pub InitiatorName: [super::super::Foundation::CHAR; 256], pub InitiatorPortNumber: u32, pub SymbolicName: [super::super::Foundation::CHAR; 256], pub Address: [super::super::Foundation::CHAR; 256], pub Socket: u16, pub SecurityFlags: u64, pub LoginOptions: ISCSI_LOGIN_OPTIONS, } #[cfg(feature = "Win32_Foundation")] impl ISCSI_TARGET_PORTAL_INFO_EXA {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for ISCSI_TARGET_PORTAL_INFO_EXA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for ISCSI_TARGET_PORTAL_INFO_EXA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_TARGET_PORTAL_INFO_EXA") .field("InitiatorName", &self.InitiatorName) .field("InitiatorPortNumber", &self.InitiatorPortNumber) .field("SymbolicName", &self.SymbolicName) .field("Address", &self.Address) .field("Socket", &self.Socket) .field("SecurityFlags", &self.SecurityFlags) .field("LoginOptions", &self.LoginOptions) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for ISCSI_TARGET_PORTAL_INFO_EXA { fn eq(&self, other: &Self) -> bool { self.InitiatorName == other.InitiatorName && self.InitiatorPortNumber == other.InitiatorPortNumber && self.SymbolicName == other.SymbolicName && self.Address == other.Address && self.Socket == other.Socket && self.SecurityFlags == other.SecurityFlags && self.LoginOptions == other.LoginOptions } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for ISCSI_TARGET_PORTAL_INFO_EXA {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for ISCSI_TARGET_PORTAL_INFO_EXA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ISCSI_TARGET_PORTAL_INFO_EXW { pub InitiatorName: [u16; 256], pub InitiatorPortNumber: u32, pub SymbolicName: [u16; 256], pub Address: [u16; 256], pub Socket: u16, pub SecurityFlags: u64, pub LoginOptions: ISCSI_LOGIN_OPTIONS, } impl ISCSI_TARGET_PORTAL_INFO_EXW {} impl ::core::default::Default for ISCSI_TARGET_PORTAL_INFO_EXW { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ISCSI_TARGET_PORTAL_INFO_EXW { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_TARGET_PORTAL_INFO_EXW") .field("InitiatorName", &self.InitiatorName) .field("InitiatorPortNumber", &self.InitiatorPortNumber) .field("SymbolicName", &self.SymbolicName) .field("Address", &self.Address) .field("Socket", &self.Socket) .field("SecurityFlags", &self.SecurityFlags) .field("LoginOptions", &self.LoginOptions) .finish() } } impl ::core::cmp::PartialEq for ISCSI_TARGET_PORTAL_INFO_EXW { fn eq(&self, other: &Self) -> bool { self.InitiatorName == other.InitiatorName && self.InitiatorPortNumber == other.InitiatorPortNumber && self.SymbolicName == other.SymbolicName && self.Address == other.Address && self.Socket == other.Socket && self.SecurityFlags == other.SecurityFlags && self.LoginOptions == other.LoginOptions } } impl ::core::cmp::Eq for ISCSI_TARGET_PORTAL_INFO_EXW {} unsafe impl ::windows::core::Abi for ISCSI_TARGET_PORTAL_INFO_EXW { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ISCSI_UNIQUE_SESSION_ID { pub AdapterUnique: u64, pub AdapterSpecific: u64, } impl ISCSI_UNIQUE_SESSION_ID {} impl ::core::default::Default for ISCSI_UNIQUE_SESSION_ID { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ISCSI_UNIQUE_SESSION_ID { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_UNIQUE_SESSION_ID").field("AdapterUnique", &self.AdapterUnique).field("AdapterSpecific", &self.AdapterSpecific).finish() } } impl ::core::cmp::PartialEq for ISCSI_UNIQUE_SESSION_ID { fn eq(&self, other: &Self) -> bool { self.AdapterUnique == other.AdapterUnique && self.AdapterSpecific == other.AdapterSpecific } } impl ::core::cmp::Eq for ISCSI_UNIQUE_SESSION_ID {} unsafe impl ::windows::core::Abi for ISCSI_UNIQUE_SESSION_ID { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ISCSI_VERSION_INFO { pub MajorVersion: u32, pub MinorVersion: u32, pub BuildNumber: u32, } impl ISCSI_VERSION_INFO {} impl ::core::default::Default for ISCSI_VERSION_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ISCSI_VERSION_INFO { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ISCSI_VERSION_INFO").field("MajorVersion", &self.MajorVersion).field("MinorVersion", &self.MinorVersion).field("BuildNumber", &self.BuildNumber).finish() } } impl ::core::cmp::PartialEq for ISCSI_VERSION_INFO { fn eq(&self, other: &Self) -> bool { self.MajorVersion == other.MajorVersion && self.MinorVersion == other.MinorVersion && self.BuildNumber == other.BuildNumber } } impl ::core::cmp::Eq for ISCSI_VERSION_INFO {} unsafe impl ::windows::core::Abi for ISCSI_VERSION_INFO { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn LoginIScsiTargetA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param9: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param10: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>>( targetname: Param0, isinformationalsession: Param1, initiatorinstance: Param2, initiatorportnumber: u32, targetportal: *mut ISCSI_TARGET_PORTALA, securityflags: u64, mappings: *mut ISCSI_TARGET_MAPPINGA, loginoptions: *mut ISCSI_LOGIN_OPTIONS, keysize: u32, key: Param9, ispersistent: Param10, uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, uniqueconnectionid: *mut ISCSI_UNIQUE_SESSION_ID, ) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn LoginIScsiTargetA( targetname: super::super::Foundation::PSTR, isinformationalsession: super::super::Foundation::BOOLEAN, initiatorinstance: super::super::Foundation::PSTR, initiatorportnumber: u32, targetportal: *mut ISCSI_TARGET_PORTALA, securityflags: u64, mappings: *mut ISCSI_TARGET_MAPPINGA, loginoptions: *mut ISCSI_LOGIN_OPTIONS, keysize: u32, key: super::super::Foundation::PSTR, ispersistent: super::super::Foundation::BOOLEAN, uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, uniqueconnectionid: *mut ISCSI_UNIQUE_SESSION_ID, ) -> u32; } ::core::mem::transmute(LoginIScsiTargetA( targetname.into_param().abi(), isinformationalsession.into_param().abi(), initiatorinstance.into_param().abi(), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(targetportal), ::core::mem::transmute(securityflags), ::core::mem::transmute(mappings), ::core::mem::transmute(loginoptions), ::core::mem::transmute(keysize), key.into_param().abi(), ispersistent.into_param().abi(), ::core::mem::transmute(uniquesessionid), ::core::mem::transmute(uniqueconnectionid), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn LoginIScsiTargetW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param9: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param10: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>>( targetname: Param0, isinformationalsession: Param1, initiatorinstance: Param2, initiatorportnumber: u32, targetportal: *mut ISCSI_TARGET_PORTALW, securityflags: u64, mappings: *mut ISCSI_TARGET_MAPPINGW, loginoptions: *mut ISCSI_LOGIN_OPTIONS, keysize: u32, key: Param9, ispersistent: Param10, uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, uniqueconnectionid: *mut ISCSI_UNIQUE_SESSION_ID, ) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn LoginIScsiTargetW( targetname: super::super::Foundation::PWSTR, isinformationalsession: super::super::Foundation::BOOLEAN, initiatorinstance: super::super::Foundation::PWSTR, initiatorportnumber: u32, targetportal: *mut ISCSI_TARGET_PORTALW, securityflags: u64, mappings: *mut ISCSI_TARGET_MAPPINGW, loginoptions: *mut ISCSI_LOGIN_OPTIONS, keysize: u32, key: super::super::Foundation::PSTR, ispersistent: super::super::Foundation::BOOLEAN, uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, uniqueconnectionid: *mut ISCSI_UNIQUE_SESSION_ID, ) -> u32; } ::core::mem::transmute(LoginIScsiTargetW( targetname.into_param().abi(), isinformationalsession.into_param().abi(), initiatorinstance.into_param().abi(), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(targetportal), ::core::mem::transmute(securityflags), ::core::mem::transmute(mappings), ::core::mem::transmute(loginoptions), ::core::mem::transmute(keysize), key.into_param().abi(), ispersistent.into_param().abi(), ::core::mem::transmute(uniquesessionid), ::core::mem::transmute(uniqueconnectionid), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn LogoutIScsiTarget(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn LogoutIScsiTarget(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID) -> u32; } ::core::mem::transmute(LogoutIScsiTarget(::core::mem::transmute(uniquesessionid))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } pub const MAX_ISCSI_ALIAS_LEN: u32 = 255u32; pub const MAX_ISCSI_DISCOVERY_DOMAIN_LEN: u32 = 256u32; pub const MAX_ISCSI_HBANAME_LEN: u32 = 256u32; pub const MAX_ISCSI_NAME_LEN: u32 = 223u32; pub const MAX_ISCSI_PORTAL_ADDRESS_LEN: u32 = 256u32; pub const MAX_ISCSI_PORTAL_ALIAS_LEN: u32 = 256u32; pub const MAX_ISCSI_PORTAL_NAME_LEN: u32 = 256u32; pub const MAX_ISCSI_TEXT_ADDRESS_LEN: u32 = 256u32; pub const MAX_RADIUS_ADDRESS_LEN: u32 = 41u32; pub const MINIPORT_DSM_NOTIFICATION_VERSION: u32 = 1u32; pub const MINIPORT_DSM_NOTIFICATION_VERSION_1: u32 = 1u32; pub const MINIPORT_DSM_NOTIFY_FLAG_BEGIN: u32 = 1u32; pub const MINIPORT_DSM_NOTIFY_FLAG_END: u32 = 2u32; pub const MINIPORT_DSM_PROFILE_CRASHDUMP_FILE: u32 = 3u32; pub const MINIPORT_DSM_PROFILE_HIBERNATION_FILE: u32 = 2u32; pub const MINIPORT_DSM_PROFILE_PAGE_FILE: u32 = 1u32; pub const MINIPORT_DSM_PROFILE_UNKNOWN: u32 = 0u32; pub const MPIO_IOCTL_FLAG_INVOLVE_DSM: u32 = 4u32; pub const MPIO_IOCTL_FLAG_USE_PATHID: u32 = 1u32; pub const MPIO_IOCTL_FLAG_USE_SCSIADDRESS: u32 = 2u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct MPIO_PASS_THROUGH_PATH { pub PassThrough: SCSI_PASS_THROUGH, pub Version: u32, pub Length: u16, pub Flags: u8, pub PortNumber: u8, pub MpioPathId: u64, } impl MPIO_PASS_THROUGH_PATH {} impl ::core::default::Default for MPIO_PASS_THROUGH_PATH { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for MPIO_PASS_THROUGH_PATH { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MPIO_PASS_THROUGH_PATH").field("PassThrough", &self.PassThrough).field("Version", &self.Version).field("Length", &self.Length).field("Flags", &self.Flags).field("PortNumber", &self.PortNumber).field("MpioPathId", &self.MpioPathId).finish() } } impl ::core::cmp::PartialEq for MPIO_PASS_THROUGH_PATH { fn eq(&self, other: &Self) -> bool { self.PassThrough == other.PassThrough && self.Version == other.Version && self.Length == other.Length && self.Flags == other.Flags && self.PortNumber == other.PortNumber && self.MpioPathId == other.MpioPathId } } impl ::core::cmp::Eq for MPIO_PASS_THROUGH_PATH {} unsafe impl ::windows::core::Abi for MPIO_PASS_THROUGH_PATH { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct MPIO_PASS_THROUGH_PATH32 { pub PassThrough: SCSI_PASS_THROUGH32, pub Version: u32, pub Length: u16, pub Flags: u8, pub PortNumber: u8, pub MpioPathId: u64, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl MPIO_PASS_THROUGH_PATH32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for MPIO_PASS_THROUGH_PATH32 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for MPIO_PASS_THROUGH_PATH32 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MPIO_PASS_THROUGH_PATH32").field("PassThrough", &self.PassThrough).field("Version", &self.Version).field("Length", &self.Length).field("Flags", &self.Flags).field("PortNumber", &self.PortNumber).field("MpioPathId", &self.MpioPathId).finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for MPIO_PASS_THROUGH_PATH32 { fn eq(&self, other: &Self) -> bool { self.PassThrough == other.PassThrough && self.Version == other.Version && self.Length == other.Length && self.Flags == other.Flags && self.PortNumber == other.PortNumber && self.MpioPathId == other.MpioPathId } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for MPIO_PASS_THROUGH_PATH32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for MPIO_PASS_THROUGH_PATH32 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct MPIO_PASS_THROUGH_PATH32_EX { pub PassThroughOffset: u32, pub Version: u32, pub Length: u16, pub Flags: u8, pub PortNumber: u8, pub MpioPathId: u64, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl MPIO_PASS_THROUGH_PATH32_EX {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for MPIO_PASS_THROUGH_PATH32_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for MPIO_PASS_THROUGH_PATH32_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MPIO_PASS_THROUGH_PATH32_EX").field("PassThroughOffset", &self.PassThroughOffset).field("Version", &self.Version).field("Length", &self.Length).field("Flags", &self.Flags).field("PortNumber", &self.PortNumber).field("MpioPathId", &self.MpioPathId).finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for MPIO_PASS_THROUGH_PATH32_EX { fn eq(&self, other: &Self) -> bool { self.PassThroughOffset == other.PassThroughOffset && self.Version == other.Version && self.Length == other.Length && self.Flags == other.Flags && self.PortNumber == other.PortNumber && self.MpioPathId == other.MpioPathId } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for MPIO_PASS_THROUGH_PATH32_EX {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for MPIO_PASS_THROUGH_PATH32_EX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct MPIO_PASS_THROUGH_PATH_DIRECT { pub PassThrough: SCSI_PASS_THROUGH_DIRECT, pub Version: u32, pub Length: u16, pub Flags: u8, pub PortNumber: u8, pub MpioPathId: u64, } impl MPIO_PASS_THROUGH_PATH_DIRECT {} impl ::core::default::Default for MPIO_PASS_THROUGH_PATH_DIRECT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for MPIO_PASS_THROUGH_PATH_DIRECT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MPIO_PASS_THROUGH_PATH_DIRECT").field("PassThrough", &self.PassThrough).field("Version", &self.Version).field("Length", &self.Length).field("Flags", &self.Flags).field("PortNumber", &self.PortNumber).field("MpioPathId", &self.MpioPathId).finish() } } impl ::core::cmp::PartialEq for MPIO_PASS_THROUGH_PATH_DIRECT { fn eq(&self, other: &Self) -> bool { self.PassThrough == other.PassThrough && self.Version == other.Version && self.Length == other.Length && self.Flags == other.Flags && self.PortNumber == other.PortNumber && self.MpioPathId == other.MpioPathId } } impl ::core::cmp::Eq for MPIO_PASS_THROUGH_PATH_DIRECT {} unsafe impl ::windows::core::Abi for MPIO_PASS_THROUGH_PATH_DIRECT { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct MPIO_PASS_THROUGH_PATH_DIRECT32 { pub PassThrough: SCSI_PASS_THROUGH_DIRECT32, pub Version: u32, pub Length: u16, pub Flags: u8, pub PortNumber: u8, pub MpioPathId: u64, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl MPIO_PASS_THROUGH_PATH_DIRECT32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for MPIO_PASS_THROUGH_PATH_DIRECT32 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for MPIO_PASS_THROUGH_PATH_DIRECT32 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MPIO_PASS_THROUGH_PATH_DIRECT32").field("PassThrough", &self.PassThrough).field("Version", &self.Version).field("Length", &self.Length).field("Flags", &self.Flags).field("PortNumber", &self.PortNumber).field("MpioPathId", &self.MpioPathId).finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for MPIO_PASS_THROUGH_PATH_DIRECT32 { fn eq(&self, other: &Self) -> bool { self.PassThrough == other.PassThrough && self.Version == other.Version && self.Length == other.Length && self.Flags == other.Flags && self.PortNumber == other.PortNumber && self.MpioPathId == other.MpioPathId } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for MPIO_PASS_THROUGH_PATH_DIRECT32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for MPIO_PASS_THROUGH_PATH_DIRECT32 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct MPIO_PASS_THROUGH_PATH_DIRECT32_EX { pub PassThroughOffset: u32, pub Version: u32, pub Length: u16, pub Flags: u8, pub PortNumber: u8, pub MpioPathId: u64, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl MPIO_PASS_THROUGH_PATH_DIRECT32_EX {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for MPIO_PASS_THROUGH_PATH_DIRECT32_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for MPIO_PASS_THROUGH_PATH_DIRECT32_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MPIO_PASS_THROUGH_PATH_DIRECT32_EX").field("PassThroughOffset", &self.PassThroughOffset).field("Version", &self.Version).field("Length", &self.Length).field("Flags", &self.Flags).field("PortNumber", &self.PortNumber).field("MpioPathId", &self.MpioPathId).finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for MPIO_PASS_THROUGH_PATH_DIRECT32_EX { fn eq(&self, other: &Self) -> bool { self.PassThroughOffset == other.PassThroughOffset && self.Version == other.Version && self.Length == other.Length && self.Flags == other.Flags && self.PortNumber == other.PortNumber && self.MpioPathId == other.MpioPathId } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for MPIO_PASS_THROUGH_PATH_DIRECT32_EX {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for MPIO_PASS_THROUGH_PATH_DIRECT32_EX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct MPIO_PASS_THROUGH_PATH_DIRECT_EX { pub PassThroughOffset: u32, pub Version: u32, pub Length: u16, pub Flags: u8, pub PortNumber: u8, pub MpioPathId: u64, } impl MPIO_PASS_THROUGH_PATH_DIRECT_EX {} impl ::core::default::Default for MPIO_PASS_THROUGH_PATH_DIRECT_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for MPIO_PASS_THROUGH_PATH_DIRECT_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MPIO_PASS_THROUGH_PATH_DIRECT_EX").field("PassThroughOffset", &self.PassThroughOffset).field("Version", &self.Version).field("Length", &self.Length).field("Flags", &self.Flags).field("PortNumber", &self.PortNumber).field("MpioPathId", &self.MpioPathId).finish() } } impl ::core::cmp::PartialEq for MPIO_PASS_THROUGH_PATH_DIRECT_EX { fn eq(&self, other: &Self) -> bool { self.PassThroughOffset == other.PassThroughOffset && self.Version == other.Version && self.Length == other.Length && self.Flags == other.Flags && self.PortNumber == other.PortNumber && self.MpioPathId == other.MpioPathId } } impl ::core::cmp::Eq for MPIO_PASS_THROUGH_PATH_DIRECT_EX {} unsafe impl ::windows::core::Abi for MPIO_PASS_THROUGH_PATH_DIRECT_EX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct MPIO_PASS_THROUGH_PATH_EX { pub PassThroughOffset: u32, pub Version: u32, pub Length: u16, pub Flags: u8, pub PortNumber: u8, pub MpioPathId: u64, } impl MPIO_PASS_THROUGH_PATH_EX {} impl ::core::default::Default for MPIO_PASS_THROUGH_PATH_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for MPIO_PASS_THROUGH_PATH_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MPIO_PASS_THROUGH_PATH_EX").field("PassThroughOffset", &self.PassThroughOffset).field("Version", &self.Version).field("Length", &self.Length).field("Flags", &self.Flags).field("PortNumber", &self.PortNumber).field("MpioPathId", &self.MpioPathId).finish() } } impl ::core::cmp::PartialEq for MPIO_PASS_THROUGH_PATH_EX { fn eq(&self, other: &Self) -> bool { self.PassThroughOffset == other.PassThroughOffset && self.Version == other.Version && self.Length == other.Length && self.Flags == other.Flags && self.PortNumber == other.PortNumber && self.MpioPathId == other.MpioPathId } } impl ::core::cmp::Eq for MPIO_PASS_THROUGH_PATH_EX {} unsafe impl ::windows::core::Abi for MPIO_PASS_THROUGH_PATH_EX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct MP_DEVICE_DATA_SET_RANGE { pub StartingOffset: i64, pub LengthInBytes: u64, } impl MP_DEVICE_DATA_SET_RANGE {} impl ::core::default::Default for MP_DEVICE_DATA_SET_RANGE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for MP_DEVICE_DATA_SET_RANGE { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MP_DEVICE_DATA_SET_RANGE").field("StartingOffset", &self.StartingOffset).field("LengthInBytes", &self.LengthInBytes).finish() } } impl ::core::cmp::PartialEq for MP_DEVICE_DATA_SET_RANGE { fn eq(&self, other: &Self) -> bool { self.StartingOffset == other.StartingOffset && self.LengthInBytes == other.LengthInBytes } } impl ::core::cmp::Eq for MP_DEVICE_DATA_SET_RANGE {} unsafe impl ::windows::core::Abi for MP_DEVICE_DATA_SET_RANGE { 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 MP_STORAGE_DIAGNOSTIC_LEVEL(pub i32); pub const MpStorageDiagnosticLevelDefault: MP_STORAGE_DIAGNOSTIC_LEVEL = MP_STORAGE_DIAGNOSTIC_LEVEL(0i32); pub const MpStorageDiagnosticLevelMax: MP_STORAGE_DIAGNOSTIC_LEVEL = MP_STORAGE_DIAGNOSTIC_LEVEL(1i32); impl ::core::convert::From<i32> for MP_STORAGE_DIAGNOSTIC_LEVEL { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MP_STORAGE_DIAGNOSTIC_LEVEL { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MP_STORAGE_DIAGNOSTIC_TARGET_TYPE(pub i32); pub const MpStorageDiagnosticTargetTypeUndefined: MP_STORAGE_DIAGNOSTIC_TARGET_TYPE = MP_STORAGE_DIAGNOSTIC_TARGET_TYPE(0i32); pub const MpStorageDiagnosticTargetTypeMiniport: MP_STORAGE_DIAGNOSTIC_TARGET_TYPE = MP_STORAGE_DIAGNOSTIC_TARGET_TYPE(2i32); pub const MpStorageDiagnosticTargetTypeHbaFirmware: MP_STORAGE_DIAGNOSTIC_TARGET_TYPE = MP_STORAGE_DIAGNOSTIC_TARGET_TYPE(3i32); pub const MpStorageDiagnosticTargetTypeMax: MP_STORAGE_DIAGNOSTIC_TARGET_TYPE = MP_STORAGE_DIAGNOSTIC_TARGET_TYPE(4i32); impl ::core::convert::From<i32> for MP_STORAGE_DIAGNOSTIC_TARGET_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MP_STORAGE_DIAGNOSTIC_TARGET_TYPE { type Abi = Self; } pub const NRB_FUNCTION_ADD_LBAS_PINNED_SET: u32 = 16u32; pub const NRB_FUNCTION_FLUSH_NVCACHE: u32 = 20u32; pub const NRB_FUNCTION_NVCACHE_INFO: u32 = 236u32; pub const NRB_FUNCTION_NVCACHE_POWER_MODE_RETURN: u32 = 1u32; pub const NRB_FUNCTION_NVCACHE_POWER_MODE_SET: u32 = 0u32; pub const NRB_FUNCTION_NVSEPARATED_FLUSH: u32 = 193u32; pub const NRB_FUNCTION_NVSEPARATED_INFO: u32 = 192u32; pub const NRB_FUNCTION_NVSEPARATED_WB_DISABLE: u32 = 194u32; pub const NRB_FUNCTION_NVSEPARATED_WB_REVERT_DEFAULT: u32 = 195u32; pub const NRB_FUNCTION_PASS_HINT_PAYLOAD: u32 = 224u32; pub const NRB_FUNCTION_QUERY_ASCENDER_STATUS: u32 = 208u32; pub const NRB_FUNCTION_QUERY_CACHE_MISS: u32 = 19u32; pub const NRB_FUNCTION_QUERY_HYBRID_DISK_STATUS: u32 = 209u32; pub const NRB_FUNCTION_QUERY_PINNED_SET: u32 = 18u32; pub const NRB_FUNCTION_REMOVE_LBAS_PINNED_SET: u32 = 17u32; pub const NRB_FUNCTION_SPINDLE_STATUS: u32 = 229u32; pub const NRB_ILLEGAL_REQUEST: u32 = 1u32; pub const NRB_INPUT_DATA_OVERRUN: u32 = 3u32; pub const NRB_INPUT_DATA_UNDERRUN: u32 = 4u32; pub const NRB_INVALID_PARAMETER: u32 = 2u32; pub const NRB_OUTPUT_DATA_OVERRUN: u32 = 5u32; pub const NRB_OUTPUT_DATA_UNDERRUN: u32 = 6u32; pub const NRB_SUCCESS: u32 = 0u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct NTSCSI_UNICODE_STRING { pub Length: u16, pub MaximumLength: u16, pub Buffer: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl NTSCSI_UNICODE_STRING {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for NTSCSI_UNICODE_STRING { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for NTSCSI_UNICODE_STRING { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("NTSCSI_UNICODE_STRING").field("Length", &self.Length).field("MaximumLength", &self.MaximumLength).field("Buffer", &self.Buffer).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for NTSCSI_UNICODE_STRING { fn eq(&self, other: &Self) -> bool { self.Length == other.Length && self.MaximumLength == other.MaximumLength && self.Buffer == other.Buffer } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for NTSCSI_UNICODE_STRING {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for NTSCSI_UNICODE_STRING { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct NVCACHE_HINT_PAYLOAD { pub Command: u8, pub Feature7_0: u8, pub Feature15_8: u8, pub Count15_8: u8, pub LBA7_0: u8, pub LBA15_8: u8, pub LBA23_16: u8, pub LBA31_24: u8, pub LBA39_32: u8, pub LBA47_40: u8, pub Auxiliary7_0: u8, pub Auxiliary23_16: u8, pub Reserved: [u8; 4], } impl NVCACHE_HINT_PAYLOAD {} impl ::core::default::Default for NVCACHE_HINT_PAYLOAD { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for NVCACHE_HINT_PAYLOAD { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("NVCACHE_HINT_PAYLOAD") .field("Command", &self.Command) .field("Feature7_0", &self.Feature7_0) .field("Feature15_8", &self.Feature15_8) .field("Count15_8", &self.Count15_8) .field("LBA7_0", &self.LBA7_0) .field("LBA15_8", &self.LBA15_8) .field("LBA23_16", &self.LBA23_16) .field("LBA31_24", &self.LBA31_24) .field("LBA39_32", &self.LBA39_32) .field("LBA47_40", &self.LBA47_40) .field("Auxiliary7_0", &self.Auxiliary7_0) .field("Auxiliary23_16", &self.Auxiliary23_16) .field("Reserved", &self.Reserved) .finish() } } impl ::core::cmp::PartialEq for NVCACHE_HINT_PAYLOAD { fn eq(&self, other: &Self) -> bool { self.Command == other.Command && self.Feature7_0 == other.Feature7_0 && self.Feature15_8 == other.Feature15_8 && self.Count15_8 == other.Count15_8 && self.LBA7_0 == other.LBA7_0 && self.LBA15_8 == other.LBA15_8 && self.LBA23_16 == other.LBA23_16 && self.LBA31_24 == other.LBA31_24 && self.LBA39_32 == other.LBA39_32 && self.LBA47_40 == other.LBA47_40 && self.Auxiliary7_0 == other.Auxiliary7_0 && self.Auxiliary23_16 == other.Auxiliary23_16 && self.Reserved == other.Reserved } } impl ::core::cmp::Eq for NVCACHE_HINT_PAYLOAD {} unsafe impl ::windows::core::Abi for NVCACHE_HINT_PAYLOAD { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct NVCACHE_PRIORITY_LEVEL_DESCRIPTOR { pub PriorityLevel: u8, pub Reserved0: [u8; 3], pub ConsumedNVMSizeFraction: u32, pub ConsumedMappingResourcesFraction: u32, pub ConsumedNVMSizeForDirtyDataFraction: u32, pub ConsumedMappingResourcesForDirtyDataFraction: u32, pub Reserved1: u32, } impl NVCACHE_PRIORITY_LEVEL_DESCRIPTOR {} impl ::core::default::Default for NVCACHE_PRIORITY_LEVEL_DESCRIPTOR { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for NVCACHE_PRIORITY_LEVEL_DESCRIPTOR { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("NVCACHE_PRIORITY_LEVEL_DESCRIPTOR") .field("PriorityLevel", &self.PriorityLevel) .field("Reserved0", &self.Reserved0) .field("ConsumedNVMSizeFraction", &self.ConsumedNVMSizeFraction) .field("ConsumedMappingResourcesFraction", &self.ConsumedMappingResourcesFraction) .field("ConsumedNVMSizeForDirtyDataFraction", &self.ConsumedNVMSizeForDirtyDataFraction) .field("ConsumedMappingResourcesForDirtyDataFraction", &self.ConsumedMappingResourcesForDirtyDataFraction) .field("Reserved1", &self.Reserved1) .finish() } } impl ::core::cmp::PartialEq for NVCACHE_PRIORITY_LEVEL_DESCRIPTOR { fn eq(&self, other: &Self) -> bool { self.PriorityLevel == other.PriorityLevel && self.Reserved0 == other.Reserved0 && self.ConsumedNVMSizeFraction == other.ConsumedNVMSizeFraction && self.ConsumedMappingResourcesFraction == other.ConsumedMappingResourcesFraction && self.ConsumedNVMSizeForDirtyDataFraction == other.ConsumedNVMSizeForDirtyDataFraction && self.ConsumedMappingResourcesForDirtyDataFraction == other.ConsumedMappingResourcesForDirtyDataFraction && self.Reserved1 == other.Reserved1 } } impl ::core::cmp::Eq for NVCACHE_PRIORITY_LEVEL_DESCRIPTOR {} unsafe impl ::windows::core::Abi for NVCACHE_PRIORITY_LEVEL_DESCRIPTOR { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct NVCACHE_REQUEST_BLOCK { pub NRBSize: u32, pub Function: u16, pub NRBFlags: u32, pub NRBStatus: u32, pub Count: u32, pub LBA: u64, pub DataBufSize: u32, pub NVCacheStatus: u32, pub NVCacheSubStatus: u32, } impl NVCACHE_REQUEST_BLOCK {} impl ::core::default::Default for NVCACHE_REQUEST_BLOCK { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for NVCACHE_REQUEST_BLOCK { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("NVCACHE_REQUEST_BLOCK") .field("NRBSize", &self.NRBSize) .field("Function", &self.Function) .field("NRBFlags", &self.NRBFlags) .field("NRBStatus", &self.NRBStatus) .field("Count", &self.Count) .field("LBA", &self.LBA) .field("DataBufSize", &self.DataBufSize) .field("NVCacheStatus", &self.NVCacheStatus) .field("NVCacheSubStatus", &self.NVCacheSubStatus) .finish() } } impl ::core::cmp::PartialEq for NVCACHE_REQUEST_BLOCK { fn eq(&self, other: &Self) -> bool { self.NRBSize == other.NRBSize && self.Function == other.Function && self.NRBFlags == other.NRBFlags && self.NRBStatus == other.NRBStatus && self.Count == other.Count && self.LBA == other.LBA && self.DataBufSize == other.DataBufSize && self.NVCacheStatus == other.NVCacheStatus && self.NVCacheSubStatus == other.NVCacheSubStatus } } impl ::core::cmp::Eq for NVCACHE_REQUEST_BLOCK {} unsafe impl ::windows::core::Abi for NVCACHE_REQUEST_BLOCK { 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 NVCACHE_STATUS(pub i32); pub const NvCacheStatusUnknown: NVCACHE_STATUS = NVCACHE_STATUS(0i32); pub const NvCacheStatusDisabling: NVCACHE_STATUS = NVCACHE_STATUS(1i32); pub const NvCacheStatusDisabled: NVCACHE_STATUS = NVCACHE_STATUS(2i32); pub const NvCacheStatusEnabled: NVCACHE_STATUS = NVCACHE_STATUS(3i32); impl ::core::convert::From<i32> for NVCACHE_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for NVCACHE_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 NVCACHE_TYPE(pub i32); pub const NvCacheTypeUnknown: NVCACHE_TYPE = NVCACHE_TYPE(0i32); pub const NvCacheTypeNone: NVCACHE_TYPE = NVCACHE_TYPE(1i32); pub const NvCacheTypeWriteBack: NVCACHE_TYPE = NVCACHE_TYPE(2i32); pub const NvCacheTypeWriteThrough: NVCACHE_TYPE = NVCACHE_TYPE(3i32); impl ::core::convert::From<i32> for NVCACHE_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for NVCACHE_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct NV_FEATURE_PARAMETER { pub NVPowerModeEnabled: u16, pub NVParameterReserv1: u16, pub NVCmdEnabled: u16, pub NVParameterReserv2: u16, pub NVPowerModeVer: u16, pub NVCmdVer: u16, pub NVSize: u32, pub NVReadSpeed: u16, pub NVWrtSpeed: u16, pub DeviceSpinUpTime: u32, } impl NV_FEATURE_PARAMETER {} impl ::core::default::Default for NV_FEATURE_PARAMETER { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for NV_FEATURE_PARAMETER { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("NV_FEATURE_PARAMETER") .field("NVPowerModeEnabled", &self.NVPowerModeEnabled) .field("NVParameterReserv1", &self.NVParameterReserv1) .field("NVCmdEnabled", &self.NVCmdEnabled) .field("NVParameterReserv2", &self.NVParameterReserv2) .field("NVPowerModeVer", &self.NVPowerModeVer) .field("NVCmdVer", &self.NVCmdVer) .field("NVSize", &self.NVSize) .field("NVReadSpeed", &self.NVReadSpeed) .field("NVWrtSpeed", &self.NVWrtSpeed) .field("DeviceSpinUpTime", &self.DeviceSpinUpTime) .finish() } } impl ::core::cmp::PartialEq for NV_FEATURE_PARAMETER { fn eq(&self, other: &Self) -> bool { self.NVPowerModeEnabled == other.NVPowerModeEnabled && self.NVParameterReserv1 == other.NVParameterReserv1 && self.NVCmdEnabled == other.NVCmdEnabled && self.NVParameterReserv2 == other.NVParameterReserv2 && self.NVPowerModeVer == other.NVPowerModeVer && self.NVCmdVer == other.NVCmdVer && self.NVSize == other.NVSize && self.NVReadSpeed == other.NVReadSpeed && self.NVWrtSpeed == other.NVWrtSpeed && self.DeviceSpinUpTime == other.DeviceSpinUpTime } } impl ::core::cmp::Eq for NV_FEATURE_PARAMETER {} unsafe impl ::windows::core::Abi for NV_FEATURE_PARAMETER { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct NV_SEP_CACHE_PARAMETER { pub Version: u32, pub Size: u32, pub Flags: NV_SEP_CACHE_PARAMETER_0, pub WriteCacheType: u8, pub WriteCacheTypeEffective: u8, pub ParameterReserve1: [u8; 3], } impl NV_SEP_CACHE_PARAMETER {} impl ::core::default::Default for NV_SEP_CACHE_PARAMETER { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for NV_SEP_CACHE_PARAMETER { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for NV_SEP_CACHE_PARAMETER {} unsafe impl ::windows::core::Abi for NV_SEP_CACHE_PARAMETER { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub union NV_SEP_CACHE_PARAMETER_0 { pub CacheFlags: NV_SEP_CACHE_PARAMETER_0_0, pub CacheFlagsSet: u8, } impl NV_SEP_CACHE_PARAMETER_0 {} impl ::core::default::Default for NV_SEP_CACHE_PARAMETER_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for NV_SEP_CACHE_PARAMETER_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for NV_SEP_CACHE_PARAMETER_0 {} unsafe impl ::windows::core::Abi for NV_SEP_CACHE_PARAMETER_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct NV_SEP_CACHE_PARAMETER_0_0 { pub _bitfield: u8, } impl NV_SEP_CACHE_PARAMETER_0_0 {} impl ::core::default::Default for NV_SEP_CACHE_PARAMETER_0_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for NV_SEP_CACHE_PARAMETER_0_0 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_CacheFlags_e__Struct").field("_bitfield", &self._bitfield).finish() } } impl ::core::cmp::PartialEq for NV_SEP_CACHE_PARAMETER_0_0 { fn eq(&self, other: &Self) -> bool { self._bitfield == other._bitfield } } impl ::core::cmp::Eq for NV_SEP_CACHE_PARAMETER_0_0 {} unsafe impl ::windows::core::Abi for NV_SEP_CACHE_PARAMETER_0_0 { type Abi = Self; } pub const NV_SEP_CACHE_PARAMETER_VERSION: u32 = 1u32; pub const NV_SEP_CACHE_PARAMETER_VERSION_1: u32 = 1u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct NV_SEP_WRITE_CACHE_TYPE(pub i32); pub const NVSEPWriteCacheTypeUnknown: NV_SEP_WRITE_CACHE_TYPE = NV_SEP_WRITE_CACHE_TYPE(0i32); pub const NVSEPWriteCacheTypeNone: NV_SEP_WRITE_CACHE_TYPE = NV_SEP_WRITE_CACHE_TYPE(1i32); pub const NVSEPWriteCacheTypeWriteBack: NV_SEP_WRITE_CACHE_TYPE = NV_SEP_WRITE_CACHE_TYPE(2i32); pub const NVSEPWriteCacheTypeWriteThrough: NV_SEP_WRITE_CACHE_TYPE = NV_SEP_WRITE_CACHE_TYPE(3i32); impl ::core::convert::From<i32> for NV_SEP_WRITE_CACHE_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for NV_SEP_WRITE_CACHE_TYPE { type Abi = Self; } pub type PDUMP_DEVICE_POWERON_ROUTINE = unsafe extern "system" fn() -> i32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct PERSISTENT_ISCSI_LOGIN_INFOA { pub TargetName: [super::super::Foundation::CHAR; 224], pub IsInformationalSession: super::super::Foundation::BOOLEAN, pub InitiatorInstance: [super::super::Foundation::CHAR; 256], pub InitiatorPortNumber: u32, pub TargetPortal: ISCSI_TARGET_PORTALA, pub SecurityFlags: u64, pub Mappings: *mut ISCSI_TARGET_MAPPINGA, pub LoginOptions: ISCSI_LOGIN_OPTIONS, } #[cfg(feature = "Win32_Foundation")] impl PERSISTENT_ISCSI_LOGIN_INFOA {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for PERSISTENT_ISCSI_LOGIN_INFOA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for PERSISTENT_ISCSI_LOGIN_INFOA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("PERSISTENT_ISCSI_LOGIN_INFOA") .field("TargetName", &self.TargetName) .field("IsInformationalSession", &self.IsInformationalSession) .field("InitiatorInstance", &self.InitiatorInstance) .field("InitiatorPortNumber", &self.InitiatorPortNumber) .field("TargetPortal", &self.TargetPortal) .field("SecurityFlags", &self.SecurityFlags) .field("Mappings", &self.Mappings) .field("LoginOptions", &self.LoginOptions) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for PERSISTENT_ISCSI_LOGIN_INFOA { fn eq(&self, other: &Self) -> bool { self.TargetName == other.TargetName && self.IsInformationalSession == other.IsInformationalSession && self.InitiatorInstance == other.InitiatorInstance && self.InitiatorPortNumber == other.InitiatorPortNumber && self.TargetPortal == other.TargetPortal && self.SecurityFlags == other.SecurityFlags && self.Mappings == other.Mappings && self.LoginOptions == other.LoginOptions } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for PERSISTENT_ISCSI_LOGIN_INFOA {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for PERSISTENT_ISCSI_LOGIN_INFOA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct PERSISTENT_ISCSI_LOGIN_INFOW { pub TargetName: [u16; 224], pub IsInformationalSession: super::super::Foundation::BOOLEAN, pub InitiatorInstance: [u16; 256], pub InitiatorPortNumber: u32, pub TargetPortal: ISCSI_TARGET_PORTALW, pub SecurityFlags: u64, pub Mappings: *mut ISCSI_TARGET_MAPPINGW, pub LoginOptions: ISCSI_LOGIN_OPTIONS, } #[cfg(feature = "Win32_Foundation")] impl PERSISTENT_ISCSI_LOGIN_INFOW {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for PERSISTENT_ISCSI_LOGIN_INFOW { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for PERSISTENT_ISCSI_LOGIN_INFOW { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("PERSISTENT_ISCSI_LOGIN_INFOW") .field("TargetName", &self.TargetName) .field("IsInformationalSession", &self.IsInformationalSession) .field("InitiatorInstance", &self.InitiatorInstance) .field("InitiatorPortNumber", &self.InitiatorPortNumber) .field("TargetPortal", &self.TargetPortal) .field("SecurityFlags", &self.SecurityFlags) .field("Mappings", &self.Mappings) .field("LoginOptions", &self.LoginOptions) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for PERSISTENT_ISCSI_LOGIN_INFOW { fn eq(&self, other: &Self) -> bool { self.TargetName == other.TargetName && self.IsInformationalSession == other.IsInformationalSession && self.InitiatorInstance == other.InitiatorInstance && self.InitiatorPortNumber == other.InitiatorPortNumber && self.TargetPortal == other.TargetPortal && self.SecurityFlags == other.SecurityFlags && self.Mappings == other.Mappings && self.LoginOptions == other.LoginOptions } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for PERSISTENT_ISCSI_LOGIN_INFOW {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for PERSISTENT_ISCSI_LOGIN_INFOW { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RefreshISNSServerA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(address: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RefreshISNSServerA(address: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(RefreshISNSServerA(address.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RefreshISNSServerW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(address: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RefreshISNSServerW(address: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(RefreshISNSServerW(address.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RefreshIScsiSendTargetPortalA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(initiatorinstance: Param0, initiatorportnumber: u32, portal: *mut ISCSI_TARGET_PORTALA) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RefreshIScsiSendTargetPortalA(initiatorinstance: super::super::Foundation::PSTR, initiatorportnumber: u32, portal: *mut ISCSI_TARGET_PORTALA) -> u32; } ::core::mem::transmute(RefreshIScsiSendTargetPortalA(initiatorinstance.into_param().abi(), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(portal))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RefreshIScsiSendTargetPortalW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(initiatorinstance: Param0, initiatorportnumber: u32, portal: *mut ISCSI_TARGET_PORTALW) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RefreshIScsiSendTargetPortalW(initiatorinstance: super::super::Foundation::PWSTR, initiatorportnumber: u32, portal: *mut ISCSI_TARGET_PORTALW) -> u32; } ::core::mem::transmute(RefreshIScsiSendTargetPortalW(initiatorinstance.into_param().abi(), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(portal))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RemoveISNSServerA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(address: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemoveISNSServerA(address: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(RemoveISNSServerA(address.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RemoveISNSServerW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(address: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemoveISNSServerW(address: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(RemoveISNSServerW(address.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn RemoveIScsiConnection(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, connectionid: *mut ISCSI_UNIQUE_SESSION_ID) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemoveIScsiConnection(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, connectionid: *mut ISCSI_UNIQUE_SESSION_ID) -> u32; } ::core::mem::transmute(RemoveIScsiConnection(::core::mem::transmute(uniquesessionid), ::core::mem::transmute(connectionid))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RemoveIScsiPersistentTargetA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(initiatorinstance: Param0, initiatorportnumber: u32, targetname: Param2, portal: *mut ISCSI_TARGET_PORTALA) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemoveIScsiPersistentTargetA(initiatorinstance: super::super::Foundation::PSTR, initiatorportnumber: u32, targetname: super::super::Foundation::PSTR, portal: *mut ISCSI_TARGET_PORTALA) -> u32; } ::core::mem::transmute(RemoveIScsiPersistentTargetA(initiatorinstance.into_param().abi(), ::core::mem::transmute(initiatorportnumber), targetname.into_param().abi(), ::core::mem::transmute(portal))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RemoveIScsiPersistentTargetW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(initiatorinstance: Param0, initiatorportnumber: u32, targetname: Param2, portal: *mut ISCSI_TARGET_PORTALW) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemoveIScsiPersistentTargetW(initiatorinstance: super::super::Foundation::PWSTR, initiatorportnumber: u32, targetname: super::super::Foundation::PWSTR, portal: *mut ISCSI_TARGET_PORTALW) -> u32; } ::core::mem::transmute(RemoveIScsiPersistentTargetW(initiatorinstance.into_param().abi(), ::core::mem::transmute(initiatorportnumber), targetname.into_param().abi(), ::core::mem::transmute(portal))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RemoveIScsiSendTargetPortalA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(initiatorinstance: Param0, initiatorportnumber: u32, portal: *mut ISCSI_TARGET_PORTALA) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemoveIScsiSendTargetPortalA(initiatorinstance: super::super::Foundation::PSTR, initiatorportnumber: u32, portal: *mut ISCSI_TARGET_PORTALA) -> u32; } ::core::mem::transmute(RemoveIScsiSendTargetPortalA(initiatorinstance.into_param().abi(), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(portal))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RemoveIScsiSendTargetPortalW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(initiatorinstance: Param0, initiatorportnumber: u32, portal: *mut ISCSI_TARGET_PORTALW) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemoveIScsiSendTargetPortalW(initiatorinstance: super::super::Foundation::PWSTR, initiatorportnumber: u32, portal: *mut ISCSI_TARGET_PORTALW) -> u32; } ::core::mem::transmute(RemoveIScsiSendTargetPortalW(initiatorinstance.into_param().abi(), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(portal))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RemoveIScsiStaticTargetA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(targetname: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemoveIScsiStaticTargetA(targetname: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(RemoveIScsiStaticTargetA(targetname.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RemoveIScsiStaticTargetW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(targetname: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemoveIScsiStaticTargetW(targetname: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(RemoveIScsiStaticTargetW(targetname.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RemovePersistentIScsiDeviceA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(devicepath: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemovePersistentIScsiDeviceA(devicepath: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(RemovePersistentIScsiDeviceA(devicepath.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RemovePersistentIScsiDeviceW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(devicepath: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemovePersistentIScsiDeviceW(devicepath: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(RemovePersistentIScsiDeviceW(devicepath.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RemoveRadiusServerA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(address: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemoveRadiusServerA(address: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(RemoveRadiusServerA(address.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RemoveRadiusServerW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(address: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RemoveRadiusServerW(address: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(RemoveRadiusServerW(address.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportActiveIScsiTargetMappingsA(buffersize: *mut u32, mappingcount: *mut u32, mappings: *mut ISCSI_TARGET_MAPPINGA) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportActiveIScsiTargetMappingsA(buffersize: *mut u32, mappingcount: *mut u32, mappings: *mut ISCSI_TARGET_MAPPINGA) -> u32; } ::core::mem::transmute(ReportActiveIScsiTargetMappingsA(::core::mem::transmute(buffersize), ::core::mem::transmute(mappingcount), ::core::mem::transmute(mappings))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ReportActiveIScsiTargetMappingsW(buffersize: *mut u32, mappingcount: *mut u32, mappings: *mut ISCSI_TARGET_MAPPINGW) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportActiveIScsiTargetMappingsW(buffersize: *mut u32, mappingcount: *mut u32, mappings: *mut ISCSI_TARGET_MAPPINGW) -> u32; } ::core::mem::transmute(ReportActiveIScsiTargetMappingsW(::core::mem::transmute(buffersize), ::core::mem::transmute(mappingcount), ::core::mem::transmute(mappings))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportISNSServerListA(buffersizeinchar: *mut u32, buffer: super::super::Foundation::PSTR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportISNSServerListA(buffersizeinchar: *mut u32, buffer: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(ReportISNSServerListA(::core::mem::transmute(buffersizeinchar), ::core::mem::transmute(buffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportISNSServerListW(buffersizeinchar: *mut u32, buffer: super::super::Foundation::PWSTR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportISNSServerListW(buffersizeinchar: *mut u32, buffer: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(ReportISNSServerListW(::core::mem::transmute(buffersizeinchar), ::core::mem::transmute(buffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportIScsiInitiatorListA<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(buffersize: *mut u32, buffer: Param1) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportIScsiInitiatorListA(buffersize: *mut u32, buffer: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(ReportIScsiInitiatorListA(::core::mem::transmute(buffersize), buffer.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportIScsiInitiatorListW<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(buffersize: *mut u32, buffer: Param1) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportIScsiInitiatorListW(buffersize: *mut u32, buffer: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(ReportIScsiInitiatorListW(::core::mem::transmute(buffersize), buffer.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportIScsiPersistentLoginsA(count: *mut u32, persistentlogininfo: *mut PERSISTENT_ISCSI_LOGIN_INFOA, buffersizeinbytes: *mut u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportIScsiPersistentLoginsA(count: *mut u32, persistentlogininfo: *mut PERSISTENT_ISCSI_LOGIN_INFOA, buffersizeinbytes: *mut u32) -> u32; } ::core::mem::transmute(ReportIScsiPersistentLoginsA(::core::mem::transmute(count), ::core::mem::transmute(persistentlogininfo), ::core::mem::transmute(buffersizeinbytes))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportIScsiPersistentLoginsW(count: *mut u32, persistentlogininfo: *mut PERSISTENT_ISCSI_LOGIN_INFOW, buffersizeinbytes: *mut u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportIScsiPersistentLoginsW(count: *mut u32, persistentlogininfo: *mut PERSISTENT_ISCSI_LOGIN_INFOW, buffersizeinbytes: *mut u32) -> u32; } ::core::mem::transmute(ReportIScsiPersistentLoginsW(::core::mem::transmute(count), ::core::mem::transmute(persistentlogininfo), ::core::mem::transmute(buffersizeinbytes))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportIScsiSendTargetPortalsA(portalcount: *mut u32, portalinfo: *mut ISCSI_TARGET_PORTAL_INFOA) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportIScsiSendTargetPortalsA(portalcount: *mut u32, portalinfo: *mut ISCSI_TARGET_PORTAL_INFOA) -> u32; } ::core::mem::transmute(ReportIScsiSendTargetPortalsA(::core::mem::transmute(portalcount), ::core::mem::transmute(portalinfo))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportIScsiSendTargetPortalsExA(portalcount: *mut u32, portalinfosize: *mut u32, portalinfo: *mut ISCSI_TARGET_PORTAL_INFO_EXA) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportIScsiSendTargetPortalsExA(portalcount: *mut u32, portalinfosize: *mut u32, portalinfo: *mut ISCSI_TARGET_PORTAL_INFO_EXA) -> u32; } ::core::mem::transmute(ReportIScsiSendTargetPortalsExA(::core::mem::transmute(portalcount), ::core::mem::transmute(portalinfosize), ::core::mem::transmute(portalinfo))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ReportIScsiSendTargetPortalsExW(portalcount: *mut u32, portalinfosize: *mut u32, portalinfo: *mut ISCSI_TARGET_PORTAL_INFO_EXW) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportIScsiSendTargetPortalsExW(portalcount: *mut u32, portalinfosize: *mut u32, portalinfo: *mut ISCSI_TARGET_PORTAL_INFO_EXW) -> u32; } ::core::mem::transmute(ReportIScsiSendTargetPortalsExW(::core::mem::transmute(portalcount), ::core::mem::transmute(portalinfosize), ::core::mem::transmute(portalinfo))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ReportIScsiSendTargetPortalsW(portalcount: *mut u32, portalinfo: *mut ISCSI_TARGET_PORTAL_INFOW) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportIScsiSendTargetPortalsW(portalcount: *mut u32, portalinfo: *mut ISCSI_TARGET_PORTAL_INFOW) -> u32; } ::core::mem::transmute(ReportIScsiSendTargetPortalsW(::core::mem::transmute(portalcount), ::core::mem::transmute(portalinfo))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportIScsiTargetPortalsA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(initiatorname: Param0, targetname: Param1, targetportaltag: *mut u16, elementcount: *mut u32, portals: *mut ISCSI_TARGET_PORTALA) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportIScsiTargetPortalsA(initiatorname: super::super::Foundation::PSTR, targetname: super::super::Foundation::PSTR, targetportaltag: *mut u16, elementcount: *mut u32, portals: *mut ISCSI_TARGET_PORTALA) -> u32; } ::core::mem::transmute(ReportIScsiTargetPortalsA(initiatorname.into_param().abi(), targetname.into_param().abi(), ::core::mem::transmute(targetportaltag), ::core::mem::transmute(elementcount), ::core::mem::transmute(portals))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportIScsiTargetPortalsW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(initiatorname: Param0, targetname: Param1, targetportaltag: *mut u16, elementcount: *mut u32, portals: *mut ISCSI_TARGET_PORTALW) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportIScsiTargetPortalsW(initiatorname: super::super::Foundation::PWSTR, targetname: super::super::Foundation::PWSTR, targetportaltag: *mut u16, elementcount: *mut u32, portals: *mut ISCSI_TARGET_PORTALW) -> u32; } ::core::mem::transmute(ReportIScsiTargetPortalsW(initiatorname.into_param().abi(), targetname.into_param().abi(), ::core::mem::transmute(targetportaltag), ::core::mem::transmute(elementcount), ::core::mem::transmute(portals))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportIScsiTargetsA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(forceupdate: Param0, buffersize: *mut u32, buffer: Param2) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportIScsiTargetsA(forceupdate: super::super::Foundation::BOOLEAN, buffersize: *mut u32, buffer: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(ReportIScsiTargetsA(forceupdate.into_param().abi(), ::core::mem::transmute(buffersize), buffer.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportIScsiTargetsW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(forceupdate: Param0, buffersize: *mut u32, buffer: Param2) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportIScsiTargetsW(forceupdate: super::super::Foundation::BOOLEAN, buffersize: *mut u32, buffer: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(ReportIScsiTargetsW(forceupdate.into_param().abi(), ::core::mem::transmute(buffersize), buffer.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportPersistentIScsiDevicesA(buffersizeinchar: *mut u32, buffer: super::super::Foundation::PSTR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportPersistentIScsiDevicesA(buffersizeinchar: *mut u32, buffer: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(ReportPersistentIScsiDevicesA(::core::mem::transmute(buffersizeinchar), ::core::mem::transmute(buffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportPersistentIScsiDevicesW(buffersizeinchar: *mut u32, buffer: super::super::Foundation::PWSTR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportPersistentIScsiDevicesW(buffersizeinchar: *mut u32, buffer: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(ReportPersistentIScsiDevicesW(::core::mem::transmute(buffersizeinchar), ::core::mem::transmute(buffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportRadiusServerListA(buffersizeinchar: *mut u32, buffer: super::super::Foundation::PSTR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportRadiusServerListA(buffersizeinchar: *mut u32, buffer: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(ReportRadiusServerListA(::core::mem::transmute(buffersizeinchar), ::core::mem::transmute(buffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ReportRadiusServerListW(buffersizeinchar: *mut u32, buffer: super::super::Foundation::PWSTR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReportRadiusServerListW(buffersizeinchar: *mut u32, buffer: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(ReportRadiusServerListW(::core::mem::transmute(buffersizeinchar), ::core::mem::transmute(buffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SCSI_ADAPTER_BUS_INFO { pub NumberOfBuses: u8, pub BusData: [SCSI_BUS_DATA; 1], } impl SCSI_ADAPTER_BUS_INFO {} impl ::core::default::Default for SCSI_ADAPTER_BUS_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SCSI_ADAPTER_BUS_INFO { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_ADAPTER_BUS_INFO").field("NumberOfBuses", &self.NumberOfBuses).field("BusData", &self.BusData).finish() } } impl ::core::cmp::PartialEq for SCSI_ADAPTER_BUS_INFO { fn eq(&self, other: &Self) -> bool { self.NumberOfBuses == other.NumberOfBuses && self.BusData == other.BusData } } impl ::core::cmp::Eq for SCSI_ADAPTER_BUS_INFO {} unsafe impl ::windows::core::Abi for SCSI_ADAPTER_BUS_INFO { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SCSI_ADDRESS { pub Length: u32, pub PortNumber: u8, pub PathId: u8, pub TargetId: u8, pub Lun: u8, } impl SCSI_ADDRESS {} impl ::core::default::Default for SCSI_ADDRESS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SCSI_ADDRESS { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_ADDRESS").field("Length", &self.Length).field("PortNumber", &self.PortNumber).field("PathId", &self.PathId).field("TargetId", &self.TargetId).field("Lun", &self.Lun).finish() } } impl ::core::cmp::PartialEq for SCSI_ADDRESS { fn eq(&self, other: &Self) -> bool { self.Length == other.Length && self.PortNumber == other.PortNumber && self.PathId == other.PathId && self.TargetId == other.TargetId && self.Lun == other.Lun } } impl ::core::cmp::Eq for SCSI_ADDRESS {} unsafe impl ::windows::core::Abi for SCSI_ADDRESS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SCSI_BUS_DATA { pub NumberOfLogicalUnits: u8, pub InitiatorBusId: u8, pub InquiryDataOffset: u32, } impl SCSI_BUS_DATA {} impl ::core::default::Default for SCSI_BUS_DATA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SCSI_BUS_DATA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_BUS_DATA").field("NumberOfLogicalUnits", &self.NumberOfLogicalUnits).field("InitiatorBusId", &self.InitiatorBusId).field("InquiryDataOffset", &self.InquiryDataOffset).finish() } } impl ::core::cmp::PartialEq for SCSI_BUS_DATA { fn eq(&self, other: &Self) -> bool { self.NumberOfLogicalUnits == other.NumberOfLogicalUnits && self.InitiatorBusId == other.InitiatorBusId && self.InquiryDataOffset == other.InquiryDataOffset } } impl ::core::cmp::Eq for SCSI_BUS_DATA {} unsafe impl ::windows::core::Abi for SCSI_BUS_DATA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct SCSI_INQUIRY_DATA { pub PathId: u8, pub TargetId: u8, pub Lun: u8, pub DeviceClaimed: super::super::Foundation::BOOLEAN, pub InquiryDataLength: u32, pub NextInquiryDataOffset: u32, pub InquiryData: [u8; 1], } #[cfg(feature = "Win32_Foundation")] impl SCSI_INQUIRY_DATA {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for SCSI_INQUIRY_DATA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for SCSI_INQUIRY_DATA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_INQUIRY_DATA") .field("PathId", &self.PathId) .field("TargetId", &self.TargetId) .field("Lun", &self.Lun) .field("DeviceClaimed", &self.DeviceClaimed) .field("InquiryDataLength", &self.InquiryDataLength) .field("NextInquiryDataOffset", &self.NextInquiryDataOffset) .field("InquiryData", &self.InquiryData) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for SCSI_INQUIRY_DATA { fn eq(&self, other: &Self) -> bool { self.PathId == other.PathId && self.TargetId == other.TargetId && self.Lun == other.Lun && self.DeviceClaimed == other.DeviceClaimed && self.InquiryDataLength == other.InquiryDataLength && self.NextInquiryDataOffset == other.NextInquiryDataOffset && self.InquiryData == other.InquiryData } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for SCSI_INQUIRY_DATA {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for SCSI_INQUIRY_DATA { type Abi = Self; } pub const SCSI_IOCTL_DATA_BIDIRECTIONAL: u32 = 3u32; pub const SCSI_IOCTL_DATA_IN: u32 = 1u32; pub const SCSI_IOCTL_DATA_OUT: u32 = 0u32; pub const SCSI_IOCTL_DATA_UNSPECIFIED: u32 = 2u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SCSI_LUN_LIST { pub OSLUN: u32, pub TargetLUN: u64, } impl SCSI_LUN_LIST {} impl ::core::default::Default for SCSI_LUN_LIST { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SCSI_LUN_LIST { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_LUN_LIST").field("OSLUN", &self.OSLUN).field("TargetLUN", &self.TargetLUN).finish() } } impl ::core::cmp::PartialEq for SCSI_LUN_LIST { fn eq(&self, other: &Self) -> bool { self.OSLUN == other.OSLUN && self.TargetLUN == other.TargetLUN } } impl ::core::cmp::Eq for SCSI_LUN_LIST {} unsafe impl ::windows::core::Abi for SCSI_LUN_LIST { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SCSI_PASS_THROUGH { pub Length: u16, pub ScsiStatus: u8, pub PathId: u8, pub TargetId: u8, pub Lun: u8, pub CdbLength: u8, pub SenseInfoLength: u8, pub DataIn: u8, pub DataTransferLength: u32, pub TimeOutValue: u32, pub DataBufferOffset: usize, pub SenseInfoOffset: u32, pub Cdb: [u8; 16], } impl SCSI_PASS_THROUGH {} impl ::core::default::Default for SCSI_PASS_THROUGH { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SCSI_PASS_THROUGH { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_PASS_THROUGH") .field("Length", &self.Length) .field("ScsiStatus", &self.ScsiStatus) .field("PathId", &self.PathId) .field("TargetId", &self.TargetId) .field("Lun", &self.Lun) .field("CdbLength", &self.CdbLength) .field("SenseInfoLength", &self.SenseInfoLength) .field("DataIn", &self.DataIn) .field("DataTransferLength", &self.DataTransferLength) .field("TimeOutValue", &self.TimeOutValue) .field("DataBufferOffset", &self.DataBufferOffset) .field("SenseInfoOffset", &self.SenseInfoOffset) .field("Cdb", &self.Cdb) .finish() } } impl ::core::cmp::PartialEq for SCSI_PASS_THROUGH { fn eq(&self, other: &Self) -> bool { self.Length == other.Length && self.ScsiStatus == other.ScsiStatus && self.PathId == other.PathId && self.TargetId == other.TargetId && self.Lun == other.Lun && self.CdbLength == other.CdbLength && self.SenseInfoLength == other.SenseInfoLength && self.DataIn == other.DataIn && self.DataTransferLength == other.DataTransferLength && self.TimeOutValue == other.TimeOutValue && self.DataBufferOffset == other.DataBufferOffset && self.SenseInfoOffset == other.SenseInfoOffset && self.Cdb == other.Cdb } } impl ::core::cmp::Eq for SCSI_PASS_THROUGH {} unsafe impl ::windows::core::Abi for SCSI_PASS_THROUGH { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct SCSI_PASS_THROUGH32 { pub Length: u16, pub ScsiStatus: u8, pub PathId: u8, pub TargetId: u8, pub Lun: u8, pub CdbLength: u8, pub SenseInfoLength: u8, pub DataIn: u8, pub DataTransferLength: u32, pub TimeOutValue: u32, pub DataBufferOffset: u32, pub SenseInfoOffset: u32, pub Cdb: [u8; 16], } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl SCSI_PASS_THROUGH32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for SCSI_PASS_THROUGH32 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for SCSI_PASS_THROUGH32 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_PASS_THROUGH32") .field("Length", &self.Length) .field("ScsiStatus", &self.ScsiStatus) .field("PathId", &self.PathId) .field("TargetId", &self.TargetId) .field("Lun", &self.Lun) .field("CdbLength", &self.CdbLength) .field("SenseInfoLength", &self.SenseInfoLength) .field("DataIn", &self.DataIn) .field("DataTransferLength", &self.DataTransferLength) .field("TimeOutValue", &self.TimeOutValue) .field("DataBufferOffset", &self.DataBufferOffset) .field("SenseInfoOffset", &self.SenseInfoOffset) .field("Cdb", &self.Cdb) .finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for SCSI_PASS_THROUGH32 { fn eq(&self, other: &Self) -> bool { self.Length == other.Length && self.ScsiStatus == other.ScsiStatus && self.PathId == other.PathId && self.TargetId == other.TargetId && self.Lun == other.Lun && self.CdbLength == other.CdbLength && self.SenseInfoLength == other.SenseInfoLength && self.DataIn == other.DataIn && self.DataTransferLength == other.DataTransferLength && self.TimeOutValue == other.TimeOutValue && self.DataBufferOffset == other.DataBufferOffset && self.SenseInfoOffset == other.SenseInfoOffset && self.Cdb == other.Cdb } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for SCSI_PASS_THROUGH32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for SCSI_PASS_THROUGH32 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct SCSI_PASS_THROUGH32_EX { pub Version: u32, pub Length: u32, pub CdbLength: u32, pub StorAddressLength: u32, pub ScsiStatus: u8, pub SenseInfoLength: u8, pub DataDirection: u8, pub Reserved: u8, pub TimeOutValue: u32, pub StorAddressOffset: u32, pub SenseInfoOffset: u32, pub DataOutTransferLength: u32, pub DataInTransferLength: u32, pub DataOutBufferOffset: u32, pub DataInBufferOffset: u32, pub Cdb: [u8; 1], } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl SCSI_PASS_THROUGH32_EX {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for SCSI_PASS_THROUGH32_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for SCSI_PASS_THROUGH32_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_PASS_THROUGH32_EX") .field("Version", &self.Version) .field("Length", &self.Length) .field("CdbLength", &self.CdbLength) .field("StorAddressLength", &self.StorAddressLength) .field("ScsiStatus", &self.ScsiStatus) .field("SenseInfoLength", &self.SenseInfoLength) .field("DataDirection", &self.DataDirection) .field("Reserved", &self.Reserved) .field("TimeOutValue", &self.TimeOutValue) .field("StorAddressOffset", &self.StorAddressOffset) .field("SenseInfoOffset", &self.SenseInfoOffset) .field("DataOutTransferLength", &self.DataOutTransferLength) .field("DataInTransferLength", &self.DataInTransferLength) .field("DataOutBufferOffset", &self.DataOutBufferOffset) .field("DataInBufferOffset", &self.DataInBufferOffset) .field("Cdb", &self.Cdb) .finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for SCSI_PASS_THROUGH32_EX { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Length == other.Length && self.CdbLength == other.CdbLength && self.StorAddressLength == other.StorAddressLength && self.ScsiStatus == other.ScsiStatus && self.SenseInfoLength == other.SenseInfoLength && self.DataDirection == other.DataDirection && self.Reserved == other.Reserved && self.TimeOutValue == other.TimeOutValue && self.StorAddressOffset == other.StorAddressOffset && self.SenseInfoOffset == other.SenseInfoOffset && self.DataOutTransferLength == other.DataOutTransferLength && self.DataInTransferLength == other.DataInTransferLength && self.DataOutBufferOffset == other.DataOutBufferOffset && self.DataInBufferOffset == other.DataInBufferOffset && self.Cdb == other.Cdb } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for SCSI_PASS_THROUGH32_EX {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for SCSI_PASS_THROUGH32_EX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SCSI_PASS_THROUGH_DIRECT { pub Length: u16, pub ScsiStatus: u8, pub PathId: u8, pub TargetId: u8, pub Lun: u8, pub CdbLength: u8, pub SenseInfoLength: u8, pub DataIn: u8, pub DataTransferLength: u32, pub TimeOutValue: u32, pub DataBuffer: *mut ::core::ffi::c_void, pub SenseInfoOffset: u32, pub Cdb: [u8; 16], } impl SCSI_PASS_THROUGH_DIRECT {} impl ::core::default::Default for SCSI_PASS_THROUGH_DIRECT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SCSI_PASS_THROUGH_DIRECT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_PASS_THROUGH_DIRECT") .field("Length", &self.Length) .field("ScsiStatus", &self.ScsiStatus) .field("PathId", &self.PathId) .field("TargetId", &self.TargetId) .field("Lun", &self.Lun) .field("CdbLength", &self.CdbLength) .field("SenseInfoLength", &self.SenseInfoLength) .field("DataIn", &self.DataIn) .field("DataTransferLength", &self.DataTransferLength) .field("TimeOutValue", &self.TimeOutValue) .field("DataBuffer", &self.DataBuffer) .field("SenseInfoOffset", &self.SenseInfoOffset) .field("Cdb", &self.Cdb) .finish() } } impl ::core::cmp::PartialEq for SCSI_PASS_THROUGH_DIRECT { fn eq(&self, other: &Self) -> bool { self.Length == other.Length && self.ScsiStatus == other.ScsiStatus && self.PathId == other.PathId && self.TargetId == other.TargetId && self.Lun == other.Lun && self.CdbLength == other.CdbLength && self.SenseInfoLength == other.SenseInfoLength && self.DataIn == other.DataIn && self.DataTransferLength == other.DataTransferLength && self.TimeOutValue == other.TimeOutValue && self.DataBuffer == other.DataBuffer && self.SenseInfoOffset == other.SenseInfoOffset && self.Cdb == other.Cdb } } impl ::core::cmp::Eq for SCSI_PASS_THROUGH_DIRECT {} unsafe impl ::windows::core::Abi for SCSI_PASS_THROUGH_DIRECT { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct SCSI_PASS_THROUGH_DIRECT32 { pub Length: u16, pub ScsiStatus: u8, pub PathId: u8, pub TargetId: u8, pub Lun: u8, pub CdbLength: u8, pub SenseInfoLength: u8, pub DataIn: u8, pub DataTransferLength: u32, pub TimeOutValue: u32, pub DataBuffer: *mut ::core::ffi::c_void, pub SenseInfoOffset: u32, pub Cdb: [u8; 16], } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl SCSI_PASS_THROUGH_DIRECT32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for SCSI_PASS_THROUGH_DIRECT32 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for SCSI_PASS_THROUGH_DIRECT32 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_PASS_THROUGH_DIRECT32") .field("Length", &self.Length) .field("ScsiStatus", &self.ScsiStatus) .field("PathId", &self.PathId) .field("TargetId", &self.TargetId) .field("Lun", &self.Lun) .field("CdbLength", &self.CdbLength) .field("SenseInfoLength", &self.SenseInfoLength) .field("DataIn", &self.DataIn) .field("DataTransferLength", &self.DataTransferLength) .field("TimeOutValue", &self.TimeOutValue) .field("DataBuffer", &self.DataBuffer) .field("SenseInfoOffset", &self.SenseInfoOffset) .field("Cdb", &self.Cdb) .finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for SCSI_PASS_THROUGH_DIRECT32 { fn eq(&self, other: &Self) -> bool { self.Length == other.Length && self.ScsiStatus == other.ScsiStatus && self.PathId == other.PathId && self.TargetId == other.TargetId && self.Lun == other.Lun && self.CdbLength == other.CdbLength && self.SenseInfoLength == other.SenseInfoLength && self.DataIn == other.DataIn && self.DataTransferLength == other.DataTransferLength && self.TimeOutValue == other.TimeOutValue && self.DataBuffer == other.DataBuffer && self.SenseInfoOffset == other.SenseInfoOffset && self.Cdb == other.Cdb } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for SCSI_PASS_THROUGH_DIRECT32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for SCSI_PASS_THROUGH_DIRECT32 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct SCSI_PASS_THROUGH_DIRECT32_EX { pub Version: u32, pub Length: u32, pub CdbLength: u32, pub StorAddressLength: u32, pub ScsiStatus: u8, pub SenseInfoLength: u8, pub DataDirection: u8, pub Reserved: u8, pub TimeOutValue: u32, pub StorAddressOffset: u32, pub SenseInfoOffset: u32, pub DataOutTransferLength: u32, pub DataInTransferLength: u32, pub DataOutBuffer: *mut ::core::ffi::c_void, pub DataInBuffer: *mut ::core::ffi::c_void, pub Cdb: [u8; 1], } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl SCSI_PASS_THROUGH_DIRECT32_EX {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for SCSI_PASS_THROUGH_DIRECT32_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for SCSI_PASS_THROUGH_DIRECT32_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_PASS_THROUGH_DIRECT32_EX") .field("Version", &self.Version) .field("Length", &self.Length) .field("CdbLength", &self.CdbLength) .field("StorAddressLength", &self.StorAddressLength) .field("ScsiStatus", &self.ScsiStatus) .field("SenseInfoLength", &self.SenseInfoLength) .field("DataDirection", &self.DataDirection) .field("Reserved", &self.Reserved) .field("TimeOutValue", &self.TimeOutValue) .field("StorAddressOffset", &self.StorAddressOffset) .field("SenseInfoOffset", &self.SenseInfoOffset) .field("DataOutTransferLength", &self.DataOutTransferLength) .field("DataInTransferLength", &self.DataInTransferLength) .field("DataOutBuffer", &self.DataOutBuffer) .field("DataInBuffer", &self.DataInBuffer) .field("Cdb", &self.Cdb) .finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for SCSI_PASS_THROUGH_DIRECT32_EX { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Length == other.Length && self.CdbLength == other.CdbLength && self.StorAddressLength == other.StorAddressLength && self.ScsiStatus == other.ScsiStatus && self.SenseInfoLength == other.SenseInfoLength && self.DataDirection == other.DataDirection && self.Reserved == other.Reserved && self.TimeOutValue == other.TimeOutValue && self.StorAddressOffset == other.StorAddressOffset && self.SenseInfoOffset == other.SenseInfoOffset && self.DataOutTransferLength == other.DataOutTransferLength && self.DataInTransferLength == other.DataInTransferLength && self.DataOutBuffer == other.DataOutBuffer && self.DataInBuffer == other.DataInBuffer && self.Cdb == other.Cdb } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for SCSI_PASS_THROUGH_DIRECT32_EX {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for SCSI_PASS_THROUGH_DIRECT32_EX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SCSI_PASS_THROUGH_DIRECT_EX { pub Version: u32, pub Length: u32, pub CdbLength: u32, pub StorAddressLength: u32, pub ScsiStatus: u8, pub SenseInfoLength: u8, pub DataDirection: u8, pub Reserved: u8, pub TimeOutValue: u32, pub StorAddressOffset: u32, pub SenseInfoOffset: u32, pub DataOutTransferLength: u32, pub DataInTransferLength: u32, pub DataOutBuffer: *mut ::core::ffi::c_void, pub DataInBuffer: *mut ::core::ffi::c_void, pub Cdb: [u8; 1], } impl SCSI_PASS_THROUGH_DIRECT_EX {} impl ::core::default::Default for SCSI_PASS_THROUGH_DIRECT_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SCSI_PASS_THROUGH_DIRECT_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_PASS_THROUGH_DIRECT_EX") .field("Version", &self.Version) .field("Length", &self.Length) .field("CdbLength", &self.CdbLength) .field("StorAddressLength", &self.StorAddressLength) .field("ScsiStatus", &self.ScsiStatus) .field("SenseInfoLength", &self.SenseInfoLength) .field("DataDirection", &self.DataDirection) .field("Reserved", &self.Reserved) .field("TimeOutValue", &self.TimeOutValue) .field("StorAddressOffset", &self.StorAddressOffset) .field("SenseInfoOffset", &self.SenseInfoOffset) .field("DataOutTransferLength", &self.DataOutTransferLength) .field("DataInTransferLength", &self.DataInTransferLength) .field("DataOutBuffer", &self.DataOutBuffer) .field("DataInBuffer", &self.DataInBuffer) .field("Cdb", &self.Cdb) .finish() } } impl ::core::cmp::PartialEq for SCSI_PASS_THROUGH_DIRECT_EX { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Length == other.Length && self.CdbLength == other.CdbLength && self.StorAddressLength == other.StorAddressLength && self.ScsiStatus == other.ScsiStatus && self.SenseInfoLength == other.SenseInfoLength && self.DataDirection == other.DataDirection && self.Reserved == other.Reserved && self.TimeOutValue == other.TimeOutValue && self.StorAddressOffset == other.StorAddressOffset && self.SenseInfoOffset == other.SenseInfoOffset && self.DataOutTransferLength == other.DataOutTransferLength && self.DataInTransferLength == other.DataInTransferLength && self.DataOutBuffer == other.DataOutBuffer && self.DataInBuffer == other.DataInBuffer && self.Cdb == other.Cdb } } impl ::core::cmp::Eq for SCSI_PASS_THROUGH_DIRECT_EX {} unsafe impl ::windows::core::Abi for SCSI_PASS_THROUGH_DIRECT_EX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SCSI_PASS_THROUGH_EX { pub Version: u32, pub Length: u32, pub CdbLength: u32, pub StorAddressLength: u32, pub ScsiStatus: u8, pub SenseInfoLength: u8, pub DataDirection: u8, pub Reserved: u8, pub TimeOutValue: u32, pub StorAddressOffset: u32, pub SenseInfoOffset: u32, pub DataOutTransferLength: u32, pub DataInTransferLength: u32, pub DataOutBufferOffset: usize, pub DataInBufferOffset: usize, pub Cdb: [u8; 1], } impl SCSI_PASS_THROUGH_EX {} impl ::core::default::Default for SCSI_PASS_THROUGH_EX { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SCSI_PASS_THROUGH_EX { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCSI_PASS_THROUGH_EX") .field("Version", &self.Version) .field("Length", &self.Length) .field("CdbLength", &self.CdbLength) .field("StorAddressLength", &self.StorAddressLength) .field("ScsiStatus", &self.ScsiStatus) .field("SenseInfoLength", &self.SenseInfoLength) .field("DataDirection", &self.DataDirection) .field("Reserved", &self.Reserved) .field("TimeOutValue", &self.TimeOutValue) .field("StorAddressOffset", &self.StorAddressOffset) .field("SenseInfoOffset", &self.SenseInfoOffset) .field("DataOutTransferLength", &self.DataOutTransferLength) .field("DataInTransferLength", &self.DataInTransferLength) .field("DataOutBufferOffset", &self.DataOutBufferOffset) .field("DataInBufferOffset", &self.DataInBufferOffset) .field("Cdb", &self.Cdb) .finish() } } impl ::core::cmp::PartialEq for SCSI_PASS_THROUGH_EX { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Length == other.Length && self.CdbLength == other.CdbLength && self.StorAddressLength == other.StorAddressLength && self.ScsiStatus == other.ScsiStatus && self.SenseInfoLength == other.SenseInfoLength && self.DataDirection == other.DataDirection && self.Reserved == other.Reserved && self.TimeOutValue == other.TimeOutValue && self.StorAddressOffset == other.StorAddressOffset && self.SenseInfoOffset == other.SenseInfoOffset && self.DataOutTransferLength == other.DataOutTransferLength && self.DataInTransferLength == other.DataInTransferLength && self.DataOutBufferOffset == other.DataOutBufferOffset && self.DataInBufferOffset == other.DataInBufferOffset && self.Cdb == other.Cdb } } impl ::core::cmp::Eq for SCSI_PASS_THROUGH_EX {} unsafe impl ::windows::core::Abi for SCSI_PASS_THROUGH_EX { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SRB_IO_CONTROL { pub HeaderLength: u32, pub Signature: [u8; 8], pub Timeout: u32, pub ControlCode: u32, pub ReturnCode: u32, pub Length: u32, } impl SRB_IO_CONTROL {} impl ::core::default::Default for SRB_IO_CONTROL { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SRB_IO_CONTROL { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SRB_IO_CONTROL").field("HeaderLength", &self.HeaderLength).field("Signature", &self.Signature).field("Timeout", &self.Timeout).field("ControlCode", &self.ControlCode).field("ReturnCode", &self.ReturnCode).field("Length", &self.Length).finish() } } impl ::core::cmp::PartialEq for SRB_IO_CONTROL { fn eq(&self, other: &Self) -> bool { self.HeaderLength == other.HeaderLength && self.Signature == other.Signature && self.Timeout == other.Timeout && self.ControlCode == other.ControlCode && self.ReturnCode == other.ReturnCode && self.Length == other.Length } } impl ::core::cmp::Eq for SRB_IO_CONTROL {} unsafe impl ::windows::core::Abi for SRB_IO_CONTROL { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct STORAGE_DIAGNOSTIC_MP_REQUEST { pub Version: u32, pub Size: u32, pub TargetType: MP_STORAGE_DIAGNOSTIC_TARGET_TYPE, pub Level: MP_STORAGE_DIAGNOSTIC_LEVEL, pub ProviderId: ::windows::core::GUID, pub BufferSize: u32, pub Reserved: u32, pub DataBuffer: [u8; 1], } impl STORAGE_DIAGNOSTIC_MP_REQUEST {} impl ::core::default::Default for STORAGE_DIAGNOSTIC_MP_REQUEST { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for STORAGE_DIAGNOSTIC_MP_REQUEST { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("STORAGE_DIAGNOSTIC_MP_REQUEST") .field("Version", &self.Version) .field("Size", &self.Size) .field("TargetType", &self.TargetType) .field("Level", &self.Level) .field("ProviderId", &self.ProviderId) .field("BufferSize", &self.BufferSize) .field("Reserved", &self.Reserved) .field("DataBuffer", &self.DataBuffer) .finish() } } impl ::core::cmp::PartialEq for STORAGE_DIAGNOSTIC_MP_REQUEST { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Size == other.Size && self.TargetType == other.TargetType && self.Level == other.Level && self.ProviderId == other.ProviderId && self.BufferSize == other.BufferSize && self.Reserved == other.Reserved && self.DataBuffer == other.DataBuffer } } impl ::core::cmp::Eq for STORAGE_DIAGNOSTIC_MP_REQUEST {} unsafe impl ::windows::core::Abi for STORAGE_DIAGNOSTIC_MP_REQUEST { type Abi = Self; } pub const STORAGE_DIAGNOSTIC_STATUS_BUFFER_TOO_SMALL: u32 = 1u32; pub const STORAGE_DIAGNOSTIC_STATUS_INVALID_PARAMETER: u32 = 3u32; pub const STORAGE_DIAGNOSTIC_STATUS_INVALID_SIGNATURE: u32 = 4u32; pub const STORAGE_DIAGNOSTIC_STATUS_INVALID_TARGET_TYPE: u32 = 5u32; pub const STORAGE_DIAGNOSTIC_STATUS_MORE_DATA: u32 = 6u32; pub const STORAGE_DIAGNOSTIC_STATUS_SUCCESS: u32 = 0u32; pub const STORAGE_DIAGNOSTIC_STATUS_UNSUPPORTED_VERSION: u32 = 2u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct STORAGE_ENDURANCE_DATA_DESCRIPTOR { pub Version: u32, pub Size: u32, pub EnduranceInfo: STORAGE_ENDURANCE_INFO, } impl STORAGE_ENDURANCE_DATA_DESCRIPTOR {} impl ::core::default::Default for STORAGE_ENDURANCE_DATA_DESCRIPTOR { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for STORAGE_ENDURANCE_DATA_DESCRIPTOR { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("STORAGE_ENDURANCE_DATA_DESCRIPTOR").field("Version", &self.Version).field("Size", &self.Size).field("EnduranceInfo", &self.EnduranceInfo).finish() } } impl ::core::cmp::PartialEq for STORAGE_ENDURANCE_DATA_DESCRIPTOR { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Size == other.Size && self.EnduranceInfo == other.EnduranceInfo } } impl ::core::cmp::Eq for STORAGE_ENDURANCE_DATA_DESCRIPTOR {} unsafe impl ::windows::core::Abi for STORAGE_ENDURANCE_DATA_DESCRIPTOR { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct STORAGE_ENDURANCE_INFO { pub ValidFields: u32, pub GroupId: u32, pub Flags: STORAGE_ENDURANCE_INFO_0, pub LifePercentage: u32, pub BytesReadCount: [u8; 16], pub ByteWriteCount: [u8; 16], } impl STORAGE_ENDURANCE_INFO {} impl ::core::default::Default for STORAGE_ENDURANCE_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for STORAGE_ENDURANCE_INFO { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("STORAGE_ENDURANCE_INFO").field("ValidFields", &self.ValidFields).field("GroupId", &self.GroupId).field("Flags", &self.Flags).field("LifePercentage", &self.LifePercentage).field("BytesReadCount", &self.BytesReadCount).field("ByteWriteCount", &self.ByteWriteCount).finish() } } impl ::core::cmp::PartialEq for STORAGE_ENDURANCE_INFO { fn eq(&self, other: &Self) -> bool { self.ValidFields == other.ValidFields && self.GroupId == other.GroupId && self.Flags == other.Flags && self.LifePercentage == other.LifePercentage && self.BytesReadCount == other.BytesReadCount && self.ByteWriteCount == other.ByteWriteCount } } impl ::core::cmp::Eq for STORAGE_ENDURANCE_INFO {} unsafe impl ::windows::core::Abi for STORAGE_ENDURANCE_INFO { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct STORAGE_ENDURANCE_INFO_0 { pub _bitfield: u32, } impl STORAGE_ENDURANCE_INFO_0 {} impl ::core::default::Default for STORAGE_ENDURANCE_INFO_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for STORAGE_ENDURANCE_INFO_0 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("_Flags_e__Struct").field("_bitfield", &self._bitfield).finish() } } impl ::core::cmp::PartialEq for STORAGE_ENDURANCE_INFO_0 { fn eq(&self, other: &Self) -> bool { self._bitfield == other._bitfield } } impl ::core::cmp::Eq for STORAGE_ENDURANCE_INFO_0 {} unsafe impl ::windows::core::Abi for STORAGE_ENDURANCE_INFO_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct STORAGE_FIRMWARE_ACTIVATE { pub Version: u32, pub Size: u32, pub SlotToActivate: u8, pub Reserved0: [u8; 3], } impl STORAGE_FIRMWARE_ACTIVATE {} impl ::core::default::Default for STORAGE_FIRMWARE_ACTIVATE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for STORAGE_FIRMWARE_ACTIVATE { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("STORAGE_FIRMWARE_ACTIVATE").field("Version", &self.Version).field("Size", &self.Size).field("SlotToActivate", &self.SlotToActivate).field("Reserved0", &self.Reserved0).finish() } } impl ::core::cmp::PartialEq for STORAGE_FIRMWARE_ACTIVATE { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Size == other.Size && self.SlotToActivate == other.SlotToActivate && self.Reserved0 == other.Reserved0 } } impl ::core::cmp::Eq for STORAGE_FIRMWARE_ACTIVATE {} unsafe impl ::windows::core::Abi for STORAGE_FIRMWARE_ACTIVATE { type Abi = Self; } pub const STORAGE_FIRMWARE_ACTIVATE_STRUCTURE_VERSION: u32 = 1u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct STORAGE_FIRMWARE_DOWNLOAD { pub Version: u32, pub Size: u32, pub Offset: u64, pub BufferSize: u64, pub ImageBuffer: [u8; 1], } impl STORAGE_FIRMWARE_DOWNLOAD {} impl ::core::default::Default for STORAGE_FIRMWARE_DOWNLOAD { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for STORAGE_FIRMWARE_DOWNLOAD { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("STORAGE_FIRMWARE_DOWNLOAD").field("Version", &self.Version).field("Size", &self.Size).field("Offset", &self.Offset).field("BufferSize", &self.BufferSize).field("ImageBuffer", &self.ImageBuffer).finish() } } impl ::core::cmp::PartialEq for STORAGE_FIRMWARE_DOWNLOAD { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Size == other.Size && self.Offset == other.Offset && self.BufferSize == other.BufferSize && self.ImageBuffer == other.ImageBuffer } } impl ::core::cmp::Eq for STORAGE_FIRMWARE_DOWNLOAD {} unsafe impl ::windows::core::Abi for STORAGE_FIRMWARE_DOWNLOAD { type Abi = Self; } pub const STORAGE_FIRMWARE_DOWNLOAD_STRUCTURE_VERSION: u32 = 1u32; pub const STORAGE_FIRMWARE_DOWNLOAD_STRUCTURE_VERSION_V2: u32 = 2u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct STORAGE_FIRMWARE_DOWNLOAD_V2 { pub Version: u32, pub Size: u32, pub Offset: u64, pub BufferSize: u64, pub Slot: u8, pub Reserved: [u8; 3], pub ImageSize: u32, pub ImageBuffer: [u8; 1], } impl STORAGE_FIRMWARE_DOWNLOAD_V2 {} impl ::core::default::Default for STORAGE_FIRMWARE_DOWNLOAD_V2 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for STORAGE_FIRMWARE_DOWNLOAD_V2 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("STORAGE_FIRMWARE_DOWNLOAD_V2") .field("Version", &self.Version) .field("Size", &self.Size) .field("Offset", &self.Offset) .field("BufferSize", &self.BufferSize) .field("Slot", &self.Slot) .field("Reserved", &self.Reserved) .field("ImageSize", &self.ImageSize) .field("ImageBuffer", &self.ImageBuffer) .finish() } } impl ::core::cmp::PartialEq for STORAGE_FIRMWARE_DOWNLOAD_V2 { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Size == other.Size && self.Offset == other.Offset && self.BufferSize == other.BufferSize && self.Slot == other.Slot && self.Reserved == other.Reserved && self.ImageSize == other.ImageSize && self.ImageBuffer == other.ImageBuffer } } impl ::core::cmp::Eq for STORAGE_FIRMWARE_DOWNLOAD_V2 {} unsafe impl ::windows::core::Abi for STORAGE_FIRMWARE_DOWNLOAD_V2 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct STORAGE_FIRMWARE_INFO { pub Version: u32, pub Size: u32, pub UpgradeSupport: super::super::Foundation::BOOLEAN, pub SlotCount: u8, pub ActiveSlot: u8, pub PendingActivateSlot: u8, pub Reserved: u32, pub Slot: [STORAGE_FIRMWARE_SLOT_INFO; 1], } #[cfg(feature = "Win32_Foundation")] impl STORAGE_FIRMWARE_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for STORAGE_FIRMWARE_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for STORAGE_FIRMWARE_INFO { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for STORAGE_FIRMWARE_INFO {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for STORAGE_FIRMWARE_INFO { type Abi = Self; } pub const STORAGE_FIRMWARE_INFO_INVALID_SLOT: u32 = 255u32; pub const STORAGE_FIRMWARE_INFO_STRUCTURE_VERSION: u32 = 1u32; pub const STORAGE_FIRMWARE_INFO_STRUCTURE_VERSION_V2: u32 = 2u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct STORAGE_FIRMWARE_INFO_V2 { pub Version: u32, pub Size: u32, pub UpgradeSupport: super::super::Foundation::BOOLEAN, pub SlotCount: u8, pub ActiveSlot: u8, pub PendingActivateSlot: u8, pub FirmwareShared: super::super::Foundation::BOOLEAN, pub Reserved: [u8; 3], pub ImagePayloadAlignment: u32, pub ImagePayloadMaxSize: u32, pub Slot: [STORAGE_FIRMWARE_SLOT_INFO_V2; 1], } #[cfg(feature = "Win32_Foundation")] impl STORAGE_FIRMWARE_INFO_V2 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for STORAGE_FIRMWARE_INFO_V2 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for STORAGE_FIRMWARE_INFO_V2 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("STORAGE_FIRMWARE_INFO_V2") .field("Version", &self.Version) .field("Size", &self.Size) .field("UpgradeSupport", &self.UpgradeSupport) .field("SlotCount", &self.SlotCount) .field("ActiveSlot", &self.ActiveSlot) .field("PendingActivateSlot", &self.PendingActivateSlot) .field("FirmwareShared", &self.FirmwareShared) .field("Reserved", &self.Reserved) .field("ImagePayloadAlignment", &self.ImagePayloadAlignment) .field("ImagePayloadMaxSize", &self.ImagePayloadMaxSize) .field("Slot", &self.Slot) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for STORAGE_FIRMWARE_INFO_V2 { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.Size == other.Size && self.UpgradeSupport == other.UpgradeSupport && self.SlotCount == other.SlotCount && self.ActiveSlot == other.ActiveSlot && self.PendingActivateSlot == other.PendingActivateSlot && self.FirmwareShared == other.FirmwareShared && self.Reserved == other.Reserved && self.ImagePayloadAlignment == other.ImagePayloadAlignment && self.ImagePayloadMaxSize == other.ImagePayloadMaxSize && self.Slot == other.Slot } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for STORAGE_FIRMWARE_INFO_V2 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for STORAGE_FIRMWARE_INFO_V2 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct STORAGE_FIRMWARE_SLOT_INFO { pub SlotNumber: u8, pub ReadOnly: super::super::Foundation::BOOLEAN, pub Reserved: [u8; 6], pub Revision: STORAGE_FIRMWARE_SLOT_INFO_0, } #[cfg(feature = "Win32_Foundation")] impl STORAGE_FIRMWARE_SLOT_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for STORAGE_FIRMWARE_SLOT_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for STORAGE_FIRMWARE_SLOT_INFO { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for STORAGE_FIRMWARE_SLOT_INFO {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for STORAGE_FIRMWARE_SLOT_INFO { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union STORAGE_FIRMWARE_SLOT_INFO_0 { pub Info: [u8; 8], pub AsUlonglong: u64, } #[cfg(feature = "Win32_Foundation")] impl STORAGE_FIRMWARE_SLOT_INFO_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for STORAGE_FIRMWARE_SLOT_INFO_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for STORAGE_FIRMWARE_SLOT_INFO_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for STORAGE_FIRMWARE_SLOT_INFO_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for STORAGE_FIRMWARE_SLOT_INFO_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct STORAGE_FIRMWARE_SLOT_INFO_V2 { pub SlotNumber: u8, pub ReadOnly: super::super::Foundation::BOOLEAN, pub Reserved: [u8; 6], pub Revision: [u8; 16], } #[cfg(feature = "Win32_Foundation")] impl STORAGE_FIRMWARE_SLOT_INFO_V2 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for STORAGE_FIRMWARE_SLOT_INFO_V2 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for STORAGE_FIRMWARE_SLOT_INFO_V2 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("STORAGE_FIRMWARE_SLOT_INFO_V2").field("SlotNumber", &self.SlotNumber).field("ReadOnly", &self.ReadOnly).field("Reserved", &self.Reserved).field("Revision", &self.Revision).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for STORAGE_FIRMWARE_SLOT_INFO_V2 { fn eq(&self, other: &Self) -> bool { self.SlotNumber == other.SlotNumber && self.ReadOnly == other.ReadOnly && self.Reserved == other.Reserved && self.Revision == other.Revision } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for STORAGE_FIRMWARE_SLOT_INFO_V2 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for STORAGE_FIRMWARE_SLOT_INFO_V2 { type Abi = Self; } pub const STORAGE_FIRMWARE_SLOT_INFO_V2_REVISION_LENGTH: u32 = 16u32; pub const ScsiRawInterfaceGuid: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x53f56309_b6bf_11d0_94f2_00a0c91efb8b); #[inline] pub unsafe fn SendScsiInquiry(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, lun: u64, evpdcmddt: u8, pagecode: u8, scsistatus: *mut u8, responsesize: *mut u32, responsebuffer: *mut u8, sensesize: *mut u32, sensebuffer: *mut u8) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SendScsiInquiry(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, lun: u64, evpdcmddt: u8, pagecode: u8, scsistatus: *mut u8, responsesize: *mut u32, responsebuffer: *mut u8, sensesize: *mut u32, sensebuffer: *mut u8) -> u32; } ::core::mem::transmute(SendScsiInquiry( ::core::mem::transmute(uniquesessionid), ::core::mem::transmute(lun), ::core::mem::transmute(evpdcmddt), ::core::mem::transmute(pagecode), ::core::mem::transmute(scsistatus), ::core::mem::transmute(responsesize), ::core::mem::transmute(responsebuffer), ::core::mem::transmute(sensesize), ::core::mem::transmute(sensebuffer), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn SendScsiReadCapacity(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, lun: u64, scsistatus: *mut u8, responsesize: *mut u32, responsebuffer: *mut u8, sensesize: *mut u32, sensebuffer: *mut u8) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SendScsiReadCapacity(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, lun: u64, scsistatus: *mut u8, responsesize: *mut u32, responsebuffer: *mut u8, sensesize: *mut u32, sensebuffer: *mut u8) -> u32; } ::core::mem::transmute(SendScsiReadCapacity(::core::mem::transmute(uniquesessionid), ::core::mem::transmute(lun), ::core::mem::transmute(scsistatus), ::core::mem::transmute(responsesize), ::core::mem::transmute(responsebuffer), ::core::mem::transmute(sensesize), ::core::mem::transmute(sensebuffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn SendScsiReportLuns(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, scsistatus: *mut u8, responsesize: *mut u32, responsebuffer: *mut u8, sensesize: *mut u32, sensebuffer: *mut u8) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SendScsiReportLuns(uniquesessionid: *mut ISCSI_UNIQUE_SESSION_ID, scsistatus: *mut u8, responsesize: *mut u32, responsebuffer: *mut u8, sensesize: *mut u32, sensebuffer: *mut u8) -> u32; } ::core::mem::transmute(SendScsiReportLuns(::core::mem::transmute(uniquesessionid), ::core::mem::transmute(scsistatus), ::core::mem::transmute(responsesize), ::core::mem::transmute(responsebuffer), ::core::mem::transmute(sensesize), ::core::mem::transmute(sensebuffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetIScsiGroupPresharedKey<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>>(keylength: u32, key: *mut u8, persist: Param2) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetIScsiGroupPresharedKey(keylength: u32, key: *mut u8, persist: super::super::Foundation::BOOLEAN) -> u32; } ::core::mem::transmute(SetIScsiGroupPresharedKey(::core::mem::transmute(keylength), ::core::mem::transmute(key), persist.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetIScsiIKEInfoA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>>(initiatorname: Param0, initiatorportnumber: u32, authinfo: *mut IKE_AUTHENTICATION_INFORMATION, persist: Param3) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetIScsiIKEInfoA(initiatorname: super::super::Foundation::PSTR, initiatorportnumber: u32, authinfo: *mut IKE_AUTHENTICATION_INFORMATION, persist: super::super::Foundation::BOOLEAN) -> u32; } ::core::mem::transmute(SetIScsiIKEInfoA(initiatorname.into_param().abi(), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(authinfo), persist.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetIScsiIKEInfoW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>>(initiatorname: Param0, initiatorportnumber: u32, authinfo: *mut IKE_AUTHENTICATION_INFORMATION, persist: Param3) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetIScsiIKEInfoW(initiatorname: super::super::Foundation::PWSTR, initiatorportnumber: u32, authinfo: *mut IKE_AUTHENTICATION_INFORMATION, persist: super::super::Foundation::BOOLEAN) -> u32; } ::core::mem::transmute(SetIScsiIKEInfoW(initiatorname.into_param().abi(), ::core::mem::transmute(initiatorportnumber), ::core::mem::transmute(authinfo), persist.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn SetIScsiInitiatorCHAPSharedSecret(sharedsecretlength: u32, sharedsecret: *mut u8) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetIScsiInitiatorCHAPSharedSecret(sharedsecretlength: u32, sharedsecret: *mut u8) -> u32; } ::core::mem::transmute(SetIScsiInitiatorCHAPSharedSecret(::core::mem::transmute(sharedsecretlength), ::core::mem::transmute(sharedsecret))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetIScsiInitiatorNodeNameA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(initiatornodename: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetIScsiInitiatorNodeNameA(initiatornodename: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(SetIScsiInitiatorNodeNameA(initiatornodename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetIScsiInitiatorNodeNameW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(initiatornodename: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetIScsiInitiatorNodeNameW(initiatornodename: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(SetIScsiInitiatorNodeNameW(initiatornodename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn SetIScsiInitiatorRADIUSSharedSecret(sharedsecretlength: u32, sharedsecret: *mut u8) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetIScsiInitiatorRADIUSSharedSecret(sharedsecretlength: u32, sharedsecret: *mut u8) -> u32; } ::core::mem::transmute(SetIScsiInitiatorRADIUSSharedSecret(::core::mem::transmute(sharedsecretlength), ::core::mem::transmute(sharedsecret))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetIScsiTunnelModeOuterAddressA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>>(initiatorname: Param0, initiatorportnumber: u32, destinationaddress: Param2, outermodeaddress: Param3, persist: Param4) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetIScsiTunnelModeOuterAddressA(initiatorname: super::super::Foundation::PSTR, initiatorportnumber: u32, destinationaddress: super::super::Foundation::PSTR, outermodeaddress: super::super::Foundation::PSTR, persist: super::super::Foundation::BOOLEAN) -> u32; } ::core::mem::transmute(SetIScsiTunnelModeOuterAddressA(initiatorname.into_param().abi(), ::core::mem::transmute(initiatorportnumber), destinationaddress.into_param().abi(), outermodeaddress.into_param().abi(), persist.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetIScsiTunnelModeOuterAddressW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::BOOLEAN>>(initiatorname: Param0, initiatorportnumber: u32, destinationaddress: Param2, outermodeaddress: Param3, persist: Param4) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetIScsiTunnelModeOuterAddressW(initiatorname: super::super::Foundation::PWSTR, initiatorportnumber: u32, destinationaddress: super::super::Foundation::PWSTR, outermodeaddress: super::super::Foundation::PWSTR, persist: super::super::Foundation::BOOLEAN) -> u32; } ::core::mem::transmute(SetIScsiTunnelModeOuterAddressW(initiatorname.into_param().abi(), ::core::mem::transmute(initiatorportnumber), destinationaddress.into_param().abi(), outermodeaddress.into_param().abi(), persist.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn SetupPersistentIScsiDevices() -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetupPersistentIScsiDevices() -> u32; } ::core::mem::transmute(SetupPersistentIScsiDevices()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn SetupPersistentIScsiVolumes() -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetupPersistentIScsiVolumes() -> u32; } ::core::mem::transmute(SetupPersistentIScsiVolumes()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct TARGETPROTOCOLTYPE(pub i32); pub const ISCSI_TCP_PROTOCOL_TYPE: TARGETPROTOCOLTYPE = TARGETPROTOCOLTYPE(0i32); impl ::core::convert::From<i32> for TARGETPROTOCOLTYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for TARGETPROTOCOLTYPE { 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 TARGET_INFORMATION_CLASS(pub i32); pub const ProtocolType: TARGET_INFORMATION_CLASS = TARGET_INFORMATION_CLASS(0i32); pub const TargetAlias: TARGET_INFORMATION_CLASS = TARGET_INFORMATION_CLASS(1i32); pub const DiscoveryMechanisms: TARGET_INFORMATION_CLASS = TARGET_INFORMATION_CLASS(2i32); pub const PortalGroups: TARGET_INFORMATION_CLASS = TARGET_INFORMATION_CLASS(3i32); pub const PersistentTargetMappings: TARGET_INFORMATION_CLASS = TARGET_INFORMATION_CLASS(4i32); pub const InitiatorName: TARGET_INFORMATION_CLASS = TARGET_INFORMATION_CLASS(5i32); pub const TargetFlags: TARGET_INFORMATION_CLASS = TARGET_INFORMATION_CLASS(6i32); pub const LoginOptions: TARGET_INFORMATION_CLASS = TARGET_INFORMATION_CLASS(7i32); impl ::core::convert::From<i32> for TARGET_INFORMATION_CLASS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for TARGET_INFORMATION_CLASS { type Abi = Self; } pub const WmiScsiAddressGuid: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x53f5630f_b6bf_11d0_94f2_00a0c91efb8b); #[repr(C)] #[derive(:: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy)] pub struct _ADAPTER_OBJECT(pub u8);
//! Asynchronous ARQ Connections //! //! This module exposes the `ArqStream` type which implements //! `AsyncRead` and `AsyncWrite`. These traits enable access //! to RF connections much as one would use a TCP socket. use std::fmt; use std::future::Future; use std::io; use std::pin::Pin; use std::sync::Arc; use std::time::Duration; use futures::executor; use futures::io::{AsyncRead, AsyncWrite}; use futures::lock::{Mutex, MutexLockFuture}; use futures::task::{Context, Poll}; use super::connectioninfo::ConnectionInfo; use crate::tncio::arqstate::ArqState; use crate::tncio::asynctnc::AsyncTncTcp; /// A TCP-like interface for ARQ RF connections /// /// See the [module-level](index.html) documentation /// for examples and usage details. pub struct ArqStream { tnc: Arc<Mutex<AsyncTncTcp>>, state: ArqState, } impl ArqStream { /// True if the connection was open (at last check) /// /// This method returns `true` if the connection was /// believed to be open during the last I/O operation /// conducted to the ARDOP TNC. /// /// Even if this value returns `true`, the connection /// may be detected as dead during the next read or /// write. pub fn is_open(&self) -> bool { self.state.is_open() } /// True if the connection is disconnecting /// /// This method returns `true` if the local side has /// initiated a disconnect but the disconnect has yet /// to complete. /// /// While the disconnect is "in flight," `is_open()` /// will continue to return true. pub fn is_disconnecting(&self) -> bool { self.state.is_disconnecting() } /// Return connection information /// /// Includes immutable details about the connection, such /// as the local and remote callsigns. pub fn info(&self) -> &ConnectionInfo { self.state.info() } /// Returns total number of bytes received /// /// Counts the total number of *payload* bytes which have /// been transmitted over the air *AND* acknowledged by /// the local station. This value is aggregated over the /// lifetime of the `ArqStream`. pub fn bytes_received(&self) -> u64 { self.state.bytes_received() } /// Total number of bytes successfully transmitted /// /// Counts the total number of *payload* bytes which have /// been transmitted over the air *AND* acknowledged by /// the remote peer. This value is aggregated over the /// lifetime of the `ArqStream`. pub fn bytes_transmitted(&self) -> u64 { self.state.bytes_transmitted() } /// Total number of bytes pending peer acknowledgement /// /// Counts the total number of bytes that have been /// accepted by the local ARDOP TNC but have not yet /// been delivered to the peer. /// /// Bytes accepted by this object become *staged*. Once /// the TNC has accepted responsibility for the bytes, /// they become *unacknowledged*. Once the remote peer /// has acknowledged the data, the bytes become /// *transmitted*. pub fn bytes_unacknowledged(&self) -> u64 { self.state.bytes_unacknowledged() } /// Bytes pending acceptance by the local TNC /// /// Counts the total number of bytes which have been /// accepted by this object internally but have not /// yet been delivered to the TNC for transmission. /// /// Bytes accepted by this object become *staged*. Once /// the TNC has accepted responsibility for the bytes, /// they become *unacknowledged*. Once the remote peer /// has acknowledged the data, the bytes become /// *transmitted*. pub fn bytes_staged(&self) -> u64 { self.state.bytes_staged() } /// Returns total time elapsed while the connection is/was open /// /// Returns the total time, in a monotonic reference frame, /// elapsed between /// 1. the connection being opened; and /// 2. the connection being closed /// If the connection is still open, then (2) is assumed to be /// `now`. /// /// # Return /// Time elapsed since connection was open pub fn elapsed_time(&self) -> Duration { self.state.elapsed_time() } // Create from TNC interface and info about a fresh connection pub(crate) fn new(tnc: Arc<Mutex<AsyncTncTcp>>, info: ConnectionInfo) -> Self { ArqStream { tnc, state: ArqState::new(info), } } } impl AsyncRead for ArqStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let this = self.get_mut(); let mut lock_future: MutexLockFuture<AsyncTncTcp> = this.tnc.lock(); let mut tnc = ready!(Pin::new(&mut lock_future).poll(cx)); let data = tnc.data_stream_sink(); this.state.poll_read(data, cx, buf) } } impl AsyncWrite for ArqStream { fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { let this = self.get_mut(); let mut lock_future: MutexLockFuture<AsyncTncTcp> = this.tnc.lock(); let mut tnc = ready!(Pin::new(&mut lock_future).poll(cx)); let data = tnc.data_stream_sink(); this.state.poll_write(data, cx, buf) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { let this = self.get_mut(); let mut lock_future: MutexLockFuture<AsyncTncTcp> = this.tnc.lock(); let mut tnc = ready!(Pin::new(&mut lock_future).poll(cx)); let data = tnc.data_stream_sink(); this.state.poll_flush(data, cx) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { let this = self.get_mut(); if !this.is_open() { return Poll::Ready(Ok(())); } if !this.is_disconnecting() { this.state.shutdown_write(); } let mut lock_future: MutexLockFuture<AsyncTncTcp> = this.tnc.lock(); let mut tnc = ready!(Pin::new(&mut lock_future).poll(cx)); match ready!(tnc.poll_disconnect(cx)) { Ok(k) => { // disconnect done this.state.shutdown_read(); Poll::Ready(Ok(k)) } Err(e) => { error!( "Unclean disconnect to {}: {}", this.state.info().peer_call(), &e ); this.state.shutdown_read(); Poll::Ready(Err(e)) } } } } impl Drop for ArqStream { fn drop(&mut self) { // if we are already closed, we drop if !self.is_open() { return; } // Mark as closed for writing self.state.shutdown_write(); // This will panic if a LocalPool is being used to // provide the asynchronous runtime. You cannot execute a // LocalPool executor from within another LocalPool executor. // // We recommend the use of either "tokio" or "async_std" // crates to provide your runtime environment. let tncref = self.tnc.clone(); executor::block_on(async move { let mut tnc = tncref.lock().await; let _ = tnc.disconnect().await; }); // Mark as fully disconnected self.state.shutdown_read(); } } impl fmt::Display for ArqStream { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.state.fmt(f) } } impl Unpin for ArqStream {}
use core::fmt; use core::iter::{Iterator, Peekable}; use core::mem; use core::ops::Add; use core::str::Bytes; mod tests; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct ByteIdx(usize); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct ByteLen(usize); #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Span { start: ByteIdx, end: ByteIdx, } impl Span { fn new<T: Into<ByteIdx>>(start: T, end: T) -> Self { Self { start: start.into(), end: end.into(), } } pub(crate) fn dummy() -> Self { Self::new(0, 0) } } impl ByteIdx { /// Returns a span from the current byte index /// to `other`. pub(crate) fn to(self, other: ByteIdx) -> Span { Span { start: self, end: other, } } } impl From<usize> for ByteIdx { fn from(other: usize) -> Self { Self(other) } } impl From<usize> for ByteLen { fn from(other: usize) -> Self { Self(other) } } impl From<ByteIdx> for usize { fn from(other: ByteIdx) -> Self { other.0 } } impl From<ByteLen> for usize { fn from(other: ByteLen) -> Self { other.0 } } impl Add<ByteLen> for ByteIdx { type Output = ByteIdx; fn add(self, rhs: ByteLen) -> Self::Output { ByteIdx(self.0 + rhs.0) } } impl Add<ByteIdx> for ByteIdx { type Output = ByteIdx; fn add(self, rhs: ByteIdx) -> Self::Output { ByteIdx(self.0 + rhs.0) } } impl Add<ByteIdx> for ByteLen { type Output = ByteIdx; fn add(self, rhs: ByteIdx) -> Self::Output { ByteIdx(self.0 + rhs.0) } } impl Add<ByteLen> for ByteLen { type Output = ByteLen; fn add(self, rhs: ByteLen) -> Self::Output { ByteLen(self.0 + rhs.0) } } trait ByteExt { fn is_indicator(self) -> bool; fn is_linebreak(self) -> bool; fn span(self, pos: impl Into<ByteIdx>) -> Span; } impl ByteExt for u8 { fn is_indicator(self) -> bool { match self { b'-' | b'?' | b':' | b',' | b'[' | b']' | b'{' | b'}' | b'#' | b'&' | b'*' | b'!' | b'|' | b'>' | b'\"' | b'\'' | b'%' | b'@' | b'`' => true, _ => false, } } fn is_linebreak(self) -> bool { self == b'\n' || self == b'\r' } fn span(self, pos: impl Into<ByteIdx>) -> Span { let pos = pos.into(); Span { start: ByteIdx(pos.0 - 1), end: pos, } } } trait UsizeExt { fn to(self, other: usize) -> Span; } impl UsizeExt for usize { fn to(self, other: usize) -> Span { ByteIdx(self).to(ByteIdx(other)) } } #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum TokenKind<'a> { Literal(&'a str), Whitespace(usize), Ampersand, Asterisk, Colon, Comma, Dash, Fold, Newline, LeftBrace, LeftBracket, Pipe, Plus, RightBrace, RightBracket, SingleQuote, DoubleQuote, QuestionMark, Dummy, } impl<'a> TokenKind<'a> { #[allow(unused)] pub fn is_indicator(&self) -> bool { use TokenKind::*; matches!( self, Colon | Comma | Dash | LeftBrace | LeftBracket | Pipe | RightBrace | RightBracket | SingleQuote | DoubleQuote | QuestionMark ) } #[allow(unused)] pub fn is_flow_indicator(&self) -> bool { use TokenKind::*; matches!( self, Comma | LeftBracket | LeftBrace | RightBracket | RightBrace ) } } impl<'a> fmt::Display for TokenKind<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use TokenKind::*; write!( f, "{}", match self { Literal(val) => val, Whitespace(..) => "WHITESPACE", Ampersand => "&", Asterisk => "*", Colon => ":", Comma => ",", Dash => "-", Fold => ">", LeftBrace => "{", LeftBracket => "[", Newline => "\n", Pipe => "|", Plus => "+", RightBrace => "}", RightBracket => "]", SingleQuote => r"'", DoubleQuote => r#"""#, QuestionMark => "?", Dummy => "DUMMY", } ) } } impl<'a> Default for TokenKind<'a> { fn default() -> Self { Self::Dummy } } #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Token<'a> { pub(crate) kind: TokenKind<'a>, pub(crate) span: Span, } impl<'a> Default for Token<'a> { fn default() -> Self { Self { kind: TokenKind::Dummy, span: Span::dummy(), } } } impl<'a> Token<'a> { /// Constructs a new token. pub(crate) fn new(kind: TokenKind<'a>, span: Span) -> Self { Self { kind, span } } pub(crate) fn start(&self) -> ByteIdx { self.span.start } pub(crate) fn end(&self) -> ByteIdx { self.span.end } } pub(crate) struct Tokenizer<'a> { source: &'a str, bytes: Peekable<Bytes<'a>>, tokens: Vec<Token<'a>>, idx: usize, current: Option<u8>, } impl<'a> Tokenizer<'a> { pub fn from_str(raw: &'a str) -> Self { let mut bytes = raw.bytes().peekable(); let current = bytes.next(); Self { bytes, source: raw, tokens: Vec::new(), idx: 0, current, } } #[allow(unused)] pub fn new(raw: &'a str) -> Self { Self::from_str(raw) } } struct SourceStr<'a> { slice: &'a str, span: Span, } impl<'a> SourceStr<'a> { pub fn new(slice: &'a str, span: Span) -> Self { Self { slice, span } } } impl<'a> Tokenizer<'a> { /// Returns the next character, if one exists, without advancing /// the source position. #[allow(unused)] fn peek(&mut self) -> Option<u8> { self.bytes.peek().map(|&b| b) } /// Returns the next character, if one exists, and advances /// the source position. fn next(&mut self) -> Option<u8> { self.idx += 1; let next = self.bytes.next(); mem::replace(&mut self.current, next) } /// Advances the source position by one character. Returns `false` /// if the source is exhausted, `true` otherwise. fn advance(&mut self) -> bool { self.next().is_some() } fn consume_whitespace(&mut self) -> Token<'a> { let SourceStr { slice, span } = self.consume_matches(|chr| chr == b' ' || chr == b'\t'); Token::new(TokenKind::Whitespace(slice.len()), span) } fn consume_literal(&mut self) -> Token<'a> { let SourceStr { slice, span } = self.consume_matches(|chr| !(chr.is_indicator() || chr.is_ascii_whitespace())); Token::new(TokenKind::Literal(slice), span) } fn consume_matches(&mut self, matches: impl Fn(u8) -> bool) -> SourceStr<'a> { let tok_start = self.idx - 1; let mut tok_end = tok_start + 1; loop { match self.current { Some(chr) if matches(chr) => { tok_end += 1; self.advance(); } _ => { return SourceStr::new(&self.source[tok_start..tok_end], tok_start.to(tok_end)) } } } } /// Tokenizes the source, consuming the Tokenizer. /// Returns the tokenized source. pub fn tokenize(mut self) -> Vec<Token<'a>> { use TokenKind::*; while let Some(chr) = self.next() { // TODO: Consider preserving comments instead of just throwing them out match chr { b'&' => self.push_tok_with(Ampersand, chr.span(self.idx)), b'*' => self.push_tok_with(Asterisk, chr.span(self.idx)), b':' => self.push_tok_with(Colon, chr.span(self.idx)), b',' => self.push_tok_with(Comma, chr.span(self.idx)), b'-' => self.push_tok_with(Dash, chr.span(self.idx)), b'\"' => self.push_tok_with(DoubleQuote, chr.span(self.idx)), b'>' => self.push_tok_with(Fold, chr.span(self.idx)), b'\n' => self.push_tok_with(Newline, chr.span(self.idx)), b'\r' => { let span = match self.peek() { Some(nc @ b'\n') => { Span::new(chr.span(self.idx).start, nc.span(self.idx + 1).end) } _ => chr.span(self.idx), }; self.push_tok_with(Newline, span); } b'{' => self.push_tok_with(LeftBrace, chr.span(self.idx)), b'[' => self.push_tok_with(LeftBracket, chr.span(self.idx)), b'|' => self.push_tok_with(Pipe, chr.span(self.idx)), b'+' => self.push_tok_with(Plus, chr.span(self.idx)), b'}' => self.push_tok_with(RightBrace, chr.span(self.idx)), b']' => self.push_tok_with(RightBracket, chr.span(self.idx)), b'\'' => self.push_tok_with(SingleQuote, chr.span(self.idx)), b'?' => self.push_tok_with(QuestionMark, chr.span(self.idx)), b'\t' | b' ' => { let tok = self.consume_whitespace(); self.push_tok(tok); if let Some(b'#') = self.current { self.consume_matches(|c| !c.is_linebreak()); } } _ => { if let Token { kind: Literal(slice), span, } = self.consume_literal() { self.push_tok_with(Literal(slice), span); } } } } self.tokens } fn push_tok(&mut self, tok: Token<'a>) { self.tokens.push(tok) } /// Constructs a token and pushes it onto the token stream fn push_tok_with(&mut self, kind: TokenKind<'a>, span: Span) { self.tokens.push(Token::new(kind, span)) } }
use std::str::SplitTerminator; pub trait StrUtils { fn digits(&self) -> Vec<u8>; fn paragraphs(&self) -> SplitTerminator<&str>; } impl StrUtils for str { fn digits(&self) -> Vec<u8> { self.chars().map(|c| c as u8 - 0x30).collect() } fn paragraphs(&self) -> SplitTerminator<&str> { self.split_terminator("\n\n") } }
use proconio::input; fn main() { input! { a:i32, b:i32, } println!("{}", a / b); }
// Copyright 2014-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. use core::{mem, slice}; use types::{BytesOrWideString, c_void}; use libc::{self, Dl_info}; use SymbolName; pub struct Symbol { inner: Dl_info, } impl Symbol { pub fn name(&self) -> Option<SymbolName> { if self.inner.dli_sname.is_null() { None } else { let ptr = self.inner.dli_sname as *const u8; unsafe { let len = libc::strlen(self.inner.dli_sname); Some(SymbolName::new(slice::from_raw_parts(ptr, len))) } } } pub fn addr(&self) -> Option<*mut c_void> { Some(self.inner.dli_saddr as *mut _) } pub fn filename_raw(&self) -> Option<BytesOrWideString> { None } pub fn lineno(&self) -> Option<u32> { None } } pub unsafe fn resolve(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) { let mut info: super::Symbol = super::Symbol { inner: Symbol { inner: mem::zeroed(), }, }; if libc::dladdr(addr as *mut _, &mut info.inner.inner) != 0 { cb(&info) } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} #[repr(transparent)] pub struct AudioRenderCategory(pub i32); impl AudioRenderCategory { pub const Other: Self = Self(0i32); pub const ForegroundOnlyMedia: Self = Self(1i32); pub const BackgroundCapableMedia: Self = Self(2i32); pub const Communications: Self = Self(3i32); pub const Alerts: Self = Self(4i32); pub const SoundEffects: Self = Self(5i32); pub const GameEffects: Self = Self(6i32); pub const GameMedia: Self = Self(7i32); pub const GameChat: Self = Self(8i32); pub const Speech: Self = Self(9i32); pub const Movie: Self = Self(10i32); pub const Media: Self = Self(11i32); } impl ::core::marker::Copy for AudioRenderCategory {} impl ::core::clone::Clone for AudioRenderCategory { fn clone(&self) -> Self { *self } }
mod expand_records; mod expand_substitutions; mod expand_unqualified_calls; use std::collections::BTreeMap; use std::sync::Arc; use firefly_diagnostics::*; use firefly_pass::Pass; use crate::ast; use self::expand_records::ExpandRecords; use self::expand_substitutions::ExpandSubstitutions; use self::expand_unqualified_calls::ExpandUnqualifiedCalls; pub struct CanonicalizeSyntax { #[allow(dead_code)] reporter: Reporter, codemap: Arc<CodeMap>, } impl CanonicalizeSyntax { pub fn new(reporter: Reporter, codemap: Arc<CodeMap>) -> Self { Self { reporter, codemap } } } impl Pass for CanonicalizeSyntax { type Input<'a> = ast::Module; type Output<'a> = ast::Module; fn run<'a>(&mut self, mut module: Self::Input<'a>) -> anyhow::Result<Self::Output<'a>> { let mut functions = BTreeMap::new(); while let Some((key, mut function)) = module.functions.pop_first() { // Prepare function for translation to CST let mut pipeline = ExpandRecords::new(&module) .chain(ExpandUnqualifiedCalls::new(&module)) .chain(ExpandSubstitutions::new(module.name, &self.codemap)); pipeline.run(&mut function)?; functions.insert(key, function); } module.functions = functions; Ok(module) } }
//! Small amethyst demo app to illustrate sprite ordering //! //! Press Space to change the order of the sprites. use amethyst::{ Logger, GameDataBuilder, Application, SimpleState, StateData, GameData, StateEvent, SimpleTrans, Trans, core::{ Transform, TransformBundle, SystemBundle, }, prelude::{ Config, }, ecs::{ DispatcherBuilder, World, Builder, Component, DenseVecStorage, System, ReadStorage, WriteStorage, Join, }, assets::{ Loader, Handle, AssetStorage, }, renderer::{ DisplayConfig, Pipeline, Stage, DrawFlat2D, ColorMask, ALPHA, DepthMode, RenderBundle, VirtualKeyCode, Texture, PngFormat, TextureMetadata, Camera, Projection, Transparent, }, input::{ is_close_requested, is_key_down, }, utils::{ application_root_dir, }, }; /// Main method fn main() -> amethyst::Result<()> { // Disable logging cruft Logger::from_config(Default::default()) .level_for("gfx_device_gl", amethyst::LogLevelFilter::Warn) .level_for("amethyst_renderer", amethyst::LogLevelFilter::Error) .start(); // Set up configuration paths let application_root = application_root_dir()?; let display_config_path = application_root.join("resources/display_config.ron"); let asset_path = application_root.join("assets"); // Load display parameters let display_config = DisplayConfig::load(&display_config_path); // Build pipeline let pipe = Pipeline::build() .with_stage(Stage::with_backbuffer() .clear_target([0.1, 0.1, 0.1, 1.0], 1.0) .with_pass( DrawFlat2D::new() .with_transparency( ColorMask::all(), ALPHA, Some(DepthMode::LessEqualWrite), ) ) ); // Set up the necessary bundles // The sprite visibility sorting for the render bundle // is what's important here. let game_data_builder = GameDataBuilder::default() .with_bundle(TransformBundle::new())? .with_bundle(RenderBundle::new( pipe, Some(display_config)) .with_sprite_visibility_sorting(&[]) )? .with_bundle(GameBundle)? ; // Build the game with our game state let mut game = Application::build( asset_path, GameState::default() )?.build(game_data_builder)?; // Run the game. game.run(); Ok(()) } // =================================================================== // Game Components #[derive(Default)] /// Sprite Order component. struct SpriteOrder { /// Controls which sprite is in front order: i32, } impl Component for SpriteOrder { type Storage = DenseVecStorage<Self>; } impl SpriteOrder { /// push the sprite towards the camera. /// if the order reaches max_order, /// this will push the sprite to the back. fn bump_order(&mut self, max_order: i32) { self.order = (self.order + 1) % max_order; } /// Registers the type with the given world fn register(world: &mut World) { world.register::<Self>(); } } /// Registers all the required components fn register_components(world: &mut World) { SpriteOrder::register(world); } // =================================================================== // Game Resources /// Adds resources to the world fn add_resources(_world: &mut World) { } // =================================================================== // Game Entities /// Adds a background sprite (i.e. no sprite order) fn add_background(world: &mut World) { let path = "sprites/background.png".to_string(); let texture_handle = load_texture_handle(world, &path); world.create_entity() .with(Transform::default()) .with(texture_handle.clone()) .build(); } /// Adds a sprite. /// Key component here is Transparent, /// which informs the sprite ordering system to use z position in displaying this sprite. fn add_sprite(world: &mut World, name: &'static str, order: i32) { let path = format!("sprites/{}.png", name); let texture_handle = load_texture_handle(world, &path); let mut my_transform = Transform::default(); my_transform.set_y((order as f32) * 20.0); // so the sprites don't block each other completely world.create_entity() .with(SpriteOrder{order}) .with(my_transform) .with(texture_handle.clone()) .with(Transparent) // We need to tell Amethyst that this sprite has some transparency element .build(); } /// Adds a camera. /// We set the camera far enough back so we have room in which to order our sprites. fn add_camera(world: &mut World) { let mut transform = Transform::default(); transform.set_z(100.0); // leave room for sprite ordering world.create_entity() .with(Camera::from( Projection::orthographic( -250.0, 250.0, -250.0, 250.0, ))) .with(transform) .build(); } /// Adds all the entities to our world. fn add_entities(world: &mut World) { add_background(world); add_camera(world); add_sprite(world, "Character Cat Girl", 0); add_sprite(world, "Roof North", 1) } // =================================================================== // Game Systems /// A system which updates the z position of a sprite /// based on the value of its order component struct SpriteOrderSystem; impl<'s>System<'s> for SpriteOrderSystem { type SystemData = ( ReadStorage<'s, SpriteOrder>, WriteStorage<'s, Transform>, ); // set the z position of the sprite based on the sprite's order #. fn run(&mut self, (sprite_order_set, mut transforms): Self::SystemData) { for (sprite_order, transform) in (&sprite_order_set, &mut transforms).join() { transform.set_z(sprite_order.order as f32); } } } // =================================================================== // Game Bundle struct GameBundle; impl<'a, 'b>SystemBundle<'a, 'b> for GameBundle { fn build(self, builder: &mut DispatcherBuilder<'a, 'b>) -> amethyst::Result<()> { builder.add(SpriteOrderSystem, "Sprite Order System", &[] ); Ok(()) } } // =================================================================== // Game State #[derive(Default)] struct GameState; impl SimpleState for GameState { fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) { let world = data.world; register_components(world); add_resources(world); add_entities(world); } /// Handles the usual quit event. Also, /// if the user presses the space bar, /// it swaps the order of the sprites. fn handle_event(&mut self, data: StateData<'_, GameData<'_, '_>>, event: StateEvent) -> SimpleTrans{ if let StateEvent::Window(event) = event { if is_close_requested(&event) || is_key_down(&event, VirtualKeyCode::Escape) { return Trans::Quit } else if is_key_down(&event, VirtualKeyCode::Space) { let world = data.world; // Run through the sprite orders and bump them. // This is an example of running a "System" from within an event response. let mut sprite_order_set = world.write_storage::<SpriteOrder>(); for sprite_order in (&mut sprite_order_set).join() { sprite_order.bump_order(2); } return Trans::None } } Trans::None } fn update (&mut self, state_data: &mut StateData<'_, GameData<'_, '_>>) -> SimpleTrans{ state_data.data.update(&state_data.world); Trans::None } } /// Utility to collect code that loads a sprite texture handle. fn load_texture_handle(world: &mut World, path: &String) -> Handle<Texture> { let loader = world.read_resource::<Loader>(); let texture_storage = world.read_resource::<AssetStorage<Texture>>(); loader.load( path.as_ref(), PngFormat, TextureMetadata::srgb_scale(), (), &texture_storage ) }
use std::error::Error; use std::fs::File; use std::io::BufReader; use itertools::Itertools; use crate::seq; use crate::utl; #[derive(Debug)] pub struct Sequence { pub class_name: String, pub codebook_size: u32, pub symbols: Vec<u16>, } impl Sequence { pub fn show(&mut self, opts: &seq::SeqShowOpts) { if opts.no_sequence { return; } if opts.only_length { println!("{}", self.symbols.len()); return; } let symbols_to_show = if opts.full || self.symbols.len() <= 30 { self.symbols.iter().join(", ") } else { let v = self.symbols[..10].to_vec(); let w = self.symbols[self.symbols.len() - 10..].to_vec(); format!( "{}{}{}", v.iter().join(", "), ", ..., ", w.iter().join(", ") ) }; println!( "<{}(M={},L={}): {}>", self.class_name, self.codebook_size, self.symbols.len(), symbols_to_show, ); } } pub fn load(filename: &str) -> Result<Sequence, Box<dyn Error>> { let f = File::open(filename)?; let mut br = BufReader::new(f); let ident = utl::read_file_ident(&mut br)?; if !ident.starts_with("<sequence>") { return Err(format!("{}: Not a sequence", filename)).unwrap(); } let class_name: String = utl::read_class_name(&mut br)?; let len = utl::read_u32(&mut br)?; let codebook_size = utl::read_u32(&mut br)?; let mut symbols: Vec<u16> = Vec::new(); for _ in 0..len { symbols.push(utl::read_u16(&mut br)?); } Ok(Sequence { class_name, codebook_size, symbols, }) }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::ACCTL1 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct COMP_ACCTL1_CINVR { bits: bool, } impl COMP_ACCTL1_CINVR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _COMP_ACCTL1_CINVW<'a> { w: &'a mut W, } impl<'a> _COMP_ACCTL1_CINVW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = "Possible values of the field `COMP_ACCTL1_ISEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP_ACCTL1_ISENR { #[doc = "Level sense, see ISLVAL"] COMP_ACCTL1_ISEN_LEVEL, #[doc = "Falling edge"] COMP_ACCTL1_ISEN_FALL, #[doc = "Rising edge"] COMP_ACCTL1_ISEN_RISE, #[doc = "Either edge"] COMP_ACCTL1_ISEN_BOTH, } impl COMP_ACCTL1_ISENR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { COMP_ACCTL1_ISENR::COMP_ACCTL1_ISEN_LEVEL => 0, COMP_ACCTL1_ISENR::COMP_ACCTL1_ISEN_FALL => 1, COMP_ACCTL1_ISENR::COMP_ACCTL1_ISEN_RISE => 2, COMP_ACCTL1_ISENR::COMP_ACCTL1_ISEN_BOTH => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> COMP_ACCTL1_ISENR { match value { 0 => COMP_ACCTL1_ISENR::COMP_ACCTL1_ISEN_LEVEL, 1 => COMP_ACCTL1_ISENR::COMP_ACCTL1_ISEN_FALL, 2 => COMP_ACCTL1_ISENR::COMP_ACCTL1_ISEN_RISE, 3 => COMP_ACCTL1_ISENR::COMP_ACCTL1_ISEN_BOTH, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `COMP_ACCTL1_ISEN_LEVEL`"] #[inline(always)] pub fn is_comp_acctl1_isen_level(&self) -> bool { *self == COMP_ACCTL1_ISENR::COMP_ACCTL1_ISEN_LEVEL } #[doc = "Checks if the value of the field is `COMP_ACCTL1_ISEN_FALL`"] #[inline(always)] pub fn is_comp_acctl1_isen_fall(&self) -> bool { *self == COMP_ACCTL1_ISENR::COMP_ACCTL1_ISEN_FALL } #[doc = "Checks if the value of the field is `COMP_ACCTL1_ISEN_RISE`"] #[inline(always)] pub fn is_comp_acctl1_isen_rise(&self) -> bool { *self == COMP_ACCTL1_ISENR::COMP_ACCTL1_ISEN_RISE } #[doc = "Checks if the value of the field is `COMP_ACCTL1_ISEN_BOTH`"] #[inline(always)] pub fn is_comp_acctl1_isen_both(&self) -> bool { *self == COMP_ACCTL1_ISENR::COMP_ACCTL1_ISEN_BOTH } } #[doc = "Values that can be written to the field `COMP_ACCTL1_ISEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP_ACCTL1_ISENW { #[doc = "Level sense, see ISLVAL"] COMP_ACCTL1_ISEN_LEVEL, #[doc = "Falling edge"] COMP_ACCTL1_ISEN_FALL, #[doc = "Rising edge"] COMP_ACCTL1_ISEN_RISE, #[doc = "Either edge"] COMP_ACCTL1_ISEN_BOTH, } impl COMP_ACCTL1_ISENW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { COMP_ACCTL1_ISENW::COMP_ACCTL1_ISEN_LEVEL => 0, COMP_ACCTL1_ISENW::COMP_ACCTL1_ISEN_FALL => 1, COMP_ACCTL1_ISENW::COMP_ACCTL1_ISEN_RISE => 2, COMP_ACCTL1_ISENW::COMP_ACCTL1_ISEN_BOTH => 3, } } } #[doc = r"Proxy"] pub struct _COMP_ACCTL1_ISENW<'a> { w: &'a mut W, } impl<'a> _COMP_ACCTL1_ISENW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: COMP_ACCTL1_ISENW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Level sense, see ISLVAL"] #[inline(always)] pub fn comp_acctl1_isen_level(self) -> &'a mut W { self.variant(COMP_ACCTL1_ISENW::COMP_ACCTL1_ISEN_LEVEL) } #[doc = "Falling edge"] #[inline(always)] pub fn comp_acctl1_isen_fall(self) -> &'a mut W { self.variant(COMP_ACCTL1_ISENW::COMP_ACCTL1_ISEN_FALL) } #[doc = "Rising edge"] #[inline(always)] pub fn comp_acctl1_isen_rise(self) -> &'a mut W { self.variant(COMP_ACCTL1_ISENW::COMP_ACCTL1_ISEN_RISE) } #[doc = "Either edge"] #[inline(always)] pub fn comp_acctl1_isen_both(self) -> &'a mut W { self.variant(COMP_ACCTL1_ISENW::COMP_ACCTL1_ISEN_BOTH) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 2); self.w.bits |= ((value as u32) & 3) << 2; self.w } } #[doc = r"Value of the field"] pub struct COMP_ACCTL1_ISLVALR { bits: bool, } impl COMP_ACCTL1_ISLVALR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _COMP_ACCTL1_ISLVALW<'a> { w: &'a mut W, } impl<'a> _COMP_ACCTL1_ISLVALW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = "Possible values of the field `COMP_ACCTL1_TSEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP_ACCTL1_TSENR { #[doc = "Level sense, see TSLVAL"] COMP_ACCTL1_TSEN_LEVEL, #[doc = "Falling edge"] COMP_ACCTL1_TSEN_FALL, #[doc = "Rising edge"] COMP_ACCTL1_TSEN_RISE, #[doc = "Either edge"] COMP_ACCTL1_TSEN_BOTH, } impl COMP_ACCTL1_TSENR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { COMP_ACCTL1_TSENR::COMP_ACCTL1_TSEN_LEVEL => 0, COMP_ACCTL1_TSENR::COMP_ACCTL1_TSEN_FALL => 1, COMP_ACCTL1_TSENR::COMP_ACCTL1_TSEN_RISE => 2, COMP_ACCTL1_TSENR::COMP_ACCTL1_TSEN_BOTH => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> COMP_ACCTL1_TSENR { match value { 0 => COMP_ACCTL1_TSENR::COMP_ACCTL1_TSEN_LEVEL, 1 => COMP_ACCTL1_TSENR::COMP_ACCTL1_TSEN_FALL, 2 => COMP_ACCTL1_TSENR::COMP_ACCTL1_TSEN_RISE, 3 => COMP_ACCTL1_TSENR::COMP_ACCTL1_TSEN_BOTH, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `COMP_ACCTL1_TSEN_LEVEL`"] #[inline(always)] pub fn is_comp_acctl1_tsen_level(&self) -> bool { *self == COMP_ACCTL1_TSENR::COMP_ACCTL1_TSEN_LEVEL } #[doc = "Checks if the value of the field is `COMP_ACCTL1_TSEN_FALL`"] #[inline(always)] pub fn is_comp_acctl1_tsen_fall(&self) -> bool { *self == COMP_ACCTL1_TSENR::COMP_ACCTL1_TSEN_FALL } #[doc = "Checks if the value of the field is `COMP_ACCTL1_TSEN_RISE`"] #[inline(always)] pub fn is_comp_acctl1_tsen_rise(&self) -> bool { *self == COMP_ACCTL1_TSENR::COMP_ACCTL1_TSEN_RISE } #[doc = "Checks if the value of the field is `COMP_ACCTL1_TSEN_BOTH`"] #[inline(always)] pub fn is_comp_acctl1_tsen_both(&self) -> bool { *self == COMP_ACCTL1_TSENR::COMP_ACCTL1_TSEN_BOTH } } #[doc = "Values that can be written to the field `COMP_ACCTL1_TSEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP_ACCTL1_TSENW { #[doc = "Level sense, see TSLVAL"] COMP_ACCTL1_TSEN_LEVEL, #[doc = "Falling edge"] COMP_ACCTL1_TSEN_FALL, #[doc = "Rising edge"] COMP_ACCTL1_TSEN_RISE, #[doc = "Either edge"] COMP_ACCTL1_TSEN_BOTH, } impl COMP_ACCTL1_TSENW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { COMP_ACCTL1_TSENW::COMP_ACCTL1_TSEN_LEVEL => 0, COMP_ACCTL1_TSENW::COMP_ACCTL1_TSEN_FALL => 1, COMP_ACCTL1_TSENW::COMP_ACCTL1_TSEN_RISE => 2, COMP_ACCTL1_TSENW::COMP_ACCTL1_TSEN_BOTH => 3, } } } #[doc = r"Proxy"] pub struct _COMP_ACCTL1_TSENW<'a> { w: &'a mut W, } impl<'a> _COMP_ACCTL1_TSENW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: COMP_ACCTL1_TSENW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Level sense, see TSLVAL"] #[inline(always)] pub fn comp_acctl1_tsen_level(self) -> &'a mut W { self.variant(COMP_ACCTL1_TSENW::COMP_ACCTL1_TSEN_LEVEL) } #[doc = "Falling edge"] #[inline(always)] pub fn comp_acctl1_tsen_fall(self) -> &'a mut W { self.variant(COMP_ACCTL1_TSENW::COMP_ACCTL1_TSEN_FALL) } #[doc = "Rising edge"] #[inline(always)] pub fn comp_acctl1_tsen_rise(self) -> &'a mut W { self.variant(COMP_ACCTL1_TSENW::COMP_ACCTL1_TSEN_RISE) } #[doc = "Either edge"] #[inline(always)] pub fn comp_acctl1_tsen_both(self) -> &'a mut W { self.variant(COMP_ACCTL1_TSENW::COMP_ACCTL1_TSEN_BOTH) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 5); self.w.bits |= ((value as u32) & 3) << 5; self.w } } #[doc = r"Value of the field"] pub struct COMP_ACCTL1_TSLVALR { bits: bool, } impl COMP_ACCTL1_TSLVALR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _COMP_ACCTL1_TSLVALW<'a> { w: &'a mut W, } impl<'a> _COMP_ACCTL1_TSLVALW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 7); self.w.bits |= ((value as u32) & 1) << 7; self.w } } #[doc = "Possible values of the field `COMP_ACCTL1_ASRCP`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP_ACCTL1_ASRCPR { #[doc = "Pin value of Cn+"] COMP_ACCTL1_ASRCP_PIN, #[doc = "Pin value of C0+"] COMP_ACCTL1_ASRCP_PIN0, #[doc = "Internal voltage reference"] COMP_ACCTL1_ASRCP_REF, #[doc = r"Reserved"] _Reserved(u8), } impl COMP_ACCTL1_ASRCPR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { COMP_ACCTL1_ASRCPR::COMP_ACCTL1_ASRCP_PIN => 0, COMP_ACCTL1_ASRCPR::COMP_ACCTL1_ASRCP_PIN0 => 1, COMP_ACCTL1_ASRCPR::COMP_ACCTL1_ASRCP_REF => 2, COMP_ACCTL1_ASRCPR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> COMP_ACCTL1_ASRCPR { match value { 0 => COMP_ACCTL1_ASRCPR::COMP_ACCTL1_ASRCP_PIN, 1 => COMP_ACCTL1_ASRCPR::COMP_ACCTL1_ASRCP_PIN0, 2 => COMP_ACCTL1_ASRCPR::COMP_ACCTL1_ASRCP_REF, i => COMP_ACCTL1_ASRCPR::_Reserved(i), } } #[doc = "Checks if the value of the field is `COMP_ACCTL1_ASRCP_PIN`"] #[inline(always)] pub fn is_comp_acctl1_asrcp_pin(&self) -> bool { *self == COMP_ACCTL1_ASRCPR::COMP_ACCTL1_ASRCP_PIN } #[doc = "Checks if the value of the field is `COMP_ACCTL1_ASRCP_PIN0`"] #[inline(always)] pub fn is_comp_acctl1_asrcp_pin0(&self) -> bool { *self == COMP_ACCTL1_ASRCPR::COMP_ACCTL1_ASRCP_PIN0 } #[doc = "Checks if the value of the field is `COMP_ACCTL1_ASRCP_REF`"] #[inline(always)] pub fn is_comp_acctl1_asrcp_ref(&self) -> bool { *self == COMP_ACCTL1_ASRCPR::COMP_ACCTL1_ASRCP_REF } } #[doc = "Values that can be written to the field `COMP_ACCTL1_ASRCP`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum COMP_ACCTL1_ASRCPW { #[doc = "Pin value of Cn+"] COMP_ACCTL1_ASRCP_PIN, #[doc = "Pin value of C0+"] COMP_ACCTL1_ASRCP_PIN0, #[doc = "Internal voltage reference"] COMP_ACCTL1_ASRCP_REF, } impl COMP_ACCTL1_ASRCPW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { COMP_ACCTL1_ASRCPW::COMP_ACCTL1_ASRCP_PIN => 0, COMP_ACCTL1_ASRCPW::COMP_ACCTL1_ASRCP_PIN0 => 1, COMP_ACCTL1_ASRCPW::COMP_ACCTL1_ASRCP_REF => 2, } } } #[doc = r"Proxy"] pub struct _COMP_ACCTL1_ASRCPW<'a> { w: &'a mut W, } impl<'a> _COMP_ACCTL1_ASRCPW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: COMP_ACCTL1_ASRCPW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Pin value of Cn+"] #[inline(always)] pub fn comp_acctl1_asrcp_pin(self) -> &'a mut W { self.variant(COMP_ACCTL1_ASRCPW::COMP_ACCTL1_ASRCP_PIN) } #[doc = "Pin value of C0+"] #[inline(always)] pub fn comp_acctl1_asrcp_pin0(self) -> &'a mut W { self.variant(COMP_ACCTL1_ASRCPW::COMP_ACCTL1_ASRCP_PIN0) } #[doc = "Internal voltage reference"] #[inline(always)] pub fn comp_acctl1_asrcp_ref(self) -> &'a mut W { self.variant(COMP_ACCTL1_ASRCPW::COMP_ACCTL1_ASRCP_REF) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 9); self.w.bits |= ((value as u32) & 3) << 9; self.w } } #[doc = r"Value of the field"] pub struct COMP_ACCTL1_TOENR { bits: bool, } impl COMP_ACCTL1_TOENR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _COMP_ACCTL1_TOENW<'a> { w: &'a mut W, } impl<'a> _COMP_ACCTL1_TOENW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 11); self.w.bits |= ((value as u32) & 1) << 11; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 1 - Comparator Output Invert"] #[inline(always)] pub fn comp_acctl1_cinv(&self) -> COMP_ACCTL1_CINVR { let bits = ((self.bits >> 1) & 1) != 0; COMP_ACCTL1_CINVR { bits } } #[doc = "Bits 2:3 - Interrupt Sense"] #[inline(always)] pub fn comp_acctl1_isen(&self) -> COMP_ACCTL1_ISENR { COMP_ACCTL1_ISENR::_from(((self.bits >> 2) & 3) as u8) } #[doc = "Bit 4 - Interrupt Sense Level Value"] #[inline(always)] pub fn comp_acctl1_islval(&self) -> COMP_ACCTL1_ISLVALR { let bits = ((self.bits >> 4) & 1) != 0; COMP_ACCTL1_ISLVALR { bits } } #[doc = "Bits 5:6 - Trigger Sense"] #[inline(always)] pub fn comp_acctl1_tsen(&self) -> COMP_ACCTL1_TSENR { COMP_ACCTL1_TSENR::_from(((self.bits >> 5) & 3) as u8) } #[doc = "Bit 7 - Trigger Sense Level Value"] #[inline(always)] pub fn comp_acctl1_tslval(&self) -> COMP_ACCTL1_TSLVALR { let bits = ((self.bits >> 7) & 1) != 0; COMP_ACCTL1_TSLVALR { bits } } #[doc = "Bits 9:10 - Analog Source Positive"] #[inline(always)] pub fn comp_acctl1_asrcp(&self) -> COMP_ACCTL1_ASRCPR { COMP_ACCTL1_ASRCPR::_from(((self.bits >> 9) & 3) as u8) } #[doc = "Bit 11 - Trigger Output Enable"] #[inline(always)] pub fn comp_acctl1_toen(&self) -> COMP_ACCTL1_TOENR { let bits = ((self.bits >> 11) & 1) != 0; COMP_ACCTL1_TOENR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 1 - Comparator Output Invert"] #[inline(always)] pub fn comp_acctl1_cinv(&mut self) -> _COMP_ACCTL1_CINVW { _COMP_ACCTL1_CINVW { w: self } } #[doc = "Bits 2:3 - Interrupt Sense"] #[inline(always)] pub fn comp_acctl1_isen(&mut self) -> _COMP_ACCTL1_ISENW { _COMP_ACCTL1_ISENW { w: self } } #[doc = "Bit 4 - Interrupt Sense Level Value"] #[inline(always)] pub fn comp_acctl1_islval(&mut self) -> _COMP_ACCTL1_ISLVALW { _COMP_ACCTL1_ISLVALW { w: self } } #[doc = "Bits 5:6 - Trigger Sense"] #[inline(always)] pub fn comp_acctl1_tsen(&mut self) -> _COMP_ACCTL1_TSENW { _COMP_ACCTL1_TSENW { w: self } } #[doc = "Bit 7 - Trigger Sense Level Value"] #[inline(always)] pub fn comp_acctl1_tslval(&mut self) -> _COMP_ACCTL1_TSLVALW { _COMP_ACCTL1_TSLVALW { w: self } } #[doc = "Bits 9:10 - Analog Source Positive"] #[inline(always)] pub fn comp_acctl1_asrcp(&mut self) -> _COMP_ACCTL1_ASRCPW { _COMP_ACCTL1_ASRCPW { w: self } } #[doc = "Bit 11 - Trigger Output Enable"] #[inline(always)] pub fn comp_acctl1_toen(&mut self) -> _COMP_ACCTL1_TOENW { _COMP_ACCTL1_TOENW { w: self } } }
use binary_search::BinarySearch; use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let mut g = vec![vec![]; n]; for i in 1..n { let p: usize = rd.get(); g[p - 1].push(i); } let mut depth = vec![0; n]; let mut in_time = vec![0; n]; let mut out_time = vec![0; n]; { let mut timer = 0; dfs(0, &g, &mut depth, &mut timer, &mut in_time, &mut out_time); } let mut a = vec![vec![]; n]; for i in 0..n { a[depth[i]].push(in_time[i]); } for d in 0..n { a[d].sort(); } let q: usize = rd.get(); for _ in 0..q { let u: usize = rd.get(); let d: usize = rd.get(); let u = u - 1; let (in_t, out_t) = (in_time[u], out_time[u]); if a[d].is_empty() { println!("0"); continue; } let ans = a[d].lower_bound(&out_t) - a[d].lower_bound(&in_t); println!("{}", ans); } } fn dfs( i: usize, g: &Vec<Vec<usize>>, depth: &mut Vec<usize>, timer: &mut usize, in_time: &mut Vec<usize>, out_time: &mut Vec<usize>, ) { in_time[i] = *timer; *timer += 1; for &j in &g[i] { depth[j] = depth[i] + 1; dfs(j, g, depth, timer, in_time, out_time); } out_time[i] = *timer; *timer += 1; }
extern crate regex; use std::io; use std::fs; use std::io::BufRead; use std::path::Path; use std::collections::HashMap; use regex::Regex; use std::ops::RangeInclusive; fn main() { let input = parse_input(); let invalid_sum: usize = input.other_tickets.iter().map(|ticket| { ticket.values.iter().filter(|v| !input.is_valid_value(v)).sum::<usize>() }).sum(); println!("Invalid sum = {}", invalid_sum); let valid_tickets: Vec<_> = input.other_tickets.iter().filter(|ticket| { ticket.values.iter().all(|v| input.is_valid_value(v)) }).collect(); let mut index_to_values: HashMap<usize, Vec<_>> = HashMap::new(); valid_tickets.iter().for_each(|ticket| { ticket.values.iter().enumerate().for_each(|(i, val)| { if index_to_values.contains_key(&i) { index_to_values.get_mut(&i).unwrap().push(val); } else { index_to_values.insert(i, vec![val]); } }); }); let mut rules = input.rules; let mut name_to_index: HashMap<_, _> = HashMap::new(); while rules.len() > 0 { let mut solved_indexes = HashMap::new(); index_to_values.iter().for_each(|(index, values)| { let mut candidates: Vec<_> = rules.iter().filter(|(_, rule)| { values.iter().all(|v| rule.is_valid_value(v)) }).map(|(name, _)| name).collect(); if candidates.len() == 1 { let name = candidates.pop().unwrap(); solved_indexes.insert(index, name.to_string()); } }); if solved_indexes.len() == 0 { eprintln!("Couldn't solve any more!"); eprintln!("Remaining rules: {:?}", rules); panic!("Stopping"); } else { solved_indexes.iter().for_each(|(index, name)| { rules.remove(name); name_to_index.insert(name.to_string(), **index); }); } } let my_ticket = input.my_ticket; println!("Index to rule {:?}", name_to_index); println!("My ticket: {:?}", my_ticket.values); let product = name_to_index.iter().filter(|(name, _)| { &name[..2] == "de" }).map(|(_, index)| { my_ticket.values[*index] }).fold(1, |acc, num| acc * num ); println!("{}", product); } struct InputData { rules: HashMap<String, Rule>, my_ticket: Ticket, other_tickets: Vec<Ticket>, } #[derive(Debug)] struct Rule { range1: RangeInclusive<usize>, range2: RangeInclusive<usize>, } impl Rule { fn is_valid_value(&self, value: &usize) -> bool { self.range1.contains(value) || self.range2.contains(value) } } impl InputData { fn is_valid_value(&self, value: &usize) -> bool { self.rules.values().any(|rule| rule.is_valid_value(value)) } } struct Ticket { values: Vec<usize>, } #[derive(Debug, Clone, Copy)] enum ParseState { Rules, MyTicket, OtherTickets } fn parse_input() -> InputData { let io_result = lines_in_file("inputs/day16.txt"); let rule_regex = Regex::new(r"^(?P<name>[^:]+): (?P<min1>\d+)-(?P<max1>\d+) or (?P<min2>\d+)-(?P<max2>\d+)$").unwrap(); match io_result { Ok(lines) => { let mut rules = HashMap::new(); let mut parse_state = ParseState::Rules; let mut my_ticket = None; let mut tickets = vec![]; lines.for_each(|line| match line { Ok(stuff) => { match (parse_state, &stuff[..]) { (ParseState::Rules, "") => { parse_state = ParseState::MyTicket; } (ParseState::MyTicket, "") => { parse_state = ParseState::OtherTickets } (ParseState::Rules, _) => { let captures = rule_regex.captures(&stuff).unwrap(); let name = captures.name("name").unwrap().as_str().to_string(); let min1 = captures.name("min1").unwrap().as_str().parse().unwrap(); let max1 = captures.name("max1").unwrap().as_str().parse().unwrap(); let min2 = captures.name("min2").unwrap().as_str().parse().unwrap(); let max2 = captures.name("max2").unwrap().as_str().parse().unwrap(); rules.insert(name, Rule { range1: min1..=max1, range2: min2..=max2, }); } (ParseState::MyTicket, _) => { if stuff.chars().nth(0).unwrap() == 'y' { } else { my_ticket = Some(parse_ticket(&stuff)); parse_state = ParseState::OtherTickets; } } (ParseState::OtherTickets, _) => { match stuff.chars().nth(0) { None => {} Some('n') => {} _ => { tickets.push(parse_ticket(&stuff)); } } } } } Err(_) => panic!("Error reading line"), }); match my_ticket { None => panic!("Couldn't find my ticket"), Some(t) => InputData { rules: rules, my_ticket: t, other_tickets: tickets, } } }, Err(_) => panic!("Error reading file"), } } fn parse_ticket(line: &str) -> Ticket { Ticket { values: line.split(",").map(|s| s.parse().unwrap()).collect() } } fn lines_in_file<P>(file_path: P) -> io::Result<io::Lines<io::BufReader<fs::File>>> where P: AsRef<Path> { let file = fs::File::open(file_path)?; Ok(io::BufReader::new(file).lines()) }
use std::{convert::TryFrom, fmt, ops}; use crate::util::{floats_equal, round, round_stp, round_tp}; use super::WorldCoords; const TILE_POSITION_PRECISION: usize = 8; #[derive(Clone)] pub struct TilePosition { pub x: u32, pub y: u32, // Offset from Tile Lower Left pub rel_x: f32, pub rel_y: f32, } impl PartialEq for TilePosition { fn eq(&self, other: &Self) -> bool { self.x == other.x && self.y == other.y && floats_equal(self.rel_x, other.rel_x) && floats_equal(self.rel_y, other.rel_y) } } #[derive(Clone)] pub struct SignedTilePosition { pub x: i64, pub y: i64, pub rel_x: f32, pub rel_y: f32, } impl PartialEq for SignedTilePosition { fn eq(&self, other: &Self) -> bool { self.x == other.x && self.y == other.y && floats_equal(self.rel_x, other.rel_x) && floats_equal(self.rel_y, other.rel_y) } } impl TilePosition { #[must_use] pub fn new(x: u32, y: u32, rel_x: f32, rel_y: f32) -> Self { Self { x, y, rel_x: round(rel_x, TILE_POSITION_PRECISION), rel_y: round(rel_y, TILE_POSITION_PRECISION), } } pub fn distance_global<'a, T>(&self, other: T, tile_size: f32) -> f32 where T: Into<&'a Self>, { self.to_world_coords(tile_size) .distance(&other.into().to_world_coords(tile_size)) } pub fn distance_relative<'a, T>(&self, other: T) -> f32 where T: Into<&'a Self>, { let (dx, dy) = self.delta_to(other.into()); dx.hypot(dy) } pub fn is_same_tile<'a, T>(&self, other: T) -> bool where T: Into<&'a Self>, { let other = other.into(); self.x == other.x && self.y == other.y } fn axes(&self) -> (f32, f32) { #[allow(clippy::cast_precision_loss)] (self.x as f32 + self.rel_x, self.y as f32 + self.rel_y) } fn delta_to(&self, target: &Self) -> (f32, f32) { let (x1, y1) = self.axes(); let (x2, y2) = target.axes(); (x2 - x1, y2 - y1) } fn to_world_coords(&self, tile_size: f32) -> WorldCoords { WorldCoords::from_tile_position(self, tile_size) } } impl SignedTilePosition { pub fn new(x: i64, y: i64, rel_x: f32, rel_y: f32) -> Self { Self { x, y, rel_x: round(rel_x, TILE_POSITION_PRECISION), rel_y: round(rel_y, TILE_POSITION_PRECISION), } } pub fn normalized(self, tile_size: f32) -> Self { let dts = 2.0 * tile_size; let Self { x, y, rel_x, rel_y } = self; debug_assert!(-dts < rel_x && rel_x < dts); debug_assert!(-dts < rel_y && rel_y < dts); #[allow(clippy::clippy::cast_precision_loss)] // pub const MAX: f32 = 3.40282347e+38_f32 WorldCoords::new(x as f32 + rel_x, y as f32 + rel_y, tile_size).to_signed_tile_position() } } impl From<TilePosition> for SignedTilePosition { fn from(tp: TilePosition) -> Self { Self { x: i64::from(tp.x), y: i64::from(tp.y), rel_x: tp.rel_x, rel_y: tp.rel_y, } } } impl TryFrom<SignedTilePosition> for TilePosition { type Error = String; #[allow( clippy::clippy::cast_sign_loss, clippy::cast_precision_loss, clippy::clippy::cast_possible_truncation )] fn try_from(stp: SignedTilePosition) -> Result<Self, Self::Error> { if stp.x >= 0 && (stp.x as f64 + f64::from(stp.rel_x)) >= 0.0 && stp.y >= 0 && (stp.y as f64 + f64::from(stp.rel_y)) >= 0.0 { Ok(Self { x: stp.x as u32, y: stp.y as u32, rel_x: stp.rel_x, rel_y: stp.rel_y, }) } else { Err("Tile Position is off grid, cannot convert".to_string()) } } } impl fmt::Debug for SignedTilePosition { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let p = 3; if cfg!(any(feature = "test", test)) { let tp = round_stp(self); write!( f, "(({}, {:.*}), ({}, {:.*})).into()", tp.x, p, tp.rel_x, tp.y, p, tp.rel_y, ) } else { write!( f, "SignedTilePosition x: {}, rel_x: {:.*}), y: {}, rel_y: {:.*}", self.x, p, self.rel_x, self.y, p, self.rel_y ) } } } impl fmt::Debug for TilePosition { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let p = 3; if cfg!(any(feature = "test", test)) { let tp = round_tp(self); write!( f, "(({}, {:.*}), ({}, {:.*})).into()", tp.x, p, tp.rel_x, tp.y, p, tp.rel_y, ) } else { write!( f, "TilePosition {{ x: {}, rel_x: {:.*}, y: {}, rel_y: {:.*} }}", self.x, p, self.rel_x, self.y, p, self.rel_y ) } } } impl ops::Sub<&TilePosition> for &TilePosition { type Output = SignedTilePosition; #[allow(clippy::integer_arithmetic)] fn sub(self, rhs: &TilePosition) -> Self::Output { let dx = i64::from(self.x) - i64::from(rhs.x); let dy = i64::from(self.y) - i64::from(rhs.y); let rel_x = self.rel_x - rhs.rel_x; let rel_y = self.rel_y - rhs.rel_y; SignedTilePosition::new(dx, dy, rel_x, rel_y) } } impl ops::Sub<TilePosition> for TilePosition { type Output = SignedTilePosition; fn sub(self, rhs: Self) -> Self::Output { &self - &rhs } } impl ops::Add<&SignedTilePosition> for &TilePosition { type Output = SignedTilePosition; #[allow(clippy::integer_arithmetic)] fn add(self, rhs: &SignedTilePosition) -> Self::Output { let dx = i64::from(self.x) + rhs.x; let dy = i64::from(self.y) + rhs.y; let rel_x = self.rel_x + rhs.rel_x; let rel_y = self.rel_y + rhs.rel_y; SignedTilePosition::new(dx, dy, rel_x, rel_y) } } impl ops::Add<SignedTilePosition> for TilePosition { type Output = SignedTilePosition; fn add(self, rhs: SignedTilePosition) -> Self::Output { &self + &rhs } } #[cfg(test)] impl From<((i64, f32), (i64, f32))> for SignedTilePosition { fn from(((x, rel_x), (y, rel_y)): ((i64, f32), (i64, f32))) -> Self { Self::new(x, y, rel_x, rel_y) } } impl From<((u32, f32), (u32, f32))> for TilePosition { fn from(((x, rel_x), (y, rel_y)): ((u32, f32), (u32, f32))) -> Self { Self::new(x, y, rel_x, rel_y) } } #[cfg(test)] mod tests { use super::*; #[test] fn subtract() { #[rustfmt::skip] assert_eq!( TilePosition::new(2, 3, 0.0, 0.0) - TilePosition::new(1, 4, 0.0, 0.0), SignedTilePosition::new(1, -1, 0.0, 0.0) ); #[rustfmt::skip] assert_eq!( TilePosition::new(1, 1, 0.5, 0.2) - TilePosition::new(1, 4, 1.0, 0.1), SignedTilePosition::new(0, -3, -0.5, 0.1) ); } #[test] fn distance() { let tp1: TilePosition = ((1, 0.0), (3, 0.3)).into(); let tp2: TilePosition = ((4, 0.1), (8, 0.8)).into(); assert_eq!(round(tp1.distance_global(&tp2, 1.0), 3), 6.313); } }
// 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::{capability::*, model::*}, by_addr::ByAddr, cm_rust::ComponentDecl, futures::{future::BoxFuture, lock::Mutex}, std::{ collections::HashMap, sync::{Arc, Weak}, }, }; #[derive(Debug, Eq, PartialEq, Hash)] pub enum EventType { // Keep the event types listed below in alphabetical order! AddDynamicChild, BindInstance, PostDestroyInstance, PreDestroyInstance, RouteBuiltinCapability, RouteFrameworkCapability, StopInstance, } /// The component manager calls out to objects that implement the `Hook` trait on registered /// component manager events. Hooks block the flow of a task, and can mutate, decorate and replace /// capabilities. This permits `Hook` to serve as a point of extensibility for the component /// manager. pub trait Hook: Send + Sync { fn on<'a>(self: Arc<Self>, event: &'a Event) -> BoxFuture<'a, Result<(), ModelError>>; } /// An object registers a hook into a component manager event via a `HookRegistration` object. /// A single object may register for multiple events through a vector of `HookRegistration` /// objects. pub struct HookRegistration { pub event_type: EventType, pub callback: Arc<dyn Hook>, } #[derive(Clone)] pub enum Event { // Keep the events listed below in alphabetical order! AddDynamicChild { realm: Arc<Realm>, }, BindInstance { realm: Arc<Realm>, component_decl: ComponentDecl, live_child_realms: Vec<Arc<Realm>>, routing_facade: RoutingFacade, }, PostDestroyInstance { realm: Arc<Realm>, }, PreDestroyInstance { realm: Arc<Realm>, }, RouteBuiltinCapability { // This is always the root realm. realm: Arc<Realm>, capability: ComponentManagerCapability, // Events are passed to hooks as immutable borrows. In order to mutate, // a field within an Event, interior mutability is employed here with // a Mutex. capability_provider: Arc<Mutex<Option<Box<dyn ComponentManagerCapabilityProvider>>>>, }, RouteFrameworkCapability { realm: Arc<Realm>, capability: ComponentManagerCapability, // Events are passed to hooks as immutable borrows. In order to mutate, // a field within an Event, interior mutability is employed here with // a Mutex. capability_provider: Arc<Mutex<Option<Box<dyn ComponentManagerCapabilityProvider>>>>, }, StopInstance { realm: Arc<Realm>, }, } impl Event { pub fn target_realm(&self) -> Arc<Realm> { match self { Event::AddDynamicChild { realm } => realm.clone(), Event::BindInstance { realm, .. } => realm.clone(), Event::PostDestroyInstance { realm } => realm.clone(), Event::PreDestroyInstance { realm } => realm.clone(), Event::RouteBuiltinCapability { realm, .. } => realm.clone(), Event::RouteFrameworkCapability { realm, .. } => realm.clone(), Event::StopInstance { realm } => realm.clone(), } } pub fn type_(&self) -> EventType { match self { Event::AddDynamicChild { .. } => EventType::AddDynamicChild, Event::BindInstance { .. } => EventType::BindInstance, Event::PostDestroyInstance { .. } => EventType::PostDestroyInstance, Event::PreDestroyInstance { .. } => EventType::PreDestroyInstance, Event::RouteBuiltinCapability { .. } => EventType::RouteBuiltinCapability, Event::RouteFrameworkCapability { .. } => EventType::RouteFrameworkCapability, Event::StopInstance { .. } => EventType::StopInstance, } } } /// This is a collection of hooks to component manager events. /// Note: Cloning Hooks results in a shallow copy. #[derive(Clone)] pub struct Hooks { parent: Option<Box<Hooks>>, inner: Arc<Mutex<HooksInner>>, } impl Hooks { pub fn new(parent: Option<&Hooks>) -> Self { Self { parent: parent.map(|hooks| Box::new(hooks.clone())), inner: Arc::new(Mutex::new(HooksInner::new())), } } pub async fn install(&self, hooks: Vec<HookRegistration>) { let mut inner = self.inner.lock().await; for hook in hooks { let hooks = &mut inner.hooks.entry(hook.event_type).or_insert(vec![]); // We cannot compare weak pointers, so we won't dedup pointers at // install time but at dispatch time when we go to upgrade pointers. hooks.push(Arc::downgrade(&hook.callback)); } } pub fn dispatch<'a>(&'a self, event: &'a Event) -> BoxFuture<Result<(), ModelError>> { Box::pin(async move { let hooks = { // We must upgrade our weak references to hooks to strong ones before we can // call out to them. While we're upgrading references, we dedup references // here as well. Ideally this would be done at installation time, not // dispatch time but comparing weak references is not yet supported. let mut strong_hooks: Vec<ByAddr<dyn Hook>> = vec![]; let mut inner = self.inner.lock().await; if let Some(hooks) = inner.hooks.get_mut(&event.type_()) { hooks.retain(|hook| match hook.upgrade() { Some(hook) => { let hook = ByAddr::new(hook); if !strong_hooks.contains(&hook) { strong_hooks.push(hook); true } else { // Don't retain a weak pointer if it is a duplicate. false } } // Don't retain a weak pointer if it cannot be upgraded. None => false, }); } strong_hooks }; for hook in hooks.into_iter() { hook.0.on(event).await?; } if let Some(parent) = &self.parent { parent.dispatch(event).await?; } Ok(()) }) } } pub struct HooksInner { hooks: HashMap<EventType, Vec<Weak<dyn Hook>>>, } impl HooksInner { pub fn new() -> Self { Self { hooks: HashMap::new() } } } #[cfg(test)] mod tests { use {super::*, std::sync::Arc}; #[derive(Clone)] struct EventLog { log: Arc<Mutex<Vec<String>>>, } impl EventLog { pub fn new() -> Self { Self { log: Arc::new(Mutex::new(Vec::new())) } } pub async fn append(&self, item: String) { let mut log = self.log.lock().await; log.push(item); } pub async fn get(&self) -> Vec<String> { self.log.lock().await.clone() } } struct CallCounter { name: String, logger: Option<EventLog>, call_count: Mutex<i32>, } impl CallCounter { pub fn new(name: &str, logger: Option<EventLog>) -> Arc<Self> { Arc::new(Self { name: name.to_string(), logger, call_count: Mutex::new(0) }) } pub async fn count(&self) -> i32 { *self.call_count.lock().await } async fn on_add_dynamic_child_async(&self) -> Result<(), ModelError> { let mut call_count = self.call_count.lock().await; *call_count += 1; if let Some(logger) = &self.logger { let fut = logger.append(format!("{}::OnAddDynamicChild", self.name)); fut.await; } Ok(()) } } impl Hook for CallCounter { fn on<'a>(self: Arc<Self>, event: &'a Event) -> BoxFuture<'a, Result<(), ModelError>> { Box::pin(async move { if let Event::AddDynamicChild { .. } = event { self.on_add_dynamic_child_async().await?; } Ok(()) }) } } fn log(v: Vec<&str>) -> Vec<String> { v.iter().map(|s| s.to_string()).collect() } // This test verifies that a hook cannot be installed twice. #[fuchsia_async::run_singlethreaded(test)] async fn install_hook_twice() { // CallCounter counts the number of AddDynamicChild events it receives. // It should only ever receive one. let call_counter = CallCounter::new("CallCounter", None); let hooks = Hooks::new(None); // Attempt to install CallCounter twice. hooks .install(vec![HookRegistration { event_type: EventType::AddDynamicChild, callback: call_counter.clone(), }]) .await; hooks .install(vec![HookRegistration { event_type: EventType::AddDynamicChild, callback: call_counter.clone(), }]) .await; let realm = { let resolver = ResolverRegistry::new(); let root_component_url = "test:///root".to_string(); Arc::new(Realm::new_root_realm(resolver, root_component_url)) }; let event = Event::AddDynamicChild { realm: realm.clone() }; hooks.dispatch(&event).await.expect("Unable to call hooks."); assert_eq!(1, call_counter.count().await); } // This test verifies that events propagate from child_hooks to parent_hooks. #[fuchsia_async::run_singlethreaded(test)] async fn event_propagation() { let parent_hooks = Hooks::new(None); let child_hooks = Hooks::new(Some(&parent_hooks)); let event_log = EventLog::new(); let parent_call_counter = CallCounter::new("ParentCallCounter", Some(event_log.clone())); parent_hooks .install(vec![HookRegistration { event_type: EventType::AddDynamicChild, callback: parent_call_counter.clone(), }]) .await; let child_call_counter = CallCounter::new("ChildCallCounter", Some(event_log.clone())); child_hooks .install(vec![HookRegistration { event_type: EventType::AddDynamicChild, callback: child_call_counter.clone(), }]) .await; assert_eq!(1, Arc::strong_count(&parent_call_counter)); assert_eq!(1, Arc::strong_count(&child_call_counter)); let realm = { let resolver = ResolverRegistry::new(); let root_component_url = "test:///root".to_string(); Arc::new(Realm::new_root_realm(resolver, root_component_url)) }; let event = Event::AddDynamicChild { realm: realm.clone() }; child_hooks.dispatch(&event).await.expect("Unable to call hooks."); // parent_call_counter gets informed of the event on child_hooks even though it has // been installed on parent_hooks. assert_eq!(1, parent_call_counter.count().await); // child_call_counter should be called only once. assert_eq!(1, child_call_counter.count().await); // Dropping the child_call_counter should drop the weak pointer to it in hooks // as well. drop(child_call_counter); // Dispatching an event on child_hooks will not call out to child_call_counter // because it has been destroyed by the call to drop above. child_hooks.dispatch(&event).await.expect("Unable to call hooks."); // ChildCallCounter should be called before ParentCallCounter. assert_eq!( log(vec![ "ChildCallCounter::OnAddDynamicChild", "ParentCallCounter::OnAddDynamicChild", "ParentCallCounter::OnAddDynamicChild", ]), event_log.get().await ); } }
use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Term; #[native_implemented::function(erlang:get/1)] pub fn result(process: &Process, key: Term) -> Term { process.get_value_from_key(key) }
use std::io::Cursor; use std::str; use neon::prelude::*; use manifest::{Manifest, NodeId, NodeType, StreamType}; use uuid::Uuid; use ::MANIFEST; /// Creates a "name" node on the given node. /// /// # Arguments /// [ /// node ID: String, /// default language: String, /// names: Array of objects /// ] /// /// The names objects should have keys "language" and "text". /// /// # Return /// True if the stream creation succeeded. /// /// # Exceptions /// Throws if there is no loaded manifest or if the node ID can't be parsed. pub fn set_node_names(mut cx: FunctionContext) -> JsResult<JsBoolean> { let node_id = get_id_arg!(cx[0]); let default_lang = cx.argument::<JsString>(1)?.value(); let names = cx.argument::<JsArray>(2)?.to_vec(&mut cx)?; info!("Setting names on node {} (default: {}; # names: {})", node_id, default_lang, names.len()); if let Some(ref mut manifest) = *MANIFEST.write() { let lang_tag_category = manifest.tags.get_language_category(); if let Ok(name_node_id) = manifest.create_node(&node_id, NodeType::Title) { for name_handle in names { let name_object = name_handle.downcast_or_throw::<JsObject, _>(&mut cx)?; let language = name_object .get(&mut cx, "language")? .downcast_or_throw::<JsString, _>(&mut cx)? .value(); let text = name_object .get(&mut cx, "text")? .downcast_or_throw::<JsString, _>(&mut cx)? .value(); debug!("Setting name \"{}\" in language \"{}\"", text, language); let text_len = text.len() as u64; let text_read = Cursor::new(text); // Create the stream match manifest.add_stream_to_node( &name_node_id, StreamType::Text { raw: true }, text_read, text_len, ) { Ok(name_stream_id) => { if language == default_lang { let default_tag = manifest.tags.get_default_language_tag(); // TODO: don't panic manifest.add_tag_to_stream(&name_stream_id, &default_tag).unwrap(); } // TODO: don't panic let lang_tag = manifest.tags.get_or_create_tag(&lang_tag_category, &language).unwrap(); manifest.add_tag_to_stream(&name_stream_id, &lang_tag).unwrap(); }, Err(e) => { warn!("Could not add name stream to node {}: {}", name_node_id, e); return Ok(cx.boolean(false)); } } } } else { warn!("Could not create name node on node {}", node_id); return Ok(cx.boolean(false)); } } else { error!("Tried to set node's name while no manifest loaded!"); return cx.throw_error("no manifest loaded"); } Ok(cx.boolean(true)) } fn get_single_node_names<'a, 'b>( cx: &'a mut CallContext<'b, JsObject>, manifest: &Manifest, node_id: &NodeId ) -> JsResult<'b, JsValue> { info!("Getting names for node {}", node_id); let lang_tag_category = manifest.tags.get_language_category(); let default_lang_tag = manifest.tags.get_default_language_tag(); if manifest.contains_node(&node_id) { // Unwrap is safe since we already checked that the node exists let name_node_id = { let name_node_ids = manifest.get_node_children_with_type(&node_id, &NodeType::Title).unwrap(); if name_node_ids.len() != 1 { warn!("Node had zero or multiple ({}) title subnodes!", name_node_ids.len()); let mut obj = cx.empty_object(); let null = cx.null(); let empty = cx.empty_object(); obj.set(cx, "default", null)?; obj.set(cx, "names", empty)?; return Ok(obj.upcast()); } name_node_ids.iter().next().unwrap().clone() }; let mut default_lang_set = false; let result_obj = cx.empty_object(); let name_obj = cx.empty_object(); let expected_type = StreamType::Text { raw: true }; // Unwrap is safe since we already checked that the node exists for stream_id in manifest.get_node_streams_with_type(&name_node_id, &expected_type).unwrap() { // get all the tag IDs from the stream - unwrap is safe since get_node_streams_with_type // guarantees that the stream IDs returned exist let all_tags = manifest.get_stream_tags(&stream_id).unwrap(); let tags = all_tags.iter().filter(|tag_id| { manifest.tags.get_tag_category(tag_id).map_or(false, |category| category == lang_tag_category) }); let (is_default, lang) = { let mut is_default = false; let mut lang = String::new(); for tag_id in tags { if *tag_id == default_lang_tag { is_default = true; } else if let Some(lang_from_tag) = manifest.tags.get_tag_value(tag_id) { lang = lang_from_tag.to_string(); } } (is_default, lang) }; if is_default { let lang_str = cx.string(&lang); result_obj.set(cx, "default", lang_str)?; default_lang_set = true; } let mut name = Vec::new(); match manifest.open_stream(&stream_id) { // Note: we assume that title streams are relatively short Ok(mut stream) => match stream.read_to_end(&mut name) { Ok(_) => {}, Err(e) => { warn!("Failed to read name stream: {}", e); return cx.throw_error(format!("failed to read name stream: {}", e)); } }, Err(e) => { warn!("Failed to open name stream: {}", e); return cx.throw_error(format!("failed to open name stream: {}", e)); } } let str_name = match str::from_utf8(&name[..]) { Ok(str_name) => str_name, Err(e) => { warn!("Stream name was not UTF-8: {}", e); return cx.throw_error(format!("stream name was not UTF-8: {}", e)); } }; debug!("Found lang: {}, name: {}", lang, str_name); let str_name = cx.string(str_name); name_obj.set(cx, lang.as_str(), str_name)?; } if !default_lang_set { let null = cx.null(); result_obj.set(cx, "default", null)?; } result_obj.set(cx, "names", name_obj)?; Ok(result_obj.upcast()) } else { warn!("Tried to read non-existant node {}'s names!", node_id); Ok(cx.null().upcast()) } } /// # Arguments /// [[node ID: string]] /// /// # Return /// An array of objects. There is a key "default" which gives the default language, /// and a key "names" which contains an object mapping language -> name. /// /// If no name stream was marked as default, then "default" is null. If the /// given node has no "Title"-type subnode or that subnode has no text streams, /// the "names" object will be empty. If the given node does not exist, this /// returns null. /// /// # Exceptions /// Throws if there is no manifest loaded or the node ID couldn't be parsed. /// Also throws if a name stream could not be read, or if a name wasn't valid /// UTF-8. pub fn get_node_names(mut cx: FunctionContext) -> JsResult<JsValue> { let nodes = cx.argument::<JsArray>(0)?.to_vec(&mut cx)?; let result = cx.empty_array(); if let Some(ref manifest) = *MANIFEST.read() { for (i, node_id_val) in nodes.iter().enumerate() { let node_id_str = node_id_val.downcast_or_throw::<JsString, _>(&mut cx)?.value(); let node_id = match Uuid::parse_str(node_id_str.as_str()) { Ok(id) => id, Err(e) => { warn!("tried to parse unparseable node ID {} ({})", node_id_str, e); return cx.throw_error(format!("{}", e)) } }; let node_names = get_single_node_names(&mut cx, manifest, &node_id)?; result.set(&mut cx, i as u32, node_names)?; } Ok(result.upcast()) } else { error!("Tried to read node's name while no manifest loaded!"); cx.throw_error("no manifest loaded") } }
table! { transfers (id) { id -> Int4, amount -> Text, currency -> Text, to_name -> Text, to_number -> Text, to_email -> Text, complete -> Bool, } } table! { users (id) { id -> Int4, first_name -> Varchar, last_name -> Varchar, user_name -> Varchar, email -> Varchar, public_key -> Varchar, private_key -> Varchar, eth_address -> Varchar, } } allow_tables_to_appear_in_same_query!( transfers, users, );
#[doc = "Reader of register DMASBMR"] pub type R = crate::R<u32, super::DMASBMR>; #[doc = "Writer for register DMASBMR"] pub type W = crate::W<u32, super::DMASBMR>; #[doc = "Register DMASBMR `reset()`'s with value 0x0101_0000"] impl crate::ResetValue for super::DMASBMR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0101_0000 } } #[doc = "Reader of field `RB`"] pub type RB_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RB`"] pub struct RB_W<'a> { w: &'a mut W, } impl<'a> RB_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 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `MB`"] pub type MB_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MB`"] pub struct MB_W<'a> { w: &'a mut W, } impl<'a> MB_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 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `AAL`"] pub type AAL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AAL`"] pub struct AAL_W<'a> { w: &'a mut W, } impl<'a> AAL_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 `FB`"] pub type FB_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FB`"] pub struct FB_W<'a> { w: &'a mut W, } impl<'a> FB_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 } } impl R { #[doc = "Bit 15 - Rebuild INCRx Burst"] #[inline(always)] pub fn rb(&self) -> RB_R { RB_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 14 - Mixed Burst"] #[inline(always)] pub fn mb(&self) -> MB_R { MB_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 12 - Address-Aligned Beats"] #[inline(always)] pub fn aal(&self) -> AAL_R { AAL_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 0 - Fixed Burst Length"] #[inline(always)] pub fn fb(&self) -> FB_R { FB_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 15 - Rebuild INCRx Burst"] #[inline(always)] pub fn rb(&mut self) -> RB_W { RB_W { w: self } } #[doc = "Bit 14 - Mixed Burst"] #[inline(always)] pub fn mb(&mut self) -> MB_W { MB_W { w: self } } #[doc = "Bit 12 - Address-Aligned Beats"] #[inline(always)] pub fn aal(&mut self) -> AAL_W { AAL_W { w: self } } #[doc = "Bit 0 - Fixed Burst Length"] #[inline(always)] pub fn fb(&mut self) -> FB_W { FB_W { w: self } } }
#![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 ISocialDashboardItemUpdater(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISocialDashboardItemUpdater { type Vtable = ISocialDashboardItemUpdater_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3cde9dc9_4800_46cd_869b_1973ec685bde); } #[repr(C)] #[doc(hidden)] pub struct ISocialDashboardItemUpdater_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut 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, value: super::super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ISocialFeedUpdater(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISocialFeedUpdater { type Vtable = ISocialFeedUpdater_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7a0c0aa7_ed89_4bd5_a8d9_15f4d9861c10); } #[repr(C)] #[doc(hidden)] pub struct ISocialFeedUpdater_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 super::SocialFeedKind) -> ::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")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ISocialInfoProviderManagerStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISocialInfoProviderManagerStatics { type Vtable = ISocialInfoProviderManagerStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1b88e52b_7787_48d6_aa12_d8e8f47ab85a); } #[repr(C)] #[doc(hidden)] pub struct ISocialInfoProviderManagerStatics_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, kind: super::SocialFeedKind, mode: super::SocialFeedUpdateMode, ownerremoteid: ::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, ownerremoteid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itemremoteid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, newcount: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, contactremoteid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, kind: super::SocialFeedKind) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SocialDashboardItemUpdater(pub ::windows::core::IInspectable); impl SocialDashboardItemUpdater { #[cfg(feature = "deprecated")] pub fn OwnerRemoteId(&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 = "deprecated")] pub fn Content(&self) -> ::windows::core::Result<super::SocialFeedContent> { 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::SocialFeedContent>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::DateTime>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn SetTimestamp<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::DateTime>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn SetThumbnail<'a, Param0: ::windows::core::IntoParam<'a, super::SocialItemThumbnail>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn Thumbnail(&self) -> ::windows::core::Result<super::SocialItemThumbnail> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::SocialItemThumbnail>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn CommitAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn TargetUri(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn SetTargetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for SocialDashboardItemUpdater { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.SocialInfo.Provider.SocialDashboardItemUpdater;{3cde9dc9-4800-46cd-869b-1973ec685bde})"); } unsafe impl ::windows::core::Interface for SocialDashboardItemUpdater { type Vtable = ISocialDashboardItemUpdater_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3cde9dc9_4800_46cd_869b_1973ec685bde); } impl ::windows::core::RuntimeName for SocialDashboardItemUpdater { const NAME: &'static str = "Windows.ApplicationModel.SocialInfo.Provider.SocialDashboardItemUpdater"; } impl ::core::convert::From<SocialDashboardItemUpdater> for ::windows::core::IUnknown { fn from(value: SocialDashboardItemUpdater) -> Self { value.0 .0 } } impl ::core::convert::From<&SocialDashboardItemUpdater> for ::windows::core::IUnknown { fn from(value: &SocialDashboardItemUpdater) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SocialDashboardItemUpdater { 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 SocialDashboardItemUpdater { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SocialDashboardItemUpdater> for ::windows::core::IInspectable { fn from(value: SocialDashboardItemUpdater) -> Self { value.0 } } impl ::core::convert::From<&SocialDashboardItemUpdater> for ::windows::core::IInspectable { fn from(value: &SocialDashboardItemUpdater) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SocialDashboardItemUpdater { 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 SocialDashboardItemUpdater { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SocialDashboardItemUpdater {} unsafe impl ::core::marker::Sync for SocialDashboardItemUpdater {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SocialFeedUpdater(pub ::windows::core::IInspectable); impl SocialFeedUpdater { #[cfg(feature = "deprecated")] pub fn OwnerRemoteId(&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 = "deprecated")] pub fn Kind(&self) -> ::windows::core::Result<super::SocialFeedKind> { let this = self; unsafe { let mut result__: super::SocialFeedKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::SocialFeedKind>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Collections")] pub fn Items(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<super::SocialFeedItem>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<super::SocialFeedItem>>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn CommitAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } } unsafe impl ::windows::core::RuntimeType for SocialFeedUpdater { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.SocialInfo.Provider.SocialFeedUpdater;{7a0c0aa7-ed89-4bd5-a8d9-15f4d9861c10})"); } unsafe impl ::windows::core::Interface for SocialFeedUpdater { type Vtable = ISocialFeedUpdater_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7a0c0aa7_ed89_4bd5_a8d9_15f4d9861c10); } impl ::windows::core::RuntimeName for SocialFeedUpdater { const NAME: &'static str = "Windows.ApplicationModel.SocialInfo.Provider.SocialFeedUpdater"; } impl ::core::convert::From<SocialFeedUpdater> for ::windows::core::IUnknown { fn from(value: SocialFeedUpdater) -> Self { value.0 .0 } } impl ::core::convert::From<&SocialFeedUpdater> for ::windows::core::IUnknown { fn from(value: &SocialFeedUpdater) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SocialFeedUpdater { 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 SocialFeedUpdater { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SocialFeedUpdater> for ::windows::core::IInspectable { fn from(value: SocialFeedUpdater) -> Self { value.0 } } impl ::core::convert::From<&SocialFeedUpdater> for ::windows::core::IInspectable { fn from(value: &SocialFeedUpdater) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SocialFeedUpdater { 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 SocialFeedUpdater { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SocialFeedUpdater {} unsafe impl ::core::marker::Sync for SocialFeedUpdater {} pub struct SocialInfoProviderManager {} impl SocialInfoProviderManager { #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn CreateSocialFeedUpdaterAsync<'a, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(kind: super::SocialFeedKind, mode: super::SocialFeedUpdateMode, ownerremoteid: Param2) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<SocialFeedUpdater>> { Self::ISocialInfoProviderManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), kind, mode, ownerremoteid.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<SocialFeedUpdater>>(result__) }) } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn CreateDashboardItemUpdaterAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(ownerremoteid: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<SocialDashboardItemUpdater>> { Self::ISocialInfoProviderManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), ownerremoteid.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<SocialDashboardItemUpdater>>(result__) }) } #[cfg(feature = "deprecated")] pub fn UpdateBadgeCountValue<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(itemremoteid: Param0, newcount: i32) -> ::windows::core::Result<()> { Self::ISocialInfoProviderManagerStatics(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), itemremoteid.into_param().abi(), newcount).ok() }) } #[cfg(feature = "deprecated")] pub fn ReportNewContentAvailable<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(contactremoteid: Param0, kind: super::SocialFeedKind) -> ::windows::core::Result<()> { Self::ISocialInfoProviderManagerStatics(|this| unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), contactremoteid.into_param().abi(), kind).ok() }) } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn ProvisionAsync() -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<bool>> { Self::ISocialInfoProviderManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<bool>>(result__) }) } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn DeprovisionAsync() -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { Self::ISocialInfoProviderManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) }) } pub fn ISocialInfoProviderManagerStatics<R, F: FnOnce(&ISocialInfoProviderManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<SocialInfoProviderManager, ISocialInfoProviderManagerStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for SocialInfoProviderManager { const NAME: &'static str = "Windows.ApplicationModel.SocialInfo.Provider.SocialInfoProviderManager"; }
use crate::error::{GameError, GameResult}; use winit::window::Fullscreen; use winit::monitor::{VideoMode, MonitorHandle}; #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub enum FullscreenMode { Exclusive, Borderless, } impl FullscreenMode { pub(crate) fn from_raw(fullscreen: Fullscreen) -> Self { match fullscreen { Fullscreen::Exclusive(_) => FullscreenMode::Exclusive, Fullscreen::Borderless(_) => FullscreenMode::Borderless, } } pub(crate) fn into_raw(self, monitor: MonitorHandle) -> GameResult<Fullscreen> { match self { FullscreenMode::Exclusive => get_preferred_video_mode(monitor) .map(|video_mode| Fullscreen::Exclusive(video_mode)), FullscreenMode::Borderless => Ok(Fullscreen::Borderless(monitor)), } } } fn get_preferred_video_mode(monitor: MonitorHandle) -> GameResult<VideoMode> { let mut preferred_video_mode: Option<VideoMode> = None; for (_, video_mode) in monitor.video_modes().enumerate() { if let Some(current_video_mode) = &preferred_video_mode { let current_size = current_video_mode.size(); let size = video_mode.size(); if current_size.width * current_size.height < size.width * size.height { preferred_video_mode = Some(video_mode); } } else { preferred_video_mode = Some(video_mode); } } preferred_video_mode.ok_or_else(|| GameError::NotSupportedError("no available video mode".into())) }
fn main() { println!("Hello, world!"); // Sharing Versus Mutation // Rust ensures no ref will ever point to a variable that has gone out of scope. But there are other ways to introduce dangling pointers. Example: let v = vec![4, 8, 19, 27, 34, 10]; let r = &v; let aside = v; // move vector to aside r[0]; // bad: uses 'v', which is now uninitialized // The assignment to aside moves the vector, leaving v uninitialized, turning r into a dangling pointer (see page 185 for diagram). // Although v stays in scope for r's entire lifetime, the problem here is that v's value gets moved elsewhere, leaving v uninitialized while r still refers to it. Naturally, Rust catches the error: // cannot move out of 'v' because it is borrowed // Throughout its lifetime, a shared ref makes its referent read-only. We may not assign to the referent or move its value elsewhere. In this code, r's lifetime contains the attempt to move the vector, so Rust rejects the program. With changes, we can fix it: let v = vec![4, 8, 19, 27, 34, 10]; { let r = &v; r[0]; // ok, vector is still there } let aside = v; // In this version, r goes out of scope earlier, the refs lifetime ends before v is moved aside, and all is well. // Another example that wreaks havoc. Suppose we have a handy function to extend a vector with the elements of a slice: fn extend(vec: &mut Vec<f64>, slice: &[f64]) { for elt in slice { vec.push(*elt); } } // This is a less flexible (and much less optimized) version of the standard library's extend_from_slice method on vectors. We can use it to build up a vector from slices of other vectors or arrays: let mut wave = Vec::new(); let head = vec![0.0, 1.0]; let tail = [0.0, -1.0]; extend(&mut wave, &head); // extend wave with another vector extend(&mut wave, &tail); // extend wave with an array assert_eq!(wave, vec![0.0, 1.0, 0.0, -1.0]); // We've built up one period of a sine wave here. If we want to add another undulation, can we append the vector to itself? extend(&mut wave, &wave); assert_eq!(wave, vec![0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0]); // This may look fine on casual inspection. But remember that when we add an element to a vector, if its buffer is full, it must allocate a new buffer with more space. Suppose wave starts with space for four elements, and so must allocate a larger buffer when extend tries to add a fifth. See page 187 for diagram illustrating the change. // The extend function's vec argument borrows wave (owned by the caller), which has allocated itself a new buffer with space for eight elements. But slice continues to point to the old four-element buffer which has been dropped. // This sort of problem isn't unique to Rust. Modifying collections while pointing into them is delicate territory in many languages (like C++ or Java). What's especially difficult about this sort of bug is that is doesn't happen all the time. In testing, our vector might always happen to have enough space, the buffer might never be reallocated, and the problem might never come to light. // Rust, however, reports the problem with our call to extend at compile time: // Cannot borrow `wave` as immutable because it is also borrowed as mutable... // In other words, we may borrow a mutable ref to the vector, and we may borrow a shared ref to its elements, but those two refs lifetimes may not overlap. In our case, both refs lifetimes contain the call to extend so Rust rejects the code. // These errors both stem from violations of Rust's rules for mutation and sharing: // 1. Shared access is read-only access. Values borrowed by shared refs are read-only. Across the lifetime of shared ref, neither its referent, nor anything reachable from that referent, can be changed by anything. There exist no live mutable refs to anything in that structure. Its owner is held read-only, and so on. It's frozen. // 2. Mutable access is exclusive access. A value borrowed by a mutable ref is reachable exclusively via that ref. Across the lifetime of a mutable ref, there is no other usable path to its referent, or to any value reachable from there. The only refs whose lifetimes may overlap with a mutable ref are those we borrow from the mutable ref itself. // Rust reported the extend example as a violation of the second rule. Since we've borrowed a mutable ref to wave, that mutable ref must be the only way to reach the vector or its elements. The shared ref to the slice is itself another way to reach the elements, violating the second rule. // Rust could also treat our bug as a violation of the first rule. Since we've borrowed a shared ref to wave's elements, the elements and the Vec itself are all read-only. We can't borrow a mutable ref to a read-only value. See page 189 for diagram showing the diffs on refs. // In both cases, the path of ownership leading to the referent cannot be changed for the refs lifetime. For a shared borrow, the path is read-only. For a mutable borrow, it's completely inaccessible. So there's no way for the program to do anything that will invalidate the ref. // Pairing the principles down to the simplest possible examples: let mut x = 10; let r1 = &x; let r2 = &x; // ok, multiple shared borrows permitted x += 10; // error, cannot assign to 'x' because it is borrowed let m = &mut x; // error, cannot borrow 'x' as mutable because it is also borrowed as immutable. let mut y = 20; let m1 = &mut y; let m2 = &mut y; // error, cannot borrow as mutable more than once let z = y; // error, cannot use 'y' because it was mutably borrowed // It is OK to re-borrow a shared ref from a shared ref: let mut w = (107, 109); let r = &w; let r0 = &r.0; // ok, re-borrowing shared as shared let m1 = &mut r.1; // error, can't re-borrow shared as mutable // We can re-borrow from a mutable reference: let mut v = (136, 139); let m = &mut v; let m0 = &mut m.0; // ok, re-borrowing mutable from mutable *m = 137; let r1 = &m.1; // ok, re-borrowing shared from mutable, and doesn't overlap with m0 v.1; // error, access through other paths still forbidden // These restrictions are pretty tight. Turning back to our attempted call extend(&mut wave, &wave), there's no quick and easy way to fix up the code to work the way we'd like. Rust applies these rules everywhere. If we borrow, say, a shared ref to a key in a HashMap, we can't borrow a mutable ref to the HashMap until the shared refs lifetime ends. // But there's good justification for this. Designing collections to support unrestricted, simultaneous iteration and modification is difficult, and often precludes simpler, more efficient implementations. See page 191 for how other languages do or don't do this. // Another example of the kind of bug these rules catch. Consider the following C++ code, meant to manage a file descriptor. To keep things simple, we're only going to show a constructor and copying assignment operator, and we're going to omit error handling: struct File { int desciptor; File(int d) : descriptor(d) {} File& operator=(const File &rhs) { close(descriptor); descriptor = dup(rhs.descriptor); } }; // The assignment operator is simple enough, but fails badly in a situation life this: File f(open("foo.txt", ...)); ... f = f; // If we assign a FIle to itself, both rhs, and *this are the same object, so operator= closes the very file descriptor it's about to pass to dup. We destroy the same resource we were meant to copy. // In Rust, the analogous code would be: struct File { descriptor: i32 } fn new_file(d: i32) -> File { File { descriptor: d } } fn clone_from(this: &mut File, rhs: &File) { close(this.descriptor); this.descriptor = dup(rhs.descriptor); } // Aside: The above isn't idiomatic Rust. There are excellent ways to give Rust types their own constructor functions and methods, which are covered in chapt 9. The above use is for example purposes. // If we write the Rust code corresponding to the use of FIle, we get: let mut f = new_file(open("foo.txt", ...)); ... clone_from(&mut f, &f); // Rust, of course, refuses to compile the code: // cannot borrow `f` as immutable because it is also borrowed as mutable.. // This should look familiar. It turns out that two classic C++ bugs, failure to cope with self-assignment, and using invalidated iterators are the same underlying kind of bug. In both cases, code assumes it's modifying one value while consulting another, when in fact they're both the same value. By requiring mutable access to be exclusive, Rust has fended off a wide class of everyday mistakes. // The immiscibility of shared and mutable refs really demonstrates its value when writing concurrent code. A data race is possible only when some value is both mutable and shared between threads, which is exactly what Rust's reference rules eliminate. A concurrent Rust program that avoids unsafe code is free of data races by construction (covered in Chapter 19). In summary, concurrency is much easier to use in Rust than in most other languages. See page 193 for Rust vs C's pointers to const. }
use std::fmt; use super::{Expression, Operand}; #[derive(Debug, Clone, PartialEq)] pub struct Expr { pub operand: Option<Operand>, pub args: Vec<Box<Expression>>, pub parent: Option<Box<Expr>>, } impl fmt::Display for Expr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut disp; let mut end = ")"; let mut is_scope = false; let mut spacer; if let Some(ref op) = self.operand { disp = format!("({} ", op); if op == &Operand::Scope { end = "\n)"; is_scope = true; } } else { disp = "(".to_string(); } let len = self.args.len(); for (i, e) in self.args.iter().enumerate() { if is_scope { spacer = "\n"; } else { spacer = " "; } if i == len - 1 { spacer = ""; } disp.push_str(&format!("{}{}", e, spacer)); } return write!(f, "{}{}", disp, end); } }
#[macro_export] macro_rules! uri_path { { $( $val:ident )/ * } => { $crate::uri::UriPath::new(vec![ $( stringify!($val) ),* ]) } } #[macro_export] macro_rules! uri_params { { $( $key:ident => $val:expr ),* } => { { use std::collections::HashMap; use std::borrow::Cow; let mut map: HashMap<&'static str, Cow<'_, str>> = HashMap::new(); $( map.insert(stringify!($key), Cow::from($val)); )* $crate::uri::QueryParameters::new(map) } } } #[macro_export] macro_rules! dbg_json { { $e:expr } => { { let val = &($e); if let serde_json::Value::Object(map) = val { eprintln!("[{}:{}] {}.keys() = {:?}", file!(), line!(), stringify!($e), map.keys().collect::<Vec<&std::string::String>>()); } else { dbg!(val); } } } }
use std::cmp::{min, max}; #[derive(Debug)] enum Spell { MagicMissile = 0, Drain = 1, Shield = 2, Poison = 3, Recharge = 4, } static SPELLS: [Spell; 5] = [Spell::MagicMissile, Spell::Drain, Spell::Shield, Spell::Poison, Spell::Recharge]; static SPELLCOST: [i32; 5] = [53, 73, 113, 173, 229]; const BOSS_HP: i32 = 55; const BOSS_DAMAGE: i32 = 8; const PLAYER_HP: i32 = 50; const PLAYER_MANA: i32 = 500; fn round( mut bosshp: i32, mut playerhp: i32, mut mana: i32, mut cost: i32, mut shield: i32, mut poison: i32, mut recharge: i32, spell: &Spell, best_cost: i32, hard_mode: bool, ) -> i32 { if cost >= best_cost { return best_cost; } let mut armor: i32 = 0; let c; match spell { &Spell::MagicMissile => { bosshp -= 4; c = 53; } &Spell::Drain => { bosshp -= 2; playerhp += 2; c = 73; }, &Spell::Shield => { if shield == 0 { shield = 6; } else { return best_cost; } c = 113; }, &Spell::Poison => { if poison == 0 { poison = 6; } else { return best_cost; } c = 173; }, &Spell::Recharge => { if recharge == 0 { recharge = 5; } else { return best_cost; } c = 229; } }; mana -= c; cost += c; // boss turn if shield > 0 { armor = 7; shield -= 1; } if poison > 0 { bosshp -= 3; poison -= 1; } if recharge > 0 { mana += 101; recharge -= 1; } if bosshp <= 0 { return cost; } else { playerhp -= max(1, BOSS_DAMAGE - armor); } if hard_mode { playerhp -= 1; } if playerhp <= 0 { return best_cost; } // player turn if shield > 0 { shield -= 1; } if poison > 0 { bosshp -= 3; poison -= 1; } if recharge > 0 { mana += 101; recharge -= 1; } if bosshp <= 0 { return cost; } let mut ret = best_cost; for (i, s) in SPELLS.iter().enumerate() { if mana < SPELLCOST[i] { continue } let r = round(bosshp, playerhp, mana, cost, shield, poison, recharge, &s, ret, hard_mode); ret = min(ret, r) } ret } fn main() { let mut best_cost = 1000000; for s in SPELLS.iter() { let score = round(BOSS_HP, PLAYER_HP, PLAYER_MANA, 0, 0, 0, 0, s, best_cost, false); best_cost = min(best_cost, score); } println!("{}", best_cost); best_cost = 1000000; for s in SPELLS.iter() { let score = round(BOSS_HP, PLAYER_HP - 1, PLAYER_MANA, 0, 0, 0, 0, s, best_cost, true); best_cost = min(best_cost, score); } println!("{}", best_cost); }
use crate::{ device::Device, hook::{Hook, Op}, }; use failure::{bail, Error}; #[derive(Debug)] pub enum Token { String(String), Immediate(i64), Open, Close, Comma, } impl Token { fn as_string(self) -> Result<String, Error> { match self { Token::String(string) => Ok(string), other => bail!("expected string, but got: {:?}", other), } } fn as_immediate(self) -> Result<i64, Error> { match self { Token::Immediate(immediate) => Ok(immediate), other => bail!("expected immediate, but got: {:?}", other), } } fn as_register(self, device: &Device) -> Result<usize, Error> { let out = match self.as_string()?.as_str() { "a" => 0, "b" => 1, "c" => 2, "d" => 3, "e" => 4, "f" => 5, "ip" => device.registers.ip, other => bail!("not a register: {}", other), }; Ok(out) } fn as_open(self) -> Result<(), Error> { match self { Token::Open => Ok(()), _ => bail!("expected string"), } } fn as_close(self) -> Result<(), Error> { match self { Token::Close => Ok(()), _ => bail!("expected string"), } } fn as_comma(self) -> Result<(), Error> { match self { Token::Comma => Ok(()), _ => bail!("expected string"), } } } fn tokenize<'a>(input: &'a str) -> Tokenizer<'a> { Tokenizer { it: input.chars().peekable(), } } pub struct Tokenizer<'a> { it: std::iter::Peekable<std::str::Chars<'a>>, } impl<'a> Tokenizer<'a> { pub fn try_next(&mut self) -> Result<Option<Token>, Error> { loop { let t = match self.it.peek().cloned() { Some(c) => match c { 'a'..='z' => return Ok(Some(Token::String(self.string()))), '0'..='9' => return Ok(Some(Token::Immediate(self.immediate()?))), '(' => Token::Open, ')' => Token::Close, ',' => Token::Comma, ' ' => { self.it.next(); continue; } c => bail!("unexpected character: {}", c), }, None => return Ok(None), }; self.it.next(); return Ok(Some(t)); } } pub fn next(&mut self) -> Result<Token, Error> { match self.try_next()? { Some(next) => Ok(next), None => bail!("expected token"), } } pub fn as_hook(&mut self, device: &Device) -> Result<Hook, Error> { let name = self.next()?.as_string()?; match name.as_str() { "line" => { self.next()?.as_open()?; let line = self.next()?.as_immediate()? as usize; self.next()?.as_close()?; return Ok(Hook::Line(line)); } "read" => { self.next()?.as_open()?; let reg = self.next()?.as_register(device)?; self.next()?.as_close()?; return Ok(Hook::Read(reg)); } "write" => { self.next()?.as_open()?; let reg = self.next()?.as_register(device)?; self.next()?.as_close()?; return Ok(Hook::Write(reg)); } "unique" => { self.next()?.as_open()?; let reg = self.next()?.as_register(device)?; self.next()?.as_close()?; return Ok(Hook::unique(reg)); } "all" => { self.next()?.as_open()?; let mut hooks = Vec::new(); hooks.push(self.as_hook(device)?); loop { match self.next()? { Token::Comma => { hooks.push(self.as_hook(device)?); } Token::Close => break, _ => bail!("expected comma or close"), } } return Ok(Hook::All(hooks)); } "not" => { self.next()?.as_open()?; let inner = self.as_hook(device)?; self.next()?.as_close()?; return Ok(Hook::Not(Box::new(inner))); } "gt" | "lt" | "eq" | "gte" | "lte" => { self.next()?.as_open()?; let reg = self.next()?.as_register(device)?; self.next()?.as_comma()?; let immediate = self.next()?.as_immediate()?; self.next()?.as_close()?; let op = match name.as_str() { "gt" => Op::Gt, "lt" => Op::Lt, "eq" => Op::Eq, "gte" => Op::Gte, "lte" => Op::Lte, other => bail!("bad operation: {}", other), }; return Ok(Hook::Op(op, reg, immediate)); } other => bail!("no such function: {}", other), } } fn string(&mut self) -> String { let mut buffer = String::new(); while let Some(c) = self.it.peek().cloned() { match c { 'a'..='z' => { buffer.push(c); } _ => break, } self.it.next(); } return buffer; } fn immediate(&mut self) -> Result<i64, Error> { let mut buffer = String::new(); while let Some(c) = self.it.peek().cloned() { match c { '0'..='9' => buffer.push(c), _ => break, } self.it.next(); } Ok(str::parse(&buffer)?) } } pub fn parse(input: &str, device: &Device) -> Result<Hook, Error> { return Ok(tokenize(input).as_hook(device)?); } #[cfg(test)] mod tests { use super::parse; #[test] pub fn test_parse() { use crate::device::Device; let device = Device::default(); parse("all(line(28), line(40))", &device).expect("not parse"); } }
use iced::{button, Button, Row, Element, Sandbox, Settings, Text, scrollable, Scrollable, HorizontalAlignment, Length, Column, Container, text_input, TextInput, Align, Radio}; const DEFAULT_SIZE: (u32, u32) = (450, 250); const MIN_SIZE: (u32, u32) = (400, 200); const PAD: u16 = 10; const SPACING: u16 = 5; const PAD_SMALL: u16 = 2; const TEXTINPUT_WIDTH: u16 = 100; pub fn main() -> iced::Result{ // Set the window properties let mut settings = Settings::default(); settings.window.size = DEFAULT_SIZE; settings.window.min_size = Some(MIN_SIZE); // run the application CRUD::run(settings) } struct ListItem { index: usize, label: String, } impl ListItem { fn new(index: usize, label: &str) -> Self { ListItem { index, label: label.to_string() } } } struct List { items: Vec<ListItem>, selected: Option<usize>, scroll: scrollable::State, } impl Default for List { fn default() -> List { let v = vec![ "Emil, Hans", "Mustermann, Max", "Tisch, Roman", ]; List { items: v.iter() .enumerate() .map( |(i, s)| ListItem::new(i, s) ).collect(), selected: None, scroll: scrollable::State::default() } } } impl List { fn view(&mut self, filter: &str) -> Container<Message> { let iterlist = self.items .iter() .filter(|i| i.label.to_lowercase().contains(&filter.to_lowercase())); let content = iterlist.fold( Column::new() .padding(PAD) .spacing(1), |column, item| { column.push(Radio::new( item.index, &item.label, self.selected, Message::SelectionChanged)) // column.push(Text::new(item)) } ); let content = Scrollable::new(&mut self.scroll) .push(content.width(Length::Fill)); Container::new(content).style(style::ListView) } fn push(&mut self, label: &str) { let index = self.items.len(); let item = ListItem::new(index, label); self.items.push(item); } fn remove(&mut self) { if let Some(i) = self.selected { self.items.remove(i); self.items = self.items.iter() .enumerate() .map(|(j, item)| ListItem::new(j, &item.label)) .collect(); self.selected = None; } } fn replace(&mut self, label: &str) { if let Some(i) = self.selected { let item = ListItem::new(i, label); self.items[i] = item; } } } #[derive(Debug, Clone)] enum Message { CreatePressed, UpdatePressed, DeletePressed, FilterUpdated(String), NameUpdated(String), SurnameUpdated(String), SelectionChanged(usize), } // To simplify the data model fields #[derive(Default)] struct InputData { value: String, state: text_input::State } #[derive(Default)] struct CRUD { names: List, input_filter: InputData, input_name: InputData, input_surname: InputData, btn_create: button::State, btn_update: button::State, btn_delete: button::State, } impl CRUD { fn make_name(&self) -> String { format!("{}, {}", self.input_surname.value, self.input_name.value) } } impl Sandbox for CRUD { type Message = Message; fn new() -> Self { Self::default() } fn title(&self) -> String { String::from("C.R.U.D.") } fn update(&mut self, message:Message) { match message { Message::FilterUpdated(s) => self.input_filter.value = s, Message::NameUpdated(s) => self.input_name.value = s, Message::SurnameUpdated(s) => self.input_surname.value = s, Message::SelectionChanged(i) => self.names.selected = Some(i), Message::CreatePressed => self.names.push(&self.make_name()), Message::UpdatePressed => self.names.replace(&self.make_name()), Message::DeletePressed => self.names.remove(), } } fn view(&mut self) -> Element<Message> { let in_filter = TextInput::new( &mut self.input_filter.state, "Filter", &self.input_filter.value, Message::FilterUpdated ) .padding(PAD_SMALL) .width(Length::Units(TEXTINPUT_WIDTH)); let header = Row::new() .align_items(Align::Center) .spacing(SPACING) .height(Length::Shrink) .push(Text::new("Filter Prefix:".to_string())) .push(in_filter); let btn_create = Button::new(&mut self.btn_create, Text::new("Create".to_string()) .horizontal_alignment(HorizontalAlignment::Center) .width(Length::Fill) ).on_press(Message::CreatePressed); let btn_update = Button::new(&mut self.btn_update, Text::new("Update".to_string()) .horizontal_alignment(HorizontalAlignment::Center) .width(Length::Fill) ).on_press(Message::UpdatePressed); let btn_delete = Button::new(&mut self.btn_delete, Text::new("Delete".to_string()) .horizontal_alignment(HorizontalAlignment::Center) .width(Length::Fill) ).on_press(Message::DeletePressed); let footer = Row::new() .spacing(SPACING) .push(btn_create) .push(btn_update) .push(btn_delete) .height(Length::Shrink); let left = self.names.view(&self.input_filter.value) .width(Length::Fill) .height(Length::Fill); let in_name = TextInput::new( &mut self.input_name.state, "Name", &self.input_name.value, Message::NameUpdated ) .padding(2) .width(Length::Units(TEXTINPUT_WIDTH)); let in_surname = TextInput::new( &mut self.input_surname.state, "Surname", &self.input_surname.value, Message::SurnameUpdated ) .padding(PAD_SMALL) .width(Length::Units(TEXTINPUT_WIDTH)); let right1 = Row::new() .push(Text::new("Name: ")) .push(in_name); let right2 = Row::new() .push(Text::new("Surname: ")) .push(in_surname); let right = Column::new() .spacing(SPACING) .align_items(Align::End) .push(right1) .push(right2); let body = Row::new() .spacing(PAD) .push(left) .push(right) .height(Length::Fill); Column::new() .padding(PAD) .spacing(SPACING) .push(header) .push(body) .push(footer) .into() } } mod style { pub struct ListView; use iced::{container, Background, Color}; impl container::StyleSheet for ListView { fn style(&self) -> container::Style { container::Style { border_color: Color::BLACK, border_width: 2., border_radius: 5., background: Some(Background::from(Color::from_rgb(0.95, 0.95, 0.95))), ..container::Style::default() } } } }
fn main() { /* A macro is code that writes code, saving us some time. println! and vec! are macros that generate code, they do not have a pre-determined number of parameters. */ // Here is the vector macro which is a declarative macro { // This brings the macro into the scope when the create is imported. #[macro_export] macro_rules! vec { // ( $( $x:expr ),* ) is a pattern matcher that executes the macro if it matches ( $( $x:expr ),* ) => { { let mut temp_vec = Vec::new(); // This is generated for each part that matches the pattern $( temp_vec.push($x); )* temp_vec } }; } } // More macros in the other project }
extern crate error_chain; extern crate serde_derive; extern crate serde_json; extern crate reqwest; use super::card; error_chain! { foreign_links { Reqwest(reqwest::Error); } } pub struct QueryResults { pub cards: Vec<card::Card>, pub not_found: Vec<String>, } #[derive(Deserialize, Debug, Clone)] struct Card { id: String, name: String, uri: String, scryfall_uri: String, rulings_uri: String, layout: String, mana_cost: Option<String>, cmc: f64, color_identity: Vec<String>, colors: Option<Vec<String>>, set_name: String, type_line: String, oracle_text: Option<String>, card_faces: Option<Vec<CardFace>>, legalities: CardLegalities, rarity: String, image_uris: Option<CardImagery>, power: Option<String>, toughness: Option<String>, loyalty: Option<String>, } #[derive(Deserialize, Debug, Clone)] struct CardFace { name: String, mana_cost: String, type_line: String, colors: Option<Vec<String>>, oracle_text: String, image_uris: Option<CardImagery>, power: Option<String>, toughness: Option<String>, loyalty: Option<String>, } #[derive(Deserialize, Debug, Clone)] struct CardLegalities { standard: String, future: String, frontier: String, modern: String, legacy: String, pauper: String, vintage: String, penny: String, commander: String, duel: String, } #[derive(Deserialize, Debug, Clone)] struct CardImagery { png: String, large: String, normal: String, small: String, border_crop: String, art_crop: String, } #[derive(Deserialize, Debug, Clone)] struct CardList { data: Vec<Card>, not_found: Vec<CardIdentifier>, } #[derive(Serialize, Deserialize, Debug, Clone)] struct CardIdentifier { name: String, } #[derive(Serialize, Debug, Clone)] struct CardIdentifiers { identifiers: Vec<CardIdentifier>, } pub fn query(card_names: Vec<String>) -> Result<QueryResults> { let request_url = format!("https://api.scryfall.com/cards/collection"); let card_query = CardIdentifiers { identifiers: card_names.iter().map(|card_name| { CardIdentifier { name: card_name.clone() } }).collect() }; let serialized = serde_json::to_string(&card_query).unwrap(); let client = reqwest::Client::new(); let mut response = client.post(&request_url) .header(reqwest::header::CONTENT_TYPE, "application/json") .body(serialized) .send()?; let text = response.text()?; let cardlist: CardList = serde_json::from_str(&text).unwrap(); let result = dto_to_cards(cardlist); Ok(result) } fn dto_to_cards(cardlist: CardList) -> QueryResults { let not_found = cardlist.not_found.into_iter().map(|ident|{ ident.name }).collect(); let cards = cardlist.data.into_iter().map(|card|{ let colors = card.colors.clone(); let image_uris = card.image_uris.clone(); let info: card::CardInfo = match card.card_faces { Some(faces) => { match card.layout.as_ref() { "split" => { card::CardInfo::Split (faces.into_iter().map(|face|{ println!("{:?}", &face); let card_type = dto_to_type(&face.type_line, face.power, face.toughness, face.loyalty); card::CardFaceInfo { card_type, colors: face.colors.unwrap_or_else(||colors.clone().unwrap_or(Vec::new())), image_uris: dto_to_imagery(face.image_uris.unwrap_or_else(||image_uris.clone().unwrap())), mana_cost: face.mana_cost, name: face.name, oracle_text: face.oracle_text, type_line: face.type_line, } }).collect()) } "flip" => { card::CardInfo::Flip (faces.into_iter().map(|face|{ println!("{:?}", &face); let card_type = dto_to_type(&face.type_line, face.power, face.toughness, face.loyalty); card::CardFaceInfo { card_type, colors: face.colors.unwrap_or_else(||colors.clone().unwrap_or(Vec::new())), image_uris: dto_to_imagery(face.image_uris.unwrap_or_else(||image_uris.clone().unwrap())), mana_cost: face.mana_cost, name: face.name, oracle_text: face.oracle_text, type_line: face.type_line, } }).collect()) } _ => { card::CardInfo::Multifaced (faces.into_iter().map(|face|{ println!("{:?}", &face); let card_type = dto_to_type(&face.type_line, face.power, face.toughness, face.loyalty); card::CardFaceInfo { card_type, colors: face.colors.unwrap_or_else(||colors.clone().unwrap_or(Vec::new())), image_uris: dto_to_imagery(face.image_uris.unwrap_or_else(||image_uris.clone().unwrap())), mana_cost: face.mana_cost, name: face.name, oracle_text: face.oracle_text, type_line: face.type_line, } }).collect()) } } } None => { let card_type = dto_to_type(&card.type_line, card.power, card.toughness, card.loyalty); card::CardInfo::Normal (card::CardFaceInfo { card_type, colors: card.colors.unwrap(), image_uris: dto_to_imagery(card.image_uris.unwrap()), mana_cost: card.mana_cost.unwrap(), name: card.name.clone(), oracle_text: card.oracle_text.unwrap(), type_line: card.type_line.clone(), }) } }; let legalities = dto_to_legalities(card.legalities); card::Card{ id: card.id, uri: card.uri, scryfall_uri: card.scryfall_uri, rulings_uri: card.rulings_uri, name: card.name, cmc: card.cmc, color_identity: card.color_identity, type_line: card.type_line, layout: card.layout, set_name: card.set_name, rarity: card.rarity, info, legalities, } }).collect(); QueryResults { cards, not_found, } } fn dto_to_type(type_line: &String, power: Option<String>, toughness: Option<String>, loyalty: Option<String>) -> card::CardType { //FIXME Doesn't properly detect Legendary or multitype if type_line.starts_with("Planeswalker") { card::CardType::Planeswalker {loyalty: loyalty.unwrap()} } else if type_line.contains("Creature") || type_line.contains("Vehicle") { card::CardType::Creature {power: power.unwrap(), toughness: toughness.unwrap()} } else { card::CardType::NonCreature } } fn dto_to_legalities(leg: CardLegalities) -> card::CardLegalities { card::CardLegalities { standard: leg.standard, future: leg.future, frontier: leg.frontier, modern: leg.modern, legacy: leg.legacy, pauper: leg.pauper, vintage: leg.vintage, penny: leg.penny, commander: leg.commander, duel: leg.duel, } } fn dto_to_imagery(im: CardImagery) -> card::CardImagery { card::CardImagery { png: im.png, large: im.large, normal: im.normal, small: im.small, border_crop: im.border_crop, art_crop: im.art_crop, } }
use crate::mesh::*; use crate::texture::*; use nalgebra_glm as glm; use std::path::{Path, PathBuf}; #[derive(Default)] pub struct Model { meshes: Vec<Mesh>, } impl Model { pub fn from_file(path: &str) -> Self { let path = Path::new(path); let root_dir = Path::new(path.parent().unwrap()); let (models, materials) = tobj::load_obj(&path).unwrap(); let mut meshes = Vec::new(); for model in models.iter() { let mesh_data = &model.mesh; let mut vertices = Vec::new(); for index in 0..mesh_data.positions.len() / 3 { let vertex = Vertex::new( glm::vec3( mesh_data.positions[index * 3], mesh_data.positions[index * 3 + 1], mesh_data.positions[index * 3 + 2], ), glm::vec3( mesh_data.normals[index * 3], mesh_data.normals[index * 3 + 1], mesh_data.normals[index * 3 + 2], ), glm::vec2( mesh_data.texcoords[index * 2], mesh_data.texcoords[index * 2 + 1], ), ); vertices.push(vertex); } let mut textures = Vec::new(); let material = &materials[mesh_data.material_id.unwrap()]; let mut diffuse_texture_path = PathBuf::from(root_dir); diffuse_texture_path.push(&material.diffuse_texture); // TODO: Push other textures and add error handling // TODO: Use a texture cache let texture = Texture::from_file(diffuse_texture_path.as_path().as_os_str().to_str().unwrap()); textures.push(texture); meshes.push(Mesh::new(vertices, mesh_data.indices.clone(), textures)); } Model { meshes } } pub fn render(&self) { for mesh in self.meshes.iter() { mesh.render(); } } }
use std::collections::hash_map::RandomState; use std::collections::HashMap; use std::convert::TryFrom; use std::io; use employee_list::print::eprint_list; use employee_list::{run, Command, Employees}; fn main() { eprint_commands(); let s = RandomState::new(); let mut employees: Employees = HashMap::with_hasher(s); loop { eprint!("> "); let mut input = String::new(); io::stdin() .read_line(&mut input) .expect("Failed to read line"); let input = input.trim(); if input == "End" { break; } match Command::try_from(input) { Ok(command) => run(command, &mut employees), Err(e) => eprintln!("{}", e), } } } fn eprint_commands() { let commands = [ "Add <PERSON> to <DEPARTMENT>", "List <DEPARTMENT>", "List", "End", ]; eprint_list("Commands", &commands); }
//! Raspberry PI 3 Model B/B+ use bcm2837::{addr::bus_to_phys, atags::Atags}; pub mod emmc; pub mod irq; pub mod mailbox; pub mod serial; pub mod timer; pub mod gpu; use crate::drivers::gpu::fb::{self, ColorDepth, ColorFormat, FramebufferInfo, FramebufferResult}; use crate::consts::{KERNEL_OFFSET}; use core::convert::TryInto; use gpu::*; pub const BOARD_NAME: &'static str = "Raspberry Pi 3"; pub const PERIPHERALS_START: usize = bcm2837::addr::PERIPHERALS_START; pub const PERIPHERALS_END: usize = bcm2837::addr::PERIPHERALS_END; pub const CPU_NUM: usize = 4; /// BCM2837 spin table (ref: linux/arch/arm/boot/dts/bcm2837.dtsi) #[no_mangle] pub static CPU_SPIN_TABLE: [usize; CPU_NUM] = [0xd8, 0xe0, 0xe8, 0xf0]; /// Initialize serial port before other initializations. pub fn init_serial_early() { serial::init(); } /// Initialize raspi3 drivers pub fn init_driver() { if let Ok(fb_info) = probe_fb_info(0, 0, 0) { fb::init(fb_info); } emmc::init(); } /// Returns the (start address, end address) of the physical memory on this /// system if it can be determined. If it cannot, `None` is returned. /// /// This function is expected to return `Some` under all normal cirumstances. pub fn probe_memory() -> Option<(usize, usize)> { let mut atags: Atags = Atags::get(); while let Some(atag) = atags.next() { if let Some(mem) = atag.mem() { return Some((mem.start as usize, (mem.start + mem.size) as usize)); } } None } fn probe_fb_info(width: u32, height: u32, depth: u32) -> FramebufferResult { let (width, height) = if width == 0 || height == 0 { mailbox::framebuffer_get_physical_size()? } else { (width, height) }; let depth = if depth == 0 { mailbox::framebuffer_get_depth()? } else { depth }; println!("get framebuffer size from mailbox, height: {}, width: {}, depth: {}", height, width, depth); let info = mailbox::framebuffer_alloc(width, height, depth)?; if info.bus_addr == 0 || info.screen_size == 0 { Err(format!("mailbox call returned an invalid address/size"))?; } if info.pitch == 0 || info.pitch != info.xres * info.depth / 8 { Err(format!( "mailbox call returned an invalid pitch value {}", info.pitch ))?; } println!("set framebuffer with xres: {}, yres: {}, pitch: {}, addr: {:#x}, screen_size: {}", info.xres, info.yres, info.pitch, info.bus_addr, info.screen_size); let paddr = bus_to_phys(info.bus_addr); let vaddr = super::memory::ioremap(paddr as usize, info.screen_size as usize, "fb"); println!("paddr: {:#x}, vaddr: {:#x}", paddr, vaddr); if vaddr == 0 { Err(format!( "cannot remap memory range [{:#x?}..{:#x?}]", paddr, paddr + info.screen_size ))?; } let depth = ColorDepth::try_from(info.depth)?; let format = match info.depth { 16 => ColorFormat::RGB565, 32 => ColorFormat::BGRA8888, _ => Err(format!("unsupported color depth {}", info.depth))?, }; Ok(FramebufferInfo { xres: info.xres, yres: info.yres, xres_virtual: info.xres_virtual, yres_virtual: info.yres_virtual, xoffset: info.xoffset, yoffset: info.yoffset, depth: depth, format: format, paddr: paddr as usize, vaddr: vaddr, screen_size: info.screen_size as usize, }) } //hackdrivers pub fn test_gpu() { if (mailbox::gpu_enable().is_ok()) { println!("enable success"); } let bus_addr: usize = 0x3fc00000; let paddr: usize = 0x3fc00000; let vaddr = paddr.wrapping_add(KERNEL_OFFSET); println!("vaddr: {:#x}", vaddr); let accessible = vaddr; let mut ans = 0; unsafe { ans = *(accessible as *mut u32); } println!("status: {}", ans); if (ans != 0x02443356) { // Magic number. println!("Error: V3D pipeline isn't powered up and accessable.\n"); return; } else { println!("Success: V3D pipline has powered up\n"); } unsafe { test_triangle(vaddr); } } pub unsafe fn addbyte(p: &mut usize, d: u8) { *(*p as *mut u8) = d; *p = *p + 1; } pub unsafe fn addword(p: &mut usize, d: u32) { *(*p as *mut u8) = (d & 0xff).try_into().unwrap(); *p = *p + 1; *(*p as *mut u8) = ((d >> 8) & 0xff).try_into().unwrap(); *p = *p + 1; *(*p as *mut u8) = ((d >> 16) & 0xff).try_into().unwrap(); *p = *p + 1; *(*p as *mut u8) = ((d >> 24) & 0xff).try_into().unwrap(); *p = *p + 1; } pub unsafe fn addshort(p: &mut usize, d: u16) { *(*p as *mut u8) = (d & 0xff).try_into().unwrap();; *p = *p + 1; *(*p as *mut u8) = ((d >> 8) & 0xff).try_into().unwrap(); *p = *p + 1; } pub unsafe fn addfloat(p: &mut usize, f: f32) { let fp = &f as *const f32; let dp = fp as *const u32; addword(p, *dp); } pub unsafe fn setV3D(v3d: usize, offset: usize, data: u32) { let tmp = v3d + offset * 4; *(tmp as *mut u32) = data; } pub unsafe fn getV3D(v3d: usize, offset: usize) -> u32 { let tmp = v3d + offset * 4; *(tmp as *mut u32) } pub unsafe fn test_triangle(v3d: usize) { let handle = mailbox::mem_alloc(0x800000, 0x1000, mailbox::MEM_FLAG_COHERENT | mailbox::MEM_FLAG_ZERO).unwrap(); println!("Successfully allocate memory, handle: {}", handle); let bus_addr = mailbox::mem_lock(handle).unwrap(); println!("Bus address: {:#x}", bus_addr); let paddr = bus_to_phys(bus_addr); let vaddr = super::memory::ioremap(paddr as usize, 0x800000, "triangle"); let mut p = vaddr; let mut list = vaddr; addbyte(&mut p, 112); addword(&mut p, bus_addr + 0x6200); // tile allocation memory address addword(&mut p, 0x8000); // tile allocation memory size addword(&mut p, bus_addr + 0x100); // Tile state data address addbyte(&mut p, 30); // 1920/64 addbyte(&mut p, 17); // 1080/64 (16.875) addbyte(&mut p, 0x04); // config // Start tile binning. addbyte(&mut p, 6); // Primitive type addbyte(&mut p, 56); addbyte(&mut p, 0x32); // 16 bit triangle // Clip Window addbyte(&mut p, 102); addshort(&mut p, 0); addshort(&mut p, 0); addshort(&mut p, 1920); // width addshort(&mut p, 1080); // height // State addbyte(&mut p, 96); addbyte(&mut p, 0x03); // enable both foward and back facing polygons addbyte(&mut p, 0x00); // depth testing disabled addbyte(&mut p, 0x02); // enable early depth write // Viewport offset addbyte(&mut p, 103); addshort(&mut p, 0); addshort(&mut p, 0); // The triangle // No Vertex Shader state (takes pre-transformed vertexes, // so we don't have to supply a working coordinate shader to test the binner. addbyte(&mut p, 65); addword(&mut p, bus_addr + 0x80); // Shader Record // primitive index list addbyte(&mut p, 32); addbyte(&mut p, 0x04); // 8bit index, trinagles addword(&mut p, 3); // Length addword(&mut p, bus_addr + 0x70); // address addword(&mut p, 2); // Maximum index // End of bin list // Flush addbyte(&mut p, 5); // Nop addbyte(&mut p, 1); // Halt addbyte(&mut p, 0); let length = p - list; //assert(length < 0x80); // Shader Record p = list + 0x80; addbyte(&mut p, 0x01); // flags addbyte(&mut p, 6*4); // stride addbyte(&mut p, 0xcc); // num uniforms (not used) addbyte(&mut p, 3); // num varyings addword(&mut p, bus_addr + 0xfe00); // Fragment shader code addword(&mut p, bus_addr + 0xff00); // Fragment shader uniforms addword(&mut p, bus_addr + 0xa0); // Vertex Data // Vertex Data p = list + 0xa0; // Vertex: Top, red addshort(&mut p, (1920/2) << 4); // X in 12.4 fixed point addshort(&mut p, 200 << 4); // Y in 12.4 fixed point addfloat(&mut p, 1.0); // Z addfloat(&mut p, 1.0); // 1/W addfloat(&mut p, 1.0); // Varying 0 (Red) addfloat(&mut p, 0.0); // Varying 1 (Green) addfloat(&mut p, 0.0); // Varying 2 (Blue) // Vertex: bottom left, Green addshort(&mut p, 560 << 4); // X in 12.4 fixed point addshort(&mut p, 800 << 4); // Y in 12.4 fixed point addfloat(&mut p, 1.0); // Z addfloat(&mut p, 1.0); // 1/W addfloat(&mut p, 0.0); // Varying 0 (Red) addfloat(&mut p, 1.0); // Varying 1 (Green) addfloat(&mut p, 0.0); // Varying 2 (Blue) // Vertex: bottom right, Blue addshort(&mut p, 1360 << 4); // X in 12.4 fixed point addshort(&mut p, 800 << 4); // Y in 12.4 fixed point addfloat(&mut p, 1.0); // Z addfloat(&mut p, 1.0); // 1/W addfloat(&mut p, 0.0); // Varying 0 (Red) addfloat(&mut p, 0.0); // Varying 1 (Green) addfloat(&mut p, 1.0); // Varying 2 (Blue) // Vertex list p = list + 0x70; addbyte(&mut p, 0); // top addbyte(&mut p, 1); // bottom left addbyte(&mut p, 2); // bottom right // fragment shader p = list + 0xfe00; addword(&mut p, 0x958e0dbf); addword(&mut p, 0xd1724823); /* mov r0, vary; mov r3.8d, 1.0 */ addword(&mut p, 0x818e7176); addword(&mut p, 0x40024821); /* fadd r0, r0, r5; mov r1, vary */ addword(&mut p, 0x818e7376); addword(&mut p, 0x10024862); /* fadd r1, r1, r5; mov r2, vary */ addword(&mut p, 0x819e7540); addword(&mut p, 0x114248a3); /* fadd r2, r2, r5; mov r3.8a, r0 */ addword(&mut p, 0x809e7009); addword(&mut p, 0x115049e3); /* nop; mov r3.8b, r1 */ addword(&mut p, 0x809e7012); addword(&mut p, 0x116049e3); /* nop; mov r3.8c, r2 */ addword(&mut p, 0x159e76c0); addword(&mut p, 0x30020ba7); /* mov tlbc, r3; nop; thrend */ addword(&mut p, 0x009e7000); addword(&mut p, 0x100009e7); /* nop; nop; nop */ addword(&mut p, 0x009e7000); addword(&mut p, 0x500009e7); /* nop; nop; sbdone */ // Render control list p = list + 0xe200; // Clear color addbyte(&mut p, 114); addword(&mut p, 0xff000000); // Opaque Black addword(&mut p, 0xff000000); // 32 bit clear colours need to be repeated twice addword(&mut p, 0); addbyte(&mut p, 0); // Tile Rendering Mode Configuration addbyte(&mut p, 113); addword(&mut p, bus_addr + 0x10000); // framebuffer addresss addshort(&mut p, 1920); // width addshort(&mut p, 1080); // height addbyte(&mut p, 0x04); // framebuffer mode (linear rgba8888) addbyte(&mut p, 0x00); // Do a store of the first tile to force the tile buffer to be cleared // Tile Coordinates addbyte(&mut p, 115); addbyte(&mut p, 0); addbyte(&mut p, 0); // Store Tile Buffer General addbyte(&mut p, 28); addshort(&mut p, 0); // Store nothing (just clear) addword(&mut p, 0); // no address is needed // Link all binned lists together for x in 0..30 { for y in 0..17 { // Tile Coordinates addbyte(&mut p, 115); addbyte(&mut p, x); addbyte(&mut p, y); // Call Tile sublist addbyte(&mut p, 17); addword(&mut p, bus_addr + 0x6200 + (y as u32 * 30 + x as u32) * 32); // Last tile needs a special store instruction if(x == 29 && y == 16) { // Store resolved tile color buffer and signal end of frame addbyte(&mut p, 25); } else { // Store resolved tile color buffer addbyte(&mut p, 24); } } } let render_length = p - (list + 0xe200); // Run our control list println!("Binner control list constructed"); println!("Start Address: {:#x}, length: {:#x}", bus_addr, length); setV3D(v3d, V3D_CT0CA, bus_addr); setV3D(v3d, V3D_CT0EA, bus_addr + length as u32); println!("V3D_CT0CS: {:#x}, Address: {:#x}", getV3D(v3d, V3D_CT0CS), getV3D(v3d, V3D_CT0CA)); // v3d[V3D_CT0CA] = bus_addr; // v3d[V3D_CT0EA] = bus_addr + length; // printf("V3D_CT0CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT0CS], v3d[V3D_CT0CA]); // Wait for control list to execute while (getV3D(v3d, V3D_CT0CS) & 0x20) > 0 {} //while(v3d[V3D_CT0CS] & 0x20); println!("V3D_CT0CS: {:#x}, Address: {:#x}", getV3D(v3d, V3D_CT0CS), getV3D(v3d, V3D_CT1CA)); println!("V3D_CT1CS: {:#x}, Address: {:#x}", getV3D(v3d, V3D_CT1CS), getV3D(v3d, V3D_CT1CA)); //printf("V3D_CT0CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT0CS], v3d[V3D_CT0CA]); //printf("V3D_CT1CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT1CS], v3d[V3D_CT1CA]); setV3D(v3d, V3D_CT1CA, bus_addr + 0xe200); setV3D(v3d, V3D_CT1EA, bus_addr + 0xe200 + render_length as u32); //v3d[V3D_CT1CA] = bus_addr + 0xe200; //v3d[V3D_CT1EA] = bus_addr + 0xe200 + render_length; while (getV3D(v3d, V3D_CT1CS) & 0x20) > 0 {} //while(v3d[V3D_CT1CS] & 0x20); println!("V3D_CT1CS`: {:#x}, address: {:#x}", getV3D(v3d, V3D_CT1CS), getV3D(v3d, V3D_CT1CA)); setV3D(v3d, V3D_CT1CS, 0x20); //pintf("V3D_CT1CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT1CS], v3d[V3D_CT1CA]); //v3d[V3D_CT1CS] = 0x20; // // just dump the frame to a file // FILE *f = fopen("frame.data", "w"); // fwrite(list + 0x10000, (1920*1080*4), 1, f); // fclose(f); // printf("frame buffer memory dumpped to frame.data\n"); let begin = list + 0x10000; let mut lock = fb::FRAME_BUFFER.lock(); if let Some(fbr) = lock.as_mut() { for x in 0..fbr.fb_info.xres { for y in 0..fbr.fb_info.yres { let mut color: u32 = 0; let pos = begin + 4 * x as usize + 1920 * 4 * y as usize; color = *(pos as *mut u32); fbr.write(x, y, color); } } } // Release resources // super::memory:: // unmapmem((void *) list, 0x800000); // mem_unlock(mbox, handle); // mem_free(mbox, handle); println!("gpu calculate over!"); }
use scrabble_score::*; use std::collections::HashMap; #[test] fn a_is_worth_one_point() { assert_eq!(score("a"), 1); } #[test] fn scoring_is_case_insensitive() { assert_eq!(score("A"), 1); } #[test] fn f_is_worth_four() { assert_eq!(score("f"), 4); } #[test] fn two_one_point_letters_make_a_two_point_word() { assert_eq!(score("at"), 2); } #[test] fn three_letter_word() { assert_eq!(score("zoo"), 12); } #[test] fn medium_word() { assert_eq!(score("street"), 6); } #[test] fn longer_words_with_valuable_letters() { assert_eq!(score("quirky"), 22); } #[test] fn long_mixed_case_word() { assert_eq!(score("OxyphenButazone"), 41); } #[test] fn non_english_scrabble_letters_do_not_score() { assert_eq!(score("pinata"), 8, "'n' should score 1"); assert_eq!(score("piñata"), 7, "'ñ' should score 0"); } #[test] fn empty_words_are_worth_zero() { assert_eq!(score(""), 0); } #[test] fn all_letters_work() { assert_eq!(score("abcdefghijklmnopqrstuvwxyz"), 87); } #[test] fn german_letters_do_not_score() { assert_eq!(score("STRASSE"), 7, "\"SS\" should score 2"); assert_eq!(score("STRAßE"), 5, "'ß' should score 0"); } #[test] fn score_with_word_multiplier() { assert_eq!(score("abc"), 7, "\"abc\" should score 7"); let no_letter_multipliers = HashMap::new(); assert_eq!( score_with_multipliers("abc", 2, &no_letter_multipliers), 14, "\"abc\" with double word should score 14" ); assert_eq!( score_with_multipliers("abc", 3, &no_letter_multipliers), 21, "\"abc\" with triple word should score 21" ); } #[test] fn score_with_letter_multiplier() { assert_eq!(score("abc"), 7, "\"abc\" should score 7"); let mut double_b = HashMap::new(); double_b.insert(1, 2); assert_eq!( score_with_multipliers("abc", 1, &double_b), 10, "\"abc\" with double B should score 10" ); let mut double_a = HashMap::new(); double_a.insert(0, 2); assert_eq!( score_with_multipliers("abc", 1, &double_a), 8, "\"abc\" with double A should score 8" ); let mut triple_c = HashMap::new(); triple_c.insert(2, 3); assert_eq!( score_with_multipliers("abc", 1, &triple_c), 13, "\"abc\" with double word should score 13" ); } #[test] fn score_with_word_and_letter_multiplier() { assert_eq!(score("abc"), 7, "\"abc\" should score 7"); let mut double_b = HashMap::new(); double_b.insert(1, 2); assert_eq!( score_with_multipliers("abc", 2, &double_b), 20, "\"abc\" with double B and double word should score 20" ); }
use crate::object::Object; use crate::service::*; use crate::errors::EvalErr; use std::rc::Rc; /// The family of functions which names match with pattern `c[ad]{1,4}r`. pub fn cadr(name: &str, obj: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> { let mut obj = expect_1_arg(obj, name)?; for op in name[1..name.len() - 1].chars().rev() { let pair = check_pair(&obj)?; obj = Rc::clone(if op == 'a' { pair.0 } else { pair.1 }); } Ok(obj) } pub fn cons(obj: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> { let (car, cdr) = expect_2_args(obj, "cons")?; Ok(Rc::new(Object::Pair(car, cdr))) } pub fn list(obj: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> { Ok(Rc::new(vec_to_list(&obj))) } pub fn length(obj: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> { let len = list_to_vec(expect_1_arg(obj, "length")?.as_ref())?.len(); Ok(Rc::new(Object::make_int(len as i64))) } pub fn is_pair(obj: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> { let arg = expect_1_arg(obj, "pair?")?; Ok(Rc::new(Object::Boolean(check_pair(&arg).is_ok()))) } pub fn is_list(obj: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> { let arg = expect_1_arg(obj, "list?")?; Ok(Rc::new(Object::Boolean(list_to_vec(&arg).is_ok()))) } pub fn is_null(obj: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> { let arg = expect_1_arg(obj, "null?")?; Ok(Rc::new(Object::Boolean(arg.is_nil()))) }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type BindableVectorChangedEventHandler = *mut ::core::ffi::c_void; pub type IBindableIterable = *mut ::core::ffi::c_void; pub type IBindableIterator = *mut ::core::ffi::c_void; pub type IBindableObservableVector = *mut ::core::ffi::c_void; pub type IBindableVector = *mut ::core::ffi::c_void; pub type IBindableVectorView = *mut ::core::ffi::c_void; pub type INotifyCollectionChanged = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct NotifyCollectionChangedAction(pub i32); impl NotifyCollectionChangedAction { pub const Add: Self = Self(0i32); pub const Remove: Self = Self(1i32); pub const Replace: Self = Self(2i32); pub const Move: Self = Self(3i32); pub const Reset: Self = Self(4i32); } impl ::core::marker::Copy for NotifyCollectionChangedAction {} impl ::core::clone::Clone for NotifyCollectionChangedAction { fn clone(&self) -> Self { *self } } pub type NotifyCollectionChangedEventArgs = *mut ::core::ffi::c_void; pub type NotifyCollectionChangedEventHandler = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct TypeKind(pub i32); impl TypeKind { pub const Primitive: Self = Self(0i32); pub const Metadata: Self = Self(1i32); pub const Custom: Self = Self(2i32); } impl ::core::marker::Copy for TypeKind {} impl ::core::clone::Clone for TypeKind { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct TypeName { pub Name: ::windows_sys::core::HSTRING, pub Kind: TypeKind, } impl ::core::marker::Copy for TypeName {} impl ::core::clone::Clone for TypeName { fn clone(&self) -> Self { *self } }
use std::mem::size_of; enum Never { } struct ZeroSize; type NeverFailResult<T> = Result<T, Never>; type ZeroSizeResult<T> = Result<T, ZeroSize>; fn main() { println!("{}", size_of::<u32>()); // 4 println!("{}", size_of::<NeverFailResult<u32>>()); // 4 println!("{}", size_of::<Option<u32>>()); // 8 println!("{}", size_of::<NeverFailResult<Option<u32>>>()); // 8 println!("{}", size_of::<u32>()); // 4 println!("{}", size_of::<ZeroSizeResult<u32>>()); // 8 println!("{}", size_of::<Option<u32>>()); // 8 println!("{}", size_of::<ZeroSizeResult<Option<u32>>>()); // 8 }
use byteorder::LittleEndian; use crate::mysql::io::BufExt; #[derive(Debug)] pub struct ColumnCount { pub columns: u64, } impl ColumnCount { pub(crate) fn read(mut buf: &[u8]) -> crate::Result<Self> { let columns = buf.get_uint_lenenc::<LittleEndian>()?.unwrap_or(0); Ok(Self { columns }) } }
//! Unix user, group, and process identifiers. //! //! # Safety //! //! The `Uid`, `Gid`, and `Pid` types can be constructed from raw integers, //! which is marked unsafe because actual OS's assign special meaning to some //! integer values. #![allow(unsafe_code)] use crate::{backend, io}; use alloc::vec::Vec; #[cfg(linux_kernel)] use backend::process::types::RawCpuid; /// The raw integer value of a Unix user ID. pub use crate::ugid::RawUid; /// The raw integer value of a Unix group ID. pub use crate::ugid::RawGid; /// The raw integer value of a Unix process ID. pub use crate::pid::RawPid; pub use crate::pid::Pid; pub use crate::ugid::{Gid, Uid}; /// A Linux CPU ID. #[cfg(linux_kernel)] #[repr(transparent)] #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub struct Cpuid(RawCpuid); #[cfg(linux_kernel)] impl Cpuid { /// Converts a `RawCpuid` into a `Cpuid`. /// /// # Safety /// /// `raw` must be the value of a valid Linux CPU ID. #[inline] pub const unsafe fn from_raw(raw: RawCpuid) -> Self { Self(raw) } /// Converts a `Cpuid` into a `RawCpuid`. #[inline] pub const fn as_raw(self) -> RawCpuid { self.0 } } /// `getuid()`—Returns the process' real user ID. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/getuid.html /// [Linux]: https://man7.org/linux/man-pages/man2/getuid.2.html #[inline] #[must_use] pub fn getuid() -> Uid { backend::ugid::syscalls::getuid() } /// `geteuid()`—Returns the process' effective user ID. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/geteuid.html /// [Linux]: https://man7.org/linux/man-pages/man2/geteuid.2.html #[inline] #[must_use] pub fn geteuid() -> Uid { backend::ugid::syscalls::geteuid() } /// `getgid()`—Returns the process' real group ID. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/getgid.html /// [Linux]: https://man7.org/linux/man-pages/man2/getgid.2.html #[inline] #[must_use] pub fn getgid() -> Gid { backend::ugid::syscalls::getgid() } /// `getegid()`—Returns the process' effective group ID. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/getegid.html /// [Linux]: https://man7.org/linux/man-pages/man2/getegid.2.html #[inline] #[must_use] pub fn getegid() -> Gid { backend::ugid::syscalls::getegid() } /// `getpid()`—Returns the process' ID. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpid.html /// [Linux]: https://man7.org/linux/man-pages/man2/getpid.2.html #[inline] #[must_use] pub fn getpid() -> Pid { backend::pid::syscalls::getpid() } /// `getppid()`—Returns the parent process' ID. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/getppid.html /// [Linux]: https://man7.org/linux/man-pages/man2/getppid.2.html #[inline] #[must_use] pub fn getppid() -> Option<Pid> { backend::process::syscalls::getppid() } /// `getpgid(pid)`—Returns the process group ID of the given process. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpgid.html /// [Linux]: https://man7.org/linux/man-pages/man2/getpgid.2.html #[inline] pub fn getpgid(pid: Option<Pid>) -> io::Result<Pid> { backend::process::syscalls::getpgid(pid) } /// `setpgid(pid, pgid)`—Sets the process group ID of the given process. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/setpgid.html /// [Linux]: https://man7.org/linux/man-pages/man2/setpgid.2.html #[inline] pub fn setpgid(pid: Option<Pid>, pgid: Option<Pid>) -> io::Result<()> { backend::process::syscalls::setpgid(pid, pgid) } /// `getpgrp()`—Returns the process' group ID. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpgrp.html /// [Linux]: https://man7.org/linux/man-pages/man2/getpgrp.2.html #[inline] #[must_use] pub fn getpgrp() -> Pid { backend::process::syscalls::getpgrp() } /// `getsid(pid)`—Get the session ID of the given process. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/getsid.html /// [Linux]: https://man7.org/linux/man-pages/man2/getsid.2.html #[cfg(not(target_os = "redox"))] #[inline] pub fn getsid(pid: Option<Pid>) -> io::Result<Pid> { backend::process::syscalls::getsid(pid) } /// `setsid()`—Create a new session. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/setsid.html /// [Linux]: https://man7.org/linux/man-pages/man2/setsid.2.html #[inline] pub fn setsid() -> io::Result<Pid> { backend::process::syscalls::setsid() } /// `getgroups()`—Return a list of the current user's groups. /// /// # References /// - [POSIX] /// - [Linux] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/getgroups.html /// [Linux]: https://man7.org/linux/man-pages/man2/getgroups.2.html pub fn getgroups() -> io::Result<Vec<Gid>> { let mut buffer = Vec::new(); // This code would benefit from having a better way to read into // uninitialized memory, but that requires `unsafe`. buffer.reserve(8); buffer.resize(buffer.capacity(), Gid::ROOT); loop { let ngroups = backend::process::syscalls::getgroups(&mut buffer)?; let ngroups = ngroups as usize; assert!(ngroups <= buffer.len()); if ngroups < buffer.len() { buffer.resize(ngroups, Gid::ROOT); return Ok(buffer); } buffer.reserve(1); // use `Vec` reallocation strategy to grow capacity exponentially buffer.resize(buffer.capacity(), Gid::ROOT); } }
#[derive(Debug)] struct User { id: u64, name: String, sex: String, age: u8, } struct Ipv4 { ip: String, ip_address: (u8, u8, u8, u8), host: String, } struct Ipv6 { ip: String, ip_address: (u8, u8, u8, u8, u8, u8), host: String, } enum Ip { V4(Ipv4), V6(Ipv6), } pub enum State { N, M, } impl State { pub fn get_u8(&self) -> u8 { match &self { State::N => 0, State::M => 1 } } } pub enum Coin { Penny, Nickel, Quarter(State), } fn value_in_coin(coin: Coin) -> u8 { match coin { Coin::Penny => 1, Coin::Nickel => 4, Coin::Quarter(s) => s.get_u8() } } fn plus_one(x: Option<i32>) -> Option<i32> { match x { None => None, Some(i) => Some(i + 1), } } fn main() { let mut user = User { id: 10, name: String::from("yaphets"), sex: String::from("male"), age: 10, }; println!("user.id is : {}", user.id); user.name = String::from("android"); let val = value_in_coin(Coin::Quarter(State::M)); println!("now result is {}", val); // tests plus_one let five = Some(5); let six = plus_one(five); let none = plus_one(None); println!("tests plus_one result is, six = {:#?}, none = {:#?}", six, none); } struct Rng { id: u32 }
pub mod action; pub mod contract; pub mod permission; pub mod print; pub mod system; pub mod table; pub use action::*; pub use contract::*; pub use permission::*; pub use print::*; pub use system::*; pub use table::*;
use super::{FromArgs, FuncArgs}; use crate::{ convert::ToPyResult, object::PyThreadingConstraint, Py, PyPayload, PyRef, PyResult, VirtualMachine, }; use std::marker::PhantomData; /// A built-in Python function. // PyCFunction in CPython pub type PyNativeFn = py_dyn_fn!(dyn Fn(&VirtualMachine, FuncArgs) -> PyResult); /// Implemented by types that are or can generate built-in functions. /// /// This trait is implemented by any function that matches the pattern: /// /// ```rust,ignore /// Fn([&self,] [T where T: FromArgs, ...] [, vm: &VirtualMachine]) /// ``` /// /// For example, anything from `Fn()` to `Fn(vm: &VirtualMachine) -> u32` to /// `Fn(PyIntRef, PyIntRef) -> String` to /// `Fn(&self, PyStrRef, FooOptions, vm: &VirtualMachine) -> PyResult<PyInt>` /// is `IntoPyNativeFn`. If you do want a really general function signature, e.g. /// to forward the args to another function, you can define a function like /// `Fn(FuncArgs [, &VirtualMachine]) -> ...` /// /// Note that the `Kind` type parameter is meaningless and should be considered /// an implementation detail; if you need to use `IntoPyNativeFn` as a trait bound /// just pass an unconstrained generic type, e.g. /// `fn foo<F, FKind>(f: F) where F: IntoPyNativeFn<FKind>` pub trait IntoPyNativeFn<Kind>: Sized + PyThreadingConstraint + 'static { fn call(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult; /// `IntoPyNativeFn::into_func()` generates a PyNativeFn that performs the /// appropriate type and arity checking, any requested conversions, and then if /// successful calls the function with the extracted parameters. fn into_func(self) -> &'static PyNativeFn { let boxed = Box::new(move |vm: &VirtualMachine, args| self.call(vm, args)); Box::leak(boxed) } } // TODO: once higher-rank trait bounds are stabilized, remove the `Kind` type // parameter and impl for F where F: for<T, R, VM> PyNativeFnInternal<T, R, VM> impl<F, T, R, VM> IntoPyNativeFn<(T, R, VM)> for F where F: PyNativeFnInternal<T, R, VM>, { #[inline(always)] fn call(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult { self.call_(vm, args) } } mod sealed { use super::*; pub trait PyNativeFnInternal<T, R, VM>: Sized + PyThreadingConstraint + 'static { fn call_(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult; } } use sealed::PyNativeFnInternal; #[doc(hidden)] pub struct OwnedParam<T>(PhantomData<T>); #[doc(hidden)] pub struct BorrowedParam<T>(PhantomData<T>); #[doc(hidden)] pub struct RefParam<T>(PhantomData<T>); // This is the "magic" that allows rust functions of varying signatures to // generate native python functions. // // Note that this could be done without a macro - it is simply to avoid repetition. macro_rules! into_py_native_fn_tuple { ($(($n:tt, $T:ident)),*) => { impl<F, $($T,)* R> PyNativeFnInternal<($(OwnedParam<$T>,)*), R, VirtualMachine> for F where F: Fn($($T,)* &VirtualMachine) -> R + PyThreadingConstraint + 'static, $($T: FromArgs,)* R: ToPyResult, { fn call_(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult { let ($($n,)*) = args.bind::<($($T,)*)>(vm)?; (self)($($n,)* vm).to_pyresult(vm) } } impl<F, S, $($T,)* R> PyNativeFnInternal<(BorrowedParam<S>, $(OwnedParam<$T>,)*), R, VirtualMachine> for F where F: Fn(&Py<S>, $($T,)* &VirtualMachine) -> R + PyThreadingConstraint + 'static, S: PyPayload, $($T: FromArgs,)* R: ToPyResult, { fn call_(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult { let (zelf, $($n,)*) = args.bind::<(PyRef<S>, $($T,)*)>(vm)?; (self)(&zelf, $($n,)* vm).to_pyresult(vm) } } impl<F, S, $($T,)* R> PyNativeFnInternal<(RefParam<S>, $(OwnedParam<$T>,)*), R, VirtualMachine> for F where F: Fn(&S, $($T,)* &VirtualMachine) -> R + PyThreadingConstraint + 'static, S: PyPayload, $($T: FromArgs,)* R: ToPyResult, { fn call_(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult { let (zelf, $($n,)*) = args.bind::<(PyRef<S>, $($T,)*)>(vm)?; (self)(&zelf, $($n,)* vm).to_pyresult(vm) } } impl<F, $($T,)* R> PyNativeFnInternal<($(OwnedParam<$T>,)*), R, ()> for F where F: Fn($($T,)*) -> R + PyThreadingConstraint + 'static, $($T: FromArgs,)* R: ToPyResult, { fn call_(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult { let ($($n,)*) = args.bind::<($($T,)*)>(vm)?; (self)($($n,)*).to_pyresult(vm) } } impl<F, S, $($T,)* R> PyNativeFnInternal<(BorrowedParam<S>, $(OwnedParam<$T>,)*), R, ()> for F where F: Fn(&Py<S>, $($T,)*) -> R + PyThreadingConstraint + 'static, S: PyPayload, $($T: FromArgs,)* R: ToPyResult, { fn call_(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult { let (zelf, $($n,)*) = args.bind::<(PyRef<S>, $($T,)*)>(vm)?; (self)(&zelf, $($n,)*).to_pyresult(vm) } } impl<F, S, $($T,)* R> PyNativeFnInternal<(RefParam<S>, $(OwnedParam<$T>,)*), R, ()> for F where F: Fn(&S, $($T,)*) -> R + PyThreadingConstraint + 'static, S: PyPayload, $($T: FromArgs,)* R: ToPyResult, { fn call_(&self, vm: &VirtualMachine, args: FuncArgs) -> PyResult { let (zelf, $($n,)*) = args.bind::<(PyRef<S>, $($T,)*)>(vm)?; (self)(&zelf, $($n,)*).to_pyresult(vm) } } }; } into_py_native_fn_tuple!(); into_py_native_fn_tuple!((v1, T1)); into_py_native_fn_tuple!((v1, T1), (v2, T2)); into_py_native_fn_tuple!((v1, T1), (v2, T2), (v3, T3)); into_py_native_fn_tuple!((v1, T1), (v2, T2), (v3, T3), (v4, T4)); into_py_native_fn_tuple!((v1, T1), (v2, T2), (v3, T3), (v4, T4), (v5, T5)); into_py_native_fn_tuple!((v1, T1), (v2, T2), (v3, T3), (v4, T4), (v5, T5), (v6, T6)); into_py_native_fn_tuple!( (v1, T1), (v2, T2), (v3, T3), (v4, T4), (v5, T5), (v6, T6), (v7, T7) ); #[cfg(test)] mod tests { use super::*; #[test] fn test_into_native_fn_noalloc() { let check_zst = |f: &'static PyNativeFn| assert_eq!(std::mem::size_of_val(f), 0); fn py_func(_b: bool, _vm: &crate::VirtualMachine) -> i32 { 1 } check_zst(py_func.into_func()); let empty_closure = || "foo".to_owned(); check_zst(empty_closure.into_func()); } }
mod boxed; mod path_ext; mod types; #[cfg(feature = "util")] pub mod util; pub use self::{ boxed::{vfs_box, vpath_box, VFSBox, VFileBox, VMetadataBox, VPathBox}, path_ext::VPathExt, types::*, };
pub struct Solution; impl Solution { pub fn simplify_path(path: String) -> String { let mut dir_names = Vec::new(); let mut cur_dir = String::new(); for c in path.chars().skip(1) { if c == '/' { dir_names.push(cur_dir); cur_dir = String::new(); } else { cur_dir.push(c); } } if !cur_dir.is_empty() { dir_names.push(cur_dir); } let mut new_dir_names = Vec::new(); for dir_name in dir_names { if dir_name == "" || dir_name == "." { } else if dir_name == ".." { new_dir_names.pop(); } else { new_dir_names.push(dir_name); } } if new_dir_names.is_empty() { "/".to_string() } else { let mut path = String::new(); for dir_name in new_dir_names { path.push('/'); path.push_str(&dir_name); } path } } } #[test] fn test0071() { assert_eq!( Solution::simplify_path("/home/".to_string()), "/home".to_string() ); assert_eq!(Solution::simplify_path("/../".to_string()), "/".to_string()); assert_eq!( Solution::simplify_path("/home//foo/".to_string()), "/home/foo".to_string() ); assert_eq!( Solution::simplify_path("/a/./b/../../c/".to_string()), "/c".to_string() ); assert_eq!( Solution::simplify_path("/a/../../b/../c//.//".to_string()), "/c".to_string() ); assert_eq!( Solution::simplify_path("/a//b////c/d//././/..".to_string()), "/a/b/c".to_string() ); }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! The special-purpose event loop used by the network manager. //! //! This event loop takes in events from Admin and State FIDL, //! and implements handlers for FIDL calls. //! //! This is implemented with a single mpsc queue for all event types - `EventLoop` holds the //! consumer, and any event handling that requires state within `EventLoop` holds a producer, //! allowing it to delegate work to the `EventLoop` by sending a message. In this documentation, we //! call anything that holds a producer a "worker". //! //! Having a single queue for all of the message types is beneficial, since in guarantees a FIFO //! ordering for all messages - whichever messages arrive first, will be handled first. //! //! We'll look at each type of message, to see how each one is handled - starting with FIDL //! messages, since they can be thought of as the entrypoint for the whole loop (as nothing happens //! until a FIDL call is made). //! //! # FIDL Worker //! //! The FIDL part of the event loop implements the fuchsia.router.config Admin and State //! interfaces. The type of the event loop message for a FIDL call is //! simply the generated FIDL type. When the event loop starts up, we use `fuchsia_app` to start a //! FIDL server that simply sends all of the events it receives to the event loop (via the sender //! end of the mpsc queue). When `EventLoop` receives this message, it calls the //! `handle_fidl_router_admin_request` or `handle_fidl_router_state_request` method, which, //! depending on what the request is, either: //! //! * Responds with the requested information. //! * Modifies the router state byt accessinc netcfg. //! * Updates local state. use crate::event::Event; use failure::{bail, Error, ResultExt}; use fidl_fuchsia_router_config::{ Id, Lif, Port, RouterAdminRequest, RouterStateGetPortsResponder, RouterStateRequest, SecurityFeatures, }; use futures::channel::mpsc; use futures::prelude::*; use network_manager_core::{ hal::NetCfg, lifmgr::LIFType, packet_filter::PacketFilter, portmgr::PortId, DeviceState, }; macro_rules! router_error { ($code:ident, $desc:expr) => { Some(fidl::encoding::OutOfLine(&mut fidl_fuchsia_router_config::Error { code: fidl_fuchsia_router_config::ErrorCode::$code, description: $desc, })) }; } macro_rules! not_supported { () => { router_error!(NotSupported, None) }; } macro_rules! not_found { () => { router_error!(NotFound, None) }; } macro_rules! internal_error { ($s:expr) => { router_error!(Internal, Some($s.to_string())) }; } /// The event loop. pub struct EventLoop { event_recv: mpsc::UnboundedReceiver<Event>, device: DeviceState, } impl EventLoop { pub fn new() -> Result<Self, Error> { let netcfg = NetCfg::new()?; let packet_filter = PacketFilter::start() .context("network_manager failed to start packet filter!") .unwrap(); let mut device = DeviceState::new(netcfg, packet_filter); let streams = device.take_event_streams(); let (event_send, event_recv) = futures::channel::mpsc::unbounded::<Event>(); let fidl_worker = crate::fidl_worker::FidlWorker; let _ = fidl_worker.spawn(event_send.clone()); let overnet_worker = crate::overnet_worker::OvernetWorker; let _r = overnet_worker.spawn(event_send.clone()); let event_worker = crate::event_worker::EventWorker; event_worker.spawn(streams, event_send.clone()); Ok(EventLoop { event_recv, device }) } pub async fn run(mut self) -> Result<(), Error> { self.device.populate_state().await?; loop { match self.event_recv.next().await { Some(Event::FidlRouterAdminEvent(req)) => { self.handle_fidl_router_admin_request(req).await; } Some(Event::FidlRouterStateEvent(req)) => { self.handle_fidl_router_state_request(req).await; } Some(Event::StackEvent(event)) => self.handle_stack_event(event).await, Some(Event::NetstackEvent(event)) => self.handle_netstack_event(event).await, None => bail!("Stream of events ended unexpectedly"), } } } async fn handle_stack_event(&mut self, event: fidl_fuchsia_net_stack::StackEvent) { self.device .update_state_for_stack_event(event) .await .unwrap_or_else(|err| warn!("error updating state: {:?}", err)); } async fn handle_netstack_event(&mut self, event: fidl_fuchsia_netstack::NetstackEvent) { self.device .update_state_for_netstack_event(event) .await .unwrap_or_else(|err| warn!("error updating state: {:?}", err)); } async fn handle_fidl_router_admin_request(&mut self, req: RouterAdminRequest) { match req { RouterAdminRequest::CreateWan { name, vlan, ports, responder } => { let r = self .fidl_create_lif( LIFType::WAN, name, vlan, ports.iter().map(|x| PortId::from(u64::from(*x))).collect(), ) .await; match r { Ok(mut id) => responder.send(Some(fidl::encoding::OutOfLine(&mut id)), None), Err(mut e) => responder.send(None, Some(fidl::encoding::OutOfLine(&mut e))), } } RouterAdminRequest::CreateLan { name, vlan, ports, responder } => { let r = self .fidl_create_lif( LIFType::LAN, name, vlan, ports.iter().map(|x| PortId::from(u64::from(*x))).collect(), ) .await; match r { Ok(mut id) => responder.send(Some(fidl::encoding::OutOfLine(&mut id)), None), Err(mut e) => responder.send(None, Some(fidl::encoding::OutOfLine(&mut e))), } } RouterAdminRequest::RemoveWan { wan_id, responder } => { let mut r = self.fidl_delete_lif(wan_id).await; responder.send(r.as_mut().map(fidl::encoding::OutOfLine)).or_else(|e| { error!("Error sending response: {:?}", e); Err(e) }) } RouterAdminRequest::RemoveLan { lan_id, responder } => { let mut r = self.fidl_delete_lif(lan_id).await; responder.send(r.as_mut().map(fidl::encoding::OutOfLine)).or_else(|e| { error!("Error sending response: {:?}", e); Err(e) }) } RouterAdminRequest::SetWanProperties { wan_id, properties, responder } => { let properties = fidl_fuchsia_router_config::LifProperties::Wan(properties); if self .device .update_lif_properties(u128::from_ne_bytes(wan_id.uuid), &properties) .await .is_err() { warn!("WAN {:?} found but failed to update properties", wan_id); responder.send(not_found!()) } else { info!("WAN properties updated"); responder.send(None) } } RouterAdminRequest::SetLanProperties { lan_id, properties, responder } => { let properties = fidl_fuchsia_router_config::LifProperties::Lan(properties); if self .device .update_lif_properties(u128::from_ne_bytes(lan_id.uuid), &properties) .await .is_err() { warn!("failed to update LAN properties"); responder.send(not_found!()) } else { info!("LAN properties updated"); responder.send(None) } } RouterAdminRequest::SetDhcpServerOptions { lan_id, options, responder } => { info!("{:?}, {:?}", lan_id, options); responder.send(not_supported!()) } RouterAdminRequest::SetDhcpAddressPool { lan_id, pool, responder } => { info!("{:?}, {:?}", lan_id, pool); responder.send(not_supported!()) } RouterAdminRequest::SetDhcpReservation { lan_id, reservation, responder } => { info!("{:?}, {:?}", lan_id, reservation); responder.send(None, not_supported!()) } RouterAdminRequest::DeleteDhcpReservation { reservation_id, responder } => { info!("{:?}", reservation_id); responder.send(not_supported!()) } RouterAdminRequest::SetDnsResolver { mut config, responder } => { info!("{:?}", config); match self .device .set_dns_resolver( &mut config.search.servers, config.search.domain_name, config.policy, ) .await { Ok(i) => responder.send( Some(fidl::encoding::OutOfLine(&mut Id { uuid: i.uuid().to_ne_bytes(), version: i.version(), })), None, ), Err(e) => responder.send(None, internal_error!(e.to_string())), } } RouterAdminRequest::SetDnsForwarder { config, responder } => { info!("{:?}", config); responder.send(not_supported!()) } RouterAdminRequest::AddDnsEntry { entry, responder } => { info!("{:?}", entry); responder.send(None, not_supported!()) } RouterAdminRequest::DeleteDnsEntry { entry_id, responder } => { info!("{:?}", entry_id); responder.send(not_supported!()) } RouterAdminRequest::SetRoute { route, responder } => { info!("{:?}", route); responder.send(None, not_supported!()) } RouterAdminRequest::UpdateRouteMetric { route_id, metric, responder } => { info!("{:?} {:?}", route_id, metric); responder.send(not_supported!()) } RouterAdminRequest::DeleteRoute { route_id, responder } => { info!("{:?}", route_id); responder.send(not_supported!()) } RouterAdminRequest::SetSecurityFeatures { features, responder } => { info!("Updating SecurityFeatures: {:?}", features); match self.update_security_features(&features).await { Ok(_) => responder.send(None), Err(e) => responder.send(internal_error!(e.to_string())), } } RouterAdminRequest::SetPortForward { rule, responder } => { info!("{:?}", rule); responder.send(None, not_supported!()) } RouterAdminRequest::DeletePortForward { rule_id, responder } => { info!("{:?}", rule_id); responder.send(not_supported!()) } RouterAdminRequest::SetPortTrigger { rule, responder } => { info!("{:?}", rule); responder.send(None, not_supported!()) } RouterAdminRequest::DeletePortTrigger { rule_id, responder } => { info!("{:?}", rule_id); responder.send(not_supported!()) } RouterAdminRequest::SetFilter { rule, responder } => { let r = self .device .set_filter(rule) .await .context("Error installing new packet filter rule"); match r { Ok(()) => responder.send(None, None), Err(e) => responder.send(None, internal_error!(e.to_string())), } } RouterAdminRequest::DeleteFilter { rule_id, responder } => { info!("{:?}", rule_id); responder.send(not_supported!()) } RouterAdminRequest::SetIpv6PinHole { rule, responder } => { info!("{:?}", rule); responder.send(None, not_supported!()) } RouterAdminRequest::DeleteIpv6PinHole { rule_id, responder } => { info!("{:?}", rule_id); responder.send(not_supported!()) } RouterAdminRequest::SetDmzHost { rule, responder } => { info!("{:?}", rule); responder.send(None, not_supported!()) } RouterAdminRequest::DeleteDmzHost { rule_id, responder } => { info!("{:?}", rule_id); responder.send(not_supported!()) } RouterAdminRequest::SetSystemConfig { config, responder } => { info!("{:?}", config); responder.send(None, not_supported!()) } RouterAdminRequest::CreateWlanNetwork { responder, .. } => { // TODO(guzt): implement responder.send(None, not_supported!()) } RouterAdminRequest::DeleteWlanNetwork { responder, .. } => { // TODO(guzt): implement responder.send(not_supported!()) } } .unwrap_or_else(|e| error!("Error sending response {}", e)) } async fn fidl_create_lif( &mut self, lif_type: LIFType, name: String, vlan: u16, ports: Vec<PortId>, ) -> Result<Id, fidl_fuchsia_router_config::Error> { let lif = self.device.create_lif(lif_type, name, vlan, ports).await; match lif { Err(e) => { error!("Error creating lif {:?}", e); Err(fidl_fuchsia_router_config::Error { code: fidl_fuchsia_router_config::ErrorCode::AlreadyExists, description: None, }) } Ok(l) => { let i = l.id(); Ok(Id { uuid: i.uuid().to_ne_bytes(), version: i.version() }) } } } async fn fidl_delete_lif(&mut self, id: Id) -> Option<fidl_fuchsia_router_config::Error> { let lif = self.device.delete_lif(u128::from_ne_bytes(id.uuid)).await; match lif { Err(e) => { error!("Error deleting lif {:?}", e); Some(fidl_fuchsia_router_config::Error { code: fidl_fuchsia_router_config::ErrorCode::NotFound, description: None, }) } Ok(()) => None, } } async fn update_security_features( &mut self, security_features: &SecurityFeatures, ) -> Result<(), Error> { if let Some(nat) = security_features.nat { if nat { self.device.enable_nat().await?; } else { self.device.disable_nat().await?; } } // TODO(cgibson): Handle additional SecurityFeatures. Ok(()) } async fn handle_fidl_router_state_request(&mut self, req: RouterStateRequest) { match req { RouterStateRequest::GetWanPorts { wan_id, responder } => { let lif = self.device.lif(u128::from_ne_bytes(wan_id.uuid)); match lif { None => { warn!("WAN {:?} not found", wan_id); responder.send(&mut None.into_iter(), not_found!()) } Some(l) => responder.send(&mut l.ports().map(|p| p.to_u32()), None), } } RouterStateRequest::GetLanPorts { lan_id, responder } => { let lif = self.device.lif(u128::from_ne_bytes(lan_id.uuid)); match lif { None => { warn!("LAN {:?} not found", lan_id); responder.send(&mut None.into_iter(), not_found!()) } Some(l) => responder.send(&mut l.ports().map(|p| p.to_u32()), None), } } RouterStateRequest::GetWan { wan_id, responder } => { let lif = self.device.lif(u128::from_ne_bytes(wan_id.uuid)); info!("lifs {:?}", lif); match lif { None => { warn!("WAN {:?} not found", wan_id); responder.send( fidl_fuchsia_router_config::Lif { element: None, name: None, port_ids: None, properties: None, vlan: None, type_: None, }, not_found!(), ) } Some(l) => { let ll = l.to_fidl_lif(); responder.send(ll, None) } } } RouterStateRequest::GetLan { lan_id, responder } => { let lif = self.device.lif(u128::from_ne_bytes(lan_id.uuid)); match lif { None => { warn!("LAN {:?} not found", lan_id); responder.send( fidl_fuchsia_router_config::Lif { element: None, name: None, port_ids: None, properties: None, vlan: None, type_: None, }, not_found!(), ) } Some(l) => { let ll = l.to_fidl_lif(); responder.send(ll, None) } } } RouterStateRequest::GetWans { responder } => { let lifs: Vec<Lif> = self.device.lifs(LIFType::WAN).map(|l| l.to_fidl_lif()).collect(); info!("result: {:?} ", lifs); responder.send(&mut lifs.into_iter()) } RouterStateRequest::GetLans { responder } => { let lifs: Vec<Lif> = self.device.lifs(LIFType::LAN).map(|l| l.to_fidl_lif()).collect(); info!("result: {:?} ", lifs); responder.send(&mut lifs.into_iter()) } RouterStateRequest::GetWanProperties { wan_id, responder } => { info!("{:?}", wan_id); let properties = fidl_fuchsia_router_config::WanProperties { connection_type: None, connection_parameters: None, address_method: None, address_v4: None, gateway_v4: None, connection_v6_mode: None, address_v6: None, gateway_v6: None, hostname: None, clone_mac: None, mtu: None, enable: None, metric: None, }; responder.send(properties, not_supported!()) } RouterStateRequest::GetLanProperties { lan_id, responder } => { info!("{:?}", lan_id); let properties = fidl_fuchsia_router_config::LanProperties { address_v4: None, enable_dhcp_server: None, dhcp_config: None, address_v6: None, enable_dns_forwarder: None, enable: None, }; responder.send(properties, not_supported!()) } RouterStateRequest::GetDhcpConfig { lan_id, responder } => { info!("{:?}", lan_id); responder.send(None, not_supported!()) } RouterStateRequest::GetDnsResolver { responder } => { let mut resolver = self.device.get_dns_resolver().await; responder.send(&mut resolver) } RouterStateRequest::GetDnsForwarder { responder } => { let config = fidl_fuchsia_router_config::DnsForwarderConfig { element: Id { uuid: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], version: 0, }, search: fidl_fuchsia_router_config::DnsSearch { domain_name: None, servers: vec![], }, }; let mut forwarder = fidl_fuchsia_router_config::DnsForwarder { config, interfaces: vec![], resolver: vec![], }; responder.send(&mut forwarder) } RouterStateRequest::GetRoutes { responder } => responder.send(&mut [].iter_mut()), RouterStateRequest::GetRoute { route_id, responder } => { info!("{:?}", route_id); responder.send(None, not_supported!()) } RouterStateRequest::GetSecurityFeatures { responder } => { let security_features = fidl_fuchsia_router_config::SecurityFeatures { allow_multicast: None, drop_icmp_echo: None, firewall: None, h323_passthru: None, ipsec_passthru: None, l2_tp_passthru: None, nat: Some(self.device.is_nat_enabled()), pptp_passthru: None, rtsp_passthru: None, sip_passthru: None, upnp: None, v6_firewall: None, }; responder.send(security_features) } RouterStateRequest::GetPortForwards { responder } => responder.send(&mut [].iter_mut()), RouterStateRequest::GetPortForward { rule_id, responder } => { info!("{:?}", rule_id); responder.send(None, not_supported!()) } RouterStateRequest::GetPorts { responder } => { self.fidl_get_ports(responder).await; Ok(()) } RouterStateRequest::GetPort { port_id, responder } => { info!("{:?}", port_id); responder.send(None, not_supported!()) } RouterStateRequest::GetPortTrigger { rule_id, responder } => { info!("{:?}", rule_id); responder.send(None, not_supported!()) } RouterStateRequest::GetPortTriggers { responder } => responder.send(&mut [].iter_mut()), RouterStateRequest::GetFilter { rule_id, responder } => { info!("{:?}", rule_id); responder.send(None, not_supported!()) } RouterStateRequest::GetFilters { responder } => { let result = self.device.get_filters().await.context("Error getting filters"); let mut filter_rules = Vec::new(); match result { Ok(f) => { filter_rules = f.into_iter().collect(); info!("Filter rules returned: {:?}", filter_rules.len()); } Err(e) => error!("Failed parsing filter rules: {}", e), } responder.send(&mut filter_rules.iter_mut()) } RouterStateRequest::GetIpv6PinHole { rule_id, responder } => { info!("{:?}", rule_id); responder.send(None, not_supported!()) } RouterStateRequest::GetIpv6PinHoles { responder } => responder.send(&mut [].iter_mut()), RouterStateRequest::GetDmzHost { rule_id, responder } => { info!("{:?}", rule_id); responder.send(None, not_supported!()) } RouterStateRequest::GetSystemConfig { responder } => { let config = fidl_fuchsia_router_config::SystemConfig { element: None, timezone: None, daylight_savings_time_enabled: None, leds_enabled: None, hostname: None, }; responder.send(config) } RouterStateRequest::GetDevice { responder } => { let device = fidl_fuchsia_router_config::Device { version: None, topology: None, config: None, }; responder.send(device) } RouterStateRequest::GetWlanNetworks { responder } => { responder.send(&mut vec![].into_iter()) } RouterStateRequest::GetRadios { responder } => responder.send(&mut vec![].into_iter()), } .unwrap_or_else(|e| error!("Error sending response {}", e)) } async fn fidl_get_ports(&mut self, responder: RouterStateGetPortsResponder) { let ps = self.device.ports(); let mut ports: Vec<Port> = ps .map(|p| Port { element: Id { uuid: p.e_id.uuid().to_ne_bytes(), version: p.e_id.version() }, id: p.port_id.to_u32(), path: p.path.clone(), }) .collect(); responder.send(&mut ports.iter_mut()).context("Error sending a response").unwrap(); } }
use buckets::Buckets; use metric::{AggregationMethod, LogLine, TagMap, Telemetry}; use sink::{Sink, Valve}; use source::report_telemetry; use std::cmp; use std::io::Write as IoWrite; use std::mem; use std::net::TcpStream; use std::net::ToSocketAddrs; use std::string; use std::sync; use time; pub struct Wavefront { host: String, port: u16, bin_width: i64, aggrs: Buckets, delivery_attempts: u32, percentiles: Vec<(String, f64)>, pub stats: String, flush_interval: u64, } #[derive(Debug, Deserialize)] pub struct WavefrontConfig { pub bin_width: i64, pub host: String, pub port: u16, pub config_path: Option<String>, pub percentiles: Vec<(String, f64)>, pub tags: TagMap, pub flush_interval: u64, } impl Default for WavefrontConfig { fn default() -> WavefrontConfig { let percentiles = vec![ ("min".to_string(), 0.0), ("max".to_string(), 1.0), ("2".to_string(), 0.02), ("9".to_string(), 0.09), ("25".to_string(), 0.25), ("50".to_string(), 0.5), ("75".to_string(), 0.75), ("90".to_string(), 0.90), ("91".to_string(), 0.91), ("95".to_string(), 0.95), ("98".to_string(), 0.98), ("99".to_string(), 0.99), ("999".to_string(), 0.999), ]; WavefrontConfig { bin_width: 1, host: "localhost".to_string(), port: 2878, config_path: Some("sinks.wavefront".to_string()), percentiles: percentiles, tags: TagMap::default(), flush_interval: 60, } } } #[inline] fn fmt_tags(tags: &TagMap, s: &mut String) -> () { let mut iter = tags.iter(); if let Some(&(ref fk, ref fv)) = iter.next() { s.push_str(fk); s.push_str("="); s.push_str(fv); for &(ref k, ref v) in iter { s.push_str(" "); s.push_str(k); s.push_str("="); s.push_str(v); } } } pub fn padding<I: Iterator<Item = Telemetry>>(xs: I, span: i64) -> Padding<I> { Padding { span: span, orig: xs, emit_q: Vec::new(), } } pub struct Padding<I> { span: i64, orig: I, emit_q: Vec<Telemetry>, } impl<I> Iterator for Padding<I> where I: Iterator<Item = Telemetry>, { type Item = I::Item; fn next(&mut self) -> Option<Self::Item> { // To figure out what to do we have to know if there's a 'gap' in the // original iterator to be filled. This is complicated by emit_q which // we use to buffer points that we've read out of the initial iterator // _and_ zero points that need to be emitted. // // We preferentially pull points from the emission queue. In the event // that there are not enough, we go to the original iterator. let next_x = if let Some(x) = self.emit_q.pop() { Some(x) } else { self.orig.next() }; let next_y = if let Some(y) = self.emit_q.pop() { Some(y) } else { self.orig.next() }; match (next_x, next_y) { (Some(x), Some(y)) => { // Telemetry hashes by considering name, timestamp and // aggregation. If these three are different then the next point // is not part of our current sequence and it requires no // padding. if x.hash() == y.hash() { match (x.timestamp - y.timestamp).abs() / self.span { 0 | 1 => { // In this case the next point, y, is within the // span configured by the user. We stash it into // emit_q and will pull it on the next iterative // go-around. self.emit_q.push(y); return Some(x); } _ => { // This case is tricky. Here we've found that the // span between our current point, x, and the next // point, y, is larger than the configured // limit. But! If the current point is zero we don't // want to make any more zero points to pad the gap. // // If the value of x is zero we stash the next // point. Else, we make our pad, stashing those // points plus y. if x.value() == Some(0.0) { self.emit_q.push(y); } else { let sub_y = y.clone().timestamp(y.timestamp - 1).set_value(0.0); self.emit_q.push(y); self.emit_q.push(sub_y); self.emit_q.push( x.clone().timestamp(x.timestamp + 1).set_value(0.0), ); } return Some(x); } } } else { self.emit_q.push(y); return Some(x); } } (Some(x), None) => { // end of sequence return Some(x); } (None, _) => { return None; } } } } #[inline] fn get_from_cache<T>(cache: &mut Vec<(T, String)>, val: T) -> &str where T: cmp::PartialOrd + string::ToString + Copy, { match cache.binary_search_by(|probe| probe.0.partial_cmp(&val).unwrap()) { Ok(idx) => &cache[idx].1, Err(idx) => { let str_val = val.to_string(); cache.insert(idx, (val, str_val)); get_from_cache(cache, val) } } } impl Wavefront { pub fn new(config: WavefrontConfig) -> Result<Wavefront, String> { if config.host == "" { return Err("Host can not be empty".to_string()); } Ok(Wavefront { host: config.host, port: config.port, bin_width: config.bin_width, aggrs: Buckets::new(config.bin_width), delivery_attempts: 0, percentiles: config.percentiles, stats: String::with_capacity(8_192), flush_interval: config.flush_interval, }) } /// Convert the buckets into a String that /// can be sent to the the wavefront proxy pub fn format_stats(&mut self) -> () { let mut time_cache: Vec<(i64, String)> = Vec::with_capacity(128); let mut count_cache: Vec<(usize, String)> = Vec::with_capacity(128); let mut value_cache: Vec<(f64, String)> = Vec::with_capacity(128); let mut tag_buf = String::with_capacity(1_024); let aggrs = mem::replace(&mut self.aggrs, Buckets::default()); for value in padding(aggrs.into_iter(), self.bin_width) { match value.aggr_method { AggregationMethod::Sum => { report_telemetry("cernan.sinks.wavefront.aggregation.sum", 1.0) } AggregationMethod::Set => { report_telemetry("cernan.sinks.wavefront.aggregation.set", 1.0) } AggregationMethod::Summarize => { report_telemetry( "cernan.sinks.wavefront.aggregation.summarize", 1.0, ); report_telemetry( "cernan.sinks.wavefront.aggregation.\ summarize.total_percentiles", self.percentiles.len() as f64, ); } }; match value.aggr_method { AggregationMethod::Sum | AggregationMethod::Set => { if let Some(v) = value.value() { self.stats.push_str(&value.name); self.stats.push_str(" "); self.stats.push_str(get_from_cache(&mut value_cache, v)); self.stats.push_str(" "); self.stats.push_str( get_from_cache(&mut time_cache, value.timestamp), ); self.stats.push_str(" "); fmt_tags(&value.tags, &mut tag_buf); self.stats.push_str(&tag_buf); self.stats.push_str("\n"); tag_buf.clear(); } } AggregationMethod::Summarize => { fmt_tags(&value.tags, &mut tag_buf); for tup in &self.percentiles { let stat: &String = &tup.0; let quant: f64 = tup.1; self.stats.push_str(&value.name); self.stats.push_str("."); self.stats.push_str(stat); self.stats.push_str(" "); self.stats.push_str(get_from_cache( &mut value_cache, value.query(quant).unwrap(), )); self.stats.push_str(" "); self.stats.push_str( get_from_cache(&mut time_cache, value.timestamp), ); self.stats.push_str(" "); self.stats.push_str(&tag_buf); self.stats.push_str("\n"); } let count = value.count(); self.stats.push_str(&value.name); self.stats.push_str(".count"); self.stats.push_str(" "); self.stats.push_str(get_from_cache(&mut count_cache, count)); self.stats.push_str(" "); self.stats .push_str(get_from_cache(&mut time_cache, value.timestamp)); self.stats.push_str(" "); self.stats.push_str(&tag_buf); self.stats.push_str("\n"); let mean = value.mean(); self.stats.push_str(&value.name); self.stats.push_str(".mean"); self.stats.push_str(" "); self.stats.push_str(get_from_cache(&mut value_cache, mean)); self.stats.push_str(" "); self.stats .push_str(get_from_cache(&mut time_cache, value.timestamp)); self.stats.push_str(" "); self.stats.push_str(&tag_buf); self.stats.push_str("\n"); tag_buf.clear(); } } } } } impl Sink for Wavefront { fn flush_interval(&self) -> Option<u64> { Some(self.flush_interval) } fn flush(&mut self) { self.format_stats(); loop { report_telemetry( "cernan.sinks.wavefront.delivery_attempts", self.delivery_attempts as f64, ); if self.delivery_attempts > 0 { debug!("delivery attempts: {}", self.delivery_attempts); } let addrs = (self.host.as_str(), self.port).to_socket_addrs(); match addrs { Ok(srv) => { let ips: Vec<_> = srv.collect(); for ip in ips { match TcpStream::connect(ip) { Ok(mut stream) => { let res = stream.write(self.stats.as_bytes()); if res.is_ok() { self.stats.clear(); self.delivery_attempts = 0; return; } else { self.delivery_attempts = self.delivery_attempts.saturating_add(1); } } Err(e) => { info!( "Unable to connect to proxy at {} using addr {} with error \ {}", self.host, ip, e ) } } time::delay(self.delivery_attempts); } } Err(e) => { info!( "Unable to perform DNS lookup on host {} with error {}", self.host, e ); } } } } fn deliver(&mut self, mut point: sync::Arc<Option<Telemetry>>) -> () { let telem: Telemetry = sync::Arc::make_mut(&mut point).take().unwrap(); self.aggrs.add(telem); } fn deliver_line(&mut self, _: sync::Arc<Option<LogLine>>) -> () { // nothing, intentionally } fn valve_state(&self) -> Valve { if self.aggrs.len() > 10_000 { Valve::Closed } else { Valve::Open } } } #[cfg(test)] mod test { use quickcheck::{QuickCheck, TestResult}; use super::*; use chrono::{TimeZone, Utc}; use metric::{TagMap, Telemetry}; use sink::Sink; use std::sync::Arc; #[test] fn test_no_unpadded_gaps() { fn inner(bin_width: u8, ms: Vec<Telemetry>) -> TestResult { if bin_width == 0 { return TestResult::discard(); } // TODO // // The fact that I have to set a bucket here suggests that 'padding' // might be sensible for inclusion as an interator on the // Bucket. But! It doesn't have to be that way, if the // Vec<Telemetry> is pre-prepped. let mut bucket = Buckets::new(bin_width as i64); for m in ms.clone() { bucket.add(m); } let mut padding = padding(bucket.into_iter(), bin_width as i64).peekable(); while let Some(t) = padding.next() { if let Some(next_t) = padding.peek() { // When we examine the next point in a series there are // three possibilities: // // 1. the points don't hash the same, so we move on // 2. the points do hash the same: // a. if their timestamps are greater than one span // apart then they are both zero // b. if both points are non-zero they must not be // more than one span apart if t.hash() == next_t.hash() { let span = (t.timestamp - next_t.timestamp).abs() / (bin_width as i64); if span > 1 { assert_eq!(t.value(), Some(0.0)); assert_eq!(next_t.value(), Some(0.0)); } if (t.value() != Some(0.0)) && (next_t.value() != Some(0.0)) { assert!(span <= 1); } } else { continue } } else { break; } } TestResult::passed() } QuickCheck::new().quickcheck(inner as fn(u8, Vec<Telemetry>) -> TestResult); } #[test] fn test_never_fewer_non_zero() { fn inner(bin_width: u8, ms: Vec<Telemetry>) -> TestResult { if bin_width == 0 { return TestResult::discard(); } let mut bucket = Buckets::new(bin_width as i64); for m in ms.clone() { bucket.add(m); } let mut total_non_zero = 0; for val in bucket.clone().into_iter() { if val.value() != Some(0.0) { total_non_zero += 1; } } let padding = padding(bucket.into_iter(), bin_width as i64); let mut total = 0; for val in padding { if val.value() != Some(0.0) { total += 1; } } assert_eq!(total_non_zero, total); TestResult::passed() } QuickCheck::new().quickcheck(inner as fn(u8, Vec<Telemetry>) -> TestResult); } #[test] fn test_format_wavefront() { let mut tags = TagMap::default(); tags.insert("source".into(), "test-src".into()); let percentiles = vec![ ("min".to_string(), 0.0), ("max".to_string(), 1.0), ("2".to_string(), 0.02), ("9".to_string(), 0.09), ("25".to_string(), 0.25), ("50".to_string(), 0.5), ("75".to_string(), 0.75), ("90".to_string(), 0.90), ("91".to_string(), 0.91), ("95".to_string(), 0.95), ("98".to_string(), 0.98), ("99".to_string(), 0.99), ("999".to_string(), 0.999), ]; let config = WavefrontConfig { bin_width: 1, host: "127.0.0.1".to_string(), port: 1987, config_path: Some("sinks.wavefront".to_string()), tags: tags.clone(), percentiles: percentiles, flush_interval: 60, }; let mut wavefront = Wavefront::new(config).unwrap(); let dt_0 = Utc.ymd(1990, 6, 12).and_hms_milli(9, 10, 11, 00).timestamp(); let dt_1 = Utc.ymd(1990, 6, 12).and_hms_milli(9, 10, 12, 00).timestamp(); let dt_2 = Utc.ymd(1990, 6, 12).and_hms_milli(9, 10, 13, 00).timestamp(); wavefront.deliver(Arc::new(Some( Telemetry::new("test.counter", -1.0) .timestamp(dt_0) .aggr_sum() .overlay_tags_from_map(&tags), ))); wavefront.deliver(Arc::new(Some( Telemetry::new("test.counter", 2.0) .timestamp(dt_0) .aggr_sum() .overlay_tags_from_map(&tags), ))); wavefront.deliver(Arc::new(Some( Telemetry::new("test.counter", 3.0) .timestamp(dt_1) .aggr_sum() .overlay_tags_from_map(&tags), ))); wavefront.deliver(Arc::new(Some( Telemetry::new("test.gauge", 3.211) .timestamp(dt_0) .aggr_set() .overlay_tags_from_map(&tags), ))); wavefront.deliver(Arc::new(Some( Telemetry::new("test.gauge", 4.322) .timestamp(dt_1) .aggr_set() .overlay_tags_from_map(&tags), ))); wavefront.deliver(Arc::new(Some( Telemetry::new("test.gauge", 5.433) .timestamp(dt_2) .aggr_set() .overlay_tags_from_map(&tags), ))); wavefront.deliver(Arc::new(Some( Telemetry::new("test.timer", 12.101) .timestamp(dt_0) .aggr_summarize() .overlay_tags_from_map(&tags), ))); wavefront.deliver(Arc::new(Some( Telemetry::new("test.timer", 1.101) .timestamp(dt_0) .aggr_summarize() .overlay_tags_from_map(&tags), ))); wavefront.deliver(Arc::new(Some( Telemetry::new("test.timer", 3.101) .timestamp(dt_0) .aggr_summarize() .overlay_tags_from_map(&tags), ))); wavefront.deliver(Arc::new(Some( Telemetry::new("test.raw", 1.0) .timestamp(dt_0) .aggr_set() .overlay_tags_from_map(&tags), ))); wavefront.deliver(Arc::new(Some( Telemetry::new("test.raw", 2.0) .timestamp(dt_1) .aggr_set() .overlay_tags_from_map(&tags), ))); wavefront.format_stats(); let lines: Vec<&str> = wavefront.stats.lines().collect(); println!("{:?}", lines); assert!(lines.contains(&"test.counter 1 645181811 source=test-src")); assert!(lines.contains(&"test.counter 3 645181812 source=test-src")); assert!(lines.contains(&"test.gauge 3.211 645181811 source=test-src")); assert!(lines.contains(&"test.gauge 4.322 645181812 source=test-src")); assert!(lines.contains(&"test.gauge 5.433 645181813 source=test-src")); assert!(lines.contains(&"test.timer.min 1.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.max 12.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.2 1.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.9 1.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.25 1.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.50 3.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.75 3.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.90 12.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.91 12.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.95 12.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.98 12.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.99 12.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.999 12.101 645181811 source=test-src")); assert!(lines.contains(&"test.timer.count 3 645181811 source=test-src")); assert!( lines.contains( &"test.timer.mean 5.434333333333334 645181811 source=test-src" ) ); assert!(lines.contains(&"test.raw 1 645181811 source=test-src")); } }
// Copyright 2018 Evgeniy Reizner // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. mod parser; mod writer; pub use self::parser::*; /// Representation of the [`<list-of-points>`] type. /// /// [`<list-of-points>`]: https://www.w3.org/TR/SVG11/shapes.html#PointsBNF #[derive(Clone, PartialEq)] pub struct Points(pub Vec<(f64, f64)>); impl_from_vec!(Points, Points, (f64, f64)); impl_vec_defer!(Points, (f64, f64));
use radio::RadioStation; use radio::song::{radio_1live, radio_ndr, radio_antenne}; /// Radiostations pub const RADIOSTATIONS: &'static [RadioStation] = &[ // Stations 1LIVE and WDR RadioStation { name: "1LIVE", shorthand: "1live", url: "http://www.wdr.de/radio/radiotext/streamtitle_1live.txt", get_song: radio_1live, }, RadioStation { name: "1LIVE diGGi", shorthand: "diggi", url: "http://www.wdr.de/radio/radiotext/streamtitle_1live_diggi.txt", get_song: radio_1live, }, RadioStation { name: "WDR2", shorthand: "wdr2", url: "http://www.wdr.de/radio/radiotext/streamtitle_wdr2.txt", get_song: radio_1live, }, RadioStation { name: "WDR3", shorthand: "wdr3", url: "http://www.wdr.de/radio/radiotext/streamtitle_wdr3.txt", get_song: radio_1live, }, RadioStation { name: "WDR4", shorthand: "wdr4", url: "http://www.wdr.de/radio/radiotext/streamtitle_wdr4.txt", get_song: radio_1live, }, RadioStation { name: "WDR5", shorthand: "wdr5", url: "http://www.wdr.de/radio/radiotext/streamtitle_wdr5.txt", get_song: radio_1live, }, RadioStation { name: "Funkhaus Europa", shorthand: "fhe", url: "http://www.wdr.de/radio/radiotext/streamtitle_fhe.txt", get_song: radio_1live, }, // RadioStation { // name: "Kiraka", // url: "http://www.wdr.de/radio/radiotext/streamtitle_kiraka.txt", // get_song: radio_1live, // }, RadioStation { name: "WDR-Event", shorthand: "wdre", url: "http://www.wdr.de/radio/radiotext/streamtitle_event.txt", get_song: radio_1live, }, // Stations NDR RadioStation { name: "NDR 1 Niedersachsen", shorthand: "ndr1n", url: "http://www.ndr.de/public/radio_playlists/ndr1niedersachsen.json", get_song: radio_ndr, }, RadioStation { name: "NDR 1 Radio MV", shorthand: "ndr1rmv", url: "http://www.ndr.de/public/radio_playlists/ndr1radiomv.json", get_song: radio_ndr, }, RadioStation { name: "NDR Welle Nord", shorthand: "ndrwn", url: "http://www.ndr.de/public/radio_playlists/ndr1wellenord.json", get_song: radio_ndr, }, RadioStation { name: "NDR 90,3", shorthand: "ndr903", url: "http://www.ndr.de/public/radio_playlists/ndr903.json", get_song: radio_ndr, }, RadioStation { name: "NDR 2", shorthand: "ndr2", url: "http://www.ndr.de/public/radio_playlists/ndr2.json", get_song: radio_ndr, }, //RadioStation { // name: "NDR Info", // shorthand: "ndri", // url: "http://www.ndr.de/public/radio_playlists/ndrinfo.json", // get_song: radio_ndr, //}, RadioStation { name: "NDR Kultur", shorthand: "ndrk", url: "http://www.ndr.de/public/radio_playlists/ndrkultur.json", get_song: radio_ndr, }, RadioStation { name: "NJOY", shorthand: "njoy", url: "http://www.ndr.de/public/radio_playlists/njoy.json", get_song: radio_ndr, }, RadioStation { name: "NDR Blue", shorthand: "ndrb", url: "http://www.ndr.de/public/radio_playlists/ndrblue.json", get_song: radio_ndr, }, RadioStation { name: "NDR Plus", shorthand: "ndrp", url: "http://www.ndr.de/public/radio_playlists/ndrplus.json", get_song: radio_ndr, }, RadioStation { name: "Antenne Niedersachsen On Air", shorthand: "antenneoa", url: "http://np.radioplayer.de/qp/v3/onair?rpIds=29&nameSize=200 &artistNameSize=200&descriptionSize=200&callback=radioplayer .playing.receive", get_song: radio_antenne, }, RadioStation { name: "Antenne Niedersachsen 80er", shorthand: "antenne80", url: "http://np.radioplayer.de/qp/v3/onair?rpIds=31&nameSize=200 &artistNameSize=200&descriptionSize=200&callback=radioplayer .playing.receive", get_song: radio_antenne, }, RadioStation { name: "Antenne Niedersachsen 90er", shorthand: "antenne90", url: "http://np.radioplayer.de/qp/v3/onair?rpIds=422&nameSize=200& artistNameSize=200&descriptionSize=200&callback=radioplayer .playing.receive", get_song: radio_antenne, }, RadioStation { name: "Antenne Niedersachsen Charts", shorthand: "antennec", url: "http://np.radioplayer.de/qp/v3/onair?rpIds=30&nameSize=200 &artistNameSize=200&descriptionSize=200&callback=radioplayer .playing.receive", get_song: radio_antenne, }, RadioStation { name: "Antenne Niedersachsen Deutsch", shorthand: "antenned", url: "http://np.radioplayer.de/qp/v3/onair?rpIds=565&nameSize=200 &artistNameSize=200&descriptionSize=200&callback=radioplayer .playing.receive", get_song: radio_antenne, }, RadioStation { name: "Antenne Niedersachsen X-Mas", shorthand: "antennexmas", url: "http://np.radioplayer.de/qp/v3/onair?rpIds=110&nameSize=200 &artistNameSize=200&descriptionSize=200&callback=radioplayer .playing.receive&_=1486056701107", get_song: radio_antenne, }, RadioStation { name: "Antenne Niedersachsen Feel Good", shorthand: "antennefg", url: "http://np.radioplayer.de/qp/v3/onair?rpIds=602&nameSize=200 &artistNameSize=200&descriptionSize=200&callback=radioplayer .playing.receive&_=1486056790331", get_song: radio_antenne, }, RadioStation { name: "Antenne Niedersachsen Love", shorthand: "antennelove", url: "http://np.radioplayer.de/qp/v3/onair?rpIds=566&nameSize=200 &artistNameSize=200&descriptionSize=200&callback=radioplayer .playing.receive&_=1486056946846", get_song: radio_antenne, }, RadioStation { name: "Antenne Oldies", shorthand: "antenneold", url: "http://np.radioplayer.de/qp/v3/onair?rpIds=32&nameSize=200 &artistNameSize=200&descriptionSize=200&callback=radioplayer .playing.receive&_=1486057006247", get_song: radio_antenne, }, RadioStation { name: "Antenne Relax", shorthand: "antennelax", url: "http://np.radioplayer.de/qp/v3/onair?rpIds=454&nameSize=200 &artistNameSize=200&descriptionSize=200&callback=radioplayer .playing.receive&_=1486057066325", get_song: radio_antenne, }, RadioStation { name: "Antenne Rock", shorthand: "antennerock", url: "http://np.radioplayer.de/qp/v3/onair?rpIds=33&nameSize=200 &artistNameSize=200&descriptionSize=200&callback=radioplayer .playing.receive&_=1486057141342", get_song: radio_antenne, }, RadioStation { name: "Antenne Schlager", shorthand: "antennesch", url: "http://np.radioplayer.de/qp/v3/onair?rpIds=601&nameSize=200 &artistNameSize=200&descriptionSize=200&callback=radioplayer .playing.receive&_=1486057202504", get_song: radio_antenne, }, ];
use {Status}; #[repr(C)] pub struct SimpleFileSystem { revision: u64, open_volume: extern "win64" fn(&SimpleFileSystem, &mut *mut super::File) -> Status, } impl super::Protocol for SimpleFileSystem { fn guid() -> ::Guid { ::Guid( 0x0964e5b22,0x6459,0x11d2, [0x8e,0x39,0x00,0xa0,0xc9,0x69,0x72,0x3b] ) } unsafe fn from_ptr(v: *const ::Void) -> *const Self { v as *const _ } } impl SimpleFileSystem { pub fn open_volume(&self) -> Result< super::Owned<super::File>, Status > { let mut ptr = ::core::ptr::null_mut(); (self.open_volume)(self, &mut ptr) // SAFE: Pointer passed to us for ownership .err_or_else(|| unsafe {super::Owned::from_ptr(ptr) } ) } }
use std::env; use std::io::{self, Error, ErrorKind, Write}; use std::process::{exit, Command, Stdio}; extern crate serde; #[macro_use] extern crate serde_json; use serde_json::Value; fn main() { query_watchman().unwrap_or_else(|e| { eprintln!("{}", e); exit(1); }) } fn query_watchman() -> io::Result<()> { let git_work_tree = env::current_dir().unwrap(); let mut watchman = Command::new("watchman") .args(&["-j", "--no-pretty"]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn()?; { let args: Vec<String> = env::args().collect(); let time = &args[2]; let time_nanoseconds: u64 = time.parse::<u64>().unwrap(); let time_seconds = time_nanoseconds / 1000000000; let watchman_query = json!( [ "query", git_work_tree, { "since": time_seconds, "fields": ["name"], "expression": [ "not", [ "allof",[ "since", time_seconds, "cclock" ], [ "not", "exists" ] ] ] } ] ); watchman .stdin .as_mut() .unwrap() .write_all(watchman_query.to_string().as_bytes())?; } let output = watchman.wait_with_output()?.stdout; let response: Value = serde_json::from_str(String::from_utf8(output).unwrap().as_str())?; match response["error"].as_str() { Some(_) => return add_to_watchman(git_work_tree), None => {} } match response["files"].as_array() { Some(files) => { for file in files { match file.as_str() { Some(filename) => print!("{}\0", filename), None => {} } } return Ok(()); } None => return Err(Error::new(ErrorKind::Other, "missing file data")), } } fn add_to_watchman(worktree: std::path::PathBuf) -> io::Result<()> { let watchman = Command::new("watchman") .args(&["watch", worktree.to_str().unwrap()]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn()?; match watchman.wait_with_output() { Ok(_) => { print!("\0"); return Ok(()); } Err(e) => return Err(e), } }
use std::collections::HashMap; use bip78::bitcoin::util::psbt::PartiallySignedTransaction as Psbt; use bitcoincore_rpc::RpcApi; fn main() { let mut args = std::env::args_os(); let _program_name = args .next() .expect("not even program name given"); let port = args .next() .expect("Missing arguments: port cookie_file bip21") .into_string() .expect("port is not UTF-8") .parse::<u16>() .expect("port must be a number"); let cookie_file = args .next() .expect("Missing arguments: cookie_file bip21"); let bip21 = args .next() .expect("Missing arguments: bip21") .into_string() .expect("bip21 is not UTF-8"); let link = bip21.parse::<bip78::Uri>().unwrap(); let mut outputs = HashMap::with_capacity(1); outputs.insert(link.address().to_string(), link.amount()); let client = bitcoincore_rpc::Client::new(format!("http://127.0.0.1:{}", port), bitcoincore_rpc::Auth::CookieFile(cookie_file.into())).unwrap(); let options = bitcoincore_rpc::json::WalletCreateFundedPsbtOptions { lock_unspent: Some(true), fee_rate: Some(bip78::bitcoin::Amount::from_sat(2000)), ..Default::default() }; let psbt = client.wallet_create_funded_psbt( &[], // inputs &outputs, None, // locktime Some(options), None, ).expect("failed to create PSBT").psbt; let psbt = client .wallet_process_psbt(&psbt, None, None, None) .unwrap() .psbt; let psbt = load_psbt_from_base64(psbt.as_bytes()).unwrap(); println!("Original psbt: {:#?}", psbt); let pj_params = bip78::sender::Params::with_fee_contribution(bip78::bitcoin::Amount::from_sat(10000), None); let (req, ctx) = link.create_request(psbt, pj_params).unwrap(); let response = reqwest::blocking::Client::new() .post(&req.url) .body(req.body) .header("Content-Type", "text/plain") .send() .expect("failed to communicate"); //.error_for_status() //.unwrap(); let psbt = ctx.process_response(response).unwrap(); println!("Proposed psbt: {:#?}", psbt); let psbt = client .wallet_process_psbt(&serialize_psbt(&psbt), None, None, None) .unwrap() .psbt; let tx = client .finalize_psbt(&psbt, Some(true)) .unwrap() .hex .expect("incomplete psbt"); client.send_raw_transaction(&tx).unwrap(); } fn load_psbt_from_base64(mut input: impl std::io::Read) -> Result<Psbt, bip78::bitcoin::consensus::encode::Error> { use bip78::bitcoin::consensus::Decodable; let reader = base64::read::DecoderReader::new(&mut input, base64::Config::new(base64::CharacterSet::Standard, true)); Psbt::consensus_decode(reader) } fn serialize_psbt(psbt: &Psbt) -> String { use bip78::bitcoin::consensus::Encodable; let mut encoder = base64::write::EncoderWriter::new(Vec::new(), base64::STANDARD); psbt.consensus_encode(&mut encoder) .expect("Vec doesn't return errors in its write implementation"); String::from_utf8(encoder.finish() .expect("Vec doesn't return errors in its write implementation")).unwrap() }
extern crate ply_rs; use ply_rs as ply; /// Sometimes only the meta data is interesting to us. /// Reading the entire ply file would be a waste of ressources. fn main() { // set up a reader, in this a file. let path = "example_plys/greg_turk_example1_ok_ascii.ply"; let f = std::fs::File::open(path).unwrap(); // Reading a header, requires a reader that provides a way to read single line // in read_ply, this conversion happens internally. let mut reader = std::io::BufReader::new(f); // create a parser let p = ply::parser::Parser::<ply::ply::DefaultElement>::new(); // use the parser: read the entire file let ply = p.read_header(&mut reader); // make sure it did work assert!(ply.is_ok()); // proof that data has been read println!("Read ply data: {:#?}", ply.unwrap()); }
#[macro_use] extern crate lazy_static; use std::env; use std::fs::File; use std::io::{BufRead, BufReader, BufWriter, Result, Write}; use std::path::Path; #[allow(dead_code)] mod encoding; use encoding::{ get_base_enc, Encoding, SYMBOL_ENCODING, ZAPFDINGBATS_ENCODING, }; fn write_cond( f: &mut BufWriter<File>, name: &str, encoding: &Encoding, ) -> Result<()> { write!( f, " static ref METRICS_{name}: FontMetrics = \ FontMetrics::from_slice(&[", name = name.to_uppercase() )?; let filename = format!("data/{}.afm", name.replace("_", "-")); println!("cargo:rerun-if-changed={}", filename); let afm_file = File::open(filename)?; for lineresult in BufReader::new(afm_file).lines() { let line = lineresult?; let words: Vec<&str> = line.split_whitespace().collect(); if words[0] == "C" && words[3] == "WX" && words[6] == "N" { if let (Some(c), Ok(w)) = (encoding.get_code(words[7]), words[4].parse::<u16>()) { write!(f, "({}, {}), ", c, w)?; } } } writeln!(f, "]);") } fn main() -> Result<()> { let dst = Path::new( &env::var("OUT_DIR").expect("Could not find directory."), ).join("metrics_data.rs"); let f = File::create(&dst).expect("Could not create file."); let f = &mut BufWriter::new(f); let textfonts = [ "Courier", "Courier_Bold", "Courier_Oblique", "Courier_BoldOblique", "Helvetica", "Helvetica_Bold", "Helvetica_Oblique", "Helvetica_BoldOblique", "Times_Roman", "Times_Bold", "Times_Italic", "Times_BoldItalic", "Symbol", "ZapfDingbats", ]; writeln!( f, "pub fn get_builtin_metrics(font: BuiltinFont) \ -> &'static FontMetrics {{\n\ match font {{" )?; for font in textfonts.iter() { writeln!( f, "BuiltinFont::{} => &METRICS_{},", font, font.to_uppercase() )?; } writeln!( f, "}}\n\ }}\n\ lazy_static! {{" )?; let encoding = get_base_enc(); for font in textfonts.iter().take(12) { write_cond(f, font, encoding.to_encoding())?; } write_cond(f, "Symbol", &SYMBOL_ENCODING)?; write_cond(f, "ZapfDingbats", &ZAPFDINGBATS_ENCODING)?; writeln!(f, "}}") }
#[macro_export] macro_rules! path { (@segment $s:literal) => { $crate::PathSegment::Literal($s) }; (@segment $i:ident) => { $crate::PathSegment::Dynamic($crate::PathParam::new( stringify!($i), $crate::PathToken::Any, )) }; (@segment [$i:ident ~ $re:literal]) => {{ $crate::PathSegment::Dynamic($crate::PathParam::new( stringify!($i), $crate::PathToken::Regex($crate::regex::Regex::new($re).unwrap()), )) }}; ($($segment:tt) / *) => {{ $crate::Path(vec![ $($crate::path!(@segment $segment) ),* ]) }}; }
//! Implements basic compacting. This is based on the compaction logic from //! diffy by Brandon Williams. use std::ops::Index; use crate::{DiffOp, DiffTag}; use super::utils::{common_prefix_len, common_suffix_len}; use super::DiffHook; /// Performs semantic cleanup operations on a diff. /// /// This merges similar ops together but also tries to move hunks up and /// down the diff with the desire to connect as many hunks as possible. /// It still needs to be combined with [`Replace`](crate::algorithms::Replace) /// to get actual replace diff ops out. #[derive(Debug)] pub struct Compact<'old, 'new, Old: ?Sized, New: ?Sized, D> { d: D, ops: Vec<DiffOp>, old: &'old Old, new: &'new New, } impl<'old, 'new, Old, New, D> Compact<'old, 'new, Old, New, D> where D: DiffHook, Old: Index<usize> + ?Sized + 'old, New: Index<usize> + ?Sized + 'new, New::Output: PartialEq<Old::Output>, { /// Creates a new compact hook wrapping another hook. pub fn new(d: D, old: &'old Old, new: &'new New) -> Self { Compact { d, ops: Vec::new(), old, new, } } /// Extracts the inner hook. pub fn into_inner(self) -> D { self.d } } impl<'old, 'new, Old: ?Sized, New: ?Sized, D: DiffHook> AsRef<D> for Compact<'old, 'new, Old, New, D> { fn as_ref(&self) -> &D { &self.d } } impl<'old, 'new, Old: ?Sized, New: ?Sized, D: DiffHook> AsMut<D> for Compact<'old, 'new, Old, New, D> { fn as_mut(&mut self) -> &mut D { &mut self.d } } impl<'old, 'new, Old, New, D> DiffHook for Compact<'old, 'new, Old, New, D> where D: DiffHook, Old: Index<usize> + ?Sized + 'old, New: Index<usize> + ?Sized + 'new, New::Output: PartialEq<Old::Output>, { type Error = D::Error; #[inline(always)] fn equal(&mut self, old_index: usize, new_index: usize, len: usize) -> Result<(), Self::Error> { self.ops.push(DiffOp::Equal { old_index, new_index, len, }); Ok(()) } #[inline(always)] fn delete( &mut self, old_index: usize, old_len: usize, new_index: usize, ) -> Result<(), Self::Error> { self.ops.push(DiffOp::Delete { old_index, old_len, new_index, }); Ok(()) } #[inline(always)] fn insert( &mut self, old_index: usize, new_index: usize, new_len: usize, ) -> Result<(), Self::Error> { self.ops.push(DiffOp::Insert { old_index, new_index, new_len, }); Ok(()) } fn finish(&mut self) -> Result<(), Self::Error> { cleanup_diff_ops(self.old, self.new, &mut self.ops); for op in &self.ops { op.apply_to_hook(&mut self.d)?; } self.d.finish() } } // Walks through all edits and shifts them up and then down, trying to see if // they run into similar edits which can be merged. pub fn cleanup_diff_ops<Old, New>(old: &Old, new: &New, ops: &mut Vec<DiffOp>) where Old: Index<usize> + ?Sized, New: Index<usize> + ?Sized, New::Output: PartialEq<Old::Output>, { // First attempt to compact all Deletions let mut pointer = 0; while let Some(&op) = ops.get(pointer) { if let DiffTag::Delete = op.tag() { pointer = shift_diff_ops_up(ops, old, new, pointer); pointer = shift_diff_ops_down(ops, old, new, pointer); } pointer += 1; } // Then attempt to compact all Insertions let mut pointer = 0; while let Some(&op) = ops.get(pointer) { if let DiffTag::Insert = op.tag() { pointer = shift_diff_ops_up(ops, old, new, pointer); pointer = shift_diff_ops_down(ops, old, new, pointer); } pointer += 1; } } fn shift_diff_ops_up<Old, New>( ops: &mut Vec<DiffOp>, old: &Old, new: &New, mut pointer: usize, ) -> usize where Old: Index<usize> + ?Sized, New: Index<usize> + ?Sized, New::Output: PartialEq<Old::Output>, { while let Some(&prev_op) = pointer.checked_sub(1).and_then(|idx| ops.get(idx)) { let this_op = ops[pointer]; match (this_op.tag(), prev_op.tag()) { // Shift Inserts Upwards (DiffTag::Insert, DiffTag::Equal) => { let suffix_len = common_suffix_len(old, prev_op.old_range(), new, this_op.new_range()); if suffix_len > 0 { if let Some(DiffTag::Equal) = ops.get(pointer + 1).map(|x| x.tag()) { ops[pointer + 1].grow_left(suffix_len); } else { ops.insert( pointer + 1, DiffOp::Equal { old_index: prev_op.old_range().end - suffix_len, new_index: this_op.new_range().end - suffix_len, len: suffix_len, }, ); } ops[pointer].shift_left(suffix_len); ops[pointer - 1].shrink_left(suffix_len); if ops[pointer - 1].is_empty() { ops.remove(pointer - 1); pointer -= 1; } } else if ops[pointer - 1].is_empty() { ops.remove(pointer - 1); pointer -= 1; } else { // We can't shift upwards anymore break; } } // Shift Deletions Upwards (DiffTag::Delete, DiffTag::Equal) => { // check common suffix for the amount we can shift let suffix_len = common_suffix_len(old, prev_op.old_range(), new, this_op.new_range()); if suffix_len != 0 { if let Some(DiffTag::Equal) = ops.get(pointer + 1).map(|x| x.tag()) { ops[pointer + 1].grow_left(suffix_len); } else { let old_range = prev_op.old_range(); ops.insert( pointer + 1, DiffOp::Equal { old_index: old_range.end - suffix_len, new_index: this_op.new_range().end - suffix_len, len: old_range.len() - suffix_len, }, ); } ops[pointer].shift_left(suffix_len); ops[pointer - 1].shrink_left(suffix_len); if ops[pointer - 1].is_empty() { ops.remove(pointer - 1); pointer -= 1; } } else if ops[pointer - 1].is_empty() { ops.remove(pointer - 1); pointer -= 1; } else { // We can't shift upwards anymore break; } } // Swap the Delete and Insert (DiffTag::Insert, DiffTag::Delete) | (DiffTag::Delete, DiffTag::Insert) => { ops.swap(pointer - 1, pointer); pointer -= 1; } // Merge the two ranges (DiffTag::Insert, DiffTag::Insert) => { ops[pointer - 1].grow_right(this_op.new_range().len()); ops.remove(pointer); pointer -= 1; } (DiffTag::Delete, DiffTag::Delete) => { ops[pointer - 1].grow_right(this_op.old_range().len()); ops.remove(pointer); pointer -= 1; } _ => unreachable!("unexpected tag"), } } pointer } fn shift_diff_ops_down<Old, New>( ops: &mut Vec<DiffOp>, old: &Old, new: &New, mut pointer: usize, ) -> usize where Old: Index<usize> + ?Sized, New: Index<usize> + ?Sized, New::Output: PartialEq<Old::Output>, { while let Some(&next_op) = pointer.checked_add(1).and_then(|idx| ops.get(idx)) { let this_op = ops[pointer]; match (this_op.tag(), next_op.tag()) { // Shift Inserts Downwards (DiffTag::Insert, DiffTag::Equal) => { let prefix_len = common_prefix_len(old, next_op.old_range(), new, this_op.new_range()); if prefix_len > 0 { if let Some(DiffTag::Equal) = pointer .checked_sub(1) .and_then(|x| ops.get(x)) .map(|x| x.tag()) { ops[pointer - 1].grow_right(prefix_len); } else { ops.insert( pointer, DiffOp::Equal { old_index: next_op.old_range().start, new_index: this_op.new_range().start, len: prefix_len, }, ); pointer += 1; } ops[pointer].shift_right(prefix_len); ops[pointer + 1].shrink_right(prefix_len); if ops[pointer + 1].is_empty() { ops.remove(pointer + 1); } } else if ops[pointer + 1].is_empty() { ops.remove(pointer + 1); } else { // We can't shift upwards anymore break; } } // Shift Deletions Downwards (DiffTag::Delete, DiffTag::Equal) => { // check common suffix for the amount we can shift let prefix_len = common_prefix_len(old, next_op.old_range(), new, this_op.new_range()); if prefix_len > 0 { if let Some(DiffTag::Equal) = pointer .checked_sub(1) .and_then(|x| ops.get(x)) .map(|x| x.tag()) { ops[pointer - 1].grow_right(prefix_len); } else { ops.insert( pointer, DiffOp::Equal { old_index: next_op.old_range().start, new_index: this_op.new_range().start, len: prefix_len, }, ); pointer += 1; } ops[pointer].shift_right(prefix_len); ops[pointer + 1].shrink_right(prefix_len); if ops[pointer + 1].is_empty() { ops.remove(pointer + 1); } } else if ops[pointer + 1].is_empty() { ops.remove(pointer + 1); } else { // We can't shift downwards anymore break; } } // Swap the Delete and Insert (DiffTag::Insert, DiffTag::Delete) | (DiffTag::Delete, DiffTag::Insert) => { ops.swap(pointer, pointer + 1); pointer += 1; } // Merge the two ranges (DiffTag::Insert, DiffTag::Insert) => { ops[pointer].grow_right(next_op.new_range().len()); ops.remove(pointer + 1); } (DiffTag::Delete, DiffTag::Delete) => { ops[pointer].grow_right(next_op.old_range().len()); ops.remove(pointer + 1); } _ => unreachable!("unexpected tag"), } } pointer }
use crate::*; #[derive(Clone, Copy, Debug, Default)] #[cfg_attr(feature = "with_serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "with_serde", serde(default))] pub(crate) struct State { /// Positive offset means scrolling down/right offset: Vec2, show_scroll: bool, // TODO: default value? } // TODO: rename VScroll #[derive(Clone, Debug)] pub struct ScrollArea { max_height: f32, always_show_scroll: bool, auto_hide_scroll: bool, } impl Default for ScrollArea { fn default() -> Self { Self { max_height: 200.0, always_show_scroll: false, auto_hide_scroll: true, } } } impl ScrollArea { pub fn max_height(mut self, max_height: f32) -> Self { self.max_height = max_height; self } pub fn always_show_scroll(mut self, always_show_scroll: bool) -> Self { self.always_show_scroll = always_show_scroll; self } pub fn auto_hide_scroll(mut self, auto_hide_scroll: bool) -> Self { self.auto_hide_scroll = auto_hide_scroll; self } } struct Prepared { id: Id, state: State, current_scroll_bar_width: f32, always_show_scroll: bool, inner_rect: Rect, content_ui: Ui, } impl ScrollArea { fn begin(self, ui: &mut Ui) -> Prepared { let Self { max_height, always_show_scroll, auto_hide_scroll, } = self; let ctx = ui.ctx().clone(); let id = ui.make_child_id("scroll_area"); let state = ctx .memory() .scroll_areas .get(&id) .cloned() .unwrap_or_default(); // content: size of contents (generally large; that's why we want scroll bars) // outer: size of scroll area including scroll bar(s) // inner: excluding scroll bar(s). The area we clip the contents to. let max_scroll_bar_width = ui.style().item_spacing.x + 16.0; let current_scroll_bar_width = if state.show_scroll || !auto_hide_scroll { max_scroll_bar_width // TODO: animate? } else { 0.0 }; let outer_size = vec2( ui.available().width(), ui.available().height().min(max_height), ); let inner_size = outer_size - vec2(current_scroll_bar_width, 0.0); let inner_rect = Rect::from_min_size(ui.available().min, inner_size); let mut content_ui = ui.child_ui(Rect::from_min_size( inner_rect.min - state.offset, vec2(inner_size.x, f32::INFINITY), )); let mut content_clip_rect = inner_rect.expand(ui.style().clip_rect_margin); content_clip_rect = content_clip_rect.intersect(ui.clip_rect()); content_clip_rect.max.x = ui.clip_rect().max.x - current_scroll_bar_width; // Nice handling of forced resizing beyond the possible content_ui.set_clip_rect(content_clip_rect); Prepared { id, state, always_show_scroll, inner_rect, current_scroll_bar_width, content_ui, } } pub fn show<R>(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { let mut prepared = self.begin(ui); let ret = add_contents(&mut prepared.content_ui); prepared.end(ui); ret } } impl Prepared { fn end(self, ui: &mut Ui) { let Prepared { id, mut state, inner_rect, always_show_scroll, current_scroll_bar_width, content_ui, } = self; let content_size = content_ui.bounding_size(); let inner_rect = Rect::from_min_size( inner_rect.min, vec2( inner_rect.width().max(content_size.x), // Expand width to fit content inner_rect.height(), ), ); let outer_rect = Rect::from_min_size( inner_rect.min, inner_rect.size() + vec2(current_scroll_bar_width, 0.0), ); let content_is_too_small = content_size.y > inner_rect.height(); if content_is_too_small { // Drag contents to scroll (for touch screens mostly): let content_interact = ui.interact(inner_rect, id.with("area"), Sense::drag()); if content_interact.active { state.offset.y -= ui.input().mouse.delta.y; } } // TODO: check that nothing else is being interacted with if ui.contains_mouse(outer_rect) { state.offset.y -= ui.input().scroll_delta.y; } let show_scroll_this_frame = content_is_too_small || always_show_scroll; if show_scroll_this_frame || state.show_scroll { let margin = ui.style().item_spacing.x; // margin between contents and scroll bar let left = inner_rect.right() + margin; let right = outer_rect.right(); let corner_radius = (right - left) / 2.0; let top = inner_rect.top(); let bottom = inner_rect.bottom(); let outer_scroll_rect = Rect::from_min_max( pos2(left, inner_rect.top()), pos2(right, inner_rect.bottom()), ); let from_content = |content_y| remap_clamp(content_y, 0.0..=content_size.y, top..=bottom); let handle_rect = Rect::from_min_max( pos2(left, from_content(state.offset.y)), pos2(right, from_content(state.offset.y + inner_rect.height())), ); // intentionally use same id for inside and outside of handle let interact_id = id.with("vertical"); let mut interact = ui.interact(handle_rect, interact_id, Sense::click_and_drag()); if let Some(mouse_pos) = ui.input().mouse.pos { if interact.active { if inner_rect.top() <= mouse_pos.y && mouse_pos.y <= inner_rect.bottom() { state.offset.y += ui.input().mouse.delta.y * content_size.y / inner_rect.height(); } } else { // Check for mouse down outside handle: let scroll_bg_interact = ui.interact(outer_scroll_rect, interact_id, Sense::click_and_drag()); if scroll_bg_interact.active { // Center scroll at mouse pos: let mpos_top = mouse_pos.y - handle_rect.height() / 2.0; state.offset.y = remap(mpos_top, top..=bottom, 0.0..=content_size.y); } interact = interact.union(scroll_bg_interact); } } state.offset.y = state.offset.y.max(0.0); state.offset.y = state.offset.y.min(content_size.y - inner_rect.height()); // Avoid frame-delay by calculating a new handle rect: let mut handle_rect = Rect::from_min_max( pos2(left, from_content(state.offset.y)), pos2(right, from_content(state.offset.y + inner_rect.height())), ); let min_handle_height = (2.0 * corner_radius).max(8.0); if handle_rect.size().y < min_handle_height { handle_rect = Rect::from_center_size( handle_rect.center(), vec2(handle_rect.size().x, min_handle_height), ); } let style = ui.style(); let handle_fill = style.interact(&interact).fill; let handle_outline = style.interact(&interact).rect_outline; ui.add_paint_cmd(paint::PaintCmd::Rect { rect: outer_scroll_rect, corner_radius, fill: Some(ui.style().dark_bg_color), outline: None, }); ui.add_paint_cmd(paint::PaintCmd::Rect { rect: handle_rect.expand(-2.0), corner_radius, fill: Some(handle_fill), outline: handle_outline, }); } let size = vec2( outer_rect.size().x, outer_rect.size().y.min(content_size.y), // shrink if content is so small that we don't need scroll bars ); ui.allocate_space(size); state.offset.y = state.offset.y.min(content_size.y - inner_rect.height()); state.offset.y = state.offset.y.max(0.0); state.show_scroll = show_scroll_this_frame; ui.memory().scroll_areas.insert(id, state); } }
use rust_blog::handlers::*; use actix_web::{get, App, HttpResponse, HttpServer, Responder}; use diesel::r2d2::ConnectionManager; use diesel::MysqlConnection; use dotenv::dotenv; use std::env; #[get("/")] async fn index() -> impl Responder { HttpResponse::Ok().body("hello there, ya filthy animal!") } #[actix_web::main] async fn main() -> std::io::Result<()> { dotenv().ok(); let database_url = env::var("DATABASE_URL").unwrap(); let manager = ConnectionManager::<MysqlConnection>::new(database_url); let pool = r2d2::Pool::builder() .build(manager) .expect("Failed to create pool.\n"); println!("Starting server at port 8080..."); HttpServer::new(move || { App::new() .data(pool.clone()) .service(index) .service(get_users) .service(get_user) .service(create_user) .service(get_post) .service(get_posts) .service(create_post) }) .bind("0.0.0.0:8080")? .run() .await }
//! # Amiwô - API Documentation //! //! Hello, and welcome to the core Amiwô API documentation! //! This crate contains both various utility functions & types //! that I used across several applications as well as //! contribution to other third party modules //! //! # Structure //! Each module in this library is held behind a feature flag. //! The present feature list is below, with an asterisk next to //! the features that are enabled by default: //! //! * "rest" => Rocket extension //! * "json" => Serde extension //! //! The recommend way to include features from this crate via Cargo in your //! project is by adding a `[dependencies.amiwo]` section to your //! `Cargo.toml` file, setting `default-features` to false, and specifying //! features manually. For example, to use the Rocket module, you would add: //! //! ```toml,ignore //! [dependencies.amiwo] //! version = "*" //! default-features = false //! features = ["rest"] //! ``` //! //! This crate is expected to grow with time, adding new elements to outside crates #![feature(use_extern_macros)] #![feature(plugin)] #![plugin(rocket_codegen)] #[macro_use] extern crate log; extern crate hyper; extern crate rocket; extern crate serde; #[macro_use] extern crate serde_json; // Amiwo specific modules pub mod error; #[macro_use] pub mod macros; pub mod util; pub mod traits; pub mod types; pub mod contrib; // Errors, Types & Trait shortcuts pub use error::GenericError; #[cfg(feature = "amiwo_rocket")] pub use contrib::rocket::FormHashMap; pub use types::IsResponseJSON; pub use types::OneOrMany; pub use types::ResponseJSON; pub use traits::Pushable;
use specs::{DispatcherBuilder, Dispatcher, World}; use shrev::{EventChannel}; use crate::event; pub mod systems; pub mod viewport; use crate::app::viewport::Viewport; pub struct App { pub world: World, pub update_dispatcher: Dispatcher<'static, 'static>, } impl App { pub fn new(mut update_dispatcher: Dispatcher<'static, 'static>, ) -> Self { let mut world = World::new(); world.add_resource(Viewport::new(320, 240)); update_dispatcher.setup(&mut world.res); world.maintain(); App { world, update_dispatcher, } } pub fn update(&mut self, delta: u32) { self.update_dispatcher.dispatch(&self.world.res); self.world.maintain(); } }
use glib::translate::*; use javascriptcore_sys; glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct GlobalContextRef(Shared<javascriptcore_sys::_JSGlobalContextRef>); match fn { ref => |ptr| javascriptcore_sys::JSGlobalContextRetain(ptr), unref => |ptr| javascriptcore_sys::JSGlobalContextRelease(ptr), } }