text stringlengths 8 4.13M |
|---|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qsurface.h
// dst-file: /src/gui/qsurface.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
use super::qsurfaceformat::*; // 773
// use super::qplatformsurface::*; // 775
use super::super::core::qsize::*; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QSurface_Class_Size() -> c_int;
// proto: bool QSurface::supportsOpenGL();
fn C_ZNK8QSurface14supportsOpenGLEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QSurfaceFormat QSurface::format();
fn C_ZNK8QSurface6formatEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QPlatformSurface * QSurface::surfaceHandle();
fn C_ZNK8QSurface13surfaceHandleEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QSize QSurface::size();
fn C_ZNK8QSurface4sizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QSurface::~QSurface();
fn C_ZN8QSurfaceD2Ev(qthis: u64 /* *mut c_void*/);
} // <= ext block end
// body block begin =>
// class sizeof(QSurface)=24
#[derive(Default)]
pub struct QSurface {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QSurface {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QSurface {
return QSurface{qclsinst: qthis, ..Default::default()};
}
}
// proto: bool QSurface::supportsOpenGL();
impl /*struct*/ QSurface {
pub fn supportsOpenGL<RetType, T: QSurface_supportsOpenGL<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.supportsOpenGL(self);
// return 1;
}
}
pub trait QSurface_supportsOpenGL<RetType> {
fn supportsOpenGL(self , rsthis: & QSurface) -> RetType;
}
// proto: bool QSurface::supportsOpenGL();
impl<'a> /*trait*/ QSurface_supportsOpenGL<i8> for () {
fn supportsOpenGL(self , rsthis: & QSurface) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QSurface14supportsOpenGLEv()};
let mut ret = unsafe {C_ZNK8QSurface14supportsOpenGLEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QSurfaceFormat QSurface::format();
impl /*struct*/ QSurface {
pub fn format<RetType, T: QSurface_format<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.format(self);
// return 1;
}
}
pub trait QSurface_format<RetType> {
fn format(self , rsthis: & QSurface) -> RetType;
}
// proto: QSurfaceFormat QSurface::format();
impl<'a> /*trait*/ QSurface_format<QSurfaceFormat> for () {
fn format(self , rsthis: & QSurface) -> QSurfaceFormat {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QSurface6formatEv()};
let mut ret = unsafe {C_ZNK8QSurface6formatEv(rsthis.qclsinst)};
let mut ret1 = QSurfaceFormat::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QPlatformSurface * QSurface::surfaceHandle();
impl /*struct*/ QSurface {
pub fn surfaceHandle<RetType, T: QSurface_surfaceHandle<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.surfaceHandle(self);
// return 1;
}
}
pub trait QSurface_surfaceHandle<RetType> {
fn surfaceHandle(self , rsthis: & QSurface) -> RetType;
}
// proto: QPlatformSurface * QSurface::surfaceHandle();
impl<'a> /*trait*/ QSurface_surfaceHandle<u64> for () {
fn surfaceHandle(self , rsthis: & QSurface) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QSurface13surfaceHandleEv()};
let mut ret = unsafe {C_ZNK8QSurface13surfaceHandleEv(rsthis.qclsinst)};
return ret as u64; // 4
// return 1;
}
}
// proto: QSize QSurface::size();
impl /*struct*/ QSurface {
pub fn size<RetType, T: QSurface_size<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.size(self);
// return 1;
}
}
pub trait QSurface_size<RetType> {
fn size(self , rsthis: & QSurface) -> RetType;
}
// proto: QSize QSurface::size();
impl<'a> /*trait*/ QSurface_size<QSize> for () {
fn size(self , rsthis: & QSurface) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QSurface4sizeEv()};
let mut ret = unsafe {C_ZNK8QSurface4sizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QSurface::~QSurface();
impl /*struct*/ QSurface {
pub fn free<RetType, T: QSurface_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QSurface_free<RetType> {
fn free(self , rsthis: & QSurface) -> RetType;
}
// proto: void QSurface::~QSurface();
impl<'a> /*trait*/ QSurface_free<()> for () {
fn free(self , rsthis: & QSurface) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QSurfaceD2Ev()};
unsafe {C_ZN8QSurfaceD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// <= body block end
|
use serde::Serialize;
#[derive(Serialize)]
#[serde(tag = "type")]
enum Message {
Request {
id: &'static str,
method: &'static str,
params: i8,
},
Response {
id: &'static str,
result: i8,
},
}
fn main() {
let data = Message::Request {
id: "...",
method: "...",
params: 1,
};
let out = coruscant_nbt::to_string_transcript(&data).unwrap();
println!("{}", out);
let data = Message::Response {
id: "...",
result: 2,
};
let out = coruscant_nbt::to_string_transcript(&data).unwrap();
println!("{}", out);
}
|
use std::cmp;
use std::collections::HashMap;
use std::env;
use std::error::Error;
use std::fs;
pub fn frequent_words(text: &[u8], k: usize) -> Vec<String> {
let mut frequent = HashMap::new();
let mut max = 0;
text.windows(k)
.map(|x| {
let kmer = frequent.entry(x).or_insert(0);
*kmer += 1;
max = cmp::max(max, *kmer);
})
.count();
frequent
.iter()
.filter_map(|(&kmer, &count)| {
if count == max {
Some(String::from_utf8(kmer.to_vec()).unwrap())
} else {
None
}
})
.collect()
}
fn main() -> Result<(), Box<dyn Error>> {
let input: String = env::args()
.nth(1)
.unwrap_or("data/rosalind_ba1b.txt".into());
let data = fs::read_to_string(input)?;
let mut lines = data.lines();
let text = lines.next().unwrap();
let k = lines.next().unwrap().parse()?;
for word in frequent_words(text.as_bytes(), k) {
print!("{} ", word);
}
println!();
Ok(())
}
|
use crate::name::Name;
use crate::rr_type::RRType;
use crate::util::InputBuffer;
use anyhow::{ensure, Result};
use std::net::{Ipv4Addr, Ipv6Addr};
pub fn name_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(Name, u16)> {
_name_from_wire(buf, len)
}
pub fn name_uncompressed_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(Name, u16)> {
_name_from_wire(buf, len)
}
fn _name_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(Name, u16)> {
let p = buf.position();
let name = Name::from_wire(buf)?;
let name_len = (buf.position() - p) as u16;
ensure!(len >= name_len, "wire is too short for domain name");
Ok((name, len - name_len))
}
pub fn ipv4_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(Ipv4Addr, u16)> {
ensure!(len >= 4, "wire is too short for ipv4 address");
let ip = buf
.read_bytes(4)
.map(|bytes| Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]))?;
Ok((ip, len - 4))
}
pub fn ipv6_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(Ipv6Addr, u16)> {
ensure!(len >= 16, "wire is too short for ipv6 address {}", len);
let ip = buf.read_bytes(16).map(|bytes| {
let mut octs = [0; 16];
octs.copy_from_slice(bytes);
Ipv6Addr::from(octs)
})?;
Ok((ip, len - 16))
}
pub fn u8_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(u8, u16)> {
ensure!(len >= 1, "wire is too short for u8");
Ok((buf.read_u8()?, len - 1))
}
pub fn u16_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(u16, u16)> {
ensure!(len >= 2, "wire is too short for u16");
Ok((buf.read_u16()?, len - 2))
}
pub fn rrtype_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(RRType, u16)> {
ensure!(len >= 2, "wire is too short for u16");
Ok((RRType::new(buf.read_u16()?), len - 2))
}
pub fn u32_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(u32, u16)> {
ensure!(len >= 4, "wire is too short for u32");
Ok((buf.read_u32()?, len - 4))
}
pub fn text_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(Vec<Vec<u8>>, u16)> {
let mut data = Vec::new();
let mut left_len = len;
while left_len > 0 {
let (txt, len) = byte_binary_from_wire(buf, left_len)?;
data.push(txt);
left_len = len;
}
Ok((data, 0))
}
pub fn byte_binary_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(Vec<u8>, u16)> {
let dl = buf.read_u8()? as u16;
ensure!(len > dl, "wire is too short for byte binary");
let data = buf.read_bytes(dl as usize)?;
Ok((data.to_vec(), len - dl - 1))
}
pub fn binary_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(Vec<u8>, u16)> {
let data = buf.read_bytes(len as usize)?;
Ok((data.to_vec(), 0))
}
|
//! Persistent accounts are stored in below path location:
//! <path>/<pid>/data/
//!
//! The persistent store would allow for this mode of operation:
//! - Concurrent single thread append with many concurrent readers.
//!
//! The underlying memory is memory mapped to a file. The accounts would be
//! stored across multiple files and the mappings of file and offset of a
//! particular account would be stored in a shared index. This will allow for
//! concurrent commits without blocking reads, which will sequentially write
//! to memory, ssd or disk, and should be as fast as the hardware allow for.
//! The only required in memory data structure with a write lock is the index,
//! which should be fast to update.
//!
//! AppendVec's only store accounts for single forks. To bootstrap the
//! index from a persistent store of AppendVec's, the entries include
//! a "write_version". A single global atomic `AccountsDB::write_version`
//! tracks the number of commits to the entire data store. So the latest
//! commit for each fork entry would be indexed.
use crate::accounts_index::{AccountsIndex, Fork};
use crate::append_vec::{AppendVec, StorageMeta, StoredAccount};
use hashbrown::{HashMap, HashSet};
use log::*;
use rand::{thread_rng, Rng};
use rayon::prelude::*;
use morgan_interface::account::Account;
use morgan_interface::pubkey::Pubkey;
use std::fs::{create_dir_all, remove_dir_all};
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};
const ACCOUNT_DATA_FILE_SIZE: u64 = 64 * 1024 * 1024;
const ACCOUNT_DATA_FILE: &str = "data";
#[derive(Debug, Default)]
pub struct ErrorCounters {
pub account_not_found: usize,
pub account_in_use: usize,
pub account_loaded_twice: usize,
pub blockhash_not_found: usize,
pub blockhash_too_old: usize,
pub reserve_blockhash: usize,
pub invalid_account_for_fee: usize,
pub insufficient_funds: usize,
pub invalid_account_index: usize,
pub duplicate_signature: usize,
pub call_chain_too_deep: usize,
pub missing_signature_for_fee: usize,
}
#[derive(Default, Clone)]
pub struct AccountInfo {
/// index identifying the append storage
id: AppendVecId,
/// offset into the storage
offset: usize,
/// difs in the account used when squashing kept for optimization
/// purposes to remove accounts with zero balance.
difs: u64,
}
/// An offset into the AccountsDB::storage vector
type AppendVecId = usize;
pub type AccountStorage = HashMap<usize, Arc<AccountStorageEntry>>;
pub type InstructionAccounts = Vec<Account>;
pub type InstructionLoaders = Vec<Vec<(Pubkey, Account)>>;
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum AccountStorageStatus {
StorageAvailable = 0,
StorageFull = 1,
}
/// Persistent storage structure holding the accounts
pub struct AccountStorageEntry {
id: AppendVecId,
fork_id: Fork,
/// storage holding the accounts
accounts: AppendVec,
/// Keeps track of the number of accounts stored in a specific AppendVec.
/// This is periodically checked to reuse the stores that do not have
/// any accounts in it
/// status corresponding to the storage, lets us know that
/// the append_vec, once maxed out, then emptied, can be reclaimed
count_and_status: RwLock<(usize, AccountStorageStatus)>,
}
impl AccountStorageEntry {
pub fn new(path: &str, fork_id: Fork, id: usize, file_size: u64) -> Self {
let p = format!("{}/{}", path, id);
let path = Path::new(&p);
let _ignored = remove_dir_all(path);
create_dir_all(path).expect("Create directory failed");
let accounts = AppendVec::new(&path.join(ACCOUNT_DATA_FILE), true, file_size as usize);
AccountStorageEntry {
id,
fork_id,
accounts,
count_and_status: RwLock::new((0, AccountStorageStatus::StorageAvailable)),
}
}
pub fn set_status(&self, mut status: AccountStorageStatus) {
let mut count_and_status = self.count_and_status.write().unwrap();
let count = count_and_status.0;
if status == AccountStorageStatus::StorageFull && count == 0 {
// this case arises when the append_vec is full (store_ptrs fails),
// but all accounts have already been removed from the storage
//
// the only time it's safe to call reset() on an append_vec is when
// every account has been removed
// **and**
// the append_vec has previously been completely full
//
self.accounts.reset();
status = AccountStorageStatus::StorageAvailable;
}
*count_and_status = (count, status);
}
pub fn status(&self) -> AccountStorageStatus {
self.count_and_status.read().unwrap().1
}
pub fn count(&self) -> usize {
self.count_and_status.read().unwrap().0
}
fn add_account(&self) {
let mut count_and_status = self.count_and_status.write().unwrap();
*count_and_status = (count_and_status.0 + 1, count_and_status.1);
}
fn remove_account(&self) {
let mut count_and_status = self.count_and_status.write().unwrap();
let (count, mut status) = *count_and_status;
if count == 1 && status == AccountStorageStatus::StorageFull {
// this case arises when we remove the last account from the
// storage, but we've learned from previous write attempts that
// the storage is full
//
// the only time it's safe to call reset() on an append_vec is when
// every account has been removed
// **and**
// the append_vec has previously been completely full
//
// otherwise, the storage may be in flight with a store()
// call
self.accounts.reset();
status = AccountStorageStatus::StorageAvailable;
}
*count_and_status = (count - 1, status);
}
}
// This structure handles the load/store of the accounts
#[derive(Default)]
pub struct AccountsDB {
/// Keeps tracks of index into AppendVec on a per fork basis
pub accounts_index: RwLock<AccountsIndex<AccountInfo>>,
/// Account storage
pub storage: RwLock<AccountStorage>,
/// distribute the accounts across storage lists
next_id: AtomicUsize,
/// write version
write_version: AtomicUsize,
/// Set of storage paths to pick from
paths: Vec<String>,
/// Starting file size of appendvecs
file_size: u64,
}
pub fn get_paths_vec(paths: &str) -> Vec<String> {
paths.split(',').map(ToString::to_string).collect()
}
impl AccountsDB {
pub fn new_with_file_size(paths: &str, file_size: u64) -> Self {
let paths = get_paths_vec(&paths);
AccountsDB {
accounts_index: RwLock::new(AccountsIndex::default()),
storage: RwLock::new(HashMap::new()),
next_id: AtomicUsize::new(0),
write_version: AtomicUsize::new(0),
paths,
file_size,
}
}
pub fn new(paths: &str) -> Self {
Self::new_with_file_size(paths, ACCOUNT_DATA_FILE_SIZE)
}
fn new_storage_entry(&self, fork_id: Fork, path: &str) -> AccountStorageEntry {
AccountStorageEntry::new(
path,
fork_id,
self.next_id.fetch_add(1, Ordering::Relaxed),
self.file_size,
)
}
pub fn has_accounts(&self, fork: Fork) -> bool {
for x in self.storage.read().unwrap().values() {
if x.fork_id == fork && x.count() > 0 {
return true;
}
}
false
}
/// Scan a specific fork through all the account storage in parallel with sequential read
// PERF: Sequentially read each storage entry in parallel
pub fn scan_account_storage<F, B>(&self, fork_id: Fork, scan_func: F) -> Vec<B>
where
F: Fn(&StoredAccount, &mut B) -> (),
F: Send + Sync,
B: Send + Default,
{
let storage_maps: Vec<Arc<AccountStorageEntry>> = self
.storage
.read()
.unwrap()
.values()
.filter(|store| store.fork_id == fork_id)
.cloned()
.collect();
storage_maps
.into_par_iter()
.map(|storage| {
let accounts = storage.accounts.accounts(0);
let mut retval = B::default();
accounts
.iter()
.for_each(|stored_account| scan_func(stored_account, &mut retval));
retval
})
.collect()
}
pub fn load(
storage: &AccountStorage,
ancestors: &HashMap<Fork, usize>,
accounts_index: &AccountsIndex<AccountInfo>,
pubkey: &Pubkey,
) -> Option<(Account, Fork)> {
let (info, fork) = accounts_index.get(pubkey, ancestors)?;
//TODO: thread this as a ref
storage
.get(&info.id)
.and_then(|store| Some(store.accounts.get_account(info.offset)?.0.clone_account()))
.map(|account| (account, fork))
}
pub fn load_slow(
&self,
ancestors: &HashMap<Fork, usize>,
pubkey: &Pubkey,
) -> Option<(Account, Fork)> {
let accounts_index = self.accounts_index.read().unwrap();
let storage = self.storage.read().unwrap();
Self::load(&storage, ancestors, &accounts_index, pubkey)
}
fn fork_storage(&self, fork_id: Fork) -> Arc<AccountStorageEntry> {
let mut candidates: Vec<Arc<AccountStorageEntry>> = {
let stores = self.storage.read().unwrap();
stores
.values()
.filter_map(|x| {
if x.status() == AccountStorageStatus::StorageAvailable && x.fork_id == fork_id
{
Some(x.clone())
} else {
None
}
})
.collect()
};
if candidates.is_empty() {
let mut stores = self.storage.write().unwrap();
let path_index = thread_rng().gen_range(0, self.paths.len());
let storage = Arc::new(self.new_storage_entry(fork_id, &self.paths[path_index]));
stores.insert(storage.id, storage.clone());
candidates.push(storage);
}
let rv = thread_rng().gen_range(0, candidates.len());
candidates[rv].clone()
}
pub fn purge_fork(&self, fork: Fork) {
//add_root should be called first
let is_root = self.accounts_index.read().unwrap().is_root(fork);
trace!("PURGING {} {}", fork, is_root);
if !is_root {
self.storage.write().unwrap().retain(|_, v| {
trace!("PURGING {} {}", v.fork_id, fork);
v.fork_id != fork
});
}
}
fn store_accounts(&self, fork_id: Fork, accounts: &[(&Pubkey, &Account)]) -> Vec<AccountInfo> {
let with_meta: Vec<(StorageMeta, &Account)> = accounts
.iter()
.map(|(pubkey, account)| {
let write_version = self.write_version.fetch_add(1, Ordering::Relaxed) as u64;
let data_len = if account.difs == 0 {
0
} else {
account.data.len() as u64
};
let meta = StorageMeta {
write_version,
pubkey: **pubkey,
data_len,
};
(meta, *account)
})
.collect();
let mut infos: Vec<AccountInfo> = vec![];
while infos.len() < with_meta.len() {
let storage = self.fork_storage(fork_id);
let rvs = storage.accounts.append_accounts(&with_meta[infos.len()..]);
if rvs.is_empty() {
storage.set_status(AccountStorageStatus::StorageFull);
}
for (offset, (_, account)) in rvs.iter().zip(&with_meta[infos.len()..]) {
storage.add_account();
infos.push(AccountInfo {
id: storage.id,
offset: *offset,
difs: account.difs,
});
}
}
infos
}
fn update_index(
&self,
fork_id: Fork,
infos: Vec<AccountInfo>,
accounts: &[(&Pubkey, &Account)],
) -> Vec<(Fork, AccountInfo)> {
let mut index = self.accounts_index.write().unwrap();
let mut reclaims = vec![];
for (i, info) in infos.into_iter().enumerate() {
let key = &accounts[i].0;
reclaims.extend(index.insert(fork_id, key, info).into_iter())
}
reclaims
}
fn remove_dead_accounts(&self, reclaims: Vec<(Fork, AccountInfo)>) -> HashSet<Fork> {
let storage = self.storage.read().unwrap();
for (fork_id, account_info) in reclaims {
if let Some(store) = storage.get(&account_info.id) {
assert_eq!(
fork_id, store.fork_id,
"AccountDB::accounts_index corrupted. Storage should only point to one fork"
);
store.remove_account();
}
}
//TODO: performance here could be improved if AccountsDB::storage was organized by fork
let dead_forks: HashSet<Fork> = storage
.values()
.filter_map(|x| {
if x.count() == 0 {
Some(x.fork_id)
} else {
None
}
})
.collect();
let live_forks: HashSet<Fork> = storage
.values()
.filter_map(|x| if x.count() > 0 { Some(x.fork_id) } else { None })
.collect();
dead_forks.difference(&live_forks).cloned().collect()
}
fn cleanup_dead_forks(&self, dead_forks: &mut HashSet<Fork>) {
let mut index = self.accounts_index.write().unwrap();
// a fork is not totally dead until it is older than the root
dead_forks.retain(|fork| *fork < index.last_root);
for fork in dead_forks.iter() {
index.cleanup_dead_fork(*fork);
}
}
/// Store the account update.
pub fn store(&self, fork_id: Fork, accounts: &[(&Pubkey, &Account)]) {
let infos = self.store_accounts(fork_id, accounts);
let reclaims = self.update_index(fork_id, infos, accounts);
trace!("reclaim: {}", reclaims.len());
let mut dead_forks = self.remove_dead_accounts(reclaims);
trace!("dead_forks: {}", dead_forks.len());
self.cleanup_dead_forks(&mut dead_forks);
trace!("purge_forks: {}", dead_forks.len());
for fork in dead_forks {
self.purge_fork(fork);
}
}
pub fn add_root(&self, fork: Fork) {
self.accounts_index.write().unwrap().add_root(fork)
}
}
#[cfg(test)]
mod tests {
// TODO: all the bank tests are bank specific, issue: 2194
use super::*;
use rand::{thread_rng, Rng};
use morgan_interface::account::Account;
fn cleanup_paths(paths: &str) {
let paths = get_paths_vec(&paths);
paths.iter().for_each(|p| {
let _ignored = remove_dir_all(p);
});
}
struct TempPaths {
pub paths: String,
}
impl Drop for TempPaths {
fn drop(&mut self) {
cleanup_paths(&self.paths);
}
}
fn get_tmp_accounts_path(paths: &str) -> TempPaths {
let vpaths = get_paths_vec(paths);
let out_dir = std::env::var("OUT_DIR").unwrap_or_else(|_| "target".to_string());
let vpaths: Vec<_> = vpaths
.iter()
.map(|path| format!("{}/{}", out_dir, path))
.collect();
TempPaths {
paths: vpaths.join(","),
}
}
#[macro_export]
macro_rules! tmp_accounts_name {
() => {
&format!("{}-{}", file!(), line!())
};
}
#[macro_export]
macro_rules! get_tmp_accounts_path {
() => {
get_tmp_accounts_path(tmp_accounts_name!())
};
}
#[test]
fn test_accountsdb_add_root() {
morgan_logger::setup();
let paths = get_tmp_accounts_path!();
let db = AccountsDB::new(&paths.paths);
let key = Pubkey::default();
let account0 = Account::new(1, 0, 0, &key);
db.store(0, &[(&key, &account0)]);
db.add_root(0);
let ancestors = vec![(1, 1)].into_iter().collect();
assert_eq!(db.load_slow(&ancestors, &key), Some((account0, 0)));
}
#[test]
fn test_accountsdb_latest_ancestor() {
morgan_logger::setup();
let paths = get_tmp_accounts_path!();
let db = AccountsDB::new(&paths.paths);
let key = Pubkey::default();
let account0 = Account::new(1, 0, 0, &key);
db.store(0, &[(&key, &account0)]);
let account1 = Account::new(0, 0, 0, &key);
db.store(1, &[(&key, &account1)]);
let ancestors = vec![(1, 1)].into_iter().collect();
assert_eq!(&db.load_slow(&ancestors, &key).unwrap().0, &account1);
let ancestors = vec![(1, 1), (0, 0)].into_iter().collect();
assert_eq!(&db.load_slow(&ancestors, &key).unwrap().0, &account1);
}
#[test]
fn test_accountsdb_latest_ancestor_with_root() {
morgan_logger::setup();
let paths = get_tmp_accounts_path!();
let db = AccountsDB::new(&paths.paths);
let key = Pubkey::default();
let account0 = Account::new(1, 0, 0, &key);
db.store(0, &[(&key, &account0)]);
let account1 = Account::new(0, 0, 0, &key);
db.store(1, &[(&key, &account1)]);
db.add_root(0);
let ancestors = vec![(1, 1)].into_iter().collect();
assert_eq!(&db.load_slow(&ancestors, &key).unwrap().0, &account1);
let ancestors = vec![(1, 1), (0, 0)].into_iter().collect();
assert_eq!(&db.load_slow(&ancestors, &key).unwrap().0, &account1);
}
#[test]
fn test_accountsdb_root_one_fork() {
morgan_logger::setup();
let paths = get_tmp_accounts_path!();
let db = AccountsDB::new(&paths.paths);
let key = Pubkey::default();
let account0 = Account::new(1, 0, 0, &key);
// store value 1 in the "root", i.e. db zero
db.store(0, &[(&key, &account0)]);
// now we have:
//
// root0 -> key.difs==1
// / \
// / \
// key.difs==0 <- fork1 \
// fork2 -> key.difs==1
// (via root0)
// store value 0 in one child
let account1 = Account::new(0, 0, 0, &key);
db.store(1, &[(&key, &account1)]);
// masking accounts is done at the Accounts level, at accountsDB we see
// original account (but could also accept "None", which is implemented
// at the Accounts level)
let ancestors = vec![(0, 0), (1, 1)].into_iter().collect();
assert_eq!(&db.load_slow(&ancestors, &key).unwrap().0, &account1);
// we should see 1 token in fork 2
let ancestors = vec![(0, 0), (2, 2)].into_iter().collect();
assert_eq!(&db.load_slow(&ancestors, &key).unwrap().0, &account0);
db.add_root(0);
let ancestors = vec![(1, 1)].into_iter().collect();
assert_eq!(db.load_slow(&ancestors, &key), Some((account1, 1)));
let ancestors = vec![(2, 2)].into_iter().collect();
assert_eq!(db.load_slow(&ancestors, &key), Some((account0, 0))); // original value
}
#[test]
fn test_accountsdb_add_root_many() {
let paths = get_tmp_accounts_path!();
let db = AccountsDB::new(&paths.paths);
let mut pubkeys: Vec<Pubkey> = vec![];
create_account(&db, &mut pubkeys, 0, 100, 0, 0);
for _ in 1..100 {
let idx = thread_rng().gen_range(0, 99);
let ancestors = vec![(0, 0)].into_iter().collect();
let account = db.load_slow(&ancestors, &pubkeys[idx]).unwrap();
let mut default_account = Account::default();
default_account.difs = (idx + 1) as u64;
assert_eq!((default_account, 0), account);
}
db.add_root(0);
// check that all the accounts appear with a new root
for _ in 1..100 {
let idx = thread_rng().gen_range(0, 99);
let ancestors = vec![(0, 0)].into_iter().collect();
let account0 = db.load_slow(&ancestors, &pubkeys[idx]).unwrap();
let ancestors = vec![(1, 1)].into_iter().collect();
let account1 = db.load_slow(&ancestors, &pubkeys[idx]).unwrap();
let mut default_account = Account::default();
default_account.difs = (idx + 1) as u64;
assert_eq!(&default_account, &account0.0);
assert_eq!(&default_account, &account1.0);
}
}
#[test]
fn test_accountsdb_count_stores() {
let paths = get_tmp_accounts_path!();
let db = AccountsDB::new(&paths.paths);
let mut pubkeys: Vec<Pubkey> = vec![];
create_account(
&db,
&mut pubkeys,
0,
2,
ACCOUNT_DATA_FILE_SIZE as usize / 3,
0,
);
assert!(check_storage(&db, 2));
let pubkey = Pubkey::new_rand();
let account = Account::new(1, 0, ACCOUNT_DATA_FILE_SIZE as usize / 3, &pubkey);
db.store(1, &[(&pubkey, &account)]);
db.store(1, &[(&pubkeys[0], &account)]);
{
let stores = db.storage.read().unwrap();
assert_eq!(stores.len(), 2);
assert_eq!(stores[&0].count(), 2);
assert_eq!(stores[&1].count(), 2);
}
db.add_root(1);
{
let stores = db.storage.read().unwrap();
assert_eq!(stores.len(), 2);
assert_eq!(stores[&0].count(), 2);
assert_eq!(stores[&1].count(), 2);
}
}
#[test]
fn test_accounts_unsquashed() {
let key = Pubkey::default();
// 1 token in the "root", i.e. db zero
let paths = get_tmp_accounts_path!();
let db0 = AccountsDB::new(&paths.paths);
let account0 = Account::new(1, 0, 0, &key);
db0.store(0, &[(&key, &account0)]);
// 0 difs in the child
let account1 = Account::new(0, 0, 0, &key);
db0.store(1, &[(&key, &account1)]);
// masking accounts is done at the Accounts level, at accountsDB we see
// original account
let ancestors = vec![(0, 0), (1, 1)].into_iter().collect();
assert_eq!(db0.load_slow(&ancestors, &key), Some((account1, 1)));
let ancestors = vec![(0, 0)].into_iter().collect();
assert_eq!(db0.load_slow(&ancestors, &key), Some((account0, 0)));
}
fn create_account(
accounts: &AccountsDB,
pubkeys: &mut Vec<Pubkey>,
fork: Fork,
num: usize,
space: usize,
num_vote: usize,
) {
for t in 0..num {
let pubkey = Pubkey::new_rand();
let account = Account::new((t + 1) as u64, 0, space, &Account::default().owner);
pubkeys.push(pubkey.clone());
let ancestors = vec![(fork, 0)].into_iter().collect();
assert!(accounts.load_slow(&ancestors, &pubkey).is_none());
accounts.store(fork, &[(&pubkey, &account)]);
}
for t in 0..num_vote {
let pubkey = Pubkey::new_rand();
let account = Account::new((num + t + 1) as u64, 0, space, &morgan_vote_api::id());
pubkeys.push(pubkey.clone());
let ancestors = vec![(fork, 0)].into_iter().collect();
assert!(accounts.load_slow(&ancestors, &pubkey).is_none());
accounts.store(fork, &[(&pubkey, &account)]);
}
}
fn update_accounts(accounts: &AccountsDB, pubkeys: &Vec<Pubkey>, fork: Fork, range: usize) {
for _ in 1..1000 {
let idx = thread_rng().gen_range(0, range);
let ancestors = vec![(fork, 0)].into_iter().collect();
if let Some((mut account, _)) = accounts.load_slow(&ancestors, &pubkeys[idx]) {
account.difs = account.difs + 1;
accounts.store(fork, &[(&pubkeys[idx], &account)]);
if account.difs == 0 {
let ancestors = vec![(fork, 0)].into_iter().collect();
assert!(accounts.load_slow(&ancestors, &pubkeys[idx]).is_none());
} else {
let mut default_account = Account::default();
default_account.difs = account.difs;
assert_eq!(default_account, account);
}
}
}
}
fn check_storage(accounts: &AccountsDB, count: usize) -> bool {
let stores = accounts.storage.read().unwrap();
assert_eq!(stores.len(), 1);
assert_eq!(stores[&0].status(), AccountStorageStatus::StorageAvailable);
stores[&0].count() == count
}
fn check_accounts(accounts: &AccountsDB, pubkeys: &Vec<Pubkey>, fork: Fork) {
for _ in 1..100 {
let idx = thread_rng().gen_range(0, 99);
let ancestors = vec![(fork, 0)].into_iter().collect();
let account = accounts.load_slow(&ancestors, &pubkeys[idx]).unwrap();
let mut default_account = Account::default();
default_account.difs = (idx + 1) as u64;
assert_eq!((default_account, 0), account);
}
}
#[test]
fn test_account_one() {
let paths = get_tmp_accounts_path!();
let accounts = AccountsDB::new(&paths.paths);
let mut pubkeys: Vec<Pubkey> = vec![];
create_account(&accounts, &mut pubkeys, 0, 1, 0, 0);
let ancestors = vec![(0, 0)].into_iter().collect();
let account = accounts.load_slow(&ancestors, &pubkeys[0]).unwrap();
let mut default_account = Account::default();
default_account.difs = 1;
assert_eq!((default_account, 0), account);
}
#[test]
fn test_account_many() {
let paths = get_tmp_accounts_path("many0,many1");
let accounts = AccountsDB::new(&paths.paths);
let mut pubkeys: Vec<Pubkey> = vec![];
create_account(&accounts, &mut pubkeys, 0, 100, 0, 0);
check_accounts(&accounts, &pubkeys, 0);
}
#[test]
fn test_account_update() {
let paths = get_tmp_accounts_path!();
let accounts = AccountsDB::new(&paths.paths);
let mut pubkeys: Vec<Pubkey> = vec![];
create_account(&accounts, &mut pubkeys, 0, 100, 0, 0);
update_accounts(&accounts, &pubkeys, 0, 99);
assert_eq!(check_storage(&accounts, 100), true);
}
#[test]
fn test_account_grow_many() {
let paths = get_tmp_accounts_path("many2,many3");
let size = 4096;
let accounts = AccountsDB::new_with_file_size(&paths.paths, size);
let mut keys = vec![];
for i in 0..9 {
let key = Pubkey::new_rand();
let account = Account::new(i + 1, 0, size as usize / 4, &key);
accounts.store(0, &[(&key, &account)]);
keys.push(key);
}
for (i, key) in keys.iter().enumerate() {
let ancestors = vec![(0, 0)].into_iter().collect();
assert_eq!(
accounts.load_slow(&ancestors, &key).unwrap().0.difs,
(i as u64) + 1
);
}
let mut append_vec_histogram = HashMap::new();
for storage in accounts.storage.read().unwrap().values() {
*append_vec_histogram.entry(storage.fork_id).or_insert(0) += 1;
}
for count in append_vec_histogram.values() {
assert!(*count >= 2);
}
}
#[test]
fn test_account_grow() {
let paths = get_tmp_accounts_path!();
let accounts = AccountsDB::new(&paths.paths);
let count = [0, 1];
let status = [
AccountStorageStatus::StorageAvailable,
AccountStorageStatus::StorageFull,
];
let pubkey1 = Pubkey::new_rand();
let account1 = Account::new(1, 0, ACCOUNT_DATA_FILE_SIZE as usize / 2, &pubkey1);
accounts.store(0, &[(&pubkey1, &account1)]);
{
let stores = accounts.storage.read().unwrap();
assert_eq!(stores.len(), 1);
assert_eq!(stores[&0].count(), 1);
assert_eq!(stores[&0].status(), AccountStorageStatus::StorageAvailable);
}
let pubkey2 = Pubkey::new_rand();
let account2 = Account::new(1, 0, ACCOUNT_DATA_FILE_SIZE as usize / 2, &pubkey2);
accounts.store(0, &[(&pubkey2, &account2)]);
{
let stores = accounts.storage.read().unwrap();
assert_eq!(stores.len(), 2);
assert_eq!(stores[&0].count(), 1);
assert_eq!(stores[&0].status(), AccountStorageStatus::StorageFull);
assert_eq!(stores[&1].count(), 1);
assert_eq!(stores[&1].status(), AccountStorageStatus::StorageAvailable);
}
let ancestors = vec![(0, 0)].into_iter().collect();
assert_eq!(
accounts.load_slow(&ancestors, &pubkey1).unwrap().0,
account1
);
assert_eq!(
accounts.load_slow(&ancestors, &pubkey2).unwrap().0,
account2
);
// lots of stores, but 3 storages should be enough for everything
for i in 0..25 {
let index = i % 2;
accounts.store(0, &[(&pubkey1, &account1)]);
{
let stores = accounts.storage.read().unwrap();
assert_eq!(stores.len(), 3);
assert_eq!(stores[&0].count(), count[index]);
assert_eq!(stores[&0].status(), status[0]);
assert_eq!(stores[&1].count(), 1);
assert_eq!(stores[&1].status(), status[1]);
assert_eq!(stores[&2].count(), count[index ^ 1]);
assert_eq!(stores[&2].status(), status[0]);
}
let ancestors = vec![(0, 0)].into_iter().collect();
assert_eq!(
accounts.load_slow(&ancestors, &pubkey1).unwrap().0,
account1
);
assert_eq!(
accounts.load_slow(&ancestors, &pubkey2).unwrap().0,
account2
);
}
}
#[test]
fn test_purge_fork_not_root() {
let paths = get_tmp_accounts_path!();
let accounts = AccountsDB::new(&paths.paths);
let mut pubkeys: Vec<Pubkey> = vec![];
create_account(&accounts, &mut pubkeys, 0, 1, 0, 0);
let ancestors = vec![(0, 0)].into_iter().collect();
assert!(accounts.load_slow(&ancestors, &pubkeys[0]).is_some());;
accounts.purge_fork(0);
assert!(accounts.load_slow(&ancestors, &pubkeys[0]).is_none());;
}
#[test]
fn test_purge_fork_after_root() {
let paths = get_tmp_accounts_path!();
let accounts = AccountsDB::new(&paths.paths);
let mut pubkeys: Vec<Pubkey> = vec![];
create_account(&accounts, &mut pubkeys, 0, 1, 0, 0);
let ancestors = vec![(0, 0)].into_iter().collect();
accounts.add_root(0);
accounts.purge_fork(0);
assert!(accounts.load_slow(&ancestors, &pubkeys[0]).is_some());
}
#[test]
fn test_lazy_gc_fork() {
//This test is pedantic
//A fork is purged when a non root bank is cleaned up. If a fork is behind root but it is
//not root, it means we are retaining dead banks.
let paths = get_tmp_accounts_path!();
let accounts = AccountsDB::new(&paths.paths);
let pubkey = Pubkey::new_rand();
let account = Account::new(1, 0, 0, &Account::default().owner);
//store an account
accounts.store(0, &[(&pubkey, &account)]);
let ancestors = vec![(0, 0)].into_iter().collect();
let info = accounts
.accounts_index
.read()
.unwrap()
.get(&pubkey, &ancestors)
.unwrap()
.0
.clone();
//fork 0 is behind root, but it is not root, therefore it is purged
accounts.add_root(1);
assert!(accounts.accounts_index.read().unwrap().is_purged(0));
//fork is still there, since gc is lazy
assert!(accounts.storage.read().unwrap().get(&info.id).is_some());
//store causes cleanup
accounts.store(1, &[(&pubkey, &account)]);
//fork is gone
assert!(accounts.storage.read().unwrap().get(&info.id).is_none());
//new value is there
let ancestors = vec![(1, 1)].into_iter().collect();
assert_eq!(accounts.load_slow(&ancestors, &pubkey), Some((account, 1)));
}
}
|
use crate::entity::Entity;
use crate::mouse::*;
use crate::State;
use crate::{BuildHandler, Event, EventHandler, WindowEvent};
use crate::style::{Display, Length};
use crate::widgets::slider::SliderEvent;
use crate::widgets::Element;
pub struct AudioLevelBar {
front: Entity,
level: f32,
}
impl AudioLevelBar {
pub fn new() -> Self {
AudioLevelBar {
front: Entity::null(),
level: 0.0,
}
}
}
impl BuildHandler for AudioLevelBar {
type Ret = Entity;
fn on_build(&mut self, state: &mut State, entity: Entity) -> Self::Ret {
self.front = Element::new().build(state, entity, |builder| {
builder.set_height(Length::Percentage(0.5)).class("front")
});
state.style.insert_element(entity, "level_bar");
entity
}
}
impl EventHandler for AudioLevelBar {
fn on_event(&mut self, state: &mut State, entity: Entity, event: &mut Event) -> bool {
return false;
}
}
// pub struct AudioLevels {
// }
|
use std::cmp::max;
use std::collections::VecDeque;
use futures::Async;
use futures::Future;
use futures::Stream;
use crate::error::Error;
use crate::responses::Update;
use std::i64;
pub struct UpdatesPoolStream<Fut, Sender> {
pub send_request: Sender,
pub buffer: VecDeque<Update>,
pub executing_request: Fut,
pub is_canceled: bool,
pub last_id: Option<i64>,
pub has_error: bool,
}
impl<Fut, Sender> Stream for UpdatesPoolStream<Fut, Sender>
where
Fut: Future<Item = Vec<Update>, Error = Error>,
Sender: Fn(Option<i64>) -> Fut,
{
type Item = Update;
type Error = Error;
fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {
if self.is_canceled {
return Ok(Async::Ready(None));
}
if let Some(update) = self.buffer.pop_front() {
return Ok(Async::Ready(Some(update)));
}
if self.has_error {
self.has_error = false;
self.executing_request = (self.send_request)(self.last_id)
}
match self.executing_request.poll() {
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(updates)) => {
let last_id = self.last_id.unwrap_or(-1);
for update in updates {
self.last_id = Some(max(update.update_id, last_id) + 1);
self.buffer.push_back(update)
}
self.executing_request = (self.send_request)(self.last_id);
self.poll()
}
Err(err) => {
self.has_error = true;
Err(err)
}
}
}
}
impl<Fut, Sender> Drop for UpdatesPoolStream<Fut, Sender> {
fn drop(&mut self) {
self.is_canceled = true;
}
}
|
use std::{fs};
#[derive(Debug, Clone, PartialEq, Copy)]
pub enum BFT {
MemChange(i128),
Move(i32),
Print,
Read,
LoopStart(Option<usize>),
LoopEnd(usize),
}
pub fn load_bf(uri: &str, read_from_file: bool) -> Vec<BFT> {
//Read from file and remove non-command characters
let file_contents: String;
if read_from_file {
file_contents = fs::read_to_string(uri).expect("Something went wrong reading the file");
} else {
file_contents = uri.to_string();
}
lex_bf(&file_contents)
}
fn lex_bf(input: &str) -> Vec<BFT> {
let mut only_bf: Vec<char> = vec![];
for current_char in input.chars() {
if "+-,.<>[]".contains(current_char) {
only_bf.push(current_char);
}
}
// Keeps track of the bracket pairs
let mut bracket_stack: Vec<usize> = vec![];
let mut code_pointer = 0;
let mut code_compression_tally = 0;
let mut tokens: Vec<BFT> = vec![];
while code_pointer < only_bf.len() {
let current_char = only_bf[code_pointer];
let new_token = match current_char {
',' => BFT::Read,
'.' => BFT::Print,
'[' => {
// Add to stack, accounting for code being compressed
bracket_stack.push(code_pointer - code_compression_tally);
BFT::LoopStart(None)
},
']' => {
let index = match bracket_stack.pop() {
Some(x) => x,
None => panic!("Unmatched ] bracket, check your brackets!"),
};
if tokens[index]==BFT::LoopStart(None) {
tokens[index] = BFT::LoopStart(Some(code_pointer - code_compression_tally));
} else {
panic!("Unmatched ] bracket, check your brackets!");
}
BFT::LoopEnd(index)
} ,
_ => {
// Only compressible characters now
let mut forward_looking = 1;
while forward_looking + code_pointer < only_bf.len() {
if only_bf[code_pointer + forward_looking] == current_char {
forward_looking += 1;
} else {
break;
}
}
// adjust search to deal with skipping
code_pointer += forward_looking - 1;
code_compression_tally += forward_looking - 1;
match current_char {
'+' => BFT::MemChange(forward_looking as i128),
'-' => BFT::MemChange(-(forward_looking as i128)),
'<' => BFT::Move(-(forward_looking as i32)),
'>' => BFT::Move(forward_looking as i32),
_ => panic!("Unrecognized character"),
}
}
};
tokens.push(new_token);
code_pointer += 1;
}
tokens
}
#[cfg(test)]
mod tests {
use crate::brainfuck_lexer::BFT;
use super::lex_bf;
#[test]
fn empty_case() {
assert_eq!(lex_bf(&""), vec![]);
}
#[test]
fn token_series() {
assert_eq!(lex_bf(&"><+-.,[]"), vec![BFT::Move(1), BFT::Move(-1), BFT::MemChange(1), BFT::MemChange(-1), BFT::Print, BFT::Read, BFT::LoopStart(Some(7)), BFT::LoopEnd(6)]);
}
#[test]
fn code_compression() {
assert_eq!(lex_bf(&">>>><<<<++++----"), vec![BFT::Move(4), BFT::Move(-4), BFT::MemChange(4), BFT::MemChange(-4)]);
}
#[test]
fn bracket_pairing() {
assert_eq!(lex_bf(&"++[++[-]-]"), vec![BFT::MemChange(2), BFT::LoopStart(Some(7)), BFT::MemChange(2), BFT::LoopStart(Some(5)), BFT::MemChange(-1), BFT::LoopEnd(3), BFT::MemChange(-1), BFT::LoopEnd(1)]);
}
#[test]
fn extra_characters() {
assert_eq!(lex_bf(&"owo + \n"), vec![BFT::MemChange(1)]);
}
} |
#[doc = "Reader of register ITLINE5"]
pub type R = crate::R<u32, super::ITLINE5>;
#[doc = "Reader of field `EXTI0`"]
pub type EXTI0_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI1`"]
pub type EXTI1_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - EXTI0"]
#[inline(always)]
pub fn exti0(&self) -> EXTI0_R {
EXTI0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - EXTI1"]
#[inline(always)]
pub fn exti1(&self) -> EXTI1_R {
EXTI1_R::new(((self.bits >> 1) & 0x01) != 0)
}
}
|
pub mod trig {
pub fn get_unit_vec(a: Vec<f64>) -> Vec<f64> {
let mut mag: f64 = 0.0;
for i in a.iter() {
mag += i*i;
}
a.iter().map(|x| x / mag.sqrt()).collect::<Vec<f64>>()
}
pub fn get_theta(a: Vec<f64>, b: Vec<f64>) -> f64 {
dot(a, b).acos()
}
pub fn dot(a: Vec<f64>, b: Vec<f64>) -> f64 {
let mut res: f64 = 0.0;
for (i, j) in a.iter().zip(b.iter()) {
res += i * j;
}
res
}
}
pub mod lin_alg {
pub fn gauss_jordan(mut aug: Vec<Vec<f64>>) -> Vec<Vec<f64>> {
let length: usize = aug.len();
for i in 0..(length - 1) {
for j in (i+1)..length {
let co_i = aug[i][i];
let co_j = aug[j][i];
for k in i..(length + 1) {
aug[j][k] -= (co_j / co_i) * aug[i][k];
}
}
}
for i in (0..length).rev() {
let co_i: f64 = aug[i][i];
aug[i][i] /= co_i;
aug[i][length] /= co_i;
for j in 0..i {
let co_j: f64 = aug[j][i];
aug[j][length] -= co_j * aug[i][length];
}
}
aug
}
}
pub mod misc {
pub fn rotate(point: (f64, f64), center: (f64, f64), theta: f64) -> (f64, f64) {
(
(point.0 - center.0) * theta.cos() - (point.1 - center.1) * theta.sin() + center.0,
(point.0 - center.0) * theta.sin() + (point.1 - center.1) * theta.cos() + center.1
)
}
} |
//! Entrypoint for interactive SQL repl loop
use observability_deps::tracing::debug;
use snafu::{ResultExt, Snafu};
use influxdb_iox_client::{connection::Connection, health};
mod repl;
mod repl_command;
/// Start IOx interactive SQL REPL loop
///
/// Supports command history and interactive editing. History is
/// stored in $HOME/.iox_sql_history.
#[derive(Debug, clap::Parser)]
pub struct Config {
// TODO add an option to avoid saving history
// TODO add an option to specify the default database (rather than having to set it via USE DATABASE)
/// Format to use for output. Can be overridden using
/// `SET FORMAT` command
///
/// Optional format ('pretty', 'json', or 'csv')
#[clap(short, long, default_value = "pretty", action)]
format: String,
}
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Health check request failed: {}", source))]
Client {
source: influxdb_iox_client::error::Error,
},
#[snafu(display("Storage service not running"))]
StorageNotRunning,
#[snafu(display("Repl Error: {}", source))]
Repl { source: repl::Error },
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// Fire up the interactive REPL
pub async fn command(connection: Connection, config: Config) -> Result<()> {
debug!("Starting interactive SQL prompt with {:?}", config);
if let Err(e) = check_health(connection.clone()).await {
eprintln!("warning: flight healthcheck failed: {}", e);
}
println!("Connected to IOx Server");
let mut repl = repl::Repl::new(connection).context(ReplSnafu)?;
repl.set_output_format(config.format).context(ReplSnafu)?;
repl.run().await.context(ReplSnafu)
}
async fn check_health(connection: Connection) -> Result<()> {
let response = health::Client::new(connection)
.check_arrow()
.await
.context(ClientSnafu)?;
match response {
true => Ok(()),
false => Err(Error::StorageNotRunning),
}
}
|
#![feature(test)]
#![deny(unconditional_recursion)]
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![warn(trivial_casts)]
#![warn(trivial_numeric_casts)]
#![warn(unsafe_code)]
#![warn(unused_import_braces)]
//! This file contains tests for the generated lexer.
use enso_flexer::prelude::*;
use enso_flexer::prelude::reader::decoder::DecoderUTF8;
use flexer_test_generation::generated::engine::TestLexer;
use flexer_test_generation::generated::engine::Token;
use flexer_test_generation::generated::engine::TokenStream;
// =============
// === Tests ===
// =============
/// Executes the test on the provided input string slice.
fn run_test_on(str:impl AsRef<str>) -> TokenStream {
// Hardcoded for ease of use here.
let reader = Reader::new(str.as_ref().as_bytes(), DecoderUTF8());
let mut lexer = TestLexer::new();
let run_result = lexer.run(reader);
match run_result.kind {
enso_flexer::ResultKind::Success => run_result.tokens,
_ => default()
}
}
#[test]
fn test_single_a_word() {
let input = "aaaaa";
let expected_output = TokenStream::from(vec![Token::word(input)]);
let result = run_test_on(input);
assert_eq!(result, expected_output);
}
#[test]
fn test_single_b_word() {
let input = "bbbbb";
let expected_output = TokenStream::from(vec![Token::word(input)]);
let result = run_test_on(input);
assert_eq!(result, expected_output);
}
#[test]
fn test_two_word() {
let input = "aaaaa bbbbb";
let expected_output = TokenStream::from(vec![Token::word("aaaaa"), Token::word("bbbbb")]);
let result = run_test_on(input);
assert_eq!(result, expected_output);
}
#[test]
fn test_multi_word() {
let input = "bbb aa a b bbbbb aa";
let expected_output = TokenStream::from(vec![
Token::word("bbb"),
Token::word("aa"),
Token::word("a"),
Token::word("b"),
Token::word("bbbbb"),
Token::word("aa")
]);
let result = run_test_on(input);
assert_eq!(result, expected_output);
}
#[test]
fn test_invalid_single_word() {
let input = "c";
let expected_output = TokenStream::from(vec![Token::unrecognized(input)]);
let result = run_test_on(input);
assert_eq!(result, expected_output);
}
#[test]
fn test_multi_word_invalid() {
let input = "aaaaaa c bbbbbb";
let expected_output = TokenStream::from(vec![
Token::word("aaaaaa"),
Token::unrecognized(" "),
Token::unrecognized("c"),
Token::unrecognized(" "),
Token::word("bbbbbb"),
]);
let result = run_test_on(input);
assert_eq!(result, expected_output);
}
#[test]
fn test_end_invalid() {
let input = "bbbbbb c";
let expected_output = TokenStream::from(vec![
Token::word("bbbbbb"),
Token::unrecognized(" "),
Token::unrecognized("c"),
]);
let result = run_test_on(input);
assert_eq!(result, expected_output);
}
|
use pathfinder_common::BlockNumber;
use crate::prelude::*;
pub(super) fn update_l1_l2_pointer(
tx: &Transaction<'_>,
head: Option<BlockNumber>,
) -> anyhow::Result<()> {
tx.inner().execute(
"UPDATE refs SET l1_l2_head = ? WHERE idx = 1",
params![&head],
)?;
Ok(())
}
pub(super) fn l1_l2_pointer(tx: &Transaction<'_>) -> anyhow::Result<Option<BlockNumber>> {
// This table always contains exactly one row.
tx.inner()
.query_row("SELECT l1_l2_head FROM refs WHERE idx = 1", [], |row| {
row.get_optional_block_number(0)
})
.map_err(|e| e.into())
}
#[cfg(test)]
mod tests {
use crate::Storage;
use super::*;
#[test]
fn empty_is_none() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
let result = l1_l2_pointer(&tx).unwrap();
assert_eq!(result, None);
}
#[test]
fn update_overwrites() {
let storage = Storage::in_memory().unwrap();
let mut connection = storage.connection().unwrap();
let tx = connection.transaction().unwrap();
update_l1_l2_pointer(&tx, Some(BlockNumber::new_or_panic(10))).unwrap();
let result = l1_l2_pointer(&tx).unwrap();
assert_eq!(result, Some(BlockNumber::new_or_panic(10)));
update_l1_l2_pointer(&tx, Some(BlockNumber::new_or_panic(33))).unwrap();
let result = l1_l2_pointer(&tx).unwrap();
assert_eq!(result, Some(BlockNumber::new_or_panic(33)));
update_l1_l2_pointer(&tx, None).unwrap();
let result = l1_l2_pointer(&tx).unwrap();
assert_eq!(result, None);
}
}
|
use super::basic::calc_shuffled_positions;
use super::tile::Terrain;
use fov::calc_fov;
use grid::{Grid, Pos};
use rand::Rng;
pub(super) fn add_grass<R: Rng>(level: &mut Grid<Terrain>, rng: &mut R) {
let positions = calc_shuffled_positions(rng);
for &pos in &positions {
if level[pos] == Terrain::Floor {
let fov_size = calc_fov_size(level, pos);
if fov_size > 60 {
level[pos] = Terrain::ShortGrass;
}
}
}
}
fn calc_fov_size(level: &mut Grid<Terrain>, pos: Pos) -> u32 {
let transparent = |pos| match level[pos] {
Terrain::Floor | Terrain::ShortGrass | Terrain::TallGrass => true,
_ => false,
};
let mut fov_size = 0;
calc_fov(pos, transparent, |_| fov_size += 1);
fov_size
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[inline]
pub unsafe fn ApplyGuestMemoryFix(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, virtualaddress: u64, fixbuffer: *const ::core::ffi::c_void, fixbuffersize: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ApplyGuestMemoryFix(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, virtualaddress: u64, fixbuffer: *const ::core::ffi::c_void, fixbuffersize: u32) -> ::windows::core::HRESULT;
}
ApplyGuestMemoryFix(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(virtualaddress), ::core::mem::transmute(fixbuffer), ::core::mem::transmute(fixbuffersize)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn ApplyPendingSavedStateFileReplayLog<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(vmrsfile: Param0) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ApplyPendingSavedStateFileReplayLog(vmrsfile: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT;
}
ApplyPendingSavedStateFileReplayLog(vmrsfile.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn CallStackUnwind(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, imageinfo: *const MODULE_INFO, imageinfocount: u32, framecount: u32, callstack: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn CallStackUnwind(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, imageinfo: *const MODULE_INFO, imageinfocount: u32, framecount: u32, callstack: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT;
}
CallStackUnwind(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(imageinfo), ::core::mem::transmute(imageinfocount), ::core::mem::transmute(framecount), ::core::mem::transmute(callstack)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct DOS_IMAGE_INFO {
pub PdbName: super::super::Foundation::PSTR,
pub ImageBaseAddress: u64,
pub ImageSize: u32,
pub Timestamp: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl DOS_IMAGE_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for DOS_IMAGE_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for DOS_IMAGE_INFO {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DOS_IMAGE_INFO").field("PdbName", &self.PdbName).field("ImageBaseAddress", &self.ImageBaseAddress).field("ImageSize", &self.ImageSize).field("Timestamp", &self.Timestamp).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for DOS_IMAGE_INFO {
fn eq(&self, other: &Self) -> bool {
self.PdbName == other.PdbName && self.ImageBaseAddress == other.ImageBaseAddress && self.ImageSize == other.ImageSize && self.Timestamp == other.Timestamp
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for DOS_IMAGE_INFO {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for DOS_IMAGE_INFO {
type Abi = Self;
}
#[cfg(feature = "Win32_Foundation")]
pub type FOUND_IMAGE_CALLBACK = unsafe extern "system" fn(context: *const ::core::ffi::c_void, imageinfo: *const DOS_IMAGE_INFO) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn FindSavedStateSymbolFieldInType<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, typename: Param2, fieldname: Param3, offset: *mut u32, found: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn FindSavedStateSymbolFieldInType(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, typename: super::super::Foundation::PSTR, fieldname: super::super::Foundation::PWSTR, offset: *mut u32, found: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT;
}
FindSavedStateSymbolFieldInType(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), typename.into_param().abi(), fieldname.into_param().abi(), ::core::mem::transmute(offset), ::core::mem::transmute(found)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn ForceActiveVirtualTrustLevel(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, virtualtrustlevel: u8) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ForceActiveVirtualTrustLevel(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, virtualtrustlevel: u8) -> ::windows::core::HRESULT;
}
ForceActiveVirtualTrustLevel(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(virtualtrustlevel)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn ForceArchitecture(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, architecture: VIRTUAL_PROCESSOR_ARCH) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ForceArchitecture(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, architecture: VIRTUAL_PROCESSOR_ARCH) -> ::windows::core::HRESULT;
}
ForceArchitecture(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(architecture)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn ForceNestedHostMode<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, hostmode: Param2, oldmode: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ForceNestedHostMode(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, hostmode: super::super::Foundation::BOOL, oldmode: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT;
}
ForceNestedHostMode(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), hostmode.into_param().abi(), ::core::mem::transmute(oldmode)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn ForcePagingMode(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, pagingmode: PAGING_MODE) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ForcePagingMode(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, pagingmode: PAGING_MODE) -> ::windows::core::HRESULT;
}
ForcePagingMode(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(pagingmode)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct GPA_MEMORY_CHUNK {
pub GuestPhysicalStartPageIndex: u64,
pub PageCount: u64,
}
impl GPA_MEMORY_CHUNK {}
impl ::core::default::Default for GPA_MEMORY_CHUNK {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for GPA_MEMORY_CHUNK {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("GPA_MEMORY_CHUNK").field("GuestPhysicalStartPageIndex", &self.GuestPhysicalStartPageIndex).field("PageCount", &self.PageCount).finish()
}
}
impl ::core::cmp::PartialEq for GPA_MEMORY_CHUNK {
fn eq(&self, other: &Self) -> bool {
self.GuestPhysicalStartPageIndex == other.GuestPhysicalStartPageIndex && self.PageCount == other.PageCount
}
}
impl ::core::cmp::Eq for GPA_MEMORY_CHUNK {}
unsafe impl ::windows::core::Abi for GPA_MEMORY_CHUNK {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union GUEST_OS_INFO {
pub AsUINT64: u64,
pub ClosedSource: GUEST_OS_INFO_0,
pub OpenSource: GUEST_OS_INFO_1,
}
impl GUEST_OS_INFO {}
impl ::core::default::Default for GUEST_OS_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for GUEST_OS_INFO {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for GUEST_OS_INFO {}
unsafe impl ::windows::core::Abi for GUEST_OS_INFO {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct GUEST_OS_INFO_0 {
pub _bitfield: u64,
}
impl GUEST_OS_INFO_0 {}
impl ::core::default::Default for GUEST_OS_INFO_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for GUEST_OS_INFO_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_ClosedSource_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for GUEST_OS_INFO_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for GUEST_OS_INFO_0 {}
unsafe impl ::windows::core::Abi for GUEST_OS_INFO_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct GUEST_OS_INFO_1 {
pub _bitfield: u64,
}
impl GUEST_OS_INFO_1 {}
impl ::core::default::Default for GUEST_OS_INFO_1 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for GUEST_OS_INFO_1 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_OpenSource_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for GUEST_OS_INFO_1 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for GUEST_OS_INFO_1 {}
unsafe impl ::windows::core::Abi for GUEST_OS_INFO_1 {
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 GUEST_OS_MICROSOFT_IDS(pub i32);
pub const GuestOsMicrosoftUndefined: GUEST_OS_MICROSOFT_IDS = GUEST_OS_MICROSOFT_IDS(0i32);
pub const GuestOsMicrosoftMSDOS: GUEST_OS_MICROSOFT_IDS = GUEST_OS_MICROSOFT_IDS(1i32);
pub const GuestOsMicrosoftWindows3x: GUEST_OS_MICROSOFT_IDS = GUEST_OS_MICROSOFT_IDS(2i32);
pub const GuestOsMicrosoftWindows9x: GUEST_OS_MICROSOFT_IDS = GUEST_OS_MICROSOFT_IDS(3i32);
pub const GuestOsMicrosoftWindowsNT: GUEST_OS_MICROSOFT_IDS = GUEST_OS_MICROSOFT_IDS(4i32);
pub const GuestOsMicrosoftWindowsCE: GUEST_OS_MICROSOFT_IDS = GUEST_OS_MICROSOFT_IDS(5i32);
impl ::core::convert::From<i32> for GUEST_OS_MICROSOFT_IDS {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for GUEST_OS_MICROSOFT_IDS {
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 GUEST_OS_OPENSOURCE_IDS(pub i32);
pub const GuestOsOpenSourceUndefined: GUEST_OS_OPENSOURCE_IDS = GUEST_OS_OPENSOURCE_IDS(0i32);
pub const GuestOsOpenSourceLinux: GUEST_OS_OPENSOURCE_IDS = GUEST_OS_OPENSOURCE_IDS(1i32);
pub const GuestOsOpenSourceFreeBSD: GUEST_OS_OPENSOURCE_IDS = GUEST_OS_OPENSOURCE_IDS(2i32);
pub const GuestOsOpenSourceXen: GUEST_OS_OPENSOURCE_IDS = GUEST_OS_OPENSOURCE_IDS(3i32);
pub const GuestOsOpenSourceIllumos: GUEST_OS_OPENSOURCE_IDS = GUEST_OS_OPENSOURCE_IDS(4i32);
impl ::core::convert::From<i32> for GUEST_OS_OPENSOURCE_IDS {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for GUEST_OS_OPENSOURCE_IDS {
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 GUEST_OS_VENDOR(pub i32);
pub const GuestOsVendorUndefined: GUEST_OS_VENDOR = GUEST_OS_VENDOR(0i32);
pub const GuestOsVendorMicrosoft: GUEST_OS_VENDOR = GUEST_OS_VENDOR(1i32);
pub const GuestOsVendorHPE: GUEST_OS_VENDOR = GUEST_OS_VENDOR(2i32);
pub const GuestOsVendorLANCOM: GUEST_OS_VENDOR = GUEST_OS_VENDOR(512i32);
impl ::core::convert::From<i32> for GUEST_OS_VENDOR {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for GUEST_OS_VENDOR {
type Abi = Self;
}
#[cfg(feature = "Win32_Foundation")]
pub type GUEST_SYMBOLS_PROVIDER_DEBUG_INFO_CALLBACK = unsafe extern "system" fn(infomessage: super::super::Foundation::PSTR);
pub const GUID_DEVINTERFACE_VM_GENCOUNTER: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3ff2c92b_6598_4e60_8e1c_0ccf4927e319);
#[inline]
pub unsafe fn GetActiveVirtualTrustLevel(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, virtualtrustlevel: *mut u8) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetActiveVirtualTrustLevel(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, virtualtrustlevel: *mut u8) -> ::windows::core::HRESULT;
}
GetActiveVirtualTrustLevel(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(virtualtrustlevel)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn GetArchitecture(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, architecture: *mut VIRTUAL_PROCESSOR_ARCH) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetArchitecture(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, architecture: *mut VIRTUAL_PROCESSOR_ARCH) -> ::windows::core::HRESULT;
}
GetArchitecture(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(architecture)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn GetEnabledVirtualTrustLevels(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, virtualtrustlevels: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetEnabledVirtualTrustLevels(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, virtualtrustlevels: *mut u32) -> ::windows::core::HRESULT;
}
GetEnabledVirtualTrustLevels(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(virtualtrustlevels)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn GetGuestEnabledVirtualTrustLevels(vmsavedstatedumphandle: *mut ::core::ffi::c_void, virtualtrustlevels: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetGuestEnabledVirtualTrustLevels(vmsavedstatedumphandle: *mut ::core::ffi::c_void, virtualtrustlevels: *mut u32) -> ::windows::core::HRESULT;
}
GetGuestEnabledVirtualTrustLevels(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(virtualtrustlevels)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn GetGuestOsInfo(vmsavedstatedumphandle: *mut ::core::ffi::c_void, virtualtrustlevel: u8, guestosinfo: *mut GUEST_OS_INFO) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetGuestOsInfo(vmsavedstatedumphandle: *mut ::core::ffi::c_void, virtualtrustlevel: u8, guestosinfo: *mut GUEST_OS_INFO) -> ::windows::core::HRESULT;
}
GetGuestOsInfo(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(virtualtrustlevel), ::core::mem::transmute(guestosinfo)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn GetGuestPhysicalMemoryChunks(vmsavedstatedumphandle: *mut ::core::ffi::c_void, memorychunkpagesize: *mut u64, memorychunks: *mut GPA_MEMORY_CHUNK, memorychunkcount: *mut u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetGuestPhysicalMemoryChunks(vmsavedstatedumphandle: *mut ::core::ffi::c_void, memorychunkpagesize: *mut u64, memorychunks: *mut GPA_MEMORY_CHUNK, memorychunkcount: *mut u64) -> ::windows::core::HRESULT;
}
GetGuestPhysicalMemoryChunks(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(memorychunkpagesize), ::core::mem::transmute(memorychunks), ::core::mem::transmute(memorychunkcount)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn GetGuestRawSavedMemorySize(vmsavedstatedumphandle: *mut ::core::ffi::c_void, guestrawsavedmemorysize: *mut u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetGuestRawSavedMemorySize(vmsavedstatedumphandle: *mut ::core::ffi::c_void, guestrawsavedmemorysize: *mut u64) -> ::windows::core::HRESULT;
}
GetGuestRawSavedMemorySize(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(guestrawsavedmemorysize)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn GetMemoryBlockCacheLimit(vmsavedstatedumphandle: *mut ::core::ffi::c_void, memoryblockcachelimit: *mut u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetMemoryBlockCacheLimit(vmsavedstatedumphandle: *mut ::core::ffi::c_void, memoryblockcachelimit: *mut u64) -> ::windows::core::HRESULT;
}
GetMemoryBlockCacheLimit(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(memoryblockcachelimit)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn GetNestedVirtualizationMode(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, enabled: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetNestedVirtualizationMode(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, enabled: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT;
}
GetNestedVirtualizationMode(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(enabled)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn GetPagingMode(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, pagingmode: *mut PAGING_MODE) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetPagingMode(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, pagingmode: *mut PAGING_MODE) -> ::windows::core::HRESULT;
}
GetPagingMode(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(pagingmode)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn GetRegisterValue(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, registerid: u32, registervalue: *mut VIRTUAL_PROCESSOR_REGISTER) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetRegisterValue(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, registerid: u32, registervalue: *mut VIRTUAL_PROCESSOR_REGISTER) -> ::windows::core::HRESULT;
}
GetRegisterValue(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(registerid), ::core::mem::transmute(registervalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn GetSavedStateSymbolFieldInfo<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, typename: Param2, typefieldinfomap: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetSavedStateSymbolFieldInfo(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, typename: super::super::Foundation::PSTR, typefieldinfomap: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT;
}
GetSavedStateSymbolFieldInfo(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), typename.into_param().abi(), ::core::mem::transmute(typefieldinfomap)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn GetSavedStateSymbolProviderHandle(vmsavedstatedumphandle: *mut ::core::ffi::c_void) -> super::super::Foundation::HANDLE {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetSavedStateSymbolProviderHandle(vmsavedstatedumphandle: *mut ::core::ffi::c_void) -> super::super::Foundation::HANDLE;
}
::core::mem::transmute(GetSavedStateSymbolProviderHandle(::core::mem::transmute(vmsavedstatedumphandle)))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn GetSavedStateSymbolTypeSize<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, typename: Param2, size: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetSavedStateSymbolTypeSize(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, typename: super::super::Foundation::PSTR, size: *mut u32) -> ::windows::core::HRESULT;
}
GetSavedStateSymbolTypeSize(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), typename.into_param().abi(), ::core::mem::transmute(size)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn GetVpCount(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpcount: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GetVpCount(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpcount: *mut u32) -> ::windows::core::HRESULT;
}
GetVpCount(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpcount)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn GuestPhysicalAddressToRawSavedMemoryOffset(vmsavedstatedumphandle: *mut ::core::ffi::c_void, physicaladdress: u64, rawsavedmemoryoffset: *mut u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GuestPhysicalAddressToRawSavedMemoryOffset(vmsavedstatedumphandle: *mut ::core::ffi::c_void, physicaladdress: u64, rawsavedmemoryoffset: *mut u64) -> ::windows::core::HRESULT;
}
GuestPhysicalAddressToRawSavedMemoryOffset(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(physicaladdress), ::core::mem::transmute(rawsavedmemoryoffset)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn GuestVirtualAddressToPhysicalAddress(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, virtualaddress: u64, physicaladdress: *mut u64, unmappedregionsize: *mut u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn GuestVirtualAddressToPhysicalAddress(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, virtualaddress: u64, physicaladdress: *mut u64, unmappedregionsize: *mut u64) -> ::windows::core::HRESULT;
}
GuestVirtualAddressToPhysicalAddress(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(virtualaddress), ::core::mem::transmute(physicaladdress), ::core::mem::transmute(unmappedregionsize)).ok()
}
#[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 HDV_DEVICE_TYPE(pub i32);
pub const HdvDeviceTypeUndefined: HDV_DEVICE_TYPE = HDV_DEVICE_TYPE(0i32);
pub const HdvDeviceTypePCI: HDV_DEVICE_TYPE = HDV_DEVICE_TYPE(1i32);
impl ::core::convert::From<i32> for HDV_DEVICE_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for HDV_DEVICE_TYPE {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct HDV_DOORBELL_FLAGS(pub i32);
pub const HDV_DOORBELL_FLAG_TRIGGER_SIZE_ANY: HDV_DOORBELL_FLAGS = HDV_DOORBELL_FLAGS(0i32);
pub const HDV_DOORBELL_FLAG_TRIGGER_SIZE_BYTE: HDV_DOORBELL_FLAGS = HDV_DOORBELL_FLAGS(1i32);
pub const HDV_DOORBELL_FLAG_TRIGGER_SIZE_WORD: HDV_DOORBELL_FLAGS = HDV_DOORBELL_FLAGS(2i32);
pub const HDV_DOORBELL_FLAG_TRIGGER_SIZE_DWORD: HDV_DOORBELL_FLAGS = HDV_DOORBELL_FLAGS(3i32);
pub const HDV_DOORBELL_FLAG_TRIGGER_SIZE_QWORD: HDV_DOORBELL_FLAGS = HDV_DOORBELL_FLAGS(4i32);
pub const HDV_DOORBELL_FLAG_TRIGGER_ANY_VALUE: HDV_DOORBELL_FLAGS = HDV_DOORBELL_FLAGS(-2147483648i32);
impl ::core::convert::From<i32> for HDV_DOORBELL_FLAGS {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for HDV_DOORBELL_FLAGS {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct HDV_MMIO_MAPPING_FLAGS(pub u32);
pub const HdvMmioMappingFlagNone: HDV_MMIO_MAPPING_FLAGS = HDV_MMIO_MAPPING_FLAGS(0u32);
pub const HdvMmioMappingFlagWriteable: HDV_MMIO_MAPPING_FLAGS = HDV_MMIO_MAPPING_FLAGS(1u32);
pub const HdvMmioMappingFlagExecutable: HDV_MMIO_MAPPING_FLAGS = HDV_MMIO_MAPPING_FLAGS(2u32);
impl ::core::convert::From<u32> for HDV_MMIO_MAPPING_FLAGS {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for HDV_MMIO_MAPPING_FLAGS {
type Abi = Self;
}
impl ::core::ops::BitOr for HDV_MMIO_MAPPING_FLAGS {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for HDV_MMIO_MAPPING_FLAGS {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for HDV_MMIO_MAPPING_FLAGS {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for HDV_MMIO_MAPPING_FLAGS {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for HDV_MMIO_MAPPING_FLAGS {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
pub const HDV_PCI_BAR_COUNT: u32 = 6u32;
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct HDV_PCI_BAR_SELECTOR(pub i32);
pub const HDV_PCI_BAR0: HDV_PCI_BAR_SELECTOR = HDV_PCI_BAR_SELECTOR(0i32);
pub const HDV_PCI_BAR1: HDV_PCI_BAR_SELECTOR = HDV_PCI_BAR_SELECTOR(1i32);
pub const HDV_PCI_BAR2: HDV_PCI_BAR_SELECTOR = HDV_PCI_BAR_SELECTOR(2i32);
pub const HDV_PCI_BAR3: HDV_PCI_BAR_SELECTOR = HDV_PCI_BAR_SELECTOR(3i32);
pub const HDV_PCI_BAR4: HDV_PCI_BAR_SELECTOR = HDV_PCI_BAR_SELECTOR(4i32);
pub const HDV_PCI_BAR5: HDV_PCI_BAR_SELECTOR = HDV_PCI_BAR_SELECTOR(5i32);
impl ::core::convert::From<i32> for HDV_PCI_BAR_SELECTOR {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for HDV_PCI_BAR_SELECTOR {
type Abi = Self;
}
pub type HDV_PCI_DEVICE_GET_DETAILS = unsafe extern "system" fn(devicecontext: *const ::core::ffi::c_void, pnpid: *mut HDV_PCI_PNP_ID, probedbarscount: u32, probedbars: *mut u32) -> ::windows::core::HRESULT;
pub type HDV_PCI_DEVICE_INITIALIZE = unsafe extern "system" fn(devicecontext: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
#[derive(:: core :: clone :: Clone)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct HDV_PCI_DEVICE_INTERFACE {
pub Version: HDV_PCI_INTERFACE_VERSION,
pub Initialize: ::core::option::Option<HDV_PCI_DEVICE_INITIALIZE>,
pub Teardown: ::core::option::Option<HDV_PCI_DEVICE_TEARDOWN>,
pub SetConfiguration: ::core::option::Option<HDV_PCI_DEVICE_SET_CONFIGURATION>,
pub GetDetails: ::core::option::Option<HDV_PCI_DEVICE_GET_DETAILS>,
pub Start: ::core::option::Option<HDV_PCI_DEVICE_START>,
pub Stop: ::core::option::Option<HDV_PCI_DEVICE_STOP>,
pub ReadConfigSpace: ::core::option::Option<HDV_PCI_READ_CONFIG_SPACE>,
pub WriteConfigSpace: ::core::option::Option<HDV_PCI_WRITE_CONFIG_SPACE>,
pub ReadInterceptedMemory: ::core::option::Option<HDV_PCI_READ_INTERCEPTED_MEMORY>,
pub WriteInterceptedMemory: ::core::option::Option<HDV_PCI_WRITE_INTERCEPTED_MEMORY>,
}
#[cfg(feature = "Win32_Foundation")]
impl HDV_PCI_DEVICE_INTERFACE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for HDV_PCI_DEVICE_INTERFACE {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for HDV_PCI_DEVICE_INTERFACE {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("HDV_PCI_DEVICE_INTERFACE").field("Version", &self.Version).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for HDV_PCI_DEVICE_INTERFACE {
fn eq(&self, other: &Self) -> bool {
self.Version == other.Version
&& self.Initialize.map(|f| f as usize) == other.Initialize.map(|f| f as usize)
&& self.Teardown.map(|f| f as usize) == other.Teardown.map(|f| f as usize)
&& self.SetConfiguration.map(|f| f as usize) == other.SetConfiguration.map(|f| f as usize)
&& self.GetDetails.map(|f| f as usize) == other.GetDetails.map(|f| f as usize)
&& self.Start.map(|f| f as usize) == other.Start.map(|f| f as usize)
&& self.Stop.map(|f| f as usize) == other.Stop.map(|f| f as usize)
&& self.ReadConfigSpace.map(|f| f as usize) == other.ReadConfigSpace.map(|f| f as usize)
&& self.WriteConfigSpace.map(|f| f as usize) == other.WriteConfigSpace.map(|f| f as usize)
&& self.ReadInterceptedMemory.map(|f| f as usize) == other.ReadInterceptedMemory.map(|f| f as usize)
&& self.WriteInterceptedMemory.map(|f| f as usize) == other.WriteInterceptedMemory.map(|f| f as usize)
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for HDV_PCI_DEVICE_INTERFACE {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for HDV_PCI_DEVICE_INTERFACE {
type Abi = ::core::mem::ManuallyDrop<Self>;
}
#[cfg(feature = "Win32_Foundation")]
pub type HDV_PCI_DEVICE_SET_CONFIGURATION = unsafe extern "system" fn(devicecontext: *const ::core::ffi::c_void, configurationvaluecount: u32, configurationvalues: *const super::super::Foundation::PWSTR) -> ::windows::core::HRESULT;
pub type HDV_PCI_DEVICE_START = unsafe extern "system" fn(devicecontext: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
pub type HDV_PCI_DEVICE_STOP = unsafe extern "system" fn(devicecontext: *const ::core::ffi::c_void);
pub type HDV_PCI_DEVICE_TEARDOWN = unsafe extern "system" fn(devicecontext: *const ::core::ffi::c_void);
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct HDV_PCI_INTERFACE_VERSION(pub i32);
pub const HdvPciDeviceInterfaceVersionInvalid: HDV_PCI_INTERFACE_VERSION = HDV_PCI_INTERFACE_VERSION(0i32);
pub const HdvPciDeviceInterfaceVersion1: HDV_PCI_INTERFACE_VERSION = HDV_PCI_INTERFACE_VERSION(1i32);
impl ::core::convert::From<i32> for HDV_PCI_INTERFACE_VERSION {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for HDV_PCI_INTERFACE_VERSION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct HDV_PCI_PNP_ID {
pub VendorID: u16,
pub DeviceID: u16,
pub RevisionID: u8,
pub ProgIf: u8,
pub SubClass: u8,
pub BaseClass: u8,
pub SubVendorID: u16,
pub SubSystemID: u16,
}
impl HDV_PCI_PNP_ID {}
impl ::core::default::Default for HDV_PCI_PNP_ID {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for HDV_PCI_PNP_ID {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("HDV_PCI_PNP_ID")
.field("VendorID", &self.VendorID)
.field("DeviceID", &self.DeviceID)
.field("RevisionID", &self.RevisionID)
.field("ProgIf", &self.ProgIf)
.field("SubClass", &self.SubClass)
.field("BaseClass", &self.BaseClass)
.field("SubVendorID", &self.SubVendorID)
.field("SubSystemID", &self.SubSystemID)
.finish()
}
}
impl ::core::cmp::PartialEq for HDV_PCI_PNP_ID {
fn eq(&self, other: &Self) -> bool {
self.VendorID == other.VendorID && self.DeviceID == other.DeviceID && self.RevisionID == other.RevisionID && self.ProgIf == other.ProgIf && self.SubClass == other.SubClass && self.BaseClass == other.BaseClass && self.SubVendorID == other.SubVendorID && self.SubSystemID == other.SubSystemID
}
}
impl ::core::cmp::Eq for HDV_PCI_PNP_ID {}
unsafe impl ::windows::core::Abi for HDV_PCI_PNP_ID {
type Abi = Self;
}
pub type HDV_PCI_READ_CONFIG_SPACE = unsafe extern "system" fn(devicecontext: *const ::core::ffi::c_void, offset: u32, value: *mut u32) -> ::windows::core::HRESULT;
pub type HDV_PCI_READ_INTERCEPTED_MEMORY = unsafe extern "system" fn(devicecontext: *const ::core::ffi::c_void, barindex: HDV_PCI_BAR_SELECTOR, offset: u64, length: u64, value: *mut u8) -> ::windows::core::HRESULT;
pub type HDV_PCI_WRITE_CONFIG_SPACE = unsafe extern "system" fn(devicecontext: *const ::core::ffi::c_void, offset: u32, value: u32) -> ::windows::core::HRESULT;
pub type HDV_PCI_WRITE_INTERCEPTED_MEMORY = unsafe extern "system" fn(devicecontext: *const ::core::ffi::c_void, barindex: HDV_PCI_BAR_SELECTOR, offset: u64, length: u64, value: *const u8) -> ::windows::core::HRESULT;
pub const HVSOCKET_ADDRESS_FLAG_PASSTHRU: u32 = 1u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct HVSOCKET_ADDRESS_INFO {
pub SystemId: ::windows::core::GUID,
pub VirtualMachineId: ::windows::core::GUID,
pub SiloId: ::windows::core::GUID,
pub Flags: u32,
}
impl HVSOCKET_ADDRESS_INFO {}
impl ::core::default::Default for HVSOCKET_ADDRESS_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for HVSOCKET_ADDRESS_INFO {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("HVSOCKET_ADDRESS_INFO").field("SystemId", &self.SystemId).field("VirtualMachineId", &self.VirtualMachineId).field("SiloId", &self.SiloId).field("Flags", &self.Flags).finish()
}
}
impl ::core::cmp::PartialEq for HVSOCKET_ADDRESS_INFO {
fn eq(&self, other: &Self) -> bool {
self.SystemId == other.SystemId && self.VirtualMachineId == other.VirtualMachineId && self.SiloId == other.SiloId && self.Flags == other.Flags
}
}
impl ::core::cmp::Eq for HVSOCKET_ADDRESS_INFO {}
unsafe impl ::windows::core::Abi for HVSOCKET_ADDRESS_INFO {
type Abi = Self;
}
pub const HVSOCKET_CONNECTED_SUSPEND: u32 = 4u32;
pub const HVSOCKET_CONNECT_TIMEOUT: u32 = 1u32;
pub const HVSOCKET_CONNECT_TIMEOUT_MAX: u32 = 300000u32;
pub const HVSOCKET_CONTAINER_PASSTHRU: u32 = 2u32;
pub const HV_GUID_BROADCAST: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xffffffff_ffff_ffff_ffff_ffffffffffff);
pub const HV_GUID_CHILDREN: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x90db8b89_0d35_4f79_8ce9_49ea0ac8b7cd);
pub const HV_GUID_LOOPBACK: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe0e16197_dd56_4a10_9195_5ee7a155a838);
pub const HV_GUID_PARENT: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa42e7cda_d03f_480c_9cc2_a4de20abb878);
pub const HV_GUID_SILOHOST: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x36bd0c5c_7276_4223_88ba_7d03b654c568);
pub const HV_GUID_VSOCK_TEMPLATE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x00000000_facb_11e6_bd58_64006a7986d3);
pub const HV_GUID_ZERO: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x00000000_0000_0000_0000_000000000000);
pub const HV_PROTOCOL_RAW: u32 = 1u32;
#[inline]
pub unsafe fn HdvCreateDeviceInstance(devicehosthandle: *const ::core::ffi::c_void, devicetype: HDV_DEVICE_TYPE, deviceclassid: *const ::windows::core::GUID, deviceinstanceid: *const ::windows::core::GUID, deviceinterface: *const ::core::ffi::c_void, devicecontext: *const ::core::ffi::c_void, devicehandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn HdvCreateDeviceInstance(devicehosthandle: *const ::core::ffi::c_void, devicetype: HDV_DEVICE_TYPE, deviceclassid: *const ::windows::core::GUID, deviceinstanceid: *const ::windows::core::GUID, deviceinterface: *const ::core::ffi::c_void, devicecontext: *const ::core::ffi::c_void, devicehandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
HdvCreateDeviceInstance(::core::mem::transmute(devicehosthandle), ::core::mem::transmute(devicetype), ::core::mem::transmute(deviceclassid), ::core::mem::transmute(deviceinstanceid), ::core::mem::transmute(deviceinterface), ::core::mem::transmute(devicecontext), ::core::mem::transmute(devicehandle)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn HdvCreateGuestMemoryAperture<'a, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(requestor: *const ::core::ffi::c_void, guestphysicaladdress: u64, bytecount: u32, writeprotected: Param3, mappedaddress: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn HdvCreateGuestMemoryAperture(requestor: *const ::core::ffi::c_void, guestphysicaladdress: u64, bytecount: u32, writeprotected: super::super::Foundation::BOOL, mappedaddress: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
HdvCreateGuestMemoryAperture(::core::mem::transmute(requestor), ::core::mem::transmute(guestphysicaladdress), ::core::mem::transmute(bytecount), writeprotected.into_param().abi(), ::core::mem::transmute(mappedaddress)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn HdvCreateSectionBackedMmioRange<'a, Param5: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(requestor: *const ::core::ffi::c_void, barindex: HDV_PCI_BAR_SELECTOR, offsetinpages: u64, lengthinpages: u64, mappingflags: HDV_MMIO_MAPPING_FLAGS, sectionhandle: Param5, sectionoffsetinpages: u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn HdvCreateSectionBackedMmioRange(requestor: *const ::core::ffi::c_void, barindex: HDV_PCI_BAR_SELECTOR, offsetinpages: u64, lengthinpages: u64, mappingflags: HDV_MMIO_MAPPING_FLAGS, sectionhandle: super::super::Foundation::HANDLE, sectionoffsetinpages: u64) -> ::windows::core::HRESULT;
}
HdvCreateSectionBackedMmioRange(::core::mem::transmute(requestor), ::core::mem::transmute(barindex), ::core::mem::transmute(offsetinpages), ::core::mem::transmute(lengthinpages), ::core::mem::transmute(mappingflags), sectionhandle.into_param().abi(), ::core::mem::transmute(sectionoffsetinpages)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn HdvDeliverGuestInterrupt(requestor: *const ::core::ffi::c_void, msiaddress: u64, msidata: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn HdvDeliverGuestInterrupt(requestor: *const ::core::ffi::c_void, msiaddress: u64, msidata: u32) -> ::windows::core::HRESULT;
}
HdvDeliverGuestInterrupt(::core::mem::transmute(requestor), ::core::mem::transmute(msiaddress), ::core::mem::transmute(msidata)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn HdvDestroyGuestMemoryAperture(requestor: *const ::core::ffi::c_void, mappedaddress: *const ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn HdvDestroyGuestMemoryAperture(requestor: *const ::core::ffi::c_void, mappedaddress: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
HdvDestroyGuestMemoryAperture(::core::mem::transmute(requestor), ::core::mem::transmute(mappedaddress)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn HdvDestroySectionBackedMmioRange(requestor: *const ::core::ffi::c_void, barindex: HDV_PCI_BAR_SELECTOR, offsetinpages: u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn HdvDestroySectionBackedMmioRange(requestor: *const ::core::ffi::c_void, barindex: HDV_PCI_BAR_SELECTOR, offsetinpages: u64) -> ::windows::core::HRESULT;
}
HdvDestroySectionBackedMmioRange(::core::mem::transmute(requestor), ::core::mem::transmute(barindex), ::core::mem::transmute(offsetinpages)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_System_HostComputeSystem")]
#[inline]
pub unsafe fn HdvInitializeDeviceHost<'a, Param0: ::windows::core::IntoParam<'a, super::HostComputeSystem::HCS_SYSTEM>>(computesystem: Param0, devicehosthandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn HdvInitializeDeviceHost(computesystem: super::HostComputeSystem::HCS_SYSTEM, devicehosthandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
HdvInitializeDeviceHost(computesystem.into_param().abi(), ::core::mem::transmute(devicehosthandle)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn HdvReadGuestMemory(requestor: *const ::core::ffi::c_void, guestphysicaladdress: u64, bytecount: u32, buffer: *mut u8) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn HdvReadGuestMemory(requestor: *const ::core::ffi::c_void, guestphysicaladdress: u64, bytecount: u32, buffer: *mut u8) -> ::windows::core::HRESULT;
}
HdvReadGuestMemory(::core::mem::transmute(requestor), ::core::mem::transmute(guestphysicaladdress), ::core::mem::transmute(bytecount), ::core::mem::transmute(buffer)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn HdvRegisterDoorbell<'a, Param5: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(requestor: *const ::core::ffi::c_void, barindex: HDV_PCI_BAR_SELECTOR, baroffset: u64, triggervalue: u64, flags: u64, doorbellevent: Param5) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn HdvRegisterDoorbell(requestor: *const ::core::ffi::c_void, barindex: HDV_PCI_BAR_SELECTOR, baroffset: u64, triggervalue: u64, flags: u64, doorbellevent: super::super::Foundation::HANDLE) -> ::windows::core::HRESULT;
}
HdvRegisterDoorbell(::core::mem::transmute(requestor), ::core::mem::transmute(barindex), ::core::mem::transmute(baroffset), ::core::mem::transmute(triggervalue), ::core::mem::transmute(flags), doorbellevent.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn HdvTeardownDeviceHost(devicehosthandle: *const ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn HdvTeardownDeviceHost(devicehosthandle: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
HdvTeardownDeviceHost(::core::mem::transmute(devicehosthandle)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn HdvUnregisterDoorbell(requestor: *const ::core::ffi::c_void, barindex: HDV_PCI_BAR_SELECTOR, baroffset: u64, triggervalue: u64, flags: u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn HdvUnregisterDoorbell(requestor: *const ::core::ffi::c_void, barindex: HDV_PCI_BAR_SELECTOR, baroffset: u64, triggervalue: u64, flags: u64) -> ::windows::core::HRESULT;
}
HdvUnregisterDoorbell(::core::mem::transmute(requestor), ::core::mem::transmute(barindex), ::core::mem::transmute(baroffset), ::core::mem::transmute(triggervalue), ::core::mem::transmute(flags)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn HdvWriteGuestMemory(requestor: *const ::core::ffi::c_void, guestphysicaladdress: u64, bytecount: u32, buffer: *const u8) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn HdvWriteGuestMemory(requestor: *const ::core::ffi::c_void, guestphysicaladdress: u64, bytecount: u32, buffer: *const u8) -> ::windows::core::HRESULT;
}
HdvWriteGuestMemory(::core::mem::transmute(requestor), ::core::mem::transmute(guestphysicaladdress), ::core::mem::transmute(bytecount), ::core::mem::transmute(buffer)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
pub const IOCTL_VMGENCOUNTER_READ: u32 = 3325956u32;
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn InKernelSpace(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, inkernelspace: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn InKernelSpace(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, inkernelspace: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT;
}
InKernelSpace(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(inkernelspace)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn IsActiveVirtualTrustLevelEnabled(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, activevirtualtrustlevelenabled: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn IsActiveVirtualTrustLevelEnabled(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, activevirtualtrustlevelenabled: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT;
}
IsActiveVirtualTrustLevelEnabled(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), ::core::mem::transmute(activevirtualtrustlevelenabled)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn IsNestedVirtualizationEnabled(vmsavedstatedumphandle: *mut ::core::ffi::c_void, enabled: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn IsNestedVirtualizationEnabled(vmsavedstatedumphandle: *mut ::core::ffi::c_void, enabled: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT;
}
IsNestedVirtualizationEnabled(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(enabled)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn LoadSavedStateFile<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(vmrsfile: Param0, vmsavedstatedumphandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn LoadSavedStateFile(vmrsfile: super::super::Foundation::PWSTR, vmsavedstatedumphandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
LoadSavedStateFile(vmrsfile.into_param().abi(), ::core::mem::transmute(vmsavedstatedumphandle)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn LoadSavedStateFiles<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(binfile: Param0, vsvfile: Param1, vmsavedstatedumphandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn LoadSavedStateFiles(binfile: super::super::Foundation::PWSTR, vsvfile: super::super::Foundation::PWSTR, vmsavedstatedumphandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
LoadSavedStateFiles(binfile.into_param().abi(), vsvfile.into_param().abi(), ::core::mem::transmute(vmsavedstatedumphandle)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn LoadSavedStateModuleSymbols<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(vmsavedstatedumphandle: *mut ::core::ffi::c_void, imagename: Param1, modulename: Param2, baseaddress: u64, sizeofbase: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn LoadSavedStateModuleSymbols(vmsavedstatedumphandle: *mut ::core::ffi::c_void, imagename: super::super::Foundation::PSTR, modulename: super::super::Foundation::PSTR, baseaddress: u64, sizeofbase: u32) -> ::windows::core::HRESULT;
}
LoadSavedStateModuleSymbols(::core::mem::transmute(vmsavedstatedumphandle), imagename.into_param().abi(), modulename.into_param().abi(), ::core::mem::transmute(baseaddress), ::core::mem::transmute(sizeofbase)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn LoadSavedStateModuleSymbolsEx<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(vmsavedstatedumphandle: *mut ::core::ffi::c_void, imagename: Param1, imagetimestamp: u32, modulename: Param3, baseaddress: u64, sizeofbase: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn LoadSavedStateModuleSymbolsEx(vmsavedstatedumphandle: *mut ::core::ffi::c_void, imagename: super::super::Foundation::PSTR, imagetimestamp: u32, modulename: super::super::Foundation::PSTR, baseaddress: u64, sizeofbase: u32) -> ::windows::core::HRESULT;
}
LoadSavedStateModuleSymbolsEx(::core::mem::transmute(vmsavedstatedumphandle), imagename.into_param().abi(), ::core::mem::transmute(imagetimestamp), modulename.into_param().abi(), ::core::mem::transmute(baseaddress), ::core::mem::transmute(sizeofbase)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn LoadSavedStateSymbolProvider<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(vmsavedstatedumphandle: *mut ::core::ffi::c_void, usersymbols: Param1, force: Param2) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn LoadSavedStateSymbolProvider(vmsavedstatedumphandle: *mut ::core::ffi::c_void, usersymbols: super::super::Foundation::PWSTR, force: super::super::Foundation::BOOL) -> ::windows::core::HRESULT;
}
LoadSavedStateSymbolProvider(::core::mem::transmute(vmsavedstatedumphandle), usersymbols.into_param().abi(), force.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn LocateSavedStateFiles<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(vmname: Param0, snapshotname: Param1, binpath: *mut super::super::Foundation::PWSTR, vsvpath: *mut super::super::Foundation::PWSTR, vmrspath: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn LocateSavedStateFiles(vmname: super::super::Foundation::PWSTR, snapshotname: super::super::Foundation::PWSTR, binpath: *mut super::super::Foundation::PWSTR, vsvpath: *mut super::super::Foundation::PWSTR, vmrspath: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT;
}
LocateSavedStateFiles(vmname.into_param().abi(), snapshotname.into_param().abi(), ::core::mem::transmute(binpath), ::core::mem::transmute(vsvpath), ::core::mem::transmute(vmrspath)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct MODULE_INFO {
pub ProcessImageName: super::super::Foundation::PSTR,
pub Image: DOS_IMAGE_INFO,
}
#[cfg(feature = "Win32_Foundation")]
impl MODULE_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for MODULE_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for MODULE_INFO {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("MODULE_INFO").field("ProcessImageName", &self.ProcessImageName).field("Image", &self.Image).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for MODULE_INFO {
fn eq(&self, other: &Self) -> bool {
self.ProcessImageName == other.ProcessImageName && self.Image == other.Image
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for MODULE_INFO {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for MODULE_INFO {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PAGING_MODE(pub i32);
pub const Paging_Invalid: PAGING_MODE = PAGING_MODE(0i32);
pub const Paging_NonPaged: PAGING_MODE = PAGING_MODE(1i32);
pub const Paging_32Bit: PAGING_MODE = PAGING_MODE(2i32);
pub const Paging_Pae: PAGING_MODE = PAGING_MODE(3i32);
pub const Paging_Long: PAGING_MODE = PAGING_MODE(4i32);
pub const Paging_Armv8: PAGING_MODE = PAGING_MODE(5i32);
impl ::core::convert::From<i32> for PAGING_MODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PAGING_MODE {
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 REGISTER_ID(pub i32);
pub const X64_RegisterRax: REGISTER_ID = REGISTER_ID(0i32);
pub const X64_RegisterRcx: REGISTER_ID = REGISTER_ID(1i32);
pub const X64_RegisterRdx: REGISTER_ID = REGISTER_ID(2i32);
pub const X64_RegisterRbx: REGISTER_ID = REGISTER_ID(3i32);
pub const X64_RegisterRsp: REGISTER_ID = REGISTER_ID(4i32);
pub const X64_RegisterRbp: REGISTER_ID = REGISTER_ID(5i32);
pub const X64_RegisterRsi: REGISTER_ID = REGISTER_ID(6i32);
pub const X64_RegisterRdi: REGISTER_ID = REGISTER_ID(7i32);
pub const X64_RegisterR8: REGISTER_ID = REGISTER_ID(8i32);
pub const X64_RegisterR9: REGISTER_ID = REGISTER_ID(9i32);
pub const X64_RegisterR10: REGISTER_ID = REGISTER_ID(10i32);
pub const X64_RegisterR11: REGISTER_ID = REGISTER_ID(11i32);
pub const X64_RegisterR12: REGISTER_ID = REGISTER_ID(12i32);
pub const X64_RegisterR13: REGISTER_ID = REGISTER_ID(13i32);
pub const X64_RegisterR14: REGISTER_ID = REGISTER_ID(14i32);
pub const X64_RegisterR15: REGISTER_ID = REGISTER_ID(15i32);
pub const X64_RegisterRip: REGISTER_ID = REGISTER_ID(16i32);
pub const X64_RegisterRFlags: REGISTER_ID = REGISTER_ID(17i32);
pub const X64_RegisterXmm0: REGISTER_ID = REGISTER_ID(18i32);
pub const X64_RegisterXmm1: REGISTER_ID = REGISTER_ID(19i32);
pub const X64_RegisterXmm2: REGISTER_ID = REGISTER_ID(20i32);
pub const X64_RegisterXmm3: REGISTER_ID = REGISTER_ID(21i32);
pub const X64_RegisterXmm4: REGISTER_ID = REGISTER_ID(22i32);
pub const X64_RegisterXmm5: REGISTER_ID = REGISTER_ID(23i32);
pub const X64_RegisterXmm6: REGISTER_ID = REGISTER_ID(24i32);
pub const X64_RegisterXmm7: REGISTER_ID = REGISTER_ID(25i32);
pub const X64_RegisterXmm8: REGISTER_ID = REGISTER_ID(26i32);
pub const X64_RegisterXmm9: REGISTER_ID = REGISTER_ID(27i32);
pub const X64_RegisterXmm10: REGISTER_ID = REGISTER_ID(28i32);
pub const X64_RegisterXmm11: REGISTER_ID = REGISTER_ID(29i32);
pub const X64_RegisterXmm12: REGISTER_ID = REGISTER_ID(30i32);
pub const X64_RegisterXmm13: REGISTER_ID = REGISTER_ID(31i32);
pub const X64_RegisterXmm14: REGISTER_ID = REGISTER_ID(32i32);
pub const X64_RegisterXmm15: REGISTER_ID = REGISTER_ID(33i32);
pub const X64_RegisterFpMmx0: REGISTER_ID = REGISTER_ID(34i32);
pub const X64_RegisterFpMmx1: REGISTER_ID = REGISTER_ID(35i32);
pub const X64_RegisterFpMmx2: REGISTER_ID = REGISTER_ID(36i32);
pub const X64_RegisterFpMmx3: REGISTER_ID = REGISTER_ID(37i32);
pub const X64_RegisterFpMmx4: REGISTER_ID = REGISTER_ID(38i32);
pub const X64_RegisterFpMmx5: REGISTER_ID = REGISTER_ID(39i32);
pub const X64_RegisterFpMmx6: REGISTER_ID = REGISTER_ID(40i32);
pub const X64_RegisterFpMmx7: REGISTER_ID = REGISTER_ID(41i32);
pub const X64_RegisterFpControlStatus: REGISTER_ID = REGISTER_ID(42i32);
pub const X64_RegisterXmmControlStatus: REGISTER_ID = REGISTER_ID(43i32);
pub const X64_RegisterCr0: REGISTER_ID = REGISTER_ID(44i32);
pub const X64_RegisterCr2: REGISTER_ID = REGISTER_ID(45i32);
pub const X64_RegisterCr3: REGISTER_ID = REGISTER_ID(46i32);
pub const X64_RegisterCr4: REGISTER_ID = REGISTER_ID(47i32);
pub const X64_RegisterCr8: REGISTER_ID = REGISTER_ID(48i32);
pub const X64_RegisterEfer: REGISTER_ID = REGISTER_ID(49i32);
pub const X64_RegisterDr0: REGISTER_ID = REGISTER_ID(50i32);
pub const X64_RegisterDr1: REGISTER_ID = REGISTER_ID(51i32);
pub const X64_RegisterDr2: REGISTER_ID = REGISTER_ID(52i32);
pub const X64_RegisterDr3: REGISTER_ID = REGISTER_ID(53i32);
pub const X64_RegisterDr6: REGISTER_ID = REGISTER_ID(54i32);
pub const X64_RegisterDr7: REGISTER_ID = REGISTER_ID(55i32);
pub const X64_RegisterEs: REGISTER_ID = REGISTER_ID(56i32);
pub const X64_RegisterCs: REGISTER_ID = REGISTER_ID(57i32);
pub const X64_RegisterSs: REGISTER_ID = REGISTER_ID(58i32);
pub const X64_RegisterDs: REGISTER_ID = REGISTER_ID(59i32);
pub const X64_RegisterFs: REGISTER_ID = REGISTER_ID(60i32);
pub const X64_RegisterGs: REGISTER_ID = REGISTER_ID(61i32);
pub const X64_RegisterLdtr: REGISTER_ID = REGISTER_ID(62i32);
pub const X64_RegisterTr: REGISTER_ID = REGISTER_ID(63i32);
pub const X64_RegisterIdtr: REGISTER_ID = REGISTER_ID(64i32);
pub const X64_RegisterGdtr: REGISTER_ID = REGISTER_ID(65i32);
pub const X64_RegisterMax: REGISTER_ID = REGISTER_ID(66i32);
pub const ARM64_RegisterX0: REGISTER_ID = REGISTER_ID(67i32);
pub const ARM64_RegisterX1: REGISTER_ID = REGISTER_ID(68i32);
pub const ARM64_RegisterX2: REGISTER_ID = REGISTER_ID(69i32);
pub const ARM64_RegisterX3: REGISTER_ID = REGISTER_ID(70i32);
pub const ARM64_RegisterX4: REGISTER_ID = REGISTER_ID(71i32);
pub const ARM64_RegisterX5: REGISTER_ID = REGISTER_ID(72i32);
pub const ARM64_RegisterX6: REGISTER_ID = REGISTER_ID(73i32);
pub const ARM64_RegisterX7: REGISTER_ID = REGISTER_ID(74i32);
pub const ARM64_RegisterX8: REGISTER_ID = REGISTER_ID(75i32);
pub const ARM64_RegisterX9: REGISTER_ID = REGISTER_ID(76i32);
pub const ARM64_RegisterX10: REGISTER_ID = REGISTER_ID(77i32);
pub const ARM64_RegisterX11: REGISTER_ID = REGISTER_ID(78i32);
pub const ARM64_RegisterX12: REGISTER_ID = REGISTER_ID(79i32);
pub const ARM64_RegisterX13: REGISTER_ID = REGISTER_ID(80i32);
pub const ARM64_RegisterX14: REGISTER_ID = REGISTER_ID(81i32);
pub const ARM64_RegisterX15: REGISTER_ID = REGISTER_ID(82i32);
pub const ARM64_RegisterX16: REGISTER_ID = REGISTER_ID(83i32);
pub const ARM64_RegisterX17: REGISTER_ID = REGISTER_ID(84i32);
pub const ARM64_RegisterX18: REGISTER_ID = REGISTER_ID(85i32);
pub const ARM64_RegisterX19: REGISTER_ID = REGISTER_ID(86i32);
pub const ARM64_RegisterX20: REGISTER_ID = REGISTER_ID(87i32);
pub const ARM64_RegisterX21: REGISTER_ID = REGISTER_ID(88i32);
pub const ARM64_RegisterX22: REGISTER_ID = REGISTER_ID(89i32);
pub const ARM64_RegisterX23: REGISTER_ID = REGISTER_ID(90i32);
pub const ARM64_RegisterX24: REGISTER_ID = REGISTER_ID(91i32);
pub const ARM64_RegisterX25: REGISTER_ID = REGISTER_ID(92i32);
pub const ARM64_RegisterX26: REGISTER_ID = REGISTER_ID(93i32);
pub const ARM64_RegisterX27: REGISTER_ID = REGISTER_ID(94i32);
pub const ARM64_RegisterX28: REGISTER_ID = REGISTER_ID(95i32);
pub const ARM64_RegisterXFp: REGISTER_ID = REGISTER_ID(96i32);
pub const ARM64_RegisterXLr: REGISTER_ID = REGISTER_ID(97i32);
pub const ARM64_RegisterPc: REGISTER_ID = REGISTER_ID(98i32);
pub const ARM64_RegisterSpEl0: REGISTER_ID = REGISTER_ID(99i32);
pub const ARM64_RegisterSpEl1: REGISTER_ID = REGISTER_ID(100i32);
pub const ARM64_RegisterCpsr: REGISTER_ID = REGISTER_ID(101i32);
pub const ARM64_RegisterQ0: REGISTER_ID = REGISTER_ID(102i32);
pub const ARM64_RegisterQ1: REGISTER_ID = REGISTER_ID(103i32);
pub const ARM64_RegisterQ2: REGISTER_ID = REGISTER_ID(104i32);
pub const ARM64_RegisterQ3: REGISTER_ID = REGISTER_ID(105i32);
pub const ARM64_RegisterQ4: REGISTER_ID = REGISTER_ID(106i32);
pub const ARM64_RegisterQ5: REGISTER_ID = REGISTER_ID(107i32);
pub const ARM64_RegisterQ6: REGISTER_ID = REGISTER_ID(108i32);
pub const ARM64_RegisterQ7: REGISTER_ID = REGISTER_ID(109i32);
pub const ARM64_RegisterQ8: REGISTER_ID = REGISTER_ID(110i32);
pub const ARM64_RegisterQ9: REGISTER_ID = REGISTER_ID(111i32);
pub const ARM64_RegisterQ10: REGISTER_ID = REGISTER_ID(112i32);
pub const ARM64_RegisterQ11: REGISTER_ID = REGISTER_ID(113i32);
pub const ARM64_RegisterQ12: REGISTER_ID = REGISTER_ID(114i32);
pub const ARM64_RegisterQ13: REGISTER_ID = REGISTER_ID(115i32);
pub const ARM64_RegisterQ14: REGISTER_ID = REGISTER_ID(116i32);
pub const ARM64_RegisterQ15: REGISTER_ID = REGISTER_ID(117i32);
pub const ARM64_RegisterQ16: REGISTER_ID = REGISTER_ID(118i32);
pub const ARM64_RegisterQ17: REGISTER_ID = REGISTER_ID(119i32);
pub const ARM64_RegisterQ18: REGISTER_ID = REGISTER_ID(120i32);
pub const ARM64_RegisterQ19: REGISTER_ID = REGISTER_ID(121i32);
pub const ARM64_RegisterQ20: REGISTER_ID = REGISTER_ID(122i32);
pub const ARM64_RegisterQ21: REGISTER_ID = REGISTER_ID(123i32);
pub const ARM64_RegisterQ22: REGISTER_ID = REGISTER_ID(124i32);
pub const ARM64_RegisterQ23: REGISTER_ID = REGISTER_ID(125i32);
pub const ARM64_RegisterQ24: REGISTER_ID = REGISTER_ID(126i32);
pub const ARM64_RegisterQ25: REGISTER_ID = REGISTER_ID(127i32);
pub const ARM64_RegisterQ26: REGISTER_ID = REGISTER_ID(128i32);
pub const ARM64_RegisterQ27: REGISTER_ID = REGISTER_ID(129i32);
pub const ARM64_RegisterQ28: REGISTER_ID = REGISTER_ID(130i32);
pub const ARM64_RegisterQ29: REGISTER_ID = REGISTER_ID(131i32);
pub const ARM64_RegisterQ30: REGISTER_ID = REGISTER_ID(132i32);
pub const ARM64_RegisterQ31: REGISTER_ID = REGISTER_ID(133i32);
pub const ARM64_RegisterFpStatus: REGISTER_ID = REGISTER_ID(134i32);
pub const ARM64_RegisterFpControl: REGISTER_ID = REGISTER_ID(135i32);
pub const ARM64_RegisterEsrEl1: REGISTER_ID = REGISTER_ID(136i32);
pub const ARM64_RegisterSpsrEl1: REGISTER_ID = REGISTER_ID(137i32);
pub const ARM64_RegisterFarEl1: REGISTER_ID = REGISTER_ID(138i32);
pub const ARM64_RegisterParEl1: REGISTER_ID = REGISTER_ID(139i32);
pub const ARM64_RegisterElrEl1: REGISTER_ID = REGISTER_ID(140i32);
pub const ARM64_RegisterTtbr0El1: REGISTER_ID = REGISTER_ID(141i32);
pub const ARM64_RegisterTtbr1El1: REGISTER_ID = REGISTER_ID(142i32);
pub const ARM64_RegisterVbarEl1: REGISTER_ID = REGISTER_ID(143i32);
pub const ARM64_RegisterSctlrEl1: REGISTER_ID = REGISTER_ID(144i32);
pub const ARM64_RegisterActlrEl1: REGISTER_ID = REGISTER_ID(145i32);
pub const ARM64_RegisterTcrEl1: REGISTER_ID = REGISTER_ID(146i32);
pub const ARM64_RegisterMairEl1: REGISTER_ID = REGISTER_ID(147i32);
pub const ARM64_RegisterAmairEl1: REGISTER_ID = REGISTER_ID(148i32);
pub const ARM64_RegisterTpidrEl0: REGISTER_ID = REGISTER_ID(149i32);
pub const ARM64_RegisterTpidrroEl0: REGISTER_ID = REGISTER_ID(150i32);
pub const ARM64_RegisterTpidrEl1: REGISTER_ID = REGISTER_ID(151i32);
pub const ARM64_RegisterContextIdrEl1: REGISTER_ID = REGISTER_ID(152i32);
pub const ARM64_RegisterCpacrEl1: REGISTER_ID = REGISTER_ID(153i32);
pub const ARM64_RegisterCsselrEl1: REGISTER_ID = REGISTER_ID(154i32);
pub const ARM64_RegisterCntkctlEl1: REGISTER_ID = REGISTER_ID(155i32);
pub const ARM64_RegisterCntvCvalEl0: REGISTER_ID = REGISTER_ID(156i32);
pub const ARM64_RegisterCntvCtlEl0: REGISTER_ID = REGISTER_ID(157i32);
pub const ARM64_RegisterMax: REGISTER_ID = REGISTER_ID(158i32);
impl ::core::convert::From<i32> for REGISTER_ID {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for REGISTER_ID {
type Abi = Self;
}
#[inline]
pub unsafe fn ReadGuestPhysicalAddress(vmsavedstatedumphandle: *mut ::core::ffi::c_void, physicaladdress: u64, buffer: *mut ::core::ffi::c_void, buffersize: u32, bytesread: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ReadGuestPhysicalAddress(vmsavedstatedumphandle: *mut ::core::ffi::c_void, physicaladdress: u64, buffer: *mut ::core::ffi::c_void, buffersize: u32, bytesread: *mut u32) -> ::windows::core::HRESULT;
}
ReadGuestPhysicalAddress(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(physicaladdress), ::core::mem::transmute(buffer), ::core::mem::transmute(buffersize), ::core::mem::transmute(bytesread)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn ReadGuestRawSavedMemory(vmsavedstatedumphandle: *mut ::core::ffi::c_void, rawsavedmemoryoffset: u64, buffer: *mut ::core::ffi::c_void, buffersize: u32, bytesread: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ReadGuestRawSavedMemory(vmsavedstatedumphandle: *mut ::core::ffi::c_void, rawsavedmemoryoffset: u64, buffer: *mut ::core::ffi::c_void, buffersize: u32, bytesread: *mut u32) -> ::windows::core::HRESULT;
}
ReadGuestRawSavedMemory(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(rawsavedmemoryoffset), ::core::mem::transmute(buffer), ::core::mem::transmute(buffersize), ::core::mem::transmute(bytesread)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn ReadSavedStateGlobalVariable<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, globalname: Param2, buffer: *mut ::core::ffi::c_void, buffersize: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ReadSavedStateGlobalVariable(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, globalname: super::super::Foundation::PSTR, buffer: *mut ::core::ffi::c_void, buffersize: u32) -> ::windows::core::HRESULT;
}
ReadSavedStateGlobalVariable(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), globalname.into_param().abi(), ::core::mem::transmute(buffer), ::core::mem::transmute(buffersize)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn ReleaseSavedStateFiles(vmsavedstatedumphandle: *mut ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ReleaseSavedStateFiles(vmsavedstatedumphandle: *mut ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
ReleaseSavedStateFiles(::core::mem::transmute(vmsavedstatedumphandle)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn ReleaseSavedStateSymbolProvider(vmsavedstatedumphandle: *mut ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ReleaseSavedStateSymbolProvider(vmsavedstatedumphandle: *mut ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
ReleaseSavedStateSymbolProvider(::core::mem::transmute(vmsavedstatedumphandle)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn ResolveSavedStateGlobalVariableAddress<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, globalname: Param2, virtualaddress: *mut u64, size: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ResolveSavedStateGlobalVariableAddress(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, globalname: super::super::Foundation::PSTR, virtualaddress: *mut u64, size: *mut u32) -> ::windows::core::HRESULT;
}
ResolveSavedStateGlobalVariableAddress(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(vpid), globalname.into_param().abi(), ::core::mem::transmute(virtualaddress), ::core::mem::transmute(size)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct SOCKADDR_HV {
pub Family: u16,
pub Reserved: u16,
pub VmId: ::windows::core::GUID,
pub ServiceId: ::windows::core::GUID,
}
impl SOCKADDR_HV {}
impl ::core::default::Default for SOCKADDR_HV {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for SOCKADDR_HV {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("SOCKADDR_HV").field("Family", &self.Family).field("Reserved", &self.Reserved).field("VmId", &self.VmId).field("ServiceId", &self.ServiceId).finish()
}
}
impl ::core::cmp::PartialEq for SOCKADDR_HV {
fn eq(&self, other: &Self) -> bool {
self.Family == other.Family && self.Reserved == other.Reserved && self.VmId == other.VmId && self.ServiceId == other.ServiceId
}
}
impl ::core::cmp::Eq for SOCKADDR_HV {}
unsafe impl ::windows::core::Abi for SOCKADDR_HV {
type Abi = Self;
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn ScanMemoryForDosImages(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, startaddress: u64, endaddress: u64, callbackcontext: *mut ::core::ffi::c_void, foundimagecallback: ::core::option::Option<FOUND_IMAGE_CALLBACK>, standaloneaddress: *const u64, standaloneaddresscount: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn ScanMemoryForDosImages(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, startaddress: u64, endaddress: u64, callbackcontext: *mut ::core::ffi::c_void, foundimagecallback: ::windows::core::RawPtr, standaloneaddress: *const u64, standaloneaddresscount: u32) -> ::windows::core::HRESULT;
}
ScanMemoryForDosImages(
::core::mem::transmute(vmsavedstatedumphandle),
::core::mem::transmute(vpid),
::core::mem::transmute(startaddress),
::core::mem::transmute(endaddress),
::core::mem::transmute(callbackcontext),
::core::mem::transmute(foundimagecallback),
::core::mem::transmute(standaloneaddress),
::core::mem::transmute(standaloneaddresscount),
)
.ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn SetMemoryBlockCacheLimit(vmsavedstatedumphandle: *mut ::core::ffi::c_void, memoryblockcachelimit: u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn SetMemoryBlockCacheLimit(vmsavedstatedumphandle: *mut ::core::ffi::c_void, memoryblockcachelimit: u64) -> ::windows::core::HRESULT;
}
SetMemoryBlockCacheLimit(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(memoryblockcachelimit)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn SetSavedStateSymbolProviderDebugInfoCallback(vmsavedstatedumphandle: *mut ::core::ffi::c_void, callback: ::core::option::Option<GUEST_SYMBOLS_PROVIDER_DEBUG_INFO_CALLBACK>) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn SetSavedStateSymbolProviderDebugInfoCallback(vmsavedstatedumphandle: *mut ::core::ffi::c_void, callback: ::windows::core::RawPtr) -> ::windows::core::HRESULT;
}
SetSavedStateSymbolProviderDebugInfoCallback(::core::mem::transmute(vmsavedstatedumphandle), ::core::mem::transmute(callback)).ok()
}
#[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 VIRTUAL_PROCESSOR_ARCH(pub i32);
pub const Arch_Unknown: VIRTUAL_PROCESSOR_ARCH = VIRTUAL_PROCESSOR_ARCH(0i32);
pub const Arch_x86: VIRTUAL_PROCESSOR_ARCH = VIRTUAL_PROCESSOR_ARCH(1i32);
pub const Arch_x64: VIRTUAL_PROCESSOR_ARCH = VIRTUAL_PROCESSOR_ARCH(2i32);
pub const Arch_Armv8: VIRTUAL_PROCESSOR_ARCH = VIRTUAL_PROCESSOR_ARCH(3i32);
impl ::core::convert::From<i32> for VIRTUAL_PROCESSOR_ARCH {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_ARCH {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union VIRTUAL_PROCESSOR_REGISTER {
pub Reg64: u64,
pub Reg32: u32,
pub Reg16: u16,
pub Reg8: u8,
pub Reg128: VIRTUAL_PROCESSOR_REGISTER_0,
pub X64: VIRTUAL_PROCESSOR_REGISTER_1,
}
impl VIRTUAL_PROCESSOR_REGISTER {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct VIRTUAL_PROCESSOR_REGISTER_0 {
pub Low64: u64,
pub High64: u64,
}
impl VIRTUAL_PROCESSOR_REGISTER_0 {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for VIRTUAL_PROCESSOR_REGISTER_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Reg128_e__Struct").field("Low64", &self.Low64).field("High64", &self.High64).finish()
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER_0 {
fn eq(&self, other: &Self) -> bool {
self.Low64 == other.Low64 && self.High64 == other.High64
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER_0 {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union VIRTUAL_PROCESSOR_REGISTER_1 {
pub Segment: VIRTUAL_PROCESSOR_REGISTER_1_1,
pub Table: VIRTUAL_PROCESSOR_REGISTER_1_2,
pub FpControlStatus: VIRTUAL_PROCESSOR_REGISTER_1_0,
pub XmmControlStatus: VIRTUAL_PROCESSOR_REGISTER_1_3,
}
impl VIRTUAL_PROCESSOR_REGISTER_1 {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER_1 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER_1 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER_1 {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER_1 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct VIRTUAL_PROCESSOR_REGISTER_1_0 {
pub FpControl: u16,
pub FpStatus: u16,
pub FpTag: u8,
pub Reserved: u8,
pub LastFpOp: u16,
pub Anonymous: VIRTUAL_PROCESSOR_REGISTER_1_0_0,
}
impl VIRTUAL_PROCESSOR_REGISTER_1_0 {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER_1_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER_1_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER_1_0 {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER_1_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union VIRTUAL_PROCESSOR_REGISTER_1_0_0 {
pub LastFpRip: u64,
pub Anonymous: VIRTUAL_PROCESSOR_REGISTER_1_0_0_0,
}
impl VIRTUAL_PROCESSOR_REGISTER_1_0_0 {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER_1_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER_1_0_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER_1_0_0 {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER_1_0_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct VIRTUAL_PROCESSOR_REGISTER_1_0_0_0 {
pub LastFpEip: u32,
pub LastFpCs: u16,
}
impl VIRTUAL_PROCESSOR_REGISTER_1_0_0_0 {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER_1_0_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for VIRTUAL_PROCESSOR_REGISTER_1_0_0_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("LastFpEip", &self.LastFpEip).field("LastFpCs", &self.LastFpCs).finish()
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER_1_0_0_0 {
fn eq(&self, other: &Self) -> bool {
self.LastFpEip == other.LastFpEip && self.LastFpCs == other.LastFpCs
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER_1_0_0_0 {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER_1_0_0_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct VIRTUAL_PROCESSOR_REGISTER_1_1 {
pub Base: u64,
pub Limit: u32,
pub Selector: u16,
pub Anonymous: VIRTUAL_PROCESSOR_REGISTER_1_1_0,
}
impl VIRTUAL_PROCESSOR_REGISTER_1_1 {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER_1_1 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER_1_1 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER_1_1 {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER_1_1 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union VIRTUAL_PROCESSOR_REGISTER_1_1_0 {
pub Attributes: u16,
pub Anonymous: VIRTUAL_PROCESSOR_REGISTER_1_1_0_0,
}
impl VIRTUAL_PROCESSOR_REGISTER_1_1_0 {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER_1_1_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER_1_1_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER_1_1_0 {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER_1_1_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct VIRTUAL_PROCESSOR_REGISTER_1_1_0_0 {
pub _bitfield: u16,
}
impl VIRTUAL_PROCESSOR_REGISTER_1_1_0_0 {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER_1_1_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for VIRTUAL_PROCESSOR_REGISTER_1_1_0_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER_1_1_0_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER_1_1_0_0 {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER_1_1_0_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct VIRTUAL_PROCESSOR_REGISTER_1_2 {
pub Limit: u16,
pub Base: u64,
}
impl VIRTUAL_PROCESSOR_REGISTER_1_2 {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER_1_2 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for VIRTUAL_PROCESSOR_REGISTER_1_2 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Table_e__Struct").field("Limit", &self.Limit).field("Base", &self.Base).finish()
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER_1_2 {
fn eq(&self, other: &Self) -> bool {
self.Limit == other.Limit && self.Base == other.Base
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER_1_2 {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER_1_2 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct VIRTUAL_PROCESSOR_REGISTER_1_3 {
pub Anonymous: VIRTUAL_PROCESSOR_REGISTER_1_3_0,
pub XmmStatusControl: u32,
pub XmmStatusControlMask: u32,
}
impl VIRTUAL_PROCESSOR_REGISTER_1_3 {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER_1_3 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER_1_3 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER_1_3 {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER_1_3 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union VIRTUAL_PROCESSOR_REGISTER_1_3_0 {
pub LastFpRdp: u64,
pub Anonymous: VIRTUAL_PROCESSOR_REGISTER_1_3_0_0,
}
impl VIRTUAL_PROCESSOR_REGISTER_1_3_0 {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER_1_3_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER_1_3_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER_1_3_0 {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER_1_3_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct VIRTUAL_PROCESSOR_REGISTER_1_3_0_0 {
pub LastFpDp: u32,
pub LastFpDs: u16,
}
impl VIRTUAL_PROCESSOR_REGISTER_1_3_0_0 {}
impl ::core::default::Default for VIRTUAL_PROCESSOR_REGISTER_1_3_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for VIRTUAL_PROCESSOR_REGISTER_1_3_0_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("LastFpDp", &self.LastFpDp).field("LastFpDs", &self.LastFpDs).finish()
}
}
impl ::core::cmp::PartialEq for VIRTUAL_PROCESSOR_REGISTER_1_3_0_0 {
fn eq(&self, other: &Self) -> bool {
self.LastFpDp == other.LastFpDp && self.LastFpDs == other.LastFpDs
}
}
impl ::core::cmp::Eq for VIRTUAL_PROCESSOR_REGISTER_1_3_0_0 {}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_REGISTER_1_3_0_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 VIRTUAL_PROCESSOR_VENDOR(pub i32);
pub const ProcessorVendor_Unknown: VIRTUAL_PROCESSOR_VENDOR = VIRTUAL_PROCESSOR_VENDOR(0i32);
pub const ProcessorVendor_Amd: VIRTUAL_PROCESSOR_VENDOR = VIRTUAL_PROCESSOR_VENDOR(1i32);
pub const ProcessorVendor_Intel: VIRTUAL_PROCESSOR_VENDOR = VIRTUAL_PROCESSOR_VENDOR(2i32);
pub const ProcessorVendor_Hygon: VIRTUAL_PROCESSOR_VENDOR = VIRTUAL_PROCESSOR_VENDOR(3i32);
pub const ProcessorVendor_Arm: VIRTUAL_PROCESSOR_VENDOR = VIRTUAL_PROCESSOR_VENDOR(4i32);
impl ::core::convert::From<i32> for VIRTUAL_PROCESSOR_VENDOR {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for VIRTUAL_PROCESSOR_VENDOR {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct VM_GENCOUNTER {
pub GenerationCount: u64,
pub GenerationCountHigh: u64,
}
impl VM_GENCOUNTER {}
impl ::core::default::Default for VM_GENCOUNTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for VM_GENCOUNTER {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("VM_GENCOUNTER").field("GenerationCount", &self.GenerationCount).field("GenerationCountHigh", &self.GenerationCountHigh).finish()
}
}
impl ::core::cmp::PartialEq for VM_GENCOUNTER {
fn eq(&self, other: &Self) -> bool {
self.GenerationCount == other.GenerationCount && self.GenerationCountHigh == other.GenerationCountHigh
}
}
impl ::core::cmp::Eq for VM_GENCOUNTER {}
unsafe impl ::windows::core::Abi for VM_GENCOUNTER {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_ACCESS_GPA_CONTROLS {
pub AsUINT64: u64,
pub Anonymous: WHV_ACCESS_GPA_CONTROLS_0,
}
impl WHV_ACCESS_GPA_CONTROLS {}
impl ::core::default::Default for WHV_ACCESS_GPA_CONTROLS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_ACCESS_GPA_CONTROLS {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_ACCESS_GPA_CONTROLS {}
unsafe impl ::windows::core::Abi for WHV_ACCESS_GPA_CONTROLS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_ACCESS_GPA_CONTROLS_0 {
pub CacheType: WHV_CACHE_TYPE,
pub Reserved: u32,
}
impl WHV_ACCESS_GPA_CONTROLS_0 {}
impl ::core::default::Default for WHV_ACCESS_GPA_CONTROLS_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_ACCESS_GPA_CONTROLS_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("CacheType", &self.CacheType).field("Reserved", &self.Reserved).finish()
}
}
impl ::core::cmp::PartialEq for WHV_ACCESS_GPA_CONTROLS_0 {
fn eq(&self, other: &Self) -> bool {
self.CacheType == other.CacheType && self.Reserved == other.Reserved
}
}
impl ::core::cmp::Eq for WHV_ACCESS_GPA_CONTROLS_0 {}
unsafe impl ::windows::core::Abi for WHV_ACCESS_GPA_CONTROLS_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_ADVISE_GPA_RANGE {
pub Populate: WHV_ADVISE_GPA_RANGE_POPULATE,
}
impl WHV_ADVISE_GPA_RANGE {}
impl ::core::default::Default for WHV_ADVISE_GPA_RANGE {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_ADVISE_GPA_RANGE {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_ADVISE_GPA_RANGE {}
unsafe impl ::windows::core::Abi for WHV_ADVISE_GPA_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 WHV_ADVISE_GPA_RANGE_CODE(pub i32);
pub const WHvAdviseGpaRangeCodePopulate: WHV_ADVISE_GPA_RANGE_CODE = WHV_ADVISE_GPA_RANGE_CODE(0i32);
pub const WHvAdviseGpaRangeCodePin: WHV_ADVISE_GPA_RANGE_CODE = WHV_ADVISE_GPA_RANGE_CODE(1i32);
pub const WHvAdviseGpaRangeCodeUnpin: WHV_ADVISE_GPA_RANGE_CODE = WHV_ADVISE_GPA_RANGE_CODE(2i32);
impl ::core::convert::From<i32> for WHV_ADVISE_GPA_RANGE_CODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_ADVISE_GPA_RANGE_CODE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_ADVISE_GPA_RANGE_POPULATE {
pub Flags: WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS,
pub AccessType: WHV_MEMORY_ACCESS_TYPE,
}
impl WHV_ADVISE_GPA_RANGE_POPULATE {}
impl ::core::default::Default for WHV_ADVISE_GPA_RANGE_POPULATE {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_ADVISE_GPA_RANGE_POPULATE {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_ADVISE_GPA_RANGE_POPULATE {}
unsafe impl ::windows::core::Abi for WHV_ADVISE_GPA_RANGE_POPULATE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS {
pub AsUINT32: u32,
pub Anonymous: WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS_0,
}
impl WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS {}
impl ::core::default::Default for WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS {}
unsafe impl ::windows::core::Abi for WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS_0 {
pub _bitfield: u32,
}
impl WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS_0 {}
impl ::core::default::Default for WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS_0 {}
unsafe impl ::windows::core::Abi for WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS_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 WHV_ALLOCATE_VPCI_RESOURCE_FLAGS(pub u32);
pub const WHvAllocateVpciResourceFlagNone: WHV_ALLOCATE_VPCI_RESOURCE_FLAGS = WHV_ALLOCATE_VPCI_RESOURCE_FLAGS(0u32);
pub const WHvAllocateVpciResourceFlagAllowDirectP2P: WHV_ALLOCATE_VPCI_RESOURCE_FLAGS = WHV_ALLOCATE_VPCI_RESOURCE_FLAGS(1u32);
impl ::core::convert::From<u32> for WHV_ALLOCATE_VPCI_RESOURCE_FLAGS {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_ALLOCATE_VPCI_RESOURCE_FLAGS {
type Abi = Self;
}
impl ::core::ops::BitOr for WHV_ALLOCATE_VPCI_RESOURCE_FLAGS {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for WHV_ALLOCATE_VPCI_RESOURCE_FLAGS {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for WHV_ALLOCATE_VPCI_RESOURCE_FLAGS {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for WHV_ALLOCATE_VPCI_RESOURCE_FLAGS {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for WHV_ALLOCATE_VPCI_RESOURCE_FLAGS {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
pub const WHV_ANY_VP: u32 = 4294967295u32;
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct WHV_CACHE_TYPE(pub i32);
pub const WHvCacheTypeUncached: WHV_CACHE_TYPE = WHV_CACHE_TYPE(0i32);
pub const WHvCacheTypeWriteCombining: WHV_CACHE_TYPE = WHV_CACHE_TYPE(1i32);
pub const WHvCacheTypeWriteThrough: WHV_CACHE_TYPE = WHV_CACHE_TYPE(4i32);
pub const WHvCacheTypeWriteProtected: WHV_CACHE_TYPE = WHV_CACHE_TYPE(5i32);
pub const WHvCacheTypeWriteBack: WHV_CACHE_TYPE = WHV_CACHE_TYPE(6i32);
impl ::core::convert::From<i32> for WHV_CACHE_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_CACHE_TYPE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union WHV_CAPABILITY {
pub HypervisorPresent: super::super::Foundation::BOOL,
pub Features: WHV_CAPABILITY_FEATURES,
pub ExtendedVmExits: WHV_EXTENDED_VM_EXITS,
pub ProcessorVendor: WHV_PROCESSOR_VENDOR,
pub ProcessorFeatures: WHV_PROCESSOR_FEATURES,
pub SyntheticProcessorFeaturesBanks: WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS,
pub ProcessorXsaveFeatures: WHV_PROCESSOR_XSAVE_FEATURES,
pub ProcessorClFlushSize: u8,
pub ExceptionExitBitmap: u64,
pub X64MsrExitBitmap: WHV_X64_MSR_EXIT_BITMAP,
pub ProcessorClockFrequency: u64,
pub InterruptClockFrequency: u64,
pub ProcessorFeaturesBanks: WHV_PROCESSOR_FEATURES_BANKS,
pub GpaRangePopulateFlags: WHV_ADVISE_GPA_RANGE_POPULATE_FLAGS,
pub ProcessorFrequencyCap: WHV_CAPABILITY_PROCESSOR_FREQUENCY_CAP,
pub ProcessorPerfmonFeatures: WHV_PROCESSOR_PERFMON_FEATURES,
pub SchedulerFeatures: WHV_SCHEDULER_FEATURES,
}
#[cfg(feature = "Win32_Foundation")]
impl WHV_CAPABILITY {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for WHV_CAPABILITY {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for WHV_CAPABILITY {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for WHV_CAPABILITY {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for WHV_CAPABILITY {
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 WHV_CAPABILITY_CODE(pub i32);
pub const WHvCapabilityCodeHypervisorPresent: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(0i32);
pub const WHvCapabilityCodeFeatures: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(1i32);
pub const WHvCapabilityCodeExtendedVmExits: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(2i32);
pub const WHvCapabilityCodeExceptionExitBitmap: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(3i32);
pub const WHvCapabilityCodeX64MsrExitBitmap: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(4i32);
pub const WHvCapabilityCodeGpaRangePopulateFlags: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(5i32);
pub const WHvCapabilityCodeSchedulerFeatures: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(6i32);
pub const WHvCapabilityCodeProcessorVendor: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(4096i32);
pub const WHvCapabilityCodeProcessorFeatures: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(4097i32);
pub const WHvCapabilityCodeProcessorClFlushSize: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(4098i32);
pub const WHvCapabilityCodeProcessorXsaveFeatures: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(4099i32);
pub const WHvCapabilityCodeProcessorClockFrequency: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(4100i32);
pub const WHvCapabilityCodeInterruptClockFrequency: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(4101i32);
pub const WHvCapabilityCodeProcessorFeaturesBanks: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(4102i32);
pub const WHvCapabilityCodeProcessorFrequencyCap: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(4103i32);
pub const WHvCapabilityCodeSyntheticProcessorFeaturesBanks: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(4104i32);
pub const WHvCapabilityCodeProcessorPerfmonFeatures: WHV_CAPABILITY_CODE = WHV_CAPABILITY_CODE(4105i32);
impl ::core::convert::From<i32> for WHV_CAPABILITY_CODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_CAPABILITY_CODE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_CAPABILITY_FEATURES {
pub Anonymous: WHV_CAPABILITY_FEATURES_0,
pub AsUINT64: u64,
}
impl WHV_CAPABILITY_FEATURES {}
impl ::core::default::Default for WHV_CAPABILITY_FEATURES {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_CAPABILITY_FEATURES {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_CAPABILITY_FEATURES {}
unsafe impl ::windows::core::Abi for WHV_CAPABILITY_FEATURES {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_CAPABILITY_FEATURES_0 {
pub _bitfield: u64,
}
impl WHV_CAPABILITY_FEATURES_0 {}
impl ::core::default::Default for WHV_CAPABILITY_FEATURES_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_CAPABILITY_FEATURES_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_CAPABILITY_FEATURES_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_CAPABILITY_FEATURES_0 {}
unsafe impl ::windows::core::Abi for WHV_CAPABILITY_FEATURES_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_CAPABILITY_PROCESSOR_FREQUENCY_CAP {
pub _bitfield: u32,
pub HighestFrequencyMhz: u32,
pub NominalFrequencyMhz: u32,
pub LowestFrequencyMhz: u32,
pub FrequencyStepMhz: u32,
}
impl WHV_CAPABILITY_PROCESSOR_FREQUENCY_CAP {}
impl ::core::default::Default for WHV_CAPABILITY_PROCESSOR_FREQUENCY_CAP {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_CAPABILITY_PROCESSOR_FREQUENCY_CAP {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_CAPABILITY_PROCESSOR_FREQUENCY_CAP")
.field("_bitfield", &self._bitfield)
.field("HighestFrequencyMhz", &self.HighestFrequencyMhz)
.field("NominalFrequencyMhz", &self.NominalFrequencyMhz)
.field("LowestFrequencyMhz", &self.LowestFrequencyMhz)
.field("FrequencyStepMhz", &self.FrequencyStepMhz)
.finish()
}
}
impl ::core::cmp::PartialEq for WHV_CAPABILITY_PROCESSOR_FREQUENCY_CAP {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield && self.HighestFrequencyMhz == other.HighestFrequencyMhz && self.NominalFrequencyMhz == other.NominalFrequencyMhz && self.LowestFrequencyMhz == other.LowestFrequencyMhz && self.FrequencyStepMhz == other.FrequencyStepMhz
}
}
impl ::core::cmp::Eq for WHV_CAPABILITY_PROCESSOR_FREQUENCY_CAP {}
unsafe impl ::windows::core::Abi for WHV_CAPABILITY_PROCESSOR_FREQUENCY_CAP {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_CPUID_OUTPUT {
pub Eax: u32,
pub Ebx: u32,
pub Ecx: u32,
pub Edx: u32,
}
impl WHV_CPUID_OUTPUT {}
impl ::core::default::Default for WHV_CPUID_OUTPUT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_CPUID_OUTPUT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_CPUID_OUTPUT").field("Eax", &self.Eax).field("Ebx", &self.Ebx).field("Ecx", &self.Ecx).field("Edx", &self.Edx).finish()
}
}
impl ::core::cmp::PartialEq for WHV_CPUID_OUTPUT {
fn eq(&self, other: &Self) -> bool {
self.Eax == other.Eax && self.Ebx == other.Ebx && self.Ecx == other.Ecx && self.Edx == other.Edx
}
}
impl ::core::cmp::Eq for WHV_CPUID_OUTPUT {}
unsafe impl ::windows::core::Abi for WHV_CPUID_OUTPUT {
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 WHV_CREATE_VPCI_DEVICE_FLAGS(pub u32);
pub const WHvCreateVpciDeviceFlagNone: WHV_CREATE_VPCI_DEVICE_FLAGS = WHV_CREATE_VPCI_DEVICE_FLAGS(0u32);
pub const WHvCreateVpciDeviceFlagPhysicallyBacked: WHV_CREATE_VPCI_DEVICE_FLAGS = WHV_CREATE_VPCI_DEVICE_FLAGS(1u32);
pub const WHvCreateVpciDeviceFlagUseLogicalInterrupts: WHV_CREATE_VPCI_DEVICE_FLAGS = WHV_CREATE_VPCI_DEVICE_FLAGS(2u32);
impl ::core::convert::From<u32> for WHV_CREATE_VPCI_DEVICE_FLAGS {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_CREATE_VPCI_DEVICE_FLAGS {
type Abi = Self;
}
impl ::core::ops::BitOr for WHV_CREATE_VPCI_DEVICE_FLAGS {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for WHV_CREATE_VPCI_DEVICE_FLAGS {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for WHV_CREATE_VPCI_DEVICE_FLAGS {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for WHV_CREATE_VPCI_DEVICE_FLAGS {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for WHV_CREATE_VPCI_DEVICE_FLAGS {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_DOORBELL_MATCH_DATA {
pub GuestAddress: u64,
pub Value: u64,
pub Length: u32,
pub _bitfield: u32,
}
impl WHV_DOORBELL_MATCH_DATA {}
impl ::core::default::Default for WHV_DOORBELL_MATCH_DATA {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_DOORBELL_MATCH_DATA {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_DOORBELL_MATCH_DATA").field("GuestAddress", &self.GuestAddress).field("Value", &self.Value).field("Length", &self.Length).field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_DOORBELL_MATCH_DATA {
fn eq(&self, other: &Self) -> bool {
self.GuestAddress == other.GuestAddress && self.Value == other.Value && self.Length == other.Length && self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_DOORBELL_MATCH_DATA {}
unsafe impl ::windows::core::Abi for WHV_DOORBELL_MATCH_DATA {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone)]
#[repr(C)]
pub struct WHV_EMULATOR_CALLBACKS {
pub Size: u32,
pub Reserved: u32,
pub WHvEmulatorIoPortCallback: ::core::option::Option<WHV_EMULATOR_IO_PORT_CALLBACK>,
pub WHvEmulatorMemoryCallback: ::core::option::Option<WHV_EMULATOR_MEMORY_CALLBACK>,
pub WHvEmulatorGetVirtualProcessorRegisters: ::core::option::Option<WHV_EMULATOR_GET_VIRTUAL_PROCESSOR_REGISTERS_CALLBACK>,
pub WHvEmulatorSetVirtualProcessorRegisters: ::core::option::Option<WHV_EMULATOR_SET_VIRTUAL_PROCESSOR_REGISTERS_CALLBACK>,
pub WHvEmulatorTranslateGvaPage: ::core::option::Option<WHV_EMULATOR_TRANSLATE_GVA_PAGE_CALLBACK>,
}
impl WHV_EMULATOR_CALLBACKS {}
impl ::core::default::Default for WHV_EMULATOR_CALLBACKS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_EMULATOR_CALLBACKS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_EMULATOR_CALLBACKS").field("Size", &self.Size).field("Reserved", &self.Reserved).finish()
}
}
impl ::core::cmp::PartialEq for WHV_EMULATOR_CALLBACKS {
fn eq(&self, other: &Self) -> bool {
self.Size == other.Size
&& self.Reserved == other.Reserved
&& self.WHvEmulatorIoPortCallback.map(|f| f as usize) == other.WHvEmulatorIoPortCallback.map(|f| f as usize)
&& self.WHvEmulatorMemoryCallback.map(|f| f as usize) == other.WHvEmulatorMemoryCallback.map(|f| f as usize)
&& self.WHvEmulatorGetVirtualProcessorRegisters.map(|f| f as usize) == other.WHvEmulatorGetVirtualProcessorRegisters.map(|f| f as usize)
&& self.WHvEmulatorSetVirtualProcessorRegisters.map(|f| f as usize) == other.WHvEmulatorSetVirtualProcessorRegisters.map(|f| f as usize)
&& self.WHvEmulatorTranslateGvaPage.map(|f| f as usize) == other.WHvEmulatorTranslateGvaPage.map(|f| f as usize)
}
}
impl ::core::cmp::Eq for WHV_EMULATOR_CALLBACKS {}
unsafe impl ::windows::core::Abi for WHV_EMULATOR_CALLBACKS {
type Abi = ::core::mem::ManuallyDrop<Self>;
}
pub type WHV_EMULATOR_GET_VIRTUAL_PROCESSOR_REGISTERS_CALLBACK = unsafe extern "system" fn(context: *const ::core::ffi::c_void, registernames: *const WHV_REGISTER_NAME, registercount: u32, registervalues: *mut WHV_REGISTER_VALUE) -> ::windows::core::HRESULT;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_EMULATOR_IO_ACCESS_INFO {
pub Direction: u8,
pub Port: u16,
pub AccessSize: u16,
pub Data: u32,
}
impl WHV_EMULATOR_IO_ACCESS_INFO {}
impl ::core::default::Default for WHV_EMULATOR_IO_ACCESS_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_EMULATOR_IO_ACCESS_INFO {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_EMULATOR_IO_ACCESS_INFO").field("Direction", &self.Direction).field("Port", &self.Port).field("AccessSize", &self.AccessSize).field("Data", &self.Data).finish()
}
}
impl ::core::cmp::PartialEq for WHV_EMULATOR_IO_ACCESS_INFO {
fn eq(&self, other: &Self) -> bool {
self.Direction == other.Direction && self.Port == other.Port && self.AccessSize == other.AccessSize && self.Data == other.Data
}
}
impl ::core::cmp::Eq for WHV_EMULATOR_IO_ACCESS_INFO {}
unsafe impl ::windows::core::Abi for WHV_EMULATOR_IO_ACCESS_INFO {
type Abi = Self;
}
pub type WHV_EMULATOR_IO_PORT_CALLBACK = unsafe extern "system" fn(context: *const ::core::ffi::c_void, ioaccess: *mut WHV_EMULATOR_IO_ACCESS_INFO) -> ::windows::core::HRESULT;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_EMULATOR_MEMORY_ACCESS_INFO {
pub GpaAddress: u64,
pub Direction: u8,
pub AccessSize: u8,
pub Data: [u8; 8],
}
impl WHV_EMULATOR_MEMORY_ACCESS_INFO {}
impl ::core::default::Default for WHV_EMULATOR_MEMORY_ACCESS_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_EMULATOR_MEMORY_ACCESS_INFO {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_EMULATOR_MEMORY_ACCESS_INFO").field("GpaAddress", &self.GpaAddress).field("Direction", &self.Direction).field("AccessSize", &self.AccessSize).field("Data", &self.Data).finish()
}
}
impl ::core::cmp::PartialEq for WHV_EMULATOR_MEMORY_ACCESS_INFO {
fn eq(&self, other: &Self) -> bool {
self.GpaAddress == other.GpaAddress && self.Direction == other.Direction && self.AccessSize == other.AccessSize && self.Data == other.Data
}
}
impl ::core::cmp::Eq for WHV_EMULATOR_MEMORY_ACCESS_INFO {}
unsafe impl ::windows::core::Abi for WHV_EMULATOR_MEMORY_ACCESS_INFO {
type Abi = Self;
}
pub type WHV_EMULATOR_MEMORY_CALLBACK = unsafe extern "system" fn(context: *const ::core::ffi::c_void, memoryaccess: *mut WHV_EMULATOR_MEMORY_ACCESS_INFO) -> ::windows::core::HRESULT;
pub type WHV_EMULATOR_SET_VIRTUAL_PROCESSOR_REGISTERS_CALLBACK = unsafe extern "system" fn(context: *const ::core::ffi::c_void, registernames: *const WHV_REGISTER_NAME, registercount: u32, registervalues: *const WHV_REGISTER_VALUE) -> ::windows::core::HRESULT;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_EMULATOR_STATUS {
pub Anonymous: WHV_EMULATOR_STATUS_0,
pub AsUINT32: u32,
}
impl WHV_EMULATOR_STATUS {}
impl ::core::default::Default for WHV_EMULATOR_STATUS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_EMULATOR_STATUS {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_EMULATOR_STATUS {}
unsafe impl ::windows::core::Abi for WHV_EMULATOR_STATUS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_EMULATOR_STATUS_0 {
pub _bitfield: u32,
}
impl WHV_EMULATOR_STATUS_0 {}
impl ::core::default::Default for WHV_EMULATOR_STATUS_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_EMULATOR_STATUS_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_EMULATOR_STATUS_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_EMULATOR_STATUS_0 {}
unsafe impl ::windows::core::Abi for WHV_EMULATOR_STATUS_0 {
type Abi = Self;
}
pub type WHV_EMULATOR_TRANSLATE_GVA_PAGE_CALLBACK = unsafe extern "system" fn(context: *const ::core::ffi::c_void, gva: u64, translateflags: WHV_TRANSLATE_GVA_FLAGS, translationresult: *mut WHV_TRANSLATE_GVA_RESULT_CODE, gpa: *mut u64) -> ::windows::core::HRESULT;
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct WHV_EXCEPTION_TYPE(pub i32);
pub const WHvX64ExceptionTypeDivideErrorFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(0i32);
pub const WHvX64ExceptionTypeDebugTrapOrFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(1i32);
pub const WHvX64ExceptionTypeBreakpointTrap: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(3i32);
pub const WHvX64ExceptionTypeOverflowTrap: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(4i32);
pub const WHvX64ExceptionTypeBoundRangeFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(5i32);
pub const WHvX64ExceptionTypeInvalidOpcodeFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(6i32);
pub const WHvX64ExceptionTypeDeviceNotAvailableFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(7i32);
pub const WHvX64ExceptionTypeDoubleFaultAbort: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(8i32);
pub const WHvX64ExceptionTypeInvalidTaskStateSegmentFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(10i32);
pub const WHvX64ExceptionTypeSegmentNotPresentFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(11i32);
pub const WHvX64ExceptionTypeStackFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(12i32);
pub const WHvX64ExceptionTypeGeneralProtectionFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(13i32);
pub const WHvX64ExceptionTypePageFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(14i32);
pub const WHvX64ExceptionTypeFloatingPointErrorFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(16i32);
pub const WHvX64ExceptionTypeAlignmentCheckFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(17i32);
pub const WHvX64ExceptionTypeMachineCheckAbort: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(18i32);
pub const WHvX64ExceptionTypeSimdFloatingPointFault: WHV_EXCEPTION_TYPE = WHV_EXCEPTION_TYPE(19i32);
impl ::core::convert::From<i32> for WHV_EXCEPTION_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_EXCEPTION_TYPE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_EXTENDED_VM_EXITS {
pub Anonymous: WHV_EXTENDED_VM_EXITS_0,
pub AsUINT64: u64,
}
impl WHV_EXTENDED_VM_EXITS {}
impl ::core::default::Default for WHV_EXTENDED_VM_EXITS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_EXTENDED_VM_EXITS {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_EXTENDED_VM_EXITS {}
unsafe impl ::windows::core::Abi for WHV_EXTENDED_VM_EXITS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_EXTENDED_VM_EXITS_0 {
pub _bitfield: u64,
}
impl WHV_EXTENDED_VM_EXITS_0 {}
impl ::core::default::Default for WHV_EXTENDED_VM_EXITS_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_EXTENDED_VM_EXITS_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_EXTENDED_VM_EXITS_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_EXTENDED_VM_EXITS_0 {}
unsafe impl ::windows::core::Abi for WHV_EXTENDED_VM_EXITS_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_HYPERCALL_CONTEXT {
pub Rax: u64,
pub Rbx: u64,
pub Rcx: u64,
pub Rdx: u64,
pub R8: u64,
pub Rsi: u64,
pub Rdi: u64,
pub Reserved0: u64,
pub XmmRegisters: [WHV_UINT128; 6],
pub Reserved1: [u64; 2],
}
impl WHV_HYPERCALL_CONTEXT {}
impl ::core::default::Default for WHV_HYPERCALL_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_HYPERCALL_CONTEXT {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_HYPERCALL_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_HYPERCALL_CONTEXT {
type Abi = Self;
}
pub const WHV_HYPERCALL_CONTEXT_MAX_XMM_REGISTERS: u32 = 6u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_INTERNAL_ACTIVITY_REGISTER {
pub Anonymous: WHV_INTERNAL_ACTIVITY_REGISTER_0,
pub AsUINT64: u64,
}
impl WHV_INTERNAL_ACTIVITY_REGISTER {}
impl ::core::default::Default for WHV_INTERNAL_ACTIVITY_REGISTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_INTERNAL_ACTIVITY_REGISTER {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_INTERNAL_ACTIVITY_REGISTER {}
unsafe impl ::windows::core::Abi for WHV_INTERNAL_ACTIVITY_REGISTER {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_INTERNAL_ACTIVITY_REGISTER_0 {
pub _bitfield: u64,
}
impl WHV_INTERNAL_ACTIVITY_REGISTER_0 {}
impl ::core::default::Default for WHV_INTERNAL_ACTIVITY_REGISTER_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_INTERNAL_ACTIVITY_REGISTER_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_INTERNAL_ACTIVITY_REGISTER_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_INTERNAL_ACTIVITY_REGISTER_0 {}
unsafe impl ::windows::core::Abi for WHV_INTERNAL_ACTIVITY_REGISTER_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_INTERRUPT_CONTROL {
pub _bitfield: u64,
pub Destination: u32,
pub Vector: u32,
}
impl WHV_INTERRUPT_CONTROL {}
impl ::core::default::Default for WHV_INTERRUPT_CONTROL {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_INTERRUPT_CONTROL {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_INTERRUPT_CONTROL").field("_bitfield", &self._bitfield).field("Destination", &self.Destination).field("Vector", &self.Vector).finish()
}
}
impl ::core::cmp::PartialEq for WHV_INTERRUPT_CONTROL {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield && self.Destination == other.Destination && self.Vector == other.Vector
}
}
impl ::core::cmp::Eq for WHV_INTERRUPT_CONTROL {}
unsafe impl ::windows::core::Abi for WHV_INTERRUPT_CONTROL {
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 WHV_INTERRUPT_DESTINATION_MODE(pub i32);
pub const WHvX64InterruptDestinationModePhysical: WHV_INTERRUPT_DESTINATION_MODE = WHV_INTERRUPT_DESTINATION_MODE(0i32);
pub const WHvX64InterruptDestinationModeLogical: WHV_INTERRUPT_DESTINATION_MODE = WHV_INTERRUPT_DESTINATION_MODE(1i32);
impl ::core::convert::From<i32> for WHV_INTERRUPT_DESTINATION_MODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_INTERRUPT_DESTINATION_MODE {
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 WHV_INTERRUPT_TRIGGER_MODE(pub i32);
pub const WHvX64InterruptTriggerModeEdge: WHV_INTERRUPT_TRIGGER_MODE = WHV_INTERRUPT_TRIGGER_MODE(0i32);
pub const WHvX64InterruptTriggerModeLevel: WHV_INTERRUPT_TRIGGER_MODE = WHV_INTERRUPT_TRIGGER_MODE(1i32);
impl ::core::convert::From<i32> for WHV_INTERRUPT_TRIGGER_MODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_INTERRUPT_TRIGGER_MODE {
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 WHV_INTERRUPT_TYPE(pub i32);
pub const WHvX64InterruptTypeFixed: WHV_INTERRUPT_TYPE = WHV_INTERRUPT_TYPE(0i32);
pub const WHvX64InterruptTypeLowestPriority: WHV_INTERRUPT_TYPE = WHV_INTERRUPT_TYPE(1i32);
pub const WHvX64InterruptTypeNmi: WHV_INTERRUPT_TYPE = WHV_INTERRUPT_TYPE(4i32);
pub const WHvX64InterruptTypeInit: WHV_INTERRUPT_TYPE = WHV_INTERRUPT_TYPE(5i32);
pub const WHvX64InterruptTypeSipi: WHV_INTERRUPT_TYPE = WHV_INTERRUPT_TYPE(6i32);
pub const WHvX64InterruptTypeLocalInt1: WHV_INTERRUPT_TYPE = WHV_INTERRUPT_TYPE(9i32);
impl ::core::convert::From<i32> for WHV_INTERRUPT_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_INTERRUPT_TYPE {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct WHV_MAP_GPA_RANGE_FLAGS(pub u32);
pub const WHvMapGpaRangeFlagNone: WHV_MAP_GPA_RANGE_FLAGS = WHV_MAP_GPA_RANGE_FLAGS(0u32);
pub const WHvMapGpaRangeFlagRead: WHV_MAP_GPA_RANGE_FLAGS = WHV_MAP_GPA_RANGE_FLAGS(1u32);
pub const WHvMapGpaRangeFlagWrite: WHV_MAP_GPA_RANGE_FLAGS = WHV_MAP_GPA_RANGE_FLAGS(2u32);
pub const WHvMapGpaRangeFlagExecute: WHV_MAP_GPA_RANGE_FLAGS = WHV_MAP_GPA_RANGE_FLAGS(4u32);
pub const WHvMapGpaRangeFlagTrackDirtyPages: WHV_MAP_GPA_RANGE_FLAGS = WHV_MAP_GPA_RANGE_FLAGS(8u32);
impl ::core::convert::From<u32> for WHV_MAP_GPA_RANGE_FLAGS {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_MAP_GPA_RANGE_FLAGS {
type Abi = Self;
}
impl ::core::ops::BitOr for WHV_MAP_GPA_RANGE_FLAGS {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for WHV_MAP_GPA_RANGE_FLAGS {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for WHV_MAP_GPA_RANGE_FLAGS {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for WHV_MAP_GPA_RANGE_FLAGS {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for WHV_MAP_GPA_RANGE_FLAGS {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
pub const WHV_MAX_DEVICE_ID_SIZE_IN_CHARS: u32 = 200u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_MEMORY_ACCESS_CONTEXT {
pub InstructionByteCount: u8,
pub Reserved: [u8; 3],
pub InstructionBytes: [u8; 16],
pub AccessInfo: WHV_MEMORY_ACCESS_INFO,
pub Gpa: u64,
pub Gva: u64,
}
impl WHV_MEMORY_ACCESS_CONTEXT {}
impl ::core::default::Default for WHV_MEMORY_ACCESS_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_MEMORY_ACCESS_CONTEXT {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_MEMORY_ACCESS_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_MEMORY_ACCESS_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_MEMORY_ACCESS_INFO {
pub Anonymous: WHV_MEMORY_ACCESS_INFO_0,
pub AsUINT32: u32,
}
impl WHV_MEMORY_ACCESS_INFO {}
impl ::core::default::Default for WHV_MEMORY_ACCESS_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_MEMORY_ACCESS_INFO {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_MEMORY_ACCESS_INFO {}
unsafe impl ::windows::core::Abi for WHV_MEMORY_ACCESS_INFO {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_MEMORY_ACCESS_INFO_0 {
pub _bitfield: u32,
}
impl WHV_MEMORY_ACCESS_INFO_0 {}
impl ::core::default::Default for WHV_MEMORY_ACCESS_INFO_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_MEMORY_ACCESS_INFO_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_MEMORY_ACCESS_INFO_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_MEMORY_ACCESS_INFO_0 {}
unsafe impl ::windows::core::Abi for WHV_MEMORY_ACCESS_INFO_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 WHV_MEMORY_ACCESS_TYPE(pub i32);
pub const WHvMemoryAccessRead: WHV_MEMORY_ACCESS_TYPE = WHV_MEMORY_ACCESS_TYPE(0i32);
pub const WHvMemoryAccessWrite: WHV_MEMORY_ACCESS_TYPE = WHV_MEMORY_ACCESS_TYPE(1i32);
pub const WHvMemoryAccessExecute: WHV_MEMORY_ACCESS_TYPE = WHV_MEMORY_ACCESS_TYPE(2i32);
impl ::core::convert::From<i32> for WHV_MEMORY_ACCESS_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_MEMORY_ACCESS_TYPE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_MEMORY_RANGE_ENTRY {
pub GuestAddress: u64,
pub SizeInBytes: u64,
}
impl WHV_MEMORY_RANGE_ENTRY {}
impl ::core::default::Default for WHV_MEMORY_RANGE_ENTRY {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_MEMORY_RANGE_ENTRY {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_MEMORY_RANGE_ENTRY").field("GuestAddress", &self.GuestAddress).field("SizeInBytes", &self.SizeInBytes).finish()
}
}
impl ::core::cmp::PartialEq for WHV_MEMORY_RANGE_ENTRY {
fn eq(&self, other: &Self) -> bool {
self.GuestAddress == other.GuestAddress && self.SizeInBytes == other.SizeInBytes
}
}
impl ::core::cmp::Eq for WHV_MEMORY_RANGE_ENTRY {}
unsafe impl ::windows::core::Abi for WHV_MEMORY_RANGE_ENTRY {
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 WHV_MSR_ACTION(pub i32);
pub const WHvMsrActionArchitectureDefault: WHV_MSR_ACTION = WHV_MSR_ACTION(0i32);
pub const WHvMsrActionIgnoreWriteReadZero: WHV_MSR_ACTION = WHV_MSR_ACTION(1i32);
pub const WHvMsrActionExit: WHV_MSR_ACTION = WHV_MSR_ACTION(2i32);
impl ::core::convert::From<i32> for WHV_MSR_ACTION {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_MSR_ACTION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_MSR_ACTION_ENTRY {
pub Index: u32,
pub ReadAction: u8,
pub WriteAction: u8,
pub Reserved: u16,
}
impl WHV_MSR_ACTION_ENTRY {}
impl ::core::default::Default for WHV_MSR_ACTION_ENTRY {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_MSR_ACTION_ENTRY {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_MSR_ACTION_ENTRY").field("Index", &self.Index).field("ReadAction", &self.ReadAction).field("WriteAction", &self.WriteAction).field("Reserved", &self.Reserved).finish()
}
}
impl ::core::cmp::PartialEq for WHV_MSR_ACTION_ENTRY {
fn eq(&self, other: &Self) -> bool {
self.Index == other.Index && self.ReadAction == other.ReadAction && self.WriteAction == other.WriteAction && self.Reserved == other.Reserved
}
}
impl ::core::cmp::Eq for WHV_MSR_ACTION_ENTRY {}
unsafe impl ::windows::core::Abi for WHV_MSR_ACTION_ENTRY {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_NOTIFICATION_PORT_PARAMETERS {
pub NotificationPortType: WHV_NOTIFICATION_PORT_TYPE,
pub Reserved: u32,
pub Anonymous: WHV_NOTIFICATION_PORT_PARAMETERS_0,
}
impl WHV_NOTIFICATION_PORT_PARAMETERS {}
impl ::core::default::Default for WHV_NOTIFICATION_PORT_PARAMETERS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_NOTIFICATION_PORT_PARAMETERS {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_NOTIFICATION_PORT_PARAMETERS {}
unsafe impl ::windows::core::Abi for WHV_NOTIFICATION_PORT_PARAMETERS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_NOTIFICATION_PORT_PARAMETERS_0 {
pub Doorbell: WHV_DOORBELL_MATCH_DATA,
pub Event: WHV_NOTIFICATION_PORT_PARAMETERS_0_0,
}
impl WHV_NOTIFICATION_PORT_PARAMETERS_0 {}
impl ::core::default::Default for WHV_NOTIFICATION_PORT_PARAMETERS_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_NOTIFICATION_PORT_PARAMETERS_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_NOTIFICATION_PORT_PARAMETERS_0 {}
unsafe impl ::windows::core::Abi for WHV_NOTIFICATION_PORT_PARAMETERS_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_NOTIFICATION_PORT_PARAMETERS_0_0 {
pub ConnectionId: u32,
}
impl WHV_NOTIFICATION_PORT_PARAMETERS_0_0 {}
impl ::core::default::Default for WHV_NOTIFICATION_PORT_PARAMETERS_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_NOTIFICATION_PORT_PARAMETERS_0_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Event_e__Struct").field("ConnectionId", &self.ConnectionId).finish()
}
}
impl ::core::cmp::PartialEq for WHV_NOTIFICATION_PORT_PARAMETERS_0_0 {
fn eq(&self, other: &Self) -> bool {
self.ConnectionId == other.ConnectionId
}
}
impl ::core::cmp::Eq for WHV_NOTIFICATION_PORT_PARAMETERS_0_0 {}
unsafe impl ::windows::core::Abi for WHV_NOTIFICATION_PORT_PARAMETERS_0_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 WHV_NOTIFICATION_PORT_PROPERTY_CODE(pub i32);
pub const WHvNotificationPortPropertyPreferredTargetVp: WHV_NOTIFICATION_PORT_PROPERTY_CODE = WHV_NOTIFICATION_PORT_PROPERTY_CODE(1i32);
pub const WHvNotificationPortPropertyPreferredTargetDuration: WHV_NOTIFICATION_PORT_PROPERTY_CODE = WHV_NOTIFICATION_PORT_PROPERTY_CODE(5i32);
impl ::core::convert::From<i32> for WHV_NOTIFICATION_PORT_PROPERTY_CODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_NOTIFICATION_PORT_PROPERTY_CODE {
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 WHV_NOTIFICATION_PORT_TYPE(pub i32);
pub const WHvNotificationPortTypeEvent: WHV_NOTIFICATION_PORT_TYPE = WHV_NOTIFICATION_PORT_TYPE(2i32);
pub const WHvNotificationPortTypeDoorbell: WHV_NOTIFICATION_PORT_TYPE = WHV_NOTIFICATION_PORT_TYPE(4i32);
impl ::core::convert::From<i32> for WHV_NOTIFICATION_PORT_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_NOTIFICATION_PORT_TYPE {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct WHV_PARTITION_COUNTER_SET(pub i32);
pub const WHvPartitionCounterSetMemory: WHV_PARTITION_COUNTER_SET = WHV_PARTITION_COUNTER_SET(0i32);
impl ::core::convert::From<i32> for WHV_PARTITION_COUNTER_SET {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_PARTITION_COUNTER_SET {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq)]
#[repr(transparent)]
pub struct WHV_PARTITION_HANDLE(pub isize);
impl ::core::default::Default for WHV_PARTITION_HANDLE {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
unsafe impl ::windows::core::Handle for WHV_PARTITION_HANDLE {}
unsafe impl ::windows::core::Abi for WHV_PARTITION_HANDLE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PARTITION_MEMORY_COUNTERS {
pub Mapped4KPageCount: u64,
pub Mapped2MPageCount: u64,
pub Mapped1GPageCount: u64,
}
impl WHV_PARTITION_MEMORY_COUNTERS {}
impl ::core::default::Default for WHV_PARTITION_MEMORY_COUNTERS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_PARTITION_MEMORY_COUNTERS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_PARTITION_MEMORY_COUNTERS").field("Mapped4KPageCount", &self.Mapped4KPageCount).field("Mapped2MPageCount", &self.Mapped2MPageCount).field("Mapped1GPageCount", &self.Mapped1GPageCount).finish()
}
}
impl ::core::cmp::PartialEq for WHV_PARTITION_MEMORY_COUNTERS {
fn eq(&self, other: &Self) -> bool {
self.Mapped4KPageCount == other.Mapped4KPageCount && self.Mapped2MPageCount == other.Mapped2MPageCount && self.Mapped1GPageCount == other.Mapped1GPageCount
}
}
impl ::core::cmp::Eq for WHV_PARTITION_MEMORY_COUNTERS {}
unsafe impl ::windows::core::Abi for WHV_PARTITION_MEMORY_COUNTERS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union WHV_PARTITION_PROPERTY {
pub ExtendedVmExits: WHV_EXTENDED_VM_EXITS,
pub ProcessorFeatures: WHV_PROCESSOR_FEATURES,
pub SyntheticProcessorFeaturesBanks: WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS,
pub ProcessorXsaveFeatures: WHV_PROCESSOR_XSAVE_FEATURES,
pub ProcessorClFlushSize: u8,
pub ProcessorCount: u32,
pub CpuidExitList: [u32; 1],
pub CpuidResultList: [WHV_X64_CPUID_RESULT; 1],
pub CpuidResultList2: [WHV_X64_CPUID_RESULT2; 1],
pub MsrActionList: [WHV_MSR_ACTION_ENTRY; 1],
pub UnimplementedMsrAction: WHV_MSR_ACTION,
pub ExceptionExitBitmap: u64,
pub LocalApicEmulationMode: WHV_X64_LOCAL_APIC_EMULATION_MODE,
pub SeparateSecurityDomain: super::super::Foundation::BOOL,
pub NestedVirtualization: super::super::Foundation::BOOL,
pub X64MsrExitBitmap: WHV_X64_MSR_EXIT_BITMAP,
pub ProcessorClockFrequency: u64,
pub InterruptClockFrequency: u64,
pub ApicRemoteRead: super::super::Foundation::BOOL,
pub ProcessorFeaturesBanks: WHV_PROCESSOR_FEATURES_BANKS,
pub ReferenceTime: u64,
pub PrimaryNumaNode: u16,
pub CpuReserve: u32,
pub CpuCap: u32,
pub CpuWeight: u32,
pub CpuGroupId: u64,
pub ProcessorFrequencyCap: u32,
pub AllowDeviceAssignment: super::super::Foundation::BOOL,
pub ProcessorPerfmonFeatures: WHV_PROCESSOR_PERFMON_FEATURES,
pub DisableSmt: super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl WHV_PARTITION_PROPERTY {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for WHV_PARTITION_PROPERTY {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for WHV_PARTITION_PROPERTY {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for WHV_PARTITION_PROPERTY {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for WHV_PARTITION_PROPERTY {
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 WHV_PARTITION_PROPERTY_CODE(pub i32);
pub const WHvPartitionPropertyCodeExtendedVmExits: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(1i32);
pub const WHvPartitionPropertyCodeExceptionExitBitmap: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(2i32);
pub const WHvPartitionPropertyCodeSeparateSecurityDomain: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(3i32);
pub const WHvPartitionPropertyCodeNestedVirtualization: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4i32);
pub const WHvPartitionPropertyCodeX64MsrExitBitmap: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(5i32);
pub const WHvPartitionPropertyCodePrimaryNumaNode: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(6i32);
pub const WHvPartitionPropertyCodeCpuReserve: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(7i32);
pub const WHvPartitionPropertyCodeCpuCap: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(8i32);
pub const WHvPartitionPropertyCodeCpuWeight: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(9i32);
pub const WHvPartitionPropertyCodeCpuGroupId: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(10i32);
pub const WHvPartitionPropertyCodeProcessorFrequencyCap: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(11i32);
pub const WHvPartitionPropertyCodeAllowDeviceAssignment: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(12i32);
pub const WHvPartitionPropertyCodeDisableSmt: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(13i32);
pub const WHvPartitionPropertyCodeProcessorFeatures: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4097i32);
pub const WHvPartitionPropertyCodeProcessorClFlushSize: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4098i32);
pub const WHvPartitionPropertyCodeCpuidExitList: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4099i32);
pub const WHvPartitionPropertyCodeCpuidResultList: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4100i32);
pub const WHvPartitionPropertyCodeLocalApicEmulationMode: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4101i32);
pub const WHvPartitionPropertyCodeProcessorXsaveFeatures: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4102i32);
pub const WHvPartitionPropertyCodeProcessorClockFrequency: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4103i32);
pub const WHvPartitionPropertyCodeInterruptClockFrequency: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4104i32);
pub const WHvPartitionPropertyCodeApicRemoteReadSupport: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4105i32);
pub const WHvPartitionPropertyCodeProcessorFeaturesBanks: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4106i32);
pub const WHvPartitionPropertyCodeReferenceTime: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4107i32);
pub const WHvPartitionPropertyCodeSyntheticProcessorFeaturesBanks: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4108i32);
pub const WHvPartitionPropertyCodeCpuidResultList2: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4109i32);
pub const WHvPartitionPropertyCodeProcessorPerfmonFeatures: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4110i32);
pub const WHvPartitionPropertyCodeMsrActionList: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4111i32);
pub const WHvPartitionPropertyCodeUnimplementedMsrAction: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(4112i32);
pub const WHvPartitionPropertyCodeProcessorCount: WHV_PARTITION_PROPERTY_CODE = WHV_PARTITION_PROPERTY_CODE(8191i32);
impl ::core::convert::From<i32> for WHV_PARTITION_PROPERTY_CODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_PARTITION_PROPERTY_CODE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PROCESSOR_APIC_COUNTERS {
pub MmioAccessCount: u64,
pub EoiAccessCount: u64,
pub TprAccessCount: u64,
pub SentIpiCount: u64,
pub SelfIpiCount: u64,
}
impl WHV_PROCESSOR_APIC_COUNTERS {}
impl ::core::default::Default for WHV_PROCESSOR_APIC_COUNTERS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_PROCESSOR_APIC_COUNTERS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_PROCESSOR_APIC_COUNTERS").field("MmioAccessCount", &self.MmioAccessCount).field("EoiAccessCount", &self.EoiAccessCount).field("TprAccessCount", &self.TprAccessCount).field("SentIpiCount", &self.SentIpiCount).field("SelfIpiCount", &self.SelfIpiCount).finish()
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_APIC_COUNTERS {
fn eq(&self, other: &Self) -> bool {
self.MmioAccessCount == other.MmioAccessCount && self.EoiAccessCount == other.EoiAccessCount && self.TprAccessCount == other.TprAccessCount && self.SentIpiCount == other.SentIpiCount && self.SelfIpiCount == other.SelfIpiCount
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_APIC_COUNTERS {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_APIC_COUNTERS {
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 WHV_PROCESSOR_COUNTER_SET(pub i32);
pub const WHvProcessorCounterSetRuntime: WHV_PROCESSOR_COUNTER_SET = WHV_PROCESSOR_COUNTER_SET(0i32);
pub const WHvProcessorCounterSetIntercepts: WHV_PROCESSOR_COUNTER_SET = WHV_PROCESSOR_COUNTER_SET(1i32);
pub const WHvProcessorCounterSetEvents: WHV_PROCESSOR_COUNTER_SET = WHV_PROCESSOR_COUNTER_SET(2i32);
pub const WHvProcessorCounterSetApic: WHV_PROCESSOR_COUNTER_SET = WHV_PROCESSOR_COUNTER_SET(3i32);
pub const WHvProcessorCounterSetSyntheticFeatures: WHV_PROCESSOR_COUNTER_SET = WHV_PROCESSOR_COUNTER_SET(4i32);
impl ::core::convert::From<i32> for WHV_PROCESSOR_COUNTER_SET {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_COUNTER_SET {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PROCESSOR_EVENT_COUNTERS {
pub PageFaultCount: u64,
pub ExceptionCount: u64,
pub InterruptCount: u64,
}
impl WHV_PROCESSOR_EVENT_COUNTERS {}
impl ::core::default::Default for WHV_PROCESSOR_EVENT_COUNTERS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_PROCESSOR_EVENT_COUNTERS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_PROCESSOR_EVENT_COUNTERS").field("PageFaultCount", &self.PageFaultCount).field("ExceptionCount", &self.ExceptionCount).field("InterruptCount", &self.InterruptCount).finish()
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_EVENT_COUNTERS {
fn eq(&self, other: &Self) -> bool {
self.PageFaultCount == other.PageFaultCount && self.ExceptionCount == other.ExceptionCount && self.InterruptCount == other.InterruptCount
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_EVENT_COUNTERS {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_EVENT_COUNTERS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_PROCESSOR_FEATURES {
pub Anonymous: WHV_PROCESSOR_FEATURES_0,
pub AsUINT64: u64,
}
impl WHV_PROCESSOR_FEATURES {}
impl ::core::default::Default for WHV_PROCESSOR_FEATURES {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_FEATURES {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_FEATURES {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_FEATURES {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PROCESSOR_FEATURES_0 {
pub _bitfield: u64,
}
impl WHV_PROCESSOR_FEATURES_0 {}
impl ::core::default::Default for WHV_PROCESSOR_FEATURES_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_PROCESSOR_FEATURES_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_FEATURES_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_FEATURES_0 {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_FEATURES_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_PROCESSOR_FEATURES1 {
pub Anonymous: WHV_PROCESSOR_FEATURES1_0,
pub AsUINT64: u64,
}
impl WHV_PROCESSOR_FEATURES1 {}
impl ::core::default::Default for WHV_PROCESSOR_FEATURES1 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_FEATURES1 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_FEATURES1 {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_FEATURES1 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PROCESSOR_FEATURES1_0 {
pub _bitfield: u64,
}
impl WHV_PROCESSOR_FEATURES1_0 {}
impl ::core::default::Default for WHV_PROCESSOR_FEATURES1_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_PROCESSOR_FEATURES1_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_FEATURES1_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_FEATURES1_0 {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_FEATURES1_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PROCESSOR_FEATURES_BANKS {
pub BanksCount: u32,
pub Reserved0: u32,
pub Anonymous: WHV_PROCESSOR_FEATURES_BANKS_0,
}
impl WHV_PROCESSOR_FEATURES_BANKS {}
impl ::core::default::Default for WHV_PROCESSOR_FEATURES_BANKS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_FEATURES_BANKS {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_FEATURES_BANKS {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_FEATURES_BANKS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_PROCESSOR_FEATURES_BANKS_0 {
pub Anonymous: WHV_PROCESSOR_FEATURES_BANKS_0_0,
pub AsUINT64: [u64; 2],
}
impl WHV_PROCESSOR_FEATURES_BANKS_0 {}
impl ::core::default::Default for WHV_PROCESSOR_FEATURES_BANKS_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_FEATURES_BANKS_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_FEATURES_BANKS_0 {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_FEATURES_BANKS_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PROCESSOR_FEATURES_BANKS_0_0 {
pub Bank0: WHV_PROCESSOR_FEATURES,
pub Bank1: WHV_PROCESSOR_FEATURES1,
}
impl WHV_PROCESSOR_FEATURES_BANKS_0_0 {}
impl ::core::default::Default for WHV_PROCESSOR_FEATURES_BANKS_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_FEATURES_BANKS_0_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_FEATURES_BANKS_0_0 {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_FEATURES_BANKS_0_0 {
type Abi = Self;
}
pub const WHV_PROCESSOR_FEATURES_BANKS_COUNT: u32 = 2u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PROCESSOR_INTERCEPT_COUNTER {
pub Count: u64,
pub Time100ns: u64,
}
impl WHV_PROCESSOR_INTERCEPT_COUNTER {}
impl ::core::default::Default for WHV_PROCESSOR_INTERCEPT_COUNTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_PROCESSOR_INTERCEPT_COUNTER {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_PROCESSOR_INTERCEPT_COUNTER").field("Count", &self.Count).field("Time100ns", &self.Time100ns).finish()
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_INTERCEPT_COUNTER {
fn eq(&self, other: &Self) -> bool {
self.Count == other.Count && self.Time100ns == other.Time100ns
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_INTERCEPT_COUNTER {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_INTERCEPT_COUNTER {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PROCESSOR_INTERCEPT_COUNTERS {
pub PageInvalidations: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub ControlRegisterAccesses: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub IoInstructions: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub HaltInstructions: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub CpuidInstructions: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub MsrAccesses: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub OtherIntercepts: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub PendingInterrupts: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub EmulatedInstructions: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub DebugRegisterAccesses: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub PageFaultIntercepts: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub NestedPageFaultIntercepts: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub Hypercalls: WHV_PROCESSOR_INTERCEPT_COUNTER,
pub RdpmcInstructions: WHV_PROCESSOR_INTERCEPT_COUNTER,
}
impl WHV_PROCESSOR_INTERCEPT_COUNTERS {}
impl ::core::default::Default for WHV_PROCESSOR_INTERCEPT_COUNTERS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_PROCESSOR_INTERCEPT_COUNTERS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_PROCESSOR_INTERCEPT_COUNTERS")
.field("PageInvalidations", &self.PageInvalidations)
.field("ControlRegisterAccesses", &self.ControlRegisterAccesses)
.field("IoInstructions", &self.IoInstructions)
.field("HaltInstructions", &self.HaltInstructions)
.field("CpuidInstructions", &self.CpuidInstructions)
.field("MsrAccesses", &self.MsrAccesses)
.field("OtherIntercepts", &self.OtherIntercepts)
.field("PendingInterrupts", &self.PendingInterrupts)
.field("EmulatedInstructions", &self.EmulatedInstructions)
.field("DebugRegisterAccesses", &self.DebugRegisterAccesses)
.field("PageFaultIntercepts", &self.PageFaultIntercepts)
.field("NestedPageFaultIntercepts", &self.NestedPageFaultIntercepts)
.field("Hypercalls", &self.Hypercalls)
.field("RdpmcInstructions", &self.RdpmcInstructions)
.finish()
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_INTERCEPT_COUNTERS {
fn eq(&self, other: &Self) -> bool {
self.PageInvalidations == other.PageInvalidations
&& self.ControlRegisterAccesses == other.ControlRegisterAccesses
&& self.IoInstructions == other.IoInstructions
&& self.HaltInstructions == other.HaltInstructions
&& self.CpuidInstructions == other.CpuidInstructions
&& self.MsrAccesses == other.MsrAccesses
&& self.OtherIntercepts == other.OtherIntercepts
&& self.PendingInterrupts == other.PendingInterrupts
&& self.EmulatedInstructions == other.EmulatedInstructions
&& self.DebugRegisterAccesses == other.DebugRegisterAccesses
&& self.PageFaultIntercepts == other.PageFaultIntercepts
&& self.NestedPageFaultIntercepts == other.NestedPageFaultIntercepts
&& self.Hypercalls == other.Hypercalls
&& self.RdpmcInstructions == other.RdpmcInstructions
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_INTERCEPT_COUNTERS {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_INTERCEPT_COUNTERS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_PROCESSOR_PERFMON_FEATURES {
pub Anonymous: WHV_PROCESSOR_PERFMON_FEATURES_0,
pub AsUINT64: u64,
}
impl WHV_PROCESSOR_PERFMON_FEATURES {}
impl ::core::default::Default for WHV_PROCESSOR_PERFMON_FEATURES {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_PERFMON_FEATURES {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_PERFMON_FEATURES {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_PERFMON_FEATURES {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PROCESSOR_PERFMON_FEATURES_0 {
pub _bitfield: u64,
}
impl WHV_PROCESSOR_PERFMON_FEATURES_0 {}
impl ::core::default::Default for WHV_PROCESSOR_PERFMON_FEATURES_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_PROCESSOR_PERFMON_FEATURES_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_PERFMON_FEATURES_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_PERFMON_FEATURES_0 {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_PERFMON_FEATURES_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PROCESSOR_RUNTIME_COUNTERS {
pub TotalRuntime100ns: u64,
pub HypervisorRuntime100ns: u64,
}
impl WHV_PROCESSOR_RUNTIME_COUNTERS {}
impl ::core::default::Default for WHV_PROCESSOR_RUNTIME_COUNTERS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_PROCESSOR_RUNTIME_COUNTERS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_PROCESSOR_RUNTIME_COUNTERS").field("TotalRuntime100ns", &self.TotalRuntime100ns).field("HypervisorRuntime100ns", &self.HypervisorRuntime100ns).finish()
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_RUNTIME_COUNTERS {
fn eq(&self, other: &Self) -> bool {
self.TotalRuntime100ns == other.TotalRuntime100ns && self.HypervisorRuntime100ns == other.HypervisorRuntime100ns
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_RUNTIME_COUNTERS {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_RUNTIME_COUNTERS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PROCESSOR_SYNTHETIC_FEATURES_COUNTERS {
pub SyntheticInterruptsCount: u64,
pub LongSpinWaitHypercallsCount: u64,
pub OtherHypercallsCount: u64,
pub SyntheticInterruptHypercallsCount: u64,
pub VirtualInterruptHypercallsCount: u64,
pub VirtualMmuHypercallsCount: u64,
}
impl WHV_PROCESSOR_SYNTHETIC_FEATURES_COUNTERS {}
impl ::core::default::Default for WHV_PROCESSOR_SYNTHETIC_FEATURES_COUNTERS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_PROCESSOR_SYNTHETIC_FEATURES_COUNTERS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_PROCESSOR_SYNTHETIC_FEATURES_COUNTERS")
.field("SyntheticInterruptsCount", &self.SyntheticInterruptsCount)
.field("LongSpinWaitHypercallsCount", &self.LongSpinWaitHypercallsCount)
.field("OtherHypercallsCount", &self.OtherHypercallsCount)
.field("SyntheticInterruptHypercallsCount", &self.SyntheticInterruptHypercallsCount)
.field("VirtualInterruptHypercallsCount", &self.VirtualInterruptHypercallsCount)
.field("VirtualMmuHypercallsCount", &self.VirtualMmuHypercallsCount)
.finish()
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_SYNTHETIC_FEATURES_COUNTERS {
fn eq(&self, other: &Self) -> bool {
self.SyntheticInterruptsCount == other.SyntheticInterruptsCount && self.LongSpinWaitHypercallsCount == other.LongSpinWaitHypercallsCount && self.OtherHypercallsCount == other.OtherHypercallsCount && self.SyntheticInterruptHypercallsCount == other.SyntheticInterruptHypercallsCount && self.VirtualInterruptHypercallsCount == other.VirtualInterruptHypercallsCount && self.VirtualMmuHypercallsCount == other.VirtualMmuHypercallsCount
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_SYNTHETIC_FEATURES_COUNTERS {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_SYNTHETIC_FEATURES_COUNTERS {
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 WHV_PROCESSOR_VENDOR(pub i32);
pub const WHvProcessorVendorAmd: WHV_PROCESSOR_VENDOR = WHV_PROCESSOR_VENDOR(0i32);
pub const WHvProcessorVendorIntel: WHV_PROCESSOR_VENDOR = WHV_PROCESSOR_VENDOR(1i32);
pub const WHvProcessorVendorHygon: WHV_PROCESSOR_VENDOR = WHV_PROCESSOR_VENDOR(2i32);
impl ::core::convert::From<i32> for WHV_PROCESSOR_VENDOR {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_VENDOR {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_PROCESSOR_XSAVE_FEATURES {
pub Anonymous: WHV_PROCESSOR_XSAVE_FEATURES_0,
pub AsUINT64: u64,
}
impl WHV_PROCESSOR_XSAVE_FEATURES {}
impl ::core::default::Default for WHV_PROCESSOR_XSAVE_FEATURES {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_XSAVE_FEATURES {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_XSAVE_FEATURES {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_XSAVE_FEATURES {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_PROCESSOR_XSAVE_FEATURES_0 {
pub _bitfield: u64,
}
impl WHV_PROCESSOR_XSAVE_FEATURES_0 {}
impl ::core::default::Default for WHV_PROCESSOR_XSAVE_FEATURES_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_PROCESSOR_XSAVE_FEATURES_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_PROCESSOR_XSAVE_FEATURES_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_PROCESSOR_XSAVE_FEATURES_0 {}
unsafe impl ::windows::core::Abi for WHV_PROCESSOR_XSAVE_FEATURES_0 {
type Abi = Self;
}
pub const WHV_READ_WRITE_GPA_RANGE_MAX_SIZE: u32 = 16u32;
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct WHV_REGISTER_NAME(pub i32);
pub const WHvX64RegisterRax: WHV_REGISTER_NAME = WHV_REGISTER_NAME(0i32);
pub const WHvX64RegisterRcx: WHV_REGISTER_NAME = WHV_REGISTER_NAME(1i32);
pub const WHvX64RegisterRdx: WHV_REGISTER_NAME = WHV_REGISTER_NAME(2i32);
pub const WHvX64RegisterRbx: WHV_REGISTER_NAME = WHV_REGISTER_NAME(3i32);
pub const WHvX64RegisterRsp: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4i32);
pub const WHvX64RegisterRbp: WHV_REGISTER_NAME = WHV_REGISTER_NAME(5i32);
pub const WHvX64RegisterRsi: WHV_REGISTER_NAME = WHV_REGISTER_NAME(6i32);
pub const WHvX64RegisterRdi: WHV_REGISTER_NAME = WHV_REGISTER_NAME(7i32);
pub const WHvX64RegisterR8: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8i32);
pub const WHvX64RegisterR9: WHV_REGISTER_NAME = WHV_REGISTER_NAME(9i32);
pub const WHvX64RegisterR10: WHV_REGISTER_NAME = WHV_REGISTER_NAME(10i32);
pub const WHvX64RegisterR11: WHV_REGISTER_NAME = WHV_REGISTER_NAME(11i32);
pub const WHvX64RegisterR12: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12i32);
pub const WHvX64RegisterR13: WHV_REGISTER_NAME = WHV_REGISTER_NAME(13i32);
pub const WHvX64RegisterR14: WHV_REGISTER_NAME = WHV_REGISTER_NAME(14i32);
pub const WHvX64RegisterR15: WHV_REGISTER_NAME = WHV_REGISTER_NAME(15i32);
pub const WHvX64RegisterRip: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16i32);
pub const WHvX64RegisterRflags: WHV_REGISTER_NAME = WHV_REGISTER_NAME(17i32);
pub const WHvX64RegisterEs: WHV_REGISTER_NAME = WHV_REGISTER_NAME(18i32);
pub const WHvX64RegisterCs: WHV_REGISTER_NAME = WHV_REGISTER_NAME(19i32);
pub const WHvX64RegisterSs: WHV_REGISTER_NAME = WHV_REGISTER_NAME(20i32);
pub const WHvX64RegisterDs: WHV_REGISTER_NAME = WHV_REGISTER_NAME(21i32);
pub const WHvX64RegisterFs: WHV_REGISTER_NAME = WHV_REGISTER_NAME(22i32);
pub const WHvX64RegisterGs: WHV_REGISTER_NAME = WHV_REGISTER_NAME(23i32);
pub const WHvX64RegisterLdtr: WHV_REGISTER_NAME = WHV_REGISTER_NAME(24i32);
pub const WHvX64RegisterTr: WHV_REGISTER_NAME = WHV_REGISTER_NAME(25i32);
pub const WHvX64RegisterIdtr: WHV_REGISTER_NAME = WHV_REGISTER_NAME(26i32);
pub const WHvX64RegisterGdtr: WHV_REGISTER_NAME = WHV_REGISTER_NAME(27i32);
pub const WHvX64RegisterCr0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(28i32);
pub const WHvX64RegisterCr2: WHV_REGISTER_NAME = WHV_REGISTER_NAME(29i32);
pub const WHvX64RegisterCr3: WHV_REGISTER_NAME = WHV_REGISTER_NAME(30i32);
pub const WHvX64RegisterCr4: WHV_REGISTER_NAME = WHV_REGISTER_NAME(31i32);
pub const WHvX64RegisterCr8: WHV_REGISTER_NAME = WHV_REGISTER_NAME(32i32);
pub const WHvX64RegisterDr0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(33i32);
pub const WHvX64RegisterDr1: WHV_REGISTER_NAME = WHV_REGISTER_NAME(34i32);
pub const WHvX64RegisterDr2: WHV_REGISTER_NAME = WHV_REGISTER_NAME(35i32);
pub const WHvX64RegisterDr3: WHV_REGISTER_NAME = WHV_REGISTER_NAME(36i32);
pub const WHvX64RegisterDr6: WHV_REGISTER_NAME = WHV_REGISTER_NAME(37i32);
pub const WHvX64RegisterDr7: WHV_REGISTER_NAME = WHV_REGISTER_NAME(38i32);
pub const WHvX64RegisterXCr0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(39i32);
pub const WHvX64RegisterVirtualCr0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(40i32);
pub const WHvX64RegisterVirtualCr3: WHV_REGISTER_NAME = WHV_REGISTER_NAME(41i32);
pub const WHvX64RegisterVirtualCr4: WHV_REGISTER_NAME = WHV_REGISTER_NAME(42i32);
pub const WHvX64RegisterVirtualCr8: WHV_REGISTER_NAME = WHV_REGISTER_NAME(43i32);
pub const WHvX64RegisterXmm0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4096i32);
pub const WHvX64RegisterXmm1: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4097i32);
pub const WHvX64RegisterXmm2: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4098i32);
pub const WHvX64RegisterXmm3: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4099i32);
pub const WHvX64RegisterXmm4: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4100i32);
pub const WHvX64RegisterXmm5: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4101i32);
pub const WHvX64RegisterXmm6: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4102i32);
pub const WHvX64RegisterXmm7: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4103i32);
pub const WHvX64RegisterXmm8: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4104i32);
pub const WHvX64RegisterXmm9: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4105i32);
pub const WHvX64RegisterXmm10: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4106i32);
pub const WHvX64RegisterXmm11: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4107i32);
pub const WHvX64RegisterXmm12: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4108i32);
pub const WHvX64RegisterXmm13: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4109i32);
pub const WHvX64RegisterXmm14: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4110i32);
pub const WHvX64RegisterXmm15: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4111i32);
pub const WHvX64RegisterFpMmx0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4112i32);
pub const WHvX64RegisterFpMmx1: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4113i32);
pub const WHvX64RegisterFpMmx2: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4114i32);
pub const WHvX64RegisterFpMmx3: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4115i32);
pub const WHvX64RegisterFpMmx4: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4116i32);
pub const WHvX64RegisterFpMmx5: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4117i32);
pub const WHvX64RegisterFpMmx6: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4118i32);
pub const WHvX64RegisterFpMmx7: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4119i32);
pub const WHvX64RegisterFpControlStatus: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4120i32);
pub const WHvX64RegisterXmmControlStatus: WHV_REGISTER_NAME = WHV_REGISTER_NAME(4121i32);
pub const WHvX64RegisterTsc: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8192i32);
pub const WHvX64RegisterEfer: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8193i32);
pub const WHvX64RegisterKernelGsBase: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8194i32);
pub const WHvX64RegisterApicBase: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8195i32);
pub const WHvX64RegisterPat: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8196i32);
pub const WHvX64RegisterSysenterCs: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8197i32);
pub const WHvX64RegisterSysenterEip: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8198i32);
pub const WHvX64RegisterSysenterEsp: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8199i32);
pub const WHvX64RegisterStar: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8200i32);
pub const WHvX64RegisterLstar: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8201i32);
pub const WHvX64RegisterCstar: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8202i32);
pub const WHvX64RegisterSfmask: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8203i32);
pub const WHvX64RegisterInitialApicId: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8204i32);
pub const WHvX64RegisterMsrMtrrCap: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8205i32);
pub const WHvX64RegisterMsrMtrrDefType: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8206i32);
pub const WHvX64RegisterMsrMtrrPhysBase0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8208i32);
pub const WHvX64RegisterMsrMtrrPhysBase1: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8209i32);
pub const WHvX64RegisterMsrMtrrPhysBase2: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8210i32);
pub const WHvX64RegisterMsrMtrrPhysBase3: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8211i32);
pub const WHvX64RegisterMsrMtrrPhysBase4: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8212i32);
pub const WHvX64RegisterMsrMtrrPhysBase5: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8213i32);
pub const WHvX64RegisterMsrMtrrPhysBase6: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8214i32);
pub const WHvX64RegisterMsrMtrrPhysBase7: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8215i32);
pub const WHvX64RegisterMsrMtrrPhysBase8: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8216i32);
pub const WHvX64RegisterMsrMtrrPhysBase9: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8217i32);
pub const WHvX64RegisterMsrMtrrPhysBaseA: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8218i32);
pub const WHvX64RegisterMsrMtrrPhysBaseB: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8219i32);
pub const WHvX64RegisterMsrMtrrPhysBaseC: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8220i32);
pub const WHvX64RegisterMsrMtrrPhysBaseD: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8221i32);
pub const WHvX64RegisterMsrMtrrPhysBaseE: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8222i32);
pub const WHvX64RegisterMsrMtrrPhysBaseF: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8223i32);
pub const WHvX64RegisterMsrMtrrPhysMask0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8256i32);
pub const WHvX64RegisterMsrMtrrPhysMask1: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8257i32);
pub const WHvX64RegisterMsrMtrrPhysMask2: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8258i32);
pub const WHvX64RegisterMsrMtrrPhysMask3: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8259i32);
pub const WHvX64RegisterMsrMtrrPhysMask4: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8260i32);
pub const WHvX64RegisterMsrMtrrPhysMask5: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8261i32);
pub const WHvX64RegisterMsrMtrrPhysMask6: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8262i32);
pub const WHvX64RegisterMsrMtrrPhysMask7: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8263i32);
pub const WHvX64RegisterMsrMtrrPhysMask8: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8264i32);
pub const WHvX64RegisterMsrMtrrPhysMask9: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8265i32);
pub const WHvX64RegisterMsrMtrrPhysMaskA: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8266i32);
pub const WHvX64RegisterMsrMtrrPhysMaskB: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8267i32);
pub const WHvX64RegisterMsrMtrrPhysMaskC: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8268i32);
pub const WHvX64RegisterMsrMtrrPhysMaskD: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8269i32);
pub const WHvX64RegisterMsrMtrrPhysMaskE: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8270i32);
pub const WHvX64RegisterMsrMtrrPhysMaskF: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8271i32);
pub const WHvX64RegisterMsrMtrrFix64k00000: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8304i32);
pub const WHvX64RegisterMsrMtrrFix16k80000: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8305i32);
pub const WHvX64RegisterMsrMtrrFix16kA0000: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8306i32);
pub const WHvX64RegisterMsrMtrrFix4kC0000: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8307i32);
pub const WHvX64RegisterMsrMtrrFix4kC8000: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8308i32);
pub const WHvX64RegisterMsrMtrrFix4kD0000: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8309i32);
pub const WHvX64RegisterMsrMtrrFix4kD8000: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8310i32);
pub const WHvX64RegisterMsrMtrrFix4kE0000: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8311i32);
pub const WHvX64RegisterMsrMtrrFix4kE8000: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8312i32);
pub const WHvX64RegisterMsrMtrrFix4kF0000: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8313i32);
pub const WHvX64RegisterMsrMtrrFix4kF8000: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8314i32);
pub const WHvX64RegisterTscAux: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8315i32);
pub const WHvX64RegisterBndcfgs: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8316i32);
pub const WHvX64RegisterMCount: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8318i32);
pub const WHvX64RegisterACount: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8319i32);
pub const WHvX64RegisterSpecCtrl: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8324i32);
pub const WHvX64RegisterPredCmd: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8325i32);
pub const WHvX64RegisterTscVirtualOffset: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8327i32);
pub const WHvX64RegisterTsxCtrl: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8328i32);
pub const WHvX64RegisterXss: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8331i32);
pub const WHvX64RegisterUCet: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8332i32);
pub const WHvX64RegisterSCet: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8333i32);
pub const WHvX64RegisterSsp: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8334i32);
pub const WHvX64RegisterPl0Ssp: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8335i32);
pub const WHvX64RegisterPl1Ssp: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8336i32);
pub const WHvX64RegisterPl2Ssp: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8337i32);
pub const WHvX64RegisterPl3Ssp: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8338i32);
pub const WHvX64RegisterInterruptSspTableAddr: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8339i32);
pub const WHvX64RegisterTscDeadline: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8341i32);
pub const WHvX64RegisterTscAdjust: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8342i32);
pub const WHvX64RegisterUmwaitControl: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8344i32);
pub const WHvX64RegisterXfd: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8345i32);
pub const WHvX64RegisterXfdErr: WHV_REGISTER_NAME = WHV_REGISTER_NAME(8346i32);
pub const WHvX64RegisterApicId: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12290i32);
pub const WHvX64RegisterApicVersion: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12291i32);
pub const WHvX64RegisterApicTpr: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12296i32);
pub const WHvX64RegisterApicPpr: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12298i32);
pub const WHvX64RegisterApicEoi: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12299i32);
pub const WHvX64RegisterApicLdr: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12301i32);
pub const WHvX64RegisterApicSpurious: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12303i32);
pub const WHvX64RegisterApicIsr0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12304i32);
pub const WHvX64RegisterApicIsr1: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12305i32);
pub const WHvX64RegisterApicIsr2: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12306i32);
pub const WHvX64RegisterApicIsr3: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12307i32);
pub const WHvX64RegisterApicIsr4: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12308i32);
pub const WHvX64RegisterApicIsr5: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12309i32);
pub const WHvX64RegisterApicIsr6: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12310i32);
pub const WHvX64RegisterApicIsr7: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12311i32);
pub const WHvX64RegisterApicTmr0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12312i32);
pub const WHvX64RegisterApicTmr1: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12313i32);
pub const WHvX64RegisterApicTmr2: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12314i32);
pub const WHvX64RegisterApicTmr3: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12315i32);
pub const WHvX64RegisterApicTmr4: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12316i32);
pub const WHvX64RegisterApicTmr5: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12317i32);
pub const WHvX64RegisterApicTmr6: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12318i32);
pub const WHvX64RegisterApicTmr7: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12319i32);
pub const WHvX64RegisterApicIrr0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12320i32);
pub const WHvX64RegisterApicIrr1: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12321i32);
pub const WHvX64RegisterApicIrr2: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12322i32);
pub const WHvX64RegisterApicIrr3: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12323i32);
pub const WHvX64RegisterApicIrr4: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12324i32);
pub const WHvX64RegisterApicIrr5: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12325i32);
pub const WHvX64RegisterApicIrr6: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12326i32);
pub const WHvX64RegisterApicIrr7: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12327i32);
pub const WHvX64RegisterApicEse: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12328i32);
pub const WHvX64RegisterApicIcr: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12336i32);
pub const WHvX64RegisterApicLvtTimer: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12338i32);
pub const WHvX64RegisterApicLvtThermal: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12339i32);
pub const WHvX64RegisterApicLvtPerfmon: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12340i32);
pub const WHvX64RegisterApicLvtLint0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12341i32);
pub const WHvX64RegisterApicLvtLint1: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12342i32);
pub const WHvX64RegisterApicLvtError: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12343i32);
pub const WHvX64RegisterApicInitCount: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12344i32);
pub const WHvX64RegisterApicCurrentCount: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12345i32);
pub const WHvX64RegisterApicDivide: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12350i32);
pub const WHvX64RegisterApicSelfIpi: WHV_REGISTER_NAME = WHV_REGISTER_NAME(12351i32);
pub const WHvRegisterSint0: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16384i32);
pub const WHvRegisterSint1: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16385i32);
pub const WHvRegisterSint2: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16386i32);
pub const WHvRegisterSint3: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16387i32);
pub const WHvRegisterSint4: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16388i32);
pub const WHvRegisterSint5: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16389i32);
pub const WHvRegisterSint6: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16390i32);
pub const WHvRegisterSint7: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16391i32);
pub const WHvRegisterSint8: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16392i32);
pub const WHvRegisterSint9: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16393i32);
pub const WHvRegisterSint10: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16394i32);
pub const WHvRegisterSint11: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16395i32);
pub const WHvRegisterSint12: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16396i32);
pub const WHvRegisterSint13: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16397i32);
pub const WHvRegisterSint14: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16398i32);
pub const WHvRegisterSint15: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16399i32);
pub const WHvRegisterScontrol: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16400i32);
pub const WHvRegisterSversion: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16401i32);
pub const WHvRegisterSiefp: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16402i32);
pub const WHvRegisterSimp: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16403i32);
pub const WHvRegisterEom: WHV_REGISTER_NAME = WHV_REGISTER_NAME(16404i32);
pub const WHvRegisterVpRuntime: WHV_REGISTER_NAME = WHV_REGISTER_NAME(20480i32);
pub const WHvX64RegisterHypercall: WHV_REGISTER_NAME = WHV_REGISTER_NAME(20481i32);
pub const WHvRegisterGuestOsId: WHV_REGISTER_NAME = WHV_REGISTER_NAME(20482i32);
pub const WHvRegisterVpAssistPage: WHV_REGISTER_NAME = WHV_REGISTER_NAME(20499i32);
pub const WHvRegisterReferenceTsc: WHV_REGISTER_NAME = WHV_REGISTER_NAME(20503i32);
pub const WHvRegisterReferenceTscSequence: WHV_REGISTER_NAME = WHV_REGISTER_NAME(20506i32);
pub const WHvRegisterPendingInterruption: WHV_REGISTER_NAME = WHV_REGISTER_NAME(-2147483648i32);
pub const WHvRegisterInterruptState: WHV_REGISTER_NAME = WHV_REGISTER_NAME(-2147483647i32);
pub const WHvRegisterPendingEvent: WHV_REGISTER_NAME = WHV_REGISTER_NAME(-2147483646i32);
pub const WHvX64RegisterDeliverabilityNotifications: WHV_REGISTER_NAME = WHV_REGISTER_NAME(-2147483644i32);
pub const WHvRegisterInternalActivityState: WHV_REGISTER_NAME = WHV_REGISTER_NAME(-2147483643i32);
pub const WHvX64RegisterPendingDebugException: WHV_REGISTER_NAME = WHV_REGISTER_NAME(-2147483642i32);
impl ::core::convert::From<i32> for WHV_REGISTER_NAME {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_REGISTER_NAME {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_REGISTER_VALUE {
pub Reg128: WHV_UINT128,
pub Reg64: u64,
pub Reg32: u32,
pub Reg16: u16,
pub Reg8: u8,
pub Fp: WHV_X64_FP_REGISTER,
pub FpControlStatus: WHV_X64_FP_CONTROL_STATUS_REGISTER,
pub XmmControlStatus: WHV_X64_XMM_CONTROL_STATUS_REGISTER,
pub Segment: WHV_X64_SEGMENT_REGISTER,
pub Table: WHV_X64_TABLE_REGISTER,
pub InterruptState: WHV_X64_INTERRUPT_STATE_REGISTER,
pub PendingInterruption: WHV_X64_PENDING_INTERRUPTION_REGISTER,
pub DeliverabilityNotifications: WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER,
pub ExceptionEvent: WHV_X64_PENDING_EXCEPTION_EVENT,
pub ExtIntEvent: WHV_X64_PENDING_EXT_INT_EVENT,
pub InternalActivity: WHV_INTERNAL_ACTIVITY_REGISTER,
pub PendingDebugException: WHV_X64_PENDING_DEBUG_EXCEPTION,
}
impl WHV_REGISTER_VALUE {}
impl ::core::default::Default for WHV_REGISTER_VALUE {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_REGISTER_VALUE {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_REGISTER_VALUE {}
unsafe impl ::windows::core::Abi for WHV_REGISTER_VALUE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_RUN_VP_CANCELED_CONTEXT {
pub CancelReason: WHV_RUN_VP_CANCEL_REASON,
}
impl WHV_RUN_VP_CANCELED_CONTEXT {}
impl ::core::default::Default for WHV_RUN_VP_CANCELED_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_RUN_VP_CANCELED_CONTEXT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_RUN_VP_CANCELED_CONTEXT").field("CancelReason", &self.CancelReason).finish()
}
}
impl ::core::cmp::PartialEq for WHV_RUN_VP_CANCELED_CONTEXT {
fn eq(&self, other: &Self) -> bool {
self.CancelReason == other.CancelReason
}
}
impl ::core::cmp::Eq for WHV_RUN_VP_CANCELED_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_RUN_VP_CANCELED_CONTEXT {
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 WHV_RUN_VP_CANCEL_REASON(pub i32);
pub const WHvRunVpCancelReasonUser: WHV_RUN_VP_CANCEL_REASON = WHV_RUN_VP_CANCEL_REASON(0i32);
impl ::core::convert::From<i32> for WHV_RUN_VP_CANCEL_REASON {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_RUN_VP_CANCEL_REASON {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_RUN_VP_EXIT_CONTEXT {
pub ExitReason: WHV_RUN_VP_EXIT_REASON,
pub Reserved: u32,
pub VpContext: WHV_VP_EXIT_CONTEXT,
pub Anonymous: WHV_RUN_VP_EXIT_CONTEXT_0,
}
impl WHV_RUN_VP_EXIT_CONTEXT {}
impl ::core::default::Default for WHV_RUN_VP_EXIT_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_RUN_VP_EXIT_CONTEXT {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_RUN_VP_EXIT_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_RUN_VP_EXIT_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_RUN_VP_EXIT_CONTEXT_0 {
pub MemoryAccess: WHV_MEMORY_ACCESS_CONTEXT,
pub IoPortAccess: WHV_X64_IO_PORT_ACCESS_CONTEXT,
pub MsrAccess: WHV_X64_MSR_ACCESS_CONTEXT,
pub CpuidAccess: WHV_X64_CPUID_ACCESS_CONTEXT,
pub VpException: WHV_VP_EXCEPTION_CONTEXT,
pub InterruptWindow: WHV_X64_INTERRUPTION_DELIVERABLE_CONTEXT,
pub UnsupportedFeature: WHV_X64_UNSUPPORTED_FEATURE_CONTEXT,
pub CancelReason: WHV_RUN_VP_CANCELED_CONTEXT,
pub ApicEoi: WHV_X64_APIC_EOI_CONTEXT,
pub ReadTsc: WHV_X64_RDTSC_CONTEXT,
pub ApicSmi: WHV_X64_APIC_SMI_CONTEXT,
pub Hypercall: WHV_HYPERCALL_CONTEXT,
pub ApicInitSipi: WHV_X64_APIC_INIT_SIPI_CONTEXT,
pub ApicWrite: WHV_X64_APIC_WRITE_CONTEXT,
pub SynicSintDeliverable: WHV_SYNIC_SINT_DELIVERABLE_CONTEXT,
}
impl WHV_RUN_VP_EXIT_CONTEXT_0 {}
impl ::core::default::Default for WHV_RUN_VP_EXIT_CONTEXT_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_RUN_VP_EXIT_CONTEXT_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_RUN_VP_EXIT_CONTEXT_0 {}
unsafe impl ::windows::core::Abi for WHV_RUN_VP_EXIT_CONTEXT_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 WHV_RUN_VP_EXIT_REASON(pub i32);
pub const WHvRunVpExitReasonNone: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(0i32);
pub const WHvRunVpExitReasonMemoryAccess: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(1i32);
pub const WHvRunVpExitReasonX64IoPortAccess: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(2i32);
pub const WHvRunVpExitReasonUnrecoverableException: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(4i32);
pub const WHvRunVpExitReasonInvalidVpRegisterValue: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(5i32);
pub const WHvRunVpExitReasonUnsupportedFeature: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(6i32);
pub const WHvRunVpExitReasonX64InterruptWindow: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(7i32);
pub const WHvRunVpExitReasonX64Halt: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(8i32);
pub const WHvRunVpExitReasonX64ApicEoi: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(9i32);
pub const WHvRunVpExitReasonSynicSintDeliverable: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(10i32);
pub const WHvRunVpExitReasonX64MsrAccess: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(4096i32);
pub const WHvRunVpExitReasonX64Cpuid: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(4097i32);
pub const WHvRunVpExitReasonException: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(4098i32);
pub const WHvRunVpExitReasonX64Rdtsc: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(4099i32);
pub const WHvRunVpExitReasonX64ApicSmiTrap: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(4100i32);
pub const WHvRunVpExitReasonHypercall: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(4101i32);
pub const WHvRunVpExitReasonX64ApicInitSipiTrap: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(4102i32);
pub const WHvRunVpExitReasonX64ApicWriteTrap: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(4103i32);
pub const WHvRunVpExitReasonCanceled: WHV_RUN_VP_EXIT_REASON = WHV_RUN_VP_EXIT_REASON(8193i32);
impl ::core::convert::From<i32> for WHV_RUN_VP_EXIT_REASON {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_RUN_VP_EXIT_REASON {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_SCHEDULER_FEATURES {
pub Anonymous: WHV_SCHEDULER_FEATURES_0,
pub AsUINT64: u64,
}
impl WHV_SCHEDULER_FEATURES {}
impl ::core::default::Default for WHV_SCHEDULER_FEATURES {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_SCHEDULER_FEATURES {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_SCHEDULER_FEATURES {}
unsafe impl ::windows::core::Abi for WHV_SCHEDULER_FEATURES {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_SCHEDULER_FEATURES_0 {
pub _bitfield: u64,
}
impl WHV_SCHEDULER_FEATURES_0 {}
impl ::core::default::Default for WHV_SCHEDULER_FEATURES_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_SCHEDULER_FEATURES_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_SCHEDULER_FEATURES_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_SCHEDULER_FEATURES_0 {}
unsafe impl ::windows::core::Abi for WHV_SCHEDULER_FEATURES_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct WHV_SRIOV_RESOURCE_DESCRIPTOR {
pub PnpInstanceId: [u16; 200],
pub VirtualFunctionId: super::super::Foundation::LUID,
pub VirtualFunctionIndex: u16,
pub Reserved: u16,
}
#[cfg(feature = "Win32_Foundation")]
impl WHV_SRIOV_RESOURCE_DESCRIPTOR {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for WHV_SRIOV_RESOURCE_DESCRIPTOR {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for WHV_SRIOV_RESOURCE_DESCRIPTOR {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_SRIOV_RESOURCE_DESCRIPTOR").field("PnpInstanceId", &self.PnpInstanceId).field("VirtualFunctionId", &self.VirtualFunctionId).field("VirtualFunctionIndex", &self.VirtualFunctionIndex).field("Reserved", &self.Reserved).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for WHV_SRIOV_RESOURCE_DESCRIPTOR {
fn eq(&self, other: &Self) -> bool {
self.PnpInstanceId == other.PnpInstanceId && self.VirtualFunctionId == other.VirtualFunctionId && self.VirtualFunctionIndex == other.VirtualFunctionIndex && self.Reserved == other.Reserved
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for WHV_SRIOV_RESOURCE_DESCRIPTOR {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for WHV_SRIOV_RESOURCE_DESCRIPTOR {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_SYNIC_EVENT_PARAMETERS {
pub VpIndex: u32,
pub TargetSint: u8,
pub Reserved: u8,
pub FlagNumber: u16,
}
impl WHV_SYNIC_EVENT_PARAMETERS {}
impl ::core::default::Default for WHV_SYNIC_EVENT_PARAMETERS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_SYNIC_EVENT_PARAMETERS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_SYNIC_EVENT_PARAMETERS").field("VpIndex", &self.VpIndex).field("TargetSint", &self.TargetSint).field("Reserved", &self.Reserved).field("FlagNumber", &self.FlagNumber).finish()
}
}
impl ::core::cmp::PartialEq for WHV_SYNIC_EVENT_PARAMETERS {
fn eq(&self, other: &Self) -> bool {
self.VpIndex == other.VpIndex && self.TargetSint == other.TargetSint && self.Reserved == other.Reserved && self.FlagNumber == other.FlagNumber
}
}
impl ::core::cmp::Eq for WHV_SYNIC_EVENT_PARAMETERS {}
unsafe impl ::windows::core::Abi for WHV_SYNIC_EVENT_PARAMETERS {
type Abi = Self;
}
pub const WHV_SYNIC_MESSAGE_SIZE: u32 = 256u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_SYNIC_SINT_DELIVERABLE_CONTEXT {
pub DeliverableSints: u16,
pub Reserved1: u16,
pub Reserved2: u32,
}
impl WHV_SYNIC_SINT_DELIVERABLE_CONTEXT {}
impl ::core::default::Default for WHV_SYNIC_SINT_DELIVERABLE_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_SYNIC_SINT_DELIVERABLE_CONTEXT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_SYNIC_SINT_DELIVERABLE_CONTEXT").field("DeliverableSints", &self.DeliverableSints).field("Reserved1", &self.Reserved1).field("Reserved2", &self.Reserved2).finish()
}
}
impl ::core::cmp::PartialEq for WHV_SYNIC_SINT_DELIVERABLE_CONTEXT {
fn eq(&self, other: &Self) -> bool {
self.DeliverableSints == other.DeliverableSints && self.Reserved1 == other.Reserved1 && self.Reserved2 == other.Reserved2
}
}
impl ::core::cmp::Eq for WHV_SYNIC_SINT_DELIVERABLE_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_SYNIC_SINT_DELIVERABLE_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_SYNTHETIC_PROCESSOR_FEATURES {
pub Anonymous: WHV_SYNTHETIC_PROCESSOR_FEATURES_0,
pub AsUINT64: u64,
}
impl WHV_SYNTHETIC_PROCESSOR_FEATURES {}
impl ::core::default::Default for WHV_SYNTHETIC_PROCESSOR_FEATURES {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_SYNTHETIC_PROCESSOR_FEATURES {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_SYNTHETIC_PROCESSOR_FEATURES {}
unsafe impl ::windows::core::Abi for WHV_SYNTHETIC_PROCESSOR_FEATURES {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_SYNTHETIC_PROCESSOR_FEATURES_0 {
pub _bitfield: u64,
}
impl WHV_SYNTHETIC_PROCESSOR_FEATURES_0 {}
impl ::core::default::Default for WHV_SYNTHETIC_PROCESSOR_FEATURES_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_SYNTHETIC_PROCESSOR_FEATURES_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_SYNTHETIC_PROCESSOR_FEATURES_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_SYNTHETIC_PROCESSOR_FEATURES_0 {}
unsafe impl ::windows::core::Abi for WHV_SYNTHETIC_PROCESSOR_FEATURES_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS {
pub BanksCount: u32,
pub Reserved0: u32,
pub Anonymous: WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0,
}
impl WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS {}
impl ::core::default::Default for WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS {}
unsafe impl ::windows::core::Abi for WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0 {
pub Anonymous: WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0_0,
pub AsUINT64: [u64; 1],
}
impl WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0 {}
impl ::core::default::Default for WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0 {}
unsafe impl ::windows::core::Abi for WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0_0 {
pub Bank0: WHV_SYNTHETIC_PROCESSOR_FEATURES,
}
impl WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0_0 {}
impl ::core::default::Default for WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0_0 {}
unsafe impl ::windows::core::Abi for WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_0_0 {
type Abi = Self;
}
pub const WHV_SYNTHETIC_PROCESSOR_FEATURES_BANKS_COUNT: 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 WHV_TRANSLATE_GVA_FLAGS(pub u32);
pub const WHvTranslateGvaFlagNone: WHV_TRANSLATE_GVA_FLAGS = WHV_TRANSLATE_GVA_FLAGS(0u32);
pub const WHvTranslateGvaFlagValidateRead: WHV_TRANSLATE_GVA_FLAGS = WHV_TRANSLATE_GVA_FLAGS(1u32);
pub const WHvTranslateGvaFlagValidateWrite: WHV_TRANSLATE_GVA_FLAGS = WHV_TRANSLATE_GVA_FLAGS(2u32);
pub const WHvTranslateGvaFlagValidateExecute: WHV_TRANSLATE_GVA_FLAGS = WHV_TRANSLATE_GVA_FLAGS(4u32);
pub const WHvTranslateGvaFlagPrivilegeExempt: WHV_TRANSLATE_GVA_FLAGS = WHV_TRANSLATE_GVA_FLAGS(8u32);
pub const WHvTranslateGvaFlagSetPageTableBits: WHV_TRANSLATE_GVA_FLAGS = WHV_TRANSLATE_GVA_FLAGS(16u32);
pub const WHvTranslateGvaFlagEnforceSmap: WHV_TRANSLATE_GVA_FLAGS = WHV_TRANSLATE_GVA_FLAGS(256u32);
pub const WHvTranslateGvaFlagOverrideSmap: WHV_TRANSLATE_GVA_FLAGS = WHV_TRANSLATE_GVA_FLAGS(512u32);
impl ::core::convert::From<u32> for WHV_TRANSLATE_GVA_FLAGS {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_TRANSLATE_GVA_FLAGS {
type Abi = Self;
}
impl ::core::ops::BitOr for WHV_TRANSLATE_GVA_FLAGS {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for WHV_TRANSLATE_GVA_FLAGS {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for WHV_TRANSLATE_GVA_FLAGS {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for WHV_TRANSLATE_GVA_FLAGS {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for WHV_TRANSLATE_GVA_FLAGS {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_TRANSLATE_GVA_RESULT {
pub ResultCode: WHV_TRANSLATE_GVA_RESULT_CODE,
pub Reserved: u32,
}
impl WHV_TRANSLATE_GVA_RESULT {}
impl ::core::default::Default for WHV_TRANSLATE_GVA_RESULT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_TRANSLATE_GVA_RESULT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_TRANSLATE_GVA_RESULT").field("ResultCode", &self.ResultCode).field("Reserved", &self.Reserved).finish()
}
}
impl ::core::cmp::PartialEq for WHV_TRANSLATE_GVA_RESULT {
fn eq(&self, other: &Self) -> bool {
self.ResultCode == other.ResultCode && self.Reserved == other.Reserved
}
}
impl ::core::cmp::Eq for WHV_TRANSLATE_GVA_RESULT {}
unsafe impl ::windows::core::Abi for WHV_TRANSLATE_GVA_RESULT {
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 WHV_TRANSLATE_GVA_RESULT_CODE(pub i32);
pub const WHvTranslateGvaResultSuccess: WHV_TRANSLATE_GVA_RESULT_CODE = WHV_TRANSLATE_GVA_RESULT_CODE(0i32);
pub const WHvTranslateGvaResultPageNotPresent: WHV_TRANSLATE_GVA_RESULT_CODE = WHV_TRANSLATE_GVA_RESULT_CODE(1i32);
pub const WHvTranslateGvaResultPrivilegeViolation: WHV_TRANSLATE_GVA_RESULT_CODE = WHV_TRANSLATE_GVA_RESULT_CODE(2i32);
pub const WHvTranslateGvaResultInvalidPageTableFlags: WHV_TRANSLATE_GVA_RESULT_CODE = WHV_TRANSLATE_GVA_RESULT_CODE(3i32);
pub const WHvTranslateGvaResultGpaUnmapped: WHV_TRANSLATE_GVA_RESULT_CODE = WHV_TRANSLATE_GVA_RESULT_CODE(4i32);
pub const WHvTranslateGvaResultGpaNoReadAccess: WHV_TRANSLATE_GVA_RESULT_CODE = WHV_TRANSLATE_GVA_RESULT_CODE(5i32);
pub const WHvTranslateGvaResultGpaNoWriteAccess: WHV_TRANSLATE_GVA_RESULT_CODE = WHV_TRANSLATE_GVA_RESULT_CODE(6i32);
pub const WHvTranslateGvaResultGpaIllegalOverlayAccess: WHV_TRANSLATE_GVA_RESULT_CODE = WHV_TRANSLATE_GVA_RESULT_CODE(7i32);
pub const WHvTranslateGvaResultIntercept: WHV_TRANSLATE_GVA_RESULT_CODE = WHV_TRANSLATE_GVA_RESULT_CODE(8i32);
impl ::core::convert::From<i32> for WHV_TRANSLATE_GVA_RESULT_CODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_TRANSLATE_GVA_RESULT_CODE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_TRIGGER_PARAMETERS {
pub TriggerType: WHV_TRIGGER_TYPE,
pub Reserved: u32,
pub Anonymous: WHV_TRIGGER_PARAMETERS_0,
}
impl WHV_TRIGGER_PARAMETERS {}
impl ::core::default::Default for WHV_TRIGGER_PARAMETERS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_TRIGGER_PARAMETERS {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_TRIGGER_PARAMETERS {}
unsafe impl ::windows::core::Abi for WHV_TRIGGER_PARAMETERS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_TRIGGER_PARAMETERS_0 {
pub Interrupt: WHV_INTERRUPT_CONTROL,
pub SynicEvent: WHV_SYNIC_EVENT_PARAMETERS,
pub DeviceInterrupt: WHV_TRIGGER_PARAMETERS_0_0,
}
impl WHV_TRIGGER_PARAMETERS_0 {}
impl ::core::default::Default for WHV_TRIGGER_PARAMETERS_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_TRIGGER_PARAMETERS_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_TRIGGER_PARAMETERS_0 {}
unsafe impl ::windows::core::Abi for WHV_TRIGGER_PARAMETERS_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_TRIGGER_PARAMETERS_0_0 {
pub LogicalDeviceId: u64,
pub MsiAddress: u64,
pub MsiData: u32,
pub Reserved: u32,
}
impl WHV_TRIGGER_PARAMETERS_0_0 {}
impl ::core::default::Default for WHV_TRIGGER_PARAMETERS_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_TRIGGER_PARAMETERS_0_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_DeviceInterrupt_e__Struct").field("LogicalDeviceId", &self.LogicalDeviceId).field("MsiAddress", &self.MsiAddress).field("MsiData", &self.MsiData).field("Reserved", &self.Reserved).finish()
}
}
impl ::core::cmp::PartialEq for WHV_TRIGGER_PARAMETERS_0_0 {
fn eq(&self, other: &Self) -> bool {
self.LogicalDeviceId == other.LogicalDeviceId && self.MsiAddress == other.MsiAddress && self.MsiData == other.MsiData && self.Reserved == other.Reserved
}
}
impl ::core::cmp::Eq for WHV_TRIGGER_PARAMETERS_0_0 {}
unsafe impl ::windows::core::Abi for WHV_TRIGGER_PARAMETERS_0_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 WHV_TRIGGER_TYPE(pub i32);
pub const WHvTriggerTypeInterrupt: WHV_TRIGGER_TYPE = WHV_TRIGGER_TYPE(0i32);
pub const WHvTriggerTypeSynicEvent: WHV_TRIGGER_TYPE = WHV_TRIGGER_TYPE(1i32);
pub const WHvTriggerTypeDeviceInterrupt: WHV_TRIGGER_TYPE = WHV_TRIGGER_TYPE(2i32);
impl ::core::convert::From<i32> for WHV_TRIGGER_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_TRIGGER_TYPE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_UINT128 {
pub Anonymous: WHV_UINT128_0,
pub Dword: [u32; 4],
}
impl WHV_UINT128 {}
impl ::core::default::Default for WHV_UINT128 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_UINT128 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_UINT128 {}
unsafe impl ::windows::core::Abi for WHV_UINT128 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_UINT128_0 {
pub Low64: u64,
pub High64: u64,
}
impl WHV_UINT128_0 {}
impl ::core::default::Default for WHV_UINT128_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_UINT128_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("Low64", &self.Low64).field("High64", &self.High64).finish()
}
}
impl ::core::cmp::PartialEq for WHV_UINT128_0 {
fn eq(&self, other: &Self) -> bool {
self.Low64 == other.Low64 && self.High64 == other.High64
}
}
impl ::core::cmp::Eq for WHV_UINT128_0 {}
unsafe impl ::windows::core::Abi for WHV_UINT128_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_VIRTUAL_PROCESSOR_PROPERTY {
pub PropertyCode: WHV_VIRTUAL_PROCESSOR_PROPERTY_CODE,
pub Reserved: u32,
pub Anonymous: WHV_VIRTUAL_PROCESSOR_PROPERTY_0,
}
impl WHV_VIRTUAL_PROCESSOR_PROPERTY {}
impl ::core::default::Default for WHV_VIRTUAL_PROCESSOR_PROPERTY {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_VIRTUAL_PROCESSOR_PROPERTY {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_VIRTUAL_PROCESSOR_PROPERTY {}
unsafe impl ::windows::core::Abi for WHV_VIRTUAL_PROCESSOR_PROPERTY {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_VIRTUAL_PROCESSOR_PROPERTY_0 {
pub NumaNode: u16,
pub Padding: u64,
}
impl WHV_VIRTUAL_PROCESSOR_PROPERTY_0 {}
impl ::core::default::Default for WHV_VIRTUAL_PROCESSOR_PROPERTY_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_VIRTUAL_PROCESSOR_PROPERTY_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_VIRTUAL_PROCESSOR_PROPERTY_0 {}
unsafe impl ::windows::core::Abi for WHV_VIRTUAL_PROCESSOR_PROPERTY_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 WHV_VIRTUAL_PROCESSOR_PROPERTY_CODE(pub i32);
pub const WHvVirtualProcessorPropertyCodeNumaNode: WHV_VIRTUAL_PROCESSOR_PROPERTY_CODE = WHV_VIRTUAL_PROCESSOR_PROPERTY_CODE(0i32);
impl ::core::convert::From<i32> for WHV_VIRTUAL_PROCESSOR_PROPERTY_CODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_VIRTUAL_PROCESSOR_PROPERTY_CODE {
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 WHV_VIRTUAL_PROCESSOR_STATE_TYPE(pub i32);
pub const WHvVirtualProcessorStateTypeSynicMessagePage: WHV_VIRTUAL_PROCESSOR_STATE_TYPE = WHV_VIRTUAL_PROCESSOR_STATE_TYPE(0i32);
pub const WHvVirtualProcessorStateTypeSynicEventFlagPage: WHV_VIRTUAL_PROCESSOR_STATE_TYPE = WHV_VIRTUAL_PROCESSOR_STATE_TYPE(1i32);
pub const WHvVirtualProcessorStateTypeSynicTimerState: WHV_VIRTUAL_PROCESSOR_STATE_TYPE = WHV_VIRTUAL_PROCESSOR_STATE_TYPE(2i32);
pub const WHvVirtualProcessorStateTypeInterruptControllerState2: WHV_VIRTUAL_PROCESSOR_STATE_TYPE = WHV_VIRTUAL_PROCESSOR_STATE_TYPE(4096i32);
pub const WHvVirtualProcessorStateTypeXsaveState: WHV_VIRTUAL_PROCESSOR_STATE_TYPE = WHV_VIRTUAL_PROCESSOR_STATE_TYPE(4097i32);
impl ::core::convert::From<i32> for WHV_VIRTUAL_PROCESSOR_STATE_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_VIRTUAL_PROCESSOR_STATE_TYPE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_VPCI_DEVICE_NOTIFICATION {
pub NotificationType: WHV_VPCI_DEVICE_NOTIFICATION_TYPE,
pub Reserved1: u32,
pub Anonymous: WHV_VPCI_DEVICE_NOTIFICATION_0,
}
impl WHV_VPCI_DEVICE_NOTIFICATION {}
impl ::core::default::Default for WHV_VPCI_DEVICE_NOTIFICATION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_VPCI_DEVICE_NOTIFICATION {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_VPCI_DEVICE_NOTIFICATION {}
unsafe impl ::windows::core::Abi for WHV_VPCI_DEVICE_NOTIFICATION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_VPCI_DEVICE_NOTIFICATION_0 {
pub Reserved2: u64,
}
impl WHV_VPCI_DEVICE_NOTIFICATION_0 {}
impl ::core::default::Default for WHV_VPCI_DEVICE_NOTIFICATION_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_VPCI_DEVICE_NOTIFICATION_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_VPCI_DEVICE_NOTIFICATION_0 {}
unsafe impl ::windows::core::Abi for WHV_VPCI_DEVICE_NOTIFICATION_0 {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct WHV_VPCI_DEVICE_NOTIFICATION_TYPE(pub i32);
pub const WHvVpciDeviceNotificationUndefined: WHV_VPCI_DEVICE_NOTIFICATION_TYPE = WHV_VPCI_DEVICE_NOTIFICATION_TYPE(0i32);
pub const WHvVpciDeviceNotificationMmioRemapping: WHV_VPCI_DEVICE_NOTIFICATION_TYPE = WHV_VPCI_DEVICE_NOTIFICATION_TYPE(1i32);
pub const WHvVpciDeviceNotificationSurpriseRemoval: WHV_VPCI_DEVICE_NOTIFICATION_TYPE = WHV_VPCI_DEVICE_NOTIFICATION_TYPE(2i32);
impl ::core::convert::From<i32> for WHV_VPCI_DEVICE_NOTIFICATION_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_VPCI_DEVICE_NOTIFICATION_TYPE {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct WHV_VPCI_DEVICE_PROPERTY_CODE(pub i32);
pub const WHvVpciDevicePropertyCodeUndefined: WHV_VPCI_DEVICE_PROPERTY_CODE = WHV_VPCI_DEVICE_PROPERTY_CODE(0i32);
pub const WHvVpciDevicePropertyCodeHardwareIDs: WHV_VPCI_DEVICE_PROPERTY_CODE = WHV_VPCI_DEVICE_PROPERTY_CODE(1i32);
pub const WHvVpciDevicePropertyCodeProbedBARs: WHV_VPCI_DEVICE_PROPERTY_CODE = WHV_VPCI_DEVICE_PROPERTY_CODE(2i32);
impl ::core::convert::From<i32> for WHV_VPCI_DEVICE_PROPERTY_CODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_VPCI_DEVICE_PROPERTY_CODE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_VPCI_DEVICE_REGISTER {
pub Location: WHV_VPCI_DEVICE_REGISTER_SPACE,
pub SizeInBytes: u32,
pub OffsetInBytes: u64,
}
impl WHV_VPCI_DEVICE_REGISTER {}
impl ::core::default::Default for WHV_VPCI_DEVICE_REGISTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_VPCI_DEVICE_REGISTER {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_VPCI_DEVICE_REGISTER").field("Location", &self.Location).field("SizeInBytes", &self.SizeInBytes).field("OffsetInBytes", &self.OffsetInBytes).finish()
}
}
impl ::core::cmp::PartialEq for WHV_VPCI_DEVICE_REGISTER {
fn eq(&self, other: &Self) -> bool {
self.Location == other.Location && self.SizeInBytes == other.SizeInBytes && self.OffsetInBytes == other.OffsetInBytes
}
}
impl ::core::cmp::Eq for WHV_VPCI_DEVICE_REGISTER {}
unsafe impl ::windows::core::Abi for WHV_VPCI_DEVICE_REGISTER {
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 WHV_VPCI_DEVICE_REGISTER_SPACE(pub i32);
pub const WHvVpciConfigSpace: WHV_VPCI_DEVICE_REGISTER_SPACE = WHV_VPCI_DEVICE_REGISTER_SPACE(-1i32);
pub const WHvVpciBar0: WHV_VPCI_DEVICE_REGISTER_SPACE = WHV_VPCI_DEVICE_REGISTER_SPACE(0i32);
pub const WHvVpciBar1: WHV_VPCI_DEVICE_REGISTER_SPACE = WHV_VPCI_DEVICE_REGISTER_SPACE(1i32);
pub const WHvVpciBar2: WHV_VPCI_DEVICE_REGISTER_SPACE = WHV_VPCI_DEVICE_REGISTER_SPACE(2i32);
pub const WHvVpciBar3: WHV_VPCI_DEVICE_REGISTER_SPACE = WHV_VPCI_DEVICE_REGISTER_SPACE(3i32);
pub const WHvVpciBar4: WHV_VPCI_DEVICE_REGISTER_SPACE = WHV_VPCI_DEVICE_REGISTER_SPACE(4i32);
pub const WHvVpciBar5: WHV_VPCI_DEVICE_REGISTER_SPACE = WHV_VPCI_DEVICE_REGISTER_SPACE(5i32);
impl ::core::convert::From<i32> for WHV_VPCI_DEVICE_REGISTER_SPACE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_VPCI_DEVICE_REGISTER_SPACE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_VPCI_HARDWARE_IDS {
pub VendorID: u16,
pub DeviceID: u16,
pub RevisionID: u8,
pub ProgIf: u8,
pub SubClass: u8,
pub BaseClass: u8,
pub SubVendorID: u16,
pub SubSystemID: u16,
}
impl WHV_VPCI_HARDWARE_IDS {}
impl ::core::default::Default for WHV_VPCI_HARDWARE_IDS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_VPCI_HARDWARE_IDS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_VPCI_HARDWARE_IDS")
.field("VendorID", &self.VendorID)
.field("DeviceID", &self.DeviceID)
.field("RevisionID", &self.RevisionID)
.field("ProgIf", &self.ProgIf)
.field("SubClass", &self.SubClass)
.field("BaseClass", &self.BaseClass)
.field("SubVendorID", &self.SubVendorID)
.field("SubSystemID", &self.SubSystemID)
.finish()
}
}
impl ::core::cmp::PartialEq for WHV_VPCI_HARDWARE_IDS {
fn eq(&self, other: &Self) -> bool {
self.VendorID == other.VendorID && self.DeviceID == other.DeviceID && self.RevisionID == other.RevisionID && self.ProgIf == other.ProgIf && self.SubClass == other.SubClass && self.BaseClass == other.BaseClass && self.SubVendorID == other.SubVendorID && self.SubSystemID == other.SubSystemID
}
}
impl ::core::cmp::Eq for WHV_VPCI_HARDWARE_IDS {}
unsafe impl ::windows::core::Abi for WHV_VPCI_HARDWARE_IDS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_VPCI_INTERRUPT_TARGET {
pub Vector: u32,
pub Flags: WHV_VPCI_INTERRUPT_TARGET_FLAGS,
pub ProcessorCount: u32,
pub Processors: [u32; 1],
}
impl WHV_VPCI_INTERRUPT_TARGET {}
impl ::core::default::Default for WHV_VPCI_INTERRUPT_TARGET {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_VPCI_INTERRUPT_TARGET {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_VPCI_INTERRUPT_TARGET").field("Vector", &self.Vector).field("Flags", &self.Flags).field("ProcessorCount", &self.ProcessorCount).field("Processors", &self.Processors).finish()
}
}
impl ::core::cmp::PartialEq for WHV_VPCI_INTERRUPT_TARGET {
fn eq(&self, other: &Self) -> bool {
self.Vector == other.Vector && self.Flags == other.Flags && self.ProcessorCount == other.ProcessorCount && self.Processors == other.Processors
}
}
impl ::core::cmp::Eq for WHV_VPCI_INTERRUPT_TARGET {}
unsafe impl ::windows::core::Abi for WHV_VPCI_INTERRUPT_TARGET {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct WHV_VPCI_INTERRUPT_TARGET_FLAGS(pub u32);
pub const WHvVpciInterruptTargetFlagNone: WHV_VPCI_INTERRUPT_TARGET_FLAGS = WHV_VPCI_INTERRUPT_TARGET_FLAGS(0u32);
pub const WHvVpciInterruptTargetFlagMulticast: WHV_VPCI_INTERRUPT_TARGET_FLAGS = WHV_VPCI_INTERRUPT_TARGET_FLAGS(1u32);
impl ::core::convert::From<u32> for WHV_VPCI_INTERRUPT_TARGET_FLAGS {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_VPCI_INTERRUPT_TARGET_FLAGS {
type Abi = Self;
}
impl ::core::ops::BitOr for WHV_VPCI_INTERRUPT_TARGET_FLAGS {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for WHV_VPCI_INTERRUPT_TARGET_FLAGS {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for WHV_VPCI_INTERRUPT_TARGET_FLAGS {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for WHV_VPCI_INTERRUPT_TARGET_FLAGS {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for WHV_VPCI_INTERRUPT_TARGET_FLAGS {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_VPCI_MMIO_MAPPING {
pub Location: WHV_VPCI_DEVICE_REGISTER_SPACE,
pub Flags: WHV_VPCI_MMIO_RANGE_FLAGS,
pub SizeInBytes: u64,
pub OffsetInBytes: u64,
pub VirtualAddress: *mut ::core::ffi::c_void,
}
impl WHV_VPCI_MMIO_MAPPING {}
impl ::core::default::Default for WHV_VPCI_MMIO_MAPPING {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_VPCI_MMIO_MAPPING {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_VPCI_MMIO_MAPPING").field("Location", &self.Location).field("Flags", &self.Flags).field("SizeInBytes", &self.SizeInBytes).field("OffsetInBytes", &self.OffsetInBytes).field("VirtualAddress", &self.VirtualAddress).finish()
}
}
impl ::core::cmp::PartialEq for WHV_VPCI_MMIO_MAPPING {
fn eq(&self, other: &Self) -> bool {
self.Location == other.Location && self.Flags == other.Flags && self.SizeInBytes == other.SizeInBytes && self.OffsetInBytes == other.OffsetInBytes && self.VirtualAddress == other.VirtualAddress
}
}
impl ::core::cmp::Eq for WHV_VPCI_MMIO_MAPPING {}
unsafe impl ::windows::core::Abi for WHV_VPCI_MMIO_MAPPING {
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 WHV_VPCI_MMIO_RANGE_FLAGS(pub u32);
pub const WHvVpciMmioRangeFlagReadAccess: WHV_VPCI_MMIO_RANGE_FLAGS = WHV_VPCI_MMIO_RANGE_FLAGS(1u32);
pub const WHvVpciMmioRangeFlagWriteAccess: WHV_VPCI_MMIO_RANGE_FLAGS = WHV_VPCI_MMIO_RANGE_FLAGS(2u32);
impl ::core::convert::From<u32> for WHV_VPCI_MMIO_RANGE_FLAGS {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_VPCI_MMIO_RANGE_FLAGS {
type Abi = Self;
}
impl ::core::ops::BitOr for WHV_VPCI_MMIO_RANGE_FLAGS {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for WHV_VPCI_MMIO_RANGE_FLAGS {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for WHV_VPCI_MMIO_RANGE_FLAGS {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for WHV_VPCI_MMIO_RANGE_FLAGS {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for WHV_VPCI_MMIO_RANGE_FLAGS {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_VPCI_PROBED_BARS {
pub Value: [u32; 6],
}
impl WHV_VPCI_PROBED_BARS {}
impl ::core::default::Default for WHV_VPCI_PROBED_BARS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_VPCI_PROBED_BARS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_VPCI_PROBED_BARS").field("Value", &self.Value).finish()
}
}
impl ::core::cmp::PartialEq for WHV_VPCI_PROBED_BARS {
fn eq(&self, other: &Self) -> bool {
self.Value == other.Value
}
}
impl ::core::cmp::Eq for WHV_VPCI_PROBED_BARS {}
unsafe impl ::windows::core::Abi for WHV_VPCI_PROBED_BARS {
type Abi = Self;
}
pub const WHV_VPCI_TYPE0_BAR_COUNT: u32 = 6u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_VP_EXCEPTION_CONTEXT {
pub InstructionByteCount: u8,
pub Reserved: [u8; 3],
pub InstructionBytes: [u8; 16],
pub ExceptionInfo: WHV_VP_EXCEPTION_INFO,
pub ExceptionType: u8,
pub Reserved2: [u8; 3],
pub ErrorCode: u32,
pub ExceptionParameter: u64,
}
impl WHV_VP_EXCEPTION_CONTEXT {}
impl ::core::default::Default for WHV_VP_EXCEPTION_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_VP_EXCEPTION_CONTEXT {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_VP_EXCEPTION_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_VP_EXCEPTION_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_VP_EXCEPTION_INFO {
pub Anonymous: WHV_VP_EXCEPTION_INFO_0,
pub AsUINT32: u32,
}
impl WHV_VP_EXCEPTION_INFO {}
impl ::core::default::Default for WHV_VP_EXCEPTION_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_VP_EXCEPTION_INFO {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_VP_EXCEPTION_INFO {}
unsafe impl ::windows::core::Abi for WHV_VP_EXCEPTION_INFO {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_VP_EXCEPTION_INFO_0 {
pub _bitfield: u32,
}
impl WHV_VP_EXCEPTION_INFO_0 {}
impl ::core::default::Default for WHV_VP_EXCEPTION_INFO_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_VP_EXCEPTION_INFO_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_VP_EXCEPTION_INFO_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_VP_EXCEPTION_INFO_0 {}
unsafe impl ::windows::core::Abi for WHV_VP_EXCEPTION_INFO_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_VP_EXIT_CONTEXT {
pub ExecutionState: WHV_X64_VP_EXECUTION_STATE,
pub _bitfield: u8,
pub Reserved: u8,
pub Reserved2: u32,
pub Cs: WHV_X64_SEGMENT_REGISTER,
pub Rip: u64,
pub Rflags: u64,
}
impl WHV_VP_EXIT_CONTEXT {}
impl ::core::default::Default for WHV_VP_EXIT_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_VP_EXIT_CONTEXT {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_VP_EXIT_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_VP_EXIT_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_APIC_EOI_CONTEXT {
pub InterruptVector: u32,
}
impl WHV_X64_APIC_EOI_CONTEXT {}
impl ::core::default::Default for WHV_X64_APIC_EOI_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_APIC_EOI_CONTEXT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_X64_APIC_EOI_CONTEXT").field("InterruptVector", &self.InterruptVector).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_APIC_EOI_CONTEXT {
fn eq(&self, other: &Self) -> bool {
self.InterruptVector == other.InterruptVector
}
}
impl ::core::cmp::Eq for WHV_X64_APIC_EOI_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_X64_APIC_EOI_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_APIC_INIT_SIPI_CONTEXT {
pub ApicIcr: u64,
}
impl WHV_X64_APIC_INIT_SIPI_CONTEXT {}
impl ::core::default::Default for WHV_X64_APIC_INIT_SIPI_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_APIC_INIT_SIPI_CONTEXT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_X64_APIC_INIT_SIPI_CONTEXT").field("ApicIcr", &self.ApicIcr).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_APIC_INIT_SIPI_CONTEXT {
fn eq(&self, other: &Self) -> bool {
self.ApicIcr == other.ApicIcr
}
}
impl ::core::cmp::Eq for WHV_X64_APIC_INIT_SIPI_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_X64_APIC_INIT_SIPI_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_APIC_SMI_CONTEXT {
pub ApicIcr: u64,
}
impl WHV_X64_APIC_SMI_CONTEXT {}
impl ::core::default::Default for WHV_X64_APIC_SMI_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_APIC_SMI_CONTEXT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_X64_APIC_SMI_CONTEXT").field("ApicIcr", &self.ApicIcr).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_APIC_SMI_CONTEXT {
fn eq(&self, other: &Self) -> bool {
self.ApicIcr == other.ApicIcr
}
}
impl ::core::cmp::Eq for WHV_X64_APIC_SMI_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_X64_APIC_SMI_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_APIC_WRITE_CONTEXT {
pub Type: WHV_X64_APIC_WRITE_TYPE,
pub Reserved: u32,
pub WriteValue: u64,
}
impl WHV_X64_APIC_WRITE_CONTEXT {}
impl ::core::default::Default for WHV_X64_APIC_WRITE_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_APIC_WRITE_CONTEXT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_X64_APIC_WRITE_CONTEXT").field("Type", &self.Type).field("Reserved", &self.Reserved).field("WriteValue", &self.WriteValue).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_APIC_WRITE_CONTEXT {
fn eq(&self, other: &Self) -> bool {
self.Type == other.Type && self.Reserved == other.Reserved && self.WriteValue == other.WriteValue
}
}
impl ::core::cmp::Eq for WHV_X64_APIC_WRITE_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_X64_APIC_WRITE_CONTEXT {
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 WHV_X64_APIC_WRITE_TYPE(pub i32);
pub const WHvX64ApicWriteTypeLdr: WHV_X64_APIC_WRITE_TYPE = WHV_X64_APIC_WRITE_TYPE(208i32);
pub const WHvX64ApicWriteTypeDfr: WHV_X64_APIC_WRITE_TYPE = WHV_X64_APIC_WRITE_TYPE(224i32);
pub const WHvX64ApicWriteTypeSvr: WHV_X64_APIC_WRITE_TYPE = WHV_X64_APIC_WRITE_TYPE(240i32);
pub const WHvX64ApicWriteTypeLint0: WHV_X64_APIC_WRITE_TYPE = WHV_X64_APIC_WRITE_TYPE(848i32);
pub const WHvX64ApicWriteTypeLint1: WHV_X64_APIC_WRITE_TYPE = WHV_X64_APIC_WRITE_TYPE(864i32);
impl ::core::convert::From<i32> for WHV_X64_APIC_WRITE_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_X64_APIC_WRITE_TYPE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_CPUID_ACCESS_CONTEXT {
pub Rax: u64,
pub Rcx: u64,
pub Rdx: u64,
pub Rbx: u64,
pub DefaultResultRax: u64,
pub DefaultResultRcx: u64,
pub DefaultResultRdx: u64,
pub DefaultResultRbx: u64,
}
impl WHV_X64_CPUID_ACCESS_CONTEXT {}
impl ::core::default::Default for WHV_X64_CPUID_ACCESS_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_CPUID_ACCESS_CONTEXT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_X64_CPUID_ACCESS_CONTEXT")
.field("Rax", &self.Rax)
.field("Rcx", &self.Rcx)
.field("Rdx", &self.Rdx)
.field("Rbx", &self.Rbx)
.field("DefaultResultRax", &self.DefaultResultRax)
.field("DefaultResultRcx", &self.DefaultResultRcx)
.field("DefaultResultRdx", &self.DefaultResultRdx)
.field("DefaultResultRbx", &self.DefaultResultRbx)
.finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_CPUID_ACCESS_CONTEXT {
fn eq(&self, other: &Self) -> bool {
self.Rax == other.Rax && self.Rcx == other.Rcx && self.Rdx == other.Rdx && self.Rbx == other.Rbx && self.DefaultResultRax == other.DefaultResultRax && self.DefaultResultRcx == other.DefaultResultRcx && self.DefaultResultRdx == other.DefaultResultRdx && self.DefaultResultRbx == other.DefaultResultRbx
}
}
impl ::core::cmp::Eq for WHV_X64_CPUID_ACCESS_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_X64_CPUID_ACCESS_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_CPUID_RESULT {
pub Function: u32,
pub Reserved: [u32; 3],
pub Eax: u32,
pub Ebx: u32,
pub Ecx: u32,
pub Edx: u32,
}
impl WHV_X64_CPUID_RESULT {}
impl ::core::default::Default for WHV_X64_CPUID_RESULT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_CPUID_RESULT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_X64_CPUID_RESULT").field("Function", &self.Function).field("Reserved", &self.Reserved).field("Eax", &self.Eax).field("Ebx", &self.Ebx).field("Ecx", &self.Ecx).field("Edx", &self.Edx).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_CPUID_RESULT {
fn eq(&self, other: &Self) -> bool {
self.Function == other.Function && self.Reserved == other.Reserved && self.Eax == other.Eax && self.Ebx == other.Ebx && self.Ecx == other.Ecx && self.Edx == other.Edx
}
}
impl ::core::cmp::Eq for WHV_X64_CPUID_RESULT {}
unsafe impl ::windows::core::Abi for WHV_X64_CPUID_RESULT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_CPUID_RESULT2 {
pub Function: u32,
pub Index: u32,
pub VpIndex: u32,
pub Flags: WHV_X64_CPUID_RESULT2_FLAGS,
pub Output: WHV_CPUID_OUTPUT,
pub Mask: WHV_CPUID_OUTPUT,
}
impl WHV_X64_CPUID_RESULT2 {}
impl ::core::default::Default for WHV_X64_CPUID_RESULT2 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_CPUID_RESULT2 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_X64_CPUID_RESULT2").field("Function", &self.Function).field("Index", &self.Index).field("VpIndex", &self.VpIndex).field("Flags", &self.Flags).field("Output", &self.Output).field("Mask", &self.Mask).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_CPUID_RESULT2 {
fn eq(&self, other: &Self) -> bool {
self.Function == other.Function && self.Index == other.Index && self.VpIndex == other.VpIndex && self.Flags == other.Flags && self.Output == other.Output && self.Mask == other.Mask
}
}
impl ::core::cmp::Eq for WHV_X64_CPUID_RESULT2 {}
unsafe impl ::windows::core::Abi for WHV_X64_CPUID_RESULT2 {
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 WHV_X64_CPUID_RESULT2_FLAGS(pub u32);
pub const WHvX64CpuidResult2FlagSubleafSpecific: WHV_X64_CPUID_RESULT2_FLAGS = WHV_X64_CPUID_RESULT2_FLAGS(1u32);
pub const WHvX64CpuidResult2FlagVpSpecific: WHV_X64_CPUID_RESULT2_FLAGS = WHV_X64_CPUID_RESULT2_FLAGS(2u32);
impl ::core::convert::From<u32> for WHV_X64_CPUID_RESULT2_FLAGS {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_X64_CPUID_RESULT2_FLAGS {
type Abi = Self;
}
impl ::core::ops::BitOr for WHV_X64_CPUID_RESULT2_FLAGS {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for WHV_X64_CPUID_RESULT2_FLAGS {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for WHV_X64_CPUID_RESULT2_FLAGS {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for WHV_X64_CPUID_RESULT2_FLAGS {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for WHV_X64_CPUID_RESULT2_FLAGS {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER {
pub Anonymous: WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER_0,
pub AsUINT64: u64,
}
impl WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER {}
impl ::core::default::Default for WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER {}
unsafe impl ::windows::core::Abi for WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER_0 {
pub _bitfield: u64,
}
impl WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER_0 {}
impl ::core::default::Default for WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_DELIVERABILITY_NOTIFICATIONS_REGISTER_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_FP_CONTROL_STATUS_REGISTER {
pub Anonymous: WHV_X64_FP_CONTROL_STATUS_REGISTER_0,
pub AsUINT128: WHV_UINT128,
}
impl WHV_X64_FP_CONTROL_STATUS_REGISTER {}
impl ::core::default::Default for WHV_X64_FP_CONTROL_STATUS_REGISTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_FP_CONTROL_STATUS_REGISTER {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_FP_CONTROL_STATUS_REGISTER {}
unsafe impl ::windows::core::Abi for WHV_X64_FP_CONTROL_STATUS_REGISTER {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_FP_CONTROL_STATUS_REGISTER_0 {
pub FpControl: u16,
pub FpStatus: u16,
pub FpTag: u8,
pub Reserved: u8,
pub LastFpOp: u16,
pub Anonymous: WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0,
}
impl WHV_X64_FP_CONTROL_STATUS_REGISTER_0 {}
impl ::core::default::Default for WHV_X64_FP_CONTROL_STATUS_REGISTER_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_FP_CONTROL_STATUS_REGISTER_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_FP_CONTROL_STATUS_REGISTER_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_FP_CONTROL_STATUS_REGISTER_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0 {
pub LastFpRip: u64,
pub Anonymous: WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0_0,
}
impl WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0 {}
impl ::core::default::Default for WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0_0 {
pub LastFpEip: u32,
pub LastFpCs: u16,
pub Reserved2: u16,
}
impl WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0_0 {}
impl ::core::default::Default for WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("LastFpEip", &self.LastFpEip).field("LastFpCs", &self.LastFpCs).field("Reserved2", &self.Reserved2).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0_0 {
fn eq(&self, other: &Self) -> bool {
self.LastFpEip == other.LastFpEip && self.LastFpCs == other.LastFpCs && self.Reserved2 == other.Reserved2
}
}
impl ::core::cmp::Eq for WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_FP_CONTROL_STATUS_REGISTER_0_0_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_FP_REGISTER {
pub Anonymous: WHV_X64_FP_REGISTER_0,
pub AsUINT128: WHV_UINT128,
}
impl WHV_X64_FP_REGISTER {}
impl ::core::default::Default for WHV_X64_FP_REGISTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_FP_REGISTER {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_FP_REGISTER {}
unsafe impl ::windows::core::Abi for WHV_X64_FP_REGISTER {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_FP_REGISTER_0 {
pub Mantissa: u64,
pub _bitfield: u64,
}
impl WHV_X64_FP_REGISTER_0 {}
impl ::core::default::Default for WHV_X64_FP_REGISTER_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_FP_REGISTER_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("Mantissa", &self.Mantissa).field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_FP_REGISTER_0 {
fn eq(&self, other: &Self) -> bool {
self.Mantissa == other.Mantissa && self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_X64_FP_REGISTER_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_FP_REGISTER_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_INTERRUPTION_DELIVERABLE_CONTEXT {
pub DeliverableType: WHV_X64_PENDING_INTERRUPTION_TYPE,
}
impl WHV_X64_INTERRUPTION_DELIVERABLE_CONTEXT {}
impl ::core::default::Default for WHV_X64_INTERRUPTION_DELIVERABLE_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_INTERRUPTION_DELIVERABLE_CONTEXT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_X64_INTERRUPTION_DELIVERABLE_CONTEXT").field("DeliverableType", &self.DeliverableType).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_INTERRUPTION_DELIVERABLE_CONTEXT {
fn eq(&self, other: &Self) -> bool {
self.DeliverableType == other.DeliverableType
}
}
impl ::core::cmp::Eq for WHV_X64_INTERRUPTION_DELIVERABLE_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_X64_INTERRUPTION_DELIVERABLE_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_INTERRUPT_STATE_REGISTER {
pub Anonymous: WHV_X64_INTERRUPT_STATE_REGISTER_0,
pub AsUINT64: u64,
}
impl WHV_X64_INTERRUPT_STATE_REGISTER {}
impl ::core::default::Default for WHV_X64_INTERRUPT_STATE_REGISTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_INTERRUPT_STATE_REGISTER {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_INTERRUPT_STATE_REGISTER {}
unsafe impl ::windows::core::Abi for WHV_X64_INTERRUPT_STATE_REGISTER {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_INTERRUPT_STATE_REGISTER_0 {
pub _bitfield: u64,
}
impl WHV_X64_INTERRUPT_STATE_REGISTER_0 {}
impl ::core::default::Default for WHV_X64_INTERRUPT_STATE_REGISTER_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_INTERRUPT_STATE_REGISTER_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_INTERRUPT_STATE_REGISTER_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_X64_INTERRUPT_STATE_REGISTER_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_INTERRUPT_STATE_REGISTER_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_IO_PORT_ACCESS_CONTEXT {
pub InstructionByteCount: u8,
pub Reserved: [u8; 3],
pub InstructionBytes: [u8; 16],
pub AccessInfo: WHV_X64_IO_PORT_ACCESS_INFO,
pub PortNumber: u16,
pub Reserved2: [u16; 3],
pub Rax: u64,
pub Rcx: u64,
pub Rsi: u64,
pub Rdi: u64,
pub Ds: WHV_X64_SEGMENT_REGISTER,
pub Es: WHV_X64_SEGMENT_REGISTER,
}
impl WHV_X64_IO_PORT_ACCESS_CONTEXT {}
impl ::core::default::Default for WHV_X64_IO_PORT_ACCESS_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_IO_PORT_ACCESS_CONTEXT {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_IO_PORT_ACCESS_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_X64_IO_PORT_ACCESS_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_IO_PORT_ACCESS_INFO {
pub Anonymous: WHV_X64_IO_PORT_ACCESS_INFO_0,
pub AsUINT32: u32,
}
impl WHV_X64_IO_PORT_ACCESS_INFO {}
impl ::core::default::Default for WHV_X64_IO_PORT_ACCESS_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_IO_PORT_ACCESS_INFO {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_IO_PORT_ACCESS_INFO {}
unsafe impl ::windows::core::Abi for WHV_X64_IO_PORT_ACCESS_INFO {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_IO_PORT_ACCESS_INFO_0 {
pub _bitfield: u32,
}
impl WHV_X64_IO_PORT_ACCESS_INFO_0 {}
impl ::core::default::Default for WHV_X64_IO_PORT_ACCESS_INFO_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_IO_PORT_ACCESS_INFO_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_IO_PORT_ACCESS_INFO_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_X64_IO_PORT_ACCESS_INFO_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_IO_PORT_ACCESS_INFO_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 WHV_X64_LOCAL_APIC_EMULATION_MODE(pub i32);
pub const WHvX64LocalApicEmulationModeNone: WHV_X64_LOCAL_APIC_EMULATION_MODE = WHV_X64_LOCAL_APIC_EMULATION_MODE(0i32);
pub const WHvX64LocalApicEmulationModeXApic: WHV_X64_LOCAL_APIC_EMULATION_MODE = WHV_X64_LOCAL_APIC_EMULATION_MODE(1i32);
pub const WHvX64LocalApicEmulationModeX2Apic: WHV_X64_LOCAL_APIC_EMULATION_MODE = WHV_X64_LOCAL_APIC_EMULATION_MODE(2i32);
impl ::core::convert::From<i32> for WHV_X64_LOCAL_APIC_EMULATION_MODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_X64_LOCAL_APIC_EMULATION_MODE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_MSR_ACCESS_CONTEXT {
pub AccessInfo: WHV_X64_MSR_ACCESS_INFO,
pub MsrNumber: u32,
pub Rax: u64,
pub Rdx: u64,
}
impl WHV_X64_MSR_ACCESS_CONTEXT {}
impl ::core::default::Default for WHV_X64_MSR_ACCESS_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_MSR_ACCESS_CONTEXT {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_MSR_ACCESS_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_X64_MSR_ACCESS_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_MSR_ACCESS_INFO {
pub Anonymous: WHV_X64_MSR_ACCESS_INFO_0,
pub AsUINT32: u32,
}
impl WHV_X64_MSR_ACCESS_INFO {}
impl ::core::default::Default for WHV_X64_MSR_ACCESS_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_MSR_ACCESS_INFO {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_MSR_ACCESS_INFO {}
unsafe impl ::windows::core::Abi for WHV_X64_MSR_ACCESS_INFO {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_MSR_ACCESS_INFO_0 {
pub _bitfield: u32,
}
impl WHV_X64_MSR_ACCESS_INFO_0 {}
impl ::core::default::Default for WHV_X64_MSR_ACCESS_INFO_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_MSR_ACCESS_INFO_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_MSR_ACCESS_INFO_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_X64_MSR_ACCESS_INFO_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_MSR_ACCESS_INFO_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_MSR_EXIT_BITMAP {
pub AsUINT64: u64,
pub Anonymous: WHV_X64_MSR_EXIT_BITMAP_0,
}
impl WHV_X64_MSR_EXIT_BITMAP {}
impl ::core::default::Default for WHV_X64_MSR_EXIT_BITMAP {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_MSR_EXIT_BITMAP {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_MSR_EXIT_BITMAP {}
unsafe impl ::windows::core::Abi for WHV_X64_MSR_EXIT_BITMAP {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_MSR_EXIT_BITMAP_0 {
pub _bitfield: u64,
}
impl WHV_X64_MSR_EXIT_BITMAP_0 {}
impl ::core::default::Default for WHV_X64_MSR_EXIT_BITMAP_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_MSR_EXIT_BITMAP_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_MSR_EXIT_BITMAP_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_X64_MSR_EXIT_BITMAP_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_MSR_EXIT_BITMAP_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_PENDING_DEBUG_EXCEPTION {
pub AsUINT64: u64,
pub Anonymous: WHV_X64_PENDING_DEBUG_EXCEPTION_0,
}
impl WHV_X64_PENDING_DEBUG_EXCEPTION {}
impl ::core::default::Default for WHV_X64_PENDING_DEBUG_EXCEPTION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_PENDING_DEBUG_EXCEPTION {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_PENDING_DEBUG_EXCEPTION {}
unsafe impl ::windows::core::Abi for WHV_X64_PENDING_DEBUG_EXCEPTION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_PENDING_DEBUG_EXCEPTION_0 {
pub _bitfield: u64,
}
impl WHV_X64_PENDING_DEBUG_EXCEPTION_0 {}
impl ::core::default::Default for WHV_X64_PENDING_DEBUG_EXCEPTION_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_PENDING_DEBUG_EXCEPTION_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_PENDING_DEBUG_EXCEPTION_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_X64_PENDING_DEBUG_EXCEPTION_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_PENDING_DEBUG_EXCEPTION_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 WHV_X64_PENDING_EVENT_TYPE(pub i32);
pub const WHvX64PendingEventException: WHV_X64_PENDING_EVENT_TYPE = WHV_X64_PENDING_EVENT_TYPE(0i32);
pub const WHvX64PendingEventExtInt: WHV_X64_PENDING_EVENT_TYPE = WHV_X64_PENDING_EVENT_TYPE(5i32);
impl ::core::convert::From<i32> for WHV_X64_PENDING_EVENT_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_X64_PENDING_EVENT_TYPE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_PENDING_EXCEPTION_EVENT {
pub Anonymous: WHV_X64_PENDING_EXCEPTION_EVENT_0,
pub AsUINT128: WHV_UINT128,
}
impl WHV_X64_PENDING_EXCEPTION_EVENT {}
impl ::core::default::Default for WHV_X64_PENDING_EXCEPTION_EVENT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_PENDING_EXCEPTION_EVENT {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_PENDING_EXCEPTION_EVENT {}
unsafe impl ::windows::core::Abi for WHV_X64_PENDING_EXCEPTION_EVENT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_PENDING_EXCEPTION_EVENT_0 {
pub _bitfield: u32,
pub ErrorCode: u32,
pub ExceptionParameter: u64,
}
impl WHV_X64_PENDING_EXCEPTION_EVENT_0 {}
impl ::core::default::Default for WHV_X64_PENDING_EXCEPTION_EVENT_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_PENDING_EXCEPTION_EVENT_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).field("ErrorCode", &self.ErrorCode).field("ExceptionParameter", &self.ExceptionParameter).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_PENDING_EXCEPTION_EVENT_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield && self.ErrorCode == other.ErrorCode && self.ExceptionParameter == other.ExceptionParameter
}
}
impl ::core::cmp::Eq for WHV_X64_PENDING_EXCEPTION_EVENT_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_PENDING_EXCEPTION_EVENT_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_PENDING_EXT_INT_EVENT {
pub Anonymous: WHV_X64_PENDING_EXT_INT_EVENT_0,
pub AsUINT128: WHV_UINT128,
}
impl WHV_X64_PENDING_EXT_INT_EVENT {}
impl ::core::default::Default for WHV_X64_PENDING_EXT_INT_EVENT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_PENDING_EXT_INT_EVENT {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_PENDING_EXT_INT_EVENT {}
unsafe impl ::windows::core::Abi for WHV_X64_PENDING_EXT_INT_EVENT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_PENDING_EXT_INT_EVENT_0 {
pub _bitfield: u64,
pub Reserved2: u64,
}
impl WHV_X64_PENDING_EXT_INT_EVENT_0 {}
impl ::core::default::Default for WHV_X64_PENDING_EXT_INT_EVENT_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_PENDING_EXT_INT_EVENT_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).field("Reserved2", &self.Reserved2).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_PENDING_EXT_INT_EVENT_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield && self.Reserved2 == other.Reserved2
}
}
impl ::core::cmp::Eq for WHV_X64_PENDING_EXT_INT_EVENT_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_PENDING_EXT_INT_EVENT_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_PENDING_INTERRUPTION_REGISTER {
pub Anonymous: WHV_X64_PENDING_INTERRUPTION_REGISTER_0,
pub AsUINT64: u64,
}
impl WHV_X64_PENDING_INTERRUPTION_REGISTER {}
impl ::core::default::Default for WHV_X64_PENDING_INTERRUPTION_REGISTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_PENDING_INTERRUPTION_REGISTER {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_PENDING_INTERRUPTION_REGISTER {}
unsafe impl ::windows::core::Abi for WHV_X64_PENDING_INTERRUPTION_REGISTER {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_PENDING_INTERRUPTION_REGISTER_0 {
pub _bitfield: u32,
pub ErrorCode: u32,
}
impl WHV_X64_PENDING_INTERRUPTION_REGISTER_0 {}
impl ::core::default::Default for WHV_X64_PENDING_INTERRUPTION_REGISTER_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_PENDING_INTERRUPTION_REGISTER_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).field("ErrorCode", &self.ErrorCode).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_PENDING_INTERRUPTION_REGISTER_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield && self.ErrorCode == other.ErrorCode
}
}
impl ::core::cmp::Eq for WHV_X64_PENDING_INTERRUPTION_REGISTER_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_PENDING_INTERRUPTION_REGISTER_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 WHV_X64_PENDING_INTERRUPTION_TYPE(pub i32);
pub const WHvX64PendingInterrupt: WHV_X64_PENDING_INTERRUPTION_TYPE = WHV_X64_PENDING_INTERRUPTION_TYPE(0i32);
pub const WHvX64PendingNmi: WHV_X64_PENDING_INTERRUPTION_TYPE = WHV_X64_PENDING_INTERRUPTION_TYPE(2i32);
pub const WHvX64PendingException: WHV_X64_PENDING_INTERRUPTION_TYPE = WHV_X64_PENDING_INTERRUPTION_TYPE(3i32);
impl ::core::convert::From<i32> for WHV_X64_PENDING_INTERRUPTION_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_X64_PENDING_INTERRUPTION_TYPE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_RDTSC_CONTEXT {
pub TscAux: u64,
pub VirtualOffset: u64,
pub Tsc: u64,
pub ReferenceTime: u64,
pub RdtscInfo: WHV_X64_RDTSC_INFO,
}
impl WHV_X64_RDTSC_CONTEXT {}
impl ::core::default::Default for WHV_X64_RDTSC_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_RDTSC_CONTEXT {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_RDTSC_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_X64_RDTSC_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_RDTSC_INFO {
pub Anonymous: WHV_X64_RDTSC_INFO_0,
pub AsUINT64: u64,
}
impl WHV_X64_RDTSC_INFO {}
impl ::core::default::Default for WHV_X64_RDTSC_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_RDTSC_INFO {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_RDTSC_INFO {}
unsafe impl ::windows::core::Abi for WHV_X64_RDTSC_INFO {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_RDTSC_INFO_0 {
pub _bitfield: u64,
}
impl WHV_X64_RDTSC_INFO_0 {}
impl ::core::default::Default for WHV_X64_RDTSC_INFO_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_RDTSC_INFO_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_RDTSC_INFO_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_X64_RDTSC_INFO_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_RDTSC_INFO_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_SEGMENT_REGISTER {
pub Base: u64,
pub Limit: u32,
pub Selector: u16,
pub Anonymous: WHV_X64_SEGMENT_REGISTER_0,
}
impl WHV_X64_SEGMENT_REGISTER {}
impl ::core::default::Default for WHV_X64_SEGMENT_REGISTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_SEGMENT_REGISTER {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_SEGMENT_REGISTER {}
unsafe impl ::windows::core::Abi for WHV_X64_SEGMENT_REGISTER {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_SEGMENT_REGISTER_0 {
pub Anonymous: WHV_X64_SEGMENT_REGISTER_0_0,
pub Attributes: u16,
}
impl WHV_X64_SEGMENT_REGISTER_0 {}
impl ::core::default::Default for WHV_X64_SEGMENT_REGISTER_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_SEGMENT_REGISTER_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_SEGMENT_REGISTER_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_SEGMENT_REGISTER_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_SEGMENT_REGISTER_0_0 {
pub _bitfield: u16,
}
impl WHV_X64_SEGMENT_REGISTER_0_0 {}
impl ::core::default::Default for WHV_X64_SEGMENT_REGISTER_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_SEGMENT_REGISTER_0_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_SEGMENT_REGISTER_0_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_X64_SEGMENT_REGISTER_0_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_SEGMENT_REGISTER_0_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_TABLE_REGISTER {
pub Pad: [u16; 3],
pub Limit: u16,
pub Base: u64,
}
impl WHV_X64_TABLE_REGISTER {}
impl ::core::default::Default for WHV_X64_TABLE_REGISTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_TABLE_REGISTER {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_X64_TABLE_REGISTER").field("Pad", &self.Pad).field("Limit", &self.Limit).field("Base", &self.Base).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_TABLE_REGISTER {
fn eq(&self, other: &Self) -> bool {
self.Pad == other.Pad && self.Limit == other.Limit && self.Base == other.Base
}
}
impl ::core::cmp::Eq for WHV_X64_TABLE_REGISTER {}
unsafe impl ::windows::core::Abi for WHV_X64_TABLE_REGISTER {
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 WHV_X64_UNSUPPORTED_FEATURE_CODE(pub i32);
pub const WHvUnsupportedFeatureIntercept: WHV_X64_UNSUPPORTED_FEATURE_CODE = WHV_X64_UNSUPPORTED_FEATURE_CODE(1i32);
pub const WHvUnsupportedFeatureTaskSwitchTss: WHV_X64_UNSUPPORTED_FEATURE_CODE = WHV_X64_UNSUPPORTED_FEATURE_CODE(2i32);
impl ::core::convert::From<i32> for WHV_X64_UNSUPPORTED_FEATURE_CODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for WHV_X64_UNSUPPORTED_FEATURE_CODE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_UNSUPPORTED_FEATURE_CONTEXT {
pub FeatureCode: WHV_X64_UNSUPPORTED_FEATURE_CODE,
pub Reserved: u32,
pub FeatureParameter: u64,
}
impl WHV_X64_UNSUPPORTED_FEATURE_CONTEXT {}
impl ::core::default::Default for WHV_X64_UNSUPPORTED_FEATURE_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_UNSUPPORTED_FEATURE_CONTEXT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("WHV_X64_UNSUPPORTED_FEATURE_CONTEXT").field("FeatureCode", &self.FeatureCode).field("Reserved", &self.Reserved).field("FeatureParameter", &self.FeatureParameter).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_UNSUPPORTED_FEATURE_CONTEXT {
fn eq(&self, other: &Self) -> bool {
self.FeatureCode == other.FeatureCode && self.Reserved == other.Reserved && self.FeatureParameter == other.FeatureParameter
}
}
impl ::core::cmp::Eq for WHV_X64_UNSUPPORTED_FEATURE_CONTEXT {}
unsafe impl ::windows::core::Abi for WHV_X64_UNSUPPORTED_FEATURE_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_VP_EXECUTION_STATE {
pub Anonymous: WHV_X64_VP_EXECUTION_STATE_0,
pub AsUINT16: u16,
}
impl WHV_X64_VP_EXECUTION_STATE {}
impl ::core::default::Default for WHV_X64_VP_EXECUTION_STATE {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_VP_EXECUTION_STATE {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_VP_EXECUTION_STATE {}
unsafe impl ::windows::core::Abi for WHV_X64_VP_EXECUTION_STATE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_VP_EXECUTION_STATE_0 {
pub _bitfield: u16,
}
impl WHV_X64_VP_EXECUTION_STATE_0 {}
impl ::core::default::Default for WHV_X64_VP_EXECUTION_STATE_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_VP_EXECUTION_STATE_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("_bitfield", &self._bitfield).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_VP_EXECUTION_STATE_0 {
fn eq(&self, other: &Self) -> bool {
self._bitfield == other._bitfield
}
}
impl ::core::cmp::Eq for WHV_X64_VP_EXECUTION_STATE_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_VP_EXECUTION_STATE_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_XMM_CONTROL_STATUS_REGISTER {
pub Anonymous: WHV_X64_XMM_CONTROL_STATUS_REGISTER_0,
pub AsUINT128: WHV_UINT128,
}
impl WHV_X64_XMM_CONTROL_STATUS_REGISTER {}
impl ::core::default::Default for WHV_X64_XMM_CONTROL_STATUS_REGISTER {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_XMM_CONTROL_STATUS_REGISTER {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_XMM_CONTROL_STATUS_REGISTER {}
unsafe impl ::windows::core::Abi for WHV_X64_XMM_CONTROL_STATUS_REGISTER {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_XMM_CONTROL_STATUS_REGISTER_0 {
pub Anonymous: WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0,
pub XmmStatusControl: u32,
pub XmmStatusControlMask: u32,
}
impl WHV_X64_XMM_CONTROL_STATUS_REGISTER_0 {}
impl ::core::default::Default for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0 {
pub LastFpRdp: u64,
pub Anonymous: WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0_0,
}
impl WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0 {}
impl ::core::default::Default for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0_0 {
pub LastFpDp: u32,
pub LastFpDs: u16,
pub Reserved: u16,
}
impl WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0_0 {}
impl ::core::default::Default for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0_0 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("_Anonymous_e__Struct").field("LastFpDp", &self.LastFpDp).field("LastFpDs", &self.LastFpDs).field("Reserved", &self.Reserved).finish()
}
}
impl ::core::cmp::PartialEq for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0_0 {
fn eq(&self, other: &Self) -> bool {
self.LastFpDp == other.LastFpDp && self.LastFpDs == other.LastFpDs && self.Reserved == other.Reserved
}
}
impl ::core::cmp::Eq for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0_0 {}
unsafe impl ::windows::core::Abi for WHV_X64_XMM_CONTROL_STATUS_REGISTER_0_0_0 {
type Abi = Self;
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn WHvAcceptPartitionMigration<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(migrationhandle: Param0) -> ::windows::core::Result<WHV_PARTITION_HANDLE> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvAcceptPartitionMigration(migrationhandle: super::super::Foundation::HANDLE, partition: *mut WHV_PARTITION_HANDLE) -> ::windows::core::HRESULT;
}
let mut result__: <WHV_PARTITION_HANDLE as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
WHvAcceptPartitionMigration(migrationhandle.into_param().abi(), &mut result__).from_abi::<WHV_PARTITION_HANDLE>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvAdviseGpaRange<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, gparanges: *const WHV_MEMORY_RANGE_ENTRY, gparangescount: u32, advice: WHV_ADVISE_GPA_RANGE_CODE, advicebuffer: *const ::core::ffi::c_void, advicebuffersizeinbytes: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvAdviseGpaRange(partition: WHV_PARTITION_HANDLE, gparanges: *const WHV_MEMORY_RANGE_ENTRY, gparangescount: u32, advice: WHV_ADVISE_GPA_RANGE_CODE, advicebuffer: *const ::core::ffi::c_void, advicebuffersizeinbytes: u32) -> ::windows::core::HRESULT;
}
WHvAdviseGpaRange(partition.into_param().abi(), ::core::mem::transmute(gparanges), ::core::mem::transmute(gparangescount), ::core::mem::transmute(advice), ::core::mem::transmute(advicebuffer), ::core::mem::transmute(advicebuffersizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn WHvAllocateVpciResource(providerid: *const ::windows::core::GUID, flags: WHV_ALLOCATE_VPCI_RESOURCE_FLAGS, resourcedescriptor: *const ::core::ffi::c_void, resourcedescriptorsizeinbytes: u32) -> ::windows::core::Result<super::super::Foundation::HANDLE> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvAllocateVpciResource(providerid: *const ::windows::core::GUID, flags: WHV_ALLOCATE_VPCI_RESOURCE_FLAGS, resourcedescriptor: *const ::core::ffi::c_void, resourcedescriptorsizeinbytes: u32, vpciresource: *mut super::super::Foundation::HANDLE) -> ::windows::core::HRESULT;
}
let mut result__: <super::super::Foundation::HANDLE as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
WHvAllocateVpciResource(::core::mem::transmute(providerid), ::core::mem::transmute(flags), ::core::mem::transmute(resourcedescriptor), ::core::mem::transmute(resourcedescriptorsizeinbytes), &mut result__).from_abi::<super::super::Foundation::HANDLE>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvCancelPartitionMigration<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvCancelPartitionMigration(partition: WHV_PARTITION_HANDLE) -> ::windows::core::HRESULT;
}
WHvCancelPartitionMigration(partition.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvCancelRunVirtualProcessor<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, flags: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvCancelRunVirtualProcessor(partition: WHV_PARTITION_HANDLE, vpindex: u32, flags: u32) -> ::windows::core::HRESULT;
}
WHvCancelRunVirtualProcessor(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(flags)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvCompletePartitionMigration<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvCompletePartitionMigration(partition: WHV_PARTITION_HANDLE) -> ::windows::core::HRESULT;
}
WHvCompletePartitionMigration(partition.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn WHvCreateNotificationPort<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(partition: Param0, parameters: *const WHV_NOTIFICATION_PORT_PARAMETERS, eventhandle: Param2, porthandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvCreateNotificationPort(partition: WHV_PARTITION_HANDLE, parameters: *const WHV_NOTIFICATION_PORT_PARAMETERS, eventhandle: super::super::Foundation::HANDLE, porthandle: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
WHvCreateNotificationPort(partition.into_param().abi(), ::core::mem::transmute(parameters), eventhandle.into_param().abi(), ::core::mem::transmute(porthandle)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvCreatePartition() -> ::windows::core::Result<WHV_PARTITION_HANDLE> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvCreatePartition(partition: *mut WHV_PARTITION_HANDLE) -> ::windows::core::HRESULT;
}
let mut result__: <WHV_PARTITION_HANDLE as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
WHvCreatePartition(&mut result__).from_abi::<WHV_PARTITION_HANDLE>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn WHvCreateTrigger<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, parameters: *const WHV_TRIGGER_PARAMETERS, triggerhandle: *mut *mut ::core::ffi::c_void, eventhandle: *mut super::super::Foundation::HANDLE) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvCreateTrigger(partition: WHV_PARTITION_HANDLE, parameters: *const WHV_TRIGGER_PARAMETERS, triggerhandle: *mut *mut ::core::ffi::c_void, eventhandle: *mut super::super::Foundation::HANDLE) -> ::windows::core::HRESULT;
}
WHvCreateTrigger(partition.into_param().abi(), ::core::mem::transmute(parameters), ::core::mem::transmute(triggerhandle), ::core::mem::transmute(eventhandle)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvCreateVirtualProcessor<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, flags: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvCreateVirtualProcessor(partition: WHV_PARTITION_HANDLE, vpindex: u32, flags: u32) -> ::windows::core::HRESULT;
}
WHvCreateVirtualProcessor(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(flags)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvCreateVirtualProcessor2<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, properties: *const WHV_VIRTUAL_PROCESSOR_PROPERTY, propertycount: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvCreateVirtualProcessor2(partition: WHV_PARTITION_HANDLE, vpindex: u32, properties: *const WHV_VIRTUAL_PROCESSOR_PROPERTY, propertycount: u32) -> ::windows::core::HRESULT;
}
WHvCreateVirtualProcessor2(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(properties), ::core::mem::transmute(propertycount)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn WHvCreateVpciDevice<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param4: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(partition: Param0, logicaldeviceid: u64, vpciresource: Param2, flags: WHV_CREATE_VPCI_DEVICE_FLAGS, notificationeventhandle: Param4) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvCreateVpciDevice(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64, vpciresource: super::super::Foundation::HANDLE, flags: WHV_CREATE_VPCI_DEVICE_FLAGS, notificationeventhandle: super::super::Foundation::HANDLE) -> ::windows::core::HRESULT;
}
WHvCreateVpciDevice(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid), vpciresource.into_param().abi(), ::core::mem::transmute(flags), notificationeventhandle.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvDeleteNotificationPort<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, porthandle: *const ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvDeleteNotificationPort(partition: WHV_PARTITION_HANDLE, porthandle: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
WHvDeleteNotificationPort(partition.into_param().abi(), ::core::mem::transmute(porthandle)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvDeletePartition<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvDeletePartition(partition: WHV_PARTITION_HANDLE) -> ::windows::core::HRESULT;
}
WHvDeletePartition(partition.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvDeleteTrigger<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, triggerhandle: *const ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvDeleteTrigger(partition: WHV_PARTITION_HANDLE, triggerhandle: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
WHvDeleteTrigger(partition.into_param().abi(), ::core::mem::transmute(triggerhandle)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvDeleteVirtualProcessor<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvDeleteVirtualProcessor(partition: WHV_PARTITION_HANDLE, vpindex: u32) -> ::windows::core::HRESULT;
}
WHvDeleteVirtualProcessor(partition.into_param().abi(), ::core::mem::transmute(vpindex)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvDeleteVpciDevice<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvDeleteVpciDevice(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64) -> ::windows::core::HRESULT;
}
WHvDeleteVpciDevice(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvEmulatorCreateEmulator(callbacks: *const WHV_EMULATOR_CALLBACKS, emulator: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvEmulatorCreateEmulator(callbacks: *const ::core::mem::ManuallyDrop<WHV_EMULATOR_CALLBACKS>, emulator: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
WHvEmulatorCreateEmulator(::core::mem::transmute(callbacks), ::core::mem::transmute(emulator)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvEmulatorDestroyEmulator(emulator: *const ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvEmulatorDestroyEmulator(emulator: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
WHvEmulatorDestroyEmulator(::core::mem::transmute(emulator)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvEmulatorTryIoEmulation(emulator: *const ::core::ffi::c_void, context: *const ::core::ffi::c_void, vpcontext: *const WHV_VP_EXIT_CONTEXT, ioinstructioncontext: *const WHV_X64_IO_PORT_ACCESS_CONTEXT) -> ::windows::core::Result<WHV_EMULATOR_STATUS> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvEmulatorTryIoEmulation(emulator: *const ::core::ffi::c_void, context: *const ::core::ffi::c_void, vpcontext: *const WHV_VP_EXIT_CONTEXT, ioinstructioncontext: *const WHV_X64_IO_PORT_ACCESS_CONTEXT, emulatorreturnstatus: *mut WHV_EMULATOR_STATUS) -> ::windows::core::HRESULT;
}
let mut result__: <WHV_EMULATOR_STATUS as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
WHvEmulatorTryIoEmulation(::core::mem::transmute(emulator), ::core::mem::transmute(context), ::core::mem::transmute(vpcontext), ::core::mem::transmute(ioinstructioncontext), &mut result__).from_abi::<WHV_EMULATOR_STATUS>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvEmulatorTryMmioEmulation(emulator: *const ::core::ffi::c_void, context: *const ::core::ffi::c_void, vpcontext: *const WHV_VP_EXIT_CONTEXT, mmioinstructioncontext: *const WHV_MEMORY_ACCESS_CONTEXT) -> ::windows::core::Result<WHV_EMULATOR_STATUS> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvEmulatorTryMmioEmulation(emulator: *const ::core::ffi::c_void, context: *const ::core::ffi::c_void, vpcontext: *const WHV_VP_EXIT_CONTEXT, mmioinstructioncontext: *const WHV_MEMORY_ACCESS_CONTEXT, emulatorreturnstatus: *mut WHV_EMULATOR_STATUS) -> ::windows::core::HRESULT;
}
let mut result__: <WHV_EMULATOR_STATUS as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
WHvEmulatorTryMmioEmulation(::core::mem::transmute(emulator), ::core::mem::transmute(context), ::core::mem::transmute(vpcontext), ::core::mem::transmute(mmioinstructioncontext), &mut result__).from_abi::<WHV_EMULATOR_STATUS>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetCapability(capabilitycode: WHV_CAPABILITY_CODE, capabilitybuffer: *mut ::core::ffi::c_void, capabilitybuffersizeinbytes: u32, writtensizeinbytes: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetCapability(capabilitycode: WHV_CAPABILITY_CODE, capabilitybuffer: *mut ::core::ffi::c_void, capabilitybuffersizeinbytes: u32, writtensizeinbytes: *mut u32) -> ::windows::core::HRESULT;
}
WHvGetCapability(::core::mem::transmute(capabilitycode), ::core::mem::transmute(capabilitybuffer), ::core::mem::transmute(capabilitybuffersizeinbytes), ::core::mem::transmute(writtensizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetInterruptTargetVpSet<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, destination: u64, destinationmode: WHV_INTERRUPT_DESTINATION_MODE, targetvps: *mut u32, vpcount: u32, targetvpcount: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetInterruptTargetVpSet(partition: WHV_PARTITION_HANDLE, destination: u64, destinationmode: WHV_INTERRUPT_DESTINATION_MODE, targetvps: *mut u32, vpcount: u32, targetvpcount: *mut u32) -> ::windows::core::HRESULT;
}
WHvGetInterruptTargetVpSet(partition.into_param().abi(), ::core::mem::transmute(destination), ::core::mem::transmute(destinationmode), ::core::mem::transmute(targetvps), ::core::mem::transmute(vpcount), ::core::mem::transmute(targetvpcount)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetPartitionCounters<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, counterset: WHV_PARTITION_COUNTER_SET, buffer: *mut ::core::ffi::c_void, buffersizeinbytes: u32, byteswritten: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetPartitionCounters(partition: WHV_PARTITION_HANDLE, counterset: WHV_PARTITION_COUNTER_SET, buffer: *mut ::core::ffi::c_void, buffersizeinbytes: u32, byteswritten: *mut u32) -> ::windows::core::HRESULT;
}
WHvGetPartitionCounters(partition.into_param().abi(), ::core::mem::transmute(counterset), ::core::mem::transmute(buffer), ::core::mem::transmute(buffersizeinbytes), ::core::mem::transmute(byteswritten)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetPartitionProperty<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, propertycode: WHV_PARTITION_PROPERTY_CODE, propertybuffer: *mut ::core::ffi::c_void, propertybuffersizeinbytes: u32, writtensizeinbytes: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetPartitionProperty(partition: WHV_PARTITION_HANDLE, propertycode: WHV_PARTITION_PROPERTY_CODE, propertybuffer: *mut ::core::ffi::c_void, propertybuffersizeinbytes: u32, writtensizeinbytes: *mut u32) -> ::windows::core::HRESULT;
}
WHvGetPartitionProperty(partition.into_param().abi(), ::core::mem::transmute(propertycode), ::core::mem::transmute(propertybuffer), ::core::mem::transmute(propertybuffersizeinbytes), ::core::mem::transmute(writtensizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetVirtualProcessorCounters<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, counterset: WHV_PROCESSOR_COUNTER_SET, buffer: *mut ::core::ffi::c_void, buffersizeinbytes: u32, byteswritten: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetVirtualProcessorCounters(partition: WHV_PARTITION_HANDLE, vpindex: u32, counterset: WHV_PROCESSOR_COUNTER_SET, buffer: *mut ::core::ffi::c_void, buffersizeinbytes: u32, byteswritten: *mut u32) -> ::windows::core::HRESULT;
}
WHvGetVirtualProcessorCounters(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(counterset), ::core::mem::transmute(buffer), ::core::mem::transmute(buffersizeinbytes), ::core::mem::transmute(byteswritten)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetVirtualProcessorCpuidOutput<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, eax: u32, ecx: u32) -> ::windows::core::Result<WHV_CPUID_OUTPUT> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetVirtualProcessorCpuidOutput(partition: WHV_PARTITION_HANDLE, vpindex: u32, eax: u32, ecx: u32, cpuidoutput: *mut WHV_CPUID_OUTPUT) -> ::windows::core::HRESULT;
}
let mut result__: <WHV_CPUID_OUTPUT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
WHvGetVirtualProcessorCpuidOutput(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(eax), ::core::mem::transmute(ecx), &mut result__).from_abi::<WHV_CPUID_OUTPUT>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetVirtualProcessorInterruptControllerState<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, state: *mut ::core::ffi::c_void, statesize: u32, writtensize: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetVirtualProcessorInterruptControllerState(partition: WHV_PARTITION_HANDLE, vpindex: u32, state: *mut ::core::ffi::c_void, statesize: u32, writtensize: *mut u32) -> ::windows::core::HRESULT;
}
WHvGetVirtualProcessorInterruptControllerState(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(state), ::core::mem::transmute(statesize), ::core::mem::transmute(writtensize)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetVirtualProcessorInterruptControllerState2<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, state: *mut ::core::ffi::c_void, statesize: u32, writtensize: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetVirtualProcessorInterruptControllerState2(partition: WHV_PARTITION_HANDLE, vpindex: u32, state: *mut ::core::ffi::c_void, statesize: u32, writtensize: *mut u32) -> ::windows::core::HRESULT;
}
WHvGetVirtualProcessorInterruptControllerState2(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(state), ::core::mem::transmute(statesize), ::core::mem::transmute(writtensize)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetVirtualProcessorRegisters<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, registernames: *const WHV_REGISTER_NAME, registercount: u32, registervalues: *mut WHV_REGISTER_VALUE) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetVirtualProcessorRegisters(partition: WHV_PARTITION_HANDLE, vpindex: u32, registernames: *const WHV_REGISTER_NAME, registercount: u32, registervalues: *mut WHV_REGISTER_VALUE) -> ::windows::core::HRESULT;
}
WHvGetVirtualProcessorRegisters(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(registernames), ::core::mem::transmute(registercount), ::core::mem::transmute(registervalues)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetVirtualProcessorState<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, statetype: WHV_VIRTUAL_PROCESSOR_STATE_TYPE, buffer: *mut ::core::ffi::c_void, buffersizeinbytes: u32, byteswritten: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetVirtualProcessorState(partition: WHV_PARTITION_HANDLE, vpindex: u32, statetype: WHV_VIRTUAL_PROCESSOR_STATE_TYPE, buffer: *mut ::core::ffi::c_void, buffersizeinbytes: u32, byteswritten: *mut u32) -> ::windows::core::HRESULT;
}
WHvGetVirtualProcessorState(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(statetype), ::core::mem::transmute(buffer), ::core::mem::transmute(buffersizeinbytes), ::core::mem::transmute(byteswritten)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetVirtualProcessorXsaveState<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, buffer: *mut ::core::ffi::c_void, buffersizeinbytes: u32, byteswritten: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetVirtualProcessorXsaveState(partition: WHV_PARTITION_HANDLE, vpindex: u32, buffer: *mut ::core::ffi::c_void, buffersizeinbytes: u32, byteswritten: *mut u32) -> ::windows::core::HRESULT;
}
WHvGetVirtualProcessorXsaveState(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(buffer), ::core::mem::transmute(buffersizeinbytes), ::core::mem::transmute(byteswritten)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetVpciDeviceInterruptTarget<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64, index: u32, multimessagenumber: u32, target: *mut WHV_VPCI_INTERRUPT_TARGET, targetsizeinbytes: u32, byteswritten: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetVpciDeviceInterruptTarget(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64, index: u32, multimessagenumber: u32, target: *mut WHV_VPCI_INTERRUPT_TARGET, targetsizeinbytes: u32, byteswritten: *mut u32) -> ::windows::core::HRESULT;
}
WHvGetVpciDeviceInterruptTarget(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid), ::core::mem::transmute(index), ::core::mem::transmute(multimessagenumber), ::core::mem::transmute(target), ::core::mem::transmute(targetsizeinbytes), ::core::mem::transmute(byteswritten)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetVpciDeviceNotification<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64, notification: *mut WHV_VPCI_DEVICE_NOTIFICATION, notificationsizeinbytes: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetVpciDeviceNotification(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64, notification: *mut WHV_VPCI_DEVICE_NOTIFICATION, notificationsizeinbytes: u32) -> ::windows::core::HRESULT;
}
WHvGetVpciDeviceNotification(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid), ::core::mem::transmute(notification), ::core::mem::transmute(notificationsizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvGetVpciDeviceProperty<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64, propertycode: WHV_VPCI_DEVICE_PROPERTY_CODE, propertybuffer: *mut ::core::ffi::c_void, propertybuffersizeinbytes: u32, writtensizeinbytes: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvGetVpciDeviceProperty(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64, propertycode: WHV_VPCI_DEVICE_PROPERTY_CODE, propertybuffer: *mut ::core::ffi::c_void, propertybuffersizeinbytes: u32, writtensizeinbytes: *mut u32) -> ::windows::core::HRESULT;
}
WHvGetVpciDeviceProperty(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid), ::core::mem::transmute(propertycode), ::core::mem::transmute(propertybuffer), ::core::mem::transmute(propertybuffersizeinbytes), ::core::mem::transmute(writtensizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvMapGpaRange<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, sourceaddress: *const ::core::ffi::c_void, guestaddress: u64, sizeinbytes: u64, flags: WHV_MAP_GPA_RANGE_FLAGS) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvMapGpaRange(partition: WHV_PARTITION_HANDLE, sourceaddress: *const ::core::ffi::c_void, guestaddress: u64, sizeinbytes: u64, flags: WHV_MAP_GPA_RANGE_FLAGS) -> ::windows::core::HRESULT;
}
WHvMapGpaRange(partition.into_param().abi(), ::core::mem::transmute(sourceaddress), ::core::mem::transmute(guestaddress), ::core::mem::transmute(sizeinbytes), ::core::mem::transmute(flags)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn WHvMapGpaRange2<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(partition: Param0, process: Param1, sourceaddress: *const ::core::ffi::c_void, guestaddress: u64, sizeinbytes: u64, flags: WHV_MAP_GPA_RANGE_FLAGS) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvMapGpaRange2(partition: WHV_PARTITION_HANDLE, process: super::super::Foundation::HANDLE, sourceaddress: *const ::core::ffi::c_void, guestaddress: u64, sizeinbytes: u64, flags: WHV_MAP_GPA_RANGE_FLAGS) -> ::windows::core::HRESULT;
}
WHvMapGpaRange2(partition.into_param().abi(), process.into_param().abi(), ::core::mem::transmute(sourceaddress), ::core::mem::transmute(guestaddress), ::core::mem::transmute(sizeinbytes), ::core::mem::transmute(flags)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvMapVpciDeviceInterrupt<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64, index: u32, messagecount: u32, target: *const WHV_VPCI_INTERRUPT_TARGET, msiaddress: *mut u64, msidata: *mut u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvMapVpciDeviceInterrupt(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64, index: u32, messagecount: u32, target: *const WHV_VPCI_INTERRUPT_TARGET, msiaddress: *mut u64, msidata: *mut u32) -> ::windows::core::HRESULT;
}
WHvMapVpciDeviceInterrupt(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid), ::core::mem::transmute(index), ::core::mem::transmute(messagecount), ::core::mem::transmute(target), ::core::mem::transmute(msiaddress), ::core::mem::transmute(msidata)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvMapVpciDeviceMmioRanges<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64, mappingcount: *mut u32, mappings: *mut *mut WHV_VPCI_MMIO_MAPPING) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvMapVpciDeviceMmioRanges(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64, mappingcount: *mut u32, mappings: *mut *mut WHV_VPCI_MMIO_MAPPING) -> ::windows::core::HRESULT;
}
WHvMapVpciDeviceMmioRanges(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid), ::core::mem::transmute(mappingcount), ::core::mem::transmute(mappings)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvPostVirtualProcessorSynicMessage<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, sintindex: u32, message: *const ::core::ffi::c_void, messagesizeinbytes: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvPostVirtualProcessorSynicMessage(partition: WHV_PARTITION_HANDLE, vpindex: u32, sintindex: u32, message: *const ::core::ffi::c_void, messagesizeinbytes: u32) -> ::windows::core::HRESULT;
}
WHvPostVirtualProcessorSynicMessage(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(sintindex), ::core::mem::transmute(message), ::core::mem::transmute(messagesizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvQueryGpaRangeDirtyBitmap<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, guestaddress: u64, rangesizeinbytes: u64, bitmap: *mut u64, bitmapsizeinbytes: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvQueryGpaRangeDirtyBitmap(partition: WHV_PARTITION_HANDLE, guestaddress: u64, rangesizeinbytes: u64, bitmap: *mut u64, bitmapsizeinbytes: u32) -> ::windows::core::HRESULT;
}
WHvQueryGpaRangeDirtyBitmap(partition.into_param().abi(), ::core::mem::transmute(guestaddress), ::core::mem::transmute(rangesizeinbytes), ::core::mem::transmute(bitmap), ::core::mem::transmute(bitmapsizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvReadGpaRange<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>, Param3: ::windows::core::IntoParam<'a, WHV_ACCESS_GPA_CONTROLS>>(partition: Param0, vpindex: u32, guestaddress: u64, controls: Param3, data: *mut ::core::ffi::c_void, datasizeinbytes: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvReadGpaRange(partition: WHV_PARTITION_HANDLE, vpindex: u32, guestaddress: u64, controls: WHV_ACCESS_GPA_CONTROLS, data: *mut ::core::ffi::c_void, datasizeinbytes: u32) -> ::windows::core::HRESULT;
}
WHvReadGpaRange(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(guestaddress), controls.into_param().abi(), ::core::mem::transmute(data), ::core::mem::transmute(datasizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvReadVpciDeviceRegister<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64, register: *const WHV_VPCI_DEVICE_REGISTER, data: *mut ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvReadVpciDeviceRegister(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64, register: *const WHV_VPCI_DEVICE_REGISTER, data: *mut ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
WHvReadVpciDeviceRegister(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid), ::core::mem::transmute(register), ::core::mem::transmute(data)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn WHvRegisterPartitionDoorbellEvent<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(partition: Param0, matchdata: *const WHV_DOORBELL_MATCH_DATA, eventhandle: Param2) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvRegisterPartitionDoorbellEvent(partition: WHV_PARTITION_HANDLE, matchdata: *const WHV_DOORBELL_MATCH_DATA, eventhandle: super::super::Foundation::HANDLE) -> ::windows::core::HRESULT;
}
WHvRegisterPartitionDoorbellEvent(partition.into_param().abi(), ::core::mem::transmute(matchdata), eventhandle.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvRequestInterrupt<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, interrupt: *const WHV_INTERRUPT_CONTROL, interruptcontrolsize: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvRequestInterrupt(partition: WHV_PARTITION_HANDLE, interrupt: *const WHV_INTERRUPT_CONTROL, interruptcontrolsize: u32) -> ::windows::core::HRESULT;
}
WHvRequestInterrupt(partition.into_param().abi(), ::core::mem::transmute(interrupt), ::core::mem::transmute(interruptcontrolsize)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvRequestVpciDeviceInterrupt<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64, msiaddress: u64, msidata: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvRequestVpciDeviceInterrupt(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64, msiaddress: u64, msidata: u32) -> ::windows::core::HRESULT;
}
WHvRequestVpciDeviceInterrupt(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid), ::core::mem::transmute(msiaddress), ::core::mem::transmute(msidata)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvResetPartition<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvResetPartition(partition: WHV_PARTITION_HANDLE) -> ::windows::core::HRESULT;
}
WHvResetPartition(partition.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvResumePartitionTime<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvResumePartitionTime(partition: WHV_PARTITION_HANDLE) -> ::windows::core::HRESULT;
}
WHvResumePartitionTime(partition.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvRetargetVpciDeviceInterrupt<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64, msiaddress: u64, msidata: u32, target: *const WHV_VPCI_INTERRUPT_TARGET) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvRetargetVpciDeviceInterrupt(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64, msiaddress: u64, msidata: u32, target: *const WHV_VPCI_INTERRUPT_TARGET) -> ::windows::core::HRESULT;
}
WHvRetargetVpciDeviceInterrupt(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid), ::core::mem::transmute(msiaddress), ::core::mem::transmute(msidata), ::core::mem::transmute(target)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvRunVirtualProcessor<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, exitcontext: *mut ::core::ffi::c_void, exitcontextsizeinbytes: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvRunVirtualProcessor(partition: WHV_PARTITION_HANDLE, vpindex: u32, exitcontext: *mut ::core::ffi::c_void, exitcontextsizeinbytes: u32) -> ::windows::core::HRESULT;
}
WHvRunVirtualProcessor(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(exitcontext), ::core::mem::transmute(exitcontextsizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvSetNotificationPortProperty<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, porthandle: *const ::core::ffi::c_void, propertycode: WHV_NOTIFICATION_PORT_PROPERTY_CODE, propertyvalue: u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvSetNotificationPortProperty(partition: WHV_PARTITION_HANDLE, porthandle: *const ::core::ffi::c_void, propertycode: WHV_NOTIFICATION_PORT_PROPERTY_CODE, propertyvalue: u64) -> ::windows::core::HRESULT;
}
WHvSetNotificationPortProperty(partition.into_param().abi(), ::core::mem::transmute(porthandle), ::core::mem::transmute(propertycode), ::core::mem::transmute(propertyvalue)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvSetPartitionProperty<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, propertycode: WHV_PARTITION_PROPERTY_CODE, propertybuffer: *const ::core::ffi::c_void, propertybuffersizeinbytes: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvSetPartitionProperty(partition: WHV_PARTITION_HANDLE, propertycode: WHV_PARTITION_PROPERTY_CODE, propertybuffer: *const ::core::ffi::c_void, propertybuffersizeinbytes: u32) -> ::windows::core::HRESULT;
}
WHvSetPartitionProperty(partition.into_param().abi(), ::core::mem::transmute(propertycode), ::core::mem::transmute(propertybuffer), ::core::mem::transmute(propertybuffersizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvSetVirtualProcessorInterruptControllerState<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, state: *const ::core::ffi::c_void, statesize: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvSetVirtualProcessorInterruptControllerState(partition: WHV_PARTITION_HANDLE, vpindex: u32, state: *const ::core::ffi::c_void, statesize: u32) -> ::windows::core::HRESULT;
}
WHvSetVirtualProcessorInterruptControllerState(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(state), ::core::mem::transmute(statesize)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvSetVirtualProcessorInterruptControllerState2<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, state: *const ::core::ffi::c_void, statesize: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvSetVirtualProcessorInterruptControllerState2(partition: WHV_PARTITION_HANDLE, vpindex: u32, state: *const ::core::ffi::c_void, statesize: u32) -> ::windows::core::HRESULT;
}
WHvSetVirtualProcessorInterruptControllerState2(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(state), ::core::mem::transmute(statesize)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvSetVirtualProcessorRegisters<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, registernames: *const WHV_REGISTER_NAME, registercount: u32, registervalues: *const WHV_REGISTER_VALUE) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvSetVirtualProcessorRegisters(partition: WHV_PARTITION_HANDLE, vpindex: u32, registernames: *const WHV_REGISTER_NAME, registercount: u32, registervalues: *const WHV_REGISTER_VALUE) -> ::windows::core::HRESULT;
}
WHvSetVirtualProcessorRegisters(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(registernames), ::core::mem::transmute(registercount), ::core::mem::transmute(registervalues)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvSetVirtualProcessorState<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, statetype: WHV_VIRTUAL_PROCESSOR_STATE_TYPE, buffer: *const ::core::ffi::c_void, buffersizeinbytes: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvSetVirtualProcessorState(partition: WHV_PARTITION_HANDLE, vpindex: u32, statetype: WHV_VIRTUAL_PROCESSOR_STATE_TYPE, buffer: *const ::core::ffi::c_void, buffersizeinbytes: u32) -> ::windows::core::HRESULT;
}
WHvSetVirtualProcessorState(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(statetype), ::core::mem::transmute(buffer), ::core::mem::transmute(buffersizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvSetVirtualProcessorXsaveState<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, buffer: *const ::core::ffi::c_void, buffersizeinbytes: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvSetVirtualProcessorXsaveState(partition: WHV_PARTITION_HANDLE, vpindex: u32, buffer: *const ::core::ffi::c_void, buffersizeinbytes: u32) -> ::windows::core::HRESULT;
}
WHvSetVirtualProcessorXsaveState(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(buffer), ::core::mem::transmute(buffersizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_System_Power")]
#[inline]
pub unsafe fn WHvSetVpciDevicePowerState<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64, powerstate: super::Power::DEVICE_POWER_STATE) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvSetVpciDevicePowerState(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64, powerstate: super::Power::DEVICE_POWER_STATE) -> ::windows::core::HRESULT;
}
WHvSetVpciDevicePowerState(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid), ::core::mem::transmute(powerstate)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvSetupPartition<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvSetupPartition(partition: WHV_PARTITION_HANDLE) -> ::windows::core::HRESULT;
}
WHvSetupPartition(partition.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn WHvSignalVirtualProcessorSynicEvent<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>, Param1: ::windows::core::IntoParam<'a, WHV_SYNIC_EVENT_PARAMETERS>>(partition: Param0, synicevent: Param1) -> ::windows::core::Result<super::super::Foundation::BOOL> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvSignalVirtualProcessorSynicEvent(partition: WHV_PARTITION_HANDLE, synicevent: WHV_SYNIC_EVENT_PARAMETERS, newlysignaled: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT;
}
let mut result__: <super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
WHvSignalVirtualProcessorSynicEvent(partition.into_param().abi(), synicevent.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::BOOL>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn WHvStartPartitionMigration<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0) -> ::windows::core::Result<super::super::Foundation::HANDLE> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvStartPartitionMigration(partition: WHV_PARTITION_HANDLE, migrationhandle: *mut super::super::Foundation::HANDLE) -> ::windows::core::HRESULT;
}
let mut result__: <super::super::Foundation::HANDLE as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
WHvStartPartitionMigration(partition.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::HANDLE>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvSuspendPartitionTime<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvSuspendPartitionTime(partition: WHV_PARTITION_HANDLE) -> ::windows::core::HRESULT;
}
WHvSuspendPartitionTime(partition.into_param().abi()).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvTranslateGva<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, vpindex: u32, gva: u64, translateflags: WHV_TRANSLATE_GVA_FLAGS, translationresult: *mut WHV_TRANSLATE_GVA_RESULT, gpa: *mut u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvTranslateGva(partition: WHV_PARTITION_HANDLE, vpindex: u32, gva: u64, translateflags: WHV_TRANSLATE_GVA_FLAGS, translationresult: *mut WHV_TRANSLATE_GVA_RESULT, gpa: *mut u64) -> ::windows::core::HRESULT;
}
WHvTranslateGva(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(gva), ::core::mem::transmute(translateflags), ::core::mem::transmute(translationresult), ::core::mem::transmute(gpa)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvUnmapGpaRange<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, guestaddress: u64, sizeinbytes: u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvUnmapGpaRange(partition: WHV_PARTITION_HANDLE, guestaddress: u64, sizeinbytes: u64) -> ::windows::core::HRESULT;
}
WHvUnmapGpaRange(partition.into_param().abi(), ::core::mem::transmute(guestaddress), ::core::mem::transmute(sizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvUnmapVpciDeviceInterrupt<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64, index: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvUnmapVpciDeviceInterrupt(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64, index: u32) -> ::windows::core::HRESULT;
}
WHvUnmapVpciDeviceInterrupt(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid), ::core::mem::transmute(index)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvUnmapVpciDeviceMmioRanges<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvUnmapVpciDeviceMmioRanges(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64) -> ::windows::core::HRESULT;
}
WHvUnmapVpciDeviceMmioRanges(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvUnregisterPartitionDoorbellEvent<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, matchdata: *const WHV_DOORBELL_MATCH_DATA) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvUnregisterPartitionDoorbellEvent(partition: WHV_PARTITION_HANDLE, matchdata: *const WHV_DOORBELL_MATCH_DATA) -> ::windows::core::HRESULT;
}
WHvUnregisterPartitionDoorbellEvent(partition.into_param().abi(), ::core::mem::transmute(matchdata)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvUpdateTriggerParameters<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, parameters: *const WHV_TRIGGER_PARAMETERS, triggerhandle: *const ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvUpdateTriggerParameters(partition: WHV_PARTITION_HANDLE, parameters: *const WHV_TRIGGER_PARAMETERS, triggerhandle: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
WHvUpdateTriggerParameters(partition.into_param().abi(), ::core::mem::transmute(parameters), ::core::mem::transmute(triggerhandle)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvWriteGpaRange<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>, Param3: ::windows::core::IntoParam<'a, WHV_ACCESS_GPA_CONTROLS>>(partition: Param0, vpindex: u32, guestaddress: u64, controls: Param3, data: *const ::core::ffi::c_void, datasizeinbytes: u32) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvWriteGpaRange(partition: WHV_PARTITION_HANDLE, vpindex: u32, guestaddress: u64, controls: WHV_ACCESS_GPA_CONTROLS, data: *const ::core::ffi::c_void, datasizeinbytes: u32) -> ::windows::core::HRESULT;
}
WHvWriteGpaRange(partition.into_param().abi(), ::core::mem::transmute(vpindex), ::core::mem::transmute(guestaddress), controls.into_param().abi(), ::core::mem::transmute(data), ::core::mem::transmute(datasizeinbytes)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn WHvWriteVpciDeviceRegister<'a, Param0: ::windows::core::IntoParam<'a, WHV_PARTITION_HANDLE>>(partition: Param0, logicaldeviceid: u64, register: *const WHV_VPCI_DEVICE_REGISTER, data: *const ::core::ffi::c_void) -> ::windows::core::Result<()> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn WHvWriteVpciDeviceRegister(partition: WHV_PARTITION_HANDLE, logicaldeviceid: u64, register: *const WHV_VPCI_DEVICE_REGISTER, data: *const ::core::ffi::c_void) -> ::windows::core::HRESULT;
}
WHvWriteVpciDeviceRegister(partition.into_param().abi(), ::core::mem::transmute(logicaldeviceid), ::core::mem::transmute(register), ::core::mem::transmute(data)).ok()
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
|
use super::Cartridge;
use crate::ines::File;
use crate::ines::Mirroring;
pub struct AxROM {
pub file: File,
chr_ram: [u8; 0x2000],
bank: u8,
}
impl AxROM {
pub fn new(file: File) -> AxROM {
AxROM {
file,
chr_ram: [0; 0x2000],
bank: 0,
}
}
}
impl Cartridge for AxROM {
fn read(&mut self, address: u16) -> u8 {
match address {
0x4020...0x7FFF => 0,
0x8000...0xFFFF => {
self.file.prg_rom[address as usize - 0x8000 + self.bank as usize * 0x8000]
}
_ => panic!("Read outside scope: {:04X}", address),
}
}
fn write(&mut self, address: u16, byte: u8) {
match address {
0x8000...0xFFFF => self.bank = 0x7 & byte,
_ => panic!(
"AxROM write outside of range: {:04X} = {:02X}",
address, byte
),
}
}
fn ppu_read(&mut self, address: u16) -> u8 {
match address {
0x0000...0x1FFF => self.chr_ram[address as usize],
_ => panic!("PPU read outside of range"),
}
}
fn ppu_write(&mut self, address: u16, byte: u8) {
match address {
0x0000...0x1FFF => self.chr_ram[address as usize] = byte,
_ => println!(
"Attempt to PPU write to AxROM: {:04X} = {:02X}",
address, byte
),
}
}
fn mirroring(&self) -> Mirroring {
self.file.mirroring
}
}
|
#[derive(Debug, PartialEq)]
pub enum Opcode {
HLT, // Halt
LOAD, // Load
// math
ADD,
MUL,
SUB,
DIV,
// jumps
JMP,
JMPF,
JMPB,
JEQ,
// equality
EQ,
NEQ,
GT,
LT,
GTQ,
LTQ,
// utility
IGL(u8), // Illegal
}
impl From<u8> for Opcode {
fn from(v: u8) -> Self {
match v {
0 => Opcode::HLT,
1 => Opcode::LOAD,
2 => Opcode::ADD,
3 => Opcode::SUB,
4 => Opcode::MUL,
5 => Opcode::DIV,
6 => Opcode::JMP,
7 => Opcode::JMPF,
8 => Opcode::JMPB,
9 => Opcode::JEQ,
0xA => Opcode::EQ,
0xB => Opcode::NEQ,
0xC => Opcode::GT,
0xD => Opcode::LT,
0xE => Opcode::GTQ,
0xF => Opcode::LTQ,
_ => Opcode::IGL(v),
}
}
}
impl From<&Opcode> for u8 {
fn from(op: &Opcode) -> Self {
match op {
Opcode::HLT => 0,
Opcode::LOAD => 1,
Opcode::ADD => 2,
Opcode::SUB => 3,
Opcode::MUL => 4,
Opcode::DIV => 5,
Opcode::JMP => 6,
Opcode::JMPF => 7,
Opcode::JMPB => 8,
Opcode::JEQ => 9,
Opcode::EQ => 0xA,
Opcode::NEQ => 0xB,
Opcode::GT => 0xC,
Opcode::LT => 0xD,
Opcode::GTQ => 0xE,
Opcode::LTQ => 0xF,
Opcode::IGL(_) => 0xFF,
}
}
}
impl<'a> From<&str> for Opcode {
fn from(opcode: &str) -> Self {
match opcode.to_uppercase().as_str() {
"HLT" => Opcode::HLT,
"LOAD" => Opcode::LOAD,
"ADD" => Opcode::ADD,
"SUB" => Opcode::SUB,
"MUL" => Opcode::MUL,
"DIV" => Opcode::DIV,
"JMP" => Opcode::JMP,
"JMPF" => Opcode::JMPF,
"JMPB" => Opcode::JMPB,
"JEQ" => Opcode::JEQ,
"EQ" => Opcode::EQ,
"NEQ" => Opcode::NEQ,
"GT" => Opcode::GT,
"LT" => Opcode::LT,
"GTQ" => Opcode::GTQ,
"LTQ" => Opcode::LTQ,
_ => Opcode::IGL(0xFF),
}
}
}
// #[derive(Debug, PartialEq)]
// pub struct Instruction {
// opcode: Opcode,
// }
// impl Instruction {
// fn new(opcode: Opcode) -> Instruction {
// Instruction { opcode: opcode }
// }
// }
// #[cfg(test)]
// mod tests {
// use super::*;
// #[test]
// fn test_create_hlt() {
// let opcode = Opcode::HLT;
// assert_eq!(opcode, Opcode::HLT);
// }
// #[test]
// fn test_create_instruction() {
// let instruction = Instruction::new(Opcode::HLT);
// assert_eq!(instruction.opcode, Opcode::HLT);
// }
// }
|
use crate::movement::ground::Grounded;
use ::amethyst::core::math::Vector3;
use ::amethyst::core::timing::Time;
use ::amethyst::ecs::*;
use serde::Serialize;
use nphysics_ecs::*;
/// The way friction is applied.
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
pub enum FrictionMode {
/// The velocity is reduced by a fixed amount each second (deceleration).
Linear,
/// The velocity is reduced by a fraction of the current velocity.
/// A value of 0.2 means that approximatively 20% of the speed will be lost each second.
/// Since it is not calculated as an integration but as discrete values, the actual slowdown will vary slightly from case to case.
Percent,
}
/// Component you add to your entities to apply a ground friction.
/// What the friction field does is dependent on the choosen `FrictionMode`.
#[derive(Serialize, Deserialize, Clone, Debug, new)]
pub struct GroundFriction3D {
/// The amount of friction speed loss by second.
pub friction: f32,
/// The way friction is applied.
pub friction_mode: FrictionMode,
/// The time to wait after touching the ground before applying the friction.
pub ground_time_before_apply: f64,
}
impl Component for GroundFriction3D {
type Storage = DenseVecStorage<Self>;
}
/// Applies friction (slows the velocity down) according to the `GroundFriction3D` component of your entity.
/// Your entity also needs to have a `Grounded` component (and the `GroundCheckerSystem` added to your dispatcher) to detect the ground.
/// It also needs to have a NextFrame<Velocity3<f32>> component. This is added automatically by rhusics when creating a dynamic physical entity.
pub struct GroundFrictionSystem;
impl<'a> System<'a> for GroundFrictionSystem {
type SystemData = (
Read<'a, Time>,
ReadStorage<'a, Grounded>,
ReadStorage<'a, GroundFriction3D>,
WriteRigidBodies<'a, f32>,
);
fn run(&mut self, (time, groundeds, frictions, mut rigid_bodies): Self::SystemData) {
fn apply_friction_single(v: f32, friction: f32) -> f32 {
if v.abs() <= friction {
return 0.0;
}
v - friction
}
for (grounded, friction, rb) in (&groundeds, &frictions, &mut rigid_bodies).join() {
if grounded.ground
&& time.absolute_time_seconds() - grounded.since
>= friction.ground_time_before_apply
{
let (x, y, z) = {
let v = rb.velocity().linear;
(v.x, v.y, v.z)
};
match friction.friction_mode {
FrictionMode::Linear => {
let slowdown = friction.friction * time.delta_seconds();
rb.set_linear_velocity(Vector3::new(
apply_friction_single(x, slowdown),
y,
apply_friction_single(z, slowdown),
));
}
FrictionMode::Percent => {
let coef = friction.friction * time.delta_seconds();
rb.set_linear_velocity(Vector3::new(
apply_friction_single(x, x * coef),
y,
apply_friction_single(z, z * coef),
));
}
}
}
}
}
}
|
use std::io::{Write, stdout};
use crossterm::{cursor::{MoveDown, MoveToPreviousLine, RestorePosition, SavePosition}, execute, style::{Attribute, Color, Print, ResetColor, SetAttribute, SetBackgroundColor, SetForegroundColor}};
#[derive(Debug)]
pub enum Error {
Display,
Logic,
Args,
}
pub type Result<T> = std::result::Result<T, Error>;
pub struct Entry {
pub name: String,
pub color: Color,
}
impl Entry {
pub fn new(name: String, color: Color) -> Entry {
return Entry {
name: format!("{}\n", &name),
color,
};
}
pub fn print(&self) -> Result<()> {
execute!(
stdout(),
SetForegroundColor(self.color),
SetBackgroundColor(Color::Black),
Print(" "),
Print(self.name.clone()),
ResetColor,
).map_err(|_| Error::Display)?;
Ok(())
}
}
pub fn print_entries(entries: &Vec<Entry>) -> Result<()> {
for entry in entries {
&entry.print()?;
}
Ok(())
}
pub fn print_selected_entry(entry: &Entry, i: usize, total: usize) -> Result<()> {
execute!(
stdout(),
SavePosition,
MoveToPreviousLine(total as u16),
MoveDown((i % total) as u16),
SetForegroundColor(entry.color),
Print(">"),
SetAttribute(Attribute::Underlined),
Print(&entry.name),
RestorePosition,
).map_err(|_| Error::Display)?;
Ok(())
}
pub fn print_clear_entry(entry: &Entry, i: usize, total: usize) -> Result<()> {
execute!(
stdout(),
SavePosition,
MoveToPreviousLine(total as u16),
MoveDown((i % total) as u16),
SetForegroundColor(entry.color),
Print(" "),
SetAttribute(Attribute::NoUnderline),
Print(&entry.name),
RestorePosition,
).map_err(|_| Error::Display)?;
Ok(())
}
|
use json_utils::json::JsValue;
use crate::core::heq::HEq;
mod js_value_eq;
use js_value_eq::js_value_eq;
mod js_value_hash;
use js_value_hash::js_value_hash;
pub struct JsValueHEq;
impl HEq<JsValue> for JsValueHEq {
fn are_eq(&self, left: &JsValue, right: &JsValue) -> bool {
js_value_eq(left, right)
}
fn calc_hash(&self, value: &JsValue) -> u64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
let mut hasher = DefaultHasher::new();
js_value_hash(value, &mut hasher);
hasher.finish()
}
}
|
use std::collections::{HashMap,HashSet};
use std::iter::FromIterator;
use std::u32;
pub struct DirectedGraph {
// <source_node, Vec<(destination_node, weight)>>
// Used HashMap for efficient lookup of a source node's neighbors.
node_edges: HashMap<usize,Vec<(usize,u32)>>
}
impl DirectedGraph {
pub fn new() -> Self {
DirectedGraph {
node_edges: HashMap::new()
}
}
pub fn with_nodes(nodes: usize) -> Self {
let mut node_edges = HashMap::with_capacity(nodes);
for node_index in 0..nodes {
node_edges.insert(node_index, Vec::new());
}
DirectedGraph {
node_edges
}
}
pub fn add_node(&mut self) -> usize {
let node_index = self.node_edges.len();
self.node_edges.insert(node_index, Vec::new());
return node_index;
}
pub fn add_edge(&mut self, start_node: usize, end_node: usize, weight: u32) {
match &mut self.node_edges.get_mut(&start_node) {
Some(edge_list) => edge_list.push((end_node, weight)),
None => eprintln!("Failed to create edge: start node {} doesn't exist in this graph!", &start_node)
};
}
pub fn well_formed(&self) -> bool {
self.node_edges.values()
.all(|edge_list| edge_list.iter()
.all(|edge| self.node_edges.contains_key(&edge.0)))
}
// Dijkstra's algorithm
pub fn distance(&self, start_node: usize, end_node: usize) -> u32 {
let mut distance: Vec<u32> = Vec::with_capacity(self.node_edges.len());
for n in 0..self.node_edges.len() {
if n == start_node {
distance.insert(n, 0);
} else {
distance.insert(n, u32::MAX);
}
}
let mut unvisited: HashSet<usize> = HashSet::from_iter(0..self.node_edges.len());
let mut current_node = start_node;
loop {
for edge in self.node_edges.get(¤t_node).unwrap() {
let neighbor_node = edge.0;
let current_distance = distance[neighbor_node];
let weight = edge.1;
let new_distance = distance[current_node] + weight;
if new_distance < current_distance {
distance[neighbor_node] = new_distance;
}
}
unvisited.remove(¤t_node);
println!("{}", unvisited.len());
let next_node = unvisited.iter().min_by(|&n1, &n2| distance[*n1].cmp(&distance[*n2]));
if !unvisited.contains(&end_node) || match next_node { None => true, Some(n) => distance[*n] == u32::MAX } {
break;
} else {
current_node = *next_node.unwrap();
}
}
return distance[end_node];
}
} |
//store.rs
//store sells items to player
//
//
use super::item_bag::ItemBag as Bag;
#[derive(Debug, Clone)]
pub struct Store {
pub items: Bag,
pub is_active: bool,
}
impl Store {
pub fn gen_store() -> Store {
Store {
items: Bag::gen_bag_with_vals(&vec![
("(R)ope", 50),
("(H)ammer", 25),
("(B)oat", 75),
("(F)ace", 100),
]),
is_active: false,
//
}
}
pub fn contents_to_strings(&self) -> Vec<String> {
self.items.contents_as_strings()
}
pub fn purchase(&self, item: &str, wallet: &mut i32) -> bool {
if self.items.contains(item) && *wallet >= self.items.count(item) {
*wallet -= self.items.count(item);
true
} else {
false
}
}
}
//purchase menu, game control
//collaspe into mod ???
|
// 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.
//! Test tools for building and serving TUF repositories containing Fuchsia packages.
use {
crate::{package::Package, serve::ServedRepositoryBuilder},
bytes::Buf,
failure::{bail, format_err, Error, ResultExt},
fidl_fuchsia_pkg_ext::{
MirrorConfigBuilder, RepositoryBlobKey, RepositoryConfig, RepositoryConfigBuilder,
RepositoryKey,
},
fidl_fuchsia_sys::{ComponentControllerProxy, LauncherProxy},
fuchsia_async::{DurationExt, TimeoutExt},
fuchsia_component::client::{launcher, AppBuilder, Output, Stdio},
fuchsia_merkle::Hash,
fuchsia_url::pkg_url::RepoUrl,
fuchsia_zircon::DurationNum,
futures::{
compat::{Future01CompatExt, Stream01CompatExt},
future::BoxFuture,
prelude::*,
},
hyper::{Body, Request, StatusCode},
serde_derive::Deserialize,
std::{
collections::{BTreeMap, BTreeSet},
fmt,
fs::{self, File},
io::{self, Cursor, Read, Write},
path::PathBuf,
sync::Arc,
time::Duration,
},
tempfile::TempDir,
walkdir::WalkDir,
};
/// A builder to simplify construction of TUF repositories containing Fuchsia packages.
#[derive(Debug)]
pub struct RepositoryBuilder<'a> {
packages: Vec<PackageRef<'a>>,
encryption_key: Option<BlobEncryptionKey>,
repodir: Option<PathBuf>,
}
impl<'a> RepositoryBuilder<'a> {
/// Creates a new `RepositoryBuilder`.
pub fn new() -> Self {
Self { packages: vec![], encryption_key: None, repodir: None }
}
/// Creates a new `RepositoryBuilder` from a template TUF repository dir.
pub fn from_template_dir(path: impl Into<PathBuf>) -> Self {
Self { packages: vec![], encryption_key: None, repodir: Some(path.into()) }
}
/// Adds a package (or a reference to one) to the repository.
pub fn add_package(mut self, package: impl Into<PackageRef<'a>>) -> Self {
self.packages.push(package.into());
self
}
/// Encrypts blobs in the repository with the given key (default is to not encrypt blobs).
pub fn set_encryption_key(mut self, key: BlobEncryptionKey) -> Self {
self.encryption_key = Some(key);
self
}
/// Builds the repository.
pub async fn build(self) -> Result<Repository, Error> {
let indir = tempfile::tempdir().context("create /in")?;
let repodir = tempfile::tempdir().context("create /repo")?;
{
let mut manifest = File::create(indir.path().join("manifests.list"))?;
for package in &self.packages {
writeln!(manifest, "/packages/{}/manifest.json", package.get().name())?;
}
}
// If configured to use a template repository directory, first copy it into the repo dir.
if let Some(templatedir) = self.repodir {
for entry in WalkDir::new(&templatedir) {
let entry = entry?;
if entry.path() == &templatedir {
continue;
}
let relative_entry_path = entry.path().strip_prefix(&templatedir)?;
let target_path = repodir.path().join(relative_entry_path);
if entry.file_type().is_dir() {
fs::create_dir(target_path)?;
} else {
fs::copy(entry.path(), target_path)?;
}
}
}
let mut pm = AppBuilder::new("fuchsia-pkg://fuchsia.com/pm#meta/pm.cmx")
.arg("publish")
.arg("-lp")
.arg("-f=/in/manifests.list")
.arg("-repo=/repo")
.add_dir_to_namespace("/in".to_owned(), File::open(indir.path()).context("open /in")?)?
.add_dir_to_namespace(
"/repo".to_owned(),
File::open(repodir.path()).context("open /repo")?,
)?;
if let Some(ref key) = self.encryption_key {
fs::write(indir.path().join("encryption.key"), key.as_bytes())?;
pm = pm.arg("-e=/in/encryption.key");
}
for package in &self.packages {
let package = package.get();
pm = pm.add_dir_to_namespace(
format!("/packages/{}", package.name()),
File::open(package.artifacts()).context("open package dir")?,
)?;
}
pm.output(&launcher()?)?.await?.ok()?;
Ok(Repository { dir: repodir, encryption_key: self.encryption_key })
}
}
/// An owned [`Package`] or a reference to one.
#[derive(Debug)]
pub enum PackageRef<'a> {
Owned(Package),
Ref(&'a Package),
}
impl PackageRef<'_> {
fn get(&self) -> &Package {
match *self {
PackageRef::Owned(ref p) => p,
PackageRef::Ref(p) => p,
}
}
}
impl From<Package> for PackageRef<'_> {
fn from(p: Package) -> Self {
PackageRef::Owned(p)
}
}
impl<'a> From<&'a Package> for PackageRef<'a> {
fn from(p: &'a Package) -> Self {
PackageRef::Ref(p)
}
}
/// A repository blob encryption key.
pub struct BlobEncryptionKey([u8; 32]);
impl BlobEncryptionKey {
/// Returns a slice of all bytes in the key.
pub fn as_bytes(&self) -> &[u8] {
&self.0[..]
}
}
impl fmt::Debug for BlobEncryptionKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("BlobEncryptionKey").field(&hex::encode(self.as_bytes())).finish()
}
}
/// Metadata for a package contained within a [`Repository`].
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq)]
pub struct PackageEntry {
path: String,
meta_far_merkle: Hash,
meta_far_size: usize,
}
fn iter_packages(
reader: impl Read,
) -> Result<impl Iterator<Item = Result<PackageEntry, Error>>, Error> {
// TODO when metadata is compatible, use rust-tuf instead.
#[derive(Debug, Deserialize)]
struct TargetsJson {
signed: Targets,
}
#[derive(Debug, Deserialize)]
struct Targets {
targets: BTreeMap<String, Target>,
}
#[derive(Debug, Deserialize)]
struct Target {
custom: TargetCustom,
}
#[derive(Debug, Deserialize)]
struct TargetCustom {
merkle: String,
size: usize,
}
let targets_json: TargetsJson = serde_json::from_reader(reader)?;
Ok(targets_json.signed.targets.into_iter().map(|(path, target)| {
Ok(PackageEntry {
path,
meta_far_merkle: target.custom.merkle.parse()?,
meta_far_size: target.custom.size,
})
}))
}
/// A TUF repository generated by a [`RepositoryBuilder`].
#[derive(Debug)]
pub struct Repository {
dir: TempDir,
encryption_key: Option<BlobEncryptionKey>,
}
impl Repository {
/// Returns an iterator over all blobs contained in this repository.
pub fn iter_blobs(&self) -> Result<impl Iterator<Item = Result<Hash, Error>>, io::Error> {
Ok(fs::read_dir(self.dir.path().join("repository/blobs"))?.map(|entry| {
Ok(entry?
.file_name()
.to_str()
.ok_or_else(|| format_err!("non-utf8 file path"))?
.parse()?)
}))
}
/// Returns a set of all blobs contained in this repository.
pub fn list_blobs(&self) -> Result<BTreeSet<Hash>, Error> {
self.iter_blobs()?.collect()
}
/// Reads the contents of requested blob from the repository.
pub fn read_blob(&self, merkle_root: &Hash) -> Result<Vec<u8>, io::Error> {
fs::read(self.dir.path().join(format!("repository/blobs/{}", merkle_root)))
}
/// Returns the path of the base of the repository.
pub fn path(&self) -> PathBuf {
self.dir.path().join("repository")
}
/// Returns an iterator over all packages contained in this repository.
pub fn iter_packages(
&self,
) -> Result<impl Iterator<Item = Result<PackageEntry, Error>>, Error> {
iter_packages(io::BufReader::new(File::open(
self.dir.path().join("repository/targets.json"),
)?))
}
/// Returns a sorted vector of all packages contained in this repository.
pub fn list_packages(&self) -> Result<Vec<PackageEntry>, Error> {
let mut packages = self.iter_packages()?.collect::<Result<Vec<_>, _>>()?;
packages.sort_unstable();
Ok(packages)
}
/// Generate a [`RepositoryConfig`] suitable for configuring a package resolver to use this
/// repository when it is served at the given URL.
pub fn make_repo_config(&self, url: RepoUrl, mirror_url: String) -> RepositoryConfig {
let mut builder = RepositoryConfigBuilder::new(url);
for key in self.root_keys() {
builder = builder.add_root_key(key);
}
let mut mirror = MirrorConfigBuilder::new(mirror_url).subscribe(false);
if let Some(ref key) = self.encryption_key {
mirror = mirror.blob_key(RepositoryBlobKey::Aes(key.as_bytes().to_vec()))
}
builder.add_mirror(mirror.build()).build()
}
fn root_keys(&self) -> BTreeSet<RepositoryKey> {
// TODO when metadata is compatible, use rust-tuf instead.
#[derive(Debug, Deserialize)]
struct RootJson {
signed: Root,
}
#[derive(Debug, Deserialize)]
struct Root {
roles: BTreeMap<String, Role>,
keys: BTreeMap<String, Key>,
}
#[derive(Debug, Deserialize)]
struct Role {
keyids: Vec<String>,
}
#[derive(Debug, Deserialize)]
struct Key {
keyval: KeyVal,
}
#[derive(Debug, Deserialize)]
struct KeyVal {
public: String,
}
let root_json: RootJson = serde_json::from_reader(io::BufReader::new(
File::open(self.dir.path().join("repository/root.json")).unwrap(),
))
.unwrap();
let root = root_json.signed;
root.roles["root"]
.keyids
.iter()
.map(|keyid| {
RepositoryKey::Ed25519(hex::decode(root.keys[keyid].keyval.public.clone()).unwrap())
})
.collect()
}
/// Serves the repository over HTTP using hyper.
pub fn build_server(self: Arc<Self>) -> ServedRepositoryBuilder {
ServedRepositoryBuilder::new(self)
}
/// Serves the repository over HTTP.
pub async fn serve<'a>(
&'a self,
launcher: &'_ LauncherProxy,
) -> Result<ServedRepository<'a>, Error> {
let indir = tempfile::tempdir().context("create /in")?;
let port_file_dir = tempfile::tempdir().unwrap();
let mut pm = AppBuilder::new("fuchsia-pkg://fuchsia.com/pm#meta/pm.cmx")
.stdout(Stdio::MakePipe)
.stderr(Stdio::MakePipe)
.arg("serve")
.arg("-l=127.0.0.1:0")
.arg("-f=/port-file-dir/port-file")
.add_dir_to_namespace("/port-file-dir".to_owned(), File::open(port_file_dir.path())?)?
.arg("-repo=/repo")
.add_dir_to_namespace(
"/repo".to_owned(),
File::open(self.dir.path()).context("open /repo")?,
)?;
if let Some(ref key) = self.encryption_key {
fs::write(indir.path().join("encryption.key"), key.as_bytes())?;
pm = pm.arg("-e=/in/encryption.key").add_dir_to_namespace(
"/in".to_owned(),
File::open(indir.path()).context("open /in")?,
)?;
}
let pm = pm.spawn(launcher)?;
let pm_controller = pm.controller().clone();
// Wait for "pm serve" to either create the port file (giving up after a 20 seconds) or
// exit, whichever happens first.
let wait_pm_down = pm.wait_with_output();
// Under high load, a fast retry timeout can prevent pm from starting up. Start out fast,
// but slow down if pm doesn't come up quickly.
let backoff = std::iter::repeat(Duration::from_millis(250))
.take(4)
.chain(std::iter::repeat(Duration::from_millis(500)).take(4))
.chain(std::iter::repeat(Duration::from_millis(1000)));
let port_file_dir_path = port_file_dir.path();
let wait_pm_up = fuchsia_backoff::retry_or_last_error(backoff, || {
async move {
match fs::read_to_string(port_file_dir_path.join("port-file")) {
Ok(port) => {
return Ok(port.parse::<u16>().unwrap_or_else(|e| {
panic!("invalid port string {:?}: {:?}", port, e)
}));
}
Err(e) => {
return Err(e.into());
}
}
}
})
.on_timeout(20.seconds().after_now(), || {
bail!("timed out waiting for 'pm serve' to create port file")
})
.boxed();
let (wait_pm_down, port) = match future::select(wait_pm_up, wait_pm_down).await {
future::Either::Left((res, wait_pm_down)) => match res {
Err(e) => {
pm_controller.kill().unwrap();
let output = wait_pm_down.await.unwrap().ok();
panic!(
"'pm serve' took too long to create the port file {:?}\n{:?}",
e, output
);
}
Ok(port) => (wait_pm_down.boxed(), port),
},
future::Either::Right((output, _)) => {
let output = output.unwrap().ok();
panic!("'pm serve' exited too soon {:?}", output,);
}
};
Ok(ServedRepository { repo: self, port, _indir: indir, pm: pm_controller, wait_pm_down })
}
}
/// A repository that is being served over HTTP. When dropped, the server will be stopped.
pub struct ServedRepository<'a> {
repo: &'a Repository,
port: u16,
_indir: TempDir,
pm: ComponentControllerProxy,
wait_pm_down: BoxFuture<'a, Result<Output, Error>>,
}
impl<'a> ServedRepository<'a> {
/// Request the given path served by the repository over HTTP.
pub async fn get(&self, path: impl AsRef<str>) -> Result<Vec<u8>, Error> {
let url = format!("http://127.0.0.1:{}/{}", self.port, path.as_ref());
get(url).await
}
/// Returns a sorted vector of all packages contained in this repository.
pub async fn list_packages(&self) -> Result<Vec<PackageEntry>, Error> {
let targets_json = self.get("targets.json").await?;
let mut packages =
iter_packages(Cursor::new(targets_json))?.collect::<Result<Vec<_>, _>>()?;
packages.sort_unstable();
Ok(packages)
}
/// Returns the URL that can be used to connect to this repository from this device.
pub fn local_url(&self) -> String {
format!("http://127.0.0.1:{}", self.port)
}
/// Generate a [`RepositoryConfig`] suitable for configuring a package resolver to use this
/// served repository.
pub fn make_repo_config(&self, url: RepoUrl) -> RepositoryConfig {
self.repo.make_repo_config(url, self.local_url())
}
/// Kill the pm component and wait for it to exit.
pub async fn stop(self) {
self.pm.kill().expect("pm to have been running");
self.wait_pm_down.await.expect("pm to exit");
}
}
pub(crate) async fn get(url: impl AsRef<str>) -> Result<Vec<u8>, Error> {
let request = Request::get(url.as_ref()).body(Body::empty()).map_err(|e| Error::from(e))?;
let client = fuchsia_hyper::new_client();
let response = client.request(request).compat().await?;
if response.status() != StatusCode::OK {
bail!("unexpected status code: {:?}", response.status());
}
let body = response.into_body().compat().try_concat().await?.collect();
Ok(body)
}
#[cfg(test)]
mod tests {
use {super::*, crate::package::PackageBuilder, fuchsia_merkle::MerkleTree, serde_json::Value};
#[fuchsia_async::run_singlethreaded(test)]
async fn test_repo_builder() -> Result<(), Error> {
let same_contents = "same contents";
let repo = RepositoryBuilder::new()
.add_package(
PackageBuilder::new("rolldice")
.add_resource_at("bin/rolldice", "#!/boot/bin/sh\necho 4\n".as_bytes())
.add_resource_at(
"meta/rolldice.cmx",
r#"{"program":{"binary":"bin/rolldice"}}"#.as_bytes(),
)
.add_resource_at("data/duplicate_a", "same contents".as_bytes())
.build()
.await?,
)
.add_package(
PackageBuilder::new("fortune")
.add_resource_at(
"bin/fortune",
"#!/boot/bin/sh\necho ask again later\n".as_bytes(),
)
.add_resource_at(
"meta/fortune.cmx",
r#"{"program":{"binary":"bin/fortune"}}"#.as_bytes(),
)
.add_resource_at("data/duplicate_b", same_contents.as_bytes())
.add_resource_at("data/duplicate_c", same_contents.as_bytes())
.build()
.await?,
)
.build()
.await?;
let blobs = repo.list_blobs()?;
// 2 meta FARs, 2 binaries, and 1 duplicated resource
assert_eq!(blobs.len(), 5);
// Spot check the contents of a blob in the repo.
let same_contents_merkle = MerkleTree::from_reader(same_contents.as_bytes())?.root();
assert_eq!(repo.read_blob(&same_contents_merkle)?.as_slice(), same_contents.as_bytes());
let packages = repo.list_packages()?;
assert_eq!(packages.len(), 2);
assert_eq!(
packages.into_iter().map(|pkg| pkg.path).collect::<Vec<_>>(),
vec!["fortune/0".to_owned(), "rolldice/0".to_owned()]
);
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_repo_encryption() -> Result<(), Error> {
let message = "Hello World!".as_bytes();
let repo = RepositoryBuilder::new()
.add_package(
PackageBuilder::new("tiny")
.add_resource_at("data/message", message)
.build()
.await?,
)
.set_encryption_key(BlobEncryptionKey([
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
0xee, 0xff, 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44,
0x33, 0x22, 0x11, 0x00,
]))
.build()
.await?;
// No blob in the repo should contain `message`.
for blob in repo.iter_blobs()? {
let blob = blob?;
assert_ne!(repo.read_blob(&blob)?, message);
}
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_repo_builder_template() -> Result<(), Error> {
let repodir = tempfile::tempdir().context("create tempdir")?;
// Populate repodir with a freshly created repository.
AppBuilder::new("fuchsia-pkg://fuchsia.com/pm#meta/pm.cmx")
.arg("newrepo")
.arg("-repo=/repo")
.add_dir_to_namespace(
"/repo".to_owned(),
File::open(repodir.path()).context("open /repo")?,
)?
.output(&launcher()?)?
.await?
.ok()?;
// Build a repo from the template.
let repo = RepositoryBuilder::from_template_dir(repodir.path())
.add_package(PackageBuilder::new("test").build().await?)
.build()
.await?;
// Ensure the repository used the generated keys.
for path in &["root.json", "snapshot.json", "timestamp.json", "targets.json"] {
assert_eq!(
fs::read(repodir.path().join("keys").join(path))?,
fs::read(repo.dir.path().join("keys").join(path))?,
);
}
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_serve_empty() -> Result<(), Error> {
let repo = RepositoryBuilder::new().build().await?;
let launcher = launcher().unwrap();
let served_repo = repo.serve(&launcher).await?;
let packages = served_repo.list_packages().await?;
assert_eq!(packages, vec![]);
Ok(())
}
#[fuchsia_async::run_singlethreaded(test)]
async fn test_serve_packages() -> Result<(), Error> {
let same_contents = "same contents";
let repo = RepositoryBuilder::new()
.add_package(
PackageBuilder::new("rolldice")
.add_resource_at("bin/rolldice", "#!/boot/bin/sh\necho 4\n".as_bytes())
.add_resource_at(
"meta/rolldice.cmx",
r#"{"program":{"binary":"bin/rolldice"}}"#.as_bytes(),
)
.add_resource_at("data/duplicate_a", "same contents".as_bytes())
.build()
.await?,
)
.add_package(
PackageBuilder::new("fortune")
.add_resource_at(
"bin/fortune",
"#!/boot/bin/sh\necho ask again later\n".as_bytes(),
)
.add_resource_at(
"meta/fortune.cmx",
r#"{"program":{"binary":"bin/fortune"}}"#.as_bytes(),
)
.add_resource_at("data/duplicate_b", same_contents.as_bytes())
.add_resource_at("data/duplicate_c", same_contents.as_bytes())
.build()
.await?,
)
.build()
.await?;
let launcher = launcher().unwrap();
let served_repository = repo.serve(&launcher).await?;
let local_packages = repo.list_packages()?;
let served_packages = served_repository.list_packages().await?;
assert_eq!(local_packages, served_packages);
let config_json = String::from_utf8(served_repository.get("config.json").await?)?;
let config: Value = serde_json::from_str(config_json.as_str())?;
let base_url = format!("http://127.0.0.1:{}", served_repository.port);
assert_eq!(
config.get("id").or_else(|| config.get("ID")),
Some(Value::String(base_url)).as_ref()
);
Ok(())
}
}
|
use structopt::StructOpt;
use super::{CliCommand, GlobalFlags};
pub const AFTER_HELP: &str = r#"EXAMPLES:
To list all installed packages:
$ deck list
To list all installed packages with the prefix "emacs":
$ deck list emacs
"#;
#[derive(Debug, StructOpt)]
pub struct List {
/// Profile to list packages from
#[structopt(
short = "p",
long = "profile",
empty_values = false,
value_name = "PROFILE_NAME"
)]
profile: Option<String>,
/// Regular expression for filtering package names
#[structopt(value_name = "PATTERN")]
pattern: Option<String>,
}
impl CliCommand for List {
fn run(self, _flags: GlobalFlags) -> Result<(), String> {
unimplemented!()
}
}
|
use crate::prelude::*;
use std::collections::HashMap;
pub fn try_load_scene(scene_path: &str) -> Result<PackedScene, String> {
if let Some(scene) = ResourceLoader::godot_singleton().load(
GodotString::from_str(format!("res://scenes/{}.tscn", scene_path)),
GodotString::from_str("PackedScene"),
false,
) {
if let Some(scene) = scene.cast::<PackedScene>() {
return Ok(scene);
} else {
return Err(format!("Could not cast {} to PackedScene", scene_path));
}
} else {
return Err(format!("Could not find {}", scene_path));
}
}
pub fn load_scene(scene_path: &str) -> PackedScene {
match try_load_scene(scene_path) {
Err(e) => panic!(e),
Ok(template) => template,
}
}
pub struct Wrapper<T> {
pub inner: T
}
unsafe impl<T> Sync for Wrapper<T> {}
unsafe impl<T> Send for Wrapper<T> {}
pub struct RPopsEngine<T> where
T: Eq + std::hash::Hash + 'static {
pub universe: Universe,
pub world: LWorld,
pub resources: Resources,
pub executor: Executor,
pub event_receiver: crossbeam_channel::Receiver<legion::event::Event>,
phantom: std::marker::PhantomData<T>,
}
impl<T> RPopsEngine<T>
where
T: Eq + std::hash::Hash {
pub fn new(_owner: Node) -> Self {
let universe = Universe::new();
let mut world = universe.create_world();
let mut resources = Resources::default();
resources.insert(Wrapper { inner: HashMap::<Entity, Node>::new() } );
let executor = Executor::new(vec![]);
let (sender, receiver) = crossbeam_channel::unbounded();
world.subscribe(sender, any());
RPopsEngine {
universe,
world,
resources,
executor,
event_receiver: receiver,
phantom: std::marker::PhantomData,
}
}
pub fn _ready(&mut self, _owner: Node) {
}
pub fn _physics_process(&mut self, mut owner: Node, _delta: f64) {
self.executor.execute(&mut self.world, &mut self.resources);
// Add and remove entities from hashmap
for event in self.event_receiver.try_iter() {
match event {
legion::event::Event::EntityRemoved(e, _) => {
if let None = self.world.get_component::<GDSpatial>(e) {
if let Some(mut wrapped) = self.resources.get_mut::<Wrapper<HashMap<Entity, Node>>>() {
// Remove from hashmap
if let Some(node) = wrapped.inner.get_mut(&e) {
unsafe { node.free() };
wrapped.inner.remove(&e);
godot_print!("Stopped syncing from entity: {:?} to node", e.index())
}
}
}
},
legion::event::Event::EntityInserted(e, _) => {
if let Some(_) = self.world.get_component::<GDSpatial>(e) {
// Add to hashmap if not already in there
if let Some(mut wrapped) = self.resources.get_mut::<Wrapper<HashMap<Entity, Node>>>() {
if !wrapped.inner.contains_key(&e) {
if let Some(renderable) = self.world.get_component::<Renderable>(e) {
if let Some(models) = self.resources.get::<Models<T>>() {
if let Some(packed_scene) = (*models).scene_from_index(renderable.index) {
unsafe {
let mut instance = packed_scene.instance(0).unwrap().cast::<Node>().unwrap();
instance.set_name(GodotString::from_str("Node"));
owner.add_child(Some(instance), true);
wrapped.inner.insert(e, instance);
godot_print!("Started syncing from entity: {:?} to node", e.index());
}
}
}
}
}
}
}
},
_ => (),
};
}
// Query on changed components to update node positions
let query = <(Read<Position>, Read<GDSpatial>)>::query()
.filter(changed::<Position>());
if let Some(mut wrapped) = self.resources.get_mut::<Wrapper<HashMap<Entity, Node>>>() {
for (entity, (pos, _)) in query.iter_entities(&mut self.world) {
if let Some(node) = wrapped.inner.get_mut(&entity) {
// Calls to godot are inherently unsafe
if let Some(mut spatial) = unsafe { node.cast::<Spatial>() } {
// Position
let mut transform = unsafe { spatial.get_translation() };
transform.x = pos.x as f32;
transform.y = pos.y as f32;
unsafe { spatial.set_translation(transform) };
// Rotation
let mut rotation = unsafe { spatial.get_rotation() };
rotation.y = pos.rotation.get();
unsafe { spatial.set_rotation(rotation) };
} else if let Some(mut node2D) = unsafe { node.cast::<Node2D>() } {
let mut position = unsafe { node2D.get_position() };
position.x = pos.x as f32;
position.y = pos.y as f32;
unsafe { node2D.set_position(position) };
unsafe { node2D.set_rotation(pos.rotation.get() as f64) };
}
}
}
}
// Update animation
let query = <(Read<GDSpatial>, Read<Renderable>)>::query();
if let Some(mut wrapped) = self.resources.get_mut::<Wrapper<HashMap<Entity, Node>>>() {
for (entity, (_, renderable)) in query.iter_entities(&mut self.world) {
if let Some(node) = wrapped.inner.get_mut(&entity) {
if let Some(mut node) = unsafe { node.cast::<Node>() } {
match renderable.template {
Template::ASprite(state) => {
if let Some(mut sprite) = get_animator::<AnimatedSprite>(node) {
// Update node from state
unsafe {
sprite._set_playing(state.playing);
let gd_string = GodotString::from(state.animation);
sprite.play(gd_string, false);
sprite.set_flip_h(state.flip_h);
sprite.set_flip_v(state.flip_v);
}
}
},
Template::APlayer(state) => {
if let Some(sprite) = get_animator::<AnimationTree>(node) {
// Update node from state
}
},
Template::ATree(state) => {
if let Some(sprite) = get_animator::<AnimationTree>(node) {
// Update node from state
}
},
_ => {}
}
}
}
}
}
}
pub fn _input(_owner: Node, _event: Option<InputEvent>) {
}
pub fn set_systems(&mut self, systems: Vec<Box<dyn Schedulable>>) {
self.executor = Executor::new(systems);
}
}
pub(crate) fn get_animator<T>(node: Node) -> Option<T>
where T: GodotObject {
let mut i = 0;
loop {
if let Some(child_node) = unsafe { node.get_child(i) } {
if let Some(child_node) = unsafe { child_node.cast::<T>() } {
return Some(child_node);
}
} else {
return None;
}
i += 1;
}
None
} |
/// Recognises an alphabetic character, `a-zA-Z`.
#[inline]
pub fn alpha(term: u8) -> bool {
(term >= 0x41 && term <= 0x5A) || (term >= 0x61 && term <= 0x7A)
}
/// Recognises a decimal digit, `0-9`.
#[inline]
pub fn digit(term: u8) -> bool {
term >= 0x30 && term <= 0x39
}
/// Recognises an alphanumeric character, `a-zA-Z0-9`.
#[inline]
pub fn alphanum(term: u8) -> bool {
alpha(term) || digit(term)
}
/// Recognises a hexadecimal digit, `0-9a-fA-F`.
#[inline]
pub fn hex_digit(term: u8) -> bool {
(term >= 0x30 && term <= 0x39)
|| (term >= 0x41 && term <= 0x46)
|| (term >= 0x61 && term <= 0x66)
}
/// Recognises an octal digit, `0-7`.
#[inline]
pub fn oct_digit(term: u8) -> bool {
term >= 0x30 && term <= 0x37
}
/// Recognises a space or tab.
#[inline]
pub fn space(term: u8) -> bool {
term == b' ' || term == b'\t'
}
/// Recognises a space, tab, line feed, or carriage return.
#[inline]
pub fn multispace(term: u8) -> bool {
space(term) || term == b'\n' || term == b'\r'
}
|
use failure::*;
use nine::common::CowStr;
use std::fmt::{self, Display};
/// TODO: this can be its own enum.
/// All possible protocol-level errors could be enumerated,
/// and have a single one for a custom message.
/// or maybe that could be its own serverfail variant.
#[derive(Debug)]
pub struct NonFatalError {
pub msg: CowStr,
cause: Option<Error>,
}
impl Display for NonFatalError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.msg)
}
}
impl Fail for NonFatalError {
fn cause(&self) -> Option<&Fail> {
self.cause.as_ref().map(|x| x.as_fail())
}
fn backtrace(&self) -> Option<&Backtrace> {
self.cause.as_ref().map(|x| x.backtrace())
}
}
#[derive(Debug)]
pub enum ServerFail {
/// An error message should be returned to the client,
/// but the server should continue as usual.
/// Typically used in response to client errors.
/// Could also be used if there was an error server-side
/// but the connection should not be affected
/// (e.g. an io error on a single file).
NonFatal(NonFatalError),
/// The error message will be converted to an Rerror,
/// sent, and then the server will shut down.
NotifiedFatal(Error),
/// The server will immediately shut down.
/// Nothing is sent to the client.
ImmediateFatal(Error),
}
impl Display for ServerFail {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::ServerFail::*;
match self {
NonFatal(x) => write!(f, "NonFatalError: {}", x),
NotifiedFatal(x) => write!(f, "Notified Fatal Error: {}", x),
ImmediateFatal(x) => write!(f, "Immediate Fatal Error: {}", x),
}
}
}
impl Fail for ServerFail {
fn cause(&self) -> Option<&Fail> {
use self::ServerFail::*;
match self {
NonFatal(x) => x.cause(),
NotifiedFatal(x) => Some(x.as_fail()),
ImmediateFatal(x) => Some(x.as_fail()),
}
}
fn backtrace(&self) -> Option<&Backtrace> {
use self::ServerFail::*;
match self {
NonFatal(x) => x.backtrace(),
NotifiedFatal(x) => Some(x.backtrace()),
ImmediateFatal(x) => Some(x.backtrace()),
}
}
}
pub type NineResult<T> = Result<T, ServerFail>;
pub fn rerr<T, S: Into<CowStr>>(s: S) -> NineResult<T> {
Err(ServerFail::NonFatal(NonFatalError {
msg: s.into(),
cause: None,
}))
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u8,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u8,
}
impl super::TXTYPE4 {
#[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() -> u8 {
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 USB_TXTYPE4_TEPR {
bits: u8,
}
impl USB_TXTYPE4_TEPR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _USB_TXTYPE4_TEPW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXTYPE4_TEPW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 0);
self.w.bits |= ((value as u8) & 15) << 0;
self.w
}
}
#[doc = "Possible values of the field `USB_TXTYPE4_PROTO`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USB_TXTYPE4_PROTOR {
#[doc = "Control"]
USB_TXTYPE4_PROTO_CTRL,
#[doc = "Isochronous"]
USB_TXTYPE4_PROTO_ISOC,
#[doc = "Bulk"]
USB_TXTYPE4_PROTO_BULK,
#[doc = "Interrupt"]
USB_TXTYPE4_PROTO_INT,
}
impl USB_TXTYPE4_PROTOR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
USB_TXTYPE4_PROTOR::USB_TXTYPE4_PROTO_CTRL => 0,
USB_TXTYPE4_PROTOR::USB_TXTYPE4_PROTO_ISOC => 1,
USB_TXTYPE4_PROTOR::USB_TXTYPE4_PROTO_BULK => 2,
USB_TXTYPE4_PROTOR::USB_TXTYPE4_PROTO_INT => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> USB_TXTYPE4_PROTOR {
match value {
0 => USB_TXTYPE4_PROTOR::USB_TXTYPE4_PROTO_CTRL,
1 => USB_TXTYPE4_PROTOR::USB_TXTYPE4_PROTO_ISOC,
2 => USB_TXTYPE4_PROTOR::USB_TXTYPE4_PROTO_BULK,
3 => USB_TXTYPE4_PROTOR::USB_TXTYPE4_PROTO_INT,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `USB_TXTYPE4_PROTO_CTRL`"]
#[inline(always)]
pub fn is_usb_txtype4_proto_ctrl(&self) -> bool {
*self == USB_TXTYPE4_PROTOR::USB_TXTYPE4_PROTO_CTRL
}
#[doc = "Checks if the value of the field is `USB_TXTYPE4_PROTO_ISOC`"]
#[inline(always)]
pub fn is_usb_txtype4_proto_isoc(&self) -> bool {
*self == USB_TXTYPE4_PROTOR::USB_TXTYPE4_PROTO_ISOC
}
#[doc = "Checks if the value of the field is `USB_TXTYPE4_PROTO_BULK`"]
#[inline(always)]
pub fn is_usb_txtype4_proto_bulk(&self) -> bool {
*self == USB_TXTYPE4_PROTOR::USB_TXTYPE4_PROTO_BULK
}
#[doc = "Checks if the value of the field is `USB_TXTYPE4_PROTO_INT`"]
#[inline(always)]
pub fn is_usb_txtype4_proto_int(&self) -> bool {
*self == USB_TXTYPE4_PROTOR::USB_TXTYPE4_PROTO_INT
}
}
#[doc = "Values that can be written to the field `USB_TXTYPE4_PROTO`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USB_TXTYPE4_PROTOW {
#[doc = "Control"]
USB_TXTYPE4_PROTO_CTRL,
#[doc = "Isochronous"]
USB_TXTYPE4_PROTO_ISOC,
#[doc = "Bulk"]
USB_TXTYPE4_PROTO_BULK,
#[doc = "Interrupt"]
USB_TXTYPE4_PROTO_INT,
}
impl USB_TXTYPE4_PROTOW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
USB_TXTYPE4_PROTOW::USB_TXTYPE4_PROTO_CTRL => 0,
USB_TXTYPE4_PROTOW::USB_TXTYPE4_PROTO_ISOC => 1,
USB_TXTYPE4_PROTOW::USB_TXTYPE4_PROTO_BULK => 2,
USB_TXTYPE4_PROTOW::USB_TXTYPE4_PROTO_INT => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _USB_TXTYPE4_PROTOW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXTYPE4_PROTOW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USB_TXTYPE4_PROTOW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Control"]
#[inline(always)]
pub fn usb_txtype4_proto_ctrl(self) -> &'a mut W {
self.variant(USB_TXTYPE4_PROTOW::USB_TXTYPE4_PROTO_CTRL)
}
#[doc = "Isochronous"]
#[inline(always)]
pub fn usb_txtype4_proto_isoc(self) -> &'a mut W {
self.variant(USB_TXTYPE4_PROTOW::USB_TXTYPE4_PROTO_ISOC)
}
#[doc = "Bulk"]
#[inline(always)]
pub fn usb_txtype4_proto_bulk(self) -> &'a mut W {
self.variant(USB_TXTYPE4_PROTOW::USB_TXTYPE4_PROTO_BULK)
}
#[doc = "Interrupt"]
#[inline(always)]
pub fn usb_txtype4_proto_int(self) -> &'a mut W {
self.variant(USB_TXTYPE4_PROTOW::USB_TXTYPE4_PROTO_INT)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 4);
self.w.bits |= ((value as u8) & 3) << 4;
self.w
}
}
#[doc = "Possible values of the field `USB_TXTYPE4_SPEED`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USB_TXTYPE4_SPEEDR {
#[doc = "Default"]
USB_TXTYPE4_SPEED_DFLT,
#[doc = "High"]
USB_TXTYPE4_SPEED_HIGH,
#[doc = "Full"]
USB_TXTYPE4_SPEED_FULL,
#[doc = "Low"]
USB_TXTYPE4_SPEED_LOW,
}
impl USB_TXTYPE4_SPEEDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
USB_TXTYPE4_SPEEDR::USB_TXTYPE4_SPEED_DFLT => 0,
USB_TXTYPE4_SPEEDR::USB_TXTYPE4_SPEED_HIGH => 1,
USB_TXTYPE4_SPEEDR::USB_TXTYPE4_SPEED_FULL => 2,
USB_TXTYPE4_SPEEDR::USB_TXTYPE4_SPEED_LOW => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> USB_TXTYPE4_SPEEDR {
match value {
0 => USB_TXTYPE4_SPEEDR::USB_TXTYPE4_SPEED_DFLT,
1 => USB_TXTYPE4_SPEEDR::USB_TXTYPE4_SPEED_HIGH,
2 => USB_TXTYPE4_SPEEDR::USB_TXTYPE4_SPEED_FULL,
3 => USB_TXTYPE4_SPEEDR::USB_TXTYPE4_SPEED_LOW,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `USB_TXTYPE4_SPEED_DFLT`"]
#[inline(always)]
pub fn is_usb_txtype4_speed_dflt(&self) -> bool {
*self == USB_TXTYPE4_SPEEDR::USB_TXTYPE4_SPEED_DFLT
}
#[doc = "Checks if the value of the field is `USB_TXTYPE4_SPEED_HIGH`"]
#[inline(always)]
pub fn is_usb_txtype4_speed_high(&self) -> bool {
*self == USB_TXTYPE4_SPEEDR::USB_TXTYPE4_SPEED_HIGH
}
#[doc = "Checks if the value of the field is `USB_TXTYPE4_SPEED_FULL`"]
#[inline(always)]
pub fn is_usb_txtype4_speed_full(&self) -> bool {
*self == USB_TXTYPE4_SPEEDR::USB_TXTYPE4_SPEED_FULL
}
#[doc = "Checks if the value of the field is `USB_TXTYPE4_SPEED_LOW`"]
#[inline(always)]
pub fn is_usb_txtype4_speed_low(&self) -> bool {
*self == USB_TXTYPE4_SPEEDR::USB_TXTYPE4_SPEED_LOW
}
}
#[doc = "Values that can be written to the field `USB_TXTYPE4_SPEED`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USB_TXTYPE4_SPEEDW {
#[doc = "Default"]
USB_TXTYPE4_SPEED_DFLT,
#[doc = "High"]
USB_TXTYPE4_SPEED_HIGH,
#[doc = "Full"]
USB_TXTYPE4_SPEED_FULL,
#[doc = "Low"]
USB_TXTYPE4_SPEED_LOW,
}
impl USB_TXTYPE4_SPEEDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
USB_TXTYPE4_SPEEDW::USB_TXTYPE4_SPEED_DFLT => 0,
USB_TXTYPE4_SPEEDW::USB_TXTYPE4_SPEED_HIGH => 1,
USB_TXTYPE4_SPEEDW::USB_TXTYPE4_SPEED_FULL => 2,
USB_TXTYPE4_SPEEDW::USB_TXTYPE4_SPEED_LOW => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _USB_TXTYPE4_SPEEDW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXTYPE4_SPEEDW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USB_TXTYPE4_SPEEDW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Default"]
#[inline(always)]
pub fn usb_txtype4_speed_dflt(self) -> &'a mut W {
self.variant(USB_TXTYPE4_SPEEDW::USB_TXTYPE4_SPEED_DFLT)
}
#[doc = "High"]
#[inline(always)]
pub fn usb_txtype4_speed_high(self) -> &'a mut W {
self.variant(USB_TXTYPE4_SPEEDW::USB_TXTYPE4_SPEED_HIGH)
}
#[doc = "Full"]
#[inline(always)]
pub fn usb_txtype4_speed_full(self) -> &'a mut W {
self.variant(USB_TXTYPE4_SPEEDW::USB_TXTYPE4_SPEED_FULL)
}
#[doc = "Low"]
#[inline(always)]
pub fn usb_txtype4_speed_low(self) -> &'a mut W {
self.variant(USB_TXTYPE4_SPEEDW::USB_TXTYPE4_SPEED_LOW)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 6);
self.w.bits |= ((value as u8) & 3) << 6;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
#[doc = "Bits 0:3 - Target Endpoint Number"]
#[inline(always)]
pub fn usb_txtype4_tep(&self) -> USB_TXTYPE4_TEPR {
let bits = ((self.bits >> 0) & 15) as u8;
USB_TXTYPE4_TEPR { bits }
}
#[doc = "Bits 4:5 - Protocol"]
#[inline(always)]
pub fn usb_txtype4_proto(&self) -> USB_TXTYPE4_PROTOR {
USB_TXTYPE4_PROTOR::_from(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bits 6:7 - Operating Speed"]
#[inline(always)]
pub fn usb_txtype4_speed(&self) -> USB_TXTYPE4_SPEEDR {
USB_TXTYPE4_SPEEDR::_from(((self.bits >> 6) & 3) as u8)
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u8) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:3 - Target Endpoint Number"]
#[inline(always)]
pub fn usb_txtype4_tep(&mut self) -> _USB_TXTYPE4_TEPW {
_USB_TXTYPE4_TEPW { w: self }
}
#[doc = "Bits 4:5 - Protocol"]
#[inline(always)]
pub fn usb_txtype4_proto(&mut self) -> _USB_TXTYPE4_PROTOW {
_USB_TXTYPE4_PROTOW { w: self }
}
#[doc = "Bits 6:7 - Operating Speed"]
#[inline(always)]
pub fn usb_txtype4_speed(&mut self) -> _USB_TXTYPE4_SPEEDW {
_USB_TXTYPE4_SPEEDW { w: self }
}
}
|
extern crate handlebars;
#[macro_use]
extern crate serde_json;
use handlebars::Handlebars;
#[test]
fn test_subexpression() {
let hbs = Handlebars::new();
let data = json!({"a": 1, "b": 0, "c": 2});
assert_eq!(
hbs.render_template("{{#if (gt a b)}}Success{{else}}Failed{{/if}}", &data)
.unwrap(),
"Success"
);
assert_eq!(
hbs.render_template("{{#if (gt a c)}}Success{{else}}Failed{{/if}}", &data)
.unwrap(),
"Failed"
);
assert_eq!(
hbs.render_template("{{#if (not (gt a c))}}Success{{else}}Failed{{/if}}", &data)
.unwrap(),
"Success"
);
assert_eq!(
hbs.render_template("{{#if (not (gt a b))}}Success{{else}}Failed{{/if}}", &data)
.unwrap(),
"Failed"
);
// no argument provided for not
assert_eq!(
hbs.render_template("{{#if (not)}}Success{{else}}Failed{{/if}}", &data)
.unwrap(),
"Failed"
);
// json literal
assert_eq!(
hbs.render_template("{{#if (not true)}}Success{{else}}Failed{{/if}}", &data)
.unwrap(),
"Failed"
);
assert_eq!(
hbs.render_template("{{#if (not false)}}Success{{else}}Failed{{/if}}", &data)
.unwrap(),
"Success"
);
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Services_Cortana")]
pub mod Cortana;
#[cfg(feature = "Services_Maps")]
pub mod Maps;
#[cfg(feature = "Services_Store")]
pub mod Store;
#[cfg(feature = "Services_TargetedContent")]
pub mod TargetedContent;
|
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Config {
build_group: Option<String>,
max_builds: Option<u32>,
trusted_users: Option<Vec<String>>,
}
|
use tic_tac_toe::{ TicTacToe, TicTacToeGame, PlayerType, GameState };
use std::io::{ stdin, stdout, Write};
trait PrintBoard {
fn print_board(&self);
}
impl PrintBoard for TicTacToeGame {
fn print_board(&self) {
let board = self.board();
for i in (0..9).step_by(3) {
println!("{}{}{}", board[i], board[i + 1], board[i + 2]);
}
}
}
fn main() {
let state = TicTacToe::from_state(0b__000_000_000, 0b__000_000_000);
let mut game = TicTacToeGame::continue_from(state, PlayerType::Cross, true);
loop {
game.print_board();
let mut input = String::new();
print!("Enter your next move: ");
stdout().flush().unwrap();
stdin()
.read_line(&mut input)
.expect("Failed to read line");
let index: u32 = match input.trim().parse() {
Ok(num) => {
if num < 9 {
num
} else {
println!("Must be a number from 0..=9, try Again");
continue;
}
},
Err(_) => {
println!("Not a number, try Again");
continue;
},
};
game.do_move(index);
match game.state() {
GameState::NoughtWins(_) => {
println!("Nought Wins");
},
GameState::CrossWins(_) => {
println!("Cross Wins");
},
GameState::Draw => {
println!("Draw");
}
GameState::InProgress => continue
}
game.print_board();
game = TicTacToeGame::new(PlayerType::Cross, true);
println!("Game is reset");
}
}
|
use brace_hook::{hook, register};
#[hook]
fn my_hook(input: &str) -> String {}
#[hook(my_hook)]
fn hook_1(input: &str) -> String {
format!("hook_1: {}", input)
}
fn hook_2(input: &str) -> String {
format!("hook_2: {}", input)
}
fn hook_3(input: &str) -> String {
format!("hook_3: {}", input)
}
register!(my_hook, hook_2);
register!(my_hook, hook_3, 0);
#[test]
fn test_hook_registration() {
let res = my_hook::with("hello");
assert_eq!(res.len(), 3);
let res: Vec<String> = res.collect();
assert!(res.contains(&String::from("hook_1: hello")));
assert!(res.contains(&String::from("hook_2: hello")));
assert!(res.contains(&String::from("hook_3: hello")));
}
#[hook]
fn empty() {}
#[hook(empty)]
fn empty_1() {}
#[test]
fn test_hook_without_args() {
assert_eq!(empty::with().len(), 1);
}
#[hook]
fn unused() {}
#[test]
fn test_hook_without_impls() {
assert_eq!(unused::with().len(), 0);
}
#[hook]
fn weighted() -> &'static str {}
#[hook(weighted, 300)]
fn weighted_a() -> &'static str {
"a"
}
#[hook(weighted, 0)]
fn weighted_b() -> &'static str {
"b"
}
#[hook(weighted, 20)]
fn weighted_c() -> &'static str {
"c"
}
#[hook(weighted, -50)]
fn weighted_d() -> &'static str {
"d"
}
#[test]
fn test_hook_with_weights() {
let mut res = weighted::with();
assert_eq!(res.len(), 4);
assert_eq!(res.next(), Some("d"));
assert_eq!(res.next(), Some("b"));
assert_eq!(res.next(), Some("c"));
assert_eq!(res.next(), Some("a"));
assert_eq!(res.next(), None);
}
#[hook]
fn mutate(items: &mut Vec<&str>) {}
#[hook(mutate, 1)]
fn mutate_1(items: &mut Vec<&str>) {
items.push("mutate 1");
}
#[hook(mutate, 2)]
fn mutate_2(items: &mut Vec<&str>) {
items.push("mutate 2");
}
#[hook(mutate, 3)]
fn mutate_3(items: &mut Vec<&str>) {
items.push("mutate 3");
}
#[test]
fn test_hook_with_mutations() {
let mut items = Vec::new();
let res = mutate::with(&mut items);
assert_eq!(res.len(), 3);
res.for_each(drop);
assert_eq!(items.len(), 3);
assert_eq!(items[0], "mutate 1");
assert_eq!(items[1], "mutate 2");
assert_eq!(items[2], "mutate 3");
}
mod custom {
pub use brace_hook::*;
}
#[hook]
#[hook_attr(crate = custom)]
fn relocate() {}
#[hook(relocate, 1)]
#[hook_attr(crate = custom)]
fn relocated() {}
#[test]
fn test_crate_location() {
assert_eq!(relocate::with().len(), 1);
}
mod nested {
use super::hook;
#[hook]
pub fn visibility() {}
#[hook(visibility, 1)]
fn visible_1() {}
#[hook(visibility, 1)]
pub fn visible_2() {}
}
#[test]
fn test_hook_visibility() {
assert_eq!(nested::visibility::with().len(), 2);
}
#[hook]
fn hook_with_default(a: &str, b: &str) -> String {
format!("a: {}, b: {}", a, b)
}
#[test]
fn test_hook_with_default() {
let res = hook_with_default::with("one", "two");
assert_eq!(res.len(), 1);
let res: Vec<String> = res.collect();
assert_eq!(res[0], "a: one, b: two");
}
#[hook]
fn hook_with_default_unused(a: &str, b: &str) -> String {
format!("a: {}, b: {}", a, b)
}
#[hook(hook_with_default_unused)]
fn hook_with_default_unused_1(a: &str, b: &str) -> String {
format!("b: {}, a: {}", b, a)
}
#[test]
fn test_hook_with_default_unused() {
let res = hook_with_default_unused::with("one", "two");
assert_eq!(res.len(), 1);
let res: Vec<String> = res.collect();
assert_eq!(res[0], "b: two, a: one");
}
|
//! Global control
use static_assertions::const_assert_eq;
register! {
GlobalControl,
u32,
RW,
Fields [
Enable WIDTH(U1) OFFSET(U0),
]
}
register! {
GlobalStatus,
u32,
RW,
Fields [
Bits WIDTH(U32) OFFSET(U0),
]
}
register! {
GlobalDBuff,
u32,
RW,
Fields [
Enable WIDTH(U1) OFFSET(U0),
]
}
register! {
GlobalSize,
u32,
RW,
Fields [
SizeWidth WIDTH(U16) OFFSET(U0),
SizeHeight WIDTH(U16) OFFSET(U16),
]
}
const_assert_eq!(core::mem::size_of::<RegisterBlock>(), 0x1000);
/// Global control
#[repr(C)]
pub struct RegisterBlock {
pub ctrl: GlobalControl::Register, // 0x000
pub status: GlobalStatus::Register, // 0x004
pub dbuf: GlobalDBuff::Register, // 0x008
pub size: GlobalSize::Register, // 0x00C
__reserved_0: [u32; 1020], // 0x010
}
|
use front::stdlib::value::{
Value,
ResultValue
};
use std::default::Default;
/// An execution engine which runs whatever is generated by the `Compiler`
pub trait Executor<Compiled> {
/// Create a new execution engine with the given configuration
fn new(config:&ExecutorConfig) -> Self;
/// Get the global object associated with this executor
fn get_global_obj(&self) -> Value;
#[inline]
/// Get a field of the global object
fn get_global<'a>(&self, field: &'a str) -> Value {
self.get_global_obj().get_field(field)
}
#[inline]
/// Set a field of the global object
fn set_global<'a>(&self, field: &'a str, value:Value) -> Value {
self.get_global_obj().set_field(field, value)
}
/// Execute a compiled expression
fn execute(&self, comp:&Compiled) -> ResultValue;
}
/// Configuration for the executor
pub struct ExecutorConfig {
/// The initial global value
pub global: Value
}
impl Default for ExecutorConfig {
#[inline(always)]
fn default() -> ExecutorConfig {
ExecutorConfig {
global: Value::new_global()
}
}
} |
use std;
use serialize;
pub struct T<'a, R: 'a + std::io::Reader> {
reader : &'a mut R,
}
pub enum E {
Other(String)
}
impl<'a, R: std::io::Reader> T<'a, R> {
pub fn new<'b>(r: &'b mut R) -> T<'b, R> {
T { reader: r }
}
}
impl<'a, R: std::io::Reader> serialize::Decoder<E> for T<'a, R> {
fn read_nil(&mut self) -> Result<(), E> {
unimplemented!()
}
fn read_uint(&mut self) -> Result<uint, E> {
unimplemented!()
}
fn read_u64(&mut self) -> Result<u64, E> {
unimplemented!()
}
fn read_u32(&mut self) -> Result<u32, E> {
unimplemented!()
}
fn read_u16(&mut self) -> Result<u16, E> {
unimplemented!()
}
fn read_u8(&mut self) -> Result<u8, E> {
unimplemented!()
}
fn read_int(&mut self) -> Result<int, E> {
unimplemented!()
}
fn read_i64(&mut self) -> Result<i64, E> {
unimplemented!()
}
fn read_i32(&mut self) -> Result<i32, E> {
unimplemented!()
}
fn read_i16(&mut self) -> Result<i16, E> {
unimplemented!()
}
fn read_i8(&mut self) -> Result<i8, E> {
unimplemented!()
}
fn read_bool(&mut self) -> Result<bool, E> {
unimplemented!()
}
fn read_f64(&mut self) -> Result<f64, E> {
unimplemented!()
}
fn read_f32(&mut self) -> Result<f32, E> {
unimplemented!()
}
fn read_char(&mut self) -> Result<char, E> {
unimplemented!()
}
fn read_str(&mut self) -> Result<String, E> {
unimplemented!()
}
// Compound types:
fn read_enum<C>(&mut self,
_name: &str,
_f: |&mut T<'a,R>| -> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn read_enum_variant<C>(&mut self,
_names: &[&str],
_f: |&mut T<'a,R>, uint| -> Result<C,E>)
-> Result<C,E> {
unimplemented!()
}
fn read_enum_variant_arg<C>(&mut self,
_a_idx: uint,
_f: |&mut T<'a,R>| -> Result<C,E>)
-> Result<C,E> {
unimplemented!()
}
fn read_enum_struct_variant<C>(&mut self,
_names: &[&str],
_f: |&mut T<'a,R>, uint|
-> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn read_enum_struct_variant_field<C>(&mut self,
_f_name: &str,
_f_idx: uint,
_f: |&mut T<'a,R>|
-> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn read_struct<C>(&mut self,
_s_name: &str,
_len: uint,
_f: |&mut T<'a,R>| -> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn read_struct_field<C>(&mut self,
_f_name: &str,
_f_idx: uint,
_f: |&mut T<'a,R>| -> Result<C,E>)
-> Result<C,E> {
unimplemented!()
}
fn read_tuple<C>(&mut self,
_len : uint,
_f: |&mut T<'a,R>| -> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn read_tuple_arg<C>(&mut self,
_a_idx: uint,
_f: |&mut T<'a,R>| -> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn read_tuple_struct<C>(&mut self,
_s_name: &str,
_len: uint,
_f: |&mut T<'a,R>| -> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn read_tuple_struct_arg<C>(&mut self,
_a_idx: uint,
_f: |&mut T<'a,R>| -> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
// Specialized types:
fn read_option<C>(&mut self,
_f: |&mut T<'a,R>, bool| -> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn read_seq<C>(&mut self,
_f: |&mut T<'a,R>, uint| -> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn read_seq_elt<C>(&mut self,
_idx: uint,
_f: |&mut T<'a,R>| -> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn read_map<C>(&mut self,
_f: |&mut T<'a,R>, uint| -> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn read_map_elt_key<C>(&mut self,
_idx: uint,
_f: |&mut T<'a,R>| -> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn read_map_elt_val<C>(&mut self,
_idx: uint,
_f: |&mut T<'a,R>| -> Result<C,E>)
-> Result<C,E>
{
unimplemented!()
}
fn error(&mut self, err: &str) -> E {
return E::Other(String::from_str(err));
}
}
|
use coi::{container, Inject};
use criterion::{criterion_group, criterion_main, Criterion};
use std::sync::Arc;
macro_rules! make_deep_container {
($($scope_type:ident)?) => {
container! {
d1 => D1Provider$(;$scope_type)?,
d2 => D2Provider$(;$scope_type)?,
d3 => D3Provider$(;$scope_type)?,
d4 => D4Provider$(;$scope_type)?,
d5 => D5Provider$(;$scope_type)?,
d6 => D6Provider$(;$scope_type)?,
d7 => D7Provider$(;$scope_type)?,
d8 => D8Provider$(;$scope_type)?,
d9 => D9Provider$(;$scope_type)?,
d10 => D10Provider$(;$scope_type)?,
d11 => D11Provider$(;$scope_type)?,
d12 => D12Provider$(;$scope_type)?,
d13 => D13Provider$(;$scope_type)?,
d14 => D14Provider$(;$scope_type)?,
d15 => D15Provider$(;$scope_type)?,
d16 => D16Provider$(;$scope_type)?,
d17 => D17Provider$(;$scope_type)?,
d18 => D18Provider$(;$scope_type)?,
d19 => D19Provider$(;$scope_type)?,
d20 => D20Provider$(;$scope_type)?,
d21 => D21Provider$(;$scope_type)?,
d22 => D22Provider$(;$scope_type)?,
d23 => D23Provider$(;$scope_type)?,
d24 => D24Provider$(;$scope_type)?,
d25 => D25Provider$(;$scope_type)?,
d26 => D26Provider$(;$scope_type)?,
d27 => D27Provider$(;$scope_type)?,
d28 => D28Provider$(;$scope_type)?,
d29 => D29Provider$(;$scope_type)?,
d30 => D30Provider$(;$scope_type)?,
d31 => D31Provider$(;$scope_type)?,
d32 => D32Provider$(;$scope_type)?,
d33 => D33Provider$(;$scope_type)?,
d34 => D34Provider$(;$scope_type)?,
d35 => D35Provider$(;$scope_type)?,
d36 => D36Provider$(;$scope_type)?,
d37 => D37Provider$(;$scope_type)?,
d38 => D38Provider$(;$scope_type)?,
d39 => D39Provider$(;$scope_type)?,
d40 => D40Provider$(;$scope_type)?,
d41 => D41Provider$(;$scope_type)?,
d42 => D42Provider$(;$scope_type)?,
d43 => D43Provider$(;$scope_type)?,
d44 => D44Provider$(;$scope_type)?,
d45 => D45Provider$(;$scope_type)?,
d46 => D46Provider$(;$scope_type)?,
d47 => D47Provider$(;$scope_type)?,
d48 => D48Provider$(;$scope_type)?,
d49 => D49Provider$(;$scope_type)?,
d50 => D50Provider$(;$scope_type)?,
d51 => D51Provider$(;$scope_type)?,
d52 => D52Provider$(;$scope_type)?,
d53 => D53Provider$(;$scope_type)?,
d54 => D54Provider$(;$scope_type)?,
d55 => D55Provider$(;$scope_type)?,
d56 => D56Provider$(;$scope_type)?,
d57 => D57Provider$(;$scope_type)?,
d58 => D58Provider$(;$scope_type)?,
d59 => D59Provider$(;$scope_type)?,
d60 => D60Provider$(;$scope_type)?,
d61 => D61Provider$(;$scope_type)?,
d62 => D62Provider$(;$scope_type)?,
d63 => D63Provider$(;$scope_type)?,
d64 => D64Provider$(;$scope_type)?,
d65 => D65Provider$(;$scope_type)?,
d66 => D66Provider$(;$scope_type)?,
d67 => D67Provider$(;$scope_type)?,
d68 => D68Provider$(;$scope_type)?,
d69 => D69Provider$(;$scope_type)?,
d70 => D70Provider$(;$scope_type)?,
d71 => D71Provider$(;$scope_type)?,
d72 => D72Provider$(;$scope_type)?,
d73 => D73Provider$(;$scope_type)?,
d74 => D74Provider$(;$scope_type)?,
d75 => D75Provider$(;$scope_type)?,
d76 => D76Provider$(;$scope_type)?,
d77 => D77Provider$(;$scope_type)?,
d78 => D78Provider$(;$scope_type)?,
d79 => D79Provider$(;$scope_type)?,
d80 => D80Provider$(;$scope_type)?,
d81 => D81Provider$(;$scope_type)?,
d82 => D82Provider$(;$scope_type)?,
d83 => D83Provider$(;$scope_type)?,
d84 => D84Provider$(;$scope_type)?,
d85 => D85Provider$(;$scope_type)?,
d86 => D86Provider$(;$scope_type)?,
d87 => D87Provider$(;$scope_type)?,
d88 => D88Provider$(;$scope_type)?,
d89 => D89Provider$(;$scope_type)?,
d90 => D90Provider$(;$scope_type)?,
d91 => D91Provider$(;$scope_type)?,
d92 => D92Provider$(;$scope_type)?,
d93 => D93Provider$(;$scope_type)?,
d94 => D94Provider$(;$scope_type)?,
d95 => D95Provider$(;$scope_type)?,
d96 => D96Provider$(;$scope_type)?,
d97 => D97Provider$(;$scope_type)?,
d98 => D98Provider$(;$scope_type)?,
d99 => D99Provider$(;$scope_type)?,
d100 => D100Provider$(;$scope_type)?,
}
}
}
macro_rules! make_wide_container {
($($scope_type:ident)?) => {
container! {
w1 => W1Provider$(;$scope_type)?,
w2 => W2Provider$(;$scope_type)?,
w3 => W3Provider$(;$scope_type)?,
w4 => W4Provider$(;$scope_type)?,
w5 => W5Provider$(;$scope_type)?,
w6 => W6Provider$(;$scope_type)?,
w7 => W7Provider$(;$scope_type)?,
w8 => W8Provider$(;$scope_type)?,
w9 => W9Provider$(;$scope_type)?,
w10 => W10Provider$(;$scope_type)?,
w11 => W11Provider$(;$scope_type)?,
w12 => W12Provider$(;$scope_type)?,
w13 => W13Provider$(;$scope_type)?,
w14 => W14Provider$(;$scope_type)?,
w15 => W15Provider$(;$scope_type)?,
w16 => W16Provider$(;$scope_type)?,
w17 => W17Provider$(;$scope_type)?,
w18 => W18Provider$(;$scope_type)?,
w19 => W19Provider$(;$scope_type)?,
w20 => W20Provider$(;$scope_type)?,
w21 => W21Provider$(;$scope_type)?,
w22 => W22Provider$(;$scope_type)?,
w23 => W23Provider$(;$scope_type)?,
w24 => W24Provider$(;$scope_type)?,
w25 => W25Provider$(;$scope_type)?,
w26 => W26Provider$(;$scope_type)?,
w27 => W27Provider$(;$scope_type)?,
w28 => W28Provider$(;$scope_type)?,
w29 => W29Provider$(;$scope_type)?,
w30 => W30Provider$(;$scope_type)?,
w31 => W31Provider$(;$scope_type)?,
w32 => W32Provider$(;$scope_type)?,
w33 => W33Provider$(;$scope_type)?,
w34 => W34Provider$(;$scope_type)?,
w35 => W35Provider$(;$scope_type)?,
w36 => W36Provider$(;$scope_type)?,
w37 => W37Provider$(;$scope_type)?,
w38 => W38Provider$(;$scope_type)?,
w39 => W39Provider$(;$scope_type)?,
w40 => W40Provider$(;$scope_type)?,
w41 => W41Provider$(;$scope_type)?,
w42 => W42Provider$(;$scope_type)?,
w43 => W43Provider$(;$scope_type)?,
w44 => W44Provider$(;$scope_type)?,
w45 => W45Provider$(;$scope_type)?,
w46 => W46Provider$(;$scope_type)?,
w47 => W47Provider$(;$scope_type)?,
w48 => W48Provider$(;$scope_type)?,
w49 => W49Provider$(;$scope_type)?,
w50 => W50Provider$(;$scope_type)?,
w51 => W51Provider$(;$scope_type)?,
w52 => W52Provider$(;$scope_type)?,
w53 => W53Provider$(;$scope_type)?,
w54 => W54Provider$(;$scope_type)?,
w55 => W55Provider$(;$scope_type)?,
w56 => W56Provider$(;$scope_type)?,
w57 => W57Provider$(;$scope_type)?,
w58 => W58Provider$(;$scope_type)?,
w59 => W59Provider$(;$scope_type)?,
w60 => W60Provider$(;$scope_type)?,
w61 => W61Provider$(;$scope_type)?,
w62 => W62Provider$(;$scope_type)?,
w63 => W63Provider$(;$scope_type)?,
w64 => W64Provider$(;$scope_type)?,
w65 => W65Provider$(;$scope_type)?,
w66 => W66Provider$(;$scope_type)?,
w67 => W67Provider$(;$scope_type)?,
w68 => W68Provider$(;$scope_type)?,
w69 => W69Provider$(;$scope_type)?,
w70 => W70Provider$(;$scope_type)?,
w71 => W71Provider$(;$scope_type)?,
w72 => W72Provider$(;$scope_type)?,
w73 => W73Provider$(;$scope_type)?,
w74 => W74Provider$(;$scope_type)?,
w75 => W75Provider$(;$scope_type)?,
w76 => W76Provider$(;$scope_type)?,
w77 => W77Provider$(;$scope_type)?,
w78 => W78Provider$(;$scope_type)?,
w79 => W79Provider$(;$scope_type)?,
w80 => W80Provider$(;$scope_type)?,
w81 => W81Provider$(;$scope_type)?,
w82 => W82Provider$(;$scope_type)?,
w83 => W83Provider$(;$scope_type)?,
w84 => W84Provider$(;$scope_type)?,
w85 => W85Provider$(;$scope_type)?,
w86 => W86Provider$(;$scope_type)?,
w87 => W87Provider$(;$scope_type)?,
w88 => W88Provider$(;$scope_type)?,
w89 => W89Provider$(;$scope_type)?,
w90 => W90Provider$(;$scope_type)?,
w91 => W91Provider$(;$scope_type)?,
w92 => W92Provider$(;$scope_type)?,
w93 => W93Provider$(;$scope_type)?,
w94 => W94Provider$(;$scope_type)?,
w95 => W95Provider$(;$scope_type)?,
w96 => W96Provider$(;$scope_type)?,
w97 => W97Provider$(;$scope_type)?,
w98 => W98Provider$(;$scope_type)?,
w99 => W99Provider$(;$scope_type)?,
w100 => W100Provider$(;$scope_type)?,
}
}
}
fn a_simple_resolve(c: &mut Criterion) {
trait I: Inject {}
#[derive(Inject)]
#[coi(provides dyn I with S)]
struct S;
impl I for S {}
let container = container! {
s => SProvider,
};
c.bench_function("simple resolver", |b| {
b.iter(|| container.resolve::<dyn I>("s").unwrap())
});
}
fn deeply_nested_transient_dependencies(c: &mut Criterion) {
let container = make_deep_container!();
c.bench_function("deeply nested transient", |b| {
b.iter(|| container.resolve::<dyn ID1>("d1").unwrap())
});
}
fn deeply_nested_singleton_dependencies(c: &mut Criterion) {
let container = make_deep_container!(singleton);
c.bench_function("deeply nested singleton", |b| {
b.iter(|| container.resolve::<dyn ID1>("d1").unwrap())
});
}
fn deeply_nested_scoped_dependencies(c: &mut Criterion) {
let container = make_deep_container!(scoped);
c.bench_function("deeply nested scoped", |b| {
b.iter(|| container.resolve::<dyn ID1>("d1").unwrap())
});
}
fn wide_transient_dependencies(c: &mut Criterion) {
let container = make_wide_container!();
c.bench_function("wide transient", |b| {
b.iter(|| container.resolve::<dyn IW1>("w1").unwrap())
});
}
fn wide_singleton_dependencies(c: &mut Criterion) {
let container = make_wide_container!(singleton);
c.bench_function("wide singleton", |b| {
b.iter(|| container.resolve::<dyn IW1>("w1").unwrap())
});
}
fn wide_scoped_dependencies(c: &mut Criterion) {
let container = make_wide_container!(scoped);
c.bench_function("wide scoped", |b| {
b.iter(|| container.resolve::<dyn IW1>("w1").unwrap())
});
}
fn scoped_container_deeply_nested_transient_dependencies(c: &mut Criterion) {
let container = make_deep_container!();
let container = container.scoped();
c.bench_function("scoped deeply nested transient", |b| {
b.iter(|| container.resolve::<dyn ID1>("d1").unwrap())
});
}
fn scoped_container_deeply_nested_singleton_dependencies(c: &mut Criterion) {
let container = make_deep_container!(singleton);
let container = container.scoped();
c.bench_function("scoped deeply nested singleton", |b| {
b.iter(|| container.resolve::<dyn ID1>("d1").unwrap())
});
}
fn scoped_container_deeply_nested_scoped_dependencies(c: &mut Criterion) {
let container = make_deep_container!(scoped);
let container = container.scoped();
c.bench_function("scoped deeply nested scoped", |b| {
b.iter(|| container.resolve::<dyn ID1>("d1").unwrap())
});
}
fn scoped_container_wide_transient_dependencies(c: &mut Criterion) {
let container = make_wide_container!();
let container = container.scoped();
c.bench_function("scoped wide transient", |b| {
b.iter(|| container.resolve::<dyn IW1>("w1").unwrap())
});
}
fn scoped_container_wide_singleton_dependencies(c: &mut Criterion) {
let container = make_wide_container!(singleton);
let container = container.scoped();
c.bench_function("scoped wide singleton", |b| {
b.iter(|| container.resolve::<dyn IW1>("w1").unwrap())
});
}
fn scoped_container_wide_scoped_dependencies(c: &mut Criterion) {
let container = make_wide_container!(scoped);
let container = container.scoped();
c.bench_function("scoped wide scoped", |b| {
b.iter(|| container.resolve::<dyn IW1>("w1").unwrap())
});
}
fn doubly_scoped_container_deeply_nested_transient_dependencies(c: &mut Criterion) {
let container = make_deep_container!();
let container = container.scoped();
let container = container.scoped();
c.bench_function("double scoped deeply nested transient", |b| {
b.iter(|| container.resolve::<dyn ID1>("d1").unwrap())
});
}
fn doubly_scoped_container_deeply_nested_singleton_dependencies(c: &mut Criterion) {
let container = make_deep_container!(singleton);
let container = container.scoped();
let container = container.scoped();
c.bench_function("double scoped deeply nested singleton", |b| {
b.iter(|| container.resolve::<dyn ID1>("d1").unwrap())
});
}
fn doubly_scoped_container_deeply_nested_scoped_dependencies(c: &mut Criterion) {
let container = make_deep_container!(scoped);
let container = container.scoped();
let container = container.scoped();
c.bench_function("double scoped deeply nested scoped", |b| {
b.iter(|| container.resolve::<dyn ID1>("d1").unwrap())
});
}
fn doubly_scoped_container_wide_transient_dependencies(c: &mut Criterion) {
let container = make_wide_container!();
let container = container.scoped();
let container = container.scoped();
c.bench_function("double scoped wide transient", |b| {
b.iter(|| container.resolve::<dyn IW1>("w1").unwrap())
});
}
fn doubly_scoped_container_wide_singleton_dependencies(c: &mut Criterion) {
let container = make_wide_container!(singleton);
let container = container.scoped();
let container = container.scoped();
c.bench_function("double scoped wide singleton", |b| {
b.iter(|| container.resolve::<dyn IW1>("w1").unwrap())
});
}
fn doubly_scoped_container_wide_scoped_dependencies(c: &mut Criterion) {
let container = make_wide_container!(scoped);
let container = container.scoped();
let container = container.scoped();
c.bench_function("double scoped wide scoped", |b| {
b.iter(|| container.resolve::<dyn IW1>("w1").unwrap())
});
}
criterion_group!(simple, a_simple_resolve);
criterion_group!(
deeply_nested,
deeply_nested_transient_dependencies,
deeply_nested_singleton_dependencies,
deeply_nested_scoped_dependencies
);
criterion_group!(
wide,
wide_transient_dependencies,
wide_singleton_dependencies,
wide_scoped_dependencies
);
criterion_group!(
scoped_deeply_nested,
scoped_container_deeply_nested_transient_dependencies,
scoped_container_deeply_nested_singleton_dependencies,
scoped_container_deeply_nested_scoped_dependencies
);
criterion_group!(
scoped_wide,
scoped_container_wide_transient_dependencies,
scoped_container_wide_singleton_dependencies,
scoped_container_wide_scoped_dependencies
);
criterion_group!(
double_scoped_deeply_nested,
doubly_scoped_container_deeply_nested_transient_dependencies,
doubly_scoped_container_deeply_nested_singleton_dependencies,
doubly_scoped_container_deeply_nested_scoped_dependencies
);
criterion_group!(
double_scoped_wide,
doubly_scoped_container_wide_transient_dependencies,
doubly_scoped_container_wide_singleton_dependencies,
doubly_scoped_container_wide_scoped_dependencies
);
criterion_main!(
simple,
deeply_nested,
wide,
scoped_deeply_nested,
scoped_wide,
double_scoped_deeply_nested,
double_scoped_wide
);
macro_rules! make_dep {
($trait:ident, $struct:ident, [$($dep_name:ident => $dep_trait:ident),*]) => {
trait $trait: Inject {}
#[allow(dead_code)]
#[derive(Inject)]
#[coi(provides dyn $trait with $struct::new($($dep_name),*))]
struct $struct {
$(
#[coi(inject)]
$dep_name: Arc<dyn $dep_trait>,
)*
}
impl $struct {
fn new($($dep_name: Arc<dyn $dep_trait>),*) -> Self {
Self { $($dep_name,)* }
}
}
impl $trait for $struct {}
}
}
make_dep!(ID1, D1, [d2 => ID2]);
make_dep!(ID2, D2, [d3 => ID3]);
make_dep!(ID3, D3, [d4 => ID4]);
make_dep!(ID4, D4, [d5 => ID5]);
make_dep!(ID5, D5, [d6 => ID6]);
make_dep!(ID6, D6, [d7 => ID7]);
make_dep!(ID7, D7, [d8 => ID8]);
make_dep!(ID8, D8, [d9 => ID9]);
make_dep!(ID9, D9, [d10 => ID10]);
make_dep!(ID10, D10, [d11 => ID11]);
make_dep!(ID11, D11, [d12 => ID12]);
make_dep!(ID12, D12, [d13 => ID13]);
make_dep!(ID13, D13, [d14 => ID14]);
make_dep!(ID14, D14, [d15 => ID15]);
make_dep!(ID15, D15, [d16 => ID16]);
make_dep!(ID16, D16, [d17 => ID17]);
make_dep!(ID17, D17, [d18 => ID18]);
make_dep!(ID18, D18, [d19 => ID19]);
make_dep!(ID19, D19, [d20 => ID20]);
make_dep!(ID20, D20, [d21 => ID21]);
make_dep!(ID21, D21, [d22 => ID22]);
make_dep!(ID22, D22, [d23 => ID23]);
make_dep!(ID23, D23, [d24 => ID24]);
make_dep!(ID24, D24, [d25 => ID25]);
make_dep!(ID25, D25, [d26 => ID26]);
make_dep!(ID26, D26, [d27 => ID27]);
make_dep!(ID27, D27, [d28 => ID28]);
make_dep!(ID28, D28, [d29 => ID29]);
make_dep!(ID29, D29, [d30 => ID30]);
make_dep!(ID30, D30, [d31 => ID31]);
make_dep!(ID31, D31, [d32 => ID32]);
make_dep!(ID32, D32, [d33 => ID33]);
make_dep!(ID33, D33, [d34 => ID34]);
make_dep!(ID34, D34, [d35 => ID35]);
make_dep!(ID35, D35, [d36 => ID36]);
make_dep!(ID36, D36, [d37 => ID37]);
make_dep!(ID37, D37, [d38 => ID38]);
make_dep!(ID38, D38, [d39 => ID39]);
make_dep!(ID39, D39, [d40 => ID40]);
make_dep!(ID40, D40, [d41 => ID41]);
make_dep!(ID41, D41, [d42 => ID42]);
make_dep!(ID42, D42, [d43 => ID43]);
make_dep!(ID43, D43, [d44 => ID44]);
make_dep!(ID44, D44, [d45 => ID45]);
make_dep!(ID45, D45, [d46 => ID46]);
make_dep!(ID46, D46, [d47 => ID47]);
make_dep!(ID47, D47, [d48 => ID48]);
make_dep!(ID48, D48, [d49 => ID49]);
make_dep!(ID49, D49, [d50 => ID50]);
make_dep!(ID50, D50, [d51 => ID51]);
make_dep!(ID51, D51, [d52 => ID52]);
make_dep!(ID52, D52, [d53 => ID53]);
make_dep!(ID53, D53, [d54 => ID54]);
make_dep!(ID54, D54, [d55 => ID55]);
make_dep!(ID55, D55, [d56 => ID56]);
make_dep!(ID56, D56, [d57 => ID57]);
make_dep!(ID57, D57, [d58 => ID58]);
make_dep!(ID58, D58, [d59 => ID59]);
make_dep!(ID59, D59, [d60 => ID60]);
make_dep!(ID60, D60, [d61 => ID61]);
make_dep!(ID61, D61, [d62 => ID62]);
make_dep!(ID62, D62, [d63 => ID63]);
make_dep!(ID63, D63, [d64 => ID64]);
make_dep!(ID64, D64, [d65 => ID65]);
make_dep!(ID65, D65, [d66 => ID66]);
make_dep!(ID66, D66, [d67 => ID67]);
make_dep!(ID67, D67, [d68 => ID68]);
make_dep!(ID68, D68, [d69 => ID69]);
make_dep!(ID69, D69, [d70 => ID70]);
make_dep!(ID70, D70, [d71 => ID71]);
make_dep!(ID71, D71, [d72 => ID72]);
make_dep!(ID72, D72, [d73 => ID73]);
make_dep!(ID73, D73, [d74 => ID74]);
make_dep!(ID74, D74, [d75 => ID75]);
make_dep!(ID75, D75, [d76 => ID76]);
make_dep!(ID76, D76, [d77 => ID77]);
make_dep!(ID77, D77, [d78 => ID78]);
make_dep!(ID78, D78, [d79 => ID79]);
make_dep!(ID79, D79, [d80 => ID80]);
make_dep!(ID80, D80, [d81 => ID81]);
make_dep!(ID81, D81, [d82 => ID82]);
make_dep!(ID82, D82, [d83 => ID83]);
make_dep!(ID83, D83, [d84 => ID84]);
make_dep!(ID84, D84, [d85 => ID85]);
make_dep!(ID85, D85, [d86 => ID86]);
make_dep!(ID86, D86, [d87 => ID87]);
make_dep!(ID87, D87, [d88 => ID88]);
make_dep!(ID88, D88, [d89 => ID89]);
make_dep!(ID89, D89, [d90 => ID90]);
make_dep!(ID90, D90, [d91 => ID91]);
make_dep!(ID91, D91, [d92 => ID92]);
make_dep!(ID92, D92, [d93 => ID93]);
make_dep!(ID93, D93, [d94 => ID94]);
make_dep!(ID94, D94, [d95 => ID95]);
make_dep!(ID95, D95, [d96 => ID96]);
make_dep!(ID96, D96, [d97 => ID97]);
make_dep!(ID97, D97, [d98 => ID98]);
make_dep!(ID98, D98, [d99 => ID99]);
make_dep!(ID99, D99, [d100 => ID100]);
make_dep!(ID100, D100, []);
make_dep!(IW1, W1, [
w2 => IW2,
w3 => IW3,
w4 => IW4,
w5 => IW5,
w6 => IW6,
w7 => IW7,
w8 => IW8,
w9 => IW9,
w10 => IW10,
w11 => IW11,
w12 => IW12,
w13 => IW13,
w14 => IW14,
w15 => IW15,
w16 => IW16,
w17 => IW17,
w18 => IW18,
w19 => IW19,
w20 => IW20,
w21 => IW21,
w22 => IW22,
w23 => IW23,
w24 => IW24,
w25 => IW25,
w26 => IW26,
w27 => IW27,
w28 => IW28,
w29 => IW29,
w30 => IW30,
w31 => IW31,
w32 => IW32,
w33 => IW33,
w34 => IW34,
w35 => IW35,
w36 => IW36,
w37 => IW37,
w38 => IW38,
w39 => IW39,
w40 => IW40,
w41 => IW41,
w42 => IW42,
w43 => IW43,
w44 => IW44,
w45 => IW45,
w46 => IW46,
w47 => IW47,
w48 => IW48,
w49 => IW49,
w50 => IW50,
w51 => IW51,
w52 => IW52,
w53 => IW53,
w54 => IW54,
w55 => IW55,
w56 => IW56,
w57 => IW57,
w58 => IW58,
w59 => IW59,
w60 => IW60,
w61 => IW61,
w62 => IW62,
w63 => IW63,
w64 => IW64,
w65 => IW65,
w66 => IW66,
w67 => IW67,
w68 => IW68,
w69 => IW69,
w70 => IW70,
w71 => IW71,
w72 => IW72,
w73 => IW73,
w74 => IW74,
w75 => IW75,
w76 => IW76,
w77 => IW77,
w78 => IW78,
w79 => IW79,
w80 => IW80,
w81 => IW81,
w82 => IW82,
w83 => IW83,
w84 => IW84,
w85 => IW85,
w86 => IW86,
w87 => IW87,
w88 => IW88,
w89 => IW89,
w90 => IW90,
w91 => IW91,
w92 => IW92,
w93 => IW93,
w94 => IW94,
w95 => IW95,
w96 => IW96,
w97 => IW97,
w98 => IW98,
w99 => IW99,
w100 => IW100
]);
make_dep!(IW2, W2, []);
make_dep!(IW3, W3, []);
make_dep!(IW4, W4, []);
make_dep!(IW5, W5, []);
make_dep!(IW6, W6, []);
make_dep!(IW7, W7, []);
make_dep!(IW8, W8, []);
make_dep!(IW9, W9, []);
make_dep!(IW10, W10, []);
make_dep!(IW11, W11, []);
make_dep!(IW12, W12, []);
make_dep!(IW13, W13, []);
make_dep!(IW14, W14, []);
make_dep!(IW15, W15, []);
make_dep!(IW16, W16, []);
make_dep!(IW17, W17, []);
make_dep!(IW18, W18, []);
make_dep!(IW19, W19, []);
make_dep!(IW20, W20, []);
make_dep!(IW21, W21, []);
make_dep!(IW22, W22, []);
make_dep!(IW23, W23, []);
make_dep!(IW24, W24, []);
make_dep!(IW25, W25, []);
make_dep!(IW26, W26, []);
make_dep!(IW27, W27, []);
make_dep!(IW28, W28, []);
make_dep!(IW29, W29, []);
make_dep!(IW30, W30, []);
make_dep!(IW31, W31, []);
make_dep!(IW32, W32, []);
make_dep!(IW33, W33, []);
make_dep!(IW34, W34, []);
make_dep!(IW35, W35, []);
make_dep!(IW36, W36, []);
make_dep!(IW37, W37, []);
make_dep!(IW38, W38, []);
make_dep!(IW39, W39, []);
make_dep!(IW40, W40, []);
make_dep!(IW41, W41, []);
make_dep!(IW42, W42, []);
make_dep!(IW43, W43, []);
make_dep!(IW44, W44, []);
make_dep!(IW45, W45, []);
make_dep!(IW46, W46, []);
make_dep!(IW47, W47, []);
make_dep!(IW48, W48, []);
make_dep!(IW49, W49, []);
make_dep!(IW50, W50, []);
make_dep!(IW51, W51, []);
make_dep!(IW52, W52, []);
make_dep!(IW53, W53, []);
make_dep!(IW54, W54, []);
make_dep!(IW55, W55, []);
make_dep!(IW56, W56, []);
make_dep!(IW57, W57, []);
make_dep!(IW58, W58, []);
make_dep!(IW59, W59, []);
make_dep!(IW60, W60, []);
make_dep!(IW61, W61, []);
make_dep!(IW62, W62, []);
make_dep!(IW63, W63, []);
make_dep!(IW64, W64, []);
make_dep!(IW65, W65, []);
make_dep!(IW66, W66, []);
make_dep!(IW67, W67, []);
make_dep!(IW68, W68, []);
make_dep!(IW69, W69, []);
make_dep!(IW70, W70, []);
make_dep!(IW71, W71, []);
make_dep!(IW72, W72, []);
make_dep!(IW73, W73, []);
make_dep!(IW74, W74, []);
make_dep!(IW75, W75, []);
make_dep!(IW76, W76, []);
make_dep!(IW77, W77, []);
make_dep!(IW78, W78, []);
make_dep!(IW79, W79, []);
make_dep!(IW80, W80, []);
make_dep!(IW81, W81, []);
make_dep!(IW82, W82, []);
make_dep!(IW83, W83, []);
make_dep!(IW84, W84, []);
make_dep!(IW85, W85, []);
make_dep!(IW86, W86, []);
make_dep!(IW87, W87, []);
make_dep!(IW88, W88, []);
make_dep!(IW89, W89, []);
make_dep!(IW90, W90, []);
make_dep!(IW91, W91, []);
make_dep!(IW92, W92, []);
make_dep!(IW93, W93, []);
make_dep!(IW94, W94, []);
make_dep!(IW95, W95, []);
make_dep!(IW96, W96, []);
make_dep!(IW97, W97, []);
make_dep!(IW98, W98, []);
make_dep!(IW99, W99, []);
make_dep!(IW100, W100, []);
|
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
pub fn hsl_to_rgb(h: f64, s: f64, l: f64) -> Color {
let r;
let g;
let b;
if s == 0.0 {
r = l;
g = l;
b = l;
Color::new(r as u8 * 255, b as u8 * 255, g as u8 * 255, 255)
} else {
let q;
let p;
if l < 0.5 {
q = l * (1.0 + s);
} else {
q = l + s - l * s;
}
p = 2.0 * l - q;
r = hue_to_rgb(p, q, h + 1.0 / 3.0);
g = hue_to_rgb(p, q, h);
b = hue_to_rgb(p, q, h - 1.0 / 3.0);
Color::new(r as u8 * 255, b as u8 * 255, g as u8 * 255, 255)
}
}
pub fn hue_to_rgb(p: f64, q: f64, t: f64) -> f64 {
let local_t: f64;
if t < 0.0 {
local_t = t + 1.0
} else {
local_t = t - 1.0
}
match local_t {
local_t if local_t < 1.0 / 6.0 => p + (q - p) * 6.0 * local_t,
local_t if local_t < 1.0 / 2.0 => q,
local_t if local_t < 2.0 / 3.0 => p + (q - p) * (2.0 / 3.0 - local_t) * 6.0,
_ => p,
}
}
impl Color {
pub fn new(r: u8, b: u8, g: u8, a: u8) -> Color {
Color { r, g, b, a }
}
}
|
use crate::event::NetworkEvent;
pub trait CloneableEvent {
fn boxed_clone(&self) -> Box<dyn NetworkEvent>;
}
impl<T: 'static + Clone + NetworkEvent> CloneableEvent for T {
fn boxed_clone(&self) -> Box<dyn NetworkEvent> {
Box::new(self.clone())
}
}
impl Clone for Box<dyn NetworkEvent> {
fn clone(&self) -> Self {
self.boxed_clone()
}
} |
/*!
An example that shows how to handle custom clipboard operations
Requires the following features: `cargo run --example clipboard --features "textbox listbox menu cursor clipboard"`
*/
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;
use nwd::NwgUi;
use nwg::NativeUi;
#[derive(Default, NwgUi)]
pub struct ClipboardCustom {
#[nwg_control(size: (400, 300), position: (300, 300), title: "Clipboard Handling")]
#[nwg_events( OnWindowClose: [nwg::stop_thread_dispatch()] )]
window: nwg::Window,
#[nwg_layout(parent: window)]
grid: nwg::GridLayout,
#[nwg_control(text:"Hello\r\nWorld\r\nClipboad\r\nExample", flags: "VISIBLE|AUTOVSCROLL|AUTOHSCROLL", focus: true,)]
#[nwg_layout_item(layout: grid, row: 0, col: 0)]
sample_text: nwg::TextBox,
#[nwg_control]
#[nwg_events(MousePressRightUp: [ClipboardCustom::show_menu])]
#[nwg_layout_item(layout: grid, col: 1, row: 0)]
listbox: nwg::ListBox<String>,
#[nwg_control(popup: true)]
listbox_menu: nwg::Menu,
#[nwg_control(parent: listbox_menu, text: "Paste Items")]
#[nwg_events(OnMenuItemSelected: [ClipboardCustom::paste_items])]
listbox_menu_paste: nwg::MenuItem,
#[nwg_control(parent: listbox_menu, text: "Copy Items")]
#[nwg_events(OnMenuItemSelected: [ClipboardCustom::copy_items])]
listbox_menu_copy: nwg::MenuItem,
}
impl ClipboardCustom {
fn show_menu(&self) {
let (x, y) = nwg::GlobalCursor::position();
self.listbox_menu.popup(x, y)
}
fn paste_items(&self) {
self.listbox.clear();
if let Some(text) = nwg::Clipboard::data_text(&self.window) {
for line in text.split("\r\n") {
self.listbox.push(line.into());
}
}
}
fn copy_items(&self) {
let mut copy_data = String::with_capacity(30);
let col = self.listbox.collection();
for item in col.iter() {
copy_data.push_str(&item);
copy_data.push_str("\r\n");
}
nwg::Clipboard::set_data_text(&self.window, ©_data);
}
}
fn main() {
nwg::init().expect("Failed to init Native Windows GUI");
nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font");
let _app = ClipboardCustom::build_ui(Default::default()).expect("Failed to build UI");
nwg::dispatch_thread_events();
}
|
use amethyst::{
animation::*,
assets::*,
audio::{SourceHandle, WavFormat},
derive::PrefabData,
ecs::*,
error::Error,
prelude::*,
renderer::{
sprite::{prefab::SpriteScenePrefab, SpriteSheetHandle},
types::Texture,
ImageFormat, SpriteRender, SpriteSheet, SpriteSheetFormat,
},
utils::{application_root_dir, scene::BasicScenePrefab},
};
use na::Vector2;
use serde::{Deserialize, Serialize};
pub fn get_resource(str: &str) -> String {
format!("{}", str)
}
pub fn load_texture<'a>(
world: &mut World,
path: String,
progress: &'a mut ProgressCounter,
) -> Handle<Texture> {
let loader = world.read_resource::<Loader>();
let texture_storage = world.read_resource::<AssetStorage<Texture>>();
loader.load(path, ImageFormat::default(), progress, &texture_storage)
}
pub fn load_spritesheet<'a>(
world: &mut World,
path: String,
progress: &'a mut ProgressCounter,
) -> SpriteSheetHandle {
let texture_handle = load_texture(world, format!("{}.png", path), progress);
let loader = world.read_resource::<Loader>();
let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();
loader.load(
format!("{}.ron", path), // Here we load the associated ron file
SpriteSheetFormat(texture_handle),
progress,
&sprite_sheet_store,
)
}
#[derive(Debug, Clone, Deserialize, PrefabData)]
pub struct MyPrefabData {
sprite_scene: SpriteScenePrefab,
animation_set: AnimationSetPrefab<AnimationId, SpriteRender>,
}
pub fn load_prefab<'a>(
world: &mut World,
path: String,
progress: &'a mut ProgressCounter,
) -> Handle<Prefab<MyPrefabData>> {
world.exec(|loader: PrefabLoader<'_, MyPrefabData>| loader.load(path, RonFormat, progress))
}
#[derive(Clone)]
pub struct PrefabStorage {
pub player: Handle<Prefab<MyPrefabData>>,
pub crab: Handle<Prefab<MyPrefabData>>,
}
pub fn load_sound_file<'a>(
world: &mut World,
path: String,
progress: &'a mut ProgressCounter,
) -> SourceHandle {
let loader = world.read_resource::<Loader>();
loader.load(path, WavFormat, (), &world.read_resource())
}
#[derive(Clone)]
pub struct SpriteStorage {
pub tile_spritesheet: SpriteSheetHandle,
}
#[derive(Clone)]
pub struct SoundStorage {
pub goblin_hit: SourceHandle,
pub player_hit: SourceHandle,
pub pylon_hit: SourceHandle,
pub sword_slash: SourceHandle,
pub main_theme: SourceHandle,
}
#[derive(Clone, Debug)]
pub struct TiledMap(pub tiled::Map);
#[derive(Clone, Copy, Debug, Default)]
pub struct TiledFormat;
impl Format<tiled::Map> for TiledFormat {
fn name(&self) -> &'static str {
"TiledFormat"
}
fn import_simple(&self, bytes: Vec<u8>) -> Result<tiled::Map, Error> {
println!("LOADING FORMAT");
let reader = bytes.as_slice();
Ok(tiled::parse(reader).unwrap())
}
}
impl Asset for TiledMap {
const NAME: &'static str = "tiled::Map";
// use `Self` if the type is directly serialized.
type Data = tiled::Map;
type HandleStorage = VecStorage<Handle<Self>>;
}
impl ProcessableAsset for TiledMap {
fn process(tiled_map: Self::Data) -> Result<ProcessingState<Self>, Error> {
Ok(ProcessingState::Loaded(Self(tiled_map)))
}
}
#[derive(Clone)]
pub struct MapStorage {
pub village_map: Handle<TiledMap>,
}
pub fn load_map<'a>(
world: &mut World,
path: String,
progress: &'a mut ProgressCounter,
) -> Handle<TiledMap> {
println!("LOADING MAP");
let loader = world.read_resource::<Loader>();
let map_storage = world.read_resource::<AssetStorage<TiledMap>>();
loader.load(path, TiledFormat::default(), progress, &map_storage)
}
#[derive(Eq, PartialOrd, PartialEq, Hash, Debug, Copy, Clone, Deserialize, Serialize)]
pub enum Direction {
East,
North,
West,
South,
}
impl Direction {
pub fn vec() -> Vec<Self> {
vec![
Direction::East,
Direction::North,
Direction::West,
Direction::South,
]
}
pub fn tilts(&self) -> Vector2<f32> {
match self {
Direction::East => Vector2::new(1.0, 0.0),
Direction::North => Vector2::new(0.0, 1.0),
Direction::West => Vector2::new(-1.0, 0.0),
Direction::South => Vector2::new(0.0, -1.0),
}
}
pub fn clockwise(&self) -> Self {
match self {
Direction::East => Direction::South,
Direction::South => Direction::West,
Direction::West => Direction::North,
Direction::North => Direction::East,
}
}
pub fn pick() -> Self {
if rand::random() {
if rand::random() {
Direction::East
} else {
Direction::North
}
} else {
if rand::random() {
Direction::West
} else {
Direction::South
}
}
}
pub fn short_seek(offset: Vector2<f32>, margin: f32) -> Self {
if f32::abs(offset.x) < margin || f32::abs(offset.y) < margin {
Direction::long_seek(offset)
} else if f32::abs(offset.x) > f32::abs(offset.y) {
if offset.y > 0.0 {
Direction::North
} else {
Direction::South
}
} else {
if offset.x > 0.0 {
Direction::East
} else {
Direction::West
}
}
}
pub fn long_seek(offset: Vector2<f32>) -> Self {
if f32::abs(offset.x) < f32::abs(offset.y) {
if offset.y > 0.0 {
Direction::North
} else {
Direction::South
}
} else {
if offset.x > 0.0 {
Direction::East
} else {
Direction::West
}
}
}
}
#[derive(Eq, PartialOrd, PartialEq, Hash, Debug, Copy, Clone, Deserialize, Serialize)]
pub enum AnimationId {
Walk(Direction),
Attack(Direction),
Idle(Direction),
Staggered(Direction),
}
impl AnimationId {
pub fn direction(&self) -> Direction {
match self {
AnimationId::Walk(direction) => *direction,
AnimationId::Attack(direction) => *direction,
AnimationId::Idle(direction) => *direction,
AnimationId::Staggered(direction) => *direction,
}
}
pub fn is_attack(&self) -> bool {
match self {
AnimationId::Attack(_) => true,
_ => false,
}
}
}
|
use crate::net::ipv6::ip_utils::IPAddr;
use crate::net::udp::udp_recv::{UDPReceiver, UDPRecvClient};
use crate::net::udp::udp_send::{UDPSendClient, UDPSender};
use super::command::{self, Command};
use kernel::{debug, ReturnCode, Driver};
pub const DST_ADDR: IPAddr = IPAddr([
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e,
0x1f,
// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
// 0x0f,
]);
pub const SRC_PORT: u16 = 15123;
pub const DST_PORT: u16 = 16123;
pub const PAYLOAD_LEN: usize = 192;
const UDP_HDR_SIZE: usize = 8;
const COMMAND_WIDTH: usize = 2; // Number of bytes that the command type takes up (including the one byte for security info)
const TL_WIDTH: usize = 2;
pub struct MLEClient<'a> {
/// UDP sender
udp_sender: &'a UDPSender<'a>,
/// UDP receiver
udp_receiver: &'a UDPReceiver<'a>,
}
impl<'a> MLEClient<'a> {
pub fn new(
sender: &'a UDPSender<'a>,
receiver: &'a UDPReceiver<'a>,
) -> MLEClient<'a> {
MLEClient {
udp_sender: sender,
udp_receiver: receiver,
}
}
pub fn start_handshake(&self) {
debug!("In start handshake");
//debug!("{}", "In start handhsake");
const len_buf: usize = COMMAND_WIDTH + (TL_WIDTH * 4) + 12;
let mut buf: [u8; len_buf] = [0; len_buf];
//debug!("Starting to output buffer");
command::format_command(Command::ParentRequest, &mut buf);
for i in 0..buf.len() {
//debug!("Buf[{}]: {}", i, buf[i]);
}
//debug!("Done with outputting buf");
debug!("Sending message...");
self.udp_sender.send_to(DST_ADDR, DST_PORT, SRC_PORT, &buf);
/*unsafe {
for i in 0..buf.len() {
UDP_DGRAM[i] = buf[i];
}
debug!("Beginning send");
self.udp_sender.send_to(DST_ADDR, DST_PORT, SRC_PORT, &UDP_DGRAM);
}*/
}
}
impl<'a> UDPSendClient for MLEClient<'a> {
fn send_done(&self, result: ReturnCode) {
debug!("Sent through MLEClient");
}
}
impl<'a> UDPRecvClient for MLEClient<'a> {
fn receive(
&self,
src_addr: IPAddr,
dst_addr: IPAddr,
src_port: u16,
dst_port: u16,
payload: &[u8],
) {
debug!("Receive in MLEClient");
}
} |
use crate::widgets::{View, TextView, Dim, Dimensions, desired_size, Vt100Formatter, CharDims};
use std::cmp::min;
impl TextView {
pub fn new(width: Dim, height: Dim) -> TextView {
TextView {
raw_text: "".to_string(),
dims: Dimensions {
width_constraint: width,
height_constraint: height,
size: (0, 0)
},
formatter: Box::new(Vt100Formatter{}),
visible: true
}
}
pub fn update_content(&mut self, s: String) -> () {
self.raw_text = s;
}
}
impl View for TextView {
fn inflate(&mut self, parent_dimensions: &CharDims) -> CharDims {
if !self.visible {
self.dims.size = (0, 0);
return self.dims.size;
}
let text_size = self.raw_text.split("\n").map(|c| c.len()).max().unwrap();
let desired_width_constraint = Dim::UpTo(text_size);
let desired_height_constraint = Dim::UpTo(self.raw_text.split("\n").count());
let most_restrictive_width = min(desired_width_constraint, min(self.dims.width_constraint, Dim::Fixed(parent_dimensions.0)));
let most_restrictive_height= min(desired_height_constraint, min(self.dims.height_constraint, Dim::Fixed(parent_dimensions.1)));
self.dims.size = (desired_size(&most_restrictive_width),
desired_size(&most_restrictive_height));
self.dims.size.clone()
}
fn constraints(&self) -> (Dim, Dim) {
(self.dims.width_constraint.clone(), self.dims.height_constraint.clone())
}
fn width(&self) -> usize { self.dims.size.0 }
fn height(&self) -> usize { self.dims.size.1 }
fn render(&self) -> String {
self.raw_text.
split("\n").take(self.height()). // First n Lines
map(|c| self.formatter.format(c.to_string(), self.width())). // Format them
collect::<Vec<String>>().join("\n") // Convert back into a single string
}
fn render_lines(&self) -> Vec<String> {
self.render()
.split("\n")
.map(|s| s.to_string())
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn fixed_size_text_widget() -> TextView {
TextView::new(Dim::Fixed(10), Dim::Fixed(2))
}
fn wrap_content_text_widget() -> TextView {
TextView::new(Dim::WrapContent, Dim::WrapContent)
}
#[test]
fn retrieves_constraints() {
assert_eq!(fixed_size_text_widget().constraints(), (Dim::Fixed(10), Dim::Fixed(2)));
}
#[test]
fn inflation_of_fixed_width_works_with_wrap_content_parent() {
let mut tw = fixed_size_text_widget();
tw.raw_text = String::from("line 1 is pretty long\nline 2 is shorter.\nline 3 is also fairly long.");
tw.inflate(&(100, 100));
assert_eq!(10, tw.width());
assert_eq!(2, tw.height());
}
#[test]
fn inflation_of_fixed_width_works_shrinks_to_fit_parent() {
let mut tw = fixed_size_text_widget();
tw.raw_text = String::from("line 1 is pretty long\nline 2 is shorter.\nline 3 is also fairly long.");
tw.inflate(&(5, 100));
assert_eq!(5, tw.width());
assert_eq!(2, tw.height());
}
#[test]
fn inflation_of_wrap_content_width_expands_to_line_length() {
let mut tw = wrap_content_text_widget();
tw.raw_text = String::from("line 1 is pretty long\nline 2 is shorter.");
tw.inflate(&(100, 100));
assert_eq!("line 1 is pretty long".len(), tw.width());
assert_eq!(2, tw.height());
}
#[test]
fn inflation_of_wrap_content_width_shrinks_to_fixed_parent_dims() {
let mut tw = wrap_content_text_widget();
tw.raw_text = String::from("line 1 is pretty long\nline 2 is shorter.\nline 3 is also fairly long.");
tw.inflate(&(3, 2));
assert_eq!(3, tw.width());
assert_eq!(2, tw.height());
}
#[test]
fn renders_all_text_within_wrap_content() {
let mut tw = wrap_content_text_widget();
tw.raw_text = String::from("some\ntext");
tw.inflate(&(100, 100));
assert_eq!(String::from("some\ntext"), tw.render());
}
#[test]
fn renders_partial_text_within_fixed_size() {
let mut tw = fixed_size_text_widget();
tw.raw_text = String::from("some really long text\nand another really long line\nthis line doesn't show up at all");
tw.inflate(&(100, 100));
assert_eq!(String::from("some reall\nand anothe"), tw.render());
}
#[test]
fn when_invisible_renders_nothing() {
let mut tw = fixed_size_text_widget();
tw.raw_text = String::from("some really long text\nand another really long line\nthis line doesn't show up at all");
tw.visible = false;
tw.inflate(&(100, 100));
assert_eq!(String::from(""), tw.render());
assert_eq!(vec![""], tw.render_lines());
}
#[test]
fn when_invisible_dims_are_0() {
let mut tw = fixed_size_text_widget();
tw.raw_text = String::from("some really long text\nand another really long line\nthis line doesn't show up at all");
tw.visible = false;
tw.inflate(&(100, 100));
assert_eq!(tw.dims.size, (0, 0));
}
} |
use arrow::{datatypes::Field, record_batch::RecordBatch};
use hashbrown::hash_map::RawEntryMut;
use hashbrown::HashMap;
use snafu::Snafu;
use crate::interner::SchemaInterner;
use super::{InfluxColumnType, Schema};
/// Namespace schema creation / validation errors.
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("No schemas found when building merged schema"))]
NoSchemas,
#[snafu(display(
"Schema Merge Error: Incompatible measurement names. Existing measurement name '{}', new measurement name '{}'",
existing_measurement, new_measurement
))]
TryMergeDifferentMeasurementNames {
existing_measurement: String,
new_measurement: String,
},
#[snafu(display(
"Schema Merge Error: Incompatible column type for '{}'. Existing type {:?}, new type {:?}",
field_name,
existing_column_type,
new_column_type
))]
TryMergeBadColumnType {
field_name: String,
existing_column_type: InfluxColumnType,
new_column_type: InfluxColumnType,
},
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// Return the merged schema for RecordBatches
///
/// This is infallable because the schemas of chunks within a
/// partition are assumed to be compatible because that schema was
/// enforced as part of writing into the partition
pub fn merge_record_batch_schemas(batches: &[RecordBatch]) -> Schema {
let mut merger = SchemaMerger::new();
for batch in batches {
let schema = Schema::try_from(batch.schema()).expect("Schema conversion error");
merger = merger.merge(&schema).expect("Schemas compatible");
}
merger.build()
}
/// Schema Merger
///
/// The usecase for merging schemas is when different chunks have
/// different schemas. This struct can be used to build a combined
/// schema by merging Schemas together according to the following
/// rules:
///
/// 1. New columns may be added in subsequent schema, but the types of
/// the columns (including any metadata) must be the same
///
/// 2. The measurement names must be consistent: one or both can be
/// `None`, or they can both be `Some(name`)
#[derive(Debug, Default)]
pub struct SchemaMerger<'a> {
/// Maps column names to their definition
fields: HashMap<String, (Field, InfluxColumnType)>,
/// The measurement name if any
measurement: Option<String>,
/// Interner, if any.
interner: Option<&'a mut SchemaInterner>,
}
impl SchemaMerger<'static> {
pub fn new() -> Self {
Self::default()
}
}
impl<'a> SchemaMerger<'a> {
pub fn with_interner(self, interner: &mut SchemaInterner) -> SchemaMerger<'_> {
SchemaMerger {
fields: self.fields,
measurement: self.measurement,
interner: Some(interner),
}
}
/// Appends the schema to the merged schema being built,
/// validating that no columns are added.
pub fn merge(mut self, other: &Schema) -> Result<Self> {
// Verify measurement name is compatible
match (self.measurement.as_ref(), other.measurement()) {
(Some(existing_measurement), Some(new_measurement)) => {
if existing_measurement != new_measurement {
return TryMergeDifferentMeasurementNamesSnafu {
existing_measurement,
new_measurement,
}
.fail();
}
}
(None, Some(other)) => self.measurement = Some(other.clone()),
_ => {}
}
// Merge fields
for (column_type, field) in other.iter() {
self.merge_field(field, column_type)?;
}
Ok(self)
}
pub fn merge_field(
&mut self,
field: &Field,
column_type: InfluxColumnType,
) -> Result<&mut Self> {
let field_name = field.name();
match self.fields.raw_entry_mut().from_key(field_name) {
RawEntryMut::Vacant(vacant) => {
// Purposefully don't propagate metadata to avoid blindly propagating
// information such as sort key, etc... that SchemaMerger cannot guarantee
// to preserve the semantics of
let field = Field::new(field_name, field.data_type().clone(), field.is_nullable());
vacant.insert(field_name.clone(), (field, column_type));
}
RawEntryMut::Occupied(occupied) => {
let (existing_field, existing_column_type) = occupied.get();
// for now, insist the types are exactly the same
// (e.g. None and Some(..) don't match). We could
// consider relaxing this constraint
if existing_column_type != &column_type {
return Err(Error::TryMergeBadColumnType {
field_name: field_name.to_string(),
existing_column_type: *existing_column_type,
new_column_type: column_type,
});
}
// both are valid schemas, so this should always hold
assert_eq!(field.is_nullable(), existing_field.is_nullable());
assert_eq!(field.data_type(), existing_field.data_type());
}
}
Ok(self)
}
/// Returns the schema that was built, the columns are always sorted in lexicographic order
pub fn build(mut self) -> Schema {
let schema = Schema::new_from_parts(
self.measurement.take(),
self.fields.drain().map(|x| x.1),
true,
)
.expect("failed to build merged schema");
if let Some(interner) = self.interner.as_mut() {
interner.intern(schema)
} else {
schema
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use crate::builder::SchemaBuilder;
use crate::InfluxFieldType::Integer;
use super::*;
#[test]
fn test_merge_same_schema() {
let schema1 = SchemaBuilder::new()
.influx_field("int_field", Integer)
.tag("the_tag")
.build()
.unwrap();
let schema2 = SchemaBuilder::new()
.influx_field("int_field", Integer)
.tag("the_tag")
.build()
.unwrap();
let merged_schema = SchemaMerger::new()
.merge(&schema1)
.unwrap()
.merge(&schema2)
.unwrap()
.build();
assert_eq!(merged_schema, schema1);
assert_eq!(merged_schema, schema2);
}
#[test]
fn test_merge_compatible_schema() {
let schema1 = SchemaBuilder::new()
.tag("the_tag")
.influx_field("int_field", Integer)
.build()
.unwrap()
.sort_fields_by_name();
// has some of the same and some new, different fields
let schema2 = SchemaBuilder::new()
.measurement("my_measurement")
.tag("the_other_tag")
.influx_field("int_field", Integer)
.influx_field("another_field", Integer)
.build()
.unwrap()
.sort_fields_by_name();
let merged_schema = SchemaMerger::new()
.merge(&schema1)
.unwrap()
.merge(&schema2)
.unwrap()
.build();
let expected_schema = SchemaBuilder::new()
.measurement("my_measurement")
.tag("the_tag")
.influx_field("int_field", Integer)
.tag("the_other_tag")
.influx_field("another_field", Integer)
.build()
.unwrap()
.sort_fields_by_name();
assert_eq!(
expected_schema, merged_schema,
"\nExpected:\n{expected_schema:#?}\nActual:\n{merged_schema:#?}"
);
}
#[test]
fn test_merge_compatible_schema_no_names() {
let schema1 = SchemaBuilder::new().tag("the_tag").build().unwrap();
// has some different fields
let schema2 = SchemaBuilder::new().tag("the_other_tag").build().unwrap();
// ensure the merge is not optimized away
let merged_schema = SchemaMerger::new()
.merge(&schema1)
.unwrap()
.merge(&schema2)
.unwrap()
.build();
let expected_schema = SchemaBuilder::new()
.tag("the_other_tag")
.tag("the_tag")
.build()
.unwrap();
assert_eq!(
expected_schema, merged_schema,
"\nExpected:\n{expected_schema:#?}\nActual:\n{merged_schema:#?}"
);
}
#[test]
fn test_merge_compatible_schema_only_measurement() {
let schema1 = SchemaBuilder::new()
.tag("the_tag")
.measurement("the_measurement")
.build()
.unwrap();
// schema has same fields but not measurement name
let schema2 = SchemaBuilder::new().tag("the_tag").build().unwrap();
// ensure the merge is not optimized away
let merged_schema = SchemaMerger::new()
.merge(&schema1)
.unwrap()
.merge(&schema2)
.unwrap()
.build();
let expected_schema = SchemaBuilder::new()
.tag("the_tag")
.measurement("the_measurement")
.build()
.unwrap();
assert_eq!(
expected_schema, merged_schema,
"\nExpected:\n{expected_schema:#?}\nActual:\n{merged_schema:#?}"
);
}
#[test]
fn test_merge_measurement_names() {
let schema1 = SchemaBuilder::new().tag("the_tag").build().unwrap();
// has some of the same and some different fields
let schema2 = SchemaBuilder::new()
.measurement("my_measurement")
.build()
.unwrap();
let merged_schema = SchemaMerger::new()
.merge(&schema1)
.unwrap()
.merge(&schema2)
.unwrap()
.build();
let expected_schema = SchemaBuilder::new()
.measurement("my_measurement")
.tag("the_tag")
.build()
.unwrap();
assert_eq!(
expected_schema, merged_schema,
"\nExpected:\n{expected_schema:#?}\nActual:\n{merged_schema:#?}"
);
}
#[test]
fn test_merge_incompatible_schema_measurement_names() {
let schema1 = SchemaBuilder::new()
.tag("the_tag")
.measurement("measurement1")
.build()
.unwrap();
// different measurement name, same otherwise
let schema2 = SchemaBuilder::new()
.tag("the_tag")
.measurement("measurement2")
.build()
.unwrap();
let merged_schema_error = SchemaMerger::new()
.merge(&schema1)
.unwrap()
.merge(&schema2)
.unwrap_err();
assert_eq!(
merged_schema_error.to_string(),
"Schema Merge Error: Incompatible measurement names. Existing measurement name 'measurement1', new measurement name 'measurement2'"
);
}
#[test]
fn test_merge_incompatible_column_types() {
let schema1 = SchemaBuilder::new().tag("the_tag").build().unwrap();
// same field name with different type
let schema2 = SchemaBuilder::new()
.influx_field("the_tag", Integer)
.build()
.unwrap();
let merged_schema_error = SchemaMerger::new()
.merge(&schema1)
.unwrap()
.merge(&schema2)
.unwrap_err();
assert_eq!(merged_schema_error.to_string(), "Schema Merge Error: Incompatible column type for 'the_tag'. Existing type Tag, new type Field(Integer)");
}
#[test]
fn test_interning() {
let schema_1a = SchemaBuilder::new()
.influx_field("int_field", Integer)
.tag("the_tag")
.build()
.unwrap();
let schema_1b = SchemaBuilder::new()
.influx_field("int_field", Integer)
.tag("the_tag")
.build()
.unwrap();
let schema_2 = SchemaBuilder::new()
.influx_field("float_field", crate::InfluxFieldType::Float)
.tag("the_tag")
.build()
.unwrap();
let mut interner = SchemaInterner::new();
let merged_schema_a = SchemaMerger::new()
.with_interner(&mut interner)
.merge(&schema_1a)
.unwrap()
.merge(&schema_2)
.unwrap()
.build();
let merged_schema_b = SchemaMerger::new()
.with_interner(&mut interner)
.merge(&schema_1b)
.unwrap()
.merge(&schema_2)
.unwrap()
.build();
assert_eq!(merged_schema_a, merged_schema_b);
assert!(Arc::ptr_eq(
merged_schema_a.inner(),
merged_schema_b.inner()
));
}
}
|
use std::convert::TryInto;
use proptest::prop_assert_eq;
use proptest::strategy::{Just, Strategy};
use proptest::test_runner::{Config, TestRunner};
use liblumen_alloc::erts::term::prelude::*;
use crate::erlang::bitstring_to_list_1::result;
use crate::test::strategy;
use crate::test::with_process_arc;
#[test]
fn without_bitstring_errors_badarg() {
crate::test::without_bitstring_errors_badarg(file!(), result);
}
#[test]
fn with_heap_binary_returns_list_of_integer() {
with_process_arc(|arc_process| {
TestRunner::new(Config::with_source_file(file!()))
.run(&strategy::byte_vec(), |byte_vec| {
let list = {
// not using an iterator because that would too closely match the code under
// test
match byte_vec.len() {
0 => Term::NIL,
1 => arc_process.cons(arc_process.integer(byte_vec[0]), Term::NIL),
2 => arc_process.cons(
arc_process.integer(byte_vec[0]),
arc_process.cons(arc_process.integer(byte_vec[1]), Term::NIL),
),
3 => arc_process.cons(
arc_process.integer(byte_vec[0]),
arc_process.cons(
arc_process.integer(byte_vec[1]),
arc_process.cons(arc_process.integer(byte_vec[2]), Term::NIL),
),
),
len => unimplemented!("len = {:?}", len),
}
};
let bitstring = arc_process.binary_from_bytes(&byte_vec);
prop_assert_eq!(result(&arc_process, bitstring), Ok(list));
Ok(())
})
.unwrap();
});
}
#[test]
fn with_subbinary_without_bit_count_returns_list_of_integer() {
with_process_arc(|arc_process| {
TestRunner::new(Config::with_source_file(file!()))
.run(
&strategy::byte_vec().prop_flat_map(|byte_vec| {
(
Just(byte_vec.clone()),
strategy::term::binary::sub::containing_bytes(
byte_vec,
arc_process.clone(),
),
)
}),
|(byte_vec, bitstring)| {
// not using an iterator because that would too closely match the code under
// test
let list = match byte_vec.len() {
0 => Term::NIL,
1 => arc_process.cons(arc_process.integer(byte_vec[0]), Term::NIL),
2 => arc_process.cons(
arc_process.integer(byte_vec[0]),
arc_process.cons(arc_process.integer(byte_vec[1]), Term::NIL),
),
3 => arc_process.cons(
arc_process.integer(byte_vec[0]),
arc_process.cons(
arc_process.integer(byte_vec[1]),
arc_process.cons(arc_process.integer(byte_vec[2]), Term::NIL),
),
),
len => unimplemented!("len = {:?}", len),
};
prop_assert_eq!(result(&arc_process, bitstring), Ok(list));
Ok(())
},
)
.unwrap();
})
}
#[test]
fn with_subbinary_with_bit_count_returns_list_of_integer_with_bitstring_for_bit_count() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::binary::sub::is_not_binary(arc_process.clone()),
)
},
|(arc_process, bitstring)| {
let subbinary: Boxed<SubBinary> = bitstring.try_into().unwrap();
let byte_vec: Vec<u8> = subbinary.full_byte_iter().collect();
let mut bit_count_byte: u8 = 0;
for (i, bit) in subbinary.partial_byte_bit_iter().enumerate() {
bit_count_byte = bit_count_byte | (bit << (7 - i));
}
let bits_original_byte_vec = vec![bit_count_byte];
let bits_original = arc_process.binary_from_bytes(&bits_original_byte_vec);
let bits_subbinary = arc_process.subbinary_from_original(
bits_original,
0,
0,
0,
subbinary.partial_byte_bit_len(),
);
// not using an iterator because that would too closely match the code under
// test
let list = match byte_vec.len() {
0 => arc_process.cons(bits_subbinary, Term::NIL),
1 => arc_process.cons(
arc_process.integer(byte_vec[0]),
arc_process.cons(bits_subbinary, Term::NIL),
),
2 => arc_process.cons(
arc_process.integer(byte_vec[0]),
arc_process.cons(
arc_process.integer(byte_vec[1]),
arc_process.cons(bits_subbinary, Term::NIL),
),
),
3 => arc_process.cons(
arc_process.integer(byte_vec[0]),
arc_process.cons(
arc_process.integer(byte_vec[1]),
arc_process.cons(
arc_process.integer(byte_vec[2]),
arc_process.cons(bits_subbinary, Term::NIL),
),
),
),
len => unimplemented!("len = {:?}", len),
};
prop_assert_eq!(result(&arc_process, bitstring), Ok(list));
Ok(())
},
);
}
|
//! ```elixir
//! text = Lumen.Web.Document.create_text_node(document, data)
//! ```
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::runtime::binary_to_string::binary_to_string;
use crate::document;
#[native_implemented::function(Elixir.Lumen.Web.Document:create_text_node/2)]
pub fn result(process: &Process, document: Term, data: Term) -> exception::Result<Term> {
let document_document = document::from_term(document)?;
let data_string: String = binary_to_string(data)?;
let text = document_document.create_text_node(&data_string);
Ok(process.resource(text))
}
|
// 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.
pub mod any;
pub mod array;
pub mod boolean;
pub mod date;
pub mod decimal;
pub mod empty_array;
pub mod empty_map;
pub mod generic;
pub mod map;
pub mod null;
pub mod nullable;
pub mod number;
pub mod number_class;
pub mod string;
pub mod timestamp;
pub mod variant;
use std::fmt::Debug;
use std::ops::Range;
use common_arrow::arrow::trusted_len::TrustedLen;
use enum_as_inner::EnumAsInner;
use serde::Deserialize;
use serde::Serialize;
pub use self::any::AnyType;
pub use self::array::ArrayType;
pub use self::boolean::BooleanType;
pub use self::date::DateType;
pub use self::decimal::DecimalDataType;
pub use self::empty_array::EmptyArrayType;
pub use self::empty_map::EmptyMapType;
pub use self::generic::GenericType;
pub use self::map::MapType;
pub use self::null::NullType;
pub use self::nullable::NullableType;
pub use self::number::*;
pub use self::number_class::*;
pub use self::string::StringType;
pub use self::timestamp::TimestampType;
pub use self::variant::VariantType;
use crate::property::Domain;
use crate::values::Column;
use crate::values::Scalar;
use crate::ColumnBuilder;
use crate::ScalarRef;
pub type GenericMap = [DataType];
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, EnumAsInner)]
pub enum DataType {
Null,
EmptyArray,
EmptyMap,
Boolean,
String,
Number(NumberDataType),
Decimal(DecimalDataType),
Timestamp,
Date,
Nullable(Box<DataType>),
Array(Box<DataType>),
Map(Box<DataType>),
Tuple(Vec<DataType>),
Variant,
Generic(usize),
}
impl DataType {
pub fn wrap_nullable(&self) -> Self {
match self {
DataType::Nullable(_) => self.clone(),
_ => Self::Nullable(Box::new(self.clone())),
}
}
pub fn is_nullable(&self) -> bool {
matches!(self, &DataType::Nullable(_))
}
pub fn is_nullable_or_null(&self) -> bool {
matches!(self, &DataType::Nullable(_) | &DataType::Null)
}
pub fn can_inside_nullable(&self) -> bool {
!self.is_nullable_or_null()
}
pub fn remove_nullable(&self) -> Self {
match self {
DataType::Nullable(ty) => (**ty).clone(),
_ => self.clone(),
}
}
pub fn unnest(&self) -> Self {
match self {
DataType::Array(ty) => ty.unnest(),
_ => self.clone(),
}
}
pub fn has_generic(&self) -> bool {
match self {
DataType::Generic(_) => true,
DataType::Nullable(ty) => ty.has_generic(),
DataType::Array(ty) => ty.has_generic(),
DataType::Map(ty) => ty.has_generic(),
DataType::Tuple(tys) => tys.iter().any(|ty| ty.has_generic()),
_ => false,
}
}
pub fn has_nested_nullable(&self) -> bool {
match self {
DataType::Nullable(box DataType::Nullable(_) | box DataType::Null) => true,
DataType::Array(ty) => ty.has_nested_nullable(),
DataType::Map(ty) => ty.has_nested_nullable(),
DataType::Tuple(tys) => tys.iter().any(|ty| ty.has_nested_nullable()),
_ => false,
}
}
pub fn is_unsigned_numeric(&self) -> bool {
match self {
DataType::Number(ty) => ALL_UNSIGNED_INTEGER_TYPES.contains(ty),
_ => false,
}
}
pub fn is_signed_numeric(&self) -> bool {
match self {
DataType::Number(ty) => {
ALL_INTEGER_TYPES.contains(ty) && !ALL_UNSIGNED_INTEGER_TYPES.contains(ty)
}
_ => false,
}
}
pub fn is_numeric(&self) -> bool {
match self {
DataType::Number(ty) => ALL_NUMERICS_TYPES.contains(ty),
_ => false,
}
}
#[inline]
pub fn is_integer(&self) -> bool {
match self {
DataType::Number(ty) => ALL_INTEGER_TYPES.contains(ty),
_ => false,
}
}
#[inline]
pub fn is_floating(&self) -> bool {
match self {
DataType::Number(ty) => ALL_FLOAT_TYPES.contains(ty),
_ => false,
}
}
pub fn is_decimal(&self) -> bool {
matches!(self, DataType::Decimal(_ty))
}
#[inline]
pub fn is_date_or_date_time(&self) -> bool {
matches!(self, DataType::Timestamp | DataType::Date)
}
pub fn numeric_byte_size(&self) -> Result<usize, String> {
match self {
DataType::Number(NumberDataType::UInt8) | DataType::Number(NumberDataType::Int8) => {
Ok(1)
}
DataType::Number(NumberDataType::UInt16) | DataType::Number(NumberDataType::Int16) => {
Ok(2)
}
DataType::Date
| DataType::Number(NumberDataType::UInt32)
| DataType::Number(NumberDataType::Float32)
| DataType::Number(NumberDataType::Int32) => Ok(4),
DataType::Timestamp
| DataType::Number(NumberDataType::UInt64)
| DataType::Number(NumberDataType::Float64)
| DataType::Number(NumberDataType::Int64) => Ok(8),
DataType::Decimal(DecimalDataType::Decimal128(_)) => Ok(16),
DataType::Decimal(DecimalDataType::Decimal256(_)) => Ok(32),
_ => Result::Err(format!(
"Function number_byte_size argument must be numeric types, but got {:?}",
self
)),
}
}
// Nullable will be displayed as Nullable(T)
pub fn wrapped_display(&self) -> String {
match self {
DataType::Nullable(inner_ty) => format!("Nullable({})", inner_ty.wrapped_display()),
_ => format!("{}", self),
}
}
pub fn sql_name(&self) -> String {
match self {
DataType::Number(num_ty) => match num_ty {
NumberDataType::UInt8 => "TINYINT UNSIGNED".to_string(),
NumberDataType::UInt16 => "SMALLINT UNSIGNED".to_string(),
NumberDataType::UInt32 => "INT UNSIGNED".to_string(),
NumberDataType::UInt64 => "BIGINT UNSIGNED".to_string(),
NumberDataType::Int8 => "TINYINT".to_string(),
NumberDataType::Int16 => "SMALLINT".to_string(),
NumberDataType::Int32 => "INT".to_string(),
NumberDataType::Int64 => "BIGINT".to_string(),
NumberDataType::Float32 => "FLOAT".to_string(),
NumberDataType::Float64 => "DOUBLE".to_string(),
},
DataType::String => "VARCHAR".to_string(),
DataType::Nullable(inner_ty) => format!("{} NULL", inner_ty.sql_name()),
_ => self.to_string().to_uppercase(),
}
}
// Returns the number of leaf columns of the DataType
pub fn num_leaf_columns(&self) -> usize {
match self {
DataType::Nullable(box inner_ty)
| DataType::Array(box inner_ty)
| DataType::Map(box inner_ty) => inner_ty.num_leaf_columns(),
DataType::Tuple(inner_tys) => inner_tys
.iter()
.map(|inner_ty| inner_ty.num_leaf_columns())
.sum(),
_ => 1,
}
}
}
pub trait ValueType: Debug + Clone + PartialEq + Sized + 'static {
type Scalar: Debug + Clone + PartialEq;
type ScalarRef<'a>: Debug + Clone + PartialEq;
type Column: Debug + Clone + PartialEq;
type Domain: Debug + Clone + PartialEq;
type ColumnIterator<'a>: Iterator<Item = Self::ScalarRef<'a>> + TrustedLen;
type ColumnBuilder: Debug + Clone;
/// Upcast GAT type's lifetime.
fn upcast_gat<'short, 'long: 'short>(long: Self::ScalarRef<'long>) -> Self::ScalarRef<'short>;
fn to_owned_scalar<'a>(scalar: Self::ScalarRef<'a>) -> Self::Scalar;
fn to_scalar_ref<'a>(scalar: &'a Self::Scalar) -> Self::ScalarRef<'a>;
fn try_downcast_scalar<'a>(scalar: &'a ScalarRef) -> Option<Self::ScalarRef<'a>>;
fn try_downcast_column<'a>(col: &'a Column) -> Option<Self::Column>;
fn try_downcast_domain(domain: &Domain) -> Option<Self::Domain>;
/// Downcast `ColumnBuilder` to a mutable reference of its inner builder type.
///
/// Not every builder can be downcasted successfully.
/// For example: `ArrayType<T: ValueType>`, `NullableType<T: ValueType>`, and `KvPair<K: ValueType, V: ValueType>`
/// cannot be downcasted and this method will return `None`.
///
/// So when using this method, we cannot unwrap the returned value directly.
/// We should:
///
/// ```ignore
/// // builder: ColumnBuilder
/// // T: ValueType
/// if let Some(inner) = T::try_downcast_builder(&mut builder) {
/// inner.push(...);
/// } else {
/// builder.push(...);
/// }
/// ```
fn try_downcast_builder<'a>(
builder: &'a mut ColumnBuilder,
) -> Option<&'a mut Self::ColumnBuilder>;
fn upcast_scalar(scalar: Self::Scalar) -> Scalar;
fn upcast_column(col: Self::Column) -> Column;
fn upcast_domain(domain: Self::Domain) -> Domain;
fn column_len<'a>(col: &'a Self::Column) -> usize;
fn index_column<'a>(col: &'a Self::Column, index: usize) -> Option<Self::ScalarRef<'a>>;
/// # Safety
///
/// Calling this method with an out-of-bounds index is *[undefined behavior]*
unsafe fn index_column_unchecked<'a>(
col: &'a Self::Column,
index: usize,
) -> Self::ScalarRef<'a>;
fn slice_column<'a>(col: &'a Self::Column, range: Range<usize>) -> Self::Column;
fn iter_column<'a>(col: &'a Self::Column) -> Self::ColumnIterator<'a>;
fn column_to_builder(col: Self::Column) -> Self::ColumnBuilder;
fn builder_len(builder: &Self::ColumnBuilder) -> usize;
fn push_item(builder: &mut Self::ColumnBuilder, item: Self::ScalarRef<'_>);
fn push_default(builder: &mut Self::ColumnBuilder);
fn append_column(builder: &mut Self::ColumnBuilder, other: &Self::Column);
fn build_column(builder: Self::ColumnBuilder) -> Self::Column;
fn build_scalar(builder: Self::ColumnBuilder) -> Self::Scalar;
fn scalar_memory_size<'a>(_: &Self::ScalarRef<'a>) -> usize {
std::mem::size_of::<Self::Scalar>()
}
fn column_memory_size(col: &Self::Column) -> usize {
Self::column_len(col) * std::mem::size_of::<Self::Scalar>()
}
}
pub trait ArgType: ValueType {
fn data_type() -> DataType;
fn full_domain() -> Self::Domain;
fn create_builder(capacity: usize, generics: &GenericMap) -> Self::ColumnBuilder;
fn column_from_vec(vec: Vec<Self::Scalar>, generics: &GenericMap) -> Self::Column {
Self::column_from_iter(vec.iter().cloned(), generics)
}
fn column_from_iter(
iter: impl Iterator<Item = Self::Scalar>,
generics: &GenericMap,
) -> Self::Column {
let mut col = Self::create_builder(iter.size_hint().0, generics);
for item in iter {
Self::push_item(&mut col, Self::to_scalar_ref(&item));
}
Self::build_column(col)
}
fn column_from_ref_iter<'a>(
iter: impl Iterator<Item = Self::ScalarRef<'a>>,
generics: &GenericMap,
) -> Self::Column {
let mut col = Self::create_builder(iter.size_hint().0, generics);
for item in iter {
Self::push_item(&mut col, item);
}
Self::build_column(col)
}
}
|
// 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.
use roxmltree;
use simplecss;
use simplecss::Token as CssToken;
use svgtypes::xmlparser::{
Stream,
StrSpan,
TextPos,
};
use {
AttributeId,
AttributeValue,
Document,
ElementId,
FilterSvg,
Node,
ParseOptions,
ParserError,
};
use super::{
Links,
NodeStringData,
PostData,
};
#[derive(Clone, Copy, Debug)]
enum CssSelector<'a> {
Universal,
Type(&'a str),
Id(&'a str),
Class(&'a str),
}
pub fn resolve_css(
ro_doc: &roxmltree::Document,
doc: &Document,
post_data: &mut PostData,
opt: &ParseOptions,
) -> Result<(), ParserError> {
// remember all resolved classes
let mut resolved_classes: Vec<String> = Vec::with_capacity(16);
for node in ro_doc.descendants().filter(|n| n.has_tag_name("style")) {
match node.attribute("type") {
Some("text/css") => {}
None => {}
Some(_) => continue,
}
let style = match node.text() {
Some(s) => StrSpan::from(s),
None => continue,
};
if let Err(_) = parse_style(style, doc, post_data, &mut resolved_classes, opt) {
let text_node = node.first_child().unwrap();
// TODO: test
let pos = ro_doc.text_pos_from(text_node.pos());
return Err(ParserError::UnsupportedCSS(pos));
}
}
postprocess_class_selector(&resolved_classes, &mut post_data.class_attrs, opt);
Ok(())
}
fn parse_style(
style: StrSpan,
doc: &Document,
post_data: &mut PostData,
resolved_classes: &mut Vec<String>,
opt: &ParseOptions,
) -> Result<(), ParserError> {
let mut selectors: Vec<CssSelector> = Vec::new();
let mut values: Vec<(&str,&str)> = Vec::with_capacity(16);
let mut tokenizer = {
let mut s = Stream::from(style);
// check for a empty string
s.skip_spaces();
if s.at_end() {
// ignore such CSS
return Ok(())
}
// we use 'new_bound' method to get absolute error positions
simplecss::Tokenizer::new(style.to_str())
};
'root: loop {
selectors.clear();
values.clear();
// get list of selectors
loop {
// remember position before next token
let last_pos = tokenizer.pos();
let token = tokenizer.parse_next()?;
match token {
CssToken::EndOfStream => {
// parsing finished
break 'root;
}
CssToken::BlockStart => {
// stop selectors parsing
break;
}
CssToken::Comma => {
// we ignore 'comma' token
continue;
}
_ => {}
}
// currently we support only simple selectors
let selector = match token {
CssToken::UniversalSelector => CssSelector::Universal,
CssToken::TypeSelector(name) => CssSelector::Type(name),
CssToken::IdSelector(name) => CssSelector::Id(name),
CssToken::ClassSelector(name) => CssSelector::Class(name),
CssToken::AttributeSelector(_)
| CssToken::PseudoClass(_)
| CssToken::LangPseudoClass(_)
| CssToken::Combinator(_) => {
return Err(ParserError::UnsupportedCSS(gen_err_pos(style, last_pos)));
}
_ => {
return Err(ParserError::InvalidCSS(gen_err_pos(style, last_pos)));
}
};
selectors.push(selector);
}
// get list of declarations
loop {
// remember position before next token
let last_pos = tokenizer.pos();
match tokenizer.parse_next()? {
CssToken::Declaration(name, value) => values.push((name, value)),
CssToken::BlockEnd => break,
CssToken::EndOfStream => break 'root,
_ => {
return Err(ParserError::InvalidCSS(gen_err_pos(style, last_pos)));
}
}
}
// process selectors
for selector in &selectors {
match *selector {
CssSelector::Universal => {
for (_, mut node) in doc.root().descendants().svg() {
apply_css_attributes(&values, &mut node, &mut post_data.links, opt)?;
}
}
CssSelector::Type(name) => {
if let Some(eid) = ElementId::from_str(name) {
for (id, mut node) in doc.root().descendants().svg() {
if id == eid {
apply_css_attributes(&values, &mut node, &mut post_data.links, opt)?;
}
}
} else {
warn!("CSS styles for a non-SVG element ('{}') are ignored.", name);
}
}
CssSelector::Id(name) => {
if let Some(mut node) = doc.root().descendants().find(|n| *n.id() == name) {
apply_css_attributes(&values, &mut node, &mut post_data.links, opt)?;
}
}
CssSelector::Class(name) => {
// we use already collected list of 'class' attributes
for d in post_data.class_attrs.iter_mut().filter(|n| n.text == name) {
apply_css_attributes(&values, &mut d.node, &mut post_data.links, opt)?;
resolved_classes.push(name.to_string());
}
}
}
}
}
Ok(())
}
fn postprocess_class_selector<'a>(
resolved_classes: &[String],
class_attrs: &mut Vec<NodeStringData>,
opt: &ParseOptions,
) {
// remove resolved classes
class_attrs.retain(|n| !resolved_classes.contains(&n.text));
if opt.skip_unresolved_classes {
for d in class_attrs {
warn!("Could not resolve an unknown class: {}.", d.text);
}
} else {
// create 'class' attributes with unresolved classes
for d in class_attrs {
if d.node.has_attribute(AttributeId::Class) {
let mut attrs = d.node.attributes_mut();
let class_val = attrs.get_value_mut(AttributeId::Class);
if let Some(&mut AttributeValue::String(ref mut text)) = class_val {
text.push(' ');
text.push_str(&d.text);
}
} else {
d.node.set_attribute((AttributeId::Class, d.text.clone()));
}
}
}
}
fn apply_css_attributes<'a>(
values: &[(&str, &'a str)],
node: &mut Node,
links: &mut Links,
opt: &ParseOptions,
) -> Result<(), ParserError> {
for &(aname, avalue) in values {
match AttributeId::from_str(aname) {
Some(aid) => {
let mut parse_attr = |aid: AttributeId| {
// TODO: to a proper stream
super::parse_svg_attribute_value(
aid, StrSpan::from(avalue), opt,
node, links,
)
};
if aid == AttributeId::Marker {
// The SVG specification defines three properties to reference markers:
// `marker-start`, `marker-mid`, `marker-end`.
// It also provides a shorthand property, marker.
// Using the marker property from a style sheet
// is equivalent to using all three (start, mid, end).
// However, shorthand properties cannot be used as presentation attributes.
// So we have to convert it to presentation attributes.
parse_attr(AttributeId::MarkerStart)?;
parse_attr(AttributeId::MarkerMid)?;
parse_attr(AttributeId::MarkerEnd)?;
} else {
parse_attr(aid)?;
}
}
None => {
node.set_attribute((aname, avalue));
}
}
}
Ok(())
}
fn gen_err_pos(span: StrSpan, pos: usize) -> TextPos {
let s = Stream::from(span.full_str());
s.gen_error_pos_from(pos)
}
|
// Copyright 2017 Dasein Phaos aka. Luxko
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! sampler description
use pipeline::sampler::*;
pub type ComparisonFunc = ::pipeline::ComparisonFunc;
/// describes a sampler
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct SamplerDesc {
/// filtering method
pub filter: Filter,
/// address mode for `u` outside [0, 1]
pub address_u: TextureAddressMode,
/// address mode for `v` outside [0, 1]
pub address_v: TextureAddressMode,
/// address mode for `w` outside [0, 1]
pub address_w: TextureAddressMode,
/// mipmap level bias
pub mip_bias: f32,
/// claming value for anisotropic filters, valid between [1..16]
pub max_anisotropy: u32,
/// function used to compare sampled data against existing sampled data
pub comparison_func: ComparisonFunc,
/// border color to use if address mod is `BORDER`
pub border_color: BorderColor,
/// lower end of the mipmap level to clamp access to
pub min_lod: f32,
/// higher end of the mipmap level to clamp access to
pub max_lod: f32,
}
|
pub struct Solution;
impl Solution {
pub fn plus_one(digits: Vec<i32>) -> Vec<i32> {
let mut digits = digits;
let mut i = digits.len() - 1;
loop {
if digits[i] == 9 {
digits[i] = 0;
if i == 0 {
digits.insert(0, 1);
break;
}
i -= 1;
} else {
digits[i] += 1;
break;
}
}
digits
}
}
#[test]
fn test0066() {
assert_eq!(Solution::plus_one(vec![1, 2, 3]), vec![1, 2, 4]);
assert_eq!(Solution::plus_one(vec![4, 3, 2, 1]), vec![4, 3, 2, 2]);
assert_eq!(Solution::plus_one(vec![1, 9]), vec![2, 0]);
assert_eq!(Solution::plus_one(vec![9, 9, 9, 9]), vec![1, 0, 0, 0, 0]);
}
|
use std::io;
use d04::*;
use file_reader;
const INPUT_FILENAME: &str = "input.txt";
fn main() {
let input_str = match file_reader::file_to_vec(INPUT_FILENAME) {
Err(_) => {
println!("Couldn't turn file into vec!");
return;
},
Ok(v) => v,
};
let mut input_str_f: Vec<String> = Vec::new();
let mut input_idx = 0;
for line in input_str.into_iter() {
if input_str_f.len() == input_idx {
input_str_f.push(line);
} else if line == "" {
input_idx += 1;
} else {
input_str_f[input_idx].push_str(" ");
input_str_f[input_idx].push_str(&line);
}
}
let input: Vec<PpData> =
input_str_f.into_iter().map(process_input).collect();
let result = input.into_iter().map(validate_pp).filter_map(io::Result::ok).collect::<Vec<()>>().len();
println!("{:?}", result);
}
fn process_input(input: String) -> PpData {
let mut data: PpData = PpData::new();
for info in input.split(" ") {
let colon_idx = info.find(':').unwrap();
let key = &info[0..colon_idx];
let val = &info[colon_idx + 1..];
match key {
"byr" => data.byr = Some(String::from(val)),
"iyr" => data.iyr = Some(String::from(val)),
"eyr" => data.eyr = Some(String::from(val)),
"hgt" => data.hgt = Some(String::from(val)),
"hcl" => data.hcl = Some(String::from(val)),
"ecl" => data.ecl = Some(String::from(val)),
"pid" => data.pid = Some(String::from(val)),
"cid" => data.cid = Some(String::from(val)),
_ => println!("BAD THINGS HAPPENING!"),
}
}
data
}
fn validate_pp(data: PpData) -> io::Result<()> {
if data.byr != None &&
data.iyr != None &&
data.eyr != None &&
data.hgt != None &&
data.hcl != None &&
data.ecl != None &&
data.pid != None {
Ok(())
} else {
Err(io::Error::new(io::ErrorKind::Other, "invalid pp"))
}
}
|
use data_types::Timestamp;
use iox_catalog::interface::Catalog;
use observability_deps::tracing::*;
use snafu::prelude::*;
use std::{sync::Arc, time::Duration};
use tokio::{select, time::sleep};
use tokio_util::sync::CancellationToken;
pub(crate) async fn perform(
shutdown: CancellationToken,
catalog: Arc<dyn Catalog>,
cutoff: Duration,
sleep_interval_minutes: u64,
) -> Result<()> {
loop {
let older_than = Timestamp::from(catalog.time_provider().now() - cutoff);
// do the delete, returning the deleted files
let deleted = catalog
.repositories()
.await
.parquet_files()
.delete_old_ids_only(older_than) // read/write
.await
.context(DeletingSnafu)?;
info!(delete_count = %deleted.len(), "iox_catalog::delete_old()");
select! {
_ = shutdown.cancelled() => {
break
},
_ = sleep(Duration::from_secs(60 * sleep_interval_minutes)) => (),
}
}
Ok(())
}
#[derive(Debug, Snafu)]
#[allow(missing_docs)]
pub enum Error {
#[snafu(display("Failed to delete old parquet files in catalog"))]
Deleting {
source: iox_catalog::interface::Error,
},
}
pub(crate) type Result<T, E = Error> = std::result::Result<T, E>;
|
extern crate proc_macro;
extern crate cfg;
extern crate gearley;
extern crate internship;
mod interner;
#[macro_use]
mod macros;
use std::collections::BTreeMap;
use cfg::earley::Grammar;
use cfg::Symbol;
use gearley::grammar::InternalGrammar;
use gearley::recognizer::Recognizer;
use gearley::forest::NullForest;
use self::interner::Interner;
pub struct NeighborhoodRuntime<T> {
stmts: Vec<Neighborhood<T>>,
param_map: Interner,
external_syms: BTreeMap<ExtPath, Symbol>,
external_grammar: Grammar,
internal_grammar: Option<InternalGrammar>,
}
impl<T> NeighborhoodRuntime<T> {
pub fn new() -> Self {
NeighborhoodRuntime {
stmts: Vec::new(),
param_map: Interner::new(),
external_syms: BTreeMap::new(),
external_grammar: Grammar::new(),
internal_grammar: None,
}
}
pub fn rule(&mut self, neighborhood: Neighborhood<T>) {
self.stmts.push(neighborhood);
}
pub fn process_rules(&mut self) {
let mut neighborhoods = neighborhood.separate_alternatives();
for neighborhood in &mut neighborhoods {
neighborhood.externalize();
}
let (start, nested, terminal) = self.external_grammar.sym();
external.rule(start).rhs([nested, terminal])
.rule(nested).rhs([terminal, terminal]);
external.set_start(start);
let cfg = InternalGrammar::from_grammar(&external);
}
pub fn validate_steps(&self, steps: &[T]) {
let mut rec = Recognizer::new(&cfg, NullForest);
for step in steps {
recognizer.scan();
}
}
}
impl<T> Path<T> {
fn segments(&self) -> Vec<Vec<Step>> {
self.steps
}
}
// #[derive(Clone, Eq, PartialEq, Ord, PartialOrd)]
// pub enum Lhs {
// Symbol(String),
// Param {
// rhs: String,
// ty_param: String,
// },
// }
pub enum Matcher<T> {
Symbol(String),
ParamApply {
rhs: String,
ty_param: String,
},
Pattern(Box<dyn Fn(&T) -> bool>),
// Processed.
ExtSymbol(Symbol),
ExtParamApply {
rhs: Symbol,
ty_param: usize,
},
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum Step {
Alternative(usize),
Idx(usize),
Repeat,
// Lhs can come after param introduction.
IntroduceParam(String),
Lhs,
Rhs,
// Processed.
ExtIntroduceParam(usize),
ExtAlternativeAndIdx(Vec<usize>, usize),
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum ExtStep {
Repeat,
// Lhs can come after param introduction.
Lhs,
Rhs,
// Processed.
AlternativeAndIdx(Vec<usize>, usize),
}
pub struct Path<T> {
steps: Vec<Step>,
matcher: Matcher<T>,
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct ExtPath {
steps: Vec<ExtStep>,
symbol: Symbol,
}
pub struct Neighborhood<T> {
paths: Vec<Path<T>>,
}
impl<T> Neighborhood<T> {
fn new() -> Self {
Neighborhood {
paths: vec![]
}
}
}
// impl Lhs {
// fn variant(s: &str) -> Lhs {
// Lhs::Symbol(s.to_string())
// }
// fn apply(ty: &str, parameter: &str) -> Lhs {
// Lhs::Param { rhs: ty.to_string(), ty_param: parameter.to_string() }
// }
// }
// impl<T> Into<Lhs> for Matcher<T> {
// fn into(self) -> Lhs {
// match self {
// Matcher::Symbol(sym) => {
// Lhs::Symbol(sym)
// }
// Matcher::Param { rhs, ty_param } => {
// Lhs::Param { rhs, ty_param }
// }
// Matcher::Pattern(_) => panic!("invalid conversion")
// }
// }
// }
impl Step {
fn is_alternative(&self) -> bool {
match self {
&Step::Alternative(_) => true,
_ => false,
}
}
fn is_idx(&self) -> bool {
match self {
&Step::Idx(_) => true,
_ => false,
}
}
}
impl<U> Matcher<U> {
pub fn variant(s: &str) -> Matcher<U> {
Matcher::Symbol(s.to_string())
}
pub fn apply(ty: &str, parameter: &str) -> Matcher<U> {
Matcher::Param { rhs: ty.to_string(), ty_param: parameter.to_string() }
}
pub fn match_pattern(func: Box<dyn Fn(&U) -> bool>) -> Matcher<U> {
Matcher::Pattern(func)
}
pub fn into_neighborhood(self) -> Neighborhood<U> {
Neighborhood {
paths: vec![
Path {
steps: vec![],
matcher: self,
}
]
}
}
}
impl<T> Neighborhood<T> {
pub fn introduce_param(mut self, param: &str) -> Neighborhood<T> {
for path in &mut self.paths {
path.steps.insert(0, Step::IntroduceParam(param.to_string()));
}
self
}
pub fn repeat(mut self) -> Neighborhood<T> {
for path in &mut self.paths {
path.steps.insert(0, Step::Repeat);
}
self
}
pub fn then(mut self, mut next: Neighborhood<T>) -> Neighborhood<T> {
if !self.paths.iter().all(|path| path.steps.get(0).map_or(false, |step| step.is_idx())) {
for path in &mut self.paths {
path.steps.insert(0, Step::Idx(0));
}
}
let last_num = self.paths.iter().map(|path|
match path.steps[0] {
Step::Idx(n) => n,
_ => unreachable!()
}
).max().map_or(-1, |n| n as isize);
for path in &mut next.paths {
path.steps.insert(0, Step::Idx((last_num + 1) as usize));
}
self.paths.extend(next.paths.into_iter());
self
}
pub fn or(mut self, mut next: Neighborhood<T>) -> Neighborhood<T> {
if !self.paths.iter().all(|path| path.steps.get(0).map_or(false, |step| step.is_idx())) {
for path in &mut self.paths {
path.steps.insert(0, Step::Alternative(0));
}
}
let last_num = self.paths.iter().map(|path|
match path.steps[0] {
Step::Alternative(n) => n,
_ => unreachable!()
}
).max().map_or(-1, |n| n as isize);
for path in &mut next.paths {
path.steps.insert(0, Step::Alternative((last_num + 1) as usize));
}
self.paths.extend(next.paths.into_iter());
self
}
pub fn offshoot(mut self, mut next: Neighborhood<T>) -> Neighborhood<T> {
if !self.paths.iter().all(|path| path.steps.get(0).map_or(false, |step| step.is_idx())) {
for path in &mut self.paths {
path.steps.insert(0, Step::Alternative(0));
}
}
let last_num = self.paths.iter().map(|path|
match path.steps[0] {
Step::Alternative(n) => n,
_ => unreachable!()
}
).max().map_or(-1, |n| n as isize);
for path in &mut next.paths {
path.steps.insert(0, Step::Alternative((last_num + 1) as usize));
}
self.paths.extend(next.paths.into_iter());
self
}
pub fn lhs_then(mut self, mut rhs: Neighborhood<T>) -> Self {
assert_eq!(self.paths.len(), 1);
for lhs_path in &mut self.paths {
lhs_path.steps.insert(0, Step::Lhs);
}
for mut rhs_path in rhs.paths {
rhs_path.steps.insert(0, Step::Rhs);
self.paths.push(rhs_path);
}
rhs
}
fn separate_alternatives(self) -> Vec<Neighborhood<T>> {
}
fn externalize(&mut self) {
let mut new_paths = vec![];
for path in &mut self.paths {
for i in 0 .. path.steps.len() {
match path.steps[i] {
Step::Rhs => {
let mut used_indices = vec![];
let mut alts = vec![];
let mut idx = None;
for j in i + 1 .. path.steps.len() {
match path.steps[j] {
Step::Alternative(i) => {
alts.push(i);
used_indices.push(j);
}
Step::Idx(i) => {
idx = Some(i);
used_indices.push(j);
break;
}
Step::Repeat | Step::IntroduceParam(..) => break,
Step::Rhs | Step::AlternativeAndIdx(..) => unreachable!()
}
}
used_indices.sort();
for i in used_indices.into_iter().rev() {
path.steps.remove(i);
}
path.steps[i] = Step::AlternativeAndIdx(alts, idx.unwrap_or(0));
}
Step::Alternative(i) => {
let mut used_indices = vec![];
let mut alts = vec![i];
let mut idx = None;
for j in i + 1 .. path.steps.len() {
match path.steps[j] {
Step::Alternative(i) => {
alts.push(i);
used_indices.push(j);
}
Step::Idx(i) => {
idx = Some(i);
used_indices.push(j);
break;
}
Step::Repeat | Step::IntroduceParam(..) => break,
Step::Rhs | Step::AlternativeAndIdx(..) => unreachable!()
}
}
used_indices.sort();
for i in used_indices.into_iter().rev() {
path.steps.remove(i);
}
path.steps[i] = Step::AlternativeAndIdx(alts, idx.unwrap_or(0));
}
Step::Idx(i) => {
path.steps[i] = Step::AlternativeAndIdx(vec![], i);
}
_ => {}
}
}
}
for i in 0 .. self.paths.len() {
let mut used_indices = vec![];
for j in 0 .. self.paths[i].steps.len() {
match self.paths[i].steps[j] {
Step::IntroduceParam(ref param_name) => {
let mut k = i + 1;
while k < self.paths.len() &&
self.paths[k].steps[.. j + 1].iter().enumerate().all(|(l, step)| step == self.paths[i].steps[l]) {
self.paths[k].steps[j] = Step::ExtIntroduceParam()
continue;
}
break;
}
used_indices.push(j);
}
_ => {}
}
}
used_indices.sort();
for j in used_indices.into_iter().rev() {
path.steps.remove(j);
}
}
for path in &mut self.paths {
for i in 1 .. path.steps.len() {
let path = Path { steps: path.steps[.. i].to_vec() };
self.external_syms.entry(path).or_insert_with(|| self.external_grammar.sym());
}
}
}
}
|
#![feature(proc_macro)]
extern crate proc_macro;
extern crate regex;
use proc_macro::TokenStream;
use std::str::FromStr;
#[proc_macro_derive(AnswerFn)]
pub fn derive_packet_enum(input: TokenStream) -> TokenStream {
let input_string = input.to_string();
let mut i = 0;
loop {
input_string.
}
let s:String = input_string.chars()
.map(|x| match x {
'!' => '?',
'A'...'Z' => 'X',
'a'...'z' => 'x',
_ => x}
).collect();
"fn answer() -> u32 { 42 }".parse().unwrap()
}
let in_decimal_system = i32::from_str_radix(&input_string, 2).unwrap();
//convert back to string
let output_string = in_decimal_system.to_string();
//convert back to token stream
to_tokenstream(&output_string)
}
#[cfg(test)]
mod tests {
#[test]
fn simple_test() {
enum p {
struct a{x:i32}
struct b(i32, f32)
}
assert_eq!(2 + 2, 4);
}
}
|
extern crate rustc_serialize;
extern crate bincode;
use std::collections::hash_map::HashMap;
/// Messages sent and received over a WebSocket.
#[derive(RustcEncodable, RustcDecodable, PartialEq, Clone)]
pub struct PeerMessage {
/// Host address passed in via CLI. Used for identification.
pub sender: String,
/// Vector clocks for each process.
pub clocks: HashMap<String, u32>,
/// The message that we want to send. For now, we're testing with a string.
pub message: String,
}
|
use super::pure::PurenessInsights;
use crate::mir::{Body, Expression, Id, VisibleExpressions};
use rustc_hash::FxHashSet;
use std::mem;
impl Expression {
/// All IDs defined inside this expression. For all expressions except
/// functions, this returns an empty vector. The IDs are returned in the
/// order that they are defined in.
pub fn defined_ids(&self) -> Vec<Id> {
let mut defined = vec![];
self.collect_defined_ids(&mut defined);
defined
}
fn collect_defined_ids(&self, defined: &mut Vec<Id>) {
if let Expression::Function {
parameters,
responsible_parameter,
body,
..
} = self
{
defined.extend(parameters);
defined.push(*responsible_parameter);
body.collect_defined_ids(defined);
}
}
}
impl Body {
pub fn defined_ids(&self) -> Vec<Id> {
let mut defined = vec![];
self.collect_defined_ids(&mut defined);
defined
}
fn collect_defined_ids(&self, defined: &mut Vec<Id>) {
for (id, expression) in self.iter() {
defined.push(id);
expression.collect_defined_ids(defined);
}
}
}
impl Expression {
/// All IDs referenced inside this expression. If this is a function, this
/// also includes references to locally defined IDs. IDs are returned in the
/// order that they are referenced, which means that the vector may contain
/// the same ID multiple times.
// PERF: Maybe change this to accept a closure instead of collecting them to an `FxHashSet`
pub fn referenced_ids(&self) -> FxHashSet<Id> {
let mut referenced = FxHashSet::default();
self.collect_referenced_ids(&mut referenced);
referenced
}
fn collect_referenced_ids(&self, referenced: &mut FxHashSet<Id>) {
match self {
Expression::Int(_)
| Expression::Text(_)
| Expression::Builtin(_)
| Expression::HirId(_) => {}
Expression::Tag { value, .. } => {
if let Some(value) = value {
referenced.insert(*value);
}
}
Expression::List(items) => {
referenced.extend(items);
}
Expression::Struct(fields) => {
for (key, value) in fields {
referenced.insert(*key);
referenced.insert(*value);
}
}
Expression::Reference(reference) => {
referenced.insert(*reference);
}
Expression::Function { body, .. } => body.collect_referenced_ids(referenced),
Expression::Parameter => {}
Expression::Call {
function,
arguments,
responsible,
} => {
referenced.insert(*function);
referenced.extend(arguments);
referenced.insert(*responsible);
}
Expression::UseModule {
current_module: _,
relative_path,
responsible,
} => {
referenced.insert(*relative_path);
referenced.insert(*responsible);
}
Expression::Panic {
reason,
responsible,
} => {
referenced.insert(*reason);
referenced.insert(*responsible);
}
Expression::TraceCallStarts {
hir_call,
function,
arguments,
responsible,
} => {
referenced.insert(*hir_call);
referenced.insert(*function);
referenced.extend(arguments);
referenced.insert(*responsible);
}
Expression::TraceCallEnds { return_value } => {
referenced.insert(*return_value);
}
Expression::TraceExpressionEvaluated {
hir_expression,
value,
} => {
referenced.insert(*hir_expression);
referenced.insert(*value);
}
Expression::TraceFoundFuzzableFunction {
hir_definition,
function,
} => {
referenced.insert(*hir_definition);
referenced.insert(*function);
}
}
}
}
impl Body {
fn collect_referenced_ids(&self, referenced: &mut FxHashSet<Id>) {
for (_, expression) in self.iter() {
expression.collect_referenced_ids(referenced);
}
}
}
impl Expression {
pub fn captured_ids(&self) -> FxHashSet<Id> {
let mut ids = self.referenced_ids();
for id in self.defined_ids() {
ids.remove(&id);
}
ids
}
}
impl Body {
pub fn all_ids(&self) -> FxHashSet<Id> {
let mut ids = self.defined_ids().into_iter().collect();
self.collect_referenced_ids(&mut ids);
ids
}
}
impl Id {
pub fn semantically_equals(
self,
other: Id,
visible: &VisibleExpressions,
pureness: &PurenessInsights,
) -> Option<bool> {
if self == other {
return Some(true);
}
let self_expr = visible.get(self);
let other_expr = visible.get(other);
if let Expression::Reference(reference) = self_expr {
return reference.semantically_equals(other, visible, pureness);
}
if let Expression::Reference(reference) = other_expr {
return self.semantically_equals(*reference, visible, pureness);
}
if self_expr.is_parameter() || other_expr.is_parameter() {
return None;
}
if self_expr == other_expr {
return Some(true);
}
if !pureness.is_definition_const(self_expr) || !pureness.is_definition_const(other_expr) {
return None;
}
Some(false)
}
}
impl Expression {
/// Replaces all referenced IDs. Does *not* replace IDs that are defined in
/// this expression.
pub fn replace_id_references(&mut self, replacer: &mut impl FnMut(&mut Id)) {
match self {
Expression::Int(_)
| Expression::Text(_)
| Expression::Builtin(_)
| Expression::HirId(_) => {}
Expression::Tag { value, .. } => {
if let Some(value) = value {
replacer(value);
}
}
Expression::List(items) => {
for item in items {
replacer(item);
}
}
Expression::Struct(fields) => {
for (key, value) in fields {
replacer(key);
replacer(value);
}
}
Expression::Reference(reference) => replacer(reference),
Expression::Function {
original_hirs: _,
parameters,
responsible_parameter,
body,
} => {
for parameter in parameters {
replacer(parameter);
}
replacer(responsible_parameter);
body.replace_id_references(replacer);
}
Expression::Parameter => {}
Expression::Call {
function,
arguments,
responsible,
} => {
replacer(function);
for argument in arguments {
replacer(argument);
}
replacer(responsible);
}
Expression::UseModule {
current_module: _,
relative_path,
responsible,
} => {
replacer(relative_path);
replacer(responsible);
}
Expression::Panic {
reason,
responsible,
} => {
replacer(reason);
replacer(responsible);
}
Expression::TraceCallStarts {
hir_call,
function,
arguments,
responsible,
} => {
replacer(hir_call);
replacer(function);
for argument in arguments {
replacer(argument);
}
replacer(responsible);
}
Expression::TraceCallEnds { return_value } => {
replacer(return_value);
}
Expression::TraceExpressionEvaluated {
hir_expression,
value,
} => {
replacer(hir_expression);
replacer(value);
}
Expression::TraceFoundFuzzableFunction {
hir_definition,
function,
} => {
replacer(hir_definition);
replacer(function);
}
}
}
}
impl Body {
pub fn replace_id_references(&mut self, replacer: &mut impl FnMut(&mut Id)) {
for (_, expression) in self.iter_mut() {
expression.replace_id_references(replacer);
}
}
}
impl Expression {
/// Replaces all IDs in this expression using the replacer, including
/// definitions.
pub fn replace_ids(&mut self, replacer: &mut impl FnMut(&mut Id)) {
match self {
Expression::Function {
original_hirs: _,
parameters,
responsible_parameter,
body,
} => {
for parameter in parameters {
replacer(parameter);
}
replacer(responsible_parameter);
body.replace_ids(replacer);
}
// All other expressions don't define IDs and instead only contain
// references. Thus, the function above does the job.
_ => self.replace_id_references(replacer),
}
}
}
impl Body {
pub fn replace_ids(&mut self, replacer: &mut impl FnMut(&mut Id)) {
let body = mem::take(self);
for (mut id, mut expression) in body.into_iter() {
replacer(&mut id);
expression.replace_ids(replacer);
self.push(id, expression);
}
}
}
|
#[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::MODE {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct CRC_POLYR {
bits: u8,
}
impl CRC_POLYR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct BIT_RVS_WRR {
bits: bool,
}
impl BIT_RVS_WRR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct CMPL_WRR {
bits: bool,
}
impl CMPL_WRR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct BIT_RVS_SUMR {
bits: bool,
}
impl BIT_RVS_SUMR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct CMPL_SUMR {
bits: bool,
}
impl CMPL_SUMR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Proxy"]
pub struct _CRC_POLYW<'a> {
w: &'a mut W,
}
impl<'a> _CRC_POLYW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _BIT_RVS_WRW<'a> {
w: &'a mut W,
}
impl<'a> _BIT_RVS_WRW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CMPL_WRW<'a> {
w: &'a mut W,
}
impl<'a> _CMPL_WRW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _BIT_RVS_SUMW<'a> {
w: &'a mut W,
}
impl<'a> _BIT_RVS_SUMW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CMPL_SUMW<'a> {
w: &'a mut W,
}
impl<'a> _CMPL_SUMW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:1 - CRC polynom: 1X= CRC-32 polynomial 01= CRC-16 polynomial 00= CRC-CCITT polynomial"]
#[inline]
pub fn crc_poly(&self) -> CRC_POLYR {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
};
CRC_POLYR { bits }
}
#[doc = "Bit 2 - Data bit order: 1= Bit order reverse for CRC_WR_DATA (per byte) 0= No bit order reverse for CRC_WR_DATA (per byte)"]
#[inline]
pub fn bit_rvs_wr(&self) -> BIT_RVS_WRR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
};
BIT_RVS_WRR { bits }
}
#[doc = "Bit 3 - Data complement: 1= 1's complement for CRC_WR_DATA 0= No 1's complement for CRC_WR_DATA"]
#[inline]
pub fn cmpl_wr(&self) -> CMPL_WRR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CMPL_WRR { bits }
}
#[doc = "Bit 4 - CRC sum bit order: 1= Bit order reverse for CRC_SUM 0= No bit order reverse for CRC_SUM"]
#[inline]
pub fn bit_rvs_sum(&self) -> BIT_RVS_SUMR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
};
BIT_RVS_SUMR { bits }
}
#[doc = "Bit 5 - CRC sum complement: 1= 1's complement for CRC_SUM 0=No 1's complement for CRC_SUM"]
#[inline]
pub fn cmpl_sum(&self) -> CMPL_SUMR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CMPL_SUMR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:1 - CRC polynom: 1X= CRC-32 polynomial 01= CRC-16 polynomial 00= CRC-CCITT polynomial"]
#[inline]
pub fn crc_poly(&mut self) -> _CRC_POLYW {
_CRC_POLYW { w: self }
}
#[doc = "Bit 2 - Data bit order: 1= Bit order reverse for CRC_WR_DATA (per byte) 0= No bit order reverse for CRC_WR_DATA (per byte)"]
#[inline]
pub fn bit_rvs_wr(&mut self) -> _BIT_RVS_WRW {
_BIT_RVS_WRW { w: self }
}
#[doc = "Bit 3 - Data complement: 1= 1's complement for CRC_WR_DATA 0= No 1's complement for CRC_WR_DATA"]
#[inline]
pub fn cmpl_wr(&mut self) -> _CMPL_WRW {
_CMPL_WRW { w: self }
}
#[doc = "Bit 4 - CRC sum bit order: 1= Bit order reverse for CRC_SUM 0= No bit order reverse for CRC_SUM"]
#[inline]
pub fn bit_rvs_sum(&mut self) -> _BIT_RVS_SUMW {
_BIT_RVS_SUMW { w: self }
}
#[doc = "Bit 5 - CRC sum complement: 1= 1's complement for CRC_SUM 0=No 1's complement for CRC_SUM"]
#[inline]
pub fn cmpl_sum(&mut self) -> _CMPL_SUMW {
_CMPL_SUMW { w: self }
}
}
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
struct UsizeRef<'a> {
a: &'a usize
}
type RefTo = Box<for<'r> Fn(&'r Vec<usize>) -> UsizeRef<'r>>;
fn ref_to<'a>(vec: &'a Vec<usize>) -> UsizeRef<'a> {
UsizeRef{ a: &vec[0]}
}
fn main() {
// Regression test: this was causing ICEs; it should compile.
let a: RefTo = Box::new(|vec: &Vec<usize>| {
UsizeRef{ a: &vec[0] }
});
}
|
use chrono::Utc;
use serenity::{
model::prelude::*, prelude::*
};
use tracing::debug;
use rand::Rng;
use std::time::Instant;
use crate::DATABASE;
use super::help;
mod image_utils;
mod level_up;
pub mod rank;
pub mod leaderboard;
pub fn get_level_xp(level: i32) -> i32 {
5 * level.pow(2) + 50 * level + 100
}
pub async fn on_message(ctx: Context, msg: Message) {
//Don't award points to bots
if msg.author.bot {return;};
let guild_id = if let Some(guild_id) = msg.guild_id {guild_id} else {return;};
let target = if let Ok(target) =
guild_id.member(&ctx, msg.author.id).await {
target
}
else {return;};
let has_tester_role = if let Some(roles) = target.roles(&ctx).await {
let rolenames: Vec<String> = roles.iter().map(|role| role.name.to_lowercase()).collect();
rolenames.contains(&"tester".to_string())
}
else {false};
if has_tester_role {
let now = Instant::now();
let mut database = DATABASE.get().expect("Database not initialized").lock().await;
let db_user = database.get_user(guild_id.to_string(), msg.author.id.to_string()).await;
// only award if user hasn't been awarded in the last minute
if (Utc::now() - db_user.last_xp).num_seconds() > 59 {
let xp = db_user.xp + rand::thread_rng().gen_range(15..25);
let level_xp = get_level_xp(db_user.level);
if xp > level_xp {
database.set_user_level(guild_id.to_string(), msg.author.id.to_string(),
db_user.level+1, xp-level_xp).await;
drop(database);
debug!("Message event locked database for {} micro seconds", now.elapsed().as_micros());
level_up::level_up(&ctx, &msg, target, db_user.level+1).await;
} else {
database.set_user_xp(guild_id.to_string(), msg.author.id.to_string(),
xp).await;
debug!("Message event locked database for {} micro seconds", now.elapsed().as_micros());
}
} else {
debug!("Message event locked database for {} micro seconds", now.elapsed().as_micros());
}
}
}
|
use regex::Regex;
pub struct PasswordEntry {
min: u8,
max: u8,
letter: char,
password: String,
}
impl PasswordEntry {
pub fn from_string(s: String) -> PasswordEntry {
let re = Regex::new(r"(\d+)-(\d+) (.): (.+)").unwrap();
let captures = re.captures(&s).unwrap();
let min = captures.get(1).unwrap().as_str().parse::<u8>().unwrap();
let max = captures.get(2).unwrap().as_str().parse::<u8>().unwrap();
let letter = captures.get(3).unwrap().as_str().chars().next().unwrap();
let password = captures.get(4).unwrap().as_str().to_string();
return PasswordEntry {
min,
max,
letter,
password,
};
}
pub fn valid(&self) -> bool {
let character_count = self.password.matches(self.letter).count() as u8;
return character_count >= self.min && character_count <= self.max;
}
pub fn valid_v2(&self) -> bool {
let first = self.password.chars().nth(self.min as usize - 1).unwrap();
let second = self.password.chars().nth(self.max as usize - 1).unwrap();
return (first == self.letter) ^ (second == self.letter);
}
}
#[cfg(test)]
mod tests {
use crate::password::PasswordEntry;
#[test]
fn test_from_string() {
let entry = PasswordEntry::from_string("7-15 y: asldfjlaksjdflkjasdy".to_string());
assert_eq!(entry.min, 7u8);
assert_eq!(entry.max, 15u8);
assert_eq!(entry.letter, 'y');
assert_eq!(entry.password, "asldfjlaksjdflkjasdy");
}
#[test]
fn test_valid() {
let too_few = PasswordEntry::from_string("20-30 x: aslkxxjalkx".to_string());
let too_many = PasswordEntry::from_string("1-2 y: asdyyasdy".to_string());
let just_right = PasswordEntry::from_string("3-5 z: 123xyzzzkz".to_string());
assert_eq!(too_few.valid(), false);
assert_eq!(too_many.valid(), false);
assert_eq!(just_right.valid(), true);
}
#[test]
fn test_valid_v2() {
let just_right = PasswordEntry::from_string("1-3 a: abcde".to_string());
let both = PasswordEntry::from_string("1-3 b: cdefg".to_string());
let neither = PasswordEntry::from_string("2-9 c: ccccccccc".to_string());
assert_eq!(just_right.valid_v2(), true);
assert_eq!(both.valid_v2(), false);
assert_eq!(neither.valid_v2(), false);
}
}
|
use crate::util;
use crate::youtube;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Album {
#[serde(skip)]
pub url: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub artist: Option<String>, // track id3, incl. VA
pub title: String, // track id3
#[serde(skip_serializing_if = "Option::is_none")]
pub license: Option<String>, // web
#[serde(skip_serializing_if = "Option::is_none")]
pub year: Option<u16>, // track id3
// Ektoplazm releases sometimes have multiple labels
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub labels: Vec<String>, // web
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<String>, // web
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tracks: Vec<Track>, // web
#[serde(skip_serializing_if = "Option::is_none")]
pub youtube_id: Option<youtube::PlaylistID>,
}
impl Album {
pub fn dirname(&self, base_dir: &Path) -> PathBuf {
let mut res = PathBuf::from(base_dir);
let clean = |s: &str| s.replace(" ", "_").replace("/", "_");
let mut comp = match &self.artist {
None => "VA".to_string(),
Some(a) => clean(a),
};
comp.push_str("_-_");
comp.push_str(&clean(&self.title));
res.push(comp);
res
}
fn has_files(&self, base_dir: &Path, basenames: Vec<&PathBuf>) -> bool {
let mut f = self.dirname(base_dir);
for bn in basenames {
f.push(bn);
if !f.is_file() {
return false;
}
assert_eq!(f.pop(), true);
}
true
}
pub fn has_mp3(&self, base_dir: &Path) -> bool {
let basenames: Option<Vec<_>> = self.tracks.iter().map(|x| x.mp3_file.as_ref()).collect();
match basenames {
None => false,
Some(bn) => self.has_files(base_dir, bn),
}
}
pub fn has_video(&self, base_dir: &Path) -> bool {
let basenames: Option<Vec<_>> = self.tracks.iter().map(|x| x.video_file.as_ref()).collect();
match basenames {
None => false,
Some(bn) => self.has_files(base_dir, bn),
}
}
pub fn print(&self) {
let nf = "(none found)".to_string();
println!(
"Artist: {}",
self.artist.as_ref().unwrap_or(&"VA".to_string())
);
println!("Title: {}", self.title);
println!(
"Year: {}",
self.year.map(|n| n.to_string()).unwrap_or(nf.clone())
);
println!("License: {}", self.license.as_ref().unwrap_or(&nf));
println!(
"Label: {}",
if self.labels.is_empty() {
nf.clone()
} else {
self.labels.join(", ")
}
);
println!(
"Tags: {}",
if self.tags.is_empty() {
nf.clone()
} else {
self.tags.join(", ")
}
);
println!(
"YT: {}",
self.youtube_id
.as_ref()
.map(|i| i.as_url())
.unwrap_or(nf.clone())
);
println!("Tracks:");
for (i, t) in self.tracks.iter().enumerate() {
let tnum = i + 1;
println!(" {:02} - {} - {}", tnum, t.artist, t.title);
if let Some(b) = t.bpm {
println!(" BPM: {}", b);
}
if let Some(f) = &t.mp3_file {
println!(
" MP3: {}/{}",
self.dirname(&PathBuf::from("mp3"))
.into_os_string()
.to_string_lossy(),
f.clone().into_os_string().to_string_lossy()
);
}
if let Some(f) = &t.video_file {
println!(
" Video: {}/{}",
self.dirname(&PathBuf::from("video"))
.into_os_string()
.to_string_lossy(),
f.clone().into_os_string().to_string_lossy()
);
}
println!(
" YT: {}",
t.youtube_id
.as_ref()
.map(|i| i.as_url())
.unwrap_or(nf.clone())
);
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Track {
pub artist: String,
pub title: String,
// Single BPM for simplicity even though there are tracks w/ something like "109/175/219"
#[serde(skip_serializing_if = "Option::is_none")]
pub bpm: Option<u16>,
// relative to mp3_subdir
#[serde(skip_serializing_if = "Option::is_none")]
pub mp3_file: Option<PathBuf>,
// relative to video_subdir
#[serde(skip_serializing_if = "Option::is_none")]
pub video_file: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none")]
pub youtube_id: Option<youtube::VideoID>,
}
pub struct Blacklist {
artists: Vec<Regex>,
labels: Vec<Regex>,
}
impl Blacklist {
pub fn new<T>(artists: T, labels: T) -> Result<Blacklist, util::Error>
where
T: IntoIterator,
T::Item: AsRef<str>,
{
let mut res = Blacklist {
artists: vec![],
labels: vec![],
};
let pat = |s: T::Item| format!(r"(?i)^{}$", s.as_ref());
for s in artists {
res.artists.push(Regex::new(&pat(s))?);
}
for s in labels {
res.labels.push(Regex::new(&pat(s))?);
}
Ok(res)
}
pub fn matches(&self, album: &Album) -> bool {
if self
.labels
.iter()
.any(|r| album.labels.iter().any(|l| r.is_match(l)))
{
return true;
}
if self
.artists
.iter()
.any(|r| album.tracks.iter().any(|t| r.is_match(&t.artist)))
{
return true;
}
return false;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn blacklist() {
let black_artists = vec!["donald duck", "agh[0o]ri tantrik"];
let black_labels = vec!["sony", "sonic tantra .*", "supraphon"];
let blacklist = Blacklist::new(black_artists, black_labels).unwrap();
let album = Album {
url: "https://ektoplazm.com/free-music/haltya-japan-anime-punk-sessions-ep".to_string(),
artist: Some("Haltya".to_string()),
title: "Japan Anime Punk Sessions EP".to_string(),
license: Some("https://creativecommons.org/licenses/by-nc-nd/3.0/".to_string()),
year: Some(2012),
labels: vec!["Not Really".to_string()],
tags: vec!["Experimental".to_string(), "Suomi".to_string()],
tracks: vec![
Track {
artist: "Haltya".to_string(),
title: "Övertüre".to_string(),
bpm: None,
mp3_file: None,
video_file: None,
youtube_id: None,
},
Track {
artist: "Haltya".to_string(),
title: "Hiro In The Sky With Diamonds".to_string(),
bpm: None,
mp3_file: None,
video_file: None,
youtube_id: None,
},
],
youtube_id: None,
};
assert!(!blacklist.matches(&album));
let album = Album {
url: "https://ektoplazm.com/free-music/sonic-shamans-vol-ii".to_string(),
artist: Some("VA".to_string()),
title: "Sonic Shamans Vol. II".to_string(),
license: Some("https://creativecommons.org/licenses/by-nc-nd/4.0/".to_string()),
year: Some(2015),
labels: vec!["Sonic Tantra Records".to_string()],
tags: vec!["Darkpsy".to_string(), "Psycore".to_string()],
tracks: vec![
Track {
artist: "Overdream".to_string(),
title: "Skip Sick!".to_string(),
bpm: Some(150),
mp3_file: None,
video_file: None,
youtube_id: None,
},
Track {
artist: "Goch".to_string(),
title: "Falling Stone".to_string(),
bpm: Some(150),
mp3_file: None,
video_file: None,
youtube_id: None,
},
],
youtube_id: None,
};
assert!(blacklist.matches(&album));
let album = Album {
url: "https://ektoplazm.com/free-music/high-tech-mechanica".to_string(),
artist: Some("VA".to_string()),
title: "High Tech Mechanica".to_string(),
license: Some("https://creativecommons.org/licenses/by-nc-sa/3.0/".to_string()),
year: Some(2011),
labels: vec!["Cosmic Crew Records".to_string()],
tags: vec!["Hi-Tech".to_string(), "Psycore".to_string()],
tracks: vec![
Track {
artist: "Murukhan".to_string(),
title: "General Dynamicz".to_string(),
bpm: Some(175),
mp3_file: None,
video_file: None,
youtube_id: None,
},
Track {
artist: "Aghori Tantrik".to_string(),
title: "Ending Lunatic Behaviour".to_string(),
bpm: Some(165),
mp3_file: None,
video_file: None,
youtube_id: None,
},
],
youtube_id: None,
};
assert!(blacklist.matches(&album));
}
}
|
use std::cell::Cell;
use std::fmt;
thread_local! {
static THREAD_TAG: Cell<Tag> = Cell::new(Tag(0));
}
/// Run the given closure with the specified tag.
pub(super) fn with_tag<F, T>(tag: Tag, f: F) -> T
where
F: FnOnce() -> T,
{
return THREAD_TAG.with(|w| {
let _guard = Guard(w.replace(tag));
f()
});
struct Guard(Tag);
impl Drop for Guard {
fn drop(&mut self) {
THREAD_TAG.with(|w| {
w.set(self.0);
});
}
}
}
/// A tag associated with a thread. Threads which are executed with
/// [Thread][super::Thread] support tagging.
///
/// You must ensure that any thread trying to use values first is checked with
/// the current tag through [Tag::ensure_on_thread]. This includes everything
/// which poses a potential thread safety risk.
///
/// This includes, but is not limited to:
/// * Accessing or mutating any racy data or APIs, such as `Cell<T>`.
/// * The type that is tagged, (and any nested types) [drop][Drop::drop]
/// implementation.
///
/// If all of the above is satifised, you can safely implement [Send] and [Sync]
/// for the type. Make sure to include a comprehensive safety message such as:
///
/// ```rust
/// # struct Foo;
/// // Safety: the structure is explicitly tagged with the thread that created
/// // it, and we ensure everywhere (including drop implementations) where racy
/// // access might occur that it is on the thread that created it.
/// unsafe impl Send for Foo {}
/// ```
///
/// Tags can only be correctly constructed in two ways:
/// * By calling [Tag::current_thread] if inside of a thread context. Such as
/// [Thread::submit][super::Thread::submit] or
/// [Thread::submit_async][super::Thread::submit_async].
/// * Externally by calling [Thread::tag][super::Thread::tag].
///
/// # Examples
///
/// ```rust
/// use std::cell::Cell;
///
/// struct Foo {
/// tag: ste::Tag,
/// data: Cell<usize>,
/// }
///
/// impl Foo {
/// fn new() -> Self {
/// Self {
/// tag: ste::Tag::current_thread(),
/// data: Cell::new(42),
/// }
/// }
///
/// fn say_hello(&self) {
/// self.tag.ensure_on_thread();
/// println!("Hello from Foo: {}", self.data.get());
/// }
/// }
///
/// // Safety: the structure is explicitly tagged with the thread that created
/// // it, and we ensure everywhere (including drop implementations) where racy
/// // access might occur that it is on the thread that created it.
/// unsafe impl Send for Foo {}
/// unsafe impl Sync for Foo {}
///
/// # fn main() -> anyhow::Result<()> {
/// let thread = ste::spawn();
///
/// let foo = thread.submit(|| Foo::new());
///
/// assert!(!foo.tag.is_on_thread());
///
/// thread.submit(|| foo.say_hello());
///
/// thread.join();
/// # Ok(()) }
/// ```
///
/// Incorrect use of the tagged struct **must** panic:
///
/// ```rust,should_panic
/// # struct Foo { tag: ste::Tag }
/// # impl Foo {
/// # fn new() -> Self { Self { tag: ste::Tag::current_thread() } }
/// # fn say_hello(&self) { self.tag.ensure_on_thread(); }
/// # }
/// # fn main() -> anyhow::Result<()> {
/// let thread = ste::spawn();
///
/// let foo = thread.submit(|| Foo::new());
///
/// assert!(!foo.tag.is_on_thread());
///
/// foo.say_hello(); // <- oops, this panics!
///
/// thread.join();
/// # Ok(()) }
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Tag(pub(super) usize);
impl Tag {
/// Get the tag associated with the current thread.
///
/// See [Tag] documentation for how to use correctly.
///
/// # Panics
///
/// Panics if not running on a tagged thread. Tagged threads are the ones
/// created with [Thread][super::Thread].
pub fn current_thread() -> Self {
match THREAD_TAG.with(|tag| tag.get()) {
Tag(0) => panic!("not running on a tagged thread"),
tag => tag,
}
}
/// Ensure that the tag is currently executing on the thread that created
/// it.
///
/// See [Tag] documentation for how to use.
///
/// # Panics
///
/// Panics if not running on a tagged thread. Tagged threads are the ones
/// created with [Thread][super::Thread].
///
/// Also panics unless called on the same thread that the tag was created
/// on.
pub fn ensure_on_thread(&self) {
let current = Self::current_thread();
if *self != current {
panic!(
"cannot operate on tagged element unless on the correct thread, \
got {:?} but expected {:?}",
current, self
);
}
}
/// Test if we're currently on the tagged thread.
///
/// See [Tag] documentation for how to use.
pub fn is_on_thread(&self) -> bool {
THREAD_TAG.with(|tag| match tag.get() {
Tag(0) => false,
tag => *self == tag,
})
}
}
impl fmt::Debug for Tag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Tag")
.field(&format_args!("{:#x}", self.0))
.finish()
}
}
|
use std::iter;
use crate::Battery;
use super::device::IoCtlDevice;
#[derive(Debug)]
pub struct IoCtlIterator(pub Option<IoCtlDevice>);
impl iter::Iterator for IoCtlIterator {
type Item = Battery;
fn next(&mut self) -> Option<Self::Item> {
match self.0.take() {
None => None,
Some(device) => Some(Battery::from(device))
}
}
}
|
#[macro_use]
extern crate abstract_machines;
use abstract_machines::*;
use cps::*;
fn main() {
let id1 = cpsabs!("x", cpsvar!("x"));
let id2 = cpsabs!("y", cpsvar!("y"));
let mut t = cps::Transform::default();
// let mut c = t.cps(cpsapp!(id1.clone(), id2.clone()), CTerm::Return);
let mut c = t.cps(id1, CTerm::Return);
// dbg!(c);
println!("{}", c);
let c0 = cpsabs!("x", cpsabs!("y", cpsvar!("y")));
let succ = cpsabs!(
"x",
cpsabs!(
"y",
cpsabs!(
"z",
cpsapp!(
cpsapp!(cpsvar!("x"), cpsvar!("y")),
cpsapp!(cpsvar!("y"), cpsvar!("z"))
)
)
)
);
let plus = cpsabs!(
"x",
cpsabs!(
"y",
cpsabs!(
"z",
cpsabs!(
"c",
cpsapp!(
cpsapp!(cpsvar!("x"), cpsvar!("z")),
cpsapp!(cpsapp!(cpsvar!("y"), cpsvar!("z")), cpsvar!("c"))
)
)
)
)
);
let c1 = cpsapp!(succ.clone(), c0.clone());
let c2 = cpsapp!(succ.clone(), c1.clone());
let c3 = cpsapp!(succ.clone(), c2.clone());
c = t.cps(c3, CTerm::Return);
println!("{}", c);
// let mut e = cps::Eval::default();
// for i in 0..5 {
// c = e.eval1(c);
// println!("{:?}", c);
// }
}
|
use mdb_rs::MDatabase;
#[test]
fn main(){
println!("{:#?}", MDatabase::open_database("test.mdb"));
}
|
//! LCD controller
// TODO - generic over TCON0/TCON1
use super::DisplayTiming;
use crate::pac::tcon1::{
Control, DataClock, GlobalControl, Timing0, Timing1, Timing2, Timing3, Timing4, Timing5, TCON1,
};
pub struct LcdController {
tcon: TCON1,
}
impl LcdController {
pub(crate) fn new(mut tcon: TCON1) -> Self {
tcon.gctrl.write(0);
tcon.gint0.write(0);
// Disable tcon0 dot clock
tcon.tcon0_dclk.modify(DataClock::Enable::Disabled);
// Set all io lines to tristate
tcon.tcon0_io_trigger.write(0xFFFF_FFFF);
tcon.io_trigger.write(0xFFFF_FFFF);
LcdController { tcon }
}
pub(crate) fn set_mode(&mut self, timing: &DisplayTiming) {
let clk_delay = self.clock_delay(timing);
if timing.flags.interlaced() {
unimplemented!();
}
self.tcon
.ctrl
.modify(Control::StartDelay::Field::new(clk_delay).unwrap() + Control::Enable::Set);
let mut yres = timing.vactive.typ;
if timing.flags.interlaced() {
yres /= 2;
}
self.tcon.timing_src.modify(
Timing0::X::Field::new(timing.hactive.typ - 1).unwrap()
+ Timing0::Y::Field::new(yres - 1).unwrap(),
);
self.tcon.timing_scale.modify(
Timing1::X::Field::new(timing.hactive.typ - 1).unwrap()
+ Timing1::Y::Field::new(yres - 1).unwrap(),
);
self.tcon.timing_out.modify(
Timing2::X::Field::new(timing.hactive.typ - 1).unwrap()
+ Timing2::Y::Field::new(yres - 1).unwrap(),
);
let bp = timing.hsync_len.typ + timing.hback_porch.typ;
let total = timing.hactive.typ + timing.hfront_porch.typ + bp;
self.tcon.timing_h.modify(
Timing3::Hbp::Field::new(bp - 1).unwrap() + Timing3::Ht::Field::new(total - 1).unwrap(),
);
let bp = timing.vsync_len.typ + timing.vback_porch.typ;
let mut total = timing.vactive.typ + timing.vfront_porch.typ + bp;
if !timing.flags.interlaced() {
total = total * 2;
}
self.tcon.timing_v.modify(
Timing4::Vbp::Field::new(bp - 1).unwrap() + Timing4::Vt::Field::new(total).unwrap(),
);
self.tcon.timing_sync.modify(
Timing5::Vspw::Field::new(timing.vsync_len.typ - 1).unwrap()
+ Timing5::Hspw::Field::new(timing.hsync_len.typ - 1).unwrap(),
);
}
pub(crate) fn enable(&mut self) {
self.tcon.gctrl.modify(GlobalControl::Enable::Set);
}
fn clock_delay(&mut self, timing: &DisplayTiming) -> u32 {
let mut delay = timing.vfront_porch.typ + timing.vsync_len.typ + timing.vback_porch.typ;
if timing.flags.interlaced() {
delay = delay / 2;
}
// TODO if tcon == 1 ...
delay = delay - 2;
if delay > 30 {
30
} else {
delay
}
}
}
|
use embedded_graphics::{
mono_font::{ascii::FONT_6X10, MonoFont},
pixelcolor::BinaryColor,
};
use crate::themes::default::button::{ButtonStateColors, ButtonStyle};
pub struct SecondaryButtonInactive;
pub struct SecondaryButtonIdle;
pub struct SecondaryButtonHovered;
pub struct SecondaryButtonPressed;
impl ButtonStateColors<BinaryColor> for SecondaryButtonInactive {
const LABEL_COLOR: BinaryColor = BinaryColor::On;
const BORDER_COLOR: BinaryColor = BinaryColor::Off;
const BACKGROUND_COLOR: BinaryColor = BinaryColor::Off;
}
impl ButtonStateColors<BinaryColor> for SecondaryButtonIdle {
const LABEL_COLOR: BinaryColor = BinaryColor::On;
const BORDER_COLOR: BinaryColor = BinaryColor::Off;
const BACKGROUND_COLOR: BinaryColor = BinaryColor::Off;
}
impl ButtonStateColors<BinaryColor> for SecondaryButtonHovered {
const LABEL_COLOR: BinaryColor = BinaryColor::On;
const BORDER_COLOR: BinaryColor = BinaryColor::On;
const BACKGROUND_COLOR: BinaryColor = BinaryColor::Off;
}
impl ButtonStateColors<BinaryColor> for SecondaryButtonPressed {
const LABEL_COLOR: BinaryColor = BinaryColor::Off;
const BORDER_COLOR: BinaryColor = BinaryColor::Off;
const BACKGROUND_COLOR: BinaryColor = BinaryColor::On;
}
pub struct SecondaryButtonStyle;
impl ButtonStyle<BinaryColor> for SecondaryButtonStyle {
type Inactive = SecondaryButtonInactive;
type Idle = SecondaryButtonIdle;
type Hovered = SecondaryButtonHovered;
type Pressed = SecondaryButtonPressed;
const FONT: MonoFont<'static> = FONT_6X10;
}
|
use std::fs::OpenOptions;
use std::fs;
use std::io::prelude::*;
use time::{get_time, at};
/// Log a message in a textfile log folder log
/// Also includes the date
pub fn log(content: &str) {
log_at("log", "log", content);
}
/// Logs a message at a directory with given name
/// Also includes the date
pub fn log_at(dir: &str, name: &str, content: &str) {
// Create all directorys
let _ = fs::create_dir_all(dir);
// Get system time
let time = at(get_time());
let name = format!(
"{}\\{}_{}_{}_{}.txt",
dir,
name,
time.tm_year + 1900,
time.tm_mon + 1,
time.tm_mday,
);
// Create and write to file
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.append(true)
.open(name)
.unwrap();
let content = format!(
"{} INFO: {}",
time.rfc3339(),
content,
);
if let Err(e) = writeln!(file, "{}", content) {
println!("{}", e);
}
}
|
extern crate xmlparser as xml;
#[macro_use] mod token;
use token::*;
test!(text_01, "<p>text</p>",
Token::ElementStart("", "p"),
Token::ElementEnd(ElementEnd::Open),
Token::Text("text"),
Token::ElementEnd(ElementEnd::Close("", "p"))
);
test!(text_02, "<p> text </p>",
Token::ElementStart("", "p"),
Token::ElementEnd(ElementEnd::Open),
Token::Text(" text "),
Token::ElementEnd(ElementEnd::Close("", "p"))
);
// 欄 is EF A4 9D. And EF can be mistreated for UTF-8 BOM.
test!(text_03, "<p>欄</p>",
Token::ElementStart("", "p"),
Token::ElementEnd(ElementEnd::Open),
Token::Text("欄"),
Token::ElementEnd(ElementEnd::Close("", "p"))
);
test!(whitespaces_01, "<p> </p>",
Token::ElementStart("", "p"),
Token::ElementEnd(ElementEnd::Open),
Token::Whitespaces(" "),
Token::ElementEnd(ElementEnd::Close("", "p"))
);
test!(whitespaces_02, "<p> \r\n\t </p>",
Token::ElementStart("", "p"),
Token::ElementEnd(ElementEnd::Open),
Token::Whitespaces(" \r\n\t "),
Token::ElementEnd(ElementEnd::Close("", "p"))
);
test!(whitespaces_03, "<p> </p>",
Token::ElementStart("", "p"),
Token::ElementEnd(ElementEnd::Open),
Token::Whitespaces(" "),
Token::ElementEnd(ElementEnd::Close("", "p"))
);
test!(whitespaces_04, "<p>	

 </p>",
Token::ElementStart("", "p"),
Token::ElementEnd(ElementEnd::Open),
Token::Whitespaces("	

 "),
Token::ElementEnd(ElementEnd::Close("", "p"))
);
|
use super::attribute::AttributeInfo;
use super::common_type::*;
#[derive(Debug)]
pub struct FieldInfo {
pub access_flags: u2,
pub name_index: u2,
pub descriptor_index: u2,
pub attributes_count: u2,
pub attributes: Vec<AttributeInfo>,
}
|
#[allow(dead_code)]
pub fn copy_dir<P: AsRef<std::path::Path>, Q: AsRef<std::path::Path>>(from: P, to: Q) -> std::io::Result<()> {
let src = from.as_ref();
let dst = to.as_ref();
std::fs::create_dir(dst)?;
for path in src.read_dir()? {
let pbuf = path.unwrap().path();
let file_name = pbuf.file_name().unwrap().to_str().unwrap().to_string();
if pbuf.is_dir() {
copy_dir(pbuf, dst.join(file_name))?;
} else {
std::fs::copy(pbuf, dst.join(file_name))?;
}
}
Ok(())
}
|
use borsh::{BorshDeserialize, BorshSerialize};
use near_sdk::collections::Map;
use near_sdk::{env, near_bindgen, AccountId, Balance, EpochHeight};
use near_sdk::json_types::U64;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
type WrappedTimestamp = U64;
/// Voting contract for unlocking transfers. Once the majority of the stake holders agree to
/// unlock transfer, the time will be recorded and the voting ends.
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct VotingContract {
/// How much each validator votes
votes: Map<AccountId, Balance>,
/// Total voted balance so far.
total_voted_stake: Balance,
/// When the voting ended. `None` means the poll is still open.
result: Option<WrappedTimestamp>,
/// Epoch height when the contract is touched last time.
last_epoch_height: EpochHeight,
}
impl Default for VotingContract {
fn default() -> Self {
env::panic(b"Voting contract should be initialized before usage")
}
}
#[near_bindgen]
impl VotingContract {
#[init]
pub fn new() -> Self {
assert!(!env::state_exists(), "The contract is already initialized");
VotingContract {
votes: Map::new(b"a".to_vec()),
total_voted_stake: 0,
result: None,
last_epoch_height: 0,
}
}
/// Ping to update the votes according to current stake of validators.
pub fn ping(&mut self) {
assert!(self.result.is_none(), "Voting has already ended");
let cur_epoch_height = env::epoch_height();
if cur_epoch_height != self.last_epoch_height {
for account_id in self.votes.keys().into_iter().collect::<Vec<_>>() {
let account_current_stake = env::validator_stake(&account_id);
let account_voted_stake = self.votes.remove(&account_id).unwrap();
if account_current_stake > 0 {
self.total_voted_stake =
self.total_voted_stake + account_current_stake - account_voted_stake;
self.votes.insert(&account_id, &account_current_stake);
}
}
self.check_result();
self.last_epoch_height = cur_epoch_height;
}
}
/// Check whether the voting has ended.
fn check_result(&mut self) {
assert!(
self.result.is_none(),
"check result is called after result is already set"
);
let total_stake = env::validator_total_stake();
if self.total_voted_stake > 2 * total_stake / 3 {
self.result = Some(U64::from(env::block_timestamp()));
}
}
/// Internal function to handle vote and withdraw.
pub fn vote(&mut self, is_vote: bool) {
self.ping();
if self.result.is_some() {
return;
}
let account_id = env::predecessor_account_id();
let account_stake = if is_vote {
let stake = env::validator_stake(&account_id);
assert!(stake > 0, "{} is not a validator", account_id);
stake
} else {
0
};
let voted_stake = self.votes.remove(&account_id).unwrap_or_default();
assert!(
voted_stake <= self.total_voted_stake,
"invariant: voted stake {} is more than total voted stake {}",
voted_stake,
self.total_voted_stake
);
self.total_voted_stake = self.total_voted_stake + account_stake - voted_stake;
if account_stake > 0 {
self.votes.insert(&account_id, &account_stake);
self.check_result();
}
}
/// Get the timestamp of when the voting finishes. `None` means the voting hasn't ended yet.
pub fn get_result(&self) -> Option<WrappedTimestamp> {
self.result.clone()
}
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(test)]
mod tests {
use super::*;
use near_sdk::MockedBlockchain;
use near_sdk::{testing_env, VMContext};
use std::collections::HashMap;
use std::iter::FromIterator;
fn get_context(predecessor_account_id: AccountId) -> VMContext {
get_context_with_epoch_height(predecessor_account_id, 0)
}
fn get_context_with_epoch_height(
predecessor_account_id: AccountId,
epoch_height: EpochHeight,
) -> VMContext {
VMContext {
current_account_id: "alice_near".to_string(),
signer_account_id: "bob_near".to_string(),
signer_account_pk: vec![0, 1, 2],
predecessor_account_id,
input: vec![],
block_index: 0,
block_timestamp: 0,
account_balance: 0,
account_locked_balance: 0,
storage_usage: 1000,
attached_deposit: 0,
prepaid_gas: 2 * 10u64.pow(14),
random_seed: vec![0, 1, 2],
is_view: false,
output_data_receivers: vec![],
epoch_height,
}
}
#[test]
#[should_panic(expected = "is not a validator")]
fn test_nonvalidator_cannot_vote() {
let context = get_context("bob.near".to_string());
let validators = HashMap::from_iter(
vec![
("alice_near".to_string(), 100),
("bob_near".to_string(), 100),
]
.into_iter(),
);
testing_env!(context, Default::default(), Default::default(), validators);
let mut contract = VotingContract::new();
contract.vote(true);
}
#[test]
#[should_panic(expected = "Voting has already ended")]
fn test_vote_again_after_voting_ends() {
let context = get_context("alice.near".to_string());
let validators = HashMap::from_iter(vec![("alice.near".to_string(), 100)].into_iter());
testing_env!(context, Default::default(), Default::default(), validators);
let mut contract = VotingContract::new();
contract.vote(true);
assert!(contract.result.is_some());
contract.vote(true);
}
#[test]
fn test_voting_simple() {
let context = get_context("test0".to_string());
let validators = (0..10)
.map(|i| (format!("test{}", i), 10))
.collect::<HashMap<_, _>>();
testing_env!(
context,
Default::default(),
Default::default(),
validators.clone()
);
let mut contract = VotingContract::new();
for i in 0..7 {
let context = get_context(format!("test{}", i));
testing_env!(
context,
Default::default(),
Default::default(),
validators.clone()
);
contract.vote(true);
assert_eq!(contract.votes.len(), i + 1);
if i < 6 {
assert!(contract.result.is_none());
} else {
assert!(contract.result.is_some());
}
}
}
#[test]
fn test_voting_with_epoch_change() {
let validators = (0..10)
.map(|i| (format!("test{}", i), 10))
.collect::<HashMap<_, _>>();
let context = get_context("test0".to_string());
testing_env!(
context,
Default::default(),
Default::default(),
validators.clone()
);
let mut contract = VotingContract::new();
for i in 0..7 {
let context = get_context_with_epoch_height(format!("test{}", i), i);
testing_env!(
context,
Default::default(),
Default::default(),
validators.clone()
);
contract.vote(true);
assert_eq!(contract.votes.len(), i + 1);
if i < 6 {
assert!(contract.result.is_none());
} else {
assert!(contract.result.is_some());
}
}
}
#[test]
fn test_validator_stake_change() {
let mut validators = HashMap::from_iter(vec![
("test1".to_string(), 40),
("test2".to_string(), 10),
("test3".to_string(), 10),
]);
let context = get_context_with_epoch_height("test1".to_string(), 1);
testing_env!(
context,
Default::default(),
Default::default(),
validators.clone()
);
let mut contract = VotingContract::new();
contract.vote(true);
validators.insert("test1".to_string(), 50);
let context = get_context_with_epoch_height("test2".to_string(), 2);
testing_env!(
context,
Default::default(),
Default::default(),
validators.clone()
);
contract.ping();
assert!(contract.result.is_some());
}
#[test]
fn test_withdraw_votes() {
let validators =
HashMap::from_iter(vec![("test1".to_string(), 10), ("test2".to_string(), 10)]);
let context = get_context_with_epoch_height("test1".to_string(), 1);
testing_env!(
context,
Default::default(),
Default::default(),
validators.clone()
);
let mut contract = VotingContract::new();
contract.vote(true);
assert_eq!(contract.votes.len(), 1);
let context = get_context_with_epoch_height("test1".to_string(), 2);
testing_env!(
context,
Default::default(),
Default::default(),
validators.clone()
);
contract.vote(false);
assert!(contract.votes.is_empty());
}
}
|
pub use blurz::{
bluetooth_session::BluetoothSession,
bluetooth_adapter::BluetoothAdapter,
bluetooth_device::BluetoothDevice,
bluetooth_discovery_session::BluetoothDiscoverySession,
};
fn search() -> BluetoothSession {
let session = BluetoothSession::create_session(None).unwrap();
let adapter = BluetoothAdapter::init(&session).unwrap();
if let Err(err) = adapter.set_powered(true) {
panic!("Cannot power on: {:?}", err);
}
if let Err(err) = adapter.set_pairable(true) {
panic!("Cannot set pairable {:?}", err);
}
let discovery_session = BluetoothDiscoverySession::create_session(&session, adapter.get_id()).unwrap();
session
}
fn main() {
let ip = "E8_07_BF_F6_6D_0D";
let address = String::from(format!("/org/bluez/hci0/dev_{}", ip));
let session = search();
let device = BluetoothDevice::new(&session, address);
if let Err(err) = device.connect(10000) {
println!("Failed to connect: {:?}", err);
}
}
|
extern crate rand;
use std::{thread, time};
use rand::Rng;
const MAX_X: usize = 40;
const MAX_Y: usize = 20;
const MAX_TICKS: usize = 60;
const TICK_DELAY: u64 = 200;
#[derive(Debug)]
pub enum ArrayOutOfBoundsException {
WtfError,
}
pub type ArrayElementResult = Result<usize, &'static str>;
fn init_grid(grid: &mut [[usize; MAX_X]; MAX_Y]) {
// https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life#Examples_of_patterns
// grid[10][2] = 1;
// grid[11][2] = 1;
// grid[12][2] = 1;
grid[10][2] = 1;
grid[10][3] = 0;
grid[10][4] = 0;
grid[11][2] = 0;
grid[11][3] = 1;
grid[11][4] = 1;
grid[12][2] = 1;
grid[12][3] = 1;
grid[12][4] = 0;
}
fn get_cell_status(cell: usize, alive_neighbours: usize) -> usize {
let mut cell_val = 0;
if cell == 1 {
if (2 == alive_neighbours) || (3 == alive_neighbours) {
cell_val = 1;
}
} else {
if alive_neighbours == 3 {
cell_val = 1;
}
}
cell_val
}
fn get_pos_value(
// Check the requested coordinate againts overflows
// returns 0 if an overflow is detected
// else returns the grid coordinate value
grid: [[usize; MAX_X]; MAX_Y],
y: usize,
action_y: &str,
x: usize,
action_x: &str,
) -> usize {
let checked_y;
let checked_x;
if action_y == "dec" {
// returns 0 if overflows
if y.saturating_sub(1) != 0 {
checked_y = y - 1;
} else {
return 0;
}
} else if action_y == "inc" {
if y + 1 < MAX_Y {
checked_y = y + 1;
} else {
return 0;
}
} else {
checked_y = y;
}
if action_x == "dec" {
if x.saturating_sub(1) != 0 {
checked_x = x - 1;
} else {
return 0;
}
} else if action_x == "inc" {
if x + 1 < MAX_X {
checked_x = x + 1;
} else {
return 0;
}
} else {
checked_x = x;
}
// coordinates are valid and inbound
grid[checked_y][checked_x]
}
fn update_grid(grid: [[usize; MAX_X]; MAX_Y]) -> [[usize; MAX_X]; MAX_Y] {
let mut new_grid = [[0; MAX_X]; MAX_Y];
for coord_y in 0..MAX_Y {
for coord_x in 0..MAX_X {
// checking my neighbours
let tl = get_pos_value(grid, coord_y, "dec", coord_x, "dec");
let tc = get_pos_value(grid, coord_y, "dec", coord_x, "");
let tr = get_pos_value(grid, coord_y, "dec", coord_x, "inc");
let cl = get_pos_value(grid, coord_y, "", coord_x, "dec");
let cell = get_pos_value(grid, coord_y, "", coord_x, "");
let cr = get_pos_value(grid, coord_y, "", coord_x, "inc");
let bl = get_pos_value(grid, coord_y, "inc", coord_x, "dec");
let bc = get_pos_value(grid, coord_y, "inc", coord_x, "");
let br = get_pos_value(grid, coord_y, "inc", coord_x, "inc");
let alive_neighbours = tl + tc + tr + cl + cr + bl + bc + br;
new_grid[coord_y][coord_x] = get_cell_status(cell, alive_neighbours);
}
}
new_grid
}
fn print_grid(grid: &mut [[usize; MAX_X]; MAX_Y]) {
for coord_y in 0..MAX_Y {
println!();
for coord_x in 0..MAX_X {
print!("{}", grid[coord_y][coord_x]);
}
}
}
fn main() {
// also: https://stackoverflow.com/a/36376568
// notice: grid[y][x]
// type is inferred, i.e.:
// let grid: [[usize; 12]; 12] = [[7;12]; 12];
let mut grid = [[0; MAX_X]; MAX_Y];
let mut num_tick = 0;
// unrelated: check this
// #[macro_use(c)]
// extern crate cute;
// let vector = c![x, for x in 1..10, if x % 2 == 0];
init_grid(&mut grid);
while num_tick <= MAX_TICKS {
let rand_str = rand::thread_rng()
.gen_ascii_chars()
.take(10)
.collect::<String>();
// https://stackoverflow.com/a/34837038
// clear screen
print!("{}[2J", 27 as char);
println!("\n\nTick: {} ---- [{}]", num_tick, rand_str);
print_grid(&mut grid);
let new_grid = update_grid(grid);
thread::sleep(time::Duration::from_millis(TICK_DELAY));
num_tick += 1;
grid = new_grid;
}
println!();
}
|
// <main>
use actix_cors::Cors;
use actix_ratelimit::{MemoryStore, MemoryStoreActor, RateLimiter};
use actix_web::{guard, http, middleware, web, App, FromRequest, HttpServer};
use actix_web_middleware_redirect_https::RedirectHTTPS;
use dotenv::dotenv;
use openssl::ssl::{SslAcceptor, SslAcceptorBuilder, SslFiletype, SslMethod};
use slog::{slog_info, Level};
use std::time::Duration;
mod config;
mod constants;
mod db;
mod defaults;
mod errors;
mod handlers;
mod logging;
mod models;
mod utils;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
dotenv().ok();
let config = config::Config::from_env().expect("error getting configuration from environment");
let pool = config.configure_pool();
// Initialize store.
let store = MemoryStore::new();
// Set environment variables for logging (consider using slog_envlogger: https://crates.io/crates/slog-envlogger).
// Might need https://crates.io/crates/slog-scope and https://crates.io/crates/slog-stdlog as additional dependencies.
// std::env::set_var("RUST_LOG", "actix_web=info,actix_server=info");
// std::env::set_var("RUST_BACKTRACE", "full");
let logger = logging::configure_log();
logging::set_global_level(Level::Trace);
slog_info!(
logger,
"Starting server at https://{}:{}/",
config.server.host,
config.server.port
);
let mut builder: SslAcceptorBuilder;
// Development mode.
if cfg!(debug_assertions) {
builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder
.set_private_key_file("tls/privkey.pem", SslFiletype::PEM)
.unwrap();
builder.set_certificate_chain_file("tls/cert.pem").unwrap();
}
// Production mode.
else {
builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder
.set_private_key_file("/root/overdue_backend/tls/privkey.pem", SslFiletype::PEM)
.unwrap();
builder
.set_certificate_chain_file("/root/overdue_backend/tls/fullchain.pem")
.unwrap();
}
HttpServer::new(move || {
// Define Cross-Origin Resource Sharing policy.
let cors = Cors::default()
.allowed_origin(constants::GAME_CLIENT_URL_DOMAIN_ORIGIN)
.allowed_origin(constants::PUBLIC_FACING_GAME_CLIENT_URL)
.allowed_origin(constants::FRONT_DOMAIN)
.allowed_methods(vec!["GET", "POST"])
.allowed_headers(vec![
http::header::CONTENT_TYPE,
http::header::CONTENT_LENGTH,
http::header::HOST,
http::header::USER_AGENT,
http::header::ORIGIN,
http::header::CONNECTION,
http::header::ACCEPT,
http::header::ACCEPT_ENCODING,
http::header::ACCEPT_LANGUAGE,
http::header::ACCEPT_CHARSET,
http::header::DNT,
http::header::REFERER,
http::header::UPGRADE,
http::header::UPGRADE_INSECURE_REQUESTS,
http::header::STRICT_TRANSPORT_SECURITY,
http::header::CONTENT_SECURITY_POLICY,
http::header::X_XSS_PROTECTION,
])
.max_age(constants::CORS_MAX_AGE_DURATION);
// Use this permissive policy for debugging phase/development mode.
// let cors = Cors::permissive();
App::new()
.wrap(middleware::Compress::default())
// Enable logging.
// .wrap(middleware::Logger::default())
.wrap(cors)
// Redirect HTTP to HTTPS
.wrap(RedirectHTTPS::default())
// Register the middleware which allows for a maximum of 60 requests per minute per client based on IP address.
.wrap(
RateLimiter::new(
MemoryStoreActor::from(store.clone()).start())
.with_interval(Duration::from_secs(constants::RATE_LIMIT_INTERVAL_DURATION))
.with_max_requests(constants::RATE_LIMIT_MAX_REQUESTS)
)
.data(models::AppState {
pool: pool.clone(),
log: logger.clone()
})
// Define all of the available endpoints.
.service(
web::resource("/submit_score{_:/?}")
.data(web::JsonConfig::default().limit(constants::INCOMING_SCORE_PAYLOAD_LIMIT))
.guard(guard::Host(constants::SERVER_HOST_URL))
.route(web::post().to(handlers::submit_score)))
.app_data(
web::Json::<models::ScoreEntry>::configure(|cfg| {
// Limit size of the payload.
cfg.limit(constants::INCOMING_SCORE_PAYLOAD_LIMIT)
.error_handler(errors::json_error_handler)
})
)
.service(
web::resource("/get_leaderboard{_:/?}")
.guard(guard::Host(constants::SERVER_HOST_URL))
.route(web::get().to(handlers::get_leaderboard)))
.app_data(
web::Query::<models::LeaderboardQueryRequest>::configure(|cfg| {
cfg.error_handler(errors::query_error_handler)
})
)
.service(
web::resource("/get_materials{_:/?}")
.guard(guard::Host(constants::SERVER_HOST_URL))
.route(web::get().to(handlers::get_materials)))
// Define easter egg endpoints.
.service(
web::resource("/vsauce{_:/?}")
.guard(guard::Host(constants::SERVER_HOST_URL))
.route(web::get().to(handlers::vsauce_handler)))
.service(
web::resource("/fortune{_:/?}")
.guard(guard::Host(constants::SERVER_HOST_URL))
.route(web::get().to(handlers::fortune_cookie_handler)))
// Serve favicon image.
.service(
web::resource("/favicon.ico")
.guard(guard::Host(constants::SERVER_HOST_URL))
.route(web::get().to(handlers::favicon_handler)))
// Default 404 handler.
.default_service(web::route().to(handlers::default_handler))
})
.keep_alive(constants::KEEP_ALIVE_DURATION)
.bind_openssl(
format!("{}:{}", config.server.host, config.server.port),
builder,
)?
.run()
.await
}
// </main>
#[cfg(test)]
#[cfg(feature = "integration")]
mod integration_tests;
|
use std::collections::HashMap;
use std::error::Error;
use std::str;
use x11rb::connection::Connection as Conn;
#[allow(unused_imports)]
use x11rb::connection::{Connection as _, RequestConnection as _};
use x11rb::protocol::xproto::*;
#[allow(unused_imports)]
use x11rb::wrapper::ConnectionExt as _;
use x11rb::xcb_ffi::XCBConnection;
pub struct Connection<'a> {
pub dpy: &'a XCBConnection,
pub screen: Screen,
atoms: HashMap<String, Atom>,
}
impl<'a> Connection<'a> {
pub fn new(connection: &'a XCBConnection, screen_num: usize) -> Self {
let mut c = Self {
dpy: connection,
screen: connection.setup().roots[screen_num].clone(),
atoms: HashMap::new(),
};
// Setting up basic ICCCM states.
c.dpy
.change_property32(
PropMode::Replace,
c.screen.root,
c.atom(b"_NET_SUPPORTED").unwrap(),
AtomEnum::ATOM,
&[
c.atom(b"_NET_SUPPORTED").unwrap(),
c.atom(b"_NET_WM_STATE").unwrap(),
c.atom(b"_NET_ACTIVE_WINDOW").unwrap(),
c.atom(b"_NET_WM_STATE_FULLSCREEN").unwrap(),
],
)
.expect("Cannot add _NET_SUPPORTED property atom.");
debug!("Applying ICCCM support on main root.");
// Force applying change right now.
c.dpy.flush().unwrap();
c
}
pub fn atom<'b>(&mut self, name: &'b [u8]) -> Result<Atom, Box<dyn Error>> {
let name_string = str::from_utf8(name)?.to_string();
let dpy = self.dpy;
let atom = self.atoms.entry(name_string).or_insert_with(|| {
dpy.intern_atom(false, name)
.map(|cookie| cookie.reply().map(|reply| reply.atom).unwrap())
.unwrap()
});
Ok(*atom)
}
}
|
mod dedupe_command;
mod print_extents_command;
pub use self::dedupe_command::*;
pub use self::print_extents_command::*;
// ex: noet ts=4 filetype=rust
|
use proconio::input;
use proconio::marker::Usize1;
use std::ops::Range;
fn main() {
input! {
n: usize,
q: usize,
a: [u8; n],
};
let bucket_size = (1..).take_while(|&s| s * s <= n).last().unwrap();
#[derive(Debug)]
struct Bucket {
data: Data,
lazy: Lazy,
values: Vec<u8>,
}
#[derive(Debug)]
struct Lazy {
flip: bool,
}
#[derive(Debug)]
struct Data {
n0: usize,
n1: usize,
inv: usize,
}
let n_bucket = if n % bucket_size == 0 {
n / bucket_size
} else {
n / bucket_size + 1
};
let mut buckets: Vec<Bucket> = (0..n_bucket)
.map(|_| Bucket {
data: Data {
n0: 0,
n1: 0,
inv: 0,
},
lazy: Lazy { flip: false },
values: Vec::new(),
})
.collect();
for j in 0..n {
let i = j / bucket_size;
let bucket = &mut buckets[i];
bucket.values.push(a[j]);
}
macro_rules! init {
($bucket: expr) => {
let mut n0 = 0;
let mut n1 = 0;
let mut inv = 0;
for j in 0..$bucket.values.len() {
if $bucket.values[j] == 0 {
n0 += 1;
inv += n1;
} else {
n1 += 1;
}
}
$bucket.data = Data { n0, n1, inv };
};
}
for i in 0..n_bucket {
init!(buckets[i]);
}
#[derive(Debug)]
enum Target {
Large(usize),
Small((usize, Range<usize>)),
}
let targets = |range: Range<usize>| -> Vec<Target> {
let (l, r) = (range.start, range.end);
assert!(l < r);
let (il, ir) = (l / bucket_size, (r - 1) / bucket_size);
if il == ir {
return vec![Target::Small((
il,
(l - il * bucket_size)..(r - ir * bucket_size),
))];
}
let mut result = Vec::new();
let mut j = l;
loop {
let i = j / bucket_size;
if il == i {
result.push(Target::Small((i, (l - il * bucket_size)..bucket_size)));
j = (il + 1) * bucket_size;
} else if il < i && i < ir {
result.push(Target::Large(i));
j += bucket_size;
} else {
assert_eq!(ir, i);
result.push(Target::Small((i, 0..(r - ir * bucket_size))));
break;
}
}
result
};
macro_rules! push {
($bucket: expr) => {
if $bucket.lazy.flip {
for j in 0..$bucket.values.len() {
$bucket.values[j] = 1 - $bucket.values[j];
}
$bucket.lazy.flip = false;
}
};
}
for _ in 0..q {
input! {
t: u8,
l: Usize1,
r: Usize1,
};
if t == 1 {
for t in targets(l..(r + 1)) {
match t {
Target::Large(i) => {
buckets[i].data = Data {
n0: buckets[i].data.n1,
n1: buckets[i].data.n0,
inv: buckets[i].data.n0 * buckets[i].data.n1 - buckets[i].data.inv,
};
buckets[i].lazy = Lazy {
flip: !buckets[i].lazy.flip,
};
}
Target::Small((i, range)) => {
push!(buckets[i]);
for j in range {
buckets[i].values[j] = 1 - buckets[i].values[j];
}
init!(buckets[i]);
}
}
}
} else {
let mut n1 = 0;
let mut inv = 0;
for t in targets(l..(r + 1)) {
match t {
Target::Large(i) => {
inv += buckets[i].data.inv + n1 * buckets[i].data.n0;
n1 += buckets[i].data.n1;
}
Target::Small((i, range)) => {
push!(buckets[i]);
for j in range {
if buckets[i].values[j] == 0 {
inv += n1;
} else {
n1 += 1;
}
}
}
}
}
println!("{}", inv);
}
}
}
|
use core::{char, convert::TryFrom, fmt};
/// All possible characters that can be used in EOSIO names.
pub const NAME_CHARS: [u8; 32] = *b".12345abcdefghijklmnopqrstuvwxyz";
/// The maximum character length of an EOSIO name.
pub const NAME_MAX_LEN: usize = 13;
/// An error which can be returned when parsing an EOSIO name.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ParseNameError {
/// The name contains a disallowed character.
BadChar(u8),
/// The name is over the maximum allowed length.
TooLong,
}
impl fmt::Display for ParseNameError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::BadChar(c) => {
write!(f, "name contains invalid character '{}'", char::from(c))
}
Self::TooLong => {
write!(f, "name is too long, must be 13 chars or less")
}
}
}
}
/// Attempts to create an EOSIO name from an `Iterator`.
///
/// # Errors
///
/// Will return `Err` if the name contains invalid characters or is too long.
///
/// # Examples
///
/// ```
/// use eosio_numstr::{name_from_bytes, ParseNameError};
/// assert_eq!(name_from_bytes("".bytes()), Ok(0));
/// assert_eq!(name_from_bytes("a".bytes()), Ok(3458764513820540928));
/// assert_eq!(name_from_bytes("123456789012".bytes()), Err(ParseNameError::BadChar(b'6')));
/// assert_eq!(name_from_bytes("123451234512".bytes()), Ok(614251535012020768));
/// assert_eq!(name_from_bytes("123451234512j".bytes()), Ok(614251535012020783));
/// assert_eq!(name_from_bytes("123451234512k".bytes()), Err(ParseNameError::BadChar(b'k')));
/// assert_eq!(name_from_bytes("12345123451234".bytes()), Err(ParseNameError::TooLong));
/// assert_eq!(name_from_bytes("eosio.token".bytes()), Ok(6138663591592764928));
/// assert_eq!(name_from_bytes("eosio.token".bytes()), Ok(6138663591592764928));
/// assert_eq!(name_from_bytes("eosio.bpay".bytes()), Ok(6138663581940940800));
/// assert_eq!(name_from_bytes("A".bytes()), Err(ParseNameError::BadChar(b'A')));
/// assert_eq!(name_from_bytes("TEST".bytes()), Err(ParseNameError::BadChar(b'T')));
/// ```
#[inline]
pub fn name_from_bytes<I>(mut iter: I) -> Result<u64, ParseNameError>
where
I: Iterator<Item = u8>,
{
let mut value = 0_u64;
let mut len = 0_u64;
// Loop through up to 12 characters
while let Some(c) = iter.next() {
let v = char_to_value(c).ok_or_else(|| ParseNameError::BadChar(c))?;
value <<= 5;
value |= u64::from(v);
len += 1;
if len == 12 {
break;
}
}
if len == 0 {
return Ok(0);
}
value <<= 4 + 5 * (12 - len);
// Check if we have a 13th character
if let Some(c) = iter.next() {
let v = char_to_value(c).ok_or_else(|| ParseNameError::BadChar(c))?;
// The 13th character can only be 4 bits, it has to be between letters 'a' to 'j'
if v > 0x0F {
return Err(ParseNameError::BadChar(c));
}
value |= u64::from(v);
// Check if we have more than 13 characters
if iter.next().is_some() {
return Err(ParseNameError::TooLong);
}
}
Ok(value)
}
/// Converts a character to a symbol.
fn char_to_value(c: u8) -> Option<u8> {
if c == b'.' {
Some(0)
} else if c >= b'1' && c <= b'5' {
Some(c - b'1' + 1)
} else if c >= b'a' && c <= b'z' {
Some(c - b'a' + 6)
} else {
None
}
}
/// Converts an EOSIO name into an array of UTF-8 characters.
///
/// # Examples
///
/// ```
/// use eosio_numstr::name_to_bytes;
/// assert_eq!(name_to_bytes(6138663591592764928), *b"eosio.token..");
/// assert_eq!(name_to_bytes(6138663581940940800), *b"eosio.bpay...");
/// assert_eq!(name_to_bytes(0), *b".............");
/// assert_eq!(name_to_bytes(614251535012020768), *b"123451234512.");
/// assert_eq!(name_to_bytes(614251535012020783), *b"123451234512j");
/// ```
#[inline]
#[must_use]
pub fn name_to_bytes(value: u64) -> [u8; NAME_MAX_LEN] {
let mut chars = [b'.'; NAME_MAX_LEN];
if value == 0 {
return chars;
}
let mask = 0xF800_0000_0000_0000;
let mut v = value;
for (i, c) in chars.iter_mut().enumerate() {
let index = (v & mask) >> (if i == 12 { 60 } else { 59 });
let index = usize::try_from(index).unwrap_or_default();
if let Some(v) = NAME_CHARS.get(index) {
*c = *v;
}
v <<= 5;
}
chars
}
#[cfg(test)]
mod tests {
use super::*;
use core::str;
use proptest::prelude::*;
proptest! {
#[test]
fn from_to_bytes(input in "[[1-5][a-z]]{0,12}[a-j]{0,1}") {
let name = match name_from_bytes(input.bytes()) {
Ok(name) => name,
Err(error) => panic!("Failed with input '{}': {}", input, error),
};
let bytes = name_to_bytes(name);
let string = str::from_utf8(&bytes).expect("Failed to convert bytes into str");
prop_assert_eq!(
string,
format!("{:.<13}", input),
"Names don't match"
);
}
#[test]
fn from_bytes_too_long(input in "[[1-5][a-z]]{12}[a-j]{2}") {
if name_from_bytes(input.bytes()).is_ok() {
panic!("Should've gotten TooLong error with input '{}'", input);
};
}
#[test]
fn to_bytes_doesnt_crash(input in 0_u64..) {
let _ = name_to_bytes(input);
}
}
}
|
// Copyright (c) 2015-2020 Vincent van Ingen <code@abitvin.com>
// Licensed under the MIT license <LICENSE.md or http://opensource.org/licenses/MIT>
// This file may not be copied, modified, or distributed except according to those terms.
use std::cell::RefCell;
use std::error::Error;
use std::fmt;
use std::rc::Rc;
use std::str::Chars;
enum Progress<'s, T> {
Some { steps: usize, ctx: ScanCtx<'s, T> },
No(ScanCtx<'s, T>),
Error { idx: usize, msg: String },
}
pub struct Rule<T>(Rc<RefCell<_Rule<T>>>);
impl<T> Clone for Rule<T> {
fn clone(&self) -> Self {
Self { 0: self.0.clone() }
}
}
struct _Rule<T> {
branch_fn: Option<Box<dyn Fn(Vec<T>, &str) -> Result<T, String>>>,
instr: Vec<Instr<T>>,
}
#[derive(Debug)]
pub struct RuleError {
pub col: usize,
pub line: usize,
pub msg: String,
}
impl fmt::Display for RuleError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Error found at line {}, column {}: {}", self.line, self.col, self.msg)
}
}
impl Error for RuleError {
fn description(&self) -> &str {
"Rule error"
}
}
impl RuleError {
fn new(text: &str, index: usize, msg: String) -> Self {
let char_count = text.char_indices().count();
let chr_idx = if char_count == index {
text.len()
}
else {
text.char_indices().skip(index).next().map(|x| x.0).unwrap()
};
let pos = cursor_pos(&text[..chr_idx]);
Self {
col: pos.col,
line: pos.line,
msg,
}
}
}
enum Instr<T> {
AnyChar,
AnyCharExcept(Vec<char>),
Alter(Vec<(&'static str, &'static str)>),
AlterString(Vec<(String, String)>),
AnyOf(Vec<Rule<T>>),
CharIn(char, char),
Eof,
Literal(&'static str),
LiteralString(String),
NoBacktrack(String),
Not(Rule<T>),
Range(u64, u64, Rule<T>),
}
#[derive(Clone)]
struct ScanErr {
idx: usize,
msg: String,
}
struct ScanCtx<'s, T> {
branches: Vec<T>,
code_iter: Chars<'s>,
index: usize,
in_not: bool,
lexeme: String,
}
impl<'s, T> ScanCtx<'s, T> {
fn new(code: &'s str) -> Self {
Self {
branches: Vec::new(),
code_iter: code.chars(),
index: 0,
in_not: false,
lexeme: String::new(),
}
}
fn branch(self) -> (ScanCtx<'s, T>, ScanCtx<'s, T>) {
let new_ctx = ScanCtx {
branches: Vec::new(),
code_iter: self.code_iter.clone(),
index: self.index,
in_not: self.in_not,
lexeme: String::new(),
};
(new_ctx, self)
}
fn merge_with(mut self, mut source: ScanCtx<'s, T>, is_rule: bool, branch_fn: &Option<impl Fn(Vec<T>, &str) -> Result<T, String>>) -> Progress<'s, T> {
let steps = source.index - self.index;
self.code_iter = source.code_iter;
self.index = source.index;
self.lexeme.push_str(&source.lexeme.to_string());
match branch_fn {
Some(ref f) if is_rule => {
match f(source.branches, &source.lexeme) {
Ok(val) => self.branches.push(val),
Err(msg) => return Progress::Error { idx: source.index - source.lexeme.char_indices().count(), msg },
}
},
_ => self.branches.append(&mut source.branches),
}
Progress::Some { steps, ctx: self }
}
}
impl<T> Default for Rule<T> {
fn default() -> Self {
Rule {
0: Rc::new(RefCell::new(_Rule {
branch_fn: None,
instr: Vec::new(),
}))
}
}
}
impl<T> Rule<T> {
pub fn new(branch_fn: impl Fn(Vec<T>, &str) -> Result<T, String> + 'static) -> Self {
Rule {
0: Rc::new(RefCell::new(_Rule {
branch_fn: Some(Box::new(branch_fn)),
instr: Vec::new(),
}))
}
}
pub fn any_char(&self) -> &Self {
let mut r = self.0.borrow_mut();
r.instr.push(Instr::AnyChar);
self
}
pub fn any_char_except(&self, exclude: Vec<char>) -> &Self {
if exclude.len() == 0 {
panic!("List of excluded characters is empty.");
}
let mut r = self.0.borrow_mut();
r.instr.push(Instr::AnyCharExcept(exclude));
self
}
pub fn alter(&self, list: Vec<(&'static str, &'static str)>) -> &Self {
if list.len() == 0 {
panic!("List is empty.");
}
if !list.iter().any(|t| { t.0.len() > 0 && t.1.len() > 0 }) {
panic!("The strings in the list must be minimal one character long.");
}
let mut r = self.0.borrow_mut();
r.instr.push(Instr::Alter(list));
self
}
pub fn alter_string(&self, list: Vec<(String, String)>) -> &Self {
if list.len() == 0 {
panic!("List is empty.");
}
if !list.iter().any(|ref t| { t.0.len() > 0 && t.1.len() > 0 }) {
panic!("The strings in the list must be minimal one character long.");
}
let mut r = self.0.borrow_mut();
r.instr.push(Instr::AlterString(list));
self
}
pub fn any_of(&self, rules: Vec<&Rule<T>>) -> &Self {
let mut r = self.0.borrow_mut();
match rules.len() {
0 => panic!("You must specify rules."),
1 => r.instr.push(Instr::Range(1, 1, rules[0].clone())),
_ => r.instr.push(Instr::AnyOf(rules.into_iter().map(|x| x.clone()).collect())),
};
self
}
pub fn at_least(&self, count: u64, rule: &Rule<T>) -> &Self {
let mut r = self.0.borrow_mut();
r.instr.push(Instr::Range(count, u64::max_value(), rule.clone()));
self
}
pub fn at_most(&self, count: u64, rule: &Rule<T>) -> &Self {
let mut r = self.0.borrow_mut();
r.instr.push(Instr::Range(0, count, rule.clone()));
self
}
pub fn between(&self, min: u64, max: u64, rule: &Rule<T>) -> &Self {
let mut r = self.0.borrow_mut();
r.instr.push(Instr::Range(min, max, rule.clone()));
self
}
pub fn char_in(&self, min: char, max: char) -> &Self {
let mut r = self.0.borrow_mut();
r.instr.push(Instr::CharIn(min, max));
self
}
pub fn eof(&self) -> &Self {
let mut r = self.0.borrow_mut();
r.instr.push(Instr::Eof);
self
}
pub fn exact(&self, count: u64, rule: &Rule<T>) -> &Self {
let mut r = self.0.borrow_mut();
r.instr.push(Instr::Range(count, count, rule.clone()));
self
}
pub fn literal(&self, text: &'static str) -> &Self {
if text.len() < 1 {
panic!("Literal text must at least 1 character long.");
}
let mut r = self.0.borrow_mut();
r.instr.push(Instr::Literal(&text));
self
}
pub fn literal_string(&self, text: String) -> &Self {
if text.len() < 1 {
panic!("Literal text must at least 1 character long.");
}
let mut r = self.0.borrow_mut();
r.instr.push(Instr::LiteralString(text));
self
}
pub fn maybe(&self, rule: &Rule<T>) -> &Self {
let mut r = self.0.borrow_mut();
r.instr.push(Instr::Range(0, 1, rule.clone()));
self
}
pub fn no_backtrack(&self, err_msg: String) -> &Self {
let mut r = self.0.borrow_mut();
r.instr.push(Instr::NoBacktrack(err_msg));
self
}
pub fn none_or_many(&self, rule: &Rule<T>) -> &Self {
let mut r = self.0.borrow_mut();
r.instr.push(Instr::Range(0, u64::max_value(), rule.clone()));
self
}
pub fn not(&self, rule: &Rule<T>) -> &Self {
let mut r = self.0.borrow_mut();
r.instr.push(Instr::Not(rule.clone()));
self
}
pub fn one(&self, rule: &Rule<T>) -> &Self {
let mut r = self.0.borrow_mut();
r.instr.push(Instr::Range(1, 1, rule.clone()));
self
}
pub fn scan(&self, code: &str) -> Result<Vec<T>, RuleError> {
let r = self.0.borrow();
if r.instr.len() == 0 {
panic!("Rule is not defined.");
}
let mut ctx = ScanCtx::new(code);
let scanner = Scanner::new();
match scanner.run(self, ctx) {
Progress::Some { steps: _, ctx: new_ctx } => ctx = new_ctx,
Progress::No(new_ctx) => return Err(RuleError::new(code, new_ctx.index, String::from("Syntax error."))),
Progress::Error { idx, msg } => return Err(RuleError::new(code, idx, msg)),
}
if let Some(_) = ctx.code_iter.next() {
Err(RuleError::new(code, ctx.index, String::from("Syntax error.")))
}
else {
Ok(ctx.branches)
}
}
}
struct Scanner {
err: RefCell<ScanErr>,
}
impl Scanner {
fn new() -> Self {
Scanner {
err: RefCell::new(ScanErr { idx: 0, msg: String::from("Syntax error.") }),
}
}
fn run<'s, T>(&self, rule: &Rule<T>, ctx: ScanCtx<'s, T>) -> Progress<'s, T> {
let r = rule.0.borrow();
let (mut new_ctx, ctx) = ctx.branch();
for p in &r.instr {
let progress = match *p {
// Leaves
Instr::AnyChar => self.scan_any_char_leaf(new_ctx),
Instr::AnyCharExcept(ref exclude) => self.scan_any_char_except_leaf(&exclude, new_ctx),
Instr::Alter(ref alter) => self.scan_alter_leaf(&alter, new_ctx),
Instr::AlterString(ref alter) => self.scan_alter_string_leaf(&alter, new_ctx),
Instr::CharIn(min, max) => self.scan_char_in_leaf(min, max, new_ctx),
Instr::Eof => self.scan_eof_leaf(new_ctx),
Instr::Literal(text) => self.scan_literal_leaf(&text, new_ctx),
Instr::LiteralString(ref text) => self.scan_literal_leaf(&text, new_ctx),
// Non leaves
Instr::AnyOf(ref rules) => self.scan_any_of(rules, new_ctx),
Instr::Not(ref r) => self.scan_not(r, new_ctx),
Instr::Range(min, max, ref r) => self.scan_rule_range(min, max, r, new_ctx),
// No backtrack
Instr::NoBacktrack(ref err_msg) => {
if new_ctx.in_not == false {
let mut err = self.err.borrow_mut();
*err = ScanErr { idx: new_ctx.index, msg: err_msg.clone() };
}
Progress::Some { steps: 0, ctx: new_ctx }
},
};
match progress {
Progress::Some { steps: _, ctx: newer_ctx } => new_ctx = newer_ctx,
Progress::No(_) => return self.no_or_error(ctx),
Progress::Error { idx, msg } => return Progress::Error { idx, msg },
}
}
ctx.merge_with(new_ctx, true, &r.branch_fn)
}
fn scan_any_char_except_leaf<'s, T>(&self, exclude: &Vec<char>, mut ctx: ScanCtx<'s, T>) -> Progress<'s, T> {
let n = ctx.code_iter.next();
if let Some(c) = n {
if exclude.contains(&c) {
return Progress::No(ctx);
}
ctx.lexeme.push(c);
ctx.index += 1;
Progress::Some { steps: 1, ctx }
}
else {
Progress::No(ctx)
}
}
fn scan_any_char_leaf<'s, T>(&self, mut ctx: ScanCtx<'s, T>) -> Progress<'s, T> {
let n = ctx.code_iter.next();
if let Some(c) = n {
ctx.lexeme.push(c);
ctx.index += 1;
Progress::Some { steps: 1, ctx }
}
else {
Progress::No(ctx)
}
}
fn scan_alter_leaf<'s, T>(&self, list: &Vec<(&'static str, &'static str)>, mut ctx: ScanCtx<'s, T>) -> Progress<'s, T> {
for alter in list {
let find = alter.0;
let steps = find.chars().count();
let compare: String = ctx.code_iter.clone().take(steps).collect();
if find == compare {
ctx.code_iter.nth(steps - 1);
ctx.lexeme.push_str(alter.1);
ctx.index += steps;
return Progress::Some { steps, ctx };
}
}
Progress::No(ctx)
}
fn scan_alter_string_leaf<'s, T>(&self, list: &Vec<(String, String)>, mut ctx: ScanCtx<'s, T>) -> Progress<'s, T> {
for alter in list {
let find = &alter.0;
let steps = find.chars().count();
let compare: String = ctx.code_iter.clone().take(steps).collect();
if *find == compare {
ctx.code_iter.nth(steps - 1);
ctx.lexeme.push_str(&alter.1);
ctx.index += steps;
return Progress::Some { steps, ctx };
}
}
Progress::No(ctx)
}
fn scan_any_of<'s, T>(&self, rules: &Vec<Rule<T>>, ctx: ScanCtx<'s, T>) -> Progress<'s,T> {
let (mut new_ctx, ctx) = ctx.branch();
for r in rules {
match self.run(r, new_ctx) {
Progress::Some { steps: _, ctx: new_ctx } => {
let r = r.0.borrow();
return ctx.merge_with(new_ctx, false, &r.branch_fn);
},
Progress::No(prev_new_ctx) => {
new_ctx = prev_new_ctx;
},
Progress::Error { idx, msg } => {
return Progress::Error { idx, msg };
}
}
}
self.no_or_error(ctx)
}
fn scan_char_in_leaf<'s, T>(&self, min: char, max: char, mut ctx: ScanCtx<'s, T>) -> Progress<'s, T> {
let c = ctx.code_iter.next();
match c {
Some(c) => {
if c < min || c > max {
Progress::No(ctx)
}
else {
ctx.lexeme.push(c);
ctx.index += 1;
Progress::Some { steps: 1, ctx }
}
},
None => {
Progress::No(ctx)
}
}
}
fn scan_eof_leaf<'s, T>(&self, mut ctx: ScanCtx<'s, T>) -> Progress<'s, T> {
if let None = ctx.code_iter.next() {
ctx.index += 1;
Progress::Some { steps: 1, ctx }
}
else {
Progress::No(ctx)
}
}
fn scan_literal_leaf<'s, T>(&self, find: &str, mut ctx: ScanCtx<'s, T>) -> Progress<'s, T> {
let iter = find.chars();
let mut steps = 0;
for i in iter {
let n = ctx.code_iter.next();
if let Some(c) = n {
if i != c {
return Progress::No(ctx);
}
ctx.index += 1;
steps += 1;
}
else {
return Progress::No(ctx);
}
}
ctx.lexeme.push_str(find);
Progress::Some { steps, ctx }
}
fn scan_not<'s, T>(&self, rule: &Rule<T>, ctx: ScanCtx<'s, T>) -> Progress<'s, T> {
let (mut new_ctx, ctx) = ctx.branch();
new_ctx.in_not = true;
match self.run(rule, new_ctx) {
Progress::Some { steps: _, ctx: _ } => Progress::No(ctx),
Progress::No(_) => Progress::Some { steps: 0, ctx },
Progress::Error{ idx: _, msg: _ } => Progress::Some { steps: 0, ctx },
}
}
fn scan_rule_range<'s, T>(&self, min: u64, max: u64, rule: &Rule<T>, ctx: ScanCtx<'s, T>) -> Progress<'s, T> {
let (mut new_ctx, ctx) = ctx.branch();
let mut count = 0u64;
loop {
match self.run(rule, new_ctx) {
Progress::Some { steps, ctx: newer_ctx } => {
if steps == 0 {
let r = rule.0.borrow();
return ctx.merge_with(newer_ctx, false, &r.branch_fn);
}
new_ctx = newer_ctx;
count += 1;
if count == max {
break;
}
},
Progress::No(prev_new_ctx) => {
new_ctx = prev_new_ctx;
break;
},
Progress::Error { idx, msg } => {
return Progress::Error { idx, msg };
}
}
}
if count >= min && count <= max {
let r = rule.0.borrow();
ctx.merge_with(new_ctx, false, &r.branch_fn)
}
else {
self.no_or_error(ctx)
}
}
fn no_or_error<'s, T>(&self, ctx: ScanCtx<'s, T>) -> Progress<'s, T> {
let err = self.err.borrow();
if ctx.index < err.idx {
Progress::Error { idx: err.idx, msg: err.msg.clone() }
}
else {
Progress::No(ctx)
}
}
}
struct CursorPos {
col: usize,
line: usize,
}
fn cursor_pos(text: &str) -> CursorPos {
let old_osx: Rule<usize> = Rule::default();
old_osx.literal("\r"); // CR
let unix: Rule<usize> = Rule::default();
unix.literal("\n"); // LF
let win: Rule<usize> = Rule::default();
win.literal("\r\n"); // CR+LF
let new_line: Rule<usize> = Rule::default();
new_line.any_of(vec![&win, &old_osx, &unix]);
let ch: Rule<usize> = Rule::default();
ch.any_char_except(vec!['\r', '\n']);
let new_line_only: Rule<usize> = Rule::new(|_, _| Ok(0));
new_line_only.one(&new_line);
let text_and_new_line: Rule<usize> = Rule::new(|_, _| Ok(0));
text_and_new_line.at_least(1, &ch).one(&new_line);
let text_only: Rule<usize> = Rule::new(|_, l| Ok(l.char_indices().count()));
text_only.at_least(1, &ch);
let line: Rule<usize> = Rule::default();
line.any_of(vec![&new_line_only, &text_and_new_line, &text_only]);
let line_counter: Rule<usize> = Rule::default();
line_counter.none_or_many(&line);
if let Ok(lines) = line_counter.scan(text) {
if lines.len() == 0 {
// The scanned `text` is an empty string.
CursorPos { col: 0, line: 1 }
}
else if lines[lines.len() - 1] == 0 {
// Only the rules `text_and_new_line` where found.
CursorPos { col: 0, line: lines.len() + 1 }
}
else {
// The last line was `text_only`.
CursorPos { col: lines[lines.len() - 1], line: lines.len() }
}
}
else {
unreachable!()
}
} |
use image;
use super::*;
pub struct ImageOutput<P, Container>
where P: image::Pixel + 'static
{
// buf: image::ImageBuffer<image::Rgb<u8>,Vec<u8>>,
buf: image::ImageBuffer<P,Container>,
path: String,
}
pub type ImageOutput8 = ImageOutput<image::Rgb<u8>, Vec<u8>>;
impl<P, Container> ImageOutput<P, Container>
where P: image::Pixel
{
pub fn new(settings: &OutputSettings, scene: &Scene) -> Result<ImageOutput8> {
Ok(ImageOutput{
buf: image::ImageBuffer::new(settings.width, settings.height),
path: path_from_template(&settings.filename_template, scene),
})
}
}
impl Output for ImageOutput8 {
fn put_pixel(&mut self, x: u32, y: u32, color: &Vec3<f64>) -> Result<()> {
let pixel = image::Rgb([(color.x*255.99) as u8,
(color.y*255.99) as u8,
(color.z*255.99) as u8]);
self.buf.put_pixel(x, y, pixel);
Ok(())
}
fn end(&mut self) -> Result<()> {
self.buf.save(&self.path)?;
Ok(())
}
}
|
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn serialize_operation_add_application_cloud_watch_logging_option(
input: &crate::input::AddApplicationCloudWatchLoggingOptionInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_add_application_cloud_watch_logging_option_input(
&mut object,
input,
);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_add_application_input(
input: &crate::input::AddApplicationInputInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_add_application_input_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_add_application_input_processing_configuration(
input: &crate::input::AddApplicationInputProcessingConfigurationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_add_application_input_processing_configuration_input(
&mut object,
input,
);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_add_application_output(
input: &crate::input::AddApplicationOutputInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_add_application_output_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_add_application_reference_data_source(
input: &crate::input::AddApplicationReferenceDataSourceInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_add_application_reference_data_source_input(
&mut object,
input,
);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_add_application_vpc_configuration(
input: &crate::input::AddApplicationVpcConfigurationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_add_application_vpc_configuration_input(
&mut object,
input,
);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_application(
input: &crate::input::CreateApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_application_presigned_url(
input: &crate::input::CreateApplicationPresignedUrlInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_application_presigned_url_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_application_snapshot(
input: &crate::input::CreateApplicationSnapshotInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_application_snapshot_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_application(
input: &crate::input::DeleteApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_application_cloud_watch_logging_option(
input: &crate::input::DeleteApplicationCloudWatchLoggingOptionInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_application_cloud_watch_logging_option_input(
&mut object,
input,
);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_application_input_processing_configuration(
input: &crate::input::DeleteApplicationInputProcessingConfigurationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_application_input_processing_configuration_input(
&mut object,
input,
);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_application_reference_data_source(
input: &crate::input::DeleteApplicationReferenceDataSourceInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_application_reference_data_source_input(
&mut object,
input,
);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_application_snapshot(
input: &crate::input::DeleteApplicationSnapshotInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_application_snapshot_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_application_vpc_configuration(
input: &crate::input::DeleteApplicationVpcConfigurationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_application_vpc_configuration_input(
&mut object,
input,
);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_application(
input: &crate::input::DescribeApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_application_snapshot(
input: &crate::input::DescribeApplicationSnapshotInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_application_snapshot_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_describe_application_version(
input: &crate::input::DescribeApplicationVersionInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_describe_application_version_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_discover_input_schema(
input: &crate::input::DiscoverInputSchemaInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_discover_input_schema_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_applications(
input: &crate::input::ListApplicationsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_applications_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_application_snapshots(
input: &crate::input::ListApplicationSnapshotsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_application_snapshots_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_application_versions(
input: &crate::input::ListApplicationVersionsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_application_versions_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_tags_for_resource(
input: &crate::input::ListTagsForResourceInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_tags_for_resource_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_rollback_application(
input: &crate::input::RollbackApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_rollback_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_start_application(
input: &crate::input::StartApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_start_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_stop_application(
input: &crate::input::StopApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_stop_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_tag_resource(
input: &crate::input::TagResourceInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_tag_resource_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_untag_resource(
input: &crate::input::UntagResourceInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_untag_resource_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_update_application(
input: &crate::input::UpdateApplicationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_update_application_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_update_application_maintenance_configuration(
input: &crate::input::UpdateApplicationMaintenanceConfigurationInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_update_application_maintenance_configuration_input(
&mut object,
input,
);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
|
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use lazy_static::lazy_static;
use rcore_fs::dev::{self, BlockDevice, DevError};
use spin::RwLock;
//pub use block::BlockDriver;
/// Block device
pub mod virtio;
/// Device tree
pub mod device_tree;
#[derive(Debug, Eq, PartialEq)]
pub enum DeviceType {
Net,
Gpu,
Input,
Block,
Rtc,
Serial,
Intc,
}
pub trait Driver: Send + Sync {
// if interrupt belongs to this driver, handle it and return true
// return false otherwise
// irq number is provided when available
// driver should skip handling when irq number is mismatched
fn try_handle_interrupt(&self, irq: Option<usize>) -> bool;
// return the correspondent device type, see DeviceType
fn device_type(&self) -> DeviceType;
// get unique identifier for this device
// should be different for each instance
fn get_id(&self) -> String;
// trait casting
/*
fn as_net(&self) -> Option<&dyn NetDriver> {
None
}
*/
fn as_block(&self) -> Option<&dyn BlockDriver> {
None
}
/*
fn as_rtc(&self) -> Option<&dyn RtcDriver> {
None
}
*/
}
/////////
pub trait BlockDriver: Driver {
fn read_block(&self, _block_id: usize, _buf: &mut [u8]) -> bool {
unimplemented!("not a block driver")
}
fn write_block(&self, _block_id: usize, _buf: &[u8]) -> bool {
unimplemented!("not a block driver")
}
}
pub trait GpuDriver: Driver {
fn resolution(&self) -> (u32, u32) {
unimplemented!("not a gpu driver")
}
fn setup_framebuffer(&self) -> (usize, usize) {
unimplemented!("not a gpu driver")
}
fn flush(&self) -> virtio_drivers::Result {
unimplemented!("not a gpu driver")
}
}
pub trait InputDriver: Driver {
fn mouse_xy(&self) -> (i32, i32) {
unimplemented!("not a input driver")
}
}
/////////
lazy_static! {
// NOTE: RwLock only write when initializing drivers
pub static ref DRIVERS: RwLock<Vec<Arc<dyn Driver>>> = RwLock::new(Vec::new());
pub static ref BLK_DRIVERS: RwLock<Vec<Arc<dyn BlockDriver>>> = RwLock::new(Vec::new());
pub static ref INPUT_DRIVERS: RwLock<Vec<Arc<dyn InputDriver>>> = RwLock::new(Vec::new());
pub static ref GPU_DRIVERS: RwLock<Vec<Arc<dyn GpuDriver>>> = RwLock::new(Vec::new());
//pub static ref IRQ_MANAGER: RwLock<irq::IrqManager> = RwLock::new(irq::IrqManager::new(true));
}
pub struct BlockDriverWrapper(pub Arc<dyn BlockDriver>);
impl BlockDevice for BlockDriverWrapper {
const BLOCK_SIZE_LOG2: u8 = 9; // 512
fn read_at(&self, block_id: usize, buf: &mut [u8]) -> dev::Result<()> {
match self.0.read_block(block_id, buf) {
true => Ok(()),
false => Err(DevError),
}
}
fn write_at(&self, block_id: usize, buf: &[u8]) -> dev::Result<()> {
match self.0.write_block(block_id, buf) {
true => Ok(()),
false => Err(DevError),
}
}
fn sync(&self) -> dev::Result<()> {
Ok(())
}
}
lazy_static! {
// Write only once at boot
pub static ref CMDLINE: RwLock<String> = RwLock::new(String::new());
}
|
use nom::{digit, is_alphanumeric, IResult};
use std::str::{self, FromStr};
#[derive(Debug)]
pub enum RuleExpression {
Literal(Box<LiteralExpression>),
Operator(Box<OperatorExpression>),
}
#[derive(Debug)]
pub enum LiteralExpression {
Num(i32),
Str(String),
Bool(bool),
}
#[derive(Debug)]
pub struct OperatorExpression {
operator_type: OperatorType,
args: Vec<RuleExpression>,
}
#[derive(Debug)]
pub enum OperatorType {
And,
Or,
List,
}
named!(int <i32>,
map_res!(
map_res!(
digit,
str::from_utf8
),
FromStr::from_str
)
);
named!(string <&str>,
map_res!(
delimited!(
tag!("\""),
escaped!(
is_not!("\\\""),
'\\',
one_of!("\\\"")
),
tag!("\"")
),
str::from_utf8
)
);
named!(boolean <bool>,
map_res!(
map_res!(
alt!(
tag!("true") | tag!("false")
),
str::from_utf8
),
FromStr::from_str
)
);
named!(literal <LiteralExpression>,
alt_complete!(
int => { |i| LiteralExpression::Num(i) } |
string => { |s| LiteralExpression::Str(String::from(s)) } |
boolean => { |b| LiteralExpression::Bool(b) }
)
);
fn parse_func_name(name: &str) -> Result<OperatorType, String> {
let op = match name {
"or" => OperatorType::Or,
"and" => OperatorType::And,
_ => return Result::Err(String::from(format!("Unknown operator {}", name)))
};
Result::Ok(op)
}
named!(args <Vec<RuleExpression>>,
separated_list!(
tag!(","),
rule_expr
)
);
named!(func <OperatorExpression>,
do_parse!(
op_type: map_res!(
map_res!(
take_while!( |x| is_alphanumeric(x) || x == b'_' ),
str::from_utf8
),
parse_func_name
) >>
tag!("(") >>
f_args: args >>
tag!(")") >>
(OperatorExpression{ operator_type: op_type, args: f_args })
)
);
named!(list <OperatorExpression>,
do_parse!(
tag!("[") >>
l_args: args >>
tag!("]") >>
(OperatorExpression{ operator_type: OperatorType::List, args: l_args })
)
);
named!(operator <OperatorExpression>,
alt_complete!(
func | list
)
);
named!(rule_expr <RuleExpression>,
ws!(
alt_complete!(
operator => { |e| RuleExpression::Operator(Box::new(e)) } |
literal => { |e| RuleExpression::Literal(Box::new(e)) }
)
)
);
fn parse_expr(text: &str) -> RuleExpression {
match rule_expr(text.as_bytes()) {
IResult::Done(_, res) => res,
_ => panic!("Error parsing")
}
}
mod eval;
#[cfg(test)]
mod tests {
use super::*;
use super::eval::*;
use super::eval::PrimitiveValue::*;
use super::eval::ExpressionValue::*;
#[test]
fn num_literal() {
let expr = parse_expr("228");
if let Single(Num(val)) = eval_expr(&expr) {
assert_eq!(val, 228);
} else {
panic!("Expected single number");
}
}
#[test]
fn str_literal() {
let expr = parse_expr("\"str 123!\"");
if let Single(Str(s)) = eval_expr(&expr) {
assert_eq!(s, "str 123!");
} else {
panic!("Expected single string");
}
}
#[test]
fn bool_literal() {
let expr = parse_expr("false");
if let Single(Bool(b)) = eval_expr(&expr) {
assert_eq!(b, false);
} else {
panic!("Expected single bool");
}
}
#[test]
fn list_operator() {
let expr = parse_expr("[1, 2]");
if let Repeated(lst) = eval_expr(&expr) {
let v: Vec<_> = lst.iter()
.map(|x| if let &Num(ref v) = x { *v } else { 0 })
.collect();
assert_eq!(v, vec![1, 2]);
} else {
panic!("Expected repeated");
}
}
#[test]
fn nested_operators() {
let expr = parse_expr("and(true, or(true, false), and(true, true))");
if let Single(Bool(b)) = eval_expr(&expr) {
assert_eq!(b, true);
} else {
panic!("Expected single bool");
}
}
}
|
// 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;
pub use common_config::InnerConfig;
use common_exception::ErrorCode;
use common_exception::Result;
use common_meta_app::principal::AuthInfo;
use common_meta_app::principal::UserInfo;
use common_users::JwtAuthenticator;
use common_users::UserApiProvider;
use crate::sessions::Session;
pub struct AuthMgr {
jwt_auth: Option<JwtAuthenticator>,
}
pub enum Credential {
Jwt {
token: String,
hostname: Option<String>,
},
Password {
name: String,
password: Option<Vec<u8>>,
hostname: Option<String>,
},
}
impl AuthMgr {
pub fn create(cfg: &InnerConfig) -> Arc<AuthMgr> {
Arc::new(AuthMgr {
jwt_auth: JwtAuthenticator::create(
cfg.query.jwt_key_file.clone(),
cfg.query.jwt_key_files.clone(),
),
})
}
pub async fn auth(&self, session: Arc<Session>, credential: &Credential) -> Result<()> {
match credential {
Credential::Jwt {
token: t,
hostname: h,
} => {
let jwt_auth = self
.jwt_auth
.as_ref()
.ok_or_else(|| ErrorCode::AuthenticateFailure("jwt auth not configured."))?;
let jwt = jwt_auth.parse_jwt_claims(t.as_str()).await?;
let user_name = jwt.subject.ok_or_else(|| {
ErrorCode::AuthenticateFailure(
"jwt auth not configured correctly, user name is missing.",
)
})?;
// setup tenant if the JWT claims contain extra.tenant_id
if let Some(tenant) = jwt.custom.tenant_id {
session.set_current_tenant(tenant);
};
let tenant = session.get_current_tenant();
// create user if not exists when the JWT claims contains ensure_user
if let Some(ref ensure_user) = jwt.custom.ensure_user {
let mut user_info = UserInfo::new(&user_name, "%", AuthInfo::JWT);
if let Some(ref roles) = ensure_user.roles {
for role in roles.clone().into_iter() {
user_info.grants.grant_role(role);
}
}
UserApiProvider::instance()
.ensure_builtin_roles(&tenant)
.await?;
UserApiProvider::instance()
.add_user(&tenant, user_info.clone(), true)
.await?;
}
let auth_role = jwt.custom.role.clone();
let user_info = UserApiProvider::instance()
.get_user_with_client_ip(
&tenant,
&user_name,
h.as_ref().unwrap_or(&"%".to_string()),
)
.await?;
session.set_authed_user(user_info, auth_role).await?;
}
Credential::Password {
name: n,
password: p,
hostname: h,
} => {
let tenant = session.get_current_tenant();
let user = UserApiProvider::instance()
.get_user_with_client_ip(&tenant, n, h.as_ref().unwrap_or(&"%".to_string()))
.await?;
let user = match &user.auth_info {
AuthInfo::None => user,
AuthInfo::Password {
hash_value: h,
hash_method: t,
} => match p {
None => return Err(ErrorCode::AuthenticateFailure("password required")),
Some(p) => {
if *h == t.hash(p) {
user
} else {
return Err(ErrorCode::AuthenticateFailure("wrong password"));
}
}
},
_ => return Err(ErrorCode::AuthenticateFailure("wrong auth type")),
};
session.set_authed_user(user, None).await?;
}
};
Ok(())
}
}
|
// Membuat input dari console dapat menggunakan `print!`
// dan inputan berada disampingnya
// dengan cara memflush `stdout`
//
use std::io::{self, Write};
fn main() {
print!("Nama Anda: ");
let stdout = io::stdout();
let mut handle = stdout.lock();
let _ = handle.flush();
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
println!("{}", input);
}
|
use std::io::{BufRead, Lines};
use subprocess::Exec;
#[inline]
pub fn exec(cmd: Exec) -> std::io::Result<Lines<impl BufRead>> {
// We usually have a decent amount of RAM nowdays.
Ok(std::io::BufReader::with_capacity(
8 * 1024 * 1024,
cmd.stream_stdout()
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?,
)
.lines())
}
|
fn main() {
let list = include_str!("input").lines().map(|st| u16::from_str_radix(st, 2).unwrap()).collect();
println!("Part Two: {}", part_one(&list));
println!("Part Two: {}", part_two(&list));
}
fn part_one(list: &Vec<u16>) -> u64 {
let mut counts = vec![0; 12];
for num in list {
for i in 0..counts.len() {
counts[i] += nth_bit_in(num, i as u16);
}
};
let mut gamma_rate = 0;
let mut epsilon_rate = 0;
let half_vol = (list.len()/2) as u16;
for i in 0..counts.len() {
if counts[i] > half_vol {
gamma_rate += 1 << i;
} else {
epsilon_rate += 1 << i;
}
}
gamma_rate * epsilon_rate
}
fn part_two(list: &Vec<u16>) -> u64 {
(get_co2_scrubber_rating(&list) as u64) * (get_oxygen_scrubber_rating(&list) as u64)
}
fn get_oxygen_scrubber_rating(list: &Vec<u16>) -> u16 {
filter_by_common_bits(list, true)
}
fn get_co2_scrubber_rating(list: &Vec<u16>) -> u16 {
filter_by_common_bits(list, false)
}
fn filter_by_common_bits(list: &Vec<u16>, choose_common: bool) -> u16 {
let mut list = list.to_owned();
for i in (0..12).rev() {
list = filter_by_common_bit(&list, i, choose_common);
if list.len() == 1 {
break;
}
}
list[0]
}
// Default bit is 1 when choose_common is true
fn filter_by_common_bit(list: &Vec<u16>, bit: u16, choose_common: bool) -> Vec<u16> {
let (one,zero):(_,Vec<_>) = list
.into_iter()
.partition(|x| nth_bit_in(x, bit) == 1);
if choose_common {
if zero.len() > one.len() { return zero; }
return one
}
if one.len() < zero.len() { return one; }
zero
}
fn nth_bit_in(num: &u16, n: u16) -> u16 {
if num & (1 << n) != 0 {
return 1
};
0
}
|
//! Example non-exhaustive enums,used in tests
#![allow(dead_code, missing_docs)]
#![allow(clippy::derive_partial_eq_without_eq)]
pub mod command_one {
use std::fmt::{self, Display};
#[repr(u8)]
#[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)]
#[sabi(kind(WithNonExhaustive(
size = 64,
traits(Debug, PartialEq, Eq, Clone),
assert_nonexhaustive = Foo,
)))]
pub enum Foo {
A,
}
impl Display for Foo {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Ok(())
}
}
}
pub mod command_one_more_traits_1 {
use std::fmt::{self, Display};
#[repr(u8)]
#[derive(StableAbi, Debug, PartialEq, Eq, Clone, Hash)]
#[sabi(kind(WithNonExhaustive(
size = 64,
traits(Debug, PartialEq, Eq, Clone, Hash),
assert_nonexhaustive(Foo),
)))]
pub enum Foo {
A,
}
impl Display for Foo {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Ok(())
}
}
}
pub mod command_one_more_traits_2 {
use std::fmt::{self, Display};
#[repr(u8)]
#[derive(StableAbi, Debug, PartialEq, Eq, PartialOrd, Clone, Hash)]
#[sabi(kind(WithNonExhaustive(
size = 64,
traits(Debug, PartialEq, Eq, PartialOrd, Clone, Hash)
)))]
pub enum Foo {
A,
}
impl Display for Foo {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Ok(())
}
}
}
pub mod command_one_more_traits_3 {
use std::fmt::{self, Display};
#[repr(u8)]
#[derive(StableAbi, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
#[sabi(kind(WithNonExhaustive(
size = 64,
traits(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)
)))]
pub enum Foo {
A,
}
impl Display for Foo {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Ok(())
}
}
}
pub mod command_a {
use std::fmt::{self, Display};
#[repr(u8)]
#[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)]
#[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))]
pub enum Foo {
A,
B(i8),
}
impl Display for Foo {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Ok(())
}
}
}
pub mod command_a_exhaustive {
use std::fmt::{self, Display};
#[repr(u8)]
#[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)]
pub enum Foo {
A,
B(i8),
}
impl Display for Foo {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Ok(())
}
}
}
pub mod command_b {
use std::fmt::{self, Display};
#[repr(u8)]
#[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)]
#[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))]
pub enum Foo {
A,
B(i8),
C,
}
impl Display for Foo {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Ok(())
}
}
}
pub mod command_c {
use crate::std_types::RString;
#[repr(u8)]
#[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)]
#[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))]
pub enum Foo {
A,
B(i8),
C,
D { name: RString },
}
}
pub mod command_c_mismatched_field {
use crate::std_types::RVec;
#[repr(u8)]
#[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)]
#[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))]
pub enum Foo {
A,
B(i8),
C,
D { name: RVec<u8> },
}
}
pub mod command_serde {
use std::fmt::{self, Display};
use serde::{Deserialize, Serialize};
use crate::std_types::RString;
#[repr(u8)]
#[derive(
StableAbi, Hash, Debug, PartialEq, Eq, Ord, PartialOrd, Clone, Deserialize, Serialize,
)]
#[sabi(kind(WithNonExhaustive(
size = 64,
traits(Debug, Display, PartialEq, Eq, Clone, Deserialize, Serialize)
)))]
// #[sabi(debug_print)]
pub enum Foo {
A,
B(i8),
C,
D { name: RString },
}
impl Display for Foo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Foo::A => write!(f, "Variant A"),
Foo::B(v) => write!(f, "Variant B with value:{}", v),
Foo::C => write!(f, "Variant C"),
Foo::D { name } => write!(f, "Variant D named:{}", name),
}
}
}
delegate_interface_serde! {
impl[T,] Traits<T> for Foo_Interface;
lifetime='borr;
delegate_to=super::codecs::Json;
}
}
pub mod too_large {
#[repr(u8)]
#[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)]
#[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))]
pub enum Foo<T = i8> {
A,
B(T),
C([u16; 32]),
}
}
pub mod generic_a {
use std::fmt::{self, Display};
#[repr(u8)]
#[derive(StableAbi, Hash, Debug, PartialOrd, Ord, PartialEq, Eq, Clone)]
#[sabi(kind(WithNonExhaustive(
size = 64,
traits(Debug, PartialEq, Eq, Ord, PartialOrd, Clone, Hash)
)))]
//#[sabi(debug_print)]
pub enum Foo<T> {
A,
B,
C(T),
}
impl<T> Display for Foo<T>
where
T: Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Foo::A => write!(f, "Variant A"),
Foo::B => write!(f, "Variant B"),
Foo::C(v) => write!(f, "Variant C:{}", v),
}
}
}
}
pub mod generic_b {
#[repr(u8)]
#[derive(StableAbi, Debug, PartialEq)]
#[sabi(kind(WithNonExhaustive(size = 64, align = 8, traits(Debug, PartialEq))))]
pub enum Foo<T> {
A,
B,
C(T),
}
}
pub mod many_ranges_a {
#[repr(u8)]
#[derive(StableAbi, Debug, PartialEq, Eq, Clone)]
#[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))]
pub enum Foo {
A,
B = 40,
C,
D,
E = 60,
F,
}
}
pub mod many_ranges_b {
#[repr(u8)]
#[derive(StableAbi, Debug, PartialEq, Eq, Clone)]
#[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))]
pub enum Foo {
A,
B = 40,
C,
E = 60,
}
}
pub mod command_h {
use std::fmt::{self, Display};
#[repr(u8)]
#[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)]
#[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))]
pub enum Foo {
A,
B,
C,
}
impl Display for Foo {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Ok(())
}
}
}
pub mod command_h_mismatched_discriminant {
use std::fmt::{self, Display};
#[repr(u8)]
#[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)]
#[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))]
pub enum Foo {
A = 40,
B,
C,
}
impl Display for Foo {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Ok(())
}
}
}
pub mod const_expr_size_align {
use std::fmt::{self, Display};
const fn size() -> usize {
10
}
const fn align() -> usize {
2
}
#[repr(u8)]
#[derive(StableAbi, Debug, PartialEq)]
#[sabi(kind(WithNonExhaustive(
size = { size() },
align = { align() },
traits(Debug, PartialEq)
)))]
pub enum Foo<T> {
A,
B,
C(T),
}
impl<T> Display for Foo<T> {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Ok(())
}
}
}
pub mod codecs {
use serde::{Deserialize, Serialize};
use crate::{
nonexhaustive_enum::{
DeserializeEnum, GetEnumInfo, GetVTable, NonExhaustive, SerializeEnum,
},
std_types::{RBoxError, RString},
};
#[repr(C)]
#[derive(StableAbi)]
#[sabi(impl_InterfaceType())]
pub struct Json;
impl<E> SerializeEnum<E> for Json
where
E: Serialize + GetEnumInfo,
{
type Proxy = RString;
fn serialize_enum(this: &E) -> Result<RString, RBoxError> {
serde_json::to_string(this)
.map(RString::from)
.map_err(RBoxError::new)
}
}
impl<'borr, E, S, I> DeserializeEnum<'borr, NonExhaustive<E, S, I>> for Json
where
E: GetVTable<S, I> + for<'de> Deserialize<'de>,
{
type Proxy = RString;
fn deserialize_enum(s: RString) -> Result<NonExhaustive<E, S, I>, RBoxError> {
serde_json::from_str(&s)
.map(NonExhaustive::with_storage_and_interface)
.map_err(RBoxError::new)
}
}
}
|
use std::ops::Range;
use bevy::{
prelude::*,
render::{
mesh::{
VertexAttribute,
VertexAttributeValues
},
pipeline::{
DynamicBinding,
PipelineSpecialization,
PrimitiveTopology,
RenderPipeline
},
}
};
use crate::egui_node::EguiNode;
/// Describes the egui jobs with tuples of (index_range, start_vertex)
#[derive(Default)]
pub struct EguiJobsDescriptor {
pub jobs: Vec<(Range<u32>, i32)>
}
/// Bundle for the draw entity of an egui context. Each context needs a unique draw entity so it can be displayed.
#[derive(Bundle)]
pub struct EguiComponents {
/// Stores the jobs information necessary to properly batch the mesh draw calls
pub jobs_descriptor: EguiJobsDescriptor,
/// Associates our entity with the Egui render passes and holds information to associate with an Egui context.
pub egui_node: Handle<EguiNode>,
/// Handle to the actual mesh information for rendering the ui
pub mesh: Handle<Mesh>,
/// The render pipelines hooked up to the egui pipeline ensuring proper rendering
pub render_pipelines: RenderPipelines,
/// Utility component allowing entity to be drawn
pub draw: Draw,
/// Relative spacial location of the gui. Does influence where the ui is drawn, as the ui is still seen through a camera
pub transform: Transform,
/// Global spacial location of the gui. Similar to the regular Transform field
pub global_transform: GlobalTransform,
}
impl Default for EguiComponents {
fn default() -> Self {
Self {
jobs_descriptor: Default::default(),
egui_node: Default::default(),
mesh: Default::default(),
render_pipelines: RenderPipelines::from_pipelines(vec![RenderPipeline::specialized(
crate::render::EGUI_PIPELINE_HANDLE,
PipelineSpecialization {
dynamic_bindings: vec![
// Transform
DynamicBinding {
bind_group: 2,
binding: 0
},
],
..Default::default()
},
)]),
draw: Default::default(),
transform: Default::default(),
global_transform: Default::default(),
}
}
}
impl EguiComponents {
pub(crate) fn from_setup(resources: &Resources) -> Self {
let mut meshes = resources.get_mut::<Assets<Mesh>>().unwrap();
Self {
mesh: meshes.add(Mesh {
primitive_topology: PrimitiveTopology::TriangleList,
attributes: vec![
VertexAttribute {
name: "BevyEguiVertex_Position".into(),
values: VertexAttributeValues::Float3(Vec::new())
},
VertexAttribute {
name: "BevyEguiVertex_Normal".into(),
values: VertexAttributeValues::Float3(Vec::new()),
},
VertexAttribute {
name: "BevyEguiVertex_Uv".into(),
values: VertexAttributeValues::Float2(Vec::new()),
},
VertexAttribute {
name: "BevyEguiVertex_Color".into(),
values: VertexAttributeValues::Float4(Vec::new())
},
VertexAttribute {
name: "BevyEguiVertex_ClipMin".into(),
values: VertexAttributeValues::Float2(Vec::new())
},
VertexAttribute {
name: "BevyEguiVertex_ClipMax".into(),
values: VertexAttributeValues::Float2(Vec::new())
}
],
indices: Some(Vec::new()),
}),
..Default::default()
}
}
} |
use super::*;
pub trait Hittable {
fn hit(&self, ray: &Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool;
}
impl<T: Hittable> Hittable for Vec<T> {
fn hit(&self, ray: &Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool {
let mut hr = HitRecord::default();
let mut hit_anything = false;
let mut closest_so_far = t_max;
for obj in self.iter() {
if obj.hit(ray, t_min, closest_so_far, &mut hr) {
hit_anything = true;
closest_so_far = hr.t;
}
}
*rec = hr;
hit_anything
}
}
|
use std::{
collections::{BTreeMap, VecDeque},
fmt,
fs::{File, OpenOptions},
io::{self, BufWriter, Seek, SeekFrom},
ops::Deref,
path::Path,
};
use slack::RtmClient;
use crate::queue::{AddResult::*, RemoveResult::*};
use crate::user::{SlackMap, UserID};
/// The User ID (a string of the form UXXXXXXX) for the Queue app
pub const QUEUE_UID: &str = "<@U01A844Q2US>";
/// Sometimes we need these.
pub const INSPIRATIONAL_QUOTE: &str =
"_Waiting in line is a great opportunity to meet people, daydream, or play._\n\t\u{2014}Patch Adams";
/// Which Slack channel Queue is running in.
const CHANNEL: &str = "3d-printer-queue";
/// A help message to display when the `help` command is invoked
const USAGE: &str = "*Queue* is a :slack: bot that keeps track of who is waiting in line to use the \
3D printers. You interact with it by @mentioning it and then typing a command (e.g. `@Queue help`).\
Here are the different commands *Queue* currently recognizes:\n\n\
• *add*: Add yourself to the queue. You can add yourself multiples times, in case there are multiple \
things you want to 3D print. However, you cannot have two back-to-back instances of yourself in the \
queue so that you let others get a chance. However, if the queue is relatively empty (and by relatively \
empty I mean less than 3 people in line), then you _can_ have back-to-back instances of yourself, since \
not as many people are being negatively affected by having back-to-back instances of yourself in the queue \
as they would be if there were more than 3 people in line.\n\
• *done*: Leave the queue. If there are multiple instances of you in the queue, the _first_ instance \
(i.e. the one closest to the front) is removed. If you were in 0th place when you were removed, the \
person is 1st place is notified of this change.\n\
• *show*: See who is in the queue and in what place.\n\
• *help*: Display this message.";
/// Given the body of a post to Slack, determine someone mentioned the Queue app
fn is_app_mention(text: &str) -> bool {
text.contains(QUEUE_UID)
}
/// The main data structure for keeping track of Slack users for an event.
#[derive(Debug)]
pub struct Queue<'a> {
/// A queue of references to UserIDs in the `uid_username_mapping`
queue: VecDeque<UserID>,
/// All the possible members of a Slack workspace that can join a queue
uid_username_mapping: &'a SlackMap,
/// All the different channels in the workspace Queue is installed in, mapping channel names to
/// channel IDs
chan_name_id_mapping: BTreeMap<String, String>,
/// The file that `self` will write to to preserve its state (may be a database connection in the future)
db_conn: BufWriter<File>,
}
/// A type used to represent the result of adding a user to the queue.
#[derive(Debug)]
pub enum AddResult {
/// The specified user was *not* added to the queue because they need to let someone else take a
/// turn before they add themselves again.
UserNotAdded,
/// The specified user was successfully added.
UserSuccessfullyAdded,
/// The specified user was added to the queue, but there was an I/O error while writing to a file
/// that keeps the queue persistent, so the backup file and the true state of the queue are now
/// out of sync.
UserUnsuccessfullyAdded(io::Error),
}
/// A type used to represent the result a removing a user from the queue.
#[derive(Debug)]
pub enum RemoveResult {
/// The user was not the the queue in the first place, so they cannot be removed!
NonExistentUser,
/// The user was successfully removed from the queue. This variant contains the position that
/// they were in before they were removed from the queue.
UserSuccessfullyRemoved(usize),
/// The specified user was removed from the queue, but there was an I/O error while writing to a
/// file that keeps the queue persistent, so the backup file and the true state of the queue are
/// now out of sync.
UserUnsuccessfullyRemoved(io::Error),
}
impl<'a> Queue<'a> {
/// Create an empty queue with no previous state. `uids_to_users` is a `std::collections::HashMap`
/// whose keys are Slack IDs and whose values are usernames associated with the given Slack ID.
///
/// This function will also create an empty file that, over the course of the lifetime of this
/// queue, will be written to representing the users in the queue so that, if the app were to
/// crash, the queue isn't lost. By default, this file's name is `queue_state.txt`. If you want
/// to use a different name, use [`Queue::from_file`](#method.from_file)
///
/// # Panics
/// This function will panic if the aforementioned `queue_state.txt` fails to be created.
pub fn new(uids_to_users: &'a SlackMap) -> Self {
Self {
queue: VecDeque::new(),
uid_username_mapping: uids_to_users,
chan_name_id_mapping: BTreeMap::new(),
db_conn: BufWriter::new(
File::create("queue_state.txt")
.expect("Could not create a backup file for the queue"),
),
}
}
/// Create a queue whose state is described by the file located at `path`, effectively restoring
/// it from a previous state. The file should be one that was previously created by running this
/// app. Or, if the file does not exist, it will be created.
///
/// # Examples
/// Say the input file contains the following content.
/// ```text
/// 0 UA8RXUPSP
/// 1 UNB2LMZRP
/// 2 UN480W9ND
/// ```
/// Then invoking this function with the above file will create a new `Queue` where the first
/// person in line has an ID of `UA8RXUPSP`, the second person in line has an ID of `UNB2LMZRP`,
/// and the third person in line has an ID of `UN480W9ND`.
///
/// # Panics
/// For better or worse, there are many ways this function can panic.
/// * If the file breaks the "rules" (see the documentation for
/// [`Queue::add_user`](#method.add_user)) of adding people to the queue (e.g. the file contains
/// the same person five times in a row, which shouldn't be allowed under any circumstance), then
/// the file will be rejected and this function will panic.
/// * If the file at `path` fails to open for any reason (e.g. permissions).
/// * If the file at `path` fails to be read for any reason.
/// * If the file is _not_ in the valid format expected by queue: each line is a positive integer,
/// followed by a tab, followed by a Slack user ID.
pub fn from_file<P: AsRef<Path>>(uids_to_users: &'a SlackMap, path: P) -> Self {
use std::io::Read; // needed for the invocation of read_to_string()
let mut people = BTreeMap::new();
let mut backup_file_contents = String::new();
let backup_file_name = path.as_ref().as_os_str().to_owned();
let mut backup_file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)
.expect("Could not open backup file for the queue");
if let Err(e) = backup_file.read_to_string(&mut backup_file_contents) {
panic!("could not read {:?}: {}", backup_file_name, e);
}
// Iterate only over the lines that have content (i.e. are not all whitespace)
for line in backup_file_contents
.lines()
.filter(|s| !s.trim().is_empty())
{
let [pos, uid] = {
let err_msg = "Invalid file format: each line must contain a parse-able \
positive integer followed by some amount of whitespace, followed by a Slack user-id";
let mut iter = line.split_whitespace();
[iter.next().expect(err_msg), iter.next().expect(err_msg)]
};
let pos = pos.parse::<usize>().expect(
"Invalid file format: each line in the file must start with a parse-\
able positive integer",
);
if let Some(_) = people.insert(pos, uid) {
panic!("Invalid file format: only one person per position (index) in line");
}
}
let mut queue = Self {
queue: VecDeque::with_capacity(people.len()),
uid_username_mapping: uids_to_users,
chan_name_id_mapping: BTreeMap::new(),
db_conn: BufWriter::new(backup_file),
};
for (pos, person) in people {
if !queue.add_user_no_write(UserID::new(person)) {
panic!(
"user {} in position {} \"breaks the addition rules\": see the Queue document\
ation for more",
person, pos
);
}
}
queue
}
/// Writes the current state of `self` to `self.db_conn` so that this particular state can be
/// reloaded later.
fn write_state(&mut self) -> io::Result<()> {
use std::io::Write; // needed for the invocation of std::io::Write::flush
// We write the state to a temporary buffer before writing the entirety of the buffer to the
// file.
let mut output = Vec::new();
// For each user in the queue, write the line
// {user position}<tab>{user ID}
// returning early if any line fails.
// Otherwise, flush the BufWriter to the file and hope it works :P
for (pos, uid) in self.queue.iter().enumerate() {
write!(output, "{}\t{}\n", pos, uid)?;
}
// Get the number of bytes in the file currently
let num_bytes = self.db_conn.seek(SeekFrom::End(0))?;
// Now go back to the start of the file
self.db_conn.seek(SeekFrom::Start(0))?;
// And now create a bunch of blanks to erase the file
let blanks = vec![b' '; num_bytes as usize];
self.db_conn.write_all(&*blanks)?;
// This is getting tiring...go back to the start of the file
self.db_conn.seek(SeekFrom::Start(0))?;
// Write the new state
self.db_conn.write_all(output.as_slice())?;
self.db_conn.flush()
}
/// Can `user` be added to `self` based on the following rules?
///
/// 1. If the queue is *not empty*, then a user can only be added to the queue if the person in
/// front of them is __not themselves__.
/// 2. If the queue *is empty*, then a user can be added up to three times.
fn can_add(&self, user: &UserID) -> bool {
self.len() < 3 || self.back() != Some(user)
}
/// Add a user to the back of the queue _without_ writing to the backup file, returning true if
/// the user could be added per the rules, and false otherwise. See
/// [`Queue::add_user`](#method.add_user) for more.
fn add_user_no_write(&mut self, user: UserID) -> bool {
if self.can_add(&user) {
self.queue.push_back(user);
true
} else {
false
}
}
/// Add a User to the back of the queue.
///
/// People are allowed to be in the queue multiple times. The rules are as follows:
/// 1. If the queue is *not empty*, then a user can only be added to the queue if the person in front
/// them is __not themselves__.
/// 2. If the queue *is empty*, then a user can be added up to three times.
///
/// This function will write to the backup file that persists the state of the queue. If that
/// write fails, then an `(u, AddResult::UserUnsuccessfullyAdded(e))` is returned, where `u` is
/// *a reference to* the user that was just added to the queue but __not__ to the backup file,
/// and `e` is a `std::io::Error` describing what went wrong. If the user couldn't be added to the
/// queue in the first place (because the addition would have violated the rules stated above),
/// then __no file I/O occurs__ and a `(u, AddResult::UserNotAddded)` is returned, where `u` is
/// *a reference to* the user that was *going to be* added. Otherwise, a
/// `(u, AddResult::UserSuccessfullyAdded)` is returned, where `u` is a *a reference to* the user
/// that was just added to the queue.
pub fn add_user(&mut self, user: UserID) -> (UserID, AddResult) {
if self.add_user_no_write(user.clone()) {
match self.write_state() {
Ok(()) => (user, UserSuccessfullyAdded),
Err(e) => (user, UserUnsuccessfullyAdded(e)),
}
} else {
(user, UserNotAdded)
}
}
/// Handle the add command. Returns a message to post in the Slack channel depending on whether
/// or not the user was actually added.
fn add(&mut self, user: UserID) -> String {
match self.add_user(user) {
(user, UserSuccessfullyAdded) => {
format!("Okay <@{}>, I have added you to the queue.", user)
}
(user, UserNotAdded) => format!(
"<@{}>, you cannot be added to the queue at \
this time. Please let others get a chance to wait in line before you go again.",
user
),
(user, UserUnsuccessfullyAdded(e)) => format!(
"Hi <@{}>. You have been \
added to the queue, but this change has not been reflected in the backup file that stores \
the state of the queue. If it helps, the reason why is: {}",
user, e
),
}
}
/// Handle the done command. Returns a message to post in the Slack channel depending on whether
/// or not the user was removed.
fn done(&mut self, user: UserID) -> String {
match self.remove_user(user) {
(user, UserSuccessfullyRemoved(idx)) => {
let mut response = format!(
"Okay <@{}>, you have been removed from{}the queue.",
user.0,
if idx == 0 { " the front of " } else { " " }
);
// If the person just removed was at the front, then notify the next person in line
// (if there is one)
if idx == 0 {
match self.peek_first_user_in_line() {
Some(next) => {
response.push_str("\nHey <@");
response.push_str(&*next.0);
response.push_str(">! You\'re next in line!");
}
None => response.push_str("\nNobody is next in line!"),
}
}
response
}
(user, NonExistentUser) => format!(
"<@{}>, you cannot be removed; you are not \
in the queue.",
user
),
(user, UserUnsuccessfullyRemoved(e)) => format!(
"Hi <@{}>. You were removed \
from the queue, but this change has not been reflected in the backup file that stores \
the state of the queue. If it helps, the reason why is: {}",
user, e
),
}
}
/// Retrieve the person who is at the front if the line, if they exist. This does **not** remove
/// the person, only retrieves them.
///
/// Returns `None` if the queue is empty. Else returns `Some(user)` where `user` is the user at
/// the front of the line.
pub(in crate) fn peek_first_user_in_line(&self) -> Option<&UserID> {
self.queue.get(0)
}
/// Remove the particular user in the queue, e.g. if they no longer want to wait in line.
///
/// Since the Queue now can hold multiple instances of the same person, this will remove the _first_
/// instance of the person. For example, say you are in the third, sixth, and eighth positions in
/// the queue. If you elect to remove yourself from the queue, you will still be in the sixth
/// and eighth positions in the queue, but you will no longer be in the third position.
/// TODO: add a method for removing _all_ instances of oneself in the queue
///
/// This function will write to the backup file that persists the state of the queue. If that write
/// fails, then `Err(e)` is returned, where `e` is an error object describing the error. Otherwise,
/// if the given user was able to be removed (i.e. at least one instance of them was in the queue),
/// then an `Ok(Some((u, i))` is returned, where `u` is the user removed and `i` is the number
/// position `u` was in _before_ they were removed from the queue (0 is the first position in the
/// queue). In all other cases, `Ok(None)` is returned.
pub fn remove_user(&mut self, user: UserID) -> (UserID, RemoveResult) {
match self.queue.iter().position(|u| *u == user) {
Some(idx) => {
// If we attempt to remove a non-existent user, Iter::position will return None, so
// *in theory* idx should refer to a valid index in the queue.
let removed = self
.queue
.remove(idx)
.expect("Attempted to remove a non-existent user");
match self.write_state() {
Ok(()) => (removed, UserSuccessfullyRemoved(idx)),
Err(e) => (removed, UserUnsuccessfullyRemoved(e)),
}
}
None => (user, NonExistentUser),
}
}
/// Given a Slack ID, return the real name-maybe username pair associated with that ID, if there is one.
fn get_username_by_id(&self, id: &UserID) -> Option<&(Option<String>, Option<String>)> {
self.uid_username_mapping.get(id)
}
/// Given the `body` of what `user` posted when mentioning Queue, determine what to say back.
///
/// Currently, this function takes a **mutable reference** to `self` and has the side-effect of
/// mutating `self`. In the future, it might return another value indicating how to mutate queue
/// after invocation of this method.
pub fn determine_response(&mut self, user: UserID, body: &str) -> String {
/*
Commands are only activated when the body has an @Queue. But we need to strip the command
of its @Queue mention before seeing what the user wants Queue to do.
*/
// TODO: handle cases where the mention is not at the beginning of the string
let lowercase_queue_id = QUEUE_UID.to_lowercase();
let body = body.to_lowercase();
let body = body.trim_start_matches(lowercase_queue_id.as_str());
match body.trim() {
"add" => self.add(user),
// "cancel" => self.cancel(user),
"done" => self.done(user),
"show" => format!("{}", self),
"help" => String::from(USAGE),
s => format!("Unrecognized command {}. Try `@Queue help`.", s),
}
}
}
impl slack::EventHandler for Queue<'_> {
fn on_event(&mut self, cli: &RtmClient, event: slack::Event) {
if cfg!(debug_assertions) {
println!("Got event: {:?}", event);
}
match event {
slack::Event::Message(message) => {
if let slack::Message::Standard(ms) = *message {
// The channel the message was posted in
let chan = ms.channel.expect("Channel does not exist");
/*
Unfortunately, this Slack bot uses the (deprecated) Slack "real time messaging" (RTM)
API because the slack crate only works with that API (not that I need the slack crate
but the only other option is using Rust's advanced, concurrency-first HTTP libraries
to build my own web API for this Slack bot, and I found working with the slack crate
easier, even if it means using a deprecated API.
I can see why Slack is encouraging you to use the new API ("granular scopes"). As the
name suggests, that API allows you to be a lot more granular with the permissions you
give the bot. I suspect that API allows you to only run the bot in certain channels,
unlike the RTM API where the bot receives any event that happens in any channel where it
has been "invited" to. So, to simulate some granularity, I am adding a check to see if
the bot should respond, or if t was invoked in a channel it should not be in (see the
CHANNEL variable).
*/
if Some(&chan) == self.chan_name_id_mapping.get(CHANNEL) {
// The content of the message
let text = ms.text.unwrap_or_default();
if is_app_mention(&*text) {
// Who posted the message
let user = ms.user.expect("User does not exist");
// What to send back to Slack
let response = self.determine_response(UserID(user), text.as_str());
// Send 'em back!
let _ = cli.sender().send_message(&*chan, &*response);
}
} else {
let response = match self.chan_name_id_mapping.get(CHANNEL) {
Some(chan_id) => {
format!("Try invoking that same command in <#{}>!", chan_id)
}
None => format!("Try invoking that same command in #{}!", CHANNEL),
};
let _ = cli.sender().send_message(&*chan, &*response);
}
}
}
_ => (),
};
}
fn on_close(&mut self, _cli: &RtmClient) {
println!("on_close");
}
fn on_connect(&mut self, cli: &RtmClient) {
println!("{}", INSPIRATIONAL_QUOTE);
match cli.start_response().channels.as_ref() {
Some(channels) => {
for channel in channels {
if let (Some(name), Some(id)) = (channel.name.as_ref(), channel.id.as_ref()) {
assert_eq!(
self.chan_name_id_mapping.insert(name.clone(), id.clone()),
None
);
}
}
}
None => panic!("Could not find any channels in this Slack workspace."),
};
let chan_id = self
.chan_name_id_mapping
.get(CHANNEL)
.expect(&*format!("Channel {} not found", CHANNEL));
let _ = cli.sender().send_message(chan_id, INSPIRATIONAL_QUOTE);
}
}
impl fmt::Display for Queue<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.len() == 0 {
f.write_str("Nobody is in line!")
} else {
write!(
f,
"Here are the people currently in line:\n{}",
self.queue
.iter()
.enumerate()
.map(|(idx, u)| {
let (maybe_real_name, maybe_username) = self.get_username_by_id(u).expect(
format!("For some reason user {} did not have an ID", u).as_str(),
);
let u = &u.to_string();
let real_name = maybe_real_name.as_ref().unwrap_or(u);
match maybe_username {
Some(uname) if !uname.is_empty() => {
format!("{}. {} ({})\n", idx, real_name, uname)
}
_ => format!("{}. {}\n", idx, real_name),
}
})
.fold(String::default(), |acc, line| acc.to_owned() + &line)
)
}
}
}
impl Deref for Queue<'_> {
type Target = VecDeque<UserID>;
fn deref(&self) -> &Self::Target {
&self.queue
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::*;
#[test]
fn create_queue() -> Result<(), String> {
let hash_map = HashMap::new();
let test_file = match File::create("queue_state_2.txt") {
Ok(f) => f,
Err(e) => return Err(format!("{}", e)),
};
let queue_a = Queue::new(&hash_map);
let queue_b = Queue {
queue: VecDeque::new(),
uid_username_mapping: &hash_map,
chan_name_id_mapping: BTreeMap::new(),
db_conn: BufWriter::new(test_file),
};
if !queue_a.is_empty() {
return Err(String::from("Queue::new does not return an empty queue"));
}
if queue_a.queue != queue_b.queue {
return Err(format!(
"queue_a.queue ({:?}) != queue_b.queue ({:?})",
queue_a.queue, queue_b.queue
));
}
if queue_a.uid_username_mapping == queue_b.uid_username_mapping {
Ok(())
} else {
Err(format!(
"queue_a.uid_username_mapping ({:?}) != queue_b.uid_username_mapping ({:?})",
queue_a.uid_username_mapping, queue_b.uid_username_mapping
))
}
}
fn add_users_helper(queue: &mut Queue, user: UserID) {
let (new_user, result) = queue.add_user(user.clone());
assert_eq!(
new_user, user,
"Queue::add_user does not return just-added user"
);
match result {
UserSuccessfullyAdded => (), // This is the intended behavior
res => panic!(
"{} was not added to the queue properly: {:?}",
new_user, res
),
}
}
#[test]
fn add_users() {
let hash_map = HashMap::new();
let mut queue = Queue::new(&hash_map);
add_users_helper(&mut queue, UserID::new("UA8RXUPSP"));
add_users_helper(&mut queue, UserID::new("UNB2LMZRP"));
add_users_helper(&mut queue, UserID::new("UN480W9ND"));
assert_eq!(
queue.queue,
[
UserID::new("UA8RXUPSP"),
UserID::new("UNB2LMZRP"),
UserID::new("UN480W9ND"),
]
);
}
/// This function tests Rule 1 of adding users to the queue: a user can only be added to the queue
/// if the last person in the queue is not themselves. This gives other people a chance to wait
/// in line.
#[test]
fn add_duplicate_users_to_nonempty_queue() {
let hash_map = HashMap::new();
let mut queue = Queue::new(&hash_map);
let test_user = UserID::new("UA8RXUPSP");
add_users_helper(&mut queue, test_user.clone());
add_users_helper(&mut queue, UserID::new("UNB2LMZRP"));
// Rule 1 states that a user can be added to the queue iff the person that would be in front
// of them is not themselves, so this addition should work
add_users_helper(&mut queue, test_user.clone());
// However, they are now the last person in the queue so if they try to add themselves again
// it shouldn't work
assert!(!queue.can_add(&test_user));
let (new_user, result) = queue.add_user(test_user);
match result {
UserNotAdded => (), // This is the intended behavior
res => panic!("{} was erroneously added to the queue: {:?}", new_user, res),
}
assert_eq!(
queue.queue,
[
UserID::new("UA8RXUPSP"),
UserID::new("UNB2LMZRP"),
UserID::new("UA8RXUPSP"),
]
);
}
/// This function tests Rule 2 of adding users to the queue. A user is allowed to add themselves
/// up to three times to the queue if it is initially empty.
#[test]
fn add_duplicate_users_to_empty_queue() {
let hash_map = HashMap::new();
let mut queue = Queue::new(&hash_map);
// This should work, because the queue is empty so UA8RXUPSP can add themselves up to 3 times
for _ in 0..3 {
let test_user = UserID::new("UA8RXUPSP");
assert!(queue.can_add(&test_user));
add_users_helper(&mut queue, test_user);
}
// But this should fail, because now it's time to let someone else have a turn
let test_user = UserID::new("UA8RXUPSP");
assert!(!queue.can_add(&test_user));
let (new_user, result) = queue.add_user(test_user);
match result {
UserNotAdded => (), // This is the intended behavior
res => panic!(
"{} was added to an empty queue for the fourth time: {:?}",
new_user, res
),
}
}
#[test]
fn remove_front_users() {
let hash_map = HashMap::new();
let mut queue = Queue::new(&hash_map);
add_users_helper(&mut queue, UserID::new("UA8RXUPSP"));
add_users_helper(&mut queue, UserID::new("UNB2LMZRP"));
add_users_helper(&mut queue, UserID::new("UN480W9ND"));
let test_user = UserID::new("UA8RXUPSP");
match queue.remove_user(UserID::new("UA8RXUPSP")) {
(u, UserSuccessfullyRemoved(0)) if u == test_user => (), // This is the expected behavior
res => panic!("Queue::remove_user returned unexpected result: {:?}", res),
}
assert_eq!(
queue.queue,
[UserID::new("UNB2LMZRP"), UserID::new("UN480W9ND"),]
);
// Empty the queue
if let (_, UserUnsuccessfullyRemoved(ioe)) = queue.remove_user(UserID::new("UNB2LMZRP")) {
panic!("{}", ioe);
}
if let (_, UserUnsuccessfullyRemoved(ioe)) = queue.remove_user(UserID::new("UN480W9ND")) {
panic!("{}", ioe);
}
assert!(queue.queue.is_empty());
}
#[test]
fn peek_front_users() {
let hash_map = HashMap::new();
let mut queue = Queue::new(&hash_map);
add_users_helper(&mut queue, UserID::new("UA8RXUPSP"));
add_users_helper(&mut queue, UserID::new("UNB2LMZRP"));
add_users_helper(&mut queue, UserID::new("UN480W9ND"));
assert_eq!(
queue.peek_first_user_in_line(),
Some(&UserID::new("UA8RXUPSP")),
"Queue::peek_first_user_in_line does not return a reference to the front user"
);
// Does not mutate the queue itself
assert_eq!(
queue.queue,
[
UserID::new("UA8RXUPSP"),
UserID::new("UNB2LMZRP"),
UserID::new("UN480W9ND"),
],
"Queue::peek_first_user_in_line mutates the queue when it is not supposed to"
);
}
#[test]
fn remove_arbitrary_users() {
let hash_map = HashMap::new();
let mut queue = Queue::new(&hash_map);
add_users_helper(&mut queue, UserID::new("UA8RXUPSP"));
add_users_helper(&mut queue, UserID::new("UNB2LMZRP"));
add_users_helper(&mut queue, UserID::new("UN480W9ND"));
let test_user = UserID::new("UNB2LMZRP");
match queue.remove_user(UserID::new("UNB2LMZRP")) {
(u, UserSuccessfullyRemoved(1)) if u == test_user => (), // This is the expected behavior
res => panic!(
"Queue::remove_user returned an unexpected result: {:?}",
res
),
}
assert_eq!(
queue.queue,
[UserID::new("UA8RXUPSP"), UserID::new("UN480W9ND"),]
);
}
#[test]
fn remove_non_existent_users() {
let hash_map = HashMap::new();
let mut queue = Queue::new(&hash_map);
match queue.remove_user(UserID::new("UNB2LMZRP")) {
(_, NonExistentUser) => (), // This is the behavior that is expected
res => panic!(
"Queue::remove_user erroneously returns a user when \
trying to remove a user from an empty queue. The result returned was: {:?}",
res
),
}
add_users_helper(&mut queue, UserID::new("UNB2LMZRP"));
add_users_helper(&mut queue, UserID::new("UN480W9ND"));
match queue.remove_user(UserID::new("UA8RXUPSP")) {
(_, NonExistentUser) => (), // This is the behavior that is expected
res => panic!(
"Queue::remove_user erroneously removes a user not \
in the queue. The user returned was: {:?}",
res
),
}
}
}
|
use codec::Encode;
use core::marker::PhantomData;
use frame_support::Parameter;
use sp_runtime::{
traits::{AtLeast32Bit, Scale},
generic::{Header as SHeader},
traits::{BlakeTwo256, IdentifyAccount, Verify},
MultiSignature, OpaqueExtrinsic,
};
use sub_runtime::ipse::{Order, Miner};
use substrate_subxt::{balances::{Balances, AccountData, BalancesEventsDecoder}, module, PairSigner, extrinsic::{DefaultExtra}, Runtime, Client, system::{System, SystemEventsDecoder}, Call, Store};
use sp_core::{sr25519::Pair, Pair as PairT};
use frame_support::sp_runtime::SaturatedConversion;
use crate::error::MinerError;
use crate::settings::Settings;
use sp_core::crypto::{Ss58Codec, AccountId32};
pub type AccountId = <IpseRuntime as System>::AccountId;
pub type Balance = <IpseRuntime as Balances>::Balance;
// define module, Store, Call , Event macro
// define submit module
#[module]
pub trait Ipse: System + Balances {}
// define Store
#[derive(Encode, Store)]
pub struct MinersStore<T: Ipse> {
#[store(returns = Option < Miner < AccountId, Balance >>)]
pub key: AccountId,
pub _runtime: PhantomData<T>,
}
#[derive(Encode, Store)]
pub struct OrdersStore<T: Ipse> {
#[store(returns = Vec < Order < AccountId, Balance >>)]
pub _runtime: PhantomData<T>,
}
// define call
#[derive(Encode, Call)]
pub struct RegisterMinerCall<T: Ipse> {
pub _runtime: PhantomData<T>,
pub nickname: Vec<u8>,
pub region: Vec<u8>,
pub url: Vec<u8>,
pub public_key: Vec<u8>,
pub income_address: AccountId,
pub capacity: u64,
pub unit_price: Balance,
}
#[derive(Encode, Call)]
pub struct ConfirmOrderCall<T: Ipse> {
pub _runtime: PhantomData<T>,
pub order_id: u64,
pub url: Vec<u8>,
}
#[derive(Encode, Call)]
pub struct DeleteOrderCall<T: Ipse> {
pub _runtime: PhantomData<T>,
pub order_id: u64,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct IpseRuntime;
impl Ipse for IpseRuntime {}
impl Runtime for IpseRuntime {
type Signature = MultiSignature;
type Extra = DefaultExtra<Self>;
}
pub trait Timestamp: System {
type Moment: Parameter
+ Default
+ AtLeast32Bit
+ Scale<Self::BlockNumber, Output=Self::Moment>
+ Copy;
}
impl System for IpseRuntime {
type Index = u32;
type BlockNumber = u32;
type Hash = sp_core::H256;
type Hashing = BlakeTwo256;
type AccountId = <<MultiSignature as Verify>::Signer as IdentifyAccount>::AccountId;
type Address = pallet_indices::address::Address<Self::AccountId, u32>;
type Header = SHeader<Self::BlockNumber, BlakeTwo256>;
type Extrinsic = OpaqueExtrinsic;
type AccountData = AccountData<<Self as Balances>::Balance>;
}
impl Balances for IpseRuntime {
type Balance = u128;
}
impl Timestamp for IpseRuntime {
type Moment = u128;
}
pub async fn register_miner(settings: &Settings, pair: Pair, sub_client: Client<IpseRuntime>) -> Result<sp_core::H256, MinerError> {
// https://stackoverflow.com/questions/56081117/how-do-you-convert-between-substrate-specific-types-and-rust-primitive-types
let signer = PairSigner::new(pair);
let res = sub_client.register_miner(
&signer,
settings.miner.nickname.as_bytes().to_vec(),
settings.miner.region.as_bytes().to_vec(),
settings.miner.url.as_bytes().to_vec(),
settings.miner.public_key.as_bytes().to_vec(),
AccountId32::from_string(settings.miner.income_address.as_str())?,
settings.miner.capacity as u64,
// (settings.miner.unit_price * (10 as u64).pow(14)).saturated_into::<Balance>(),
settings.miner.unit_price .saturated_into::<Balance>(),
).await?;
Ok(res)
}
pub async fn confirm_order(pair: Pair, sub_client: Client<IpseRuntime>, order_id: u64, url: String) -> Result<sp_core::H256, MinerError> {
let signer = PairSigner::new(pair);
let res = sub_client.confirm_order(
&signer,
order_id,
url.into_bytes(),
).await?;
Ok(res)
}
pub async fn delete_order(pair: Pair, sub_client: Client<IpseRuntime>, order_id: u64) -> Result<sp_core::H256, MinerError> {
let signer = PairSigner::new(pair);
let res = sub_client.delete_order(
&signer,
order_id,
).await?;
Ok(res)
} |
//! Mocks for the tokens module.
#![cfg(test)]
use frame_support::{impl_outer_event, impl_outer_origin, parameter_types};
use frame_system as system;
use sp_core::H256;
use sp_runtime::{testing::Header, traits::IdentityLookup, Perbill};
use sp_std::cell::RefCell;
use std::collections::HashMap;
use super::*;
impl_outer_origin! {
pub enum Origin for Runtime {}
}
mod tokens {
pub use crate::Event;
}
impl_outer_event! {
pub enum TestEvent for Runtime {
frame_system<T>,
tokens<T>,
}
}
// Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Runtime;
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
type AccountId = u128;
impl frame_system::Trait for Runtime {
type Origin = Origin;
type Call = ();
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = ::sp_runtime::traits::BlakeTwo256;
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = TestEvent;
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
type ModuleToIndex = ();
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumExtrinsicWeight = ();
type BaseCallFilter = ();
type SystemWeightInfo = ();
}
pub type System = system::Module<Runtime>;
type CurrencyId = u32;
pub type Balance = u64;
thread_local! {
pub static ACCUMULATED_RECEIVED: RefCell<HashMap<(AccountId, CurrencyId), Balance>> = RefCell::new(HashMap::new());
}
pub struct MockOnReceived;
impl OnReceived<AccountId, CurrencyId, Balance> for MockOnReceived {
fn on_received(who: &AccountId, currency_id: CurrencyId, amount: Balance) {
ACCUMULATED_RECEIVED.with(|v| {
let mut old_map = v.borrow().clone();
if let Some(before) = old_map.get_mut(&(*who, currency_id)) {
*before += amount;
} else {
old_map.insert((*who, currency_id), amount);
};
*v.borrow_mut() = old_map;
});
}
}
impl Trait for Runtime {
type Event = TestEvent;
type Balance = Balance;
type Amount = i64;
type CurrencyId = CurrencyId;
type OnReceived = MockOnReceived;
type WeightInfo = ();
}
pub type Tokens = Module<Runtime>;
pub const TEST_TOKEN_ID: CurrencyId = 1;
pub const ALICE: AccountId = 1;
pub const BOB: AccountId = 2;
pub const ID_1: LockIdentifier = *b"1 ";
pub const ID_2: LockIdentifier = *b"2 ";
pub struct ExtBuilder {
endowed_accounts: Vec<(AccountId, CurrencyId, Balance)>,
}
impl Default for ExtBuilder {
fn default() -> Self {
Self {
endowed_accounts: vec![],
}
}
}
impl ExtBuilder {
pub fn balances(mut self, endowed_accounts: Vec<(AccountId, CurrencyId, Balance)>) -> Self {
self.endowed_accounts = endowed_accounts;
self
}
pub fn one_hundred_for_alice_n_bob(self) -> Self {
self.balances(vec![(ALICE, TEST_TOKEN_ID, 100), (BOB, TEST_TOKEN_ID, 100)])
}
pub fn build(self) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default()
.build_storage::<Runtime>()
.unwrap();
GenesisConfig::<Runtime> {
endowed_accounts: self.endowed_accounts,
}
.assimilate_storage(&mut t)
.unwrap();
t.into()
}
}
|
// pretty-expanded FIXME #23616
// Copyright 2013 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.
#![allow(unnecessary_allocation)]
#![feature(box_syntax)]
// Tests for a previous bug that occurred due to an interaction
// between struct field initialization and the auto-coercion
// from a vector to a slice. The drop glue was being invoked on
// the temporary slice with a wrong type, triggering an LLVM assert.
struct Thing1<'a> {
baz: &'a [Box<isize>],
bar: Box<u64>,
}
struct Thing2<'a> {
baz: &'a [Box<isize>],
bar: u64,
}
pub fn main() {
let _t1_fixed = Thing1 {
baz: &[],
bar: box 32,
};
Thing1 {
baz: &Vec::new(),
bar: box 32,
};
let _t2_fixed = Thing2 {
baz: &[],
bar: 32,
};
Thing2 {
baz: &Vec::new(),
bar: 32,
};
}
|
//! An async parser for `multipart/form-data` content-type in Rust.
//!
//! It accepts a [`Stream`](https://docs.rs/futures/0.3.5/futures/stream/trait.Stream.html) of [`Bytes`](https://docs.rs/bytes/0.5.4/bytes/struct.Bytes.html) as
//! a source, so that It can be plugged into any async Rust environment e.g. any async server.
//!
//! # Examples
//!
//! ```no_run
//! use bytes::Bytes;
//! use futures::stream::Stream;
//! // Import multer types.
//! use multer::Multipart;
//! use std::convert::Infallible;
//! use futures::stream::once;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Generate a byte stream and the boundary from somewhere e.g. server request body.
//! let (stream, boundary) = get_byte_stream_from_somewhere().await;
//!
//! // Create a `Multipart` instance from that byte stream and the boundary.
//! let mut multipart = Multipart::new(stream, boundary);
//!
//! // Iterate over the fields, use `next_field()` to get the next field.
//! while let Some(mut field) = multipart.next_field().await? {
//! // Get field name.
//! let name = field.name();
//! // Get the field's filename if provided in "Content-Disposition" header.
//! let file_name = field.file_name();
//!
//! println!("Name: {:?}, File Name: {:?}", name, file_name);
//!
//! // Process the field data chunks e.g. store them in a file.
//! while let Some(chunk) = field.chunk().await? {
//! // Do something with field chunk.
//! println!("Chunk: {:?}", chunk);
//! }
//! }
//!
//! Ok(())
//! }
//!
//! // Generate a byte stream and the boundary from somewhere e.g. server request body.
//! async fn get_byte_stream_from_somewhere() -> (impl Stream<Item = Result<Bytes, Infallible>>, &'static str) {
//! let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
//! let stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
//!
//! (stream, "X-BOUNDARY")
//! }
//! ```
//!
//! ## Prevent Denial of Service (DoS) Attack
//!
//! This crate also provides some APIs to prevent potential DoS attacks with fine grained control. It's recommended to add some constraints
//! on field (specially text field) size to avoid potential DoS attacks from attackers running the server out of memory.
//!
//! An example:
//!
//! ```
//! use multer::{Multipart, Constraints, SizeLimit};
//! # use bytes::Bytes;
//! # use std::convert::Infallible;
//! # use futures::stream::once;
//!
//! # async fn run() {
//! # let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
//! # let some_stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
//! // Create some constraints to be applied to the fields to prevent DoS attack.
//! let constraints = Constraints::new()
//! // We only accept `my_text_field` and `my_file_field` fields,
//! // For any unknown field, we will throw an error.
//! .allowed_fields(vec!["my_text_field", "my_file_field"])
//! .size_limit(
//! SizeLimit::new()
//! // Set 15mb as size limit for the whole stream body.
//! .whole_stream(15 * 1024 * 1024)
//! // Set 10mb as size limit for all fields.
//! .per_field(10 * 1024 * 1024)
//! // Set 30kb as size limit for our text field only.
//! .for_field("my_text_field", 30 * 1024),
//! );
//!
//! // Create a `Multipart` instance from a stream and the constraints.
//! let mut multipart = Multipart::new_with_constraints(some_stream, "X-BOUNDARY", constraints);
//!
//! while let Some(field) = multipart.next_field().await.unwrap() {
//! let content = field.text().await.unwrap();
//! assert_eq!(content, "abcd");
//! }
//! # }
//! # tokio::runtime::Runtime::new().unwrap().block_on(run());
//! ```
//!
//! Please refer [`Constraints`](./struct.Constraints.html) for more info.
//!
//! ## Usage with [hyper.rs](https://hyper.rs/) server
//!
//! An [example](https://github.com/rousan/multer-rs/blob/master/examples/hyper_server_example.rs) showing usage with [hyper.rs](https://hyper.rs/).
//!
//! For more examples, please visit [examples](https://github.com/rousan/multer-rs/tree/master/examples).
pub use constraints::Constraints;
pub use error::Error;
pub use field::Field;
pub use multipart::Multipart;
pub use size_limit::SizeLimit;
mod buffer;
mod constants;
mod constraints;
mod content_disposition;
mod error;
mod field;
mod helpers;
mod multipart;
mod size_limit;
mod state;
/// A Result type often returned from methods that can have `multer` errors.
pub type Result<T> = std::result::Result<T, Error>;
/// Parses the `Content-Type` header to extract the boundary value.
///
/// # Examples
///
/// ```
/// # fn run(){
/// let content_type = "multipart/form-data; boundary=ABCDEFG";
///
/// assert_eq!(multer::parse_boundary(content_type), Ok("ABCDEFG".to_owned()));
/// # }
/// # run();
/// ```
pub fn parse_boundary<T: AsRef<str>>(content_type: T) -> crate::Result<String> {
let m = content_type
.as_ref()
.parse::<mime::Mime>()
.map_err(|err| crate::Error::DecodeContentType(err.into()))?;
if !(m.type_() == mime::MULTIPART && m.subtype() == mime::FORM_DATA) {
return Err(crate::Error::NoMultipart);
}
m.get_param(mime::BOUNDARY)
.map(|name| name.as_str().to_owned())
.ok_or_else(|| crate::Error::NoBoundary)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_boundary() {
let content_type = "multipart/form-data; boundary=ABCDEFG";
assert_eq!(parse_boundary(content_type), Ok("ABCDEFG".to_owned()));
let content_type = "multipart/form-data; boundary=------ABCDEFG";
assert_eq!(parse_boundary(content_type), Ok("------ABCDEFG".to_owned()));
let content_type = "boundary=------ABCDEFG";
assert!(parse_boundary(content_type).is_err());
let content_type = "text/plain";
assert!(parse_boundary(content_type).is_err());
let content_type = "text/plain; boundary=------ABCDEFG";
assert!(parse_boundary(content_type).is_err());
}
}
|
use std::fs;
use std::time::Instant;
use crate::Cardinal::{EAST, NORTH, SOUTH, WEST};
use std::ops::Neg;
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
#[repr(i32)]
enum Cardinal {
NORTH,
EAST,
SOUTH,
WEST,
}
fn move_stuff(mut x: i32, mut y: i32, dir: Cardinal, step: i32) -> (i32, i32) {
match dir {
Cardinal::NORTH => {
y += step;
}
Cardinal::EAST => {
x += step;
}
Cardinal::SOUTH => {
y -= step;
}
Cardinal::WEST => {
x -= step;
}
}
(x, y)
}
fn convert_to_enum(c: i32) -> Cardinal {
match c {
0 => NORTH,
1 => EAST,
2 => SOUTH,
3 => WEST,
_ => panic!("ERROR")
}
}
fn rotate(rot: Cardinal, number: i32) -> Cardinal {
let clock = ((((number / 90) + (rot as i32)) % 4) + 4) % 4;
if clock != 1 && clock != 0 && clock != 2 && clock != 3 {
panic!("EROOR")
}
convert_to_enum(clock)
}
fn translate(x: i32, y: i32, number: i32) -> (i32, i32) {
let clock = (((number / 90) % 4) + 4) % 4;
match clock {
0 => (x, y),
1 => (y, -x),
2 => (-x, -y),
3 => (-y, x),
_ => unimplemented!("NOT POSSIBLE")
}
}
fn part1(mut directions: Vec<String>) -> usize {
let mut current_rotation = EAST;
let mut x = 0;
let mut y = 0;
for direction in directions {
let mut it = direction.chars();
let command = it.next().unwrap();
let number = it.collect::<String>().parse::<i32>().unwrap();
match command {
'N' => {
let res = move_stuff(x, y, NORTH, number);
x = res.0;
y = res.1;
}
'E' => {
let res = move_stuff(x, y, EAST, number);
x = res.0;
y = res.1;
}
'S' => {
let res = move_stuff(x, y, SOUTH, number);
x = res.0;
y = res.1;
}
'W' => {
let res = move_stuff(x, y, WEST, number);
x = res.0;
y = res.1;
}
'F' => {
let res = move_stuff(x, y, current_rotation, number);
x = res.0;
y = res.1;
}
'R' => { current_rotation = rotate(current_rotation, number) }
'L' => { current_rotation = rotate(current_rotation, number.neg()) }
_ => { unimplemented!("not a pattern") }
}
}
(x.abs() + y.abs()) as usize
}
fn part2(directions: Vec<String>) -> usize {
let mut waypoint_x = 10;
let mut waypoint_y = 1;
let mut ship_x: i64 = 0;
let mut ship_y: i64 = 0;
for direction in directions {
let mut it = direction.chars();
let command = it.next().unwrap();
let number = it.collect::<String>().parse::<i32>().unwrap();
match command {
'N' => {
let res = move_stuff(waypoint_x, waypoint_y, NORTH, number);
waypoint_x = res.0;
waypoint_y = res.1;
}
'E' => {
let res = move_stuff(waypoint_x, waypoint_y, EAST, number);
waypoint_x = res.0;
waypoint_y = res.1;
}
'S' => {
let res = move_stuff(waypoint_x, waypoint_y, SOUTH, number);
waypoint_x = res.0;
waypoint_y = res.1;
}
'W' => {
let res = move_stuff(waypoint_x, waypoint_y, WEST, number);
waypoint_x = res.0;
waypoint_y = res.1;
}
'F' => {
ship_x+=waypoint_x as i64 *number as i64;
ship_y+=waypoint_y as i64 *number as i64;
}
'R' => {
let res = translate(waypoint_x, waypoint_y, number);
waypoint_x = res.0;
waypoint_y = res.1;
}
'L' => {
let res = translate(waypoint_x, waypoint_y, number.neg());
waypoint_x = res.0;
waypoint_y = res.1;
}
_ => { unimplemented!("not a pattern") }
}
}
(ship_x.abs() + ship_y.abs()) as usize
}
fn main() {
let input = fs::read_to_string("input/input.txt")
.expect("Something went wrong reading the file");
let lines = input.lines();
let mut adapters: Vec<String> = vec![];
for line in lines {
adapters.push(line.parse::<String>().expect("Ouf that's not a string !"))
}
println!("Running part1");
let now = Instant::now();
println!("Found {}", part1(adapters.clone()));
println!("Took {}us", now.elapsed().as_micros());
println!("Running part2");
let now = Instant::now();
println!("Found {}", part2(adapters.clone()));
println!("Took {}us", now.elapsed().as_micros());
} |
#![allow(unused)]
use rox::Rox;
use color_eyre::eyre::Result;
fn main() -> Result<()>{
color_eyre::install()?;
if let Some(config_file_path) = std::env::args().nth(1) {
let rox = Rox::interpret(&config_file_path)?;
println!("**Printing Name Value pairs**");
for item in rox.switches {
println!("{:?}", item);
}
println!("**Printing invalid**");
for comment in rox.invalid {
println!("{}", comment);
}
}
else {
eprintln!("Usage: `rox {{rox file}}`");
}
Ok(())
}
|
// 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 common_hashtable::HashtableLike;
#[inline]
pub fn estimated_key_size<Table: HashtableLike>(table: &Table) -> usize {
table.unsize_key_size().unwrap_or_default()
}
|
#![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 ILockApplicationHost(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILockApplicationHost {
type Vtable = ILockApplicationHost_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x38ee31ad_d94f_4e7c_81fa_4f4436506281);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILockApplicationHost_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILockApplicationHostStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILockApplicationHostStatics {
type Vtable = ILockApplicationHostStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf48fab8e_23d7_4e63_96a1_666ff52d3b2c);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILockApplicationHostStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILockScreenBadge(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILockScreenBadge {
type Vtable = ILockScreenBadge_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe95105d9_2bff_4db0_9b4f_3824778b9c9a);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILockScreenBadge_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 = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] 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,
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) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILockScreenInfo(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILockScreenInfo {
type Vtable = ILockScreenInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf59aa65c_9711_4dc9_a630_95b6cb8cdad0);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILockScreenInfo_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, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[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, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[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, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILockScreenUnlockingDeferral(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILockScreenUnlockingDeferral {
type Vtable = ILockScreenUnlockingDeferral_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7e7d1ad6_5203_43e7_9bd6_7c3947d1e3fe);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILockScreenUnlockingDeferral_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILockScreenUnlockingEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILockScreenUnlockingEventArgs {
type Vtable = ILockScreenUnlockingEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x44e6c007_75fb_4abb_9f8b_824748900c71);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILockScreenUnlockingEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::DateTime) -> ::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 LockApplicationHost(pub ::windows::core::IInspectable);
impl LockApplicationHost {
pub fn RequestUnlock(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation")]
pub fn Unlocking<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<LockApplicationHost, LockScreenUnlockingEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveUnlocking<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
pub fn GetForCurrentView() -> ::windows::core::Result<LockApplicationHost> {
Self::ILockApplicationHostStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<LockApplicationHost>(result__)
})
}
pub fn ILockApplicationHostStatics<R, F: FnOnce(&ILockApplicationHostStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<LockApplicationHost, ILockApplicationHostStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for LockApplicationHost {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.LockScreen.LockApplicationHost;{38ee31ad-d94f-4e7c-81fa-4f4436506281})");
}
unsafe impl ::windows::core::Interface for LockApplicationHost {
type Vtable = ILockApplicationHost_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x38ee31ad_d94f_4e7c_81fa_4f4436506281);
}
impl ::windows::core::RuntimeName for LockApplicationHost {
const NAME: &'static str = "Windows.ApplicationModel.LockScreen.LockApplicationHost";
}
impl ::core::convert::From<LockApplicationHost> for ::windows::core::IUnknown {
fn from(value: LockApplicationHost) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&LockApplicationHost> for ::windows::core::IUnknown {
fn from(value: &LockApplicationHost) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for LockApplicationHost {
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 LockApplicationHost {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<LockApplicationHost> for ::windows::core::IInspectable {
fn from(value: LockApplicationHost) -> Self {
value.0
}
}
impl ::core::convert::From<&LockApplicationHost> for ::windows::core::IInspectable {
fn from(value: &LockApplicationHost) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for LockApplicationHost {
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 LockApplicationHost {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for LockApplicationHost {}
unsafe impl ::core::marker::Sync for LockApplicationHost {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct LockScreenBadge(pub ::windows::core::IInspectable);
impl LockScreenBadge {
#[cfg(feature = "Storage_Streams")]
pub fn Logo(&self) -> ::windows::core::Result<super::super::Storage::Streams::IRandomAccessStream> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IRandomAccessStream>(result__)
}
}
#[cfg(feature = "Storage_Streams")]
pub fn Glyph(&self) -> ::windows::core::Result<super::super::Storage::Streams::IRandomAccessStream> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IRandomAccessStream>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Number(&self) -> ::windows::core::Result<super::super::Foundation::IReference<u32>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<u32>>(result__)
}
}
pub fn AutomationName(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn LaunchApp(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for LockScreenBadge {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.LockScreen.LockScreenBadge;{e95105d9-2bff-4db0-9b4f-3824778b9c9a})");
}
unsafe impl ::windows::core::Interface for LockScreenBadge {
type Vtable = ILockScreenBadge_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe95105d9_2bff_4db0_9b4f_3824778b9c9a);
}
impl ::windows::core::RuntimeName for LockScreenBadge {
const NAME: &'static str = "Windows.ApplicationModel.LockScreen.LockScreenBadge";
}
impl ::core::convert::From<LockScreenBadge> for ::windows::core::IUnknown {
fn from(value: LockScreenBadge) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&LockScreenBadge> for ::windows::core::IUnknown {
fn from(value: &LockScreenBadge) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for LockScreenBadge {
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 LockScreenBadge {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<LockScreenBadge> for ::windows::core::IInspectable {
fn from(value: LockScreenBadge) -> Self {
value.0
}
}
impl ::core::convert::From<&LockScreenBadge> for ::windows::core::IInspectable {
fn from(value: &LockScreenBadge) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for LockScreenBadge {
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 LockScreenBadge {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for LockScreenBadge {}
unsafe impl ::core::marker::Sync for LockScreenBadge {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct LockScreenInfo(pub ::windows::core::IInspectable);
impl LockScreenInfo {
#[cfg(feature = "Foundation")]
pub fn LockScreenImageChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<LockScreenInfo, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveLockScreenImageChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Storage_Streams")]
pub fn LockScreenImage(&self) -> ::windows::core::Result<super::super::Storage::Streams::IRandomAccessStream> {
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::Storage::Streams::IRandomAccessStream>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn BadgesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<LockScreenInfo, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveBadgesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation_Collections")]
pub fn Badges(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<LockScreenBadge>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<LockScreenBadge>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn DetailTextChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<LockScreenInfo, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveDetailTextChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation_Collections")]
pub fn DetailText(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn AlarmIconChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<LockScreenInfo, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveAlarmIconChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Storage_Streams")]
pub fn AlarmIcon(&self) -> ::windows::core::Result<super::super::Storage::Streams::IRandomAccessStream> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IRandomAccessStream>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for LockScreenInfo {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.LockScreen.LockScreenInfo;{f59aa65c-9711-4dc9-a630-95b6cb8cdad0})");
}
unsafe impl ::windows::core::Interface for LockScreenInfo {
type Vtable = ILockScreenInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf59aa65c_9711_4dc9_a630_95b6cb8cdad0);
}
impl ::windows::core::RuntimeName for LockScreenInfo {
const NAME: &'static str = "Windows.ApplicationModel.LockScreen.LockScreenInfo";
}
impl ::core::convert::From<LockScreenInfo> for ::windows::core::IUnknown {
fn from(value: LockScreenInfo) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&LockScreenInfo> for ::windows::core::IUnknown {
fn from(value: &LockScreenInfo) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for LockScreenInfo {
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 LockScreenInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<LockScreenInfo> for ::windows::core::IInspectable {
fn from(value: LockScreenInfo) -> Self {
value.0
}
}
impl ::core::convert::From<&LockScreenInfo> for ::windows::core::IInspectable {
fn from(value: &LockScreenInfo) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for LockScreenInfo {
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 LockScreenInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for LockScreenInfo {}
unsafe impl ::core::marker::Sync for LockScreenInfo {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct LockScreenUnlockingDeferral(pub ::windows::core::IInspectable);
impl LockScreenUnlockingDeferral {
pub fn Complete(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for LockScreenUnlockingDeferral {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.LockScreen.LockScreenUnlockingDeferral;{7e7d1ad6-5203-43e7-9bd6-7c3947d1e3fe})");
}
unsafe impl ::windows::core::Interface for LockScreenUnlockingDeferral {
type Vtable = ILockScreenUnlockingDeferral_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7e7d1ad6_5203_43e7_9bd6_7c3947d1e3fe);
}
impl ::windows::core::RuntimeName for LockScreenUnlockingDeferral {
const NAME: &'static str = "Windows.ApplicationModel.LockScreen.LockScreenUnlockingDeferral";
}
impl ::core::convert::From<LockScreenUnlockingDeferral> for ::windows::core::IUnknown {
fn from(value: LockScreenUnlockingDeferral) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&LockScreenUnlockingDeferral> for ::windows::core::IUnknown {
fn from(value: &LockScreenUnlockingDeferral) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for LockScreenUnlockingDeferral {
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 LockScreenUnlockingDeferral {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<LockScreenUnlockingDeferral> for ::windows::core::IInspectable {
fn from(value: LockScreenUnlockingDeferral) -> Self {
value.0
}
}
impl ::core::convert::From<&LockScreenUnlockingDeferral> for ::windows::core::IInspectable {
fn from(value: &LockScreenUnlockingDeferral) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for LockScreenUnlockingDeferral {
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 LockScreenUnlockingDeferral {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for LockScreenUnlockingDeferral {}
unsafe impl ::core::marker::Sync for LockScreenUnlockingDeferral {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct LockScreenUnlockingEventArgs(pub ::windows::core::IInspectable);
impl LockScreenUnlockingEventArgs {
pub fn GetDeferral(&self) -> ::windows::core::Result<LockScreenUnlockingDeferral> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<LockScreenUnlockingDeferral>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Deadline(&self) -> ::windows::core::Result<super::super::Foundation::DateTime> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::DateTime = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::DateTime>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for LockScreenUnlockingEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.LockScreen.LockScreenUnlockingEventArgs;{44e6c007-75fb-4abb-9f8b-824748900c71})");
}
unsafe impl ::windows::core::Interface for LockScreenUnlockingEventArgs {
type Vtable = ILockScreenUnlockingEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x44e6c007_75fb_4abb_9f8b_824748900c71);
}
impl ::windows::core::RuntimeName for LockScreenUnlockingEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.LockScreen.LockScreenUnlockingEventArgs";
}
impl ::core::convert::From<LockScreenUnlockingEventArgs> for ::windows::core::IUnknown {
fn from(value: LockScreenUnlockingEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&LockScreenUnlockingEventArgs> for ::windows::core::IUnknown {
fn from(value: &LockScreenUnlockingEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for LockScreenUnlockingEventArgs {
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 LockScreenUnlockingEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<LockScreenUnlockingEventArgs> for ::windows::core::IInspectable {
fn from(value: LockScreenUnlockingEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&LockScreenUnlockingEventArgs> for ::windows::core::IInspectable {
fn from(value: &LockScreenUnlockingEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for LockScreenUnlockingEventArgs {
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 LockScreenUnlockingEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for LockScreenUnlockingEventArgs {}
unsafe impl ::core::marker::Sync for LockScreenUnlockingEventArgs {}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.