text
stringlengths
8
4.13M
use crate::schema::*; use diesel::{Insertable, Queryable}; use serde::Serialize; #[derive(Serialize, Queryable, Insertable)] #[table_name = "blog"] pub struct Blog { pub id: uuid::Uuid, pub title: String, pub markdown: String, pub created_time: chrono::NaiveDateTime, } impl Blog { pub fn new(title: String, markdown: String) -> Self { Blog { id: uuid::Uuid::new_v4(), title, markdown, created_time: chrono::Utc::now().naive_utc(), } } } #[derive(Serialize, Queryable)] pub struct SlimBlog { pub id: uuid::Uuid, pub title: String, pub created_time: chrono::NaiveDateTime, } impl SlimBlog { pub fn new(id: uuid::Uuid, title: String, created_time: chrono::NaiveDateTime) -> Self { SlimBlog { id, title, created_time, } } } #[derive(Serialize, Queryable)] pub struct MetaData { pub id: uuid::Uuid, pub created_time: chrono::NaiveDateTime, }
extern crate itertools; use itertools::Itertools; #[derive(Debug, PartialEq)] pub enum Error { IncompleteNumber, Overflow, } /// Convert a list of numbers to a stream of bytes encoded with variable length encoding. pub fn to_bytes(values: &[u32]) -> Vec<u8> { let mut res = vec![]; for val in values.iter() { let bin_representation = to_bin(*val); match bin_representation.len() < 8 { true => res.push(bin_to_byte(&bin_representation.chars().collect())), false => { let mut sevens = vec![]; for seven in bin_representation.chars().rev().chunks(7).into_iter() { sevens.push(seven.collect::<String>()); } for (lsb, msbs) in sevens.split_first() { for msb in msbs.iter().rev() { let msb = msb.chars().rev().collect::<String>(); let msb_str: Vec<char> = pad_byte(&msb, "1").chars().collect(); res.push(bin_to_byte(&msb_str)); } let lsb = lsb.chars().rev().collect::<String>(); res.push(bin_to_byte(&pad_byte(&lsb, "0").chars().collect())); } } } } res } /// Given a stream of bytes, extract all numbers which are encoded in there. pub fn from_bytes(bytes: &[u8]) -> Result<Vec<u32>, Error> { if bytes.iter().all(|b| *b & 128 == 128) { return Err(Error::IncompleteNumber); } if bytes.len() == 1 { return Ok(vec![*bytes.get(0).unwrap() as u32]); } let mut results = vec![]; let groups = bytes.iter() .group_by(|b| *b & 128 == 128) .into_iter().map(|(_pred, group)| group.cloned().collect()).collect::<Vec<Vec<u8>>>(); let nums_iter = groups.iter().chunks(2); for num in nums_iter.into_iter() { let num_parts = num.collect_vec(); let msbs: Vec<u8> = num_parts.get(0).unwrap().to_vec(); let number_of_lsbs = num_parts.get(1).unwrap().len(); match number_of_lsbs { 1 => { let lsb: u8 = *num_parts.get(1).unwrap().get(0).unwrap(); let calculated_num = parse_single_number(&msbs, lsb); if calculated_num > u32::max_value() as u64 { return Err(Error::Overflow); } results.push(calculated_num as u32); } _ => { let lsb: u8 = *num_parts.get(1).unwrap().get(0).unwrap(); let calculated_num = parse_single_number(&msbs, lsb); if calculated_num > u32::max_value() as u64 { return Err(Error::Overflow); } results.push(calculated_num as u32); for lsb in num_parts.get(1).unwrap().iter().skip(1) { results.push(*lsb as u32) } } } } Ok(results) } fn parse_single_number(bytes: &[u8], lsb: u8) -> u64 { let mut stream = String::new(); for byte in bytes.iter() { stream.push_str(&skip_msb(&byte_to_bin(*byte))) } let least_significant_byte = &skip_msb(&byte_to_bin(lsb)); stream.push_str(least_significant_byte); bin_to_num64(&stream.chars().collect()) as u64 } fn byte_to_bin(num: u8) -> String { let raw_repr = format!("{:b}", num); match raw_repr.len() == 8 { true => raw_repr, _ => pad_byte(&format!("{:b}", num),"0") } } fn to_bin(num: u32) -> String { format!("{:b}", num) } fn skip_msb(byte_repr: &str) -> String { byte_repr.chars().skip(1).collect() } fn pad_byte(byte_repr: &str, first: &str) -> String { let padding = String::from("0").repeat(7 - byte_repr.len()); format!("{}{}{}", first, padding, byte_repr) } fn bin_to_byte(bin: &Vec<char>) -> u8 { bin.iter().rev().enumerate().fold(0_u8, { |acc: u8, (e, bin_dig)| acc + bin_dig.to_digit(2).unwrap() as u8 * 2_u8.pow(e as u32) }) } fn bin_to_num64(bin: &Vec<char>) -> u64 { bin.iter().rev().enumerate().fold(0_u64, { |acc: u64, (e, bin_dig)| acc + bin_dig.to_digit(2).unwrap() as u64 * 2_u64.pow(e as u32) }) }
mod fizzbazz1; fn main() { fizzbazz1::run(); }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtGui/qsessionmanager.h // dst-file: /src/gui/qsessionmanager.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::super::core::qobject::*; // 771 use std::ops::Deref; use super::super::core::qstring::*; // 771 use super::super::core::qstringlist::*; // 771 use super::super::core::qobjectdefs::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QSessionManager_Class_Size() -> c_int; // proto: QString QSessionManager::sessionId(); fn C_ZNK15QSessionManager9sessionIdEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QString QSessionManager::sessionKey(); fn C_ZNK15QSessionManager10sessionKeyEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QSessionManager::setRestartCommand(const QStringList & ); fn C_ZN15QSessionManager17setRestartCommandERK11QStringList(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: const QMetaObject * QSessionManager::metaObject(); fn C_ZNK15QSessionManager10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QSessionManager::allowsErrorInteraction(); fn C_ZN15QSessionManager22allowsErrorInteractionEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QStringList QSessionManager::restartCommand(); fn C_ZNK15QSessionManager14restartCommandEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QSessionManager::requestPhase2(); fn C_ZN15QSessionManager13requestPhase2Ev(qthis: u64 /* *mut c_void*/); // proto: bool QSessionManager::isPhase2(); fn C_ZNK15QSessionManager8isPhase2Ev(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QSessionManager::release(); fn C_ZN15QSessionManager7releaseEv(qthis: u64 /* *mut c_void*/); // proto: void QSessionManager::setManagerProperty(const QString & name, const QString & value); fn C_ZN15QSessionManager18setManagerPropertyERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); // proto: void QSessionManager::setManagerProperty(const QString & name, const QStringList & value); fn C_ZN15QSessionManager18setManagerPropertyERK7QStringRK11QStringList(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); // proto: QStringList QSessionManager::discardCommand(); fn C_ZNK15QSessionManager14discardCommandEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QSessionManager::cancel(); fn C_ZN15QSessionManager6cancelEv(qthis: u64 /* *mut c_void*/); // proto: void QSessionManager::setDiscardCommand(const QStringList & ); fn C_ZN15QSessionManager17setDiscardCommandERK11QStringList(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: bool QSessionManager::allowsInteraction(); fn C_ZN15QSessionManager17allowsInteractionEv(qthis: u64 /* *mut c_void*/) -> c_char; } // <= ext block end // body block begin => // class sizeof(QSessionManager)=1 #[derive(Default)] pub struct QSessionManager { qbase: QObject, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QSessionManager { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QSessionManager { return QSessionManager{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QSessionManager { type Target = QObject; fn deref(&self) -> &QObject { return & self.qbase; } } impl AsRef<QObject> for QSessionManager { fn as_ref(& self) -> & QObject { return & self.qbase; } } // proto: QString QSessionManager::sessionId(); impl /*struct*/ QSessionManager { pub fn sessionId<RetType, T: QSessionManager_sessionId<RetType>>(& self, overload_args: T) -> RetType { return overload_args.sessionId(self); // return 1; } } pub trait QSessionManager_sessionId<RetType> { fn sessionId(self , rsthis: & QSessionManager) -> RetType; } // proto: QString QSessionManager::sessionId(); impl<'a> /*trait*/ QSessionManager_sessionId<QString> for () { fn sessionId(self , rsthis: & QSessionManager) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QSessionManager9sessionIdEv()}; let mut ret = unsafe {C_ZNK15QSessionManager9sessionIdEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QString QSessionManager::sessionKey(); impl /*struct*/ QSessionManager { pub fn sessionKey<RetType, T: QSessionManager_sessionKey<RetType>>(& self, overload_args: T) -> RetType { return overload_args.sessionKey(self); // return 1; } } pub trait QSessionManager_sessionKey<RetType> { fn sessionKey(self , rsthis: & QSessionManager) -> RetType; } // proto: QString QSessionManager::sessionKey(); impl<'a> /*trait*/ QSessionManager_sessionKey<QString> for () { fn sessionKey(self , rsthis: & QSessionManager) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QSessionManager10sessionKeyEv()}; let mut ret = unsafe {C_ZNK15QSessionManager10sessionKeyEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QSessionManager::setRestartCommand(const QStringList & ); impl /*struct*/ QSessionManager { pub fn setRestartCommand<RetType, T: QSessionManager_setRestartCommand<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setRestartCommand(self); // return 1; } } pub trait QSessionManager_setRestartCommand<RetType> { fn setRestartCommand(self , rsthis: & QSessionManager) -> RetType; } // proto: void QSessionManager::setRestartCommand(const QStringList & ); impl<'a> /*trait*/ QSessionManager_setRestartCommand<()> for (&'a QStringList) { fn setRestartCommand(self , rsthis: & QSessionManager) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QSessionManager17setRestartCommandERK11QStringList()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN15QSessionManager17setRestartCommandERK11QStringList(rsthis.qclsinst, arg0)}; // return 1; } } // proto: const QMetaObject * QSessionManager::metaObject(); impl /*struct*/ QSessionManager { pub fn metaObject<RetType, T: QSessionManager_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QSessionManager_metaObject<RetType> { fn metaObject(self , rsthis: & QSessionManager) -> RetType; } // proto: const QMetaObject * QSessionManager::metaObject(); impl<'a> /*trait*/ QSessionManager_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QSessionManager) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QSessionManager10metaObjectEv()}; let mut ret = unsafe {C_ZNK15QSessionManager10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QSessionManager::allowsErrorInteraction(); impl /*struct*/ QSessionManager { pub fn allowsErrorInteraction<RetType, T: QSessionManager_allowsErrorInteraction<RetType>>(& self, overload_args: T) -> RetType { return overload_args.allowsErrorInteraction(self); // return 1; } } pub trait QSessionManager_allowsErrorInteraction<RetType> { fn allowsErrorInteraction(self , rsthis: & QSessionManager) -> RetType; } // proto: bool QSessionManager::allowsErrorInteraction(); impl<'a> /*trait*/ QSessionManager_allowsErrorInteraction<i8> for () { fn allowsErrorInteraction(self , rsthis: & QSessionManager) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QSessionManager22allowsErrorInteractionEv()}; let mut ret = unsafe {C_ZN15QSessionManager22allowsErrorInteractionEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QStringList QSessionManager::restartCommand(); impl /*struct*/ QSessionManager { pub fn restartCommand<RetType, T: QSessionManager_restartCommand<RetType>>(& self, overload_args: T) -> RetType { return overload_args.restartCommand(self); // return 1; } } pub trait QSessionManager_restartCommand<RetType> { fn restartCommand(self , rsthis: & QSessionManager) -> RetType; } // proto: QStringList QSessionManager::restartCommand(); impl<'a> /*trait*/ QSessionManager_restartCommand<QStringList> for () { fn restartCommand(self , rsthis: & QSessionManager) -> QStringList { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QSessionManager14restartCommandEv()}; let mut ret = unsafe {C_ZNK15QSessionManager14restartCommandEv(rsthis.qclsinst)}; let mut ret1 = QStringList::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QSessionManager::requestPhase2(); impl /*struct*/ QSessionManager { pub fn requestPhase2<RetType, T: QSessionManager_requestPhase2<RetType>>(& self, overload_args: T) -> RetType { return overload_args.requestPhase2(self); // return 1; } } pub trait QSessionManager_requestPhase2<RetType> { fn requestPhase2(self , rsthis: & QSessionManager) -> RetType; } // proto: void QSessionManager::requestPhase2(); impl<'a> /*trait*/ QSessionManager_requestPhase2<()> for () { fn requestPhase2(self , rsthis: & QSessionManager) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QSessionManager13requestPhase2Ev()}; unsafe {C_ZN15QSessionManager13requestPhase2Ev(rsthis.qclsinst)}; // return 1; } } // proto: bool QSessionManager::isPhase2(); impl /*struct*/ QSessionManager { pub fn isPhase2<RetType, T: QSessionManager_isPhase2<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isPhase2(self); // return 1; } } pub trait QSessionManager_isPhase2<RetType> { fn isPhase2(self , rsthis: & QSessionManager) -> RetType; } // proto: bool QSessionManager::isPhase2(); impl<'a> /*trait*/ QSessionManager_isPhase2<i8> for () { fn isPhase2(self , rsthis: & QSessionManager) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QSessionManager8isPhase2Ev()}; let mut ret = unsafe {C_ZNK15QSessionManager8isPhase2Ev(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QSessionManager::release(); impl /*struct*/ QSessionManager { pub fn release<RetType, T: QSessionManager_release<RetType>>(& self, overload_args: T) -> RetType { return overload_args.release(self); // return 1; } } pub trait QSessionManager_release<RetType> { fn release(self , rsthis: & QSessionManager) -> RetType; } // proto: void QSessionManager::release(); impl<'a> /*trait*/ QSessionManager_release<()> for () { fn release(self , rsthis: & QSessionManager) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QSessionManager7releaseEv()}; unsafe {C_ZN15QSessionManager7releaseEv(rsthis.qclsinst)}; // return 1; } } // proto: void QSessionManager::setManagerProperty(const QString & name, const QString & value); impl /*struct*/ QSessionManager { pub fn setManagerProperty<RetType, T: QSessionManager_setManagerProperty<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setManagerProperty(self); // return 1; } } pub trait QSessionManager_setManagerProperty<RetType> { fn setManagerProperty(self , rsthis: & QSessionManager) -> RetType; } // proto: void QSessionManager::setManagerProperty(const QString & name, const QString & value); impl<'a> /*trait*/ QSessionManager_setManagerProperty<()> for (&'a QString, &'a QString) { fn setManagerProperty(self , rsthis: & QSessionManager) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QSessionManager18setManagerPropertyERK7QStringS2_()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN15QSessionManager18setManagerPropertyERK7QStringS2_(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QSessionManager::setManagerProperty(const QString & name, const QStringList & value); impl<'a> /*trait*/ QSessionManager_setManagerProperty<()> for (&'a QString, &'a QStringList) { fn setManagerProperty(self , rsthis: & QSessionManager) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QSessionManager18setManagerPropertyERK7QStringRK11QStringList()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN15QSessionManager18setManagerPropertyERK7QStringRK11QStringList(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: QStringList QSessionManager::discardCommand(); impl /*struct*/ QSessionManager { pub fn discardCommand<RetType, T: QSessionManager_discardCommand<RetType>>(& self, overload_args: T) -> RetType { return overload_args.discardCommand(self); // return 1; } } pub trait QSessionManager_discardCommand<RetType> { fn discardCommand(self , rsthis: & QSessionManager) -> RetType; } // proto: QStringList QSessionManager::discardCommand(); impl<'a> /*trait*/ QSessionManager_discardCommand<QStringList> for () { fn discardCommand(self , rsthis: & QSessionManager) -> QStringList { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QSessionManager14discardCommandEv()}; let mut ret = unsafe {C_ZNK15QSessionManager14discardCommandEv(rsthis.qclsinst)}; let mut ret1 = QStringList::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QSessionManager::cancel(); impl /*struct*/ QSessionManager { pub fn cancel<RetType, T: QSessionManager_cancel<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cancel(self); // return 1; } } pub trait QSessionManager_cancel<RetType> { fn cancel(self , rsthis: & QSessionManager) -> RetType; } // proto: void QSessionManager::cancel(); impl<'a> /*trait*/ QSessionManager_cancel<()> for () { fn cancel(self , rsthis: & QSessionManager) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QSessionManager6cancelEv()}; unsafe {C_ZN15QSessionManager6cancelEv(rsthis.qclsinst)}; // return 1; } } // proto: void QSessionManager::setDiscardCommand(const QStringList & ); impl /*struct*/ QSessionManager { pub fn setDiscardCommand<RetType, T: QSessionManager_setDiscardCommand<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setDiscardCommand(self); // return 1; } } pub trait QSessionManager_setDiscardCommand<RetType> { fn setDiscardCommand(self , rsthis: & QSessionManager) -> RetType; } // proto: void QSessionManager::setDiscardCommand(const QStringList & ); impl<'a> /*trait*/ QSessionManager_setDiscardCommand<()> for (&'a QStringList) { fn setDiscardCommand(self , rsthis: & QSessionManager) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QSessionManager17setDiscardCommandERK11QStringList()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN15QSessionManager17setDiscardCommandERK11QStringList(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QSessionManager::allowsInteraction(); impl /*struct*/ QSessionManager { pub fn allowsInteraction<RetType, T: QSessionManager_allowsInteraction<RetType>>(& self, overload_args: T) -> RetType { return overload_args.allowsInteraction(self); // return 1; } } pub trait QSessionManager_allowsInteraction<RetType> { fn allowsInteraction(self , rsthis: & QSessionManager) -> RetType; } // proto: bool QSessionManager::allowsInteraction(); impl<'a> /*trait*/ QSessionManager_allowsInteraction<i8> for () { fn allowsInteraction(self , rsthis: & QSessionManager) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QSessionManager17allowsInteractionEv()}; let mut ret = unsafe {C_ZN15QSessionManager17allowsInteractionEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // <= body block end
//! A zero overhead Windows I/O library #![cfg(windows)] #![deny(missing_docs)] #![allow(bad_style)] #![doc(html_root_url = "https://docs.rs/miow/0.1/x86_64-pc-windows-msvc/")] extern crate kernel32; extern crate net2; extern crate winapi; extern crate ws2_32; #[cfg(test)] extern crate rand; use std::cmp; use std::io; use std::time::Duration; use winapi::*; macro_rules! t { ($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{} failed with {:?}", stringify!($e), e), }) } mod handle; mod overlapped; pub mod iocp; pub mod net; pub mod pipe; pub use overlapped::Overlapped; fn cvt(i: BOOL) -> io::Result<BOOL> { if i == 0 { Err(io::Error::last_os_error()) } else { Ok(i) } } fn dur2ms(dur: Option<Duration>) -> u32 { let dur = match dur { Some(dur) => dur, None => return INFINITE, }; let ms = dur.as_secs().checked_mul(1_000); let ms_extra = dur.subsec_nanos() / 1_000_000; ms.and_then(|ms| { ms.checked_add(ms_extra as u64) }).map(|ms| { cmp::min(u32::max_value() as u64, ms) as u32 }).unwrap_or(INFINITE - 1) }
use crate::utils::EitherIter; use crate::{CoordinateType, LineString, Point}; use geo_types::PointsIter; use std::iter::Rev; pub(crate) fn twice_signed_ring_area<T>(linestring: &LineString<T>) -> T where T: CoordinateType, { if linestring.0.is_empty() || linestring.0.len() == 1 { return T::zero(); } let mut tmp = T::zero(); for line in linestring.lines() { tmp = tmp + line.determinant(); } tmp } /// Iterates through a list of `Point`s pub struct Points<'a, T>(EitherIter<Point<T>, PointsIter<'a, T>, Rev<PointsIter<'a, T>>>) where T: CoordinateType + 'a; impl<'a, T> Iterator for Points<'a, T> where T: CoordinateType, { type Item = Point<T>; fn next(&mut self) -> Option<Self::Item> { self.0.next() } } /// How a linestring is wound, clockwise or counter-clockwise #[derive(PartialEq, Clone, Debug, Eq)] pub enum WindingOrder { Clockwise, CounterClockwise, } /// Calculate, and work with, the winding order pub trait Winding<T> where T: CoordinateType, { /// Return the winding order of this object fn winding_order(&self) -> Option<WindingOrder>; /// True iff this clockwise fn is_cw(&self) -> bool { self.winding_order() == Some(WindingOrder::Clockwise) } /// True iff this is wound counterclockwise fn is_ccw(&self) -> bool { self.winding_order() == Some(WindingOrder::CounterClockwise) } /// Iterate over the points in a clockwise order /// /// The object isn't changed, and the points are returned either in order, or in reverse /// order, so that the resultant order makes it appear clockwise fn points_cw(&self) -> Points<T>; /// Iterate over the points in a counter-clockwise order /// /// The object isn't changed, and the points are returned either in order, or in reverse /// order, so that the resultant order makes it appear counter-clockwise fn points_ccw(&self) -> Points<T>; /// Change this objects's points so they are in clockwise winding order fn make_cw_winding(&mut self); /// Change this line's points so they are in counterclockwise winding order fn make_ccw_winding(&mut self); /// Return a clone of this object, but in the specified winding order fn clone_to_winding_order(&self, winding_order: WindingOrder) -> Self where Self: Sized + Clone, { let mut new: Self = self.clone(); new.make_winding_order(winding_order); new } /// Change the winding order so that it is in this winding order fn make_winding_order(&mut self, winding_order: WindingOrder) { match winding_order { WindingOrder::Clockwise => self.make_cw_winding(), WindingOrder::CounterClockwise => self.make_ccw_winding(), } } } impl<T> Winding<T> for LineString<T> where T: CoordinateType, { /// Returns the winding order of this line /// None if the winding order is undefined. fn winding_order(&self) -> Option<WindingOrder> { let shoelace = twice_signed_ring_area(self); if shoelace < T::zero() { Some(WindingOrder::Clockwise) } else if shoelace > T::zero() { Some(WindingOrder::CounterClockwise) } else if shoelace == T::zero() { None } else { // make compiler stop complaining unreachable!() } } /// Iterate over the points in a clockwise order /// /// The Linestring isn't changed, and the points are returned either in order, or in reverse /// order, so that the resultant order makes it appear clockwise fn points_cw(&self) -> Points<T> { match self.winding_order() { Some(WindingOrder::CounterClockwise) => Points(EitherIter::B(self.points_iter().rev())), _ => Points(EitherIter::A(self.points_iter())), } } /// Iterate over the points in a counter-clockwise order /// /// The Linestring isn't changed, and the points are returned either in order, or in reverse /// order, so that the resultant order makes it appear counter-clockwise fn points_ccw(&self) -> Points<T> { match self.winding_order() { Some(WindingOrder::Clockwise) => Points(EitherIter::B(self.points_iter().rev())), _ => Points(EitherIter::A(self.points_iter())), } } /// Change this line's points so they are in clockwise winding order fn make_cw_winding(&mut self) { if let Some(WindingOrder::CounterClockwise) = self.winding_order() { self.0.reverse(); } } /// Change this line's points so they are in counterclockwise winding order fn make_ccw_winding(&mut self) { if let Some(WindingOrder::Clockwise) = self.winding_order() { self.0.reverse(); } } } #[cfg(test)] mod test { use super::*; #[test] fn winding_order() { // 3 points forming a triangle let a = Point::new(0., 0.); let b = Point::new(2., 0.); let c = Point::new(1., 2.); // That triangle, but in clockwise ordering let cw_line = LineString::from(vec![a.0, c.0, b.0, a.0]); // That triangle, but in counterclockwise ordering let ccw_line = LineString::from(vec![a.0, b.0, c.0, a.0]); assert_eq!(cw_line.winding_order(), Some(WindingOrder::Clockwise)); assert_eq!(cw_line.is_cw(), true); assert_eq!(cw_line.is_ccw(), false); assert_eq!( ccw_line.winding_order(), Some(WindingOrder::CounterClockwise) ); assert_eq!(ccw_line.is_cw(), false); assert_eq!(ccw_line.is_ccw(), true); let cw_points1: Vec<_> = cw_line.points_cw().collect(); assert_eq!(cw_points1.len(), 4); assert_eq!(cw_points1[0], a); assert_eq!(cw_points1[1], c); assert_eq!(cw_points1[2], b); assert_eq!(cw_points1[3], a); let ccw_points1: Vec<_> = cw_line.points_ccw().collect(); assert_eq!(ccw_points1.len(), 4); assert_eq!(ccw_points1[0], a); assert_eq!(ccw_points1[1], b); assert_eq!(ccw_points1[2], c); assert_eq!(ccw_points1[3], a); assert_ne!(cw_points1, ccw_points1); let cw_points2: Vec<_> = ccw_line.points_cw().collect(); let ccw_points2: Vec<_> = ccw_line.points_ccw().collect(); // cw_line and ccw_line are wound differently, but the ordered winding iterator should have // make them similar assert_eq!(cw_points2, cw_points2); assert_eq!(ccw_points2, ccw_points2); // test make_clockwise_winding let mut new_line1 = ccw_line.clone(); new_line1.make_cw_winding(); assert_eq!(new_line1.winding_order(), Some(WindingOrder::Clockwise)); assert_eq!(new_line1, cw_line); assert_ne!(new_line1, ccw_line); // test make_counterclockwise_winding let mut new_line2 = cw_line.clone(); new_line2.make_ccw_winding(); assert_eq!( new_line2.winding_order(), Some(WindingOrder::CounterClockwise) ); assert_ne!(new_line2, cw_line); assert_eq!(new_line2, ccw_line); } }
use std::time::{SystemTime, UNIX_EPOCH}; use diesel::sqlite::SqliteConnection; use ruma_events::room::message::MessageType; use ruma_identifiers::UserId; use slog::Logger; use api::rocketchat::WebhookMessage; use api::{MatrixApi, RocketchatApi}; use config::Config; use errors::*; use http::header::HeaderValue; use i18n::*; use log; use models::{RocketchatRoom, RocketchatServer, Room, UserOnRocketchatServer, VirtualUser}; const IMAGE_MESSAGE_TEXT: &str = "Uploaded an image"; const FILE_MESSAGE_TEXT: &str = "Uploaded a file"; const RESEND_THRESHOLD_IN_SECONDS: i64 = 3; /// Forwards messages from Rocket.Chat to Matrix pub struct Forwarder<'a> { /// Application service configuration config: &'a Config, /// SQL database connection connection: &'a SqliteConnection, /// Logger context logger: &'a Logger, /// Matrix REST API matrix_api: &'a MatrixApi, /// Manages virtual users that the application service uses virtual_user: &'a VirtualUser<'a>, } impl<'a> Forwarder<'a> { /// Create a new `Forwarder`. pub fn new( config: &'a Config, connection: &'a SqliteConnection, logger: &'a Logger, matrix_api: &'a MatrixApi, virtual_user: &'a VirtualUser, ) -> Forwarder<'a> { Forwarder { config, connection, logger, matrix_api, virtual_user } } /// Send a message to the Matrix channel. pub fn send(&self, server: &RocketchatServer, message: &WebhookMessage) -> Result<()> { let is_direct_message = message.channel_id.contains(&message.user_id); if !is_direct_message && !self.is_sendable_message(message.user_id.clone(), server.id.clone())? { debug!( self.logger, "Skipping message, because the message was just posted by the user Matrix and echoed back from Rocket.Chat" ); return Ok(()); } let room = match self.prepare_room(server, message)? { Some(room) => room, None => { debug!( self.logger, "Ignoring message from Rocket.Chat channel `{}`, because the channel is not bridged.", message.channel_id ); return Ok(()); } }; let sender_id = self.virtual_user.find_or_register(&server.id, &message.user_id, &message.user_name)?; let current_displayname = self.matrix_api.get_display_name(sender_id.clone())?.unwrap_or_default(); if message.user_name != current_displayname { debug!(self.logger, "Display name changed from `{}` to `{}`, will update", current_displayname, message.user_name); if let Err(err) = self.matrix_api.set_display_name(sender_id.clone(), message.user_name.clone()) { log::log_error(self.logger, &err) } } if message.text == IMAGE_MESSAGE_TEXT || message.text == FILE_MESSAGE_TEXT { self.forward_file(server, message, &room, &sender_id) } else { self.matrix_api.send_text_message(room.id.clone(), sender_id, message.text.clone()) } } fn is_sendable_message(&self, rocketchat_user_id: String, server_id: String) -> Result<bool> { match UserOnRocketchatServer::find_by_rocketchat_user_id(self.connection, server_id, rocketchat_user_id)? { Some(user_on_rocketchatserver) => { let now = SystemTime::now().duration_since(UNIX_EPOCH).chain_err(|| ErrorKind::InternalServerError)?.as_secs() as i64; let last_sent = now - user_on_rocketchatserver.last_message_sent; debug!(self.logger, "Found {}, last message sent {}s ago", user_on_rocketchatserver.matrix_user_id, last_sent); Ok(last_sent > RESEND_THRESHOLD_IN_SECONDS) } None => Ok(true), } } fn prepare_room(&self, server: &RocketchatServer, message: &WebhookMessage) -> Result<Option<Room>> { let is_direct_message_room = message.channel_id.contains(&message.user_id); if is_direct_message_room { self.prepare_dm_room(server, message) } else { self.prepare_room_for_channel(server, message) } } fn prepare_dm_room(&self, server: &RocketchatServer, message: &WebhookMessage) -> Result<Option<Room>> { let receiver = match self.find_matching_user_for_direct_message(server, message)? { Some(receiver) => receiver, None => { debug!(self.logger, "Ignoring message, because not matching user for the direct chat message was found"); return Ok(None); } }; if receiver.rocketchat_user_id.clone().unwrap_or_default() == message.user_id { debug!(self.logger, "Not forwarding direct message, because the sender is the receivers virtual user"); return Ok(None); } let room = match self.try_to_find_or_create_direct_message_room(server, &receiver, message)? { Some(room) => room, None => return Ok(None), }; Ok(Some(room)) } fn try_to_find_or_create_direct_message_room( &self, server: &RocketchatServer, receiver: &UserOnRocketchatServer, message: &WebhookMessage, ) -> Result<Option<Room>> { let sender_id = self.virtual_user.build_user_id(&message.user_id, &server.id)?; if let Some(room) = Room::get_dm( self.config, self.logger, self.matrix_api, message.channel_id.clone(), &sender_id, &receiver.matrix_user_id, )? { self.invite_user_into_direct_message_room(&room, receiver)?; return Ok(Some(room)); } self.auto_bridge_direct_message_channel(server, receiver, message) } fn invite_user_into_direct_message_room(&self, room: &Room, receiver: &UserOnRocketchatServer) -> Result<()> { let direct_message_recepient = room.direct_message_matrix_user()?; if direct_message_recepient.is_none() { let inviting_user_id = self.matrix_api.get_room_creator(room.id.clone())?; room.join_user(receiver.matrix_user_id.clone(), inviting_user_id)?; } Ok(()) } fn prepare_room_for_channel(&self, server: &RocketchatServer, message: &WebhookMessage) -> Result<Option<Room>> { let channel = RocketchatRoom::new(self.config, self.logger, self.matrix_api, message.channel_id.clone(), &server.id); let room_id = match channel.matrix_id()? { Some(room_id) => room_id, None => return Ok(None), }; let inviting_user_id = self.config.matrix_bot_user_id()?; let user_id = message.user_id.clone(); let user_name = message.user_name.clone(); let sender_id = self.virtual_user.find_or_register(&server.id, &user_id, &user_name)?; let room = Room::new(self.config, self.logger, self.matrix_api, room_id); room.join_user(sender_id, inviting_user_id)?; Ok(Some(room)) } fn auto_bridge_direct_message_channel( &self, server: &RocketchatServer, receiver: &UserOnRocketchatServer, message: &WebhookMessage, ) -> Result<Option<Room>> { debug!( self.logger, "Got a message for a room that is not bridged yet (channel_id `{}`), checking if it's a direct message", &message.channel_id ); let rocketchat_api = RocketchatApi::new(server.rocketchat_url.clone(), self.logger.clone())?.with_credentials( receiver.rocketchat_user_id.clone().unwrap_or_default(), receiver.rocketchat_auth_token.clone().unwrap_or_default(), ); if rocketchat_api.dm_list()?.iter().any(|dm| dm.id == message.channel_id) { let sender_id = self.virtual_user.find_or_register(&server.id, &message.user_id, &message.user_name)?; let room_display_name_suffix = t!(["defaults", "direct_message_room_display_name_suffix"]).l(DEFAULT_LANGUAGE); let room_display_name = format!("{} {}", message.user_name, room_display_name_suffix); let display_name = Some(room_display_name); let room_id = Room::create(self.matrix_api, None, &display_name, &sender_id, &receiver.matrix_user_id)?; // invite the bot user into the direct message room to be able to read the room state // the bot will leave as soon as the AS gets the join event let invitee_id = self.config.matrix_bot_user_id()?; self.matrix_api.invite(room_id.clone(), invitee_id.clone(), sender_id.clone())?; info!(self.logger, "Direct message room {} successfully created", &room_id); let room = Room::new(self.config, self.logger, self.matrix_api, room_id); Ok(Some(room)) } else { debug!( self.logger, "User {} matched the channel_id, but does not have access to the channel. \ Not bridging channel {} automatically", receiver.matrix_user_id, message.channel_id ); Ok(None) } } // this is a pretty hacky way to find a Matrix user that could be the recipient for this // message. The message itself doesn't contain any information about the recipient so the // channel ID has to be checked against all users that use the application service and are // logged in on the sending Rocket.Chat server, because direct message channel IDs consist of // the `user_id`s of the two participants. fn find_matching_user_for_direct_message( &self, server: &RocketchatServer, message: &WebhookMessage, ) -> Result<Option<UserOnRocketchatServer>> { for user_on_rocketchatserver in server.logged_in_users_on_rocketchat_server(self.connection)? { if let Some(rocketchat_user_id) = user_on_rocketchatserver.rocketchat_user_id.clone() { if message.channel_id.contains(&rocketchat_user_id) && rocketchat_user_id != message.user_id { debug!( self.logger, "Matching user with rocketchat_user_id `{}` for channel_id `{}` found.", rocketchat_user_id, &message.channel_id ); return Ok(Some(user_on_rocketchatserver)); } } } Ok(None) } fn forward_file(&self, server: &RocketchatServer, message: &WebhookMessage, room: &Room, sender_id: &UserId) -> Result<()> { debug!(self.logger, "Forwarding file, room {}", room.id); let users = room.logged_in_users(self.connection, server.id.clone())?; // This chooses an arbitrary user from the room to use the credentials to be able to retreive the file from the // Rocket.Chat server. let user = match users.first() { Some(user) => user, None => { warn!( self.logger, "No logged in user in bridged room {} found, cannot retreive image from Rocket.Chat server", room.id ); return Ok(()); } }; let rocketchat_api = RocketchatApi::new(server.rocketchat_url.clone(), self.logger.clone())?.with_credentials( user.rocketchat_user_id.clone().unwrap_or_default(), user.rocketchat_auth_token.clone().unwrap_or_default(), ); let files = rocketchat_api.attachments(&message.message_id)?; for file in files { let file_url = self.matrix_api.upload(file.data.to_vec(), file.content_type.clone())?; let message_type = self.message_type(&file.content_type); debug!(self.logger, "Uploaded file, URL is {}", file_url); self.matrix_api.send_data_message( room.id.clone(), sender_id.clone(), file.title.clone(), file_url, message_type, )?; } Ok(()) } fn message_type(&self, content_type: &HeaderValue) -> MessageType { let raw_content_type = content_type.to_str().unwrap_or_default(); if raw_content_type.starts_with("image/") { MessageType::Image } else if raw_content_type.starts_with("audio/") { MessageType::Audio } else if raw_content_type.starts_with("video/") { MessageType::Video } else { MessageType::File } } }
use bigneon_db::models::{FeeSchedule, TicketType}; use bigneon_db::utils::errors::DatabaseError; use chrono::NaiveDateTime; use diesel::PgConnection; use models::DisplayTicketPricing; use uuid::Uuid; #[derive(Debug, Deserialize, PartialEq, Serialize)] pub struct AdminDisplayTicketType { pub id: Uuid, pub name: String, pub capacity: u32, pub status: String, pub start_date: NaiveDateTime, pub end_date: NaiveDateTime, pub quantity: u32, pub increment: i32, pub ticket_pricing: Vec<DisplayTicketPricing>, } impl AdminDisplayTicketType { pub fn from_ticket_type( ticket_type: &TicketType, fee_schedule: &FeeSchedule, conn: &PgConnection, ) -> Result<AdminDisplayTicketType, DatabaseError> { let quantity = ticket_type.remaining_ticket_count(conn)?; let capacity = ticket_type.ticket_capacity(conn)?; let mut ticket_pricing_list = Vec::new(); for ticket_pricing in ticket_type.valid_ticket_pricing(conn)? { ticket_pricing_list.push(DisplayTicketPricing::from_ticket_pricing( &ticket_pricing, fee_schedule, conn, )?); } Ok(AdminDisplayTicketType { id: ticket_type.id, name: ticket_type.name.clone(), status: ticket_type.status().to_string(), start_date: ticket_type.start_date, end_date: ticket_type.end_date, ticket_pricing: ticket_pricing_list, quantity, capacity, increment: ticket_type.increment, }) } }
#![cfg_attr(feature = "serde_macros", feature(custom_derive, plugin))] #![cfg_attr(feature = "serde_macros", plugin(serde_macros))] #![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #[macro_use] extern crate clap; #[macro_use] extern crate log; extern crate ansi_term; extern crate crypto; extern crate csv; extern crate env_logger; extern crate hyper; extern crate rand; extern crate scoped_threadpool; extern crate serde; extern crate serde_json; #[cfg(feature = "serde_macros")] include!("main.rs.in"); #[cfg(not(feature = "serde_macros"))] include!(concat!(env!("OUT_DIR"), "/main.rs"));
/* * Copyright (C) 2020-2022 Zixiao Han */ use crate::{ def, util::{self, get_lowest_index, get_highest_index}, }; const SLIDE_ATTACK_PERM_COUNT: usize = 256; pub struct BitMask { pub index_masks: [u64; def::BOARD_SIZE], pub rank_masks: [u64; def::BOARD_SIZE], pub file_masks: [u64; def::BOARD_SIZE], pub diag_up_masks: [u64; def::BOARD_SIZE], pub diag_down_masks: [u64; def::BOARD_SIZE], pub wp_forward_masks: [u64; def::BOARD_SIZE], pub bp_forward_masks: [u64; def::BOARD_SIZE], pub wp_behind_masks: [u64; def::BOARD_SIZE], pub bp_behind_masks: [u64; def::BOARD_SIZE], pub wp_attack_masks: [u64; def::BOARD_SIZE], pub bp_attack_masks: [u64; def::BOARD_SIZE], pub wp_mov_masks: [u64; def::BOARD_SIZE], pub bp_mov_masks: [u64; def::BOARD_SIZE], pub wp_init_mov_masks: [u64; def::BOARD_SIZE], pub bp_init_mov_masks: [u64; def::BOARD_SIZE], pub wp_front_control_sqr_masks: [u64; def::BOARD_SIZE], pub bp_front_control_sqr_masks: [u64; def::BOARD_SIZE], pub wp_connected_sqr_masks: [u64; def::BOARD_SIZE], pub bp_connected_sqr_masks: [u64; def::BOARD_SIZE], pub n_attack_masks: [u64; def::BOARD_SIZE], pub k_attack_masks: [u64; def::BOARD_SIZE], up_attack_masks: [u64; def::BOARD_SIZE], down_attack_masks: [u64; def::BOARD_SIZE], left_attack_masks: [u64; def::BOARD_SIZE], right_attack_masks: [u64; def::BOARD_SIZE], up_left_attack_masks: [u64; def::BOARD_SIZE], up_right_attack_masks: [u64; def::BOARD_SIZE], down_left_attack_masks: [u64; def::BOARD_SIZE], down_right_attack_masks: [u64; def::BOARD_SIZE], pub horizontal_attack_masks: [[u64; SLIDE_ATTACK_PERM_COUNT]; def::BOARD_SIZE], pub vertical_attack_masks: [[u64; SLIDE_ATTACK_PERM_COUNT]; def::BOARD_SIZE], pub diag_up_attack_masks: [[u64; SLIDE_ATTACK_PERM_COUNT]; def::BOARD_SIZE], pub diag_down_attack_masks: [[u64; SLIDE_ATTACK_PERM_COUNT]; def::BOARD_SIZE], pub wk_attack_zone_masks: [u64; def::BOARD_SIZE], pub bk_attack_zone_masks: [u64; def::BOARD_SIZE], pub b_cover_masks: [u64; def::BOARD_SIZE], } impl BitMask { fn new() -> Self { let mut bitmask = BitMask { index_masks: [0; def::BOARD_SIZE], rank_masks: [0; def::BOARD_SIZE], file_masks: [0; def::BOARD_SIZE], diag_up_masks: [0; def::BOARD_SIZE], diag_down_masks: [0; def::BOARD_SIZE], wp_forward_masks: [0; def::BOARD_SIZE], bp_forward_masks: [0; def::BOARD_SIZE], wp_behind_masks: [0; def::BOARD_SIZE], bp_behind_masks: [0; def::BOARD_SIZE], wp_attack_masks: [0; def::BOARD_SIZE], bp_attack_masks: [0; def::BOARD_SIZE], wp_mov_masks: [0; def::BOARD_SIZE], bp_mov_masks: [0; def::BOARD_SIZE], wp_init_mov_masks: [0; def::BOARD_SIZE], bp_init_mov_masks: [0; def::BOARD_SIZE], wp_front_control_sqr_masks: [0; def::BOARD_SIZE], bp_front_control_sqr_masks: [0; def::BOARD_SIZE], wp_connected_sqr_masks: [0; def::BOARD_SIZE], bp_connected_sqr_masks: [0; def::BOARD_SIZE], n_attack_masks: [0; def::BOARD_SIZE], k_attack_masks: [0; def::BOARD_SIZE], left_attack_masks: [0; def::BOARD_SIZE], right_attack_masks: [0; def::BOARD_SIZE], up_attack_masks: [0; def::BOARD_SIZE], down_attack_masks: [0; def::BOARD_SIZE], up_left_attack_masks: [0; def::BOARD_SIZE], up_right_attack_masks: [0; def::BOARD_SIZE], down_left_attack_masks: [0; def::BOARD_SIZE], down_right_attack_masks: [0; def::BOARD_SIZE], horizontal_attack_masks: [[0; SLIDE_ATTACK_PERM_COUNT]; def::BOARD_SIZE], vertical_attack_masks: [[0; SLIDE_ATTACK_PERM_COUNT]; def::BOARD_SIZE], diag_up_attack_masks: [[0; SLIDE_ATTACK_PERM_COUNT]; def::BOARD_SIZE], diag_down_attack_masks: [[0; SLIDE_ATTACK_PERM_COUNT]; def::BOARD_SIZE], wk_attack_zone_masks: [0; def::BOARD_SIZE], bk_attack_zone_masks: [0; def::BOARD_SIZE], b_cover_masks: [0; def::BOARD_SIZE], }; bitmask.init_base(); bitmask.init_n_masks(); bitmask.init_k_masks(); bitmask.init_up_left_masks(); bitmask.init_down_left_masks(); bitmask.init_up_right_masks(); bitmask.init_down_right_masks(); bitmask.init_up_masks(); bitmask.init_down_masks(); bitmask.init_left_masks(); bitmask.init_right_masks(); bitmask.init_horizontal_attack_masks(); bitmask.init_vertical_attack_masks(); bitmask.init_diag_up_attack_masks(); bitmask.init_diag_down_attack_masks(); bitmask.init_p_attack_masks(); bitmask.init_p_mov_masks(); bitmask.init_p_misc_masks(); bitmask.init_p_endgame_masks(); bitmask.init_k_safety_masks(); bitmask.init_b_cover_masks(); bitmask } fn init_base(&mut self) { let mut file_masks = [0; def::DIM_SIZE]; let mut rank_masks = [0; def::DIM_SIZE]; let mut diag_up_masks = [0; def::DIM_SIZE << 1]; let mut diag_down_masks = [0; def::DIM_SIZE << 1]; for index in 0..def::BOARD_SIZE { let index_mask = 1u64 << index; self.index_masks[index] = index_mask; let file = index % def::DIM_SIZE; file_masks[file] = file_masks[file] | index_mask; let rank = index / def::DIM_SIZE; rank_masks[rank] = rank_masks[rank] | index_mask; let diag_up = (rank - file) & 15; diag_up_masks[diag_up] = diag_up_masks[diag_up] | index_mask; let diag_down = (rank + file) ^ 7; diag_down_masks[diag_down] = diag_down_masks[diag_down] | index_mask; } for index in 0..def::BOARD_SIZE { let file = index % def::DIM_SIZE; self.file_masks[index] = file_masks[file]; let rank = index / def::DIM_SIZE; self.rank_masks[index] = rank_masks[rank]; let diag_up = (rank - file) & 15; self.diag_up_masks[index] = diag_up_masks[diag_up]; let diag_down = (rank + file) ^ 7; self.diag_down_masks[index] = diag_down_masks[diag_down]; } } fn init_n_masks(&mut self) { for index in 0..def::BOARD_SIZE { if index + 6 < def::BOARD_SIZE && (self.index_masks[index] & self.file_masks[0] == 0) && (self.index_masks[index] & self.file_masks[1] == 0) { self.n_attack_masks[index] = self.n_attack_masks[index] | self.index_masks[index + 6]; } if index >= 6 && (self.index_masks[index] & self.file_masks[6] == 0) && (self.index_masks[index] & self.file_masks[7] == 0) { self.n_attack_masks[index] = self.n_attack_masks[index] | self.index_masks[index - 6]; } if index + 10 < def::BOARD_SIZE && (self.index_masks[index] & self.file_masks[6] == 0) && (self.index_masks[index] & self.file_masks[7] == 0) { self.n_attack_masks[index] = self.n_attack_masks[index] | self.index_masks[index + 10]; } if index >= 10 && (self.index_masks[index] & self.file_masks[0] == 0) && (self.index_masks[index] & self.file_masks[1] == 0) { self.n_attack_masks[index] = self.n_attack_masks[index] | self.index_masks[index - 10]; } if index + 15 < def::BOARD_SIZE && (self.index_masks[index] & self.file_masks[0] == 0) { self.n_attack_masks[index] = self.n_attack_masks[index] | self.index_masks[index + 15]; } if index >= 15 && (self.index_masks[index] & self.file_masks[7] == 0) { self.n_attack_masks[index] = self.n_attack_masks[index] | self.index_masks[index - 15]; } if index + 17 < def::BOARD_SIZE && (self.index_masks[index] & self.file_masks[7] == 0) { self.n_attack_masks[index] = self.n_attack_masks[index] | self.index_masks[index + 17]; } if index >= 17 && (self.index_masks[index] & self.file_masks[0] == 0) { self.n_attack_masks[index] = self.n_attack_masks[index] | self.index_masks[index - 17]; } } } fn init_k_masks(&mut self) { for index in 0..def::BOARD_SIZE { if index + 1 < def::BOARD_SIZE && (self.index_masks[index] & self.file_masks[7] == 0) { self.k_attack_masks[index] = self.k_attack_masks[index] | self.index_masks[index + 1]; } if index >= 1 && (self.index_masks[index] & self.file_masks[0] == 0) { self.k_attack_masks[index] = self.k_attack_masks[index] | self.index_masks[index - 1]; } if index + 8 < def::BOARD_SIZE { self.k_attack_masks[index] = self.k_attack_masks[index] | self.index_masks[index + 8]; } if index >= 8 { self.k_attack_masks[index] = self.k_attack_masks[index] | self.index_masks[index - 8]; } if index + 7 < def::BOARD_SIZE && (self.index_masks[index] & self.file_masks[0] == 0) { self.k_attack_masks[index] = self.k_attack_masks[index] | self.index_masks[index + 7]; } if index >= 7 && (self.index_masks[index] & self.file_masks[7] == 0) { self.k_attack_masks[index] = self.k_attack_masks[index] | self.index_masks[index - 7]; } if index + 9 < def::BOARD_SIZE && (self.index_masks[index] & self.file_masks[7] == 0) { self.k_attack_masks[index] = self.k_attack_masks[index] | self.index_masks[index + 9]; } if index >= 9 && (self.index_masks[index] & self.file_masks[0] == 0) { self.k_attack_masks[index] = self.k_attack_masks[index] | self.index_masks[index - 9]; } } } fn init_up_masks(&mut self) { for index in 0..def::BOARD_SIZE { let mut up_index = index; while up_index < 56 { up_index += 8; self.up_attack_masks[index] ^= self.index_masks[up_index]; } } } fn init_down_masks(&mut self) { for index in 0..def::BOARD_SIZE { let mut down_index = index; while down_index > 7 { down_index -= 8; self.down_attack_masks[index] ^= self.index_masks[down_index]; } } } fn init_left_masks(&mut self) { for index in 0..def::BOARD_SIZE { let mut left_index = index; while left_index % 8 > 0 { left_index -= 1; self.left_attack_masks[index] ^= self.index_masks[left_index]; } } } fn init_right_masks(&mut self) { for index in 0..def::BOARD_SIZE { let mut right_index = index; while right_index % 8 < 7 { right_index += 1; self.right_attack_masks[index] ^= self.index_masks[right_index]; } } } fn init_up_left_masks(&mut self) { for index in 0..def::BOARD_SIZE { let mut up_left_index = index; while up_left_index < 56 && up_left_index % 8 > 0 { up_left_index += 7; self.up_left_attack_masks[index] ^= self.index_masks[up_left_index]; } } } fn init_up_right_masks(&mut self) { for index in 0..def::BOARD_SIZE { let mut up_right_index = index; while up_right_index < 56 && up_right_index % 8 < 7 { up_right_index += 9; self.up_right_attack_masks[index] ^= self.index_masks[up_right_index]; } } } fn init_down_left_masks(&mut self) { for index in 0..def::BOARD_SIZE { let mut down_left_index = index; while down_left_index > 7 && down_left_index % 8 > 0 { down_left_index -= 9; self.down_left_attack_masks[index] ^= self.index_masks[down_left_index]; } } } fn init_down_right_masks(&mut self) { for index in 0..def::BOARD_SIZE { let mut down_right_index = index; while down_right_index > 7 && down_right_index % 8 < 7 { down_right_index -= 7; self.down_right_attack_masks[index] ^= self.index_masks[down_right_index]; } } } fn init_horizontal_attack_masks(&mut self) { let horizontal_masks = util::gen_all_perms_1st_rank(); for index in 0..def::DIM_SIZE { let right_attack_mask = self.right_attack_masks[index]; let left_attack_mask = self.left_attack_masks[index]; for occupy_mask in &horizontal_masks { let mut left_mov_mask = 0; let mut right_mov_mask = 0; right_mov_mask ^= right_attack_mask; if right_attack_mask & occupy_mask != 0 { let lowest_blocker_index = get_lowest_index(right_attack_mask & occupy_mask); right_mov_mask &= !self.right_attack_masks[lowest_blocker_index]; } left_mov_mask ^= left_attack_mask; if left_attack_mask & occupy_mask != 0 { let highest_blocker_index = get_highest_index(left_attack_mask & occupy_mask); left_mov_mask &= !self.left_attack_masks[highest_blocker_index]; } let mov_mask = left_mov_mask | right_mov_mask; self.horizontal_attack_masks[index][*occupy_mask as usize] = mov_mask; for rank in 1..def::DIM_SIZE { self.horizontal_attack_masks[rank * def::DIM_SIZE + index][*occupy_mask as usize] = mov_mask << rank * def::DIM_SIZE; } } } } fn init_vertical_attack_masks(&mut self) { let vertical_masks = util::gen_all_perms_1st_file(); for rank in 0..def::DIM_SIZE { let index = rank * def::DIM_SIZE; let up_attack_mask = self.up_attack_masks[index]; let down_attack_mask = self.down_attack_masks[index]; for occupy_mask in &vertical_masks { let mut up_mov_mask = 0; let mut down_mov_mask = 0; up_mov_mask ^= up_attack_mask; if up_attack_mask & occupy_mask != 0 { let lowest_blocker_index = get_lowest_index(up_attack_mask & occupy_mask); up_mov_mask &= !self.up_attack_masks[lowest_blocker_index]; } down_mov_mask ^= down_attack_mask; if down_attack_mask & occupy_mask != 0 { let highest_blocker_index = get_highest_index(down_attack_mask & occupy_mask); down_mov_mask &= !self.down_attack_masks[highest_blocker_index]; } let mov_mask = up_mov_mask | down_mov_mask; let mapped_mask = util::kindergarten_transform_file(*occupy_mask, index); self.vertical_attack_masks[index][mapped_mask as usize] = mov_mask; for file in 1..def::DIM_SIZE { self.vertical_attack_masks[index + file][mapped_mask as usize] = mov_mask << file; } } } } fn init_diag_up_attack_masks(&mut self) { let diag_up_masks = util::gen_all_perms_diag_up(); let mut index = 0; loop { if index > def:: BOARD_SIZE - 1 { break; } let up_right_attack_mask = self.up_right_attack_masks[index]; let down_left_attack_mask = self.down_left_attack_masks[index]; for occupy_mask in &diag_up_masks { let mut down_left_mov_mask = 0; let mut up_right_mov_mask = 0; up_right_mov_mask ^= up_right_attack_mask; if up_right_attack_mask & occupy_mask != 0 { let lowest_blocker_index = get_lowest_index(up_right_attack_mask & occupy_mask); up_right_mov_mask &= !self.up_right_attack_masks[lowest_blocker_index]; } down_left_mov_mask ^= down_left_attack_mask; if down_left_attack_mask & occupy_mask != 0 { let highest_blocker_index = get_highest_index(down_left_attack_mask & occupy_mask); down_left_mov_mask &= !self.down_left_attack_masks[highest_blocker_index]; } let mov_mask = down_left_mov_mask | up_right_mov_mask; let mapped_mask = util::kindergarten_transform_rank_diag(*occupy_mask); self.diag_up_attack_masks[index][mapped_mask as usize] = mov_mask; for up in 1..def::DIM_SIZE { if index + up * def::DIM_SIZE >= def::BOARD_SIZE - 1 { continue; } let mapped_mask = util::kindergarten_transform_rank_diag(*occupy_mask << up * def::DIM_SIZE); self.diag_up_attack_masks[index + up * def::DIM_SIZE][mapped_mask as usize] = mov_mask << up * def::DIM_SIZE; } for down in 1..def::DIM_SIZE { if index <= down * def::DIM_SIZE { continue; } let mapped_mask = util::kindergarten_transform_rank_diag(*occupy_mask >> down * def::DIM_SIZE); self.diag_up_attack_masks[index - down * def::DIM_SIZE][mapped_mask as usize] = mov_mask >> down * def::DIM_SIZE; } } index = index + 9; } } fn init_diag_down_attack_masks(&mut self) { let diag_down_masks = util::gen_all_perms_diag_down(); let mut index = 7; loop { if index > def:: BOARD_SIZE - def:: DIM_SIZE { break; } let up_left_attack_mask = self.up_left_attack_masks[index]; let down_right_attack_mask = self.down_right_attack_masks[index]; for occupy_mask in &diag_down_masks { let mut up_left_mov_mask = 0; let mut down_right_mov_mask = 0; up_left_mov_mask ^= up_left_attack_mask; if up_left_attack_mask & occupy_mask != 0 { let lowest_blocker_index = get_lowest_index(up_left_attack_mask & occupy_mask); up_left_mov_mask &= !self.up_left_attack_masks[lowest_blocker_index]; } down_right_mov_mask ^= down_right_attack_mask; if down_right_attack_mask & occupy_mask != 0 { let highest_blocker_index = get_highest_index(down_right_attack_mask & occupy_mask); down_right_mov_mask &= !self.down_right_attack_masks[highest_blocker_index]; } let mov_mask = up_left_mov_mask | down_right_mov_mask; let mapped_mask = util::kindergarten_transform_rank_diag(*occupy_mask); self.diag_down_attack_masks[index][mapped_mask as usize] = mov_mask; for up in 1..def::DIM_SIZE { if index + up * def::DIM_SIZE >= def::BOARD_SIZE - 1 { continue; } let mapped_mask = util::kindergarten_transform_rank_diag(*occupy_mask << up * def::DIM_SIZE); self.diag_down_attack_masks[index + up * def::DIM_SIZE][mapped_mask as usize] = mov_mask << up * def::DIM_SIZE; } for down in 1..def::DIM_SIZE { if index <= down * def::DIM_SIZE { continue; } let mapped_mask = util::kindergarten_transform_rank_diag(*occupy_mask >> down * def::DIM_SIZE); self.diag_down_attack_masks[index - down * def::DIM_SIZE][mapped_mask as usize] = mov_mask >> down * def::DIM_SIZE; } } index = index + 7; } } fn init_b_cover_masks(&mut self) { for index in 0..def::BOARD_SIZE { self.b_cover_masks[index] = self.up_left_attack_masks[index] ^ self.up_right_attack_masks[index] ^ self.down_left_attack_masks[index] ^ self.down_right_attack_masks[index]; } } fn init_p_attack_masks(&mut self) { for index in 0..def::BOARD_SIZE { if self.index_masks[index] & self.file_masks[0] == 0 { if index < 56 { self.wp_attack_masks[index] = self.wp_attack_masks[index] | self.index_masks[index + 7]; } if index > 7 { self.bp_attack_masks[index] = self.bp_attack_masks[index] | self.index_masks[index - 9]; } } if self.index_masks[index] & self.file_masks[7] == 0 { if index < 56 { self.wp_attack_masks[index] = self.wp_attack_masks[index] | self.index_masks[index + 9]; } if index > 7 { self.bp_attack_masks[index] = self.bp_attack_masks[index] | self.index_masks[index - 7]; } } } } fn init_p_mov_masks(&mut self) { for index in 8..def::BOARD_SIZE - 8 { self.wp_mov_masks[index] = self.index_masks[index + 8]; self.bp_mov_masks[index] = self.index_masks[index - 8]; if index < 16 { self.wp_init_mov_masks[index] = self.index_masks[index + 16]; } if index > 47 { self.bp_init_mov_masks[index] = self.index_masks[index - 16]; } } } fn init_p_misc_masks(&mut self) { for index in 0..def::BOARD_SIZE { self.wp_forward_masks[index] = self.up_attack_masks[index]; self.bp_forward_masks[index] = self.down_attack_masks[index]; if index % 8 > 0 { self.wp_forward_masks[index] ^= self.up_attack_masks[index - 1]; self.wp_behind_masks[index] ^= self.down_attack_masks[index - 1] ^ self.index_masks[index - 1]; self.bp_forward_masks[index] ^= self.down_attack_masks[index - 1]; self.bp_behind_masks[index] ^= self.up_attack_masks[index - 1] ^ self.index_masks[index - 1]; } if index % 8 < 7 { self.wp_forward_masks[index] ^= self.up_attack_masks[index + 1]; self.wp_behind_masks[index] ^= self.down_attack_masks[index + 1] ^ self.index_masks[index + 1]; self.bp_forward_masks[index] ^= self.down_attack_masks[index + 1]; self.bp_behind_masks[index] ^= self.up_attack_masks[index + 1] ^ self.index_masks[index + 1]; } } for index in 8..def::BOARD_SIZE - 8 { let mut connected_mask = 0; if index % 8 != 0 { connected_mask |= self.index_masks[index - 1]; connected_mask |= self.index_masks[index - 9]; } if index % 8 != 7 { connected_mask |= self.index_masks[index + 1]; connected_mask |= self.index_masks[index - 7]; } self.wp_connected_sqr_masks[index] = connected_mask; } for index in 8..def::BOARD_SIZE - 8 { let mut connected_mask = 0; if index % 8 != 0 { connected_mask |= self.index_masks[index - 1]; connected_mask |= self.index_masks[index + 7]; } if index % 8 != 7 { connected_mask |= self.index_masks[index + 1]; connected_mask |= self.index_masks[index + 9]; } self.bp_connected_sqr_masks[index] = connected_mask; } } fn init_p_endgame_masks(&mut self) { for index in 8..def::BOARD_SIZE - 16 { let mut front_control_mask = 0; front_control_mask |= self.index_masks[index + 16]; if index % 8 != 0 { front_control_mask |= self.index_masks[index + 15]; } if index % 8 != 7 { front_control_mask |= self.index_masks[index + 17]; } self.wp_front_control_sqr_masks[index] = front_control_mask; } for index in 16..def::BOARD_SIZE - 8 { let mut front_control_mask = 0; front_control_mask |= self.index_masks[index - 16]; if index % 8 != 0 { front_control_mask |= self.index_masks[index - 17]; } if index % 8 != 7 { front_control_mask |= self.index_masks[index - 15]; } self.bp_front_control_sqr_masks[index] = front_control_mask; } } fn init_k_safety_masks(&mut self) { for index in 0..def::BOARD_SIZE - 16 { let mut attack_zone_mask = self.k_attack_masks[index]; attack_zone_mask |= self.index_masks[index + 8]; attack_zone_mask |= self.index_masks[index + 16]; if index % 8 != 0 { attack_zone_mask |= self.index_masks[index + 7]; attack_zone_mask |= self.index_masks[index + 15]; } if index % 8 != 7 { attack_zone_mask |= self.index_masks[index + 9]; attack_zone_mask |= self.index_masks[index + 17]; } self.wk_attack_zone_masks[index] = attack_zone_mask; } for index in 16..def::BOARD_SIZE { let mut attack_zone_mask = self.k_attack_masks[index]; attack_zone_mask |= self.index_masks[index - 8]; attack_zone_mask |= self.index_masks[index - 16]; if index % 8 != 0 { attack_zone_mask |= self.index_masks[index - 9]; attack_zone_mask |= self.index_masks[index - 17]; } if index % 8 != 7 { attack_zone_mask |= self.index_masks[index - 7]; attack_zone_mask |= self.index_masks[index - 15]; } self.bk_attack_zone_masks[index] = attack_zone_mask; } } } static mut BITMASK: BitMask = BitMask { index_masks: [0; def::BOARD_SIZE], rank_masks: [0; def::BOARD_SIZE], file_masks: [0; def::BOARD_SIZE], diag_up_masks: [0; def::BOARD_SIZE], diag_down_masks: [0; def::BOARD_SIZE], wp_forward_masks: [0; def::BOARD_SIZE], bp_forward_masks: [0; def::BOARD_SIZE], wp_behind_masks: [0; def::BOARD_SIZE], bp_behind_masks: [0; def::BOARD_SIZE], wp_attack_masks: [0; def::BOARD_SIZE], bp_attack_masks: [0; def::BOARD_SIZE], wp_mov_masks: [0; def::BOARD_SIZE], bp_mov_masks: [0; def::BOARD_SIZE], wp_init_mov_masks: [0; def::BOARD_SIZE], bp_init_mov_masks: [0; def::BOARD_SIZE], wp_front_control_sqr_masks: [0; def::BOARD_SIZE], bp_front_control_sqr_masks: [0; def::BOARD_SIZE], wp_connected_sqr_masks: [0; def::BOARD_SIZE], bp_connected_sqr_masks: [0; def::BOARD_SIZE], n_attack_masks: [0; def::BOARD_SIZE], k_attack_masks: [0; def::BOARD_SIZE], left_attack_masks: [0; def::BOARD_SIZE], right_attack_masks: [0; def::BOARD_SIZE], up_attack_masks: [0; def::BOARD_SIZE], down_attack_masks: [0; def::BOARD_SIZE], up_left_attack_masks: [0; def::BOARD_SIZE], up_right_attack_masks: [0; def::BOARD_SIZE], down_left_attack_masks: [0; def::BOARD_SIZE], down_right_attack_masks: [0; def::BOARD_SIZE], horizontal_attack_masks: [[0; SLIDE_ATTACK_PERM_COUNT]; def::BOARD_SIZE], vertical_attack_masks: [[0; SLIDE_ATTACK_PERM_COUNT]; def::BOARD_SIZE], diag_up_attack_masks: [[0; SLIDE_ATTACK_PERM_COUNT]; def::BOARD_SIZE], diag_down_attack_masks: [[0; SLIDE_ATTACK_PERM_COUNT]; def::BOARD_SIZE], wk_attack_zone_masks: [0; def::BOARD_SIZE], bk_attack_zone_masks: [0; def::BOARD_SIZE], b_cover_masks: [0; def::BOARD_SIZE], }; pub fn init() { unsafe { BITMASK = BitMask::new(); } } #[inline] pub fn get_bitmask() -> &'static BitMask { unsafe { &BITMASK } } #[cfg(test)] mod tests { use super::*; use crate::{ util, }; #[test] fn test_horizontal_masks() { init(); let bitmask = get_bitmask(); let index = util::map_sqr_notation_to_index("e4"); let rank_mask = bitmask.rank_masks[index]; let occupy_mask = 0b00000010_00000001_00000000_00000000_01001100_00000000_00000000_00000001 & rank_mask; assert_eq!(0b00000000_00000000_00000000_00000000_01101000_00000000_00000000_00000000, bitmask.horizontal_attack_masks[index][util::kindergarten_transform_rank_diag(occupy_mask) as usize]); } #[test] fn test_diagup_masks() { init(); let bitmask = get_bitmask(); let index = util::map_sqr_notation_to_index("d4"); let diag_up_mask = bitmask.diag_up_masks[index]; let occupy_mask = 0b00000010_00000001_00000000_00010000_00001000_00000000_00000010_00000010 & diag_up_mask; assert_eq!(0b00000000_00000000_00000000_00010000_00000000_00000100_00000010_00000000, bitmask.diag_up_attack_masks[index][util::kindergarten_transform_rank_diag(occupy_mask) as usize]); } #[test] fn test_diagup_masks1() { init(); let bitmask = get_bitmask(); let index = util::map_sqr_notation_to_index("f4"); let diag_up_mask = bitmask.diag_up_masks[index]; let occupy_mask = 0b00000000_00000000_10000000_00000000_00100000_00010000_00000000_00000000 & diag_up_mask; assert_eq!(0b00000000_00000000_10000000_01000000_00000000_00010000_00000000_00000000, bitmask.diag_up_attack_masks[index][util::kindergarten_transform_rank_diag(occupy_mask) as usize]); } #[test] fn test_diagup_masks2() { init(); let bitmask = get_bitmask(); let index = util::map_sqr_notation_to_index("a5"); let diag_up_mask = bitmask.diag_up_masks[index]; let occupy_mask = 0b00000000_00000100_00000000_00000001_00000000_00000000_00000000_00000000 & diag_up_mask; assert_eq!(0b00000000_00000100_00000010_00000000_00000000_00000000_00000000_00000000, bitmask.diag_up_attack_masks[index][util::kindergarten_transform_rank_diag(occupy_mask) as usize]); } #[test] fn test_diagdown_masks() { init(); let bitmask = get_bitmask(); let index = util::map_sqr_notation_to_index("g2"); let diag_down_mask = bitmask.diag_down_masks[index]; let occupy_mask = 0b00000000_00000000_00000000_00000000_00010000_00000000_01000000_00000000 & diag_down_mask; assert_eq!(0b00000000_00000000_00000000_00000000_00010000_00100000_00000000_10000000, bitmask.diag_down_attack_masks[index][util::kindergarten_transform_rank_diag(occupy_mask) as usize]); } #[test] fn test_vertical_masks() { init(); let bitmask = get_bitmask(); let index = util::map_sqr_notation_to_index("e4"); let occupy_mask = 0b00000000_00000000_00010000_00000000_00010000_00000000_00000000_00010000; assert_eq!(0b00000000_00000000_00010000_00010000_00000000_00010000_00010000_00010000, bitmask.vertical_attack_masks[index][util::kindergarten_transform_file(occupy_mask, index) as usize]); } #[test] fn test_vertical_masks1() { init(); let bitmask = get_bitmask(); let index = util::map_sqr_notation_to_index("h2"); let occupy_mask = 0b00000000_00000000_00000000_00000000_10000000_00000000_10000000_00000000; assert_eq!(0b00000000_00000000_00000000_00000000_10000000_10000000_00000000_10000000, bitmask.vertical_attack_masks[index][util::kindergarten_transform_file(occupy_mask, index) as usize]); } }
use std::{ future::Future, io::{self, ErrorKind}, pin::Pin, }; use actix_http::{body::BoxBody, error::PayloadError}; use actix_web::{ dev::Payload, error::JsonPayloadError, http, http::{Method, StatusCode}, Error, FromRequest, HttpRequest, HttpResponse, Responder, Result, }; use async_graphql::{http::MultipartOptions, ParseRequestError}; use futures_util::{ future::{self, FutureExt}, StreamExt, TryStreamExt, }; /// Extractor for GraphQL request. /// /// `async_graphql::http::MultipartOptions` allows to configure extraction /// process. pub struct GraphQLRequest(pub async_graphql::Request); impl GraphQLRequest { /// Unwraps the value to `async_graphql::Request`. #[must_use] pub fn into_inner(self) -> async_graphql::Request { self.0 } } type BatchToRequestMapper = fn(<<GraphQLBatchRequest as FromRequest>::Future as Future>::Output) -> Result<GraphQLRequest>; impl FromRequest for GraphQLRequest { type Error = Error; type Future = future::Map<<GraphQLBatchRequest as FromRequest>::Future, BatchToRequestMapper>; fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { GraphQLBatchRequest::from_request(req, payload).map(|res| { Ok(Self( res?.0 .into_single() .map_err(actix_web::error::ErrorBadRequest)?, )) }) } } /// Extractor for GraphQL batch request. /// /// `async_graphql::http::MultipartOptions` allows to configure extraction /// process. pub struct GraphQLBatchRequest(pub async_graphql::BatchRequest); impl GraphQLBatchRequest { /// Unwraps the value to `async_graphql::BatchRequest`. #[must_use] pub fn into_inner(self) -> async_graphql::BatchRequest { self.0 } } impl FromRequest for GraphQLBatchRequest { type Error = Error; type Future = Pin<Box<dyn Future<Output = Result<GraphQLBatchRequest>>>>; fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { let config = req .app_data::<MultipartOptions>() .cloned() .unwrap_or_default(); if req.method() == Method::GET { let res = async_graphql::http::parse_query_string(req.query_string()) .map_err(|err| io::Error::new(ErrorKind::Other, err)); Box::pin(async move { Ok(Self(async_graphql::BatchRequest::Single(res?))) }) } else if req.method() == Method::POST { let content_type = req .headers() .get(http::header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()) .map(|value| value.to_string()); let (tx, rx) = async_channel::bounded(16); // Payload is !Send so we create indirection with a channel let mut payload = payload.take(); actix::spawn(async move { while let Some(item) = payload.next().await { if tx.send(item).await.is_err() { return; } } }); Box::pin(async move { Ok(GraphQLBatchRequest( async_graphql::http::receive_batch_body( content_type, rx.map_err(|e| match e { PayloadError::Incomplete(Some(e)) | PayloadError::Io(e) => e, PayloadError::Incomplete(None) => { io::Error::from(ErrorKind::UnexpectedEof) } PayloadError::EncodingCorrupted => io::Error::new( ErrorKind::InvalidData, "cannot decode content-encoding", ), PayloadError::Overflow => io::Error::new( ErrorKind::InvalidData, "a payload reached size limit", ), PayloadError::UnknownLength => { io::Error::new(ErrorKind::Other, "a payload length is unknown") } PayloadError::Http2Payload(e) if e.is_io() => e.into_io().unwrap(), PayloadError::Http2Payload(e) => io::Error::new(ErrorKind::Other, e), _ => io::Error::new(ErrorKind::Other, e), }) .into_async_read(), config, ) .await .map_err(|err| match err { ParseRequestError::PayloadTooLarge => { actix_web::error::ErrorPayloadTooLarge(err) } _ => actix_web::error::ErrorBadRequest(err), })?, )) }) } else { Box::pin(async move { Err(actix_web::error::ErrorMethodNotAllowed( "GraphQL only supports GET and POST requests", )) }) } } } /// Responder for a GraphQL response. /// /// This contains a batch response, but since regular responses are a type of /// batch response it works for both. pub struct GraphQLResponse(pub async_graphql::BatchResponse); impl From<async_graphql::Response> for GraphQLResponse { fn from(resp: async_graphql::Response) -> Self { Self(resp.into()) } } impl From<async_graphql::BatchResponse> for GraphQLResponse { fn from(resp: async_graphql::BatchResponse) -> Self { Self(resp) } } #[cfg(feature = "cbor")] mod cbor { use core::fmt; use actix_web::{http::StatusCode, ResponseError}; #[derive(Debug)] pub struct Error(pub serde_cbor::Error); impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl ResponseError for Error { fn status_code(&self) -> StatusCode { StatusCode::INTERNAL_SERVER_ERROR } } } impl Responder for GraphQLResponse { type Body = BoxBody; fn respond_to(self, req: &HttpRequest) -> HttpResponse { let mut builder = HttpResponse::build(StatusCode::OK); if self.0.is_ok() { if let Some(cache_control) = self.0.cache_control().value() { builder.append_header((http::header::CACHE_CONTROL, cache_control)); } } let accept = req .headers() .get(http::header::ACCEPT) .and_then(|val| val.to_str().ok()); let (ct, body) = match accept { // optional cbor support #[cfg(feature = "cbor")] // this avoids copy-pasting the mime type Some(ct @ "application/cbor") => ( ct, match serde_cbor::to_vec(&self.0) { Ok(body) => body, Err(e) => return HttpResponse::from_error(cbor::Error(e)), }, ), _ => ( "application/json", match serde_json::to_vec(&self.0) { Ok(body) => body, Err(e) => return HttpResponse::from_error(JsonPayloadError::Serialize(e)), }, ), }; let mut resp = builder.content_type(ct).body(body); for (name, value) in self.0.http_headers_iter() { resp.headers_mut().append(name, value); } resp } }
pub(crate) use _sha1::make_module; #[pymodule] mod _sha1 { use crate::hashlib::_hashlib::{local_sha1, HashArgs}; use crate::vm::{PyPayload, PyResult, VirtualMachine}; #[pyfunction] fn sha1(args: HashArgs, vm: &VirtualMachine) -> PyResult { Ok(local_sha1(args).into_pyobject(vm)) } }
use regex::Regex; use rustc_hash::FxHashSet as HashSet; use std::cmp; pub const INPUT: &str = include_str!("../input.txt"); pub fn parse_input(input: &str) -> Vec<Blueprint> { let regex_str = concat!( r"Blueprint (\d+): ", r"Each ore robot costs (\d+) ore. ", r"Each clay robot costs (\d+) ore. ", r"Each obsidian robot costs (\d+) ore and (\d+) clay. ", r"Each geode robot costs (\d+) ore and (\d+) obsidian." ); let regex = Regex::new(regex_str).unwrap(); regex .captures_iter(input) .map(|captures| { let id = captures[1].parse().unwrap(); let ore_collector_cost = Cost { amount: captures[2].parse().unwrap(), resource: Resource::Ore, }; let clay_collector_cost = Cost { amount: captures[3].parse().unwrap(), resource: Resource::Ore, }; let obsidian_collector_costs = [ Cost { amount: captures[4].parse().unwrap(), resource: Resource::Ore, }, Cost { amount: captures[5].parse().unwrap(), resource: Resource::Clay, }, ]; let geode_collector_costs = [ Cost { amount: captures[6].parse().unwrap(), resource: Resource::Ore, }, Cost { amount: captures[7].parse().unwrap(), resource: Resource::Obsidian, }, ]; Blueprint::new( id, Box::new([ore_collector_cost]), Box::new([clay_collector_cost]), Box::new(obsidian_collector_costs), Box::new(geode_collector_costs), ) }) .collect() } pub fn part_one(blueprints: &[Blueprint]) -> u32 { blueprints .iter() .map(|b| b.id * find_max_geode_count(b, 24)) .sum() } pub fn part_two(blueprints: &[Blueprint]) -> u32 { blueprints .iter() .take(3) .map(|b| find_max_geode_count(b, 32)) .product() } fn find_max_geode_count(blueprint: &Blueprint, time_limit: u32) -> u32 { let initial_state = State { remaining_time: time_limit, ore: ResourceState { amount: 0, collector_count: 1, }, ..Default::default() }; let mut max_geode_count = 0; let mut seen = HashSet::default(); let mut states = vec![initial_state]; while let Some(state) = states.pop() { for r in Resource::iter() { let collector_count = state.resource(r).collector_count; let ResourceBlueprint { collector_costs, max_useful_collectors, } = blueprint.resource(r); let capped = max_useful_collectors.map_or(false, |c| collector_count >= c); if capped { continue; } let time_to_afford = state.time_to_afford(collector_costs); if time_to_afford.is_none() { continue; } let time_to_build = 1 + time_to_afford.unwrap(); if time_to_build >= state.remaining_time { let final_geode_count = state.geode.amount + state.remaining_time * state.geode.collector_count; max_geode_count = cmp::max(max_geode_count, final_geode_count); continue; } let mut new_state = state.clone(); new_state.remaining_time -= time_to_build; for r in Resource::iter() { new_state.resource_mut(r).amount += time_to_build * state.resource(r).collector_count; } for cost in collector_costs.iter() { new_state.resource_mut(cost.resource).amount -= cost.amount; } new_state.resource_mut(r).collector_count += 1; if !seen.contains(&new_state) && new_state.upper_bound_geode_count() > max_geode_count { seen.insert(new_state.clone()); states.push(new_state); } } } max_geode_count } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Cost { amount: u32, resource: Resource, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Resource { Ore, Clay, Obsidian, Geode, } impl Resource { fn iter() -> impl Iterator<Item = Resource> { [ Resource::Ore, Resource::Clay, Resource::Obsidian, Resource::Geode, ] .into_iter() } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Blueprint { id: u32, ore: ResourceBlueprint, clay: ResourceBlueprint, obsidian: ResourceBlueprint, geode: ResourceBlueprint, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct ResourceBlueprint { collector_costs: Box<[Cost]>, max_useful_collectors: Option<u32>, } impl Blueprint { fn new( id: u32, ore_collector_costs: Box<[Cost]>, clay_collector_costs: Box<[Cost]>, obsidian_collector_costs: Box<[Cost]>, geode_collector_costs: Box<[Cost]>, ) -> Self { let all_costs = [ ore_collector_costs.iter().copied(), clay_collector_costs.iter().copied(), obsidian_collector_costs.iter().copied(), geode_collector_costs.iter().copied(), ] .into_iter() .flatten() .collect::<Vec<_>>(); let max_useful_collectors = |r| { all_costs .iter() .filter(|c| c.resource == r) .map(|c| c.amount) .max() }; Blueprint { id, ore: ResourceBlueprint { collector_costs: ore_collector_costs, max_useful_collectors: max_useful_collectors(Resource::Ore), }, clay: ResourceBlueprint { collector_costs: clay_collector_costs, max_useful_collectors: max_useful_collectors(Resource::Clay), }, obsidian: ResourceBlueprint { collector_costs: obsidian_collector_costs, max_useful_collectors: max_useful_collectors(Resource::Obsidian), }, geode: ResourceBlueprint { collector_costs: geode_collector_costs, max_useful_collectors: max_useful_collectors(Resource::Geode), }, } } fn resource(&self, resource: Resource) -> &ResourceBlueprint { match resource { Resource::Ore => &self.ore, Resource::Clay => &self.clay, Resource::Obsidian => &self.obsidian, Resource::Geode => &self.geode, } } } #[derive(Debug, Clone, PartialEq, Eq, Hash, Default)] struct State { remaining_time: u32, ore: ResourceState, clay: ResourceState, obsidian: ResourceState, geode: ResourceState, } #[derive(Debug, Clone, PartialEq, Eq, Hash, Default)] struct ResourceState { amount: u32, collector_count: u32, } impl State { fn resource(&self, resource: Resource) -> &ResourceState { match resource { Resource::Ore => &self.ore, Resource::Clay => &self.clay, Resource::Obsidian => &self.obsidian, Resource::Geode => &self.geode, } } fn resource_mut(&mut self, resource: Resource) -> &mut ResourceState { match resource { Resource::Ore => &mut self.ore, Resource::Clay => &mut self.clay, Resource::Obsidian => &mut self.obsidian, Resource::Geode => &mut self.geode, } } fn time_to_afford(&self, costs: &[Cost]) -> Option<u32> { let times = costs .iter() .map(|c| { let amount = self.resource(c.resource).amount; let collector_count = self.resource(c.resource).collector_count; if amount >= c.amount { return Some(0); } else if collector_count == 0 { return None; } let needed = c.amount - amount; let t = if needed % collector_count == 0 { needed / collector_count } else { needed / collector_count + 1 }; Some(t) }) .collect::<Option<Vec<_>>>()?; times.into_iter().max() } fn upper_bound_geode_count(&self) -> u32 { let mut upper_bound = self.geode.amount; for m in 0..self.remaining_time { upper_bound += self.geode.collector_count + m; } upper_bound } } #[cfg(test)] mod test { use super::*; #[test] fn test_part_one() { let blueprints = parse_input(INPUT); assert_eq!(part_one(&blueprints), 1659); } #[test] fn test_part_two() { let blueprints = parse_input(INPUT); assert_eq!(part_two(&blueprints), 6804); } }
//! This crate contains the API for the protocol of the analytics server. `Event` is the type which is sent to the //! analytics server. Here are some examples of `Event` structures using different `Message` variants: //! //! `{"received_time":"2017-04-11T04:29:16.064185621Z","serviced_time":"2017-04-11T04:29:16.064188591Z","message":{"AllChannels":{"total_channels":5,"success":true}}}` //! //! `{"received_time":"2017-04-11T04:29:16.064324152Z","serviced_time":"2017-04-11T04:29:16.064324934Z","message":{"MostRecentMessages":{"num_messages":8,"success":true}}}` //! //! `{"received_time":"2017-04-11T04:29:16.064422755Z","serviced_time":"2017-04-11T04:29:16.064423786Z","message":{"MoreMessages":{"num_requested":5,"num_sent":0,"success":false}}}` //! //! `{"received_time":"2017-04-11T04:29:16.064537018Z","serviced_time":"2017-04-11T04:29:16.064537698Z","message":{"SendMessage":{"message_length":87,"success":true}}}` //! //! `{"received_time":"2017-04-11T04:29:16.064613838Z","serviced_time":"2017-04-11T04:29:16.064614475Z","message":{"CreateChannel":{"channel_name_length":7,"success":true}}}` use chrono::{UTC, DateTime}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum Message { /// JSON Example: /// `{"received_time":"2017-04-11T04:29:16.064185621Z","serviced_time":"2017-04-11T04:29:16.064188591Z","message":{"AllChannels":{"total_channels":5,"success":true}}}` AllChannels { total_channels: usize, success: bool, }, /// JSON Example: /// `{"received_time":"2017-04-11T04:29:16.064324152Z","serviced_time":"2017-04-11T04:29:16.064324934Z","message":{"MostRecentMessages":{"num_messages":8,"success":true}}}` MostRecentMessages { num_messages: usize, success: bool }, /// JSON Example: /// `{"received_time":"2017-04-11T04:29:16.064422755Z","serviced_time":"2017-04-11T04:29:16.064423786Z","message":{"MoreMessages":{"num_requested":5,"num_sent":0,"success":false}}}` MoreMessages { num_requested: usize, num_sent: usize, success: bool, }, /// JSON Example: /// `{"received_time":"2017-04-11T04:29:16.064537018Z","serviced_time":"2017-04-11T04:29:16.064537698Z","message":{"SendMessage":{"message_length":87,"success":true}}}` SendMessage { message_length: usize, success: bool, }, /// JSON Example: /// `{"received_time":"2017-04-11T04:29:16.064613838Z","serviced_time":"2017-04-11T04:29:16.064614475Z","message":{"CreateChannel":{"channel_name_length":7,"success":true}}}` CreateChannel { channel_name_length: usize, success: bool, }, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Event { pub received_time: DateTime<UTC>, pub serviced_time: DateTime<UTC>, pub message: Message, }
use std::io; fn main() { println!("Welcome to Dhrumil's epic Leap Year validator!"); loop { println!("Which year would you like to try: "); let mut str_year = String::new(); io::stdin().read_line(&mut str_year) .expect("Failed to read line"); let year: u32 = match str_year.trim().parse() { Ok(num) => num, Err(_) => { println!("That was not a number. Please give me the leap year you'd like to verify."); break; } }; let mut flag = false; if year % 4 == 0 { flag = true; if year % 100 == 0 && !(year % 400 == 0) { flag = false; } } if flag == true { println!("True. This year is a leap year"); } else { println!("False. This year isn't a leap year.") } println!("Would you like to test more years? y/n"); let mut again = String::new(); io::stdin().read_line(&mut again) .expect("Failed to read line"); if again.trim() == "N" || again.trim() == "n" || again.trim() == "no" || again.trim() == "No" { println!("Thanks for checking out my leap year validator!"); break; } } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::{ font_catalog::TypefaceInAssetIndex, font_db::FontDb, FontCatalog, FontPackageListing, FontSets, }, failure::Error, font_info::FontInfoLoader, manifest::{v2, FontManifestWrapper}, std::path::Path, }; /// Builds a `FontDb` and then generates a manifest from all of the font metadata that has been /// loaded. /// /// For test coverage, see integration tests. pub(crate) fn generate_manifest( font_catalog: FontCatalog, font_pkgs: FontPackageListing, font_sets: FontSets, font_info_loader: impl FontInfoLoader, font_dir: impl AsRef<Path>, ) -> Result<FontManifestWrapper, Error> { let db = FontDb::new(font_catalog, font_pkgs, font_sets, font_info_loader, font_dir)?; let manifest = v2::FontsManifest { families: db .iter_families() .map(|fi_family| v2::Family { name: fi_family.name.clone(), aliases: fi_family .aliases .iter() .cloned() .map(|string_or_alias_set| string_or_alias_set.into()) .collect(), generic_family: fi_family.generic_family, fallback: fi_family.fallback, assets: db .iter_assets(fi_family) .map(|fi_asset| v2::Asset { file_name: fi_asset.file_name.clone(), location: db.get_asset_location(fi_asset), typefaces: fi_asset .typefaces .values() .map(|fi_typeface| v2::Typeface { index: fi_typeface.index, languages: fi_typeface.languages.clone(), style: fi_typeface.style.clone(), code_points: db .get_code_points( fi_asset, TypefaceInAssetIndex(fi_typeface.index), ) .clone(), }) .collect(), }) .collect(), }) .collect(), }; Ok(FontManifestWrapper::Version2(manifest)) }
#[cfg(feature = "glob")] use crate::glob::*; use crate::{VMetadata, VPath}; use async_stream::{stream, try_stream}; use futures_lite::{Stream, StreamExt}; // use futures_core::{future::BoxFuture, Stream, TryStream}; // use futures_util::{pin_mut, StreamExt}; use std::future::Future; use std::io; use std::pin::Pin; pub async fn walkdir<V: VPath + 'static + std::marker::Unpin>( path: V, ) -> io::Result<Pin<Box<dyn Stream<Item = io::Result<V>> + Send>>> where V::ReadDir: Send + std::marker::Unpin, V::Metadata: Send, { walkdir_match::<V, _>(path, |_| true).await } pub fn walkdir_match<V: VPath + 'static + std::marker::Unpin, F>( path: V, check: F, ) -> Pin<Box<Future<Outptut = io::Result<Pin<Box<dyn Stream<Item = io::Result<V>> + Send>>>>>> where F: Sync + Send + 'static + Clone + Fn(&V) -> bool, V::ReadDir: Send + std::marker::Unpin, V::Metadata: Send, { let out = async move { let readdir = path.read_dir().await?; let out = try_stream! { while let Some(value) = readdir.next().await { let value = value?; let meta = value.metadata().await?; if meta.is_dir() { let readdir = walkdir_match::<V, F>(value, check.clone()).await?; // pin_mut!(readdir); while let Some(value) = readdir.next().await { let value = value?; if check(&value) { yield value; } } } else if meta.is_file() { if check(&value) { yield value; } } else { continue; } } }; Ok(Box::pin(out) as Pin<Box<dyn Stream<Item = io::Result<V>> + Send>>) }; Box::pin(out) //Ok(Box::pin(out) as Pin<Box<dyn Stream<Item = io::Result<V>> + Send>>) } #[cfg(feature = "glob")] pub fn glob<P: VPath>( path: P, glob: Globber, ) -> BoxFuture<'static, io::Result<Pin<Box<dyn Stream<Item = io::Result<P>> + Send>>>> where P: VPath + 'static + std::marker::Unpin, P::ReadDir: Send, P::Metadata: Send, { walkdir_match(path, move |path| glob.is_match(path)) } #[cfg(test)] mod tests { use super::*; use crate::*; // #[tokio::test] // async fn test_walkdir() { // let fs = PhysicalFS::new("../").unwrap(); // let path = fs.path("."); // let mut readdir = walkdir(path).await.unwrap(); // while let Some(path) = readdir.next().await { // //println!("TEST TEST {:?}", path); // } // } // #[cfg(feature = "glob")] // #[tokio::test] // async fn test_glob() { // let fs = PhysicalFS::new("../../").unwrap(); // let path = fs.path("."); // println!("PATH {:?}", path); // let mut readdir = glob(path, Globber::new("**/*.toml")).await.unwrap(); // while let Some(path) = readdir.next().await { // println!("TEST TEST {:?}", path); // } // } }
use libc::{c_char}; use std::ffi::{CString, CStr}; use ffi::support::{CVec}; use ffi::support::IntoCVec; use speller::Speller; #[no_mangle] pub extern fn speller_vec_free(ptr: *mut CVec<*mut c_char>) { unsafe { let vec = Vec::<*mut c_char>::from_c_vec_raw(ptr); for c_str in vec.into_iter() { CString::from_raw(c_str); } } } #[no_mangle] pub extern fn speller_suggest(handle: *mut Speller, raw_word: *mut c_char) -> *const CVec<*const c_char> { let c_str = unsafe { CStr::from_ptr(raw_word) }; let word = c_str.to_str().unwrap(); let speller = unsafe { &mut *handle }; let suggestions: Vec<String> = speller.suggest(&word); let raw_suggestions: Vec<*mut c_char> = suggestions.into_iter() .map(|s| CString::new(s).unwrap().into_raw() as *mut c_char) .collect(); unsafe { raw_suggestions.into_c_vec_raw() as *const _ } } /* #[no_mangle] pub extern fn speller_new() -> *const Speller { let x = Box::new(Speller {}); Box::into_raw(x) } */ #[no_mangle] pub extern fn speller_free(ptr: *mut Speller) { unsafe { Box::from_raw(ptr) }; } #[no_mangle] pub extern fn it_works() -> bool { true }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(feature = "Win32_Foundation")] pub fn AccNotifyTouchInteraction(hwndapp: super::super::Foundation::HWND, hwndtarget: super::super::Foundation::HWND, pttarget: super::super::Foundation::POINT) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn AccSetRunningUtilityState(hwndapp: super::super::Foundation::HWND, dwutilitystatemask: u32, dwutilitystate: ACC_UTILITY_STATE_FLAGS) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn AccessibleChildren(pacccontainer: IAccessible, ichildstart: i32, cchildren: i32, rgvarchildren: *mut super::super::System::Com::VARIANT, pcobtained: *mut i32) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn AccessibleObjectFromEvent(hwnd: super::super::Foundation::HWND, dwid: u32, dwchildid: u32, ppacc: *mut IAccessible, pvarchild: *mut super::super::System::Com::VARIANT) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn AccessibleObjectFromPoint(ptscreen: super::super::Foundation::POINT, ppacc: *mut IAccessible, pvarchild: *mut super::super::System::Com::VARIANT) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn AccessibleObjectFromWindow(hwnd: super::super::Foundation::HWND, dwid: u32, riid: *const ::windows_sys::core::GUID, ppvobject: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn CreateStdAccessibleObject(hwnd: super::super::Foundation::HWND, idobject: i32, riid: *const ::windows_sys::core::GUID, ppvobject: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn CreateStdAccessibleProxyA(hwnd: super::super::Foundation::HWND, pclassname: super::super::Foundation::PSTR, idobject: i32, riid: *const ::windows_sys::core::GUID, ppvobject: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn CreateStdAccessibleProxyW(hwnd: super::super::Foundation::HWND, pclassname: super::super::Foundation::PWSTR, idobject: i32, riid: *const ::windows_sys::core::GUID, ppvobject: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; pub fn DockPattern_SetDockPosition(hobj: HUIAPATTERNOBJECT, dockposition: DockPosition) -> ::windows_sys::core::HRESULT; pub fn ExpandCollapsePattern_Collapse(hobj: HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; pub fn ExpandCollapsePattern_Expand(hobj: HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; pub fn GetOleaccVersionInfo(pver: *mut u32, pbuild: *mut u32); #[cfg(feature = "Win32_Foundation")] pub fn GetRoleTextA(lrole: u32, lpszrole: super::super::Foundation::PSTR, cchrolemax: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn GetRoleTextW(lrole: u32, lpszrole: super::super::Foundation::PWSTR, cchrolemax: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn GetStateTextA(lstatebit: u32, lpszstate: super::super::Foundation::PSTR, cchstate: u32) -> u32; #[cfg(feature = "Win32_Foundation")] pub fn GetStateTextW(lstatebit: u32, lpszstate: super::super::Foundation::PWSTR, cchstate: u32) -> u32; pub fn GridPattern_GetItem(hobj: HUIAPATTERNOBJECT, row: i32, column: i32, presult: *mut HUIANODE) -> ::windows_sys::core::HRESULT; pub fn InvokePattern_Invoke(hobj: HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn IsWinEventHookInstalled(event: u32) -> super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn ItemContainerPattern_FindItemByProperty(hobj: HUIAPATTERNOBJECT, hnodestartafter: HUIANODE, propertyid: i32, value: super::super::System::Com::VARIANT, pfound: *mut HUIANODE) -> ::windows_sys::core::HRESULT; pub fn LegacyIAccessiblePattern_DoDefaultAction(hobj: HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; pub fn LegacyIAccessiblePattern_GetIAccessible(hobj: HUIAPATTERNOBJECT, paccessible: *mut IAccessible) -> ::windows_sys::core::HRESULT; pub fn LegacyIAccessiblePattern_Select(hobj: HUIAPATTERNOBJECT, flagsselect: i32) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn LegacyIAccessiblePattern_SetValue(hobj: HUIAPATTERNOBJECT, szvalue: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn LresultFromObject(riid: *const ::windows_sys::core::GUID, wparam: super::super::Foundation::WPARAM, punk: ::windows_sys::core::IUnknown) -> super::super::Foundation::LRESULT; #[cfg(feature = "Win32_Foundation")] pub fn MultipleViewPattern_GetViewName(hobj: HUIAPATTERNOBJECT, viewid: i32, ppstr: *mut super::super::Foundation::BSTR) -> ::windows_sys::core::HRESULT; pub fn MultipleViewPattern_SetCurrentView(hobj: HUIAPATTERNOBJECT, viewid: i32) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn NotifyWinEvent(event: u32, hwnd: super::super::Foundation::HWND, idobject: i32, idchild: i32); #[cfg(feature = "Win32_Foundation")] pub fn ObjectFromLresult(lresult: super::super::Foundation::LRESULT, riid: *const ::windows_sys::core::GUID, wparam: super::super::Foundation::WPARAM, ppvobject: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; pub fn RangeValuePattern_SetValue(hobj: HUIAPATTERNOBJECT, val: f64) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_WindowsAndMessaging"))] pub fn RegisterPointerInputTarget(hwnd: super::super::Foundation::HWND, pointertype: super::WindowsAndMessaging::POINTER_INPUT_TYPE) -> super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_WindowsAndMessaging"))] pub fn RegisterPointerInputTargetEx(hwnd: super::super::Foundation::HWND, pointertype: super::WindowsAndMessaging::POINTER_INPUT_TYPE, fobserve: super::super::Foundation::BOOL) -> super::super::Foundation::BOOL; pub fn ScrollItemPattern_ScrollIntoView(hobj: HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; pub fn ScrollPattern_Scroll(hobj: HUIAPATTERNOBJECT, horizontalamount: ScrollAmount, verticalamount: ScrollAmount) -> ::windows_sys::core::HRESULT; pub fn ScrollPattern_SetScrollPercent(hobj: HUIAPATTERNOBJECT, horizontalpercent: f64, verticalpercent: f64) -> ::windows_sys::core::HRESULT; pub fn SelectionItemPattern_AddToSelection(hobj: HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; pub fn SelectionItemPattern_RemoveFromSelection(hobj: HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; pub fn SelectionItemPattern_Select(hobj: HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn SetWinEventHook(eventmin: u32, eventmax: u32, hmodwineventproc: super::super::Foundation::HINSTANCE, pfnwineventproc: WINEVENTPROC, idprocess: u32, idthread: u32, dwflags: u32) -> HWINEVENTHOOK; pub fn SynchronizedInputPattern_Cancel(hobj: HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; pub fn SynchronizedInputPattern_StartListening(hobj: HUIAPATTERNOBJECT, inputtype: SynchronizedInputType) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_System_Com")] pub fn TextPattern_GetSelection(hobj: HUIAPATTERNOBJECT, pretval: *mut *mut super::super::System::Com::SAFEARRAY) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_System_Com")] pub fn TextPattern_GetVisibleRanges(hobj: HUIAPATTERNOBJECT, pretval: *mut *mut super::super::System::Com::SAFEARRAY) -> ::windows_sys::core::HRESULT; pub fn TextPattern_RangeFromChild(hobj: HUIAPATTERNOBJECT, hnodechild: HUIANODE, pretval: *mut HUIATEXTRANGE) -> ::windows_sys::core::HRESULT; pub fn TextPattern_RangeFromPoint(hobj: HUIAPATTERNOBJECT, point: UiaPoint, pretval: *mut HUIATEXTRANGE) -> ::windows_sys::core::HRESULT; pub fn TextPattern_get_DocumentRange(hobj: HUIAPATTERNOBJECT, pretval: *mut HUIATEXTRANGE) -> ::windows_sys::core::HRESULT; pub fn TextPattern_get_SupportedTextSelection(hobj: HUIAPATTERNOBJECT, pretval: *mut SupportedTextSelection) -> ::windows_sys::core::HRESULT; pub fn TextRange_AddToSelection(hobj: HUIATEXTRANGE) -> ::windows_sys::core::HRESULT; pub fn TextRange_Clone(hobj: HUIATEXTRANGE, pretval: *mut HUIATEXTRANGE) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn TextRange_Compare(hobj: HUIATEXTRANGE, range: HUIATEXTRANGE, pretval: *mut super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT; pub fn TextRange_CompareEndpoints(hobj: HUIATEXTRANGE, endpoint: TextPatternRangeEndpoint, targetrange: HUIATEXTRANGE, targetendpoint: TextPatternRangeEndpoint, pretval: *mut i32) -> ::windows_sys::core::HRESULT; pub fn TextRange_ExpandToEnclosingUnit(hobj: HUIATEXTRANGE, unit: TextUnit) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn TextRange_FindAttribute(hobj: HUIATEXTRANGE, attributeid: i32, val: super::super::System::Com::VARIANT, backward: super::super::Foundation::BOOL, pretval: *mut HUIATEXTRANGE) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn TextRange_FindText(hobj: HUIATEXTRANGE, text: super::super::Foundation::BSTR, backward: super::super::Foundation::BOOL, ignorecase: super::super::Foundation::BOOL, pretval: *mut HUIATEXTRANGE) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn TextRange_GetAttributeValue(hobj: HUIATEXTRANGE, attributeid: i32, pretval: *mut super::super::System::Com::VARIANT) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_System_Com")] pub fn TextRange_GetBoundingRectangles(hobj: HUIATEXTRANGE, pretval: *mut *mut super::super::System::Com::SAFEARRAY) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_System_Com")] pub fn TextRange_GetChildren(hobj: HUIATEXTRANGE, pretval: *mut *mut super::super::System::Com::SAFEARRAY) -> ::windows_sys::core::HRESULT; pub fn TextRange_GetEnclosingElement(hobj: HUIATEXTRANGE, pretval: *mut HUIANODE) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn TextRange_GetText(hobj: HUIATEXTRANGE, maxlength: i32, pretval: *mut super::super::Foundation::BSTR) -> ::windows_sys::core::HRESULT; pub fn TextRange_Move(hobj: HUIATEXTRANGE, unit: TextUnit, count: i32, pretval: *mut i32) -> ::windows_sys::core::HRESULT; pub fn TextRange_MoveEndpointByRange(hobj: HUIATEXTRANGE, endpoint: TextPatternRangeEndpoint, targetrange: HUIATEXTRANGE, targetendpoint: TextPatternRangeEndpoint) -> ::windows_sys::core::HRESULT; pub fn TextRange_MoveEndpointByUnit(hobj: HUIATEXTRANGE, endpoint: TextPatternRangeEndpoint, unit: TextUnit, count: i32, pretval: *mut i32) -> ::windows_sys::core::HRESULT; pub fn TextRange_RemoveFromSelection(hobj: HUIATEXTRANGE) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn TextRange_ScrollIntoView(hobj: HUIATEXTRANGE, aligntotop: super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT; pub fn TextRange_Select(hobj: HUIATEXTRANGE) -> ::windows_sys::core::HRESULT; pub fn TogglePattern_Toggle(hobj: HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; pub fn TransformPattern_Move(hobj: HUIAPATTERNOBJECT, x: f64, y: f64) -> ::windows_sys::core::HRESULT; pub fn TransformPattern_Resize(hobj: HUIAPATTERNOBJECT, width: f64, height: f64) -> ::windows_sys::core::HRESULT; pub fn TransformPattern_Rotate(hobj: HUIAPATTERNOBJECT, degrees: f64) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub fn UiaAddEvent(hnode: HUIANODE, eventid: i32, pcallback: *mut UiaEventCallback, scope: TreeScope, pproperties: *mut i32, cproperties: i32, prequest: *mut UiaCacheRequest, phevent: *mut HUIAEVENT) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn UiaClientsAreListening() -> super::super::Foundation::BOOL; pub fn UiaDisconnectAllProviders() -> ::windows_sys::core::HRESULT; pub fn UiaDisconnectProvider(pprovider: IRawElementProviderSimple) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn UiaEventAddWindow(hevent: HUIAEVENT, hwnd: super::super::Foundation::HWND) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn UiaEventRemoveWindow(hevent: HUIAEVENT, hwnd: super::super::Foundation::HWND) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub fn UiaFind(hnode: HUIANODE, pparams: *mut UiaFindParams, prequest: *mut UiaCacheRequest, pprequesteddata: *mut *mut super::super::System::Com::SAFEARRAY, ppoffsets: *mut *mut super::super::System::Com::SAFEARRAY, pptreestructures: *mut *mut super::super::System::Com::SAFEARRAY) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn UiaGetErrorDescription(pdescription: *mut super::super::Foundation::BSTR) -> super::super::Foundation::BOOL; pub fn UiaGetPatternProvider(hnode: HUIANODE, patternid: i32, phobj: *mut HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn UiaGetPropertyValue(hnode: HUIANODE, propertyid: i32, pvalue: *mut super::super::System::Com::VARIANT) -> ::windows_sys::core::HRESULT; pub fn UiaGetReservedMixedAttributeValue(punkmixedattributevalue: *mut ::windows_sys::core::IUnknown) -> ::windows_sys::core::HRESULT; pub fn UiaGetReservedNotSupportedValue(punknotsupportedvalue: *mut ::windows_sys::core::IUnknown) -> ::windows_sys::core::HRESULT; pub fn UiaGetRootNode(phnode: *mut HUIANODE) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_System_Com")] pub fn UiaGetRuntimeId(hnode: HUIANODE, pruntimeid: *mut *mut super::super::System::Com::SAFEARRAY) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub fn UiaGetUpdatedCache(hnode: HUIANODE, prequest: *mut UiaCacheRequest, normalizestate: NormalizeState, pnormalizecondition: *mut UiaCondition, pprequesteddata: *mut *mut super::super::System::Com::SAFEARRAY, pptreestructure: *mut super::super::Foundation::BSTR) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn UiaHPatternObjectFromVariant(pvar: *mut super::super::System::Com::VARIANT, phobj: *mut HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn UiaHTextRangeFromVariant(pvar: *mut super::super::System::Com::VARIANT, phtextrange: *mut HUIATEXTRANGE) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn UiaHUiaNodeFromVariant(pvar: *mut super::super::System::Com::VARIANT, phnode: *mut HUIANODE) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn UiaHasServerSideProvider(hwnd: super::super::Foundation::HWND) -> super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn UiaHostProviderFromHwnd(hwnd: super::super::Foundation::HWND, ppprovider: *mut IRawElementProviderSimple) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn UiaIAccessibleFromProvider(pprovider: IRawElementProviderSimple, dwflags: u32, ppaccessible: *mut IAccessible, pvarchild: *mut super::super::System::Com::VARIANT) -> ::windows_sys::core::HRESULT; pub fn UiaLookupId(r#type: AutomationIdentifierType, pguid: *const ::windows_sys::core::GUID) -> i32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub fn UiaNavigate(hnode: HUIANODE, direction: NavigateDirection, pcondition: *mut UiaCondition, prequest: *mut UiaCacheRequest, pprequesteddata: *mut *mut super::super::System::Com::SAFEARRAY, pptreestructure: *mut super::super::Foundation::BSTR) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub fn UiaNodeFromFocus(prequest: *mut UiaCacheRequest, pprequesteddata: *mut *mut super::super::System::Com::SAFEARRAY, pptreestructure: *mut super::super::Foundation::BSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn UiaNodeFromHandle(hwnd: super::super::Foundation::HWND, phnode: *mut HUIANODE) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub fn UiaNodeFromPoint(x: f64, y: f64, prequest: *mut UiaCacheRequest, pprequesteddata: *mut *mut super::super::System::Com::SAFEARRAY, pptreestructure: *mut super::super::Foundation::BSTR) -> ::windows_sys::core::HRESULT; pub fn UiaNodeFromProvider(pprovider: IRawElementProviderSimple, phnode: *mut HUIANODE) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn UiaNodeRelease(hnode: HUIANODE) -> super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn UiaPatternRelease(hobj: HUIAPATTERNOBJECT) -> super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn UiaProviderForNonClient(hwnd: super::super::Foundation::HWND, idobject: i32, idchild: i32, ppprovider: *mut IRawElementProviderSimple) -> ::windows_sys::core::HRESULT; pub fn UiaProviderFromIAccessible(paccessible: IAccessible, idchild: i32, dwflags: u32, ppprovider: *mut IRawElementProviderSimple) -> ::windows_sys::core::HRESULT; pub fn UiaRaiseActiveTextPositionChangedEvent(provider: IRawElementProviderSimple, textrange: ITextRangeProvider) -> ::windows_sys::core::HRESULT; pub fn UiaRaiseAsyncContentLoadedEvent(pprovider: IRawElementProviderSimple, asynccontentloadedstate: AsyncContentLoadedState, percentcomplete: f64) -> ::windows_sys::core::HRESULT; pub fn UiaRaiseAutomationEvent(pprovider: IRawElementProviderSimple, id: i32) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn UiaRaiseAutomationPropertyChangedEvent(pprovider: IRawElementProviderSimple, id: i32, oldvalue: super::super::System::Com::VARIANT, newvalue: super::super::System::Com::VARIANT) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub fn UiaRaiseChangesEvent(pprovider: IRawElementProviderSimple, eventidcount: i32, puiachanges: *mut UiaChangeInfo) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn UiaRaiseNotificationEvent(provider: IRawElementProviderSimple, notificationkind: NotificationKind, notificationprocessing: NotificationProcessing, displaystring: super::super::Foundation::BSTR, activityid: super::super::Foundation::BSTR) -> ::windows_sys::core::HRESULT; pub fn UiaRaiseStructureChangedEvent(pprovider: IRawElementProviderSimple, structurechangetype: StructureChangeType, pruntimeid: *mut i32, cruntimeidlen: i32) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_System_Com")] pub fn UiaRaiseTextEditTextChangedEvent(pprovider: IRawElementProviderSimple, texteditchangetype: TextEditChangeType, pchangeddata: *mut super::super::System::Com::SAFEARRAY) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub fn UiaRegisterProviderCallback(pcallback: *mut UiaProviderCallback); pub fn UiaRemoveEvent(hevent: HUIAEVENT) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn UiaReturnRawElementProvider(hwnd: super::super::Foundation::HWND, wparam: super::super::Foundation::WPARAM, lparam: super::super::Foundation::LPARAM, el: IRawElementProviderSimple) -> super::super::Foundation::LRESULT; pub fn UiaSetFocus(hnode: HUIANODE) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn UiaTextRangeRelease(hobj: HUIATEXTRANGE) -> super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn UnhookWinEvent(hwineventhook: HWINEVENTHOOK) -> super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_WindowsAndMessaging"))] pub fn UnregisterPointerInputTarget(hwnd: super::super::Foundation::HWND, pointertype: super::WindowsAndMessaging::POINTER_INPUT_TYPE) -> super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_WindowsAndMessaging"))] pub fn UnregisterPointerInputTargetEx(hwnd: super::super::Foundation::HWND, pointertype: super::WindowsAndMessaging::POINTER_INPUT_TYPE) -> super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn ValuePattern_SetValue(hobj: HUIAPATTERNOBJECT, pval: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; pub fn VirtualizedItemPattern_Realize(hobj: HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn WindowFromAccessibleObject(param0: IAccessible, phwnd: *mut super::super::Foundation::HWND) -> ::windows_sys::core::HRESULT; pub fn WindowPattern_Close(hobj: HUIAPATTERNOBJECT) -> ::windows_sys::core::HRESULT; pub fn WindowPattern_SetWindowVisualState(hobj: HUIAPATTERNOBJECT, state: WindowVisualState) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn WindowPattern_WaitForInputIdle(hobj: HUIAPATTERNOBJECT, milliseconds: i32, presult: *mut super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT; } #[repr(C)] pub struct ACCESSTIMEOUT { pub cbSize: u32, pub dwFlags: u32, pub iTimeOutMSec: u32, } impl ::core::marker::Copy for ACCESSTIMEOUT {} impl ::core::clone::Clone for ACCESSTIMEOUT { fn clone(&self) -> Self { *self } } pub type ACC_UTILITY_STATE_FLAGS = u32; pub const ANRUS_ON_SCREEN_KEYBOARD_ACTIVE: ACC_UTILITY_STATE_FLAGS = 1u32; pub const ANRUS_TOUCH_MODIFICATION_ACTIVE: ACC_UTILITY_STATE_FLAGS = 2u32; pub const ANRUS_PRIORITY_AUDIO_ACTIVE: ACC_UTILITY_STATE_FLAGS = 4u32; pub const ANRUS_PRIORITY_AUDIO_ACTIVE_NODUCK: ACC_UTILITY_STATE_FLAGS = 8u32; pub const ANRUS_PRIORITY_AUDIO_DYNAMIC_DUCK: u32 = 16u32; pub const AcceleratorKey_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1363699167, data2: 9559, data3: 19641, data4: [174, 237, 108, 237, 8, 76, 229, 44] }; pub const AccessKey_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 109214482, data2: 43001, data3: 18965, data4: [145, 124, 255, 165, 173, 62, 176, 167], }; pub type ActiveEnd = i32; pub const ActiveEnd_None: ActiveEnd = 0i32; pub const ActiveEnd_Start: ActiveEnd = 1i32; pub const ActiveEnd_End: ActiveEnd = 2i32; pub const ActiveTextPositionChanged_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2780864156, data2: 51069, data3: 20261, data4: [180, 145, 229, 187, 112, 23, 203, 212], }; pub type AnimationStyle = i32; pub const AnimationStyle_None: AnimationStyle = 0i32; pub const AnimationStyle_LasVegasLights: AnimationStyle = 1i32; pub const AnimationStyle_BlinkingBackground: AnimationStyle = 2i32; pub const AnimationStyle_SparkleText: AnimationStyle = 3i32; pub const AnimationStyle_MarchingBlackAnts: AnimationStyle = 4i32; pub const AnimationStyle_MarchingRedAnts: AnimationStyle = 5i32; pub const AnimationStyle_Shimmer: AnimationStyle = 6i32; pub const AnimationStyle_Other: AnimationStyle = -1i32; pub type AnnoScope = i32; pub const ANNO_THIS: AnnoScope = 0i32; pub const ANNO_CONTAINER: AnnoScope = 1i32; pub const AnnotationObjects_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 822677704, data2: 31854, data3: 20256, data4: [190, 205, 74, 175, 109, 25, 17, 86] }; pub const AnnotationType_AdvancedProofingIssue: i32 = 60020i32; pub const AnnotationType_Author: i32 = 60019i32; pub const AnnotationType_CircularReferenceError: i32 = 60022i32; pub const AnnotationType_Comment: i32 = 60003i32; pub const AnnotationType_ConflictingChange: i32 = 60018i32; pub const AnnotationType_DataValidationError: i32 = 60021i32; pub const AnnotationType_DeletionChange: i32 = 60012i32; pub const AnnotationType_EditingLockedChange: i32 = 60016i32; pub const AnnotationType_Endnote: i32 = 60009i32; pub const AnnotationType_ExternalChange: i32 = 60017i32; pub const AnnotationType_Footer: i32 = 60007i32; pub const AnnotationType_Footnote: i32 = 60010i32; pub const AnnotationType_FormatChange: i32 = 60014i32; pub const AnnotationType_FormulaError: i32 = 60004i32; pub const AnnotationType_GrammarError: i32 = 60002i32; pub const AnnotationType_Header: i32 = 60006i32; pub const AnnotationType_Highlighted: i32 = 60008i32; pub const AnnotationType_InsertionChange: i32 = 60011i32; pub const AnnotationType_Mathematics: i32 = 60023i32; pub const AnnotationType_MoveChange: i32 = 60013i32; pub const AnnotationType_Sensitive: i32 = 60024i32; pub const AnnotationType_SpellingError: i32 = 60001i32; pub const AnnotationType_TrackChanges: i32 = 60005i32; pub const AnnotationType_Unknown: i32 = 60000i32; pub const AnnotationType_UnsyncedChange: i32 = 60015i32; pub const AnnotationTypes_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1689722742, data2: 21444, data3: 18070, data4: [162, 25, 32, 233, 64, 201, 161, 118], }; pub const Annotation_AdvancedProofingIssue_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3670521644, data2: 49394, data3: 19332, data4: [185, 13, 95, 175, 192, 240, 239, 28], }; pub const Annotation_AnnotationTypeId_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 548292687, data2: 27119, data3: 19528, data4: [143, 91, 196, 147, 139, 32, 106, 199], }; pub const Annotation_AnnotationTypeName_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2608957586, data2: 23241, data3: 19193, data4: [170, 150, 245, 138, 119, 176, 88, 227], }; pub const Annotation_Author_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4049720231, data2: 63515, data3: 16680, data4: [177, 127, 113, 246, 144, 145, 69, 32], }; pub const Annotation_Author_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2052228194, data2: 40028, data3: 18947, data4: [169, 116, 139, 48, 122, 153, 55, 242], }; pub const Annotation_CircularReferenceError_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 633183476, data2: 5957, data3: 18009, data4: [186, 103, 114, 127, 3, 24, 198, 22] }; pub const Annotation_Comment_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4247771696, data2: 9907, data3: 19462, data4: [139, 199, 152, 241, 83, 46, 70, 253] }; pub const Annotation_ConflictingChange_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2561640450, data2: 20860, data3: 17823, data4: [175, 19, 1, 109, 63, 171, 135, 126] }; pub const Annotation_Custom_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2663917392, data2: 14641, data3: 18770, data4: [133, 188, 29, 191, 247, 138, 67, 227], }; pub const Annotation_DataValidationError_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3362037672, data2: 38773, data3: 17278, data4: [173, 70, 231, 9, 217, 60, 35, 67] }; pub const Annotation_DateTime_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2578827869, data2: 6863, data3: 16715, data4: [164, 208, 107, 53, 11, 4, 117, 120] }; pub const Annotation_DeletionChange_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3191692037, data2: 38173, data3: 17127, data4: [144, 29, 173, 200, 194, 207, 52, 208], }; pub const Annotation_EditingLockedChange_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3273604636, data2: 29731, data3: 19884, data4: [131, 72, 65, 240, 153, 255, 111, 100], }; pub const Annotation_Endnote_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1969582684, data2: 11673, data3: 18489, data4: [150, 13, 51, 211, 184, 102, 171, 165], }; pub const Annotation_ExternalChange_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1973443377, data2: 24337, data3: 17149, data4: [136, 125, 223, 160, 16, 219, 35, 146], }; pub const Annotation_Footer_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3437932614, data2: 6195, data3: 18346, data4: [128, 128, 112, 30, 208, 176, 200, 50], }; pub const Annotation_Footnote_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1038159393, data2: 16677, data3: 17115, data4: [134, 32, 190, 128, 131, 8, 6, 36] }; pub const Annotation_FormatChange_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3945034565, data2: 54513, data3: 16846, data4: [142, 82, 247, 155, 105, 99, 94, 72] }; pub const Annotation_FormulaError_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2506168706, data2: 3243, data3: 18133, data4: [162, 240, 227, 13, 25, 5, 248, 191] }; pub const Annotation_GrammarError_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1970930829, data2: 17688, data3: 16838, data4: [133, 76, 220, 0, 155, 124, 251, 83] }; pub const Annotation_Header_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2256224411, data2: 45590, data3: 17522, data4: [162, 25, 82, 94, 49, 6, 129, 248] }; pub const Annotation_Highlighted_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1971095630, data2: 32899, data3: 16513, data4: [139, 156, 232, 127, 80, 114, 240, 228], }; pub const Annotation_InsertionChange_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 230601638, data2: 57109, data3: 16740, data4: [163, 192, 226, 26, 140, 233, 49, 196], }; pub const Annotation_Mathematics_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3937100619, data2: 9936, data3: 16577, data4: [128, 115, 87, 202, 28, 99, 60, 155] }; pub const Annotation_MoveChange_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2644871147, data2: 9189, data3: 17552, data4: [179, 133, 26, 34, 221, 200, 177, 135], }; pub const Annotation_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4140247767, data2: 13676, data3: 18512, data4: [146, 145, 49, 111, 96, 138, 140, 132], }; pub const Annotation_Sensitive_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 938786895, data2: 3858, data3: 17508, data4: [146, 156, 130, 143, 209, 82, 146, 227], }; pub const Annotation_SpellingError_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2927974014, data2: 40654, data3: 16959, data4: [129, 183, 150, 196, 61, 83, 229, 14], }; pub const Annotation_Target_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3072012333, data2: 8452, data3: 17581, data4: [156, 92, 9, 43, 73, 7, 215, 15] }; pub const Annotation_TrackChanges_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 568780936, data2: 56340, data3: 16406, data4: [172, 39, 25, 5, 83, 200, 196, 112] }; pub const Annotation_UnsyncedChange_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 407966058, data2: 3655, data3: 19248, data4: [140, 181, 215, 218, 228, 251, 205, 27], }; pub const AppBar_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1628737677, data2: 52226, data3: 19767, data4: [135, 91, 181, 48, 199, 19, 149, 84] }; pub const AriaProperties_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1108567948, data2: 57381, data3: 18722, data4: [190, 181, 228, 59, 160, 142, 98, 33], }; pub const AriaRole_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3709893525, data2: 48714, data3: 19981, data4: [183, 39, 99, 172, 233, 75, 105, 22] }; pub type AsyncContentLoadedState = i32; pub const AsyncContentLoadedState_Beginning: AsyncContentLoadedState = 0i32; pub const AsyncContentLoadedState_Progress: AsyncContentLoadedState = 1i32; pub const AsyncContentLoadedState_Completed: AsyncContentLoadedState = 2i32; pub const AsyncContentLoaded_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1608442140, data2: 54010, data3: 20409, data4: [144, 78, 92, 190, 232, 148, 213, 239], }; pub type AutomationElementMode = i32; pub const AutomationElementMode_None: AutomationElementMode = 0i32; pub const AutomationElementMode_Full: AutomationElementMode = 1i32; pub const AutomationFocusChanged_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3062505239, data2: 62989, data3: 16807, data4: [163, 204, 176, 82, 146, 21, 95, 224], }; pub const AutomationId_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3358328064, data2: 46606, data3: 17168, data4: [162, 103, 48, 60, 83, 31, 142, 229] }; pub type AutomationIdentifierType = i32; pub const AutomationIdentifierType_Property: AutomationIdentifierType = 0i32; pub const AutomationIdentifierType_Pattern: AutomationIdentifierType = 1i32; pub const AutomationIdentifierType_Event: AutomationIdentifierType = 2i32; pub const AutomationIdentifierType_ControlType: AutomationIdentifierType = 3i32; pub const AutomationIdentifierType_TextAttribute: AutomationIdentifierType = 4i32; pub const AutomationIdentifierType_LandmarkType: AutomationIdentifierType = 5i32; pub const AutomationIdentifierType_Annotation: AutomationIdentifierType = 6i32; pub const AutomationIdentifierType_Changes: AutomationIdentifierType = 7i32; pub const AutomationIdentifierType_Style: AutomationIdentifierType = 8i32; pub const AutomationPropertyChanged_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 623377313, data2: 36218, data3: 17968, data4: [164, 204, 230, 99, 21, 148, 47, 82] }; pub const BoundingRectangle_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2076174514, data2: 15356, data3: 18653, data4: [183, 41, 199, 148, 184, 70, 233, 161], }; pub type BulletStyle = i32; pub const BulletStyle_None: BulletStyle = 0i32; pub const BulletStyle_HollowRoundBullet: BulletStyle = 1i32; pub const BulletStyle_FilledRoundBullet: BulletStyle = 2i32; pub const BulletStyle_HollowSquareBullet: BulletStyle = 3i32; pub const BulletStyle_FilledSquareBullet: BulletStyle = 4i32; pub const BulletStyle_DashBullet: BulletStyle = 5i32; pub const BulletStyle_Other: BulletStyle = -1i32; pub const Button_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1517871977, data2: 50849, data3: 20275, data4: [169, 215, 121, 242, 13, 12, 120, 142], }; pub const CAccPropServices: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3052942603, data2: 1352, data3: 18609, data4: [166, 238, 136, 189, 0, 180, 165, 231], }; pub const CLSID_AccPropServices: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3052942603, data2: 1352, data3: 18609, data4: [166, 238, 136, 189, 0, 180, 165, 231], }; pub const CUIAutomation: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4282964900, data2: 24815, data3: 16897, data4: [170, 135, 84, 16, 62, 239, 89, 78] }; pub const CUIAutomation8: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3794457395, data2: 45663, data3: 17932, data4: [131, 208, 5, 129, 16, 115, 149, 201], }; pub const CUIAutomationRegistrar: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1848244927, data2: 39287, data3: 17105, data4: [141, 14, 202, 126, 97, 173, 135, 230], }; pub const Calendar_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2299784072, data2: 229, data3: 18108, data4: [142, 78, 20, 167, 134, 225, 101, 161] }; pub type CapStyle = i32; pub const CapStyle_None: CapStyle = 0i32; pub const CapStyle_SmallCap: CapStyle = 1i32; pub const CapStyle_AllCap: CapStyle = 2i32; pub const CapStyle_AllPetiteCaps: CapStyle = 3i32; pub const CapStyle_PetiteCaps: CapStyle = 4i32; pub const CapStyle_Unicase: CapStyle = 5i32; pub const CapStyle_Titling: CapStyle = 6i32; pub const CapStyle_Other: CapStyle = -1i32; pub type CaretBidiMode = i32; pub const CaretBidiMode_LTR: CaretBidiMode = 0i32; pub const CaretBidiMode_RTL: CaretBidiMode = 1i32; pub type CaretPosition = i32; pub const CaretPosition_Unknown: CaretPosition = 0i32; pub const CaretPosition_EndOfLine: CaretPosition = 1i32; pub const CaretPosition_BeginningOfLine: CaretPosition = 2i32; pub const CenterPoint_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 212864008, data2: 21516, data3: 20187, data4: [148, 69, 38, 53, 158, 166, 151, 133] }; pub const Changes_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2113038100, data2: 24911, data3: 19973, data4: [148, 136, 113, 108, 91, 161, 148, 54], }; pub const Changes_Summary_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 826107302, data2: 58895, data3: 19810, data4: [152, 97, 85, 175, 215, 40, 210, 7] }; pub const CheckBox_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4216387874, data2: 41947, data3: 18880, data4: [139, 195, 6, 218, 213, 87, 120, 226], }; pub const ClassName_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 360411669, data2: 35151, data3: 19301, data4: [132, 226, 170, 192, 218, 8, 177, 107], }; pub const ClickablePoint_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 26644539, data2: 45571, data3: 18456, data4: [169, 243, 240, 142, 103, 95, 35, 65] }; pub type CoalesceEventsOptions = i32; pub const CoalesceEventsOptions_Disabled: CoalesceEventsOptions = 0i32; pub const CoalesceEventsOptions_Enabled: CoalesceEventsOptions = 1i32; pub const ComboBox_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1422606956, data2: 12083, data3: 20479, data4: [170, 161, 174, 246, 13, 172, 93, 235], }; pub type ConditionType = i32; pub const ConditionType_True: ConditionType = 0i32; pub const ConditionType_False: ConditionType = 1i32; pub const ConditionType_Property: ConditionType = 2i32; pub const ConditionType_And: ConditionType = 3i32; pub const ConditionType_Or: ConditionType = 4i32; pub const ConditionType_Not: ConditionType = 5i32; pub type ConnectionRecoveryBehaviorOptions = i32; pub const ConnectionRecoveryBehaviorOptions_Disabled: ConnectionRecoveryBehaviorOptions = 0i32; pub const ConnectionRecoveryBehaviorOptions_Enabled: ConnectionRecoveryBehaviorOptions = 1i32; pub const ControlType_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3396816874, data2: 10412, data3: 19394, data4: [148, 202, 172, 236, 109, 108, 16, 163], }; pub const ControllerFor_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1360153738, data2: 42450, data3: 20243, data4: [155, 230, 127, 168, 186, 157, 58, 144], }; pub const Culture_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3805761319, data2: 15737, data3: 19906, data4: [184, 139, 48, 68, 150, 58, 138, 251], }; pub const CustomNavigation_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2951385994, data2: 25118, data3: 16468, data4: [187, 44, 47, 70, 17, 77, 172, 63] }; pub const Custom_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4070482115, data2: 44471, data3: 17162, data4: [186, 144, 229, 44, 115, 19, 230, 237], }; pub const DISPID_ACC_CHILD: i32 = -5002i32; pub const DISPID_ACC_CHILDCOUNT: i32 = -5001i32; pub const DISPID_ACC_DEFAULTACTION: i32 = -5013i32; pub const DISPID_ACC_DESCRIPTION: i32 = -5005i32; pub const DISPID_ACC_DODEFAULTACTION: i32 = -5018i32; pub const DISPID_ACC_FOCUS: i32 = -5011i32; pub const DISPID_ACC_HELP: i32 = -5008i32; pub const DISPID_ACC_HELPTOPIC: i32 = -5009i32; pub const DISPID_ACC_HITTEST: i32 = -5017i32; pub const DISPID_ACC_KEYBOARDSHORTCUT: i32 = -5010i32; pub const DISPID_ACC_LOCATION: i32 = -5015i32; pub const DISPID_ACC_NAME: i32 = -5003i32; pub const DISPID_ACC_NAVIGATE: i32 = -5016i32; pub const DISPID_ACC_PARENT: i32 = -5000i32; pub const DISPID_ACC_ROLE: i32 = -5006i32; pub const DISPID_ACC_SELECT: i32 = -5014i32; pub const DISPID_ACC_SELECTION: i32 = -5012i32; pub const DISPID_ACC_STATE: i32 = -5007i32; pub const DISPID_ACC_VALUE: i32 = -5004i32; pub const DataGrid_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2226619311, data2: 53507, data3: 19210, data4: [132, 21, 231, 57, 66, 65, 15, 75] }; pub const DataItem_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2685892674, data2: 55631, data3: 17061, data4: [129, 75, 96, 104, 173, 220, 141, 165], }; pub const DescribedBy_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2086167992, data2: 39314, data3: 16637, data4: [141, 176, 107, 241, 211, 23, 249, 152], }; pub type DockPosition = i32; pub const DockPosition_Top: DockPosition = 0i32; pub const DockPosition_Left: DockPosition = 1i32; pub const DockPosition_Bottom: DockPosition = 2i32; pub const DockPosition_Right: DockPosition = 3i32; pub const DockPosition_Fill: DockPosition = 4i32; pub const DockPosition_None: DockPosition = 5i32; pub const Dock_DockPosition_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1835528238, data2: 49328, data3: 19216, data4: [181, 185, 24, 214, 236, 249, 135, 96], }; pub const Dock_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2629478470, data2: 33736, data3: 17037, data4: [130, 127, 126, 96, 99, 254, 6, 32] }; pub const Document_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1020705647, data2: 28424, data3: 17762, data4: [178, 41, 228, 226, 252, 122, 158, 180], }; pub const Drag_DragCancel_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3287148282, data2: 13393, data3: 19983, data4: [158, 113, 223, 156, 40, 10, 70, 87] }; pub const Drag_DragComplete_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 954818952, data2: 61215, data3: 17982, data4: [145, 202, 58, 119, 146, 194, 156, 175], }; pub const Drag_DragStart_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2285520907, data2: 15017, data3: 17053, data4: [149, 228, 217, 200, 208, 17, 240, 221], }; pub const Drag_DropEffect_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1685006201, data2: 18643, data3: 19235, data4: [137, 2, 75, 241, 0, 0, 93, 243] }; pub const Drag_DropEffects_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4124447062, data2: 31974, data3: 18878, data4: [168, 54, 146, 105, 220, 236, 146, 15], }; pub const Drag_GrabbedItems_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2009159212, data2: 31622, data3: 19233, data4: [158, 215, 60, 239, 218, 111, 76, 67], }; pub const Drag_IsGrabbed_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1173489395, data2: 30156, data3: 19658, data4: [169, 185, 252, 223, 185, 130, 216, 162], }; pub const Drag_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3233735199, data2: 52403, data3: 20461, data4: [153, 91, 17, 79, 110, 61, 39, 40] }; pub const DropTarget_DragEnter_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2866360731, data2: 812, data3: 19080, data4: [150, 29, 28, 245, 121, 88, 30, 52] }; pub const DropTarget_DragLeave_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 260238101, data2: 9378, data3: 18824, data4: [146, 23, 222, 22, 42, 238, 39, 43] }; pub const DropTarget_DropTargetEffect_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2344049013, data2: 41162, data3: 18817, data4: [184, 24, 135, 252, 102, 233, 80, 157], }; pub const DropTarget_DropTargetEffects_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3156071661, data2: 52105, data3: 17905, data4: [165, 146, 224, 59, 8, 174, 121, 15] }; pub const DropTarget_Dropped_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1647110872, data2: 7899, data3: 19005, data4: [171, 188, 190, 34, 17, 255, 104, 181], }; pub const DropTarget_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 197913686, data2: 48436, data3: 19323, data4: [159, 213, 38, 89, 144, 94, 163, 220] }; pub const Edit_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1694803400, data2: 11398, data3: 20359, data4: [174, 123, 26, 189, 220, 129, 12, 249], }; pub type EventArgsType = i32; pub const EventArgsType_Simple: EventArgsType = 0i32; pub const EventArgsType_PropertyChanged: EventArgsType = 1i32; pub const EventArgsType_StructureChanged: EventArgsType = 2i32; pub const EventArgsType_AsyncContentLoaded: EventArgsType = 3i32; pub const EventArgsType_WindowClosed: EventArgsType = 4i32; pub const EventArgsType_TextEditTextChanged: EventArgsType = 5i32; pub const EventArgsType_Changes: EventArgsType = 6i32; pub const EventArgsType_Notification: EventArgsType = 7i32; pub const EventArgsType_ActiveTextPositionChanged: EventArgsType = 8i32; pub const EventArgsType_StructuredMarkup: EventArgsType = 9i32; pub type ExpandCollapseState = i32; pub const ExpandCollapseState_Collapsed: ExpandCollapseState = 0i32; pub const ExpandCollapseState_Expanded: ExpandCollapseState = 1i32; pub const ExpandCollapseState_PartiallyExpanded: ExpandCollapseState = 2i32; pub const ExpandCollapseState_LeafNode: ExpandCollapseState = 3i32; pub const ExpandCollapse_ExpandCollapseState_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 660229192, data2: 34215, data3: 20329, data4: [171, 160, 175, 21, 118, 16, 0, 43] }; pub const ExpandCollapse_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2919624610, data2: 63953, data3: 17034, data4: [131, 76, 83, 165, 197, 47, 155, 139], }; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct ExtendedProperty { pub PropertyName: super::super::Foundation::BSTR, pub PropertyValue: super::super::Foundation::BSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for ExtendedProperty {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for ExtendedProperty { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct FILTERKEYS { pub cbSize: u32, pub dwFlags: u32, pub iWaitMSec: u32, pub iDelayMSec: u32, pub iRepeatMSec: u32, pub iBounceMSec: u32, } impl ::core::marker::Copy for FILTERKEYS {} impl ::core::clone::Clone for FILTERKEYS { fn clone(&self) -> Self { *self } } pub const FillColor_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1846461648, data2: 58024, data3: 19030, data4: [157, 231, 149, 51, 137, 147, 59, 57], }; pub type FillType = i32; pub const FillType_None: FillType = 0i32; pub const FillType_Color: FillType = 1i32; pub const FillType_Gradient: FillType = 2i32; pub const FillType_Picture: FillType = 3i32; pub const FillType_Pattern: FillType = 4i32; pub const FillType_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3338433764, data2: 36025, data3: 17052, data4: [169, 225, 155, 196, 172, 55, 43, 98], }; pub type FlowDirections = i32; pub const FlowDirections_Default: FlowDirections = 0i32; pub const FlowDirections_RightToLeft: FlowDirections = 1i32; pub const FlowDirections_BottomToTop: FlowDirections = 2i32; pub const FlowDirections_Vertical: FlowDirections = 4i32; pub const FlowsFrom_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 96896079, data2: 6622, data3: 18680, data4: [149, 250, 136, 13, 91, 15, 214, 21] }; pub const FlowsTo_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3841146144, data2: 21914, data3: 18427, data4: [168, 48, 249, 203, 79, 241, 167, 10], }; pub const FrameworkId_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3690830080, data2: 32282, data3: 20312, data4: [182, 27, 112, 99, 18, 15, 119, 59] }; pub const FullDescription_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 222580991, data2: 27375, data3: 20275, data4: [149, 221, 123, 239, 167, 42, 67, 145], }; pub const GridItem_ColumnSpan_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1480500213, data2: 34512, data3: 19208, data4: [166, 236, 44, 84, 99, 255, 193, 9] }; pub const GridItem_Column_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3346317660, data2: 25280, data3: 17689, data4: [139, 220, 71, 190, 87, 60, 138, 213], }; pub const GridItem_Parent_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2643534418, data2: 47487, data3: 20172, data4: [133, 16, 234, 14, 51, 66, 124, 114] }; pub const GridItem_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4074096759, data2: 42082, data3: 18775, data4: [162, 165, 44, 150, 179, 3, 188, 99] }; pub const GridItem_RowSpan_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1166158108, data2: 18027, data3: 20115, data4: [142, 131, 61, 23, 21, 236, 12, 94] }; pub const GridItem_Row_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1646499626, data2: 51525, data3: 17763, data4: [147, 41, 253, 201, 116, 175, 37, 83], }; pub const Grid_ColumnCount_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4271305589, data2: 17578, data3: 17718, data4: [172, 122, 42, 117, 215, 26, 62, 252], }; pub const Grid_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 638201035, data2: 37800, data3: 20036, data4: [164, 193, 61, 243, 151, 242, 176, 43], }; pub const Grid_RowCount_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 714409407, data2: 49899, data3: 20406, data4: [179, 86, 130, 69, 174, 83, 112, 62] }; pub const Group_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2907744796, data2: 59592, data3: 18292, data4: [174, 27, 221, 134, 223, 11, 59, 220], }; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HIGHCONTRASTA { pub cbSize: u32, pub dwFlags: HIGHCONTRASTW_FLAGS, pub lpszDefaultScheme: super::super::Foundation::PSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for HIGHCONTRASTA {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for HIGHCONTRASTA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HIGHCONTRASTW { pub cbSize: u32, pub dwFlags: HIGHCONTRASTW_FLAGS, pub lpszDefaultScheme: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for HIGHCONTRASTW {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for HIGHCONTRASTW { fn clone(&self) -> Self { *self } } pub type HIGHCONTRASTW_FLAGS = u32; pub const HCF_HIGHCONTRASTON: HIGHCONTRASTW_FLAGS = 1u32; pub const HCF_AVAILABLE: HIGHCONTRASTW_FLAGS = 2u32; pub const HCF_HOTKEYACTIVE: HIGHCONTRASTW_FLAGS = 4u32; pub const HCF_CONFIRMHOTKEY: HIGHCONTRASTW_FLAGS = 8u32; pub const HCF_HOTKEYSOUND: HIGHCONTRASTW_FLAGS = 16u32; pub const HCF_INDICATOR: HIGHCONTRASTW_FLAGS = 32u32; pub const HCF_HOTKEYAVAILABLE: HIGHCONTRASTW_FLAGS = 64u32; pub const HCF_OPTION_NOTHEMECHANGE: HIGHCONTRASTW_FLAGS = 4096u32; pub type HUIAEVENT = isize; pub type HUIANODE = isize; pub type HUIAPATTERNOBJECT = isize; pub type HUIATEXTRANGE = isize; pub type HWINEVENTHOOK = isize; pub const HasKeyboardFocus_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3481992505, data2: 16198, data3: 18432, data4: [150, 86, 178, 191, 18, 82, 153, 5] }; pub const HeaderItem_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3871085259, data2: 31886, data3: 18895, data4: [177, 104, 74, 147, 163, 43, 235, 176], }; pub const Header_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1536216014, data2: 30971, data3: 17940, data4: [130, 182, 85, 77, 116, 113, 142, 103], }; pub const HeadingLevel1: i32 = 80051i32; pub const HeadingLevel2: i32 = 80052i32; pub const HeadingLevel3: i32 = 80053i32; pub const HeadingLevel4: i32 = 80054i32; pub const HeadingLevel5: i32 = 80055i32; pub const HeadingLevel6: i32 = 80056i32; pub const HeadingLevel7: i32 = 80057i32; pub const HeadingLevel8: i32 = 80058i32; pub const HeadingLevel9: i32 = 80059i32; pub const HeadingLevel_None: i32 = 80050i32; pub const HeadingLevel_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 688407154, data2: 43695, data3: 18992, data4: [135, 150, 60, 18, 246, 43, 107, 187] }; pub const HelpText_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 139810437, data2: 2423, data3: 17863, data4: [167, 166, 171, 175, 86, 132, 18, 26] }; pub type HorizontalTextAlignment = i32; pub const HorizontalTextAlignment_Left: HorizontalTextAlignment = 0i32; pub const HorizontalTextAlignment_Centered: HorizontalTextAlignment = 1i32; pub const HorizontalTextAlignment_Right: HorizontalTextAlignment = 2i32; pub const HorizontalTextAlignment_Justified: HorizontalTextAlignment = 3i32; pub const HostedFragmentRootsInvalidated_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3871191102, data2: 2337, data3: 20165, data4: [141, 207, 234, 232, 119, 176, 66, 107], }; pub const Hyperlink_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2320892460, data2: 45069, data3: 19733, data4: [143, 240, 91, 107, 38, 110, 94, 2] }; pub type IAccIdentity = *mut ::core::ffi::c_void; pub type IAccPropServer = *mut ::core::ffi::c_void; pub type IAccPropServices = *mut ::core::ffi::c_void; pub type IAccessible = *mut ::core::ffi::c_void; pub type IAccessibleEx = *mut ::core::ffi::c_void; pub type IAccessibleHandler = *mut ::core::ffi::c_void; pub type IAccessibleHostingElementProviders = *mut ::core::ffi::c_void; pub type IAccessibleWindowlessSite = *mut ::core::ffi::c_void; pub type IAnnotationProvider = *mut ::core::ffi::c_void; pub type ICustomNavigationProvider = *mut ::core::ffi::c_void; pub type IDockProvider = *mut ::core::ffi::c_void; pub type IDragProvider = *mut ::core::ffi::c_void; pub type IDropTargetProvider = *mut ::core::ffi::c_void; pub type IExpandCollapseProvider = *mut ::core::ffi::c_void; pub type IGridItemProvider = *mut ::core::ffi::c_void; pub type IGridProvider = *mut ::core::ffi::c_void; pub const IIS_ControlAccessible: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 952533670, data2: 38705, data3: 17394, data4: [159, 174, 233, 1, 230, 65, 177, 1] }; pub const IIS_IsOleaccProxy: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2418448378, data2: 32996, data3: 17760, data4: [128, 42, 161, 63, 34, 166, 71, 9] }; pub type IInvokeProvider = *mut ::core::ffi::c_void; pub type IItemContainerProvider = *mut ::core::ffi::c_void; pub type ILegacyIAccessibleProvider = *mut ::core::ffi::c_void; pub type IMultipleViewProvider = *mut ::core::ffi::c_void; pub type IObjectModelProvider = *mut ::core::ffi::c_void; pub type IProxyProviderWinEventHandler = *mut ::core::ffi::c_void; pub type IProxyProviderWinEventSink = *mut ::core::ffi::c_void; pub type IRangeValueProvider = *mut ::core::ffi::c_void; pub type IRawElementProviderAdviseEvents = *mut ::core::ffi::c_void; pub type IRawElementProviderFragment = *mut ::core::ffi::c_void; pub type IRawElementProviderFragmentRoot = *mut ::core::ffi::c_void; pub type IRawElementProviderHostingAccessibles = *mut ::core::ffi::c_void; pub type IRawElementProviderHwndOverride = *mut ::core::ffi::c_void; pub type IRawElementProviderSimple = *mut ::core::ffi::c_void; pub type IRawElementProviderSimple2 = *mut ::core::ffi::c_void; pub type IRawElementProviderSimple3 = *mut ::core::ffi::c_void; pub type IRawElementProviderWindowlessSite = *mut ::core::ffi::c_void; pub type IRichEditUiaInformation = *mut ::core::ffi::c_void; pub type IRicheditWindowlessAccessibility = *mut ::core::ffi::c_void; pub type IScrollItemProvider = *mut ::core::ffi::c_void; pub type IScrollProvider = *mut ::core::ffi::c_void; pub type ISelectionItemProvider = *mut ::core::ffi::c_void; pub type ISelectionProvider = *mut ::core::ffi::c_void; pub type ISelectionProvider2 = *mut ::core::ffi::c_void; pub type ISpreadsheetItemProvider = *mut ::core::ffi::c_void; pub type ISpreadsheetProvider = *mut ::core::ffi::c_void; pub type IStylesProvider = *mut ::core::ffi::c_void; pub type ISynchronizedInputProvider = *mut ::core::ffi::c_void; pub type ITableItemProvider = *mut ::core::ffi::c_void; pub type ITableProvider = *mut ::core::ffi::c_void; pub type ITextChildProvider = *mut ::core::ffi::c_void; pub type ITextEditProvider = *mut ::core::ffi::c_void; pub type ITextProvider = *mut ::core::ffi::c_void; pub type ITextProvider2 = *mut ::core::ffi::c_void; pub type ITextRangeProvider = *mut ::core::ffi::c_void; pub type ITextRangeProvider2 = *mut ::core::ffi::c_void; pub type IToggleProvider = *mut ::core::ffi::c_void; pub type ITransformProvider = *mut ::core::ffi::c_void; pub type ITransformProvider2 = *mut ::core::ffi::c_void; pub type IUIAutomation = *mut ::core::ffi::c_void; pub type IUIAutomation2 = *mut ::core::ffi::c_void; pub type IUIAutomation3 = *mut ::core::ffi::c_void; pub type IUIAutomation4 = *mut ::core::ffi::c_void; pub type IUIAutomation5 = *mut ::core::ffi::c_void; pub type IUIAutomation6 = *mut ::core::ffi::c_void; pub type IUIAutomationActiveTextPositionChangedEventHandler = *mut ::core::ffi::c_void; pub type IUIAutomationAndCondition = *mut ::core::ffi::c_void; pub type IUIAutomationAnnotationPattern = *mut ::core::ffi::c_void; pub type IUIAutomationBoolCondition = *mut ::core::ffi::c_void; pub type IUIAutomationCacheRequest = *mut ::core::ffi::c_void; pub type IUIAutomationChangesEventHandler = *mut ::core::ffi::c_void; pub type IUIAutomationCondition = *mut ::core::ffi::c_void; pub type IUIAutomationCustomNavigationPattern = *mut ::core::ffi::c_void; pub type IUIAutomationDockPattern = *mut ::core::ffi::c_void; pub type IUIAutomationDragPattern = *mut ::core::ffi::c_void; pub type IUIAutomationDropTargetPattern = *mut ::core::ffi::c_void; pub type IUIAutomationElement = *mut ::core::ffi::c_void; pub type IUIAutomationElement2 = *mut ::core::ffi::c_void; pub type IUIAutomationElement3 = *mut ::core::ffi::c_void; pub type IUIAutomationElement4 = *mut ::core::ffi::c_void; pub type IUIAutomationElement5 = *mut ::core::ffi::c_void; pub type IUIAutomationElement6 = *mut ::core::ffi::c_void; pub type IUIAutomationElement7 = *mut ::core::ffi::c_void; pub type IUIAutomationElement8 = *mut ::core::ffi::c_void; pub type IUIAutomationElement9 = *mut ::core::ffi::c_void; pub type IUIAutomationElementArray = *mut ::core::ffi::c_void; pub type IUIAutomationEventHandler = *mut ::core::ffi::c_void; pub type IUIAutomationEventHandlerGroup = *mut ::core::ffi::c_void; pub type IUIAutomationExpandCollapsePattern = *mut ::core::ffi::c_void; pub type IUIAutomationFocusChangedEventHandler = *mut ::core::ffi::c_void; pub type IUIAutomationGridItemPattern = *mut ::core::ffi::c_void; pub type IUIAutomationGridPattern = *mut ::core::ffi::c_void; pub type IUIAutomationInvokePattern = *mut ::core::ffi::c_void; pub type IUIAutomationItemContainerPattern = *mut ::core::ffi::c_void; pub type IUIAutomationLegacyIAccessiblePattern = *mut ::core::ffi::c_void; pub type IUIAutomationMultipleViewPattern = *mut ::core::ffi::c_void; pub type IUIAutomationNotCondition = *mut ::core::ffi::c_void; pub type IUIAutomationNotificationEventHandler = *mut ::core::ffi::c_void; pub type IUIAutomationObjectModelPattern = *mut ::core::ffi::c_void; pub type IUIAutomationOrCondition = *mut ::core::ffi::c_void; pub type IUIAutomationPatternHandler = *mut ::core::ffi::c_void; pub type IUIAutomationPatternInstance = *mut ::core::ffi::c_void; pub type IUIAutomationPropertyChangedEventHandler = *mut ::core::ffi::c_void; pub type IUIAutomationPropertyCondition = *mut ::core::ffi::c_void; pub type IUIAutomationProxyFactory = *mut ::core::ffi::c_void; pub type IUIAutomationProxyFactoryEntry = *mut ::core::ffi::c_void; pub type IUIAutomationProxyFactoryMapping = *mut ::core::ffi::c_void; pub type IUIAutomationRangeValuePattern = *mut ::core::ffi::c_void; pub type IUIAutomationRegistrar = *mut ::core::ffi::c_void; pub type IUIAutomationScrollItemPattern = *mut ::core::ffi::c_void; pub type IUIAutomationScrollPattern = *mut ::core::ffi::c_void; pub type IUIAutomationSelectionItemPattern = *mut ::core::ffi::c_void; pub type IUIAutomationSelectionPattern = *mut ::core::ffi::c_void; pub type IUIAutomationSelectionPattern2 = *mut ::core::ffi::c_void; pub type IUIAutomationSpreadsheetItemPattern = *mut ::core::ffi::c_void; pub type IUIAutomationSpreadsheetPattern = *mut ::core::ffi::c_void; pub type IUIAutomationStructureChangedEventHandler = *mut ::core::ffi::c_void; pub type IUIAutomationStylesPattern = *mut ::core::ffi::c_void; pub type IUIAutomationSynchronizedInputPattern = *mut ::core::ffi::c_void; pub type IUIAutomationTableItemPattern = *mut ::core::ffi::c_void; pub type IUIAutomationTablePattern = *mut ::core::ffi::c_void; pub type IUIAutomationTextChildPattern = *mut ::core::ffi::c_void; pub type IUIAutomationTextEditPattern = *mut ::core::ffi::c_void; pub type IUIAutomationTextEditTextChangedEventHandler = *mut ::core::ffi::c_void; pub type IUIAutomationTextPattern = *mut ::core::ffi::c_void; pub type IUIAutomationTextPattern2 = *mut ::core::ffi::c_void; pub type IUIAutomationTextRange = *mut ::core::ffi::c_void; pub type IUIAutomationTextRange2 = *mut ::core::ffi::c_void; pub type IUIAutomationTextRange3 = *mut ::core::ffi::c_void; pub type IUIAutomationTextRangeArray = *mut ::core::ffi::c_void; pub type IUIAutomationTogglePattern = *mut ::core::ffi::c_void; pub type IUIAutomationTransformPattern = *mut ::core::ffi::c_void; pub type IUIAutomationTransformPattern2 = *mut ::core::ffi::c_void; pub type IUIAutomationTreeWalker = *mut ::core::ffi::c_void; pub type IUIAutomationValuePattern = *mut ::core::ffi::c_void; pub type IUIAutomationVirtualizedItemPattern = *mut ::core::ffi::c_void; pub type IUIAutomationWindowPattern = *mut ::core::ffi::c_void; pub type IValueProvider = *mut ::core::ffi::c_void; pub type IVirtualizedItemProvider = *mut ::core::ffi::c_void; pub type IWindowProvider = *mut ::core::ffi::c_void; pub const Image_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 758593252, data2: 27414, data3: 19543, data4: [169, 98, 249, 50, 96, 167, 82, 67] }; pub const InputDiscarded_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2134295399, data2: 31512, data3: 16764, data4: [151, 227, 157, 88, 221, 201, 68, 171], }; pub const InputReachedOtherElement_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3978304906, data2: 20076, data3: 16734, data4: [168, 116, 36, 96, 201, 182, 107, 168], }; pub const InputReachedTarget_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2481804442, data2: 1353, data3: 16624, data4: [190, 219, 40, 228, 79, 125, 226, 163], }; pub const Invoke_Invoked_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3755383280, data2: 51477, data3: 18909, data4: [180, 34, 221, 231, 133, 195, 210, 75], }; pub const Invoke_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3648439036, data2: 26346, data3: 19054, data4: [178, 143, 194, 76, 117, 70, 173, 55], }; pub const IsAnnotationPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 190526008, data2: 27996, data3: 16822, data4: [188, 196, 94, 128, 127, 101, 81, 196], }; pub const IsContentElement_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1272603816, data2: 62936, data3: 18443, data4: [129, 85, 239, 46, 137, 173, 182, 114], }; pub const IsControlElement_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2515751045, data2: 43980, data3: 19197, data4: [165, 244, 219, 180, 108, 35, 15, 219], }; pub const IsCustomNavigationPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2408480980, data2: 9041, data3: 18656, data4: [135, 74, 84, 170, 115, 19, 136, 154] }; pub const IsDataValidForForm_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1146799748, data2: 50172, data3: 19929, data4: [172, 248, 132, 90, 87, 146, 150, 186], }; pub const IsDialog_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2634939291, data2: 33846, data3: 17665, data4: [187, 187, 229, 52, 164, 251, 59, 63], }; pub const IsDockPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 637576388, data2: 12280, data3: 19606, data4: [174, 49, 143, 230, 25, 161, 60, 108] }; pub const IsDragPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3919030199, data2: 7481, data3: 19623, data4: [190, 15, 39, 127, 207, 86, 5, 204] }; pub const IsDropTargetPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 109491758, data2: 36377, data3: 19119, data4: [135, 61, 56, 79, 109, 59, 146, 190] }; pub const IsEnabled_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 554254975, data2: 55904, data3: 20461, data4: [191, 27, 38, 75, 220, 230, 235, 58] }; pub const IsExpandCollapsePatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2459777030, data2: 21127, data3: 18213, data4: [170, 22, 34, 42, 252, 99, 213, 149] }; pub const IsGridItemPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1514399012, data2: 63906, data3: 19218, data4: [132, 200, 180, 138, 62, 254, 221, 52], }; pub const IsGridPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1445118572, data2: 61679, data3: 20283, data4: [151, 203, 113, 76, 8, 104, 88, 139] }; pub const IsInvokePatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1316116280, data2: 33636, data3: 18041, data4: [170, 108, 243, 244, 25, 49, 247, 80], }; pub const IsItemContainerPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1649106087, data2: 65088, data3: 18775, data4: [160, 25, 32, 196, 207, 17, 146, 15] }; pub const IsKeyboardFocusable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4156052778, data2: 2137, data3: 19255, data4: [185, 203, 81, 231, 32, 146, 242, 159], }; pub const IsLegacyIAccessiblePatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3639333063, data2: 37530, data3: 20199, data4: [141, 58, 211, 217, 68, 19, 2, 123] }; pub const IsMultipleViewPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4278858219, data2: 36389, data3: 18077, data4: [141, 110, 231, 113, 162, 124, 27, 144], }; pub const IsObjectModelPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1797380251, data2: 10305, data3: 16687, data4: [142, 242, 21, 202, 149, 35, 24, 186], }; pub const IsOffscreen_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 63164768, data2: 56185, data3: 17115, data4: [162, 239, 28, 35, 30, 237, 229, 7] }; pub const IsPassword_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3897044657, data2: 26748, data3: 18811, data4: [190, 188, 3, 190, 83, 236, 20, 84] }; pub const IsPeripheral_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3665134198, data2: 32469, data3: 18900, data4: [142, 104, 236, 201, 162, 211, 0, 221], }; pub const IsRangeValuePatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4255392842, data2: 60237, data3: 17407, data4: [181, 173, 237, 54, 211, 115, 236, 76], }; pub const IsRequiredForForm_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1331643343, data2: 23035, data3: 19422, data4: [162, 112, 96, 46, 94, 17, 65, 233] }; pub const IsScrollItemPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 481106437, data2: 2343, data3: 19318, data4: [151, 225, 15, 205, 178, 9, 185, 138] }; pub const IsScrollPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1052474186, data2: 33418, data3: 19287, data4: [157, 34, 47, 234, 22, 50, 237, 13] }; pub const IsSelectionItemPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2347554349, data2: 3011, data3: 16649, data4: [190, 226, 142, 103, 21, 41, 14, 104] }; pub const IsSelectionPattern2Available_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1225262843, data2: 28297, data3: 19015, data4: [131, 25, 210, 102, 229, 17, 240, 33], }; pub const IsSelectionPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4119375038, data2: 51049, data3: 18488, data4: [154, 96, 38, 134, 220, 17, 136, 196], }; pub const IsSpreadsheetItemPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2682755882, data2: 12180, data3: 17405, data4: [153, 107, 84, 158, 49, 111, 74, 205], }; pub const IsSpreadsheetPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1878275890, data2: 58548, data3: 17749, data4: [151, 188, 236, 219, 188, 77, 24, 136], }; pub const IsStructuredMarkupPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2966733206, data2: 11275, data3: 18588, data4: [177, 101, 164, 5, 146, 140, 111, 61], }; pub const IsStylesPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 670258131, data2: 17820, data3: 19289, data4: [164, 144, 80, 97, 29, 172, 175, 181] }; pub const IsSynchronizedInputPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1976999109, data2: 53951, data3: 18755, data4: [135, 110, 180, 91, 98, 166, 204, 102], }; pub const IsTableItemPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3946230797, data2: 36516, data3: 18587, data4: [160, 19, 230, 13, 89, 81, 254, 52] }; pub const IsTablePatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3414382431, data2: 17858, data3: 16456, data4: [156, 118, 21, 151, 21, 161, 57, 223], }; pub const IsTextChildPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1436444127, data2: 12543, data3: 17333, data4: [181, 237, 91, 40, 59, 128, 199, 233], }; pub const IsTextEditPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2017673820, data2: 35634, data3: 18508, data4: [154, 181, 227, 32, 5, 113, 255, 218], }; pub const IsTextPattern2Available_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1104122397, data2: 58353, data3: 19234, data4: [156, 129, 225, 195, 237, 51, 28, 34], }; pub const IsTextPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4225947293, data2: 45046, data3: 19013, data4: [130, 226, 252, 146, 168, 47, 89, 23], }; pub const IsTogglePatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2020109651, data2: 64720, data3: 19331, data4: [155, 120, 88, 50, 206, 99, 187, 91] }; pub const IsTransformPattern2Available_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 630721355, data2: 48644, data3: 18192, data4: [171, 74, 253, 163, 29, 189, 40, 149] }; pub const IsTransformPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2818017284, data2: 54923, data3: 16503, data4: [165, 198, 122, 94, 161, 172, 49, 197], }; pub const IsValuePatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 189800615, data2: 8473, data3: 18235, data4: [190, 55, 92, 235, 152, 187, 251, 34] }; pub const IsVirtualizedItemPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 808235345, data2: 10952, data3: 17878, data4: [151, 123, 210, 179, 165, 165, 63, 32], }; pub const IsWindowPatternAvailable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3886382001, data2: 22664, data3: 16725, data4: [152, 220, 180, 34, 253, 87, 242, 188], }; pub const ItemContainer_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1024711183, data2: 35738, data3: 19097, data4: [133, 250, 197, 201, 166, 159, 30, 212], }; pub const ItemStatus_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1373504289, data2: 14707, data3: 17383, data4: [137, 19, 11, 8, 232, 19, 195, 127] }; pub const ItemType_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3453633357, data2: 25122, data3: 16699, data4: [166, 138, 50, 93, 209, 212, 15, 57] }; pub const LIBID_Accessibility: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 514120688, data2: 15419, data3: 4559, data4: [129, 12, 0, 170, 0, 56, 155, 113] }; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub type LPFNACCESSIBLECHILDREN = ::core::option::Option<unsafe extern "system" fn(pacccontainer: IAccessible, ichildstart: i32, cchildren: i32, rgvarchildren: *mut super::super::System::Com::VARIANT, pcobtained: *mut i32) -> ::windows_sys::core::HRESULT>; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub type LPFNACCESSIBLEOBJECTFROMPOINT = ::core::option::Option<unsafe extern "system" fn(ptscreen: super::super::Foundation::POINT, ppacc: *mut IAccessible, pvarchild: *mut super::super::System::Com::VARIANT) -> ::windows_sys::core::HRESULT>; #[cfg(feature = "Win32_Foundation")] pub type LPFNACCESSIBLEOBJECTFROMWINDOW = ::core::option::Option<unsafe extern "system" fn(hwnd: super::super::Foundation::HWND, dwid: u32, riid: *const ::windows_sys::core::GUID, ppvobject: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT>; #[cfg(feature = "Win32_Foundation")] pub type LPFNCREATESTDACCESSIBLEOBJECT = ::core::option::Option<unsafe extern "system" fn(hwnd: super::super::Foundation::HWND, idobject: i32, riid: *const ::windows_sys::core::GUID, ppvobject: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT>; #[cfg(feature = "Win32_Foundation")] pub type LPFNLRESULTFROMOBJECT = ::core::option::Option<unsafe extern "system" fn(riid: *const ::windows_sys::core::GUID, wparam: super::super::Foundation::WPARAM, punk: ::windows_sys::core::IUnknown) -> super::super::Foundation::LRESULT>; #[cfg(feature = "Win32_Foundation")] pub type LPFNOBJECTFROMLRESULT = ::core::option::Option<unsafe extern "system" fn(lresult: super::super::Foundation::LRESULT, riid: *const ::windows_sys::core::GUID, wparam: super::super::Foundation::WPARAM, ppvobject: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT>; pub const LabeledBy_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3854078539, data2: 64650, data3: 18997, data4: [128, 49, 207, 120, 172, 67, 229, 94], }; pub const LandmarkType_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1161840114, data2: 28513, data3: 18935, data4: [164, 248, 181, 240, 207, 130, 218, 30], }; pub const LayoutInvalidated_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3984418116, data2: 42685, data3: 17813, data4: [155, 174, 61, 40, 148, 108, 199, 21], }; pub const LegacyIAccessible_ChildId_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2585336669, data2: 40690, data3: 18311, data4: [164, 89, 220, 222, 136, 93, 212, 232], }; pub const LegacyIAccessible_DefaultAction_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 993204009, data2: 60077, data3: 17666, data4: [184, 95, 146, 97, 86, 34, 145, 60] }; pub const LegacyIAccessible_Description_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1178895384, data2: 32112, data3: 20137, data4: [157, 39, 183, 231, 117, 207, 42, 215], }; pub const LegacyIAccessible_Help_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2487231314, data2: 5660, data3: 19319, data4: [169, 141, 168, 114, 204, 51, 148, 122], }; pub const LegacyIAccessible_KeyboardShortcut_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2406025644, data2: 184, data3: 16985, data4: [164, 28, 150, 98, 102, 212, 58, 138] }; pub const LegacyIAccessible_Name_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3404400189, data2: 16558, data3: 18537, data4: [170, 90, 27, 142, 93, 102, 103, 57] }; pub const LegacyIAccessible_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1422658207, data2: 13205, data3: 18607, data4: [186, 141, 115, 248, 86, 144, 243, 224], }; pub const LegacyIAccessible_Role_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1750525343, data2: 52143, data3: 20017, data4: [147, 232, 188, 191, 111, 126, 73, 28], }; pub const LegacyIAccessible_Selection_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2326311392, data2: 2193, data3: 16588, data4: [139, 6, 144, 215, 212, 22, 98, 25] }; pub const LegacyIAccessible_State_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3751303252, data2: 8833, data3: 17216, data4: [171, 156, 198, 14, 44, 88, 3, 246] }; pub const LegacyIAccessible_Value_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3049631926, data2: 33303, data3: 19063, data4: [151, 165, 25, 10, 133, 237, 1, 86] }; pub const Level_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 606782761, data2: 52534, data3: 16399, data4: [170, 217, 120, 118, 239, 58, 246, 39], }; pub const ListItem_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2067208178, data2: 17617, data3: 19032, data4: [152, 168, 241, 42, 155, 143, 120, 226], }; pub const List_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2601819873, data2: 31946, data3: 19708, data4: [154, 241, 202, 199, 189, 221, 48, 49], }; pub const LiveRegionChanged_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 271408784, data2: 59049, data3: 16822, data4: [177, 197, 169, 177, 146, 157, 149, 16], }; pub type LiveSetting = i32; pub const Off: LiveSetting = 0i32; pub const Polite: LiveSetting = 1i32; pub const Assertive: LiveSetting = 2i32; pub const LiveSetting_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3240873358, data2: 10894, data3: 18768, data4: [138, 231, 54, 37, 17, 29, 88, 235] }; pub const LocalizedControlType_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2271428687, data2: 41405, data3: 17706, data4: [137, 196, 63, 1, 211, 131, 56, 6] }; pub const LocalizedLandmarkType_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2059934080, data2: 60155, data3: 20402, data4: [191, 145, 244, 133, 190, 245, 232, 225], }; #[repr(C)] pub struct MOUSEKEYS { pub cbSize: u32, pub dwFlags: u32, pub iMaxSpeed: u32, pub iTimeToMaxSpeed: u32, pub iCtrlSpeed: u32, pub dwReserved1: u32, pub dwReserved2: u32, } impl ::core::marker::Copy for MOUSEKEYS {} impl ::core::clone::Clone for MOUSEKEYS { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct MSAAMENUINFO { pub dwMSAASignature: u32, pub cchWText: u32, pub pszWText: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for MSAAMENUINFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for MSAAMENUINFO { fn clone(&self) -> Self { *self } } pub const MSAA_MENU_SIG: i32 = -1441927155i32; pub const MenuBar_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3426239056, data2: 3707, data3: 19176, data4: [149, 174, 160, 143, 38, 27, 82, 238] }; pub const MenuClosed_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1022436974, data2: 5506, data3: 16449, data4: [172, 215, 136, 163, 90, 150, 82, 151], }; pub const MenuItem_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4099024339, data2: 53408, data3: 18904, data4: [152, 52, 154, 0, 13, 42, 237, 220] }; pub const MenuModeEnd_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2664254623, data2: 32989, data3: 18360, data4: [130, 103, 90, 236, 6, 187, 44, 255] }; pub const MenuModeStart_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 416794161, data2: 5738, data3: 19145, data4: [174, 59, 239, 75, 84, 32, 230, 129] }; pub const MenuOpened_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3957516613, data2: 26314, data3: 20177, data4: [159, 248, 42, 215, 223, 10, 27, 8] }; pub const Menu_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 781915200, data2: 3752, data3: 16893, data4: [179, 116, 193, 234, 111, 80, 60, 209] }; pub const MultipleView_CurrentView_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2055317114, data2: 47439, data3: 18549, data4: [145, 139, 101, 200, 210, 249, 152, 229], }; pub const MultipleView_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1417308900, data2: 4415, data3: 18372, data4: [133, 15, 219, 77, 250, 70, 107, 29] }; pub const MultipleView_SupportedViews_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2371729917, data2: 52796, data3: 19175, data4: [183, 136, 64, 10, 60, 100, 85, 71] }; pub const NAVDIR_DOWN: u32 = 2u32; pub const NAVDIR_FIRSTCHILD: u32 = 7u32; pub const NAVDIR_LASTCHILD: u32 = 8u32; pub const NAVDIR_LEFT: u32 = 3u32; pub const NAVDIR_MAX: u32 = 9u32; pub const NAVDIR_MIN: u32 = 0u32; pub const NAVDIR_NEXT: u32 = 5u32; pub const NAVDIR_PREVIOUS: u32 = 6u32; pub const NAVDIR_RIGHT: u32 = 4u32; pub const NAVDIR_UP: u32 = 1u32; pub const Name_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3282473499, data2: 19097, data3: 17649, data4: [188, 166, 97, 24, 112, 82, 196, 49] }; pub type NavigateDirection = i32; pub const NavigateDirection_Parent: NavigateDirection = 0i32; pub const NavigateDirection_NextSibling: NavigateDirection = 1i32; pub const NavigateDirection_PreviousSibling: NavigateDirection = 2i32; pub const NavigateDirection_FirstChild: NavigateDirection = 3i32; pub const NavigateDirection_LastChild: NavigateDirection = 4i32; pub const NewNativeWindowHandle_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1368830779, data2: 14346, data3: 18818, data4: [149, 225, 145, 243, 239, 96, 224, 36], }; pub type NormalizeState = i32; pub const NormalizeState_None: NormalizeState = 0i32; pub const NormalizeState_View: NormalizeState = 1i32; pub const NormalizeState_Custom: NormalizeState = 2i32; pub type NotificationKind = i32; pub const NotificationKind_ItemAdded: NotificationKind = 0i32; pub const NotificationKind_ItemRemoved: NotificationKind = 1i32; pub const NotificationKind_ActionCompleted: NotificationKind = 2i32; pub const NotificationKind_ActionAborted: NotificationKind = 3i32; pub const NotificationKind_Other: NotificationKind = 4i32; pub type NotificationProcessing = i32; pub const NotificationProcessing_ImportantAll: NotificationProcessing = 0i32; pub const NotificationProcessing_ImportantMostRecent: NotificationProcessing = 1i32; pub const NotificationProcessing_All: NotificationProcessing = 2i32; pub const NotificationProcessing_MostRecent: NotificationProcessing = 3i32; pub const NotificationProcessing_CurrentThenMostRecent: NotificationProcessing = 4i32; pub const Notification_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1925554935, data2: 38792, data3: 18447, data4: [184, 235, 77, 238, 0, 246, 24, 111] }; pub const ObjectModel_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1040493822, data2: 2300, data3: 18412, data4: [150, 188, 53, 63, 163, 179, 74, 167] }; pub const OptimizeForVisualContent_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1787109968, data2: 51034, data3: 20061, data4: [184, 88, 227, 129, 176, 247, 136, 97], }; pub type OrientationType = i32; pub const OrientationType_None: OrientationType = 0i32; pub const OrientationType_Horizontal: OrientationType = 1i32; pub const OrientationType_Vertical: OrientationType = 2i32; pub const Orientation_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2686381666, data2: 14468, data3: 17429, data4: [136, 126, 103, 142, 194, 30, 57, 186], }; pub const OutlineColor_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3281376960, data2: 19285, data3: 18274, data4: [160, 115, 253, 48, 58, 99, 79, 82] }; pub type OutlineStyles = i32; pub const OutlineStyles_None: OutlineStyles = 0i32; pub const OutlineStyles_Outline: OutlineStyles = 1i32; pub const OutlineStyles_Shadow: OutlineStyles = 2i32; pub const OutlineStyles_Engraved: OutlineStyles = 4i32; pub const OutlineStyles_Embossed: OutlineStyles = 8i32; pub const OutlineThickness_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 333872327, data2: 56002, data3: 18568, data4: [189, 211, 55, 92, 98, 250, 150, 24] }; pub const PROPID_ACC_DEFAULTACTION: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 403441451, data2: 49791, data3: 17351, data4: [153, 34, 246, 53, 98, 164, 99, 43] }; pub const PROPID_ACC_DESCRIPTION: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1296621540, data2: 48447, data3: 18719, data4: [166, 72, 73, 45, 111, 32, 197, 136] }; pub const PROPID_ACC_DESCRIPTIONMAP: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 535905119, data2: 35348, data3: 18299, data4: [178, 38, 160, 171, 226, 121, 151, 93], }; pub const PROPID_ACC_DODEFAULTACTION: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 463508771, data2: 11835, data3: 18854, data4: [160, 89, 89, 104, 42, 60, 72, 253] }; pub const PROPID_ACC_FOCUS: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1857238495, data2: 7209, data3: 16679, data4: [177, 44, 222, 233, 253, 21, 127, 43] }; pub const PROPID_ACC_HELP: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3358712095, data2: 17627, data3: 19097, data4: [151, 104, 203, 143, 151, 139, 114, 49], }; pub const PROPID_ACC_HELPTOPIC: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2021462905, data2: 36574, data3: 17419, data4: [138, 236, 17, 247, 191, 144, 48, 179], }; pub const PROPID_ACC_KEYBOARDSHORTCUT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2107363054, data2: 32030, data3: 18809, data4: [147, 130, 81, 128, 244, 23, 44, 52] }; pub const PROPID_ACC_NAME: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1619869176, data2: 33064, data3: 19111, data4: [164, 40, 245, 94, 73, 38, 114, 145] }; pub const PROPID_ACC_NAV_DOWN: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 51802349, data2: 15583, data3: 18642, data4: [150, 19, 19, 143, 45, 216, 166, 104] }; pub const PROPID_ACC_NAV_FIRSTCHILD: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3486524760, data2: 21883, data3: 19559, data4: [132, 249, 42, 9, 252, 228, 7, 73] }; pub const PROPID_ACC_NAV_LASTCHILD: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 808372901, data2: 18645, data3: 20365, data4: [182, 113, 26, 141, 32, 167, 120, 50] }; pub const PROPID_ACC_NAV_LEFT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 578848459, data2: 33521, data3: 19001, data4: [135, 5, 220, 220, 15, 255, 146, 245] }; pub const PROPID_ACC_NAV_NEXT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 484201557, data2: 36057, data3: 19602, data4: [163, 113, 57, 57, 162, 254, 62, 238] }; pub const PROPID_ACC_NAV_PREV: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2003646609, data2: 51003, data3: 17536, data4: [179, 246, 7, 106, 22, 161, 90, 246] }; pub const PROPID_ACC_NAV_RIGHT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3441499551, data2: 57803, data3: 20453, data4: [167, 124, 146, 11, 136, 77, 9, 91] }; pub const PROPID_ACC_NAV_UP: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 23992875, data2: 6734, data3: 18279, data4: [134, 18, 51, 134, 246, 105, 53, 236] }; pub const PROPID_ACC_PARENT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1196171958, data2: 65474, data3: 18042, data4: [177, 181, 233, 88, 180, 101, 115, 48], }; pub const PROPID_ACC_ROLE: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3415236594, data2: 31697, data3: 19461, data4: [179, 200, 230, 194, 65, 54, 77, 112], }; pub const PROPID_ACC_ROLEMAP: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4154117538, data2: 5133, data3: 20454, data4: [137, 20, 32, 132, 118, 50, 130, 105] }; pub const PROPID_ACC_SELECTION: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3114075964, data2: 55089, data3: 16475, data4: [144, 97, 217, 94, 143, 132, 41, 132], }; pub const PROPID_ACC_STATE: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2832520624, data2: 2593, data3: 17104, data4: [165, 192, 81, 78, 152, 79, 69, 123] }; pub const PROPID_ACC_STATEMAP: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1133800542, data2: 2752, data3: 16450, data4: [181, 37, 7, 187, 219, 225, 127, 167] }; pub const PROPID_ACC_VALUE: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 306177091, data2: 8474, data3: 17941, data4: [149, 39, 196, 90, 126, 147, 113, 122] }; pub const PROPID_ACC_VALUEMAP: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3659283833, data2: 64604, data3: 16910, data4: [179, 153, 157, 21, 51, 84, 158, 117], }; pub const Pane_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1546338139, data2: 37250, data3: 17059, data4: [141, 236, 140, 4, 193, 238, 99, 77] }; pub const PositionInSet_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 869391444, data2: 25630, data3: 19830, data4: [166, 177, 19, 243, 65, 193, 248, 150], }; pub const ProcessId_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1078565272, data2: 39985, data3: 16965, data4: [164, 3, 135, 50, 14, 89, 234, 246] }; pub const ProgressBar_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 579641222, data2: 50028, data3: 18363, data4: [159, 182, 165, 131, 75, 252, 83, 164], }; pub type PropertyConditionFlags = i32; pub const PropertyConditionFlags_None: PropertyConditionFlags = 0i32; pub const PropertyConditionFlags_IgnoreCase: PropertyConditionFlags = 1i32; pub const PropertyConditionFlags_MatchSubstring: PropertyConditionFlags = 2i32; pub const ProviderDescription_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3701829770, data2: 49515, data3: 19673, data4: [184, 137, 190, 177, 106, 128, 73, 4], }; pub type ProviderOptions = i32; pub const ProviderOptions_ClientSideProvider: ProviderOptions = 1i32; pub const ProviderOptions_ServerSideProvider: ProviderOptions = 2i32; pub const ProviderOptions_NonClientAreaProvider: ProviderOptions = 4i32; pub const ProviderOptions_OverrideProvider: ProviderOptions = 8i32; pub const ProviderOptions_ProviderOwnsSetFocus: ProviderOptions = 16i32; pub const ProviderOptions_UseComThreading: ProviderOptions = 32i32; pub const ProviderOptions_RefuseNonClientSupport: ProviderOptions = 64i32; pub const ProviderOptions_HasNativeIAccessible: ProviderOptions = 128i32; pub const ProviderOptions_UseClientCoordinates: ProviderOptions = 256i32; pub type ProviderType = i32; pub const ProviderType_BaseHwnd: ProviderType = 0i32; pub const ProviderType_Proxy: ProviderType = 1i32; pub const ProviderType_NonClientArea: ProviderType = 2i32; pub const ROLE_SYSTEM_ALERT: u32 = 8u32; pub const ROLE_SYSTEM_ANIMATION: u32 = 54u32; pub const ROLE_SYSTEM_APPLICATION: u32 = 14u32; pub const ROLE_SYSTEM_BORDER: u32 = 19u32; pub const ROLE_SYSTEM_BUTTONDROPDOWN: u32 = 56u32; pub const ROLE_SYSTEM_BUTTONDROPDOWNGRID: u32 = 58u32; pub const ROLE_SYSTEM_BUTTONMENU: u32 = 57u32; pub const ROLE_SYSTEM_CARET: u32 = 7u32; pub const ROLE_SYSTEM_CELL: u32 = 29u32; pub const ROLE_SYSTEM_CHARACTER: u32 = 32u32; pub const ROLE_SYSTEM_CHART: u32 = 17u32; pub const ROLE_SYSTEM_CHECKBUTTON: u32 = 44u32; pub const ROLE_SYSTEM_CLIENT: u32 = 10u32; pub const ROLE_SYSTEM_CLOCK: u32 = 61u32; pub const ROLE_SYSTEM_COLUMN: u32 = 27u32; pub const ROLE_SYSTEM_COLUMNHEADER: u32 = 25u32; pub const ROLE_SYSTEM_COMBOBOX: u32 = 46u32; pub const ROLE_SYSTEM_CURSOR: u32 = 6u32; pub const ROLE_SYSTEM_DIAGRAM: u32 = 53u32; pub const ROLE_SYSTEM_DIAL: u32 = 49u32; pub const ROLE_SYSTEM_DIALOG: u32 = 18u32; pub const ROLE_SYSTEM_DOCUMENT: u32 = 15u32; pub const ROLE_SYSTEM_DROPLIST: u32 = 47u32; pub const ROLE_SYSTEM_EQUATION: u32 = 55u32; pub const ROLE_SYSTEM_GRAPHIC: u32 = 40u32; pub const ROLE_SYSTEM_GRIP: u32 = 4u32; pub const ROLE_SYSTEM_GROUPING: u32 = 20u32; pub const ROLE_SYSTEM_HELPBALLOON: u32 = 31u32; pub const ROLE_SYSTEM_HOTKEYFIELD: u32 = 50u32; pub const ROLE_SYSTEM_INDICATOR: u32 = 39u32; pub const ROLE_SYSTEM_IPADDRESS: u32 = 63u32; pub const ROLE_SYSTEM_LINK: u32 = 30u32; pub const ROLE_SYSTEM_LIST: u32 = 33u32; pub const ROLE_SYSTEM_LISTITEM: u32 = 34u32; pub const ROLE_SYSTEM_MENUBAR: u32 = 2u32; pub const ROLE_SYSTEM_MENUITEM: u32 = 12u32; pub const ROLE_SYSTEM_MENUPOPUP: u32 = 11u32; pub const ROLE_SYSTEM_OUTLINE: u32 = 35u32; pub const ROLE_SYSTEM_OUTLINEBUTTON: u32 = 64u32; pub const ROLE_SYSTEM_OUTLINEITEM: u32 = 36u32; pub const ROLE_SYSTEM_PAGETAB: u32 = 37u32; pub const ROLE_SYSTEM_PAGETABLIST: u32 = 60u32; pub const ROLE_SYSTEM_PANE: u32 = 16u32; pub const ROLE_SYSTEM_PROGRESSBAR: u32 = 48u32; pub const ROLE_SYSTEM_PROPERTYPAGE: u32 = 38u32; pub const ROLE_SYSTEM_PUSHBUTTON: u32 = 43u32; pub const ROLE_SYSTEM_RADIOBUTTON: u32 = 45u32; pub const ROLE_SYSTEM_ROW: u32 = 28u32; pub const ROLE_SYSTEM_ROWHEADER: u32 = 26u32; pub const ROLE_SYSTEM_SCROLLBAR: u32 = 3u32; pub const ROLE_SYSTEM_SEPARATOR: u32 = 21u32; pub const ROLE_SYSTEM_SLIDER: u32 = 51u32; pub const ROLE_SYSTEM_SOUND: u32 = 5u32; pub const ROLE_SYSTEM_SPINBUTTON: u32 = 52u32; pub const ROLE_SYSTEM_SPLITBUTTON: u32 = 62u32; pub const ROLE_SYSTEM_STATICTEXT: u32 = 41u32; pub const ROLE_SYSTEM_STATUSBAR: u32 = 23u32; pub const ROLE_SYSTEM_TABLE: u32 = 24u32; pub const ROLE_SYSTEM_TEXT: u32 = 42u32; pub const ROLE_SYSTEM_TITLEBAR: u32 = 1u32; pub const ROLE_SYSTEM_TOOLBAR: u32 = 22u32; pub const ROLE_SYSTEM_TOOLTIP: u32 = 13u32; pub const ROLE_SYSTEM_WHITESPACE: u32 = 59u32; pub const ROLE_SYSTEM_WINDOW: u32 = 9u32; pub const RadioButton_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1004227035, data2: 65068, data3: 17539, data4: [179, 225, 229, 127, 33, 148, 64, 198], }; pub const RangeValue_IsReadOnly_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 637145173, data2: 57023, data3: 17267, data4: [167, 158, 31, 26, 25, 8, 211, 196] }; pub const RangeValue_LargeChange_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2717475621, data2: 14909, data3: 19268, data4: [142, 31, 74, 70, 217, 132, 64, 25] }; pub const RangeValue_Maximum_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 422680852, data2: 63865, data3: 19253, data4: [161, 166, 211, 126, 5, 67, 52, 115] }; pub const RangeValue_Minimum_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2026623922, data2: 26701, data3: 18528, data4: [175, 147, 209, 249, 92, 176, 34, 253], }; pub const RangeValue_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 414190983, data2: 45513, data3: 18282, data4: [191, 189, 95, 11, 219, 146, 111, 99] }; pub const RangeValue_SmallChange_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2177025111, data2: 14657, data3: 16647, data4: [153, 117, 19, 151, 96, 247, 192, 114], }; pub const RangeValue_Value_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 320822680, data2: 50444, data3: 18589, data4: [171, 229, 174, 34, 8, 152, 197, 247] }; pub const Rotation_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1987894397, data2: 44736, data3: 16656, data4: [173, 50, 48, 237, 212, 3, 73, 46] }; pub type RowOrColumnMajor = i32; pub const RowOrColumnMajor_RowMajor: RowOrColumnMajor = 0i32; pub const RowOrColumnMajor_ColumnMajor: RowOrColumnMajor = 1i32; pub const RowOrColumnMajor_Indeterminate: RowOrColumnMajor = 2i32; pub const RuntimeId_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2745101306, data2: 32698, data3: 19593, data4: [180, 212, 185, 158, 45, 231, 209, 96], }; pub const SELFLAG_ADDSELECTION: u32 = 8u32; pub const SELFLAG_EXTENDSELECTION: u32 = 4u32; pub const SELFLAG_NONE: u32 = 0u32; pub const SELFLAG_REMOVESELECTION: u32 = 16u32; pub const SELFLAG_TAKEFOCUS: u32 = 1u32; pub const SELFLAG_TAKESELECTION: u32 = 2u32; pub const SELFLAG_VALID: u32 = 31u32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct SERIALKEYSA { pub cbSize: u32, pub dwFlags: SERIALKEYS_FLAGS, pub lpszActivePort: super::super::Foundation::PSTR, pub lpszPort: super::super::Foundation::PSTR, pub iBaudRate: u32, pub iPortState: u32, pub iActive: u32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for SERIALKEYSA {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for SERIALKEYSA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct SERIALKEYSW { pub cbSize: u32, pub dwFlags: SERIALKEYS_FLAGS, pub lpszActivePort: super::super::Foundation::PWSTR, pub lpszPort: super::super::Foundation::PWSTR, pub iBaudRate: u32, pub iPortState: u32, pub iActive: u32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for SERIALKEYSW {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for SERIALKEYSW { fn clone(&self) -> Self { *self } } pub type SERIALKEYS_FLAGS = u32; pub const SERKF_AVAILABLE: SERIALKEYS_FLAGS = 2u32; pub const SERKF_INDICATOR: SERIALKEYS_FLAGS = 4u32; pub const SERKF_SERIALKEYSON: SERIALKEYS_FLAGS = 1u32; pub const SID_ControlElementProvider: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4101578088, data2: 57940, data3: 19363, data4: [154, 83, 38, 165, 197, 73, 121, 70] }; pub const SID_IsUIAutomationObject: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3111115653, data2: 29188, data3: 18212, data4: [132, 43, 199, 5, 157, 237, 185, 208], }; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct SOUNDSENTRYA { pub cbSize: u32, pub dwFlags: SOUNDSENTRY_FLAGS, pub iFSTextEffect: SOUNDSENTRY_TEXT_EFFECT, pub iFSTextEffectMSec: u32, pub iFSTextEffectColorBits: u32, pub iFSGrafEffect: SOUND_SENTRY_GRAPHICS_EFFECT, pub iFSGrafEffectMSec: u32, pub iFSGrafEffectColor: u32, pub iWindowsEffect: SOUNDSENTRY_WINDOWS_EFFECT, pub iWindowsEffectMSec: u32, pub lpszWindowsEffectDLL: super::super::Foundation::PSTR, pub iWindowsEffectOrdinal: u32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for SOUNDSENTRYA {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for SOUNDSENTRYA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct SOUNDSENTRYW { pub cbSize: u32, pub dwFlags: SOUNDSENTRY_FLAGS, pub iFSTextEffect: SOUNDSENTRY_TEXT_EFFECT, pub iFSTextEffectMSec: u32, pub iFSTextEffectColorBits: u32, pub iFSGrafEffect: SOUND_SENTRY_GRAPHICS_EFFECT, pub iFSGrafEffectMSec: u32, pub iFSGrafEffectColor: u32, pub iWindowsEffect: SOUNDSENTRY_WINDOWS_EFFECT, pub iWindowsEffectMSec: u32, pub lpszWindowsEffectDLL: super::super::Foundation::PWSTR, pub iWindowsEffectOrdinal: u32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for SOUNDSENTRYW {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for SOUNDSENTRYW { fn clone(&self) -> Self { *self } } pub type SOUNDSENTRY_FLAGS = u32; pub const SSF_SOUNDSENTRYON: SOUNDSENTRY_FLAGS = 1u32; pub const SSF_AVAILABLE: SOUNDSENTRY_FLAGS = 2u32; pub const SSF_INDICATOR: SOUNDSENTRY_FLAGS = 4u32; pub type SOUNDSENTRY_TEXT_EFFECT = u32; pub const SSTF_BORDER: SOUNDSENTRY_TEXT_EFFECT = 2u32; pub const SSTF_CHARS: SOUNDSENTRY_TEXT_EFFECT = 1u32; pub const SSTF_DISPLAY: SOUNDSENTRY_TEXT_EFFECT = 3u32; pub const SSTF_NONE: SOUNDSENTRY_TEXT_EFFECT = 0u32; pub type SOUNDSENTRY_WINDOWS_EFFECT = u32; pub const SSWF_CUSTOM: SOUNDSENTRY_WINDOWS_EFFECT = 4u32; pub const SSWF_DISPLAY: SOUNDSENTRY_WINDOWS_EFFECT = 3u32; pub const SSWF_NONE: SOUNDSENTRY_WINDOWS_EFFECT = 0u32; pub const SSWF_TITLE: SOUNDSENTRY_WINDOWS_EFFECT = 1u32; pub const SSWF_WINDOW: SOUNDSENTRY_WINDOWS_EFFECT = 2u32; pub type SOUND_SENTRY_GRAPHICS_EFFECT = u32; pub const SSGF_DISPLAY: SOUND_SENTRY_GRAPHICS_EFFECT = 3u32; pub const SSGF_NONE: SOUND_SENTRY_GRAPHICS_EFFECT = 0u32; pub const STATE_SYSTEM_HASPOPUP: u32 = 1073741824u32; pub const STATE_SYSTEM_NORMAL: u32 = 0u32; #[repr(C)] pub struct STICKYKEYS { pub cbSize: u32, pub dwFlags: STICKYKEYS_FLAGS, } impl ::core::marker::Copy for STICKYKEYS {} impl ::core::clone::Clone for STICKYKEYS { fn clone(&self) -> Self { *self } } pub type STICKYKEYS_FLAGS = u32; pub const SKF_STICKYKEYSON: STICKYKEYS_FLAGS = 1u32; pub const SKF_AVAILABLE: STICKYKEYS_FLAGS = 2u32; pub const SKF_HOTKEYACTIVE: STICKYKEYS_FLAGS = 4u32; pub const SKF_CONFIRMHOTKEY: STICKYKEYS_FLAGS = 8u32; pub const SKF_HOTKEYSOUND: STICKYKEYS_FLAGS = 16u32; pub const SKF_INDICATOR: STICKYKEYS_FLAGS = 32u32; pub const SKF_AUDIBLEFEEDBACK: STICKYKEYS_FLAGS = 64u32; pub const SKF_TRISTATE: STICKYKEYS_FLAGS = 128u32; pub const SKF_TWOKEYSOFF: STICKYKEYS_FLAGS = 256u32; pub const SKF_LALTLATCHED: STICKYKEYS_FLAGS = 268435456u32; pub const SKF_LCTLLATCHED: STICKYKEYS_FLAGS = 67108864u32; pub const SKF_LSHIFTLATCHED: STICKYKEYS_FLAGS = 16777216u32; pub const SKF_RALTLATCHED: STICKYKEYS_FLAGS = 536870912u32; pub const SKF_RCTLLATCHED: STICKYKEYS_FLAGS = 134217728u32; pub const SKF_RSHIFTLATCHED: STICKYKEYS_FLAGS = 33554432u32; pub const SKF_LWINLATCHED: STICKYKEYS_FLAGS = 1073741824u32; pub const SKF_RWINLATCHED: STICKYKEYS_FLAGS = 2147483648u32; pub const SKF_LALTLOCKED: STICKYKEYS_FLAGS = 1048576u32; pub const SKF_LCTLLOCKED: STICKYKEYS_FLAGS = 262144u32; pub const SKF_LSHIFTLOCKED: STICKYKEYS_FLAGS = 65536u32; pub const SKF_RALTLOCKED: STICKYKEYS_FLAGS = 2097152u32; pub const SKF_RCTLLOCKED: STICKYKEYS_FLAGS = 524288u32; pub const SKF_RSHIFTLOCKED: STICKYKEYS_FLAGS = 131072u32; pub const SKF_LWINLOCKED: STICKYKEYS_FLAGS = 4194304u32; pub const SKF_RWINLOCKED: STICKYKEYS_FLAGS = 8388608u32; pub type SayAsInterpretAs = i32; pub const SayAsInterpretAs_None: SayAsInterpretAs = 0i32; pub const SayAsInterpretAs_Spell: SayAsInterpretAs = 1i32; pub const SayAsInterpretAs_Cardinal: SayAsInterpretAs = 2i32; pub const SayAsInterpretAs_Ordinal: SayAsInterpretAs = 3i32; pub const SayAsInterpretAs_Number: SayAsInterpretAs = 4i32; pub const SayAsInterpretAs_Date: SayAsInterpretAs = 5i32; pub const SayAsInterpretAs_Time: SayAsInterpretAs = 6i32; pub const SayAsInterpretAs_Telephone: SayAsInterpretAs = 7i32; pub const SayAsInterpretAs_Currency: SayAsInterpretAs = 8i32; pub const SayAsInterpretAs_Net: SayAsInterpretAs = 9i32; pub const SayAsInterpretAs_Url: SayAsInterpretAs = 10i32; pub const SayAsInterpretAs_Address: SayAsInterpretAs = 11i32; pub const SayAsInterpretAs_Alphanumeric: SayAsInterpretAs = 12i32; pub const SayAsInterpretAs_Name: SayAsInterpretAs = 13i32; pub const SayAsInterpretAs_Media: SayAsInterpretAs = 14i32; pub const SayAsInterpretAs_Date_MonthDayYear: SayAsInterpretAs = 15i32; pub const SayAsInterpretAs_Date_DayMonthYear: SayAsInterpretAs = 16i32; pub const SayAsInterpretAs_Date_YearMonthDay: SayAsInterpretAs = 17i32; pub const SayAsInterpretAs_Date_YearMonth: SayAsInterpretAs = 18i32; pub const SayAsInterpretAs_Date_MonthYear: SayAsInterpretAs = 19i32; pub const SayAsInterpretAs_Date_DayMonth: SayAsInterpretAs = 20i32; pub const SayAsInterpretAs_Date_MonthDay: SayAsInterpretAs = 21i32; pub const SayAsInterpretAs_Date_Year: SayAsInterpretAs = 22i32; pub const SayAsInterpretAs_Time_HoursMinutesSeconds12: SayAsInterpretAs = 23i32; pub const SayAsInterpretAs_Time_HoursMinutes12: SayAsInterpretAs = 24i32; pub const SayAsInterpretAs_Time_HoursMinutesSeconds24: SayAsInterpretAs = 25i32; pub const SayAsInterpretAs_Time_HoursMinutes24: SayAsInterpretAs = 26i32; pub type ScrollAmount = i32; pub const ScrollAmount_LargeDecrement: ScrollAmount = 0i32; pub const ScrollAmount_SmallDecrement: ScrollAmount = 1i32; pub const ScrollAmount_NoAmount: ScrollAmount = 2i32; pub const ScrollAmount_LargeIncrement: ScrollAmount = 3i32; pub const ScrollAmount_SmallIncrement: ScrollAmount = 4i32; pub const ScrollBar_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3673377590, data2: 20581, data3: 18758, data4: [178, 47, 146, 89, 95, 192, 117, 26] }; pub const ScrollItem_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1167183877, data2: 43011, data3: 19804, data4: [180, 213, 141, 40, 0, 249, 6, 167] }; pub const Scroll_HorizontalScrollPercent_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3351329806, data2: 60193, data3: 18431, data4: [172, 196, 181, 163, 53, 15, 81, 145], }; pub const Scroll_HorizontalViewSize_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1891821012, data2: 64688, data3: 18195, data4: [169, 170, 175, 146, 255, 121, 228, 205], }; pub const Scroll_HorizontallyScrollable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2341622087, data2: 10445, data3: 18862, data4: [189, 99, 244, 65, 24, 210, 231, 25] }; pub const Scroll_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2304746676, data2: 30109, data3: 19536, data4: [142, 21, 3, 70, 6, 114, 0, 60] }; pub const Scroll_VerticalScrollPercent_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1821208729, data2: 45736, data3: 18760, data4: [191, 247, 60, 249, 5, 139, 254, 251], }; pub const Scroll_VerticalViewSize_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3731500578, data2: 55495, data3: 16581, data4: [131, 186, 229, 246, 129, 213, 49, 8], }; pub const Scroll_VerticallyScrollable_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2299938712, data2: 104, data3: 17173, data4: [184, 154, 30, 124, 251, 188, 61, 252] }; pub const Selection2_CurrentSelectedItem_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 874871846, data2: 33717, data3: 16806, data4: [147, 156, 174, 132, 28, 19, 98, 54] }; pub const Selection2_FirstSelectedItem_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3424971367, data2: 13980, data3: 20053, data4: [159, 247, 56, 218, 105, 84, 12, 41] }; pub const Selection2_ItemCount_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3142183839, data2: 17773, data3: 16456, data4: [181, 145, 156, 32, 38, 184, 70, 54] }; pub const Selection2_LastSelectedItem_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3481000592, data2: 11651, data3: 18936, data4: [134, 12, 156, 227, 148, 207, 137, 180], }; pub const SelectionItem_ElementAddedToSelectionEvent_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1015164369, data2: 50183, data3: 19898, data4: [145, 221, 121, 212, 174, 208, 174, 198], }; pub const SelectionItem_ElementRemovedFromSelectionEvent_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 159361193, data2: 28793, data3: 16815, data4: [139, 156, 9, 52, 216, 48, 94, 92] }; pub const SelectionItem_ElementSelectedEvent_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3116882939, data2: 20158, data3: 17714, data4: [170, 244, 0, 140, 246, 71, 35, 60] }; pub const SelectionItem_IsSelected_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4045570911, data2: 52575, data3: 17375, data4: [183, 157, 75, 132, 158, 158, 96, 32], }; pub const SelectionItem_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2613464811, data2: 34759, data3: 19240, data4: [148, 187, 77, 159, 164, 55, 182, 239], }; pub const SelectionItem_SelectionContainer_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2755025774, data2: 39966, data3: 19299, data4: [139, 83, 194, 66, 29, 209, 232, 251], }; pub const Selection_CanSelectMultiple_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1238842789, data2: 51331, data3: 17664, data4: [136, 61, 143, 207, 141, 175, 108, 190], }; pub const Selection_InvalidatedEvent_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3401664772, data2: 5812, data3: 19283, data4: [142, 71, 76, 177, 223, 38, 123, 183] }; pub const Selection_IsSelectionRequired_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2980987938, data2: 25598, data3: 17639, data4: [165, 165, 167, 56, 200, 41, 177, 154], }; pub const Selection_Pattern2_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4221721771, data2: 43928, data3: 18935, data4: [167, 220, 254, 83, 157, 193, 91, 231], }; pub const Selection_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1726199784, data2: 55329, data3: 19749, data4: [135, 97, 67, 93, 44, 139, 37, 63] }; pub const Selection_Selection_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2859319970, data2: 3627, data3: 19768, data4: [150, 213, 52, 228, 112, 184, 24, 83] }; pub const SemanticZoom_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1607682627, data2: 1566, data3: 17096, data4: [181, 137, 157, 204, 247, 75, 196, 58], }; pub const Separator_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2271734691, data2: 10851, data3: 19120, data4: [172, 141, 170, 80, 226, 61, 233, 120], }; pub const SizeOfSet_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 369152828, data2: 15263, data3: 17257, data4: [148, 49, 170, 41, 63, 52, 76, 241] }; pub const Size_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 727676445, data2: 63621, data3: 17412, data4: [151, 63, 155, 29, 152, 227, 109, 143], }; pub const Slider_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2956182091, data2: 15157, data3: 19690, data4: [182, 9, 118, 54, 130, 250, 102, 11] }; pub const Spinner_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1624001336, data2: 15537, data3: 16737, data4: [180, 66, 198, 183, 38, 193, 120, 37], }; pub const SplitButton_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1880223775, data2: 19150, data3: 18689, data4: [180, 97, 146, 10, 111, 28, 166, 80] }; pub const SpreadsheetItem_AnnotationObjects_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2736344120, data2: 51644, data3: 17924, data4: [147, 150, 174, 63, 159, 69, 127, 123], }; pub const SpreadsheetItem_AnnotationTypes_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3339473360, data2: 54786, data3: 19269, data4: [175, 188, 180, 113, 43, 150, 215, 43], }; pub const SpreadsheetItem_Formula_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3858949245, data2: 6983, data3: 19434, data4: [135, 207, 59, 11, 11, 92, 21, 182] }; pub const SpreadsheetItem_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 852460543, data2: 61864, data3: 19084, data4: [134, 88, 212, 123, 167, 78, 32, 186] }; pub const Spreadsheet_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1784358089, data2: 40222, data3: 19333, data4: [158, 68, 192, 46, 49, 105, 177, 11] }; pub const StatusBar_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3562962203, data2: 22643, data3: 18271, data4: [149, 164, 4, 51, 225, 241, 176, 10] }; pub type StructureChangeType = i32; pub const StructureChangeType_ChildAdded: StructureChangeType = 0i32; pub const StructureChangeType_ChildRemoved: StructureChangeType = 1i32; pub const StructureChangeType_ChildrenInvalidated: StructureChangeType = 2i32; pub const StructureChangeType_ChildrenBulkAdded: StructureChangeType = 3i32; pub const StructureChangeType_ChildrenBulkRemoved: StructureChangeType = 4i32; pub const StructureChangeType_ChildrenReordered: StructureChangeType = 5i32; pub const StructureChanged_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1503099233, data2: 16093, data3: 19217, data4: [177, 59, 103, 107, 42, 42, 108, 169], }; pub const StructuredMarkup_CompositionComplete_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3297393687, data2: 26490, data3: 16455, data4: [166, 141, 252, 18, 87, 82, 138, 239], }; pub const StructuredMarkup_Deleted_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4191199264, data2: 57793, data3: 20175, data4: [185, 170, 82, 239, 222, 126, 65, 225], }; pub const StructuredMarkup_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2881292408, data2: 34405, data3: 20316, data4: [148, 252, 54, 231, 216, 187, 112, 107], }; pub const StructuredMarkup_SelectionChanged_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2814907895, data2: 65439, data3: 16839, data4: [163, 167, 171, 108, 191, 219, 73, 3], }; pub const StyleId_BulletedList: i32 = 70015i32; pub const StyleId_BulletedList_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1499721060, data2: 25638, data3: 17970, data4: [140, 175, 163, 42, 212, 2, 217, 26] }; pub const StyleId_Custom: i32 = 70000i32; pub const StyleId_Custom_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4012825918, data2: 43417, data3: 19324, data4: [163, 120, 9, 187, 213, 42, 53, 22] }; pub const StyleId_Emphasis: i32 = 70013i32; pub const StyleId_Emphasis_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3396238782, data2: 13662, data3: 18464, data4: [149, 160, 146, 95, 4, 29, 52, 112] }; pub const StyleId_Heading1: i32 = 70001i32; pub const StyleId_Heading1_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2139000681, data2: 26726, data3: 17953, data4: [147, 12, 154, 93, 12, 165, 150, 28] }; pub const StyleId_Heading2: i32 = 70002i32; pub const StyleId_Heading2_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3131683393, data2: 23657, data3: 18077, data4: [133, 173, 71, 71, 55, 181, 43, 20] }; pub const StyleId_Heading3: i32 = 70003i32; pub const StyleId_Heading3_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3213617618, data2: 55480, data3: 20165, data4: [140, 82, 156, 251, 13, 3, 89, 112] }; pub const StyleId_Heading4: i32 = 70004i32; pub const StyleId_Heading4_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2218196928, data2: 38264, data3: 17916, data4: [131, 164, 255, 64, 5, 51, 21, 221] }; pub const StyleId_Heading5: i32 = 70005i32; pub const StyleId_Heading5_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2426356301, data2: 3519, data3: 16494, data4: [151, 187, 78, 119, 61, 151, 152, 247], }; pub const StyleId_Heading6: i32 = 70006i32; pub const StyleId_Heading6_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2312254553, data2: 23899, data3: 18468, data4: [164, 32, 17, 211, 237, 130, 228, 15], }; pub const StyleId_Heading7: i32 = 70007i32; pub const StyleId_Heading7_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2742617203, data2: 59822, data3: 16941, data4: [184, 227, 59, 103, 92, 97, 129, 164], }; pub const StyleId_Heading8: i32 = 70008i32; pub const StyleId_Heading8_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 734085445, data2: 41996, data3: 18561, data4: [132, 174, 242, 35, 86, 133, 56, 12] }; pub const StyleId_Heading9: i32 = 70009i32; pub const StyleId_Heading9_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3339555123, data2: 47914, data3: 17363, data4: [138, 198, 51, 101, 120, 132, 176, 240], }; pub const StyleId_Normal: i32 = 70012i32; pub const StyleId_Normal_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3440694313, data2: 58462, data3: 17525, data4: [161, 197, 127, 158, 107, 233, 110, 186], }; pub const StyleId_NumberedList: i32 = 70016i32; pub const StyleId_NumberedList_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 513203157, data2: 25795, data3: 17360, data4: [177, 238, 181, 59, 6, 227, 237, 223] }; pub const StyleId_Quote: i32 = 70014i32; pub const StyleId_Quote_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1562124778, data2: 33173, data3: 20332, data4: [135, 234, 93, 171, 236, 230, 76, 29], }; pub const StyleId_Subtitle: i32 = 70011i32; pub const StyleId_Subtitle_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3050961943, data2: 23919, data3: 17440, data4: [180, 57, 124, 177, 154, 212, 52, 226], }; pub const StyleId_Title: i32 = 70010i32; pub const StyleId_Title_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 366485530, data2: 65487, data3: 18463, data4: [176, 161, 48, 182, 59, 233, 143, 7] }; pub const Styles_ExtendedProperties_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4099001760, data2: 47626, data3: 18049, data4: [176, 176, 13, 189, 181, 62, 88, 243], }; pub const Styles_FillColor_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1676671354, data2: 41413, data3: 19229, data4: [132, 235, 183, 101, 242, 237, 214, 50], }; pub const Styles_FillPatternColor_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2476366334, data2: 36797, data3: 20085, data4: [162, 113, 172, 69, 149, 25, 81, 99] }; pub const Styles_FillPatternStyle_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2177852703, data2: 18475, data3: 17489, data4: [163, 10, 225, 84, 94, 85, 79, 184] }; pub const Styles_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 451290709, data2: 55922, data3: 19808, data4: [161, 83, 229, 170, 105, 136, 227, 191], }; pub const Styles_Shape_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3340379128, data2: 30604, data3: 16397, data4: [132, 88, 59, 84, 62, 82, 105, 132] }; pub const Styles_StyleId_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3665986863, data2: 14359, data3: 16947, data4: [130, 175, 2, 39, 158, 114, 204, 119], }; pub const Styles_StyleName_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 470986805, data2: 1489, data3: 20309, data4: [158, 142, 20, 137, 243, 255, 85, 13] }; pub type SupportedTextSelection = i32; pub const SupportedTextSelection_None: SupportedTextSelection = 0i32; pub const SupportedTextSelection_Single: SupportedTextSelection = 1i32; pub const SupportedTextSelection_Multiple: SupportedTextSelection = 2i32; pub type SynchronizedInputType = i32; pub const SynchronizedInputType_KeyUp: SynchronizedInputType = 1i32; pub const SynchronizedInputType_KeyDown: SynchronizedInputType = 2i32; pub const SynchronizedInputType_LeftMouseUp: SynchronizedInputType = 4i32; pub const SynchronizedInputType_LeftMouseDown: SynchronizedInputType = 8i32; pub const SynchronizedInputType_RightMouseUp: SynchronizedInputType = 16i32; pub const SynchronizedInputType_RightMouseDown: SynchronizedInputType = 32i32; pub const SynchronizedInput_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 96635046, data2: 50299, data3: 18571, data4: [182, 83, 51, 151, 122, 85, 27, 139] }; pub const SystemAlert_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3530642525, data2: 31290, data3: 18343, data4: [132, 116, 129, 210, 154, 36, 81, 201], }; #[repr(C)] pub struct TOGGLEKEYS { pub cbSize: u32, pub dwFlags: u32, } impl ::core::marker::Copy for TOGGLEKEYS {} impl ::core::clone::Clone for TOGGLEKEYS { fn clone(&self) -> Self { *self } } pub const TabItem_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 745169743, data2: 37403, data3: 20078, data4: [178, 110, 8, 252, 176, 121, 143, 76] }; pub const Tab_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 952966957, data2: 13178, data3: 19410, data4: [165, 227, 173, 180, 105, 227, 11, 211], }; pub const TableItem_ColumnHeaderItems_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2524599971, data2: 29878, data3: 17182, data4: [141, 230, 153, 196, 17, 3, 28, 88] }; pub const TableItem_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3742581693, data2: 6280, data3: 18985, data4: [165, 12, 185, 46, 109, 227, 127, 111], }; pub const TableItem_RowHeaderItems_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3019396000, data2: 1396, data3: 19672, data4: [188, 215, 237, 89, 35, 87, 45, 151] }; pub const Table_ColumnHeaders_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2951862059, data2: 38541, data3: 17073, data4: [180, 89, 21, 11, 41, 157, 166, 100] }; pub const Table_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2000419342, data2: 23492, data3: 19947, data4: [146, 27, 222, 123, 50, 6, 34, 158] }; pub const Table_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3289719182, data2: 41000, data3: 17950, data4: [170, 146, 143, 146, 92, 247, 147, 81], }; pub const Table_RowHeaders_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3655555975, data2: 28344, data3: 17762, data4: [170, 198, 168, 169, 7, 82, 54, 168] }; pub const Table_RowOrColumnMajor_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2210297283, data2: 10750, data3: 18992, data4: [133, 225, 42, 98, 119, 253, 16, 110], }; pub const TextChild_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1966328503, data2: 15358, data3: 16879, data4: [158, 133, 226, 99, 140, 190, 22, 158], }; pub type TextDecorationLineStyle = i32; pub const TextDecorationLineStyle_None: TextDecorationLineStyle = 0i32; pub const TextDecorationLineStyle_Single: TextDecorationLineStyle = 1i32; pub const TextDecorationLineStyle_WordsOnly: TextDecorationLineStyle = 2i32; pub const TextDecorationLineStyle_Double: TextDecorationLineStyle = 3i32; pub const TextDecorationLineStyle_Dot: TextDecorationLineStyle = 4i32; pub const TextDecorationLineStyle_Dash: TextDecorationLineStyle = 5i32; pub const TextDecorationLineStyle_DashDot: TextDecorationLineStyle = 6i32; pub const TextDecorationLineStyle_DashDotDot: TextDecorationLineStyle = 7i32; pub const TextDecorationLineStyle_Wavy: TextDecorationLineStyle = 8i32; pub const TextDecorationLineStyle_ThickSingle: TextDecorationLineStyle = 9i32; pub const TextDecorationLineStyle_DoubleWavy: TextDecorationLineStyle = 11i32; pub const TextDecorationLineStyle_ThickWavy: TextDecorationLineStyle = 12i32; pub const TextDecorationLineStyle_LongDash: TextDecorationLineStyle = 13i32; pub const TextDecorationLineStyle_ThickDash: TextDecorationLineStyle = 14i32; pub const TextDecorationLineStyle_ThickDashDot: TextDecorationLineStyle = 15i32; pub const TextDecorationLineStyle_ThickDashDotDot: TextDecorationLineStyle = 16i32; pub const TextDecorationLineStyle_ThickDot: TextDecorationLineStyle = 17i32; pub const TextDecorationLineStyle_ThickLongDash: TextDecorationLineStyle = 18i32; pub const TextDecorationLineStyle_Other: TextDecorationLineStyle = -1i32; pub type TextEditChangeType = i32; pub const TextEditChangeType_None: TextEditChangeType = 0i32; pub const TextEditChangeType_AutoCorrect: TextEditChangeType = 1i32; pub const TextEditChangeType_Composition: TextEditChangeType = 2i32; pub const TextEditChangeType_CompositionFinalized: TextEditChangeType = 3i32; pub const TextEditChangeType_AutoComplete: TextEditChangeType = 4i32; pub const TextEdit_ConversionTargetChanged_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 864600451, data2: 60751, data3: 19595, data4: [155, 170, 54, 77, 81, 216, 132, 127] }; pub const TextEdit_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1777598345, data2: 23289, data3: 19573, data4: [147, 64, 242, 222, 41, 46, 69, 145] }; pub const TextEdit_TextChanged_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 302711560, data2: 60450, data3: 20152, data4: [156, 152, 152, 103, 205, 161, 177, 101], }; pub type TextPatternRangeEndpoint = i32; pub const TextPatternRangeEndpoint_Start: TextPatternRangeEndpoint = 0i32; pub const TextPatternRangeEndpoint_End: TextPatternRangeEndpoint = 1i32; pub type TextUnit = i32; pub const TextUnit_Character: TextUnit = 0i32; pub const TextUnit_Format: TextUnit = 1i32; pub const TextUnit_Word: TextUnit = 2i32; pub const TextUnit_Line: TextUnit = 3i32; pub const TextUnit_Paragraph: TextUnit = 4i32; pub const TextUnit_Page: TextUnit = 5i32; pub const TextUnit_Document: TextUnit = 6i32; pub const Text_AfterParagraphSpacing_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1485617976, data2: 58927, data3: 18812, data4: [181, 209, 204, 223, 14, 232, 35, 216], }; pub const Text_AfterSpacing_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1485617976, data2: 58927, data3: 18812, data4: [181, 209, 204, 223, 14, 232, 35, 216], }; pub const Text_AnimationStyle_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1652689392, data2: 31898, data3: 19799, data4: [190, 100, 31, 24, 54, 87, 31, 245] }; pub const Text_AnnotationObjects_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4282503016, data2: 59307, data3: 16569, data4: [140, 114, 114, 168, 237, 148, 1, 125], }; pub const Text_AnnotationTypes_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2905519153, data2: 61006, data3: 19425, data4: [167, 186, 85, 89, 21, 90, 115, 239] }; pub const Text_BackgroundColor_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4257520135, data2: 22589, data3: 20247, data4: [173, 39, 119, 252, 131, 42, 60, 11] }; pub const Text_BeforeParagraphSpacing_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3195734705, data2: 51234, data3: 18980, data4: [133, 233, 200, 242, 101, 15, 199, 156], }; pub const Text_BeforeSpacing_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3195734705, data2: 51234, data3: 18980, data4: [133, 233, 200, 242, 101, 15, 199, 156], }; pub const Text_BulletStyle_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3238624400, data2: 54724, data3: 16951, data4: [151, 129, 59, 236, 139, 165, 78, 72], }; pub const Text_CapStyle_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4211448912, data2: 37580, data3: 18853, data4: [186, 143, 10, 168, 114, 187, 162, 243], }; pub const Text_CaretBidiMode_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2459887526, data2: 20947, data3: 18197, data4: [150, 220, 182, 148, 250, 36, 161, 104], }; pub const Text_CaretPosition_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2988945713, data2: 39049, data3: 18258, data4: [169, 27, 115, 62, 253, 197, 197, 160], }; pub const Text_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2929160924, data2: 54065, data3: 20233, data4: [190, 32, 126, 109, 250, 240, 123, 10], }; pub const Text_Culture_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3254934265, data2: 42029, data3: 19693, data4: [161, 251, 198, 116, 99, 21, 34, 46] }; pub const Text_FontName_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1692810152, data2: 62181, data3: 18286, data4: [164, 119, 23, 52, 254, 170, 247, 38], }; pub const Text_FontSize_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3697209087, data2: 1286, data3: 18035, data4: [147, 242, 55, 126, 74, 142, 1, 241] }; pub const Text_FontWeight_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1874862937, data2: 45846, data3: 20319, data4: [180, 1, 241, 206, 85, 116, 24, 83] }; pub const Text_ForegroundColor_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1926351197, data2: 24160, data3: 18202, data4: [150, 177, 108, 27, 59, 119, 164, 54], }; pub const Text_HorizontalTextAlignment_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 82469217, data2: 64419, data3: 18298, data4: [149, 42, 187, 50, 109, 2, 106, 91] }; pub const Text_IndentationFirstLine_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 544185045, data2: 49619, data3: 16970, data4: [129, 130, 109, 169, 167, 243, 214, 50], }; pub const Text_IndentationLeading_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1559653292, data2: 11589, data3: 19019, data4: [182, 201, 247, 34, 29, 40, 21, 176] }; pub const Text_IndentationTrailing_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2550098959, data2: 7396, data3: 16522, data4: [182, 123, 148, 216, 62, 182, 155, 242], }; pub const Text_IsActive_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4121224499, data2: 57784, data3: 17259, data4: [147, 93, 181, 122, 163, 245, 88, 196], }; pub const Text_IsHidden_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 906068731, data2: 48599, data3: 18422, data4: [171, 105, 25, 227, 63, 138, 51, 68] }; pub const Text_IsItalic_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4242614870, data2: 4918, data3: 18996, data4: [150, 99, 27, 171, 71, 35, 147, 32] }; pub const Text_IsReadOnly_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2805470571, data2: 51774, data3: 18782, data4: [149, 20, 131, 60, 68, 15, 235, 17] }; pub const Text_IsSubscript_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4041922648, data2: 36691, data3: 16700, data4: [135, 63, 26, 125, 127, 94, 13, 228] }; pub const Text_IsSuperscript_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3664801508, data2: 45994, data3: 17989, data4: [164, 31, 205, 37, 21, 125, 234, 118], }; pub const Text_LineSpacing_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1677684910, data2: 55619, data3: 19271, data4: [138, 183, 167, 160, 51, 211, 33, 75], }; pub const Text_Link_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3012490525, data2: 40589, data3: 20038, data4: [145, 68, 86, 235, 225, 119, 50, 155], }; pub const Text_MarginBottom_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2128974788, data2: 29364, data3: 19628, data4: [146, 113, 62, 210, 75, 14, 77, 66] }; pub const Text_MarginLeading_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2660385488, data2: 24272, data3: 18688, data4: [142, 138, 238, 204, 3, 131, 90, 252], }; pub const Text_MarginTop_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1748865903, data2: 51641, data3: 19098, data4: [179, 217, 210, 13, 51, 49, 30, 42] }; pub const Text_MarginTrailing_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2941398936, data2: 39325, data3: 16559, data4: [165, 178, 1, 105, 208, 52, 32, 2] }; pub const Text_OutlineStyles_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1533500199, data2: 56201, data3: 18174, data4: [151, 12, 97, 77, 82, 59, 185, 125] }; pub const Text_OverlineColor_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2209036346, data2: 64835, data3: 16602, data4: [171, 62, 236, 248, 22, 92, 187, 109], }; pub const Text_OverlineStyle_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 170085734, data2: 24958, data3: 17023, data4: [135, 29, 225, 255, 30, 12, 33, 63] }; pub const Text_Pattern2_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1233418658, data2: 23330, data3: 17549, data4: [182, 228, 100, 116, 144, 134, 6, 152], }; pub const Text_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2249584733, data2: 32229, data3: 17661, data4: [166, 121, 44, 164, 180, 96, 51, 168], }; pub const Text_SayAsInterpretAs_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3012220588, data2: 61153, data3: 19310, data4: [136, 204, 1, 76, 239, 169, 63, 203] }; pub const Text_SelectionActiveEnd_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 526814403, data2: 39871, data3: 16747, data4: [176, 162, 248, 159, 134, 246, 97, 44], }; pub const Text_StrikethroughColor_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3219216920, data2: 35905, data3: 19546, data4: [154, 11, 4, 175, 14, 7, 244, 135] }; pub const Text_StrikethroughStyle_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1922121457, data2: 55808, data3: 20225, data4: [137, 156, 172, 90, 133, 119, 163, 7], }; pub const Text_StyleId_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 348324062, data2: 49963, data3: 17563, data4: [171, 124, 176, 224, 120, 154, 234, 93], }; pub const Text_StyleName_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 583655569, data2: 19814, data3: 17880, data4: [168, 40, 115, 123, 171, 76, 152, 167], }; pub const Text_Tabs_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 778620939, data2: 37630, data3: 17112, data4: [137, 154, 167, 132, 170, 68, 84, 161], }; pub const Text_TextChangedEvent_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1244930178, data2: 62595, data3: 18628, data4: [172, 17, 168, 75, 67, 94, 42, 132] }; pub const Text_TextFlowDirections_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2346682169, data2: 62496, data3: 16958, data4: [175, 119, 32, 165, 217, 115, 169, 7], }; pub const Text_TextSelectionChangedEvent_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2442058401, data2: 29107, data3: 18862, data4: [151, 65, 121, 190, 184, 211, 88, 243], }; pub const Text_UnderlineColor_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3215010931, data2: 64994, data3: 17523, data4: [191, 100, 16, 54, 214, 170, 15, 69] }; pub const Text_UnderlineStyle_Attribute_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1597710784, data2: 60900, data3: 17597, data4: [156, 54, 56, 83, 3, 140, 191, 235] }; pub const Thumb_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1880926327, data2: 58128, data3: 19926, data4: [182, 68, 121, 126, 79, 174, 162, 19], }; pub const TitleBar_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2561299903, data2: 15280, data3: 19301, data4: [131, 110, 46, 163, 13, 188, 23, 31] }; pub type ToggleState = i32; pub const ToggleState_Off: ToggleState = 0i32; pub const ToggleState_On: ToggleState = 1i32; pub const ToggleState_Indeterminate: ToggleState = 2i32; pub const Toggle_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 188847968, data2: 58100, data3: 17407, data4: [140, 95, 148, 87, 200, 43, 86, 233] }; pub const Toggle_ToggleState_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2990333010, data2: 8898, data3: 19564, data4: [157, 237, 245, 196, 34, 71, 158, 222], }; pub const ToolBar_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2399582033, data2: 57730, data3: 20120, data4: [136, 147, 34, 132, 84, 58, 125, 206], }; pub const ToolTipClosed_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 661484015, data2: 9385, data3: 18870, data4: [142, 151, 218, 152, 180, 1, 187, 205] }; pub const ToolTipOpened_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1061918719, data2: 11996, data3: 17693, data4: [188, 164, 149, 163, 24, 141, 91, 3] }; pub const ToolTip_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 98420433, data2: 8503, data3: 18280, data4: [152, 234, 115, 245, 47, 113, 52, 243] }; pub const Tranform_Pattern2_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2331835655, data2: 41833, data3: 17630, data4: [152, 139, 47, 127, 244, 159, 184, 168], }; pub const Transform2_CanZoom_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4082624656, data2: 42838, data3: 17241, data4: [156, 166, 134, 112, 43, 248, 243, 129], }; pub const Transform2_ZoomLevel_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4007829274, data2: 62626, data3: 19291, data4: [172, 101, 149, 207, 147, 40, 51, 135], }; pub const Transform2_ZoomMaximum_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1118530423, data2: 52912, data3: 20170, data4: [184, 42, 108, 250, 95, 161, 252, 8] }; pub const Transform2_ZoomMinimum_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1949092886, data2: 19153, data3: 19975, data4: [150, 254, 177, 34, 198, 230, 178, 43], }; pub const Transform_CanMove_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 460685901, data2: 8331, data3: 20447, data4: [188, 205, 241, 244, 229, 116, 31, 79] }; pub const Transform_CanResize_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3147357349, data2: 19482, data3: 16852, data4: [164, 246, 235, 193, 40, 100, 65, 128], }; pub const Transform_CanRotate_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 268933960, data2: 14409, data3: 18287, data4: [172, 150, 68, 169, 92, 132, 64, 217] }; pub const Transform_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 615804891, data2: 22654, data3: 18929, data4: [156, 74, 216, 233, 139, 102, 75, 123], }; pub const TreeItem_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1657405113, data2: 36860, data3: 18552, data4: [163, 164, 150, 176, 48, 49, 92, 24] }; pub type TreeScope = i32; pub const TreeScope_None: TreeScope = 0i32; pub const TreeScope_Element: TreeScope = 1i32; pub const TreeScope_Children: TreeScope = 2i32; pub const TreeScope_Descendants: TreeScope = 4i32; pub const TreeScope_Parent: TreeScope = 8i32; pub const TreeScope_Ancestors: TreeScope = 16i32; pub const TreeScope_Subtree: TreeScope = 7i32; pub type TreeTraversalOptions = i32; pub const TreeTraversalOptions_Default: TreeTraversalOptions = 0i32; pub const TreeTraversalOptions_PostOrder: TreeTraversalOptions = 1i32; pub const TreeTraversalOptions_LastToFirstOrder: TreeTraversalOptions = 2i32; pub const Tree_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1969304732, data2: 53825, data3: 17396, data4: [153, 8, 181, 240, 145, 190, 230, 17], }; pub const UIA_AcceleratorKeyPropertyId: i32 = 30006i32; pub const UIA_AccessKeyPropertyId: i32 = 30007i32; pub const UIA_ActiveTextPositionChangedEventId: i32 = 20036i32; pub const UIA_AfterParagraphSpacingAttributeId: i32 = 40042i32; pub const UIA_AnimationStyleAttributeId: i32 = 40000i32; pub const UIA_AnnotationAnnotationTypeIdPropertyId: i32 = 30113i32; pub const UIA_AnnotationAnnotationTypeNamePropertyId: i32 = 30114i32; pub const UIA_AnnotationAuthorPropertyId: i32 = 30115i32; pub const UIA_AnnotationDateTimePropertyId: i32 = 30116i32; pub const UIA_AnnotationObjectsAttributeId: i32 = 40032i32; pub const UIA_AnnotationObjectsPropertyId: i32 = 30156i32; pub const UIA_AnnotationPatternId: i32 = 10023i32; pub const UIA_AnnotationTargetPropertyId: i32 = 30117i32; pub const UIA_AnnotationTypesAttributeId: i32 = 40031i32; pub const UIA_AnnotationTypesPropertyId: i32 = 30155i32; pub const UIA_AppBarControlTypeId: i32 = 50040i32; pub const UIA_AriaPropertiesPropertyId: i32 = 30102i32; pub const UIA_AriaRolePropertyId: i32 = 30101i32; pub const UIA_AsyncContentLoadedEventId: i32 = 20006i32; pub const UIA_AutomationFocusChangedEventId: i32 = 20005i32; pub const UIA_AutomationIdPropertyId: i32 = 30011i32; pub const UIA_AutomationPropertyChangedEventId: i32 = 20004i32; pub const UIA_BackgroundColorAttributeId: i32 = 40001i32; pub const UIA_BeforeParagraphSpacingAttributeId: i32 = 40041i32; pub const UIA_BoundingRectanglePropertyId: i32 = 30001i32; pub const UIA_BulletStyleAttributeId: i32 = 40002i32; pub const UIA_ButtonControlTypeId: i32 = 50000i32; pub const UIA_CalendarControlTypeId: i32 = 50001i32; pub const UIA_CapStyleAttributeId: i32 = 40003i32; pub const UIA_CaretBidiModeAttributeId: i32 = 40039i32; pub const UIA_CaretPositionAttributeId: i32 = 40038i32; pub const UIA_CenterPointPropertyId: i32 = 30165i32; pub const UIA_ChangesEventId: i32 = 20034i32; pub const UIA_CheckBoxControlTypeId: i32 = 50002i32; pub const UIA_ClassNamePropertyId: i32 = 30012i32; pub const UIA_ClickablePointPropertyId: i32 = 30014i32; pub const UIA_ComboBoxControlTypeId: i32 = 50003i32; pub const UIA_ControlTypePropertyId: i32 = 30003i32; pub const UIA_ControllerForPropertyId: i32 = 30104i32; pub const UIA_CultureAttributeId: i32 = 40004i32; pub const UIA_CulturePropertyId: i32 = 30015i32; pub const UIA_CustomControlTypeId: i32 = 50025i32; pub const UIA_CustomLandmarkTypeId: i32 = 80000i32; pub const UIA_CustomNavigationPatternId: i32 = 10033i32; pub const UIA_DataGridControlTypeId: i32 = 50028i32; pub const UIA_DataItemControlTypeId: i32 = 50029i32; pub const UIA_DescribedByPropertyId: i32 = 30105i32; pub const UIA_DockDockPositionPropertyId: i32 = 30069i32; pub const UIA_DockPatternId: i32 = 10011i32; pub const UIA_DocumentControlTypeId: i32 = 50030i32; pub const UIA_DragDropEffectPropertyId: i32 = 30139i32; pub const UIA_DragDropEffectsPropertyId: i32 = 30140i32; pub const UIA_DragGrabbedItemsPropertyId: i32 = 30144i32; pub const UIA_DragIsGrabbedPropertyId: i32 = 30138i32; pub const UIA_DragPatternId: i32 = 10030i32; pub const UIA_Drag_DragCancelEventId: i32 = 20027i32; pub const UIA_Drag_DragCompleteEventId: i32 = 20028i32; pub const UIA_Drag_DragStartEventId: i32 = 20026i32; pub const UIA_DropTargetDropTargetEffectPropertyId: i32 = 30142i32; pub const UIA_DropTargetDropTargetEffectsPropertyId: i32 = 30143i32; pub const UIA_DropTargetPatternId: i32 = 10031i32; pub const UIA_DropTarget_DragEnterEventId: i32 = 20029i32; pub const UIA_DropTarget_DragLeaveEventId: i32 = 20030i32; pub const UIA_DropTarget_DroppedEventId: i32 = 20031i32; pub const UIA_E_ELEMENTNOTAVAILABLE: u32 = 2147746305u32; pub const UIA_E_ELEMENTNOTENABLED: u32 = 2147746304u32; pub const UIA_E_INVALIDOPERATION: u32 = 2148734217u32; pub const UIA_E_NOCLICKABLEPOINT: u32 = 2147746306u32; pub const UIA_E_NOTSUPPORTED: u32 = 2147746308u32; pub const UIA_E_PROXYASSEMBLYNOTLOADED: u32 = 2147746307u32; pub const UIA_E_TIMEOUT: u32 = 2148734213u32; pub const UIA_EditControlTypeId: i32 = 50004i32; pub const UIA_ExpandCollapseExpandCollapseStatePropertyId: i32 = 30070i32; pub const UIA_ExpandCollapsePatternId: i32 = 10005i32; pub const UIA_FillColorPropertyId: i32 = 30160i32; pub const UIA_FillTypePropertyId: i32 = 30162i32; pub const UIA_FlowsFromPropertyId: i32 = 30148i32; pub const UIA_FlowsToPropertyId: i32 = 30106i32; pub const UIA_FontNameAttributeId: i32 = 40005i32; pub const UIA_FontSizeAttributeId: i32 = 40006i32; pub const UIA_FontWeightAttributeId: i32 = 40007i32; pub const UIA_ForegroundColorAttributeId: i32 = 40008i32; pub const UIA_FormLandmarkTypeId: i32 = 80001i32; pub const UIA_FrameworkIdPropertyId: i32 = 30024i32; pub const UIA_FullDescriptionPropertyId: i32 = 30159i32; pub const UIA_GridColumnCountPropertyId: i32 = 30063i32; pub const UIA_GridItemColumnPropertyId: i32 = 30065i32; pub const UIA_GridItemColumnSpanPropertyId: i32 = 30067i32; pub const UIA_GridItemContainingGridPropertyId: i32 = 30068i32; pub const UIA_GridItemPatternId: i32 = 10007i32; pub const UIA_GridItemRowPropertyId: i32 = 30064i32; pub const UIA_GridItemRowSpanPropertyId: i32 = 30066i32; pub const UIA_GridPatternId: i32 = 10006i32; pub const UIA_GridRowCountPropertyId: i32 = 30062i32; pub const UIA_GroupControlTypeId: i32 = 50026i32; pub const UIA_HasKeyboardFocusPropertyId: i32 = 30008i32; pub const UIA_HeaderControlTypeId: i32 = 50034i32; pub const UIA_HeaderItemControlTypeId: i32 = 50035i32; pub const UIA_HeadingLevelPropertyId: i32 = 30173i32; pub const UIA_HelpTextPropertyId: i32 = 30013i32; pub const UIA_HorizontalTextAlignmentAttributeId: i32 = 40009i32; pub const UIA_HostedFragmentRootsInvalidatedEventId: i32 = 20025i32; pub const UIA_HyperlinkControlTypeId: i32 = 50005i32; pub const UIA_IAFP_DEFAULT: u32 = 0u32; pub const UIA_IAFP_UNWRAP_BRIDGE: u32 = 1u32; pub const UIA_ImageControlTypeId: i32 = 50006i32; pub const UIA_IndentationFirstLineAttributeId: i32 = 40010i32; pub const UIA_IndentationLeadingAttributeId: i32 = 40011i32; pub const UIA_IndentationTrailingAttributeId: i32 = 40012i32; pub const UIA_InputDiscardedEventId: i32 = 20022i32; pub const UIA_InputReachedOtherElementEventId: i32 = 20021i32; pub const UIA_InputReachedTargetEventId: i32 = 20020i32; pub const UIA_InvokePatternId: i32 = 10000i32; pub const UIA_Invoke_InvokedEventId: i32 = 20009i32; pub const UIA_IsActiveAttributeId: i32 = 40036i32; pub const UIA_IsAnnotationPatternAvailablePropertyId: i32 = 30118i32; pub const UIA_IsContentElementPropertyId: i32 = 30017i32; pub const UIA_IsControlElementPropertyId: i32 = 30016i32; pub const UIA_IsCustomNavigationPatternAvailablePropertyId: i32 = 30151i32; pub const UIA_IsDataValidForFormPropertyId: i32 = 30103i32; pub const UIA_IsDialogPropertyId: i32 = 30174i32; pub const UIA_IsDockPatternAvailablePropertyId: i32 = 30027i32; pub const UIA_IsDragPatternAvailablePropertyId: i32 = 30137i32; pub const UIA_IsDropTargetPatternAvailablePropertyId: i32 = 30141i32; pub const UIA_IsEnabledPropertyId: i32 = 30010i32; pub const UIA_IsExpandCollapsePatternAvailablePropertyId: i32 = 30028i32; pub const UIA_IsGridItemPatternAvailablePropertyId: i32 = 30029i32; pub const UIA_IsGridPatternAvailablePropertyId: i32 = 30030i32; pub const UIA_IsHiddenAttributeId: i32 = 40013i32; pub const UIA_IsInvokePatternAvailablePropertyId: i32 = 30031i32; pub const UIA_IsItalicAttributeId: i32 = 40014i32; pub const UIA_IsItemContainerPatternAvailablePropertyId: i32 = 30108i32; pub const UIA_IsKeyboardFocusablePropertyId: i32 = 30009i32; pub const UIA_IsLegacyIAccessiblePatternAvailablePropertyId: i32 = 30090i32; pub const UIA_IsMultipleViewPatternAvailablePropertyId: i32 = 30032i32; pub const UIA_IsObjectModelPatternAvailablePropertyId: i32 = 30112i32; pub const UIA_IsOffscreenPropertyId: i32 = 30022i32; pub const UIA_IsPasswordPropertyId: i32 = 30019i32; pub const UIA_IsPeripheralPropertyId: i32 = 30150i32; pub const UIA_IsRangeValuePatternAvailablePropertyId: i32 = 30033i32; pub const UIA_IsReadOnlyAttributeId: i32 = 40015i32; pub const UIA_IsRequiredForFormPropertyId: i32 = 30025i32; pub const UIA_IsScrollItemPatternAvailablePropertyId: i32 = 30035i32; pub const UIA_IsScrollPatternAvailablePropertyId: i32 = 30034i32; pub const UIA_IsSelectionItemPatternAvailablePropertyId: i32 = 30036i32; pub const UIA_IsSelectionPattern2AvailablePropertyId: i32 = 30168i32; pub const UIA_IsSelectionPatternAvailablePropertyId: i32 = 30037i32; pub const UIA_IsSpreadsheetItemPatternAvailablePropertyId: i32 = 30132i32; pub const UIA_IsSpreadsheetPatternAvailablePropertyId: i32 = 30128i32; pub const UIA_IsStylesPatternAvailablePropertyId: i32 = 30127i32; pub const UIA_IsSubscriptAttributeId: i32 = 40016i32; pub const UIA_IsSuperscriptAttributeId: i32 = 40017i32; pub const UIA_IsSynchronizedInputPatternAvailablePropertyId: i32 = 30110i32; pub const UIA_IsTableItemPatternAvailablePropertyId: i32 = 30039i32; pub const UIA_IsTablePatternAvailablePropertyId: i32 = 30038i32; pub const UIA_IsTextChildPatternAvailablePropertyId: i32 = 30136i32; pub const UIA_IsTextEditPatternAvailablePropertyId: i32 = 30149i32; pub const UIA_IsTextPattern2AvailablePropertyId: i32 = 30119i32; pub const UIA_IsTextPatternAvailablePropertyId: i32 = 30040i32; pub const UIA_IsTogglePatternAvailablePropertyId: i32 = 30041i32; pub const UIA_IsTransformPattern2AvailablePropertyId: i32 = 30134i32; pub const UIA_IsTransformPatternAvailablePropertyId: i32 = 30042i32; pub const UIA_IsValuePatternAvailablePropertyId: i32 = 30043i32; pub const UIA_IsVirtualizedItemPatternAvailablePropertyId: i32 = 30109i32; pub const UIA_IsWindowPatternAvailablePropertyId: i32 = 30044i32; pub const UIA_ItemContainerPatternId: i32 = 10019i32; pub const UIA_ItemStatusPropertyId: i32 = 30026i32; pub const UIA_ItemTypePropertyId: i32 = 30021i32; pub const UIA_LabeledByPropertyId: i32 = 30018i32; pub const UIA_LandmarkTypePropertyId: i32 = 30157i32; pub const UIA_LayoutInvalidatedEventId: i32 = 20008i32; pub const UIA_LegacyIAccessibleChildIdPropertyId: i32 = 30091i32; pub const UIA_LegacyIAccessibleDefaultActionPropertyId: i32 = 30100i32; pub const UIA_LegacyIAccessibleDescriptionPropertyId: i32 = 30094i32; pub const UIA_LegacyIAccessibleHelpPropertyId: i32 = 30097i32; pub const UIA_LegacyIAccessibleKeyboardShortcutPropertyId: i32 = 30098i32; pub const UIA_LegacyIAccessibleNamePropertyId: i32 = 30092i32; pub const UIA_LegacyIAccessiblePatternId: i32 = 10018i32; pub const UIA_LegacyIAccessibleRolePropertyId: i32 = 30095i32; pub const UIA_LegacyIAccessibleSelectionPropertyId: i32 = 30099i32; pub const UIA_LegacyIAccessibleStatePropertyId: i32 = 30096i32; pub const UIA_LegacyIAccessibleValuePropertyId: i32 = 30093i32; pub const UIA_LevelPropertyId: i32 = 30154i32; pub const UIA_LineSpacingAttributeId: i32 = 40040i32; pub const UIA_LinkAttributeId: i32 = 40035i32; pub const UIA_ListControlTypeId: i32 = 50008i32; pub const UIA_ListItemControlTypeId: i32 = 50007i32; pub const UIA_LiveRegionChangedEventId: i32 = 20024i32; pub const UIA_LiveSettingPropertyId: i32 = 30135i32; pub const UIA_LocalizedControlTypePropertyId: i32 = 30004i32; pub const UIA_LocalizedLandmarkTypePropertyId: i32 = 30158i32; pub const UIA_MainLandmarkTypeId: i32 = 80002i32; pub const UIA_MarginBottomAttributeId: i32 = 40018i32; pub const UIA_MarginLeadingAttributeId: i32 = 40019i32; pub const UIA_MarginTopAttributeId: i32 = 40020i32; pub const UIA_MarginTrailingAttributeId: i32 = 40021i32; pub const UIA_MenuBarControlTypeId: i32 = 50010i32; pub const UIA_MenuClosedEventId: i32 = 20007i32; pub const UIA_MenuControlTypeId: i32 = 50009i32; pub const UIA_MenuItemControlTypeId: i32 = 50011i32; pub const UIA_MenuModeEndEventId: i32 = 20019i32; pub const UIA_MenuModeStartEventId: i32 = 20018i32; pub const UIA_MenuOpenedEventId: i32 = 20003i32; pub const UIA_MultipleViewCurrentViewPropertyId: i32 = 30071i32; pub const UIA_MultipleViewPatternId: i32 = 10008i32; pub const UIA_MultipleViewSupportedViewsPropertyId: i32 = 30072i32; pub const UIA_NamePropertyId: i32 = 30005i32; pub const UIA_NativeWindowHandlePropertyId: i32 = 30020i32; pub const UIA_NavigationLandmarkTypeId: i32 = 80003i32; pub const UIA_NotificationEventId: i32 = 20035i32; pub const UIA_ObjectModelPatternId: i32 = 10022i32; pub const UIA_OptimizeForVisualContentPropertyId: i32 = 30111i32; pub const UIA_OrientationPropertyId: i32 = 30023i32; pub const UIA_OutlineColorPropertyId: i32 = 30161i32; pub const UIA_OutlineStylesAttributeId: i32 = 40022i32; pub const UIA_OutlineThicknessPropertyId: i32 = 30164i32; pub const UIA_OverlineColorAttributeId: i32 = 40023i32; pub const UIA_OverlineStyleAttributeId: i32 = 40024i32; pub const UIA_PFIA_DEFAULT: u32 = 0u32; pub const UIA_PFIA_UNWRAP_BRIDGE: u32 = 1u32; pub const UIA_PaneControlTypeId: i32 = 50033i32; pub const UIA_PositionInSetPropertyId: i32 = 30152i32; pub const UIA_ProcessIdPropertyId: i32 = 30002i32; pub const UIA_ProgressBarControlTypeId: i32 = 50012i32; pub const UIA_ProviderDescriptionPropertyId: i32 = 30107i32; pub const UIA_RadioButtonControlTypeId: i32 = 50013i32; pub const UIA_RangeValueIsReadOnlyPropertyId: i32 = 30048i32; pub const UIA_RangeValueLargeChangePropertyId: i32 = 30051i32; pub const UIA_RangeValueMaximumPropertyId: i32 = 30050i32; pub const UIA_RangeValueMinimumPropertyId: i32 = 30049i32; pub const UIA_RangeValuePatternId: i32 = 10003i32; pub const UIA_RangeValueSmallChangePropertyId: i32 = 30052i32; pub const UIA_RangeValueValuePropertyId: i32 = 30047i32; pub const UIA_RotationPropertyId: i32 = 30166i32; pub const UIA_RuntimeIdPropertyId: i32 = 30000i32; pub const UIA_SayAsInterpretAsAttributeId: i32 = 40043i32; pub const UIA_SayAsInterpretAsMetadataId: i32 = 100000i32; pub const UIA_ScrollBarControlTypeId: i32 = 50014i32; pub const UIA_ScrollHorizontalScrollPercentPropertyId: i32 = 30053i32; pub const UIA_ScrollHorizontalViewSizePropertyId: i32 = 30054i32; pub const UIA_ScrollHorizontallyScrollablePropertyId: i32 = 30057i32; pub const UIA_ScrollItemPatternId: i32 = 10017i32; pub const UIA_ScrollPatternId: i32 = 10004i32; pub const UIA_ScrollPatternNoScroll: f64 = -1f64; pub const UIA_ScrollVerticalScrollPercentPropertyId: i32 = 30055i32; pub const UIA_ScrollVerticalViewSizePropertyId: i32 = 30056i32; pub const UIA_ScrollVerticallyScrollablePropertyId: i32 = 30058i32; pub const UIA_SearchLandmarkTypeId: i32 = 80004i32; pub const UIA_Selection2CurrentSelectedItemPropertyId: i32 = 30171i32; pub const UIA_Selection2FirstSelectedItemPropertyId: i32 = 30169i32; pub const UIA_Selection2ItemCountPropertyId: i32 = 30172i32; pub const UIA_Selection2LastSelectedItemPropertyId: i32 = 30170i32; pub const UIA_SelectionActiveEndAttributeId: i32 = 40037i32; pub const UIA_SelectionCanSelectMultiplePropertyId: i32 = 30060i32; pub const UIA_SelectionIsSelectionRequiredPropertyId: i32 = 30061i32; pub const UIA_SelectionItemIsSelectedPropertyId: i32 = 30079i32; pub const UIA_SelectionItemPatternId: i32 = 10010i32; pub const UIA_SelectionItemSelectionContainerPropertyId: i32 = 30080i32; pub const UIA_SelectionItem_ElementAddedToSelectionEventId: i32 = 20010i32; pub const UIA_SelectionItem_ElementRemovedFromSelectionEventId: i32 = 20011i32; pub const UIA_SelectionItem_ElementSelectedEventId: i32 = 20012i32; pub const UIA_SelectionPattern2Id: i32 = 10034i32; pub const UIA_SelectionPatternId: i32 = 10001i32; pub const UIA_SelectionSelectionPropertyId: i32 = 30059i32; pub const UIA_Selection_InvalidatedEventId: i32 = 20013i32; pub const UIA_SemanticZoomControlTypeId: i32 = 50039i32; pub const UIA_SeparatorControlTypeId: i32 = 50038i32; pub const UIA_SizeOfSetPropertyId: i32 = 30153i32; pub const UIA_SizePropertyId: i32 = 30167i32; pub const UIA_SliderControlTypeId: i32 = 50015i32; pub const UIA_SpinnerControlTypeId: i32 = 50016i32; pub const UIA_SplitButtonControlTypeId: i32 = 50031i32; pub const UIA_SpreadsheetItemAnnotationObjectsPropertyId: i32 = 30130i32; pub const UIA_SpreadsheetItemAnnotationTypesPropertyId: i32 = 30131i32; pub const UIA_SpreadsheetItemFormulaPropertyId: i32 = 30129i32; pub const UIA_SpreadsheetItemPatternId: i32 = 10027i32; pub const UIA_SpreadsheetPatternId: i32 = 10026i32; pub const UIA_StatusBarControlTypeId: i32 = 50017i32; pub const UIA_StrikethroughColorAttributeId: i32 = 40025i32; pub const UIA_StrikethroughStyleAttributeId: i32 = 40026i32; pub const UIA_StructureChangedEventId: i32 = 20002i32; pub const UIA_StyleIdAttributeId: i32 = 40034i32; pub const UIA_StyleNameAttributeId: i32 = 40033i32; pub const UIA_StylesExtendedPropertiesPropertyId: i32 = 30126i32; pub const UIA_StylesFillColorPropertyId: i32 = 30122i32; pub const UIA_StylesFillPatternColorPropertyId: i32 = 30125i32; pub const UIA_StylesFillPatternStylePropertyId: i32 = 30123i32; pub const UIA_StylesPatternId: i32 = 10025i32; pub const UIA_StylesShapePropertyId: i32 = 30124i32; pub const UIA_StylesStyleIdPropertyId: i32 = 30120i32; pub const UIA_StylesStyleNamePropertyId: i32 = 30121i32; pub const UIA_SummaryChangeId: i32 = 90000i32; pub const UIA_SynchronizedInputPatternId: i32 = 10021i32; pub const UIA_SystemAlertEventId: i32 = 20023i32; pub const UIA_TabControlTypeId: i32 = 50018i32; pub const UIA_TabItemControlTypeId: i32 = 50019i32; pub const UIA_TableColumnHeadersPropertyId: i32 = 30082i32; pub const UIA_TableControlTypeId: i32 = 50036i32; pub const UIA_TableItemColumnHeaderItemsPropertyId: i32 = 30085i32; pub const UIA_TableItemPatternId: i32 = 10013i32; pub const UIA_TableItemRowHeaderItemsPropertyId: i32 = 30084i32; pub const UIA_TablePatternId: i32 = 10012i32; pub const UIA_TableRowHeadersPropertyId: i32 = 30081i32; pub const UIA_TableRowOrColumnMajorPropertyId: i32 = 30083i32; pub const UIA_TabsAttributeId: i32 = 40027i32; pub const UIA_TextChildPatternId: i32 = 10029i32; pub const UIA_TextControlTypeId: i32 = 50020i32; pub const UIA_TextEditPatternId: i32 = 10032i32; pub const UIA_TextEdit_ConversionTargetChangedEventId: i32 = 20033i32; pub const UIA_TextEdit_TextChangedEventId: i32 = 20032i32; pub const UIA_TextFlowDirectionsAttributeId: i32 = 40028i32; pub const UIA_TextPattern2Id: i32 = 10024i32; pub const UIA_TextPatternId: i32 = 10014i32; pub const UIA_Text_TextChangedEventId: i32 = 20015i32; pub const UIA_Text_TextSelectionChangedEventId: i32 = 20014i32; pub const UIA_ThumbControlTypeId: i32 = 50027i32; pub const UIA_TitleBarControlTypeId: i32 = 50037i32; pub const UIA_TogglePatternId: i32 = 10015i32; pub const UIA_ToggleToggleStatePropertyId: i32 = 30086i32; pub const UIA_ToolBarControlTypeId: i32 = 50021i32; pub const UIA_ToolTipClosedEventId: i32 = 20001i32; pub const UIA_ToolTipControlTypeId: i32 = 50022i32; pub const UIA_ToolTipOpenedEventId: i32 = 20000i32; pub const UIA_Transform2CanZoomPropertyId: i32 = 30133i32; pub const UIA_Transform2ZoomLevelPropertyId: i32 = 30145i32; pub const UIA_Transform2ZoomMaximumPropertyId: i32 = 30147i32; pub const UIA_Transform2ZoomMinimumPropertyId: i32 = 30146i32; pub const UIA_TransformCanMovePropertyId: i32 = 30087i32; pub const UIA_TransformCanResizePropertyId: i32 = 30088i32; pub const UIA_TransformCanRotatePropertyId: i32 = 30089i32; pub const UIA_TransformPattern2Id: i32 = 10028i32; pub const UIA_TransformPatternId: i32 = 10016i32; pub const UIA_TreeControlTypeId: i32 = 50023i32; pub const UIA_TreeItemControlTypeId: i32 = 50024i32; pub const UIA_UnderlineColorAttributeId: i32 = 40029i32; pub const UIA_UnderlineStyleAttributeId: i32 = 40030i32; pub const UIA_ValueIsReadOnlyPropertyId: i32 = 30046i32; pub const UIA_ValuePatternId: i32 = 10002i32; pub const UIA_ValueValuePropertyId: i32 = 30045i32; pub const UIA_VirtualizedItemPatternId: i32 = 10020i32; pub const UIA_VisualEffectsPropertyId: i32 = 30163i32; pub const UIA_WindowCanMaximizePropertyId: i32 = 30073i32; pub const UIA_WindowCanMinimizePropertyId: i32 = 30074i32; pub const UIA_WindowControlTypeId: i32 = 50032i32; pub const UIA_WindowIsModalPropertyId: i32 = 30077i32; pub const UIA_WindowIsTopmostPropertyId: i32 = 30078i32; pub const UIA_WindowPatternId: i32 = 10009i32; pub const UIA_WindowWindowInteractionStatePropertyId: i32 = 30076i32; pub const UIA_WindowWindowVisualStatePropertyId: i32 = 30075i32; pub const UIA_Window_WindowClosedEventId: i32 = 20017i32; pub const UIA_Window_WindowOpenedEventId: i32 = 20016i32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct UIAutomationEventInfo { pub guid: ::windows_sys::core::GUID, pub pProgrammaticName: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for UIAutomationEventInfo {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for UIAutomationEventInfo { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct UIAutomationMethodInfo { pub pProgrammaticName: super::super::Foundation::PWSTR, pub doSetFocus: super::super::Foundation::BOOL, pub cInParameters: u32, pub cOutParameters: u32, pub pParameterTypes: *mut UIAutomationType, pub pParameterNames: *mut super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for UIAutomationMethodInfo {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for UIAutomationMethodInfo { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct UIAutomationParameter { pub r#type: UIAutomationType, pub pData: *mut ::core::ffi::c_void, } impl ::core::marker::Copy for UIAutomationParameter {} impl ::core::clone::Clone for UIAutomationParameter { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct UIAutomationPatternInfo { pub guid: ::windows_sys::core::GUID, pub pProgrammaticName: super::super::Foundation::PWSTR, pub providerInterfaceId: ::windows_sys::core::GUID, pub clientInterfaceId: ::windows_sys::core::GUID, pub cProperties: u32, pub pProperties: *mut UIAutomationPropertyInfo, pub cMethods: u32, pub pMethods: *mut UIAutomationMethodInfo, pub cEvents: u32, pub pEvents: *mut UIAutomationEventInfo, pub pPatternHandler: IUIAutomationPatternHandler, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for UIAutomationPatternInfo {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for UIAutomationPatternInfo { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct UIAutomationPropertyInfo { pub guid: ::windows_sys::core::GUID, pub pProgrammaticName: super::super::Foundation::PWSTR, pub r#type: UIAutomationType, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for UIAutomationPropertyInfo {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for UIAutomationPropertyInfo { fn clone(&self) -> Self { *self } } pub type UIAutomationType = i32; pub const UIAutomationType_Int: UIAutomationType = 1i32; pub const UIAutomationType_Bool: UIAutomationType = 2i32; pub const UIAutomationType_String: UIAutomationType = 3i32; pub const UIAutomationType_Double: UIAutomationType = 4i32; pub const UIAutomationType_Point: UIAutomationType = 5i32; pub const UIAutomationType_Rect: UIAutomationType = 6i32; pub const UIAutomationType_Element: UIAutomationType = 7i32; pub const UIAutomationType_Array: UIAutomationType = 65536i32; pub const UIAutomationType_Out: UIAutomationType = 131072i32; pub const UIAutomationType_IntArray: UIAutomationType = 65537i32; pub const UIAutomationType_BoolArray: UIAutomationType = 65538i32; pub const UIAutomationType_StringArray: UIAutomationType = 65539i32; pub const UIAutomationType_DoubleArray: UIAutomationType = 65540i32; pub const UIAutomationType_PointArray: UIAutomationType = 65541i32; pub const UIAutomationType_RectArray: UIAutomationType = 65542i32; pub const UIAutomationType_ElementArray: UIAutomationType = 65543i32; pub const UIAutomationType_OutInt: UIAutomationType = 131073i32; pub const UIAutomationType_OutBool: UIAutomationType = 131074i32; pub const UIAutomationType_OutString: UIAutomationType = 131075i32; pub const UIAutomationType_OutDouble: UIAutomationType = 131076i32; pub const UIAutomationType_OutPoint: UIAutomationType = 131077i32; pub const UIAutomationType_OutRect: UIAutomationType = 131078i32; pub const UIAutomationType_OutElement: UIAutomationType = 131079i32; pub const UIAutomationType_OutIntArray: UIAutomationType = 196609i32; pub const UIAutomationType_OutBoolArray: UIAutomationType = 196610i32; pub const UIAutomationType_OutStringArray: UIAutomationType = 196611i32; pub const UIAutomationType_OutDoubleArray: UIAutomationType = 196612i32; pub const UIAutomationType_OutPointArray: UIAutomationType = 196613i32; pub const UIAutomationType_OutRectArray: UIAutomationType = 196614i32; pub const UIAutomationType_OutElementArray: UIAutomationType = 196615i32; #[repr(C)] pub struct UiaAndOrCondition { pub ConditionType: ConditionType, pub ppConditions: *mut *mut UiaCondition, pub cConditions: i32, } impl ::core::marker::Copy for UiaAndOrCondition {} impl ::core::clone::Clone for UiaAndOrCondition { fn clone(&self) -> Self { *self } } pub const UiaAppendRuntimeId: u32 = 3u32; #[repr(C)] pub struct UiaAsyncContentLoadedEventArgs { pub Type: EventArgsType, pub EventId: i32, pub AsyncContentLoadedState: AsyncContentLoadedState, pub PercentComplete: f64, } impl ::core::marker::Copy for UiaAsyncContentLoadedEventArgs {} impl ::core::clone::Clone for UiaAsyncContentLoadedEventArgs { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct UiaCacheRequest { pub pViewCondition: *mut UiaCondition, pub Scope: TreeScope, pub pProperties: *mut i32, pub cProperties: i32, pub pPatterns: *mut i32, pub cPatterns: i32, pub automationElementMode: AutomationElementMode, } impl ::core::marker::Copy for UiaCacheRequest {} impl ::core::clone::Clone for UiaCacheRequest { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub struct UiaChangeInfo { pub uiaId: i32, pub payload: super::super::System::Com::VARIANT, pub extraInfo: super::super::System::Com::VARIANT, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl ::core::marker::Copy for UiaChangeInfo {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl ::core::clone::Clone for UiaChangeInfo { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub struct UiaChangesEventArgs { pub Type: EventArgsType, pub EventId: i32, pub EventIdCount: i32, pub pUiaChanges: *mut UiaChangeInfo, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl ::core::marker::Copy for UiaChangesEventArgs {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl ::core::clone::Clone for UiaChangesEventArgs { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct UiaCondition { pub ConditionType: ConditionType, } impl ::core::marker::Copy for UiaCondition {} impl ::core::clone::Clone for UiaCondition { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct UiaEventArgs { pub Type: EventArgsType, pub EventId: i32, } impl ::core::marker::Copy for UiaEventArgs {} impl ::core::clone::Clone for UiaEventArgs { fn clone(&self) -> Self { *self } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub type UiaEventCallback = ::core::option::Option<unsafe extern "system" fn(pargs: *mut UiaEventArgs, prequesteddata: *mut super::super::System::Com::SAFEARRAY, ptreestructure: super::super::Foundation::BSTR)>; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct UiaFindParams { pub MaxDepth: i32, pub FindFirst: super::super::Foundation::BOOL, pub ExcludeRoot: super::super::Foundation::BOOL, pub pFindCondition: *mut UiaCondition, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for UiaFindParams {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for UiaFindParams { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct UiaNotCondition { pub ConditionType: ConditionType, pub pCondition: *mut UiaCondition, } impl ::core::marker::Copy for UiaNotCondition {} impl ::core::clone::Clone for UiaNotCondition { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct UiaPoint { pub x: f64, pub y: f64, } impl ::core::marker::Copy for UiaPoint {} impl ::core::clone::Clone for UiaPoint { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub struct UiaPropertyChangedEventArgs { pub Type: EventArgsType, pub EventId: i32, pub PropertyId: i32, pub OldValue: super::super::System::Com::VARIANT, pub NewValue: super::super::System::Com::VARIANT, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl ::core::marker::Copy for UiaPropertyChangedEventArgs {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl ::core::clone::Clone for UiaPropertyChangedEventArgs { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub struct UiaPropertyCondition { pub ConditionType: ConditionType, pub PropertyId: i32, pub Value: super::super::System::Com::VARIANT, pub Flags: PropertyConditionFlags, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl ::core::marker::Copy for UiaPropertyCondition {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl ::core::clone::Clone for UiaPropertyCondition { fn clone(&self) -> Self { *self } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub type UiaProviderCallback = ::core::option::Option<unsafe extern "system" fn(hwnd: super::super::Foundation::HWND, providertype: ProviderType) -> *mut super::super::System::Com::SAFEARRAY>; #[repr(C)] pub struct UiaRect { pub left: f64, pub top: f64, pub width: f64, pub height: f64, } impl ::core::marker::Copy for UiaRect {} impl ::core::clone::Clone for UiaRect { fn clone(&self) -> Self { *self } } pub const UiaRootObjectId: i32 = -25i32; #[repr(C)] pub struct UiaStructureChangedEventArgs { pub Type: EventArgsType, pub EventId: i32, pub StructureChangeType: StructureChangeType, pub pRuntimeId: *mut i32, pub cRuntimeIdLen: i32, } impl ::core::marker::Copy for UiaStructureChangedEventArgs {} impl ::core::clone::Clone for UiaStructureChangedEventArgs { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_System_Com")] pub struct UiaTextEditTextChangedEventArgs { pub Type: EventArgsType, pub EventId: i32, pub TextEditChangeType: TextEditChangeType, pub pTextChange: *mut super::super::System::Com::SAFEARRAY, } #[cfg(feature = "Win32_System_Com")] impl ::core::marker::Copy for UiaTextEditTextChangedEventArgs {} #[cfg(feature = "Win32_System_Com")] impl ::core::clone::Clone for UiaTextEditTextChangedEventArgs { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct UiaWindowClosedEventArgs { pub Type: EventArgsType, pub EventId: i32, pub pRuntimeId: *mut i32, pub cRuntimeIdLen: i32, } impl ::core::marker::Copy for UiaWindowClosedEventArgs {} impl ::core::clone::Clone for UiaWindowClosedEventArgs { fn clone(&self) -> Self { *self } } pub const Value_IsReadOnly_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3943239472, data2: 57932, data3: 18329, data4: [167, 5, 13, 36, 123, 192, 55, 248] }; pub const Value_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 402304414, data2: 51319, data3: 18267, data4: [185, 51, 119, 51, 39, 121, 182, 55] }; pub const Value_Value_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3915341412, data2: 9887, data3: 19077, data4: [186, 153, 64, 146, 195, 234, 41, 134], }; pub const VirtualizedItem_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4111472446, data2: 11889, data3: 17897, data4: [166, 229, 98, 246, 237, 130, 137, 213], }; pub type VisualEffects = i32; pub const VisualEffects_None: VisualEffects = 0i32; pub const VisualEffects_Shadow: VisualEffects = 1i32; pub const VisualEffects_Reflection: VisualEffects = 2i32; pub const VisualEffects_Glow: VisualEffects = 4i32; pub const VisualEffects_SoftEdges: VisualEffects = 8i32; pub const VisualEffects_Bevel: VisualEffects = 16i32; pub const VisualEffects_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3860497765, data2: 43737, data3: 18135, data4: [158, 112, 78, 138, 132, 32, 212, 32], }; #[cfg(feature = "Win32_Foundation")] pub type WINEVENTPROC = ::core::option::Option<unsafe extern "system" fn(hwineventhook: HWINEVENTHOOK, event: u32, hwnd: super::super::Foundation::HWND, idobject: i32, idchild: i32, ideventthread: u32, dwmseventtime: u32)>; pub type WindowInteractionState = i32; pub const WindowInteractionState_Running: WindowInteractionState = 0i32; pub const WindowInteractionState_Closing: WindowInteractionState = 1i32; pub const WindowInteractionState_ReadyForUserInteraction: WindowInteractionState = 2i32; pub const WindowInteractionState_BlockedByModalWindow: WindowInteractionState = 3i32; pub const WindowInteractionState_NotResponding: WindowInteractionState = 4i32; pub type WindowVisualState = i32; pub const WindowVisualState_Normal: WindowVisualState = 0i32; pub const WindowVisualState_Maximized: WindowVisualState = 1i32; pub const WindowVisualState_Minimized: WindowVisualState = 2i32; pub const Window_CanMaximize_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1694496063, data2: 25437, data3: 16833, data4: [149, 12, 203, 90, 223, 190, 40, 227], }; pub const Window_CanMinimize_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3074115109, data2: 22920, data3: 19351, data4: [180, 194, 166, 254, 110, 120, 200, 198], }; pub const Window_Control_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3778703938, data2: 62562, data3: 20301, data4: [174, 193, 83, 178, 141, 108, 50, 144], }; pub const Window_IsModal_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4283328658, data2: 14265, data3: 20426, data4: [133, 50, 255, 230, 116, 236, 254, 237], }; pub const Window_IsTopmost_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4017980883, data2: 2359, data3: 18786, data4: [146, 65, 182, 35, 69, 242, 64, 65] }; pub const Window_Pattern_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 663754549, data2: 51040, data3: 18836, data4: [173, 17, 89, 25, 230, 6, 177, 16] }; pub const Window_WindowClosed_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3992011256, data2: 64103, data3: 20002, data4: [187, 247, 148, 78, 5, 115, 94, 226] }; pub const Window_WindowInteractionState_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1340941988, data2: 1109, data3: 20386, data4: [178, 28, 196, 218, 45, 177, 255, 156], }; pub const Window_WindowOpened_Event_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3555204358, data2: 56901, data3: 20271, data4: [150, 51, 222, 158, 2, 251, 101, 175], }; pub const Window_WindowVisualState_Property_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1253544031, data2: 59488, data3: 17726, data4: [163, 10, 246, 67, 30, 93, 170, 213] }; pub type ZoomUnit = i32; pub const ZoomUnit_NoAmount: ZoomUnit = 0i32; pub const ZoomUnit_LargeDecrement: ZoomUnit = 1i32; pub const ZoomUnit_SmallDecrement: ZoomUnit = 2i32; pub const ZoomUnit_LargeIncrement: ZoomUnit = 3i32; pub const ZoomUnit_SmallIncrement: ZoomUnit = 4i32;
//! Manage xml character escapes use std::borrow::Cow; use errors::Result; use errors::ErrorKind::Escape; use from_ascii::FromAsciiRadix; // UTF-8 ranges and tags for encoding characters const TAG_CONT: u8 = 0b1000_0000; const TAG_TWO_B: u8 = 0b1100_0000; const TAG_THREE_B: u8 = 0b1110_0000; const TAG_FOUR_B: u8 = 0b1111_0000; const MAX_ONE_B: u32 = 0x80; const MAX_TWO_B: u32 = 0x800; const MAX_THREE_B: u32 = 0x10000; enum ByteOrChar { Byte(u8), Char(u32), } /// helper function to unescape a `&[u8]` and replace all /// xml escaped characters ('&...;') into their corresponding value pub fn unescape(raw: &[u8]) -> Result<Cow<[u8]>> { let mut escapes = Vec::new(); let mut bytes = raw.iter().enumerate(); while let Some((i, _)) = bytes.by_ref().find(|&(_, b)| *b == b'&') { if let Some((j, _)) = bytes.find(|&(_, &b)| b == b';') { // search for character correctness // copied and modified from xml-rs inside_reference.rs match &raw[i + 1..j] { b"lt" => escapes.push((i..j, ByteOrChar::Byte(b'<'))), b"gt" => escapes.push((i..j, ByteOrChar::Byte(b'>'))), b"amp" => escapes.push((i..j, ByteOrChar::Byte(b'&'))), b"apos" => escapes.push((i..j, ByteOrChar::Byte(b'\''))), b"quot" => escapes.push((i..j, ByteOrChar::Byte(b'\"'))), b"#x0" | b"#0" => { return Err(Escape("Null character entity is not allowed".to_string(), i..j) .into()) } bytes if bytes.len() > 1 && bytes[0] == b'#' => { let code = if bytes[1] == b'x' { u32::from_ascii_radix(&bytes[2..], 16) } else { u32::from_ascii_radix(&bytes[1..], 10) }; escapes.push((i..j, ByteOrChar::Char( code.map_err(|e| Escape(format!("{:?}", e), i..j))?))); } _ => return Err(Escape("".to_owned(), i..j).into()), } } else { return Err(Escape("Cannot find ';' after '&'".to_string(), i..bytes.len()).into()); } } if escapes.is_empty() { Ok(Cow::Borrowed(raw)) } else { let len = bytes.len(); let mut v = Vec::with_capacity(len); let mut start = 0; for (r, b) in escapes { v.extend_from_slice(&raw[start..r.start]); match b { ByteOrChar::Byte(b) => v.push(b), ByteOrChar::Char(c) => push_utf8(&mut v, c), } start = r.end + 1; } if start < raw.len() { v.extend_from_slice(&raw[start..]); } Ok(Cow::Owned(v)) } } fn push_utf8(buf: &mut Vec<u8>, code: u32) { if code < MAX_ONE_B { buf.push(code as u8); } else if code < MAX_TWO_B { buf.push((code >> 6 & 0x1F) as u8 | TAG_TWO_B); buf.push((code & 0x3F) as u8 | TAG_CONT); } else if code < MAX_THREE_B { buf.push((code >> 12 & 0x0F) as u8 | TAG_THREE_B); buf.push((code >> 6 & 0x3F) as u8 | TAG_CONT); buf.push((code & 0x3F) as u8 | TAG_CONT); } else { buf.push((code >> 18 & 0x07) as u8 | TAG_FOUR_B); buf.push((code >> 12 & 0x3F) as u8 | TAG_CONT); buf.push((code >> 6 & 0x3F) as u8 | TAG_CONT); buf.push((code & 0x3F) as u8 | TAG_CONT); } } #[test] fn test_escape() { assert_eq!(&*unescape(b"test").unwrap(), b"test"); assert_eq!(&*unescape(b"&lt;test&gt;").unwrap(), b"<test>"); println!("{}", ::std::str::from_utf8(&*unescape(b"&#xa9;").unwrap()).unwrap()); assert_eq!(&*unescape(b"&#x30;").unwrap(), b"0"); assert_eq!(&*unescape(b"&#48;").unwrap(), b"0"); }
// use super::varargs::VarArgs; use wasmer_runtime_core::Instance; #[allow(clippy::cast_ptr_alignment)] pub extern "C" fn _sigemptyset(set: u32, instance: &mut Instance) -> i32 { debug!("emscripten::_sigemptyset"); let set_addr = instance.memory_offset_addr(0, set as _) as *mut u32; unsafe { *set_addr = 0; } 0 } pub extern "C" fn _sigaction(signum: u32, act: u32, oldact: u32, _instance: &mut Instance) -> i32 { debug!("emscripten::_sigaction {}, {}, {}", signum, act, oldact); 0 } #[allow(clippy::cast_ptr_alignment)] pub extern "C" fn _sigaddset(set: u32, signum: u32, instance: &mut Instance) -> i32 { debug!("emscripten::_sigaddset {}, {}", set, signum); let set_addr = instance.memory_offset_addr(0, set as _) as *mut u32; unsafe { *set_addr |= 1 << (signum - 1); } 0 } pub extern "C" fn _sigprocmask() -> i32 { debug!("emscripten::_sigprocmask"); 0 } pub extern "C" fn _signal(sig: u32, _instance: &mut Instance) -> i32 { debug!("emscripten::_signal ({})", sig); 0 }
#[macro_use] extern crate clap; extern crate time; extern crate clog; use clap::{App, Arg, ArgGroup}; use clog::{LinkStyle, Clog}; fn main () { let styles = LinkStyle::variants(); let matches = App::new("clog") // Pull version from Cargo.toml .version(&format!("v{}", crate_version!())[..]) .about("a conventional changelog for the rest of us") .args_from_usage("-r, --repository=[repo] 'Repository used for generating commit and issue links{n}\ (without the .git, e.g. https://github.com/thoughtram/clog)' -f, --from=[from] 'e.g. 12a8546' -T, --format=[format] 'The output format, defaults to markdown{n}\ (valid values: markdown, json)' -M, --major 'Increment major version by one (Sets minor and patch to 0)' -g, --git-dir=[gitdir] 'Local .git directory (defaults to current dir + \'.git\')*' -w, --work-tree=[workdir] 'Local working tree of the git project{n}\ (defaults to current dir)*' -m, --minor 'Increment minor version by one (Sets patch to 0)' -p, --patch 'Increment patch version by one' -s, --subtitle=[subtitle] 'e.g. \"Crazy Release Title\"' -t, --to=[to] 'e.g. 8057684 (Defaults to HEAD when omitted)' -o, --outfile=[outfile] 'Where to write the changelog (Defaults to stdout when omitted)' -c, --config=[config] 'The Clog Configuration TOML file to use (Defaults to{n}\ \'.clog.toml\')**' -i, --infile=[infile] 'A changelog to append to, but *NOT* write to (Useful in{n}\ conjunction with --outfile)' --setversion=[ver] 'e.g. 1.0.1'") // Because --from-latest-tag can't be used with --from, we add it seperately so we can // specify a .conflicts_with() .arg(Arg::from_usage("-F, --from-latest-tag 'use latest tag as start (instead of --from)'") .conflicts_with("from")) // Because we may want to add more "flavors" at a later date, we can automate the process // of enumerating all possible values with clap .arg(Arg::from_usage("-l, --link-style=[style] 'The style of repository link to generate{n}(Defaults to github)'") .possible_values(&styles)) // Because no one should use --changelog and either an --infile or --outfile, we add those // to conflicting lists .arg(Arg::from_usage("-C, --changelog=[changelog] 'A previous changelog to prepend new changes to (this is like{n}\ using the same file for both --infile and --outfile and{n}\ should not be used in conjuction with either)'") .conflicts_with("infile") .conflicts_with("outfile")) // Since --setversion shouldn't be used with any of the --major, --minor, or --match, we // set those as exclusions .arg_group(ArgGroup::with_name("setver") .add_all(vec!["major", "minor", "patch", "ver"])) .after_help("\ * If your .git directory is a child of your project directory (most common, such as\n\ /myproject/.git) AND not in the current working directory (i.e you need to use --work-tree or\n\ --git-dir) you only need to specify either the --work-tree (i.e. /myproject) OR --git-dir (i.e. \n\ /myproject/.git), you don't need to use both.\n\n\ ** If using the --config to specify a clog configuration TOML file NOT in the current working\n\ directory (meaning you need to use --work-tree or --git-dir) AND the TOML file is inside your\n\ project directory (i.e. /myproject/.clog.toml) you do not need to use --work-tree or --git-dir.") .get_matches(); let start_nsec = time::get_time().nsec; let clog = Clog::from_matches(&matches).unwrap_or_else(|e| e.exit()); if let Some(ref file) = clog.outfile { clog.write_changelog_to(file).unwrap_or_else(|e| e.exit()); let end_nsec = time::get_time().nsec; let elapsed_mssec = (end_nsec - start_nsec) / 1000000; println!("changelog written. (took {} ms)", elapsed_mssec); } else { clog.write_changelog().unwrap_or_else(|e| e.exit()); } }
use std::fs::File; use std::io::{BufRead, BufReader}; use std::cmp::{min, max}; fn path(wire: Vec<(char, i32)>) -> (Vec<i32>, Vec<i32>) { let (mut coords, mut steps) = (vec![0, 0], vec![0]); for (dir, amt) in wire { coords.push(coords[coords.len() - 2] + match dir { 'U' | 'R' => amt, 'D' | 'L' => -amt, _ => panic!("invalid direction"), }); steps.push(steps[steps.len() - 1] + amt); } (coords, steps) } fn main() { let mut input = BufReader::new(File::open("in3.txt").unwrap()).lines().map(|line| line.unwrap().split(',').map(|segment| (segment.chars().next().unwrap(), segment[1..].parse::<i32>().unwrap())).collect::<Vec<_>>()); let ((coords1, steps1), (coords2, steps2), mut min_dist, mut min_steps) = (path(input.next().unwrap()), path(input.next().unwrap()), 300_000, 300_000); for i in 0 .. coords1.len() - 2 { for j in 0 .. coords2.len() - 2 { let (ci0, ci1, ci2, cj0, cj1, cj2) = (coords1[i], coords1[i + 1], coords1[i + 2], coords2[j], coords2[j + 1], coords2[j + 2]); if (i + j) % 2 == 1 && min(cj0, cj2) <= ci1 && ci1 <= max(cj0, cj2) && min(ci0, ci2) <= cj1 && cj1 <= max(ci0, ci2) { min_dist = min(min_dist, ci1.abs() + cj1.abs()); min_steps = min(min_steps, steps1[i] + (ci1 - cj0).abs() + steps2[j] + (cj1 - ci0).abs()); } } } println!("Part A: {}", min_dist); // 1337 println!("Part B: {}", min_steps); // 65356 }
pub mod weapons;
use gtk::prelude::*; use gtk::{HeaderBarBuilder, StackSwitcherBuilder}; mod settings; use crate::ui::State; use settings::Settings; use std::cell::RefCell; use std::rc::Rc; pub struct Header { pub container: gtk::HeaderBar, pub stack_switch: gtk::StackSwitcher, pub settings: Settings, } impl Header { pub fn new(state: &Rc<RefCell<State>>) -> Header { let container = HeaderBarBuilder::new().show_close_button(true).build(); let stack_switch = StackSwitcherBuilder::new().build(); container.set_custom_title(Some(&stack_switch)); let settings = Settings::new(state); container.pack_end(&settings.menu_button); Header { container, stack_switch, settings, } } }
use std::cell::RefCell; use std::cmp::Ordering; use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; use std::time::Duration; use glommio::channels::channel_mesh::Senders as ChannelMeshSender; use glommio::sync::RwLock; use glommio::timer::TimerActionOnce; use glommio::Local; use tokio::sync::mpsc::Sender as BoundedSender; use tokio::sync::oneshot::Sender; use tokio::sync::Mutex; use tracing::{debug, instrument, trace}; use crate::cache::{Cache, KeyCacheEntry, KeyCacheResult}; use crate::compact_sched::CompactScheduler; use crate::context::Context; use crate::error::{HelixError, Result}; use crate::file::{FileNo, IndexBlockBuilder, Rick, SSTable, TableBuilder}; use crate::index::MemIndex; use crate::io_worker; use crate::option::{Options, ReadOption}; use crate::types::{Bytes, Entry, LevelId, LevelInfo, ThreadId, TimeRange, Timestamp, ValueFormat}; pub struct LevelConfig { /// Use one file to store non-Rick (SSTable) entries or not. pub sharding_sstable: bool, /// Max levels can hold. This option should be greater than 0. /// Levels will be L0 to L`max_level` (inclusive). /// Might be useless due to TimeStamp Reviewer? pub max_level: usize, /// The max difference of timestamps inside one level. /// Might be useless due to TimeStamp Reviewer? pub level_duration: u64, } /// APIs require unique reference (&mut self) because this `Level` is designed /// to be used inside one thread (!Send). The fields should also be !Send if /// possible. crate struct Levels<CS: CompactScheduler> { tid: ThreadId, // todo: remove this mutex timestamp_reviewer: Arc<Mutex<Box<dyn TimestampReviewer>>>, ctx: Arc<Context>, memindex: Mutex<MemIndex>, // todo: use group of ricks to achieve log-rotate/GC rick: Mutex<Rick>, level_info: Arc<Mutex<LevelInfo>>, cache: Cache, write_batch: Rc<WriteBatch>, ts_action_sender: ChannelMeshSender<TimestampAction>, compact_sched: Rc<CS>, } impl<CS: CompactScheduler> Levels<CS> { pub async fn try_new( tid: ThreadId, opts: Options, timestamp_reviewer: Arc<Mutex<Box<dyn TimestampReviewer>>>, ctx: Arc<Context>, ts_action_sender: ChannelMeshSender<TimestampAction>, level_info: Arc<Mutex<LevelInfo>>, compact_sched: Rc<CS>, ) -> Result<Rc<Self>> { // todo: remove the default rick. the number in `FileNo::Rick` shouldn't be 0. let rick_file = ctx.file_manager.open(tid, FileNo::Rick(0)).await.unwrap(); let rick = Rick::open(rick_file, Some(ValueFormat::RawValue)).await?; let memindex = rick.construct_index().await?; let cache = Cache::with_config(opts.cache); let write_batch = WriteBatch::with_config(opts.write_batch); let levels = Self { tid, timestamp_reviewer, ctx, memindex: Mutex::new(memindex), rick: Mutex::new(rick), level_info, cache, write_batch: Rc::new(write_batch), ts_action_sender, compact_sched, }; let levels = Rc::new(levels); Ok(levels) } pub async fn put(self: Rc<Self>, entries: Vec<Entry>, notifier: Sender<Result<()>>) { self.write_batch .clone() .enqueue(entries, notifier, self.clone()) .await; } /// Put entries without batching them. pub async fn put_internal(&self, entries: Vec<Entry>) -> Result<()> { if entries.is_empty() { return Ok(()); } let max_timestamp = entries .iter() .max_by_key(|entry| entry.timestamp) .unwrap() .timestamp; let indices = self.rick.lock().await.append(entries).await?; self.memindex.lock().await.insert_entries(indices)?; // review timestamp and handle actions. let review_actions = self.timestamp_reviewer.lock().await.observe(max_timestamp); self.handle_actions(review_actions.clone()).await?; Local::yield_if_needed().await; Ok(()) } pub async fn get( &self, time_key: &(Timestamp, Bytes), opt: ReadOption, ) -> Result<Option<Entry>> { let level = self.level_info.lock().await.get_level_id(time_key.0); match level { None => Ok(None), Some(0) => self.get_from_rick(time_key).await, Some(l) => self.get_from_table(time_key, l, opt).await, } } // todo: handle multi level scan pub async fn scan( &self, time_range: TimeRange, key_start: Bytes, key_end: Bytes, sender: BoundedSender<Vec<Entry>>, cmp: Arc<dyn Fn(&[u8], &[u8]) -> Ordering>, ) -> Result<()> { let mut user_keys = self.memindex.lock().await.user_keys(); // filter user_keys.retain(|key| { cmp(key, &key_start) != Ordering::Less && cmp(key, &key_end) != Ordering::Greater }); // sort user_keys.sort_by(|lhs, rhs| cmp(lhs, rhs)); // todo: refine this for user_key in user_keys { let mut time_key = (0, user_key); for ts in time_range.range() { time_key.0 = ts; if let Some(entry) = self.get(&time_key, ReadOption::default()).await? { sender.send(vec![entry]).await?; } } } Ok(()) } #[inline] async fn get_from_rick(&self, time_key: &(Timestamp, Bytes)) -> Result<Option<Entry>> { if let Some(offset) = self.memindex.lock().await.get(time_key)? { let entry = self.rick.lock().await.read(offset).await?; return Ok(Some(entry)); } Ok(None) } // todo: refine, split #[inline] async fn get_from_table( &self, time_key: &(Timestamp, Bytes), level_id: LevelId, opt: ReadOption, ) -> Result<Option<Entry>> { let mut key_cache_entry = KeyCacheEntry::new(time_key); let cache_result = self.cache.get_key(time_key); trace!("cache result of {:?} : {:?}", time_key, cache_result); let entry = match cache_result { KeyCacheResult::Value(value) => { return Ok(Some(Entry { timestamp: time_key.0, key: time_key.1.to_owned(), value, })); } KeyCacheResult::Compressed(compressed) => { let value = ok_unwrap!(self.decompress_and_find(time_key, &compressed, opt.decompress)?); key_cache_entry.value = Some(&value); key_cache_entry.compressed = Some(&compressed); self.cache.put_key(key_cache_entry); Ok(Some(Entry { timestamp: time_key.0, key: time_key.1.clone(), value: value.clone(), })) } KeyCacheResult::Position(tid, level_id, offset) => { let rick_file = self .ctx .file_manager .open(tid, FileNo::Rick(level_id)) .await?; let rick = Rick::open(rick_file, None).await?; let raw_bytes = rick.read(offset as u64).await?; let value = ok_unwrap!(self.decompress_and_find( time_key, &raw_bytes.value, opt.decompress )?); key_cache_entry.value = Some(&value); key_cache_entry.compressed = Some(&raw_bytes.value); self.cache.put_key(key_cache_entry); Ok(Some(Entry { timestamp: time_key.0, key: time_key.1.clone(), value: value.clone(), })) } KeyCacheResult::NotFound => { let handle = if let Some(handle) = self.cache.get_table_handle(&(self.tid, level_id).into()) { handle } else { let table_file = self .ctx .file_manager .open(self.tid, FileNo::SSTable(level_id)) .await?; // table file is empty, means this level haven't finished it compaction. Need to // read value from L0 rick. // But this check (via file's size) is not good. the write operation may not // guarantee to be atomic. todo: add a flag to indicate // whether a compact is finished. if table_file.size().await? == 0 { return self.get_from_rick(time_key).await; } let handle = SSTable::open(table_file) .await? .into_read_handle(self.ctx.clone()) .await?; let handle = Rc::new(handle); self.cache .put_table_handle((self.tid, level_id).into(), handle.clone()) .await?; handle }; let entry = handle.get(time_key).await?; let is_compressed = handle.is_compressed(); // update cache if let Some(mut entry) = entry { if is_compressed { let value = ok_unwrap!(self.decompress_and_find( time_key, &entry.value, opt.decompress, )?); key_cache_entry.compressed = Some(&entry.value); self.cache.put_key(key_cache_entry); entry.timestamp = time_key.0; entry.value = value; } else { key_cache_entry.value = Some(&entry.value); self.cache.put_key(key_cache_entry); } Ok(Some(entry)) } else { Ok(None) } } }; entry } /// Propagate action to other peers. async fn propagate_action(&self, action: TimestampAction) -> Result<()> { for consumer_id in 0..self.ts_action_sender.nr_consumers() { if consumer_id != self.ts_action_sender.peer_id() { self.ts_action_sender .send_to(consumer_id, action) .await // todo: check this unwrap .unwrap(); } } Ok(()) } pub(crate) async fn handle_actions(&self, actions: Vec<TimestampAction>) -> Result<()> { for action in actions { debug!("tid: {}, action: {:?}", self.tid, action); match action { TimestampAction::Compact(start_ts, end_ts, level_id) => { let level_id = match level_id { Some(id) => id, None => { // fetch new level id and update level info let level_id = self .level_info .lock() .await .add_level(start_ts, end_ts, &self.ctx.file_manager) .await?; // propagate self.propagate_action(TimestampAction::Compact( start_ts, end_ts, Some(level_id), )) .await?; level_id } }; self.compact(TimeRange::from((start_ts, end_ts)), level_id) .await?; // todo: enable this // self.compact_sched.enqueue(level_id); } TimestampAction::Outdate(_) => { self.propagate_action(action).await?; self.outdate().await? } } } Ok(()) } /// Compact entries from rick in [start_ts, end_ts] to next level. /// /// This function is wrapped by `Gate` which means HelixCore will wait it to /// finish before close and shutdown. Whereas compactions that are invoked /// after the gate is closing or closed will be ignored. /// /// todo: how to handle rick file is not fully covered by given time range?. #[instrument] crate async fn compact(&self, range: TimeRange, level_id: LevelId) -> Result<()> { // Keep the gate open until compact finished. The question mark (try) indicates // a early return once it's failed to spawn to the gate. let (tx, rx) = glommio::channels::local_channel::new_bounded(1); io_worker::GATE .with(|gate| gate.spawn(async move { rx.recv().await }))? .detach(); debug!( "[compact] start compact. range {:?}, level {}", range, level_id ); let mut table_builder = TableBuilder::begin( self.tid, level_id, self.ctx .file_manager .open(self.tid, FileNo::SSTable(level_id)) .await?, ); // make entry_map (from memindex) and purge let memindex = self.memindex.lock().await; let offsets = memindex.load_time_range(range); drop(memindex); let mut rick = self.rick.lock().await; let entries = rick.reads(offsets).await?; let offset_end = rick.get_legal_offset_end(); drop(rick); trace!("[compact] level {}, rick reads", level_id); let mut entry_map = HashMap::new(); for entry in entries { let Entry { timestamp, key, value, } = entry; let pair_list: &mut Vec<_> = entry_map.entry(key).or_default(); pair_list.push((timestamp, value)); } trace!("[compact] level {}, make entry map", level_id); // prepare output files. let mut index_bb = IndexBlockBuilder::new(); let rick_file = self .ctx .file_manager .open(self.tid, FileNo::Rick(level_id)) .await?; let mut rick = Rick::open(rick_file, Some(ValueFormat::CompressedValue)).await?; rick.set_align_ts(range.start()).await?; // call compress_fn to compact points, build rick file and index block. for (key, ts_value) in entry_map { debug_assert!(!ts_value.is_empty()); let first_ts = ts_value[0].0; let compressed_data = self .ctx .fn_registry .compress_entries(key.clone(), ts_value)?; // todo: add rick builder let mut position = rick .append(vec![Entry { timestamp: first_ts, key, value: compressed_data, }]) .await?; let (timestamp, key, offset) = position.pop().unwrap(); index_bb.add_entry(&key, timestamp, offset); } trace!("[compact] level {}, build rick", level_id); // make sstable // table_builder.add_entries(keys, value_positions); table_builder.add_block(index_bb); table_builder.finish().await?; trace!("[compact] level {}, build table", level_id); // todo: gc rick // self.rick.lock().await.clean().await?; // todo: gc memindex // self.memindex.lock().await.purge_time_range(range); let mut memindex = self.memindex.lock().await; memindex.purge_time_range(range); drop(memindex); trace!("[compact] level {}, purge memindex", level_id); let mut rick = self.rick.lock().await; rick.push_legal_offset_start(offset_end).await?; drop(rick); trace!("[compact] level {}, clean rick", level_id); debug!("compact {} finish", level_id); let _ = tx.send(()).await; Ok(()) } /// Perform compaction on the given level id. /// /// This procedure assume the level going to compact is inactive, which has /// the level id assigned, has corresponding rick file, and may serving read /// requests. /// /// It's not this procedure's response to switch active level. And it also /// has nothing to do with memindex. #[instrument] crate async fn compact_level(&self, level_id: LevelId) -> Result<()> { self.compact_sched.finished(level_id); Ok(()) } async fn outdate(&self) -> Result<()> { self.level_info .lock() .await .remove_last_level(&self.ctx.file_manager) .await?; todo!() } fn decompress_and_find( &self, time_key: &(Timestamp, Bytes), raw_bytes: &[u8], decompress: bool, ) -> Result<Option<Bytes>> { if !decompress { return Ok(Some(raw_bytes.to_owned())); } let mut entries = self .ctx .fn_registry .decompress_entries(&time_key.1, raw_bytes)?; // todo: move this logic to UDCF entries.sort_by_key(|e| e.0); let index = ok_unwrap!(entries .binary_search_by_key(&time_key.0, |(ts, _)| *ts) .ok()); let (_, value) = &entries[index]; Ok(Some(value.clone())) } } impl<CS: CompactScheduler> std::fmt::Debug for Levels<CS> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Levels") .field("thread id", &self.tid) .finish() } } /// "Timestamp" in `HelixDB` is a logical concept. It is not bound with the real /// time. [TimestampReviewer] defines how timestamp should be considered. /// Including when to do a compaction, when to outdate a part of data etc. pub trait TimestampReviewer: Send + Sync { fn observe(&mut self, timestamp: Timestamp) -> Vec<TimestampAction>; } /// Actions given by [TimestampReviewer]. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum TimestampAction { /// Compact data between two timestamps (both inclusive). /// The third parameter is the id of new level. This field is filled by the /// peer who observed this original "compact action" (sent by /// `TimestampReviewer`). Compact(Timestamp, Timestamp, Option<LevelId>), /// Outdate data which timestamp is smaller than given. Outdate(Timestamp), } /// A simple timestamp review implementation. It has two config entries /// `rick_range` and `outdate_range`. `rick_range` defines the range of /// rick and sstable files. `outdate_range` defines how much data should /// be kept. `outdate_range` should be integer times of `rick_range` even /// if it is unchecked. /// /// This implementation is not bound with real world time. It assume the /// timestamp comes from `observe()` call is the newest. And just triggers /// compaction and outdate only based on this. In real scenario /// when timestamp has more meaning or restriction, more complex logic can /// be achieved. pub struct SimpleTimestampReviewer { // config part rick_range: Timestamp, outdate_range: Timestamp, // status part last_compacted: Timestamp, last_outdated: Timestamp, } impl SimpleTimestampReviewer { pub fn new(rick_range: Timestamp, outdate_range: Timestamp) -> Self { Self { rick_range, outdate_range, last_compacted: 0, last_outdated: 0, } } } impl TimestampReviewer for SimpleTimestampReviewer { fn observe(&mut self, timestamp: Timestamp) -> Vec<TimestampAction> { let mut actions = vec![]; if timestamp - self.last_compacted + 1 >= self.rick_range { actions.push(TimestampAction::Compact( self.last_compacted, timestamp, None, )); self.last_compacted = timestamp + 1; } if timestamp - self.last_outdated + 1 >= self.outdate_range { actions.push(TimestampAction::Outdate( self.last_outdated + self.rick_range - 1, )); self.last_outdated += self.rick_range; } actions } } #[derive(Debug, Clone, Copy)] pub struct WriteBatchConfig { /// The maximum number of entries can be hold in one batch. pub batch_size: usize, /// The longest time duration between two batch consumptions. pub timeout: Duration, } impl Default for WriteBatchConfig { fn default() -> Self { Self { batch_size: 0, timeout: Duration::from_millis(0), } } } /// Batching write request struct WriteBatch { notifier: RefCell<Vec<Sender<Result<()>>>>, buf: RefCell<Vec<Entry>>, timeout: Duration, batch_size: usize, /// Lock on two vectors `notifier` and `buf`. lock: Mutex<()>, /// Generated by `TimerActionOnce::do_in()` with the purpose of /// consuming batched entries after some duration. action: RwLock<Option<TimerActionOnce<()>>>, // level: Rc<Levels>, } impl WriteBatch { pub fn with_config(config: WriteBatchConfig) -> Self { Self { notifier: RefCell::new(vec![]), buf: RefCell::new(vec![]), timeout: config.timeout, batch_size: config.batch_size, lock: Mutex::new(()), action: RwLock::new(None), } } pub fn default() -> Self { Self::with_config(WriteBatchConfig::default()) } /// Enqueue some write requests. Then check the size limit. /// This will reset the timeout timer. #[allow(clippy::branches_sharing_code)] pub async fn enqueue<CS: CompactScheduler>( self: Rc<Self>, mut reqs: Vec<Entry>, tx: Sender<Result<()>>, level: Rc<Levels<CS>>, ) { // enqueue let guard = self.lock.lock().await; self.notifier.borrow_mut().push(tx); self.buf.borrow_mut().append(&mut reqs); // check size limit if self.buf.borrow().len() >= self.batch_size { drop(guard); self.consume(level).await; } else { drop(guard); self.set_or_rearm(level).await; } } /// Consume all batched entries. pub async fn consume<CS: CompactScheduler>(self: Rc<Self>, level: Rc<Levels<CS>>) { // let mut action_guard = self.action.write().await.unwrap(); // take contents let guard = self.lock.lock().await; let notifier = self.notifier.take(); let buf = self.buf.take(); drop(guard); // write and reply let result = io_worker::GATE .with(|gate| { gate.spawn(async move { level.put_internal(buf).await }) .unwrap() }) .await; if result.is_ok() { for tx in notifier { let _ = tx.send(Ok(())); } } else { for tx in notifier { let _ = tx.send(Err(HelixError::Poisoned("Put".to_string()))); } } // todo: finish cancellation // destroy action timer as this "consume action" is already triggered // (regardless of it is triggered by timer or `Levels`'). // if let Some(action) = action_guard.take() { // action.cancel().await; // } } async fn destroy_action(&self) { let mut action_guard = self.action.write().await.unwrap(); if let Some(action) = &*action_guard { action.destroy(); } drop(action_guard.take()); } async fn set_or_rearm<CS: CompactScheduler>(self: Rc<Self>, level: Rc<Levels<CS>>) { let mut action = self.action.write().await.unwrap(); // rearm timer if let Some(action) = &*action { action.rearm_in(self.timeout); return; } // otherwise set the action *action = Some(TimerActionOnce::do_in( self.timeout, self.clone().consume(level), )); } } #[cfg(test)] mod test { use glommio::channels::channel_mesh::MeshBuilder; use glommio::LocalExecutor; use tempfile::tempdir; use super::*; use crate::compact_sched::QueueUpCompSched; use crate::file::FileManager; use crate::fn_registry::FnRegistry; #[tokio::test] async fn simple_timestamp_reviewer_trigger_compact_and_outdate() { let mut tsr = SimpleTimestampReviewer::new(10, 30); let mut actions = vec![]; let expected = vec![ TimestampAction::Compact(0, 9, None), TimestampAction::Compact(10, 19, None), TimestampAction::Compact(20, 29, None), TimestampAction::Outdate(9), TimestampAction::Compact(30, 39, None), TimestampAction::Outdate(19), ]; for i in 0..40 { actions.append(&mut tsr.observe(i)); } assert_eq!(actions, expected); } #[test] fn put_get_on_rick() { let ex = LocalExecutor::default(); ex.run(async { let base_dir = tempdir().unwrap(); let file_manager = FileManager::with_base_dir(base_dir.path(), 1).unwrap(); let fn_registry = FnRegistry::new_noop(); let ctx = Arc::new(Context { file_manager, fn_registry, }); let timestamp_reviewer: Arc<Mutex<Box<dyn TimestampReviewer>>> = Arc::new(Mutex::new(Box::new(SimpleTimestampReviewer::new(10, 30)))); let sender = MeshBuilder::full(1, 1).join().await.unwrap().0; let level_info = Arc::new(Mutex::new( ctx.file_manager.open_level_info().await.unwrap(), )); let (sched, tq) = QueueUpCompSched::default(); let levels = Levels::try_new( 0, Options::default(), timestamp_reviewer, ctx, sender, level_info, sched.clone(), ) .await .unwrap(); sched.clone().init(levels.clone()); sched.install(tq).unwrap(); let entries = vec![ (1, b"key1".to_vec(), b"value1".to_vec()).into(), (2, b"key1".to_vec(), b"value1".to_vec()).into(), (3, b"key1".to_vec(), b"value1".to_vec()).into(), (1, b"key2".to_vec(), b"value2".to_vec()).into(), (2, b"key2".to_vec(), b"value2".to_vec()).into(), (3, b"key3".to_vec(), b"value1".to_vec()).into(), ]; levels.put_internal(entries.clone()).await.unwrap(); for entry in entries { assert_eq!( entry, levels .get(entry.time_key(), ReadOption::default().no_decompress()) .await .unwrap() .unwrap() ); } // overwrite a key let new_entry: Entry = (1, b"key1".to_vec(), b"value3".to_vec()).into(); levels.put_internal(vec![new_entry.clone()]).await.unwrap(); assert_eq!( new_entry, levels .get(new_entry.time_key(), ReadOption::default().no_decompress()) .await .unwrap() .unwrap() ); }); } #[test] fn put_get_with_compaction() { let ex = LocalExecutor::default(); ex.run(async { let base_dir = tempdir().unwrap(); let file_manager = FileManager::with_base_dir(base_dir.path(), 1).unwrap(); let fn_registry = FnRegistry::new_noop(); let ctx = Arc::new(Context { file_manager, fn_registry, }); let timestamp_reviewer: Arc<Mutex<Box<dyn TimestampReviewer>>> = Arc::new(Mutex::new(Box::new(SimpleTimestampReviewer::new(10, 30)))); let sender = MeshBuilder::full(1, 1).join().await.unwrap().0; let level_info = Arc::new(Mutex::new( ctx.file_manager.open_level_info().await.unwrap(), )); let (sched, tq) = QueueUpCompSched::default(); let levels = Levels::try_new( 0, Options::default(), timestamp_reviewer, ctx.clone(), sender, level_info, sched.clone(), ) .await .unwrap(); sched.clone().init(levels.clone()); sched.install(tq).unwrap(); for timestamp in 0..25 { levels .put_internal(vec![(timestamp, b"key".to_vec(), b"value".to_vec()).into()]) .await .unwrap(); } for timestamp in 0..25 { let result = levels .get(&(timestamp, b"key".to_vec()), ReadOption::default()) .await .unwrap() .unwrap(); assert_eq!( result, (timestamp, b"key".to_vec(), b"value".to_vec()).into() ); } }); } }
use crate::parse::{Instruction, ParseError, ParseResult, RollbackableTokenStream, ToneModifier}; fn hex_to_num(hex: u8) -> Option<usize> { if b'0' <= hex && hex <= b'9' { Some((hex - b'0') as usize) } else if b'a' <= hex && hex <= b'f' { Some((hex - b'a') as usize + 10) } else if b'A' <= hex && hex <= b'F' { Some((hex - b'A') as usize + 10) } else { None } } #[derive(PartialEq, Debug)] pub enum Effect { Delay { delay: f32, feedback: f32 }, LowPassFilter { cut_off: f32 }, HighPassFilter { cut_off: f32 }, } fn effects(stream: &mut RollbackableTokenStream) -> ParseResult { let (effect_at, effect) = stream.take_character()?; match effect { 'd' => { let params: Vec<_> = stream .comma_separated_n_numbers(2)? .into_iter() .map(|x| x as f32 / 1000.0) .collect(); let delay = params[0]; let feedback = params[1]; Ok(Some(Instruction::ToneModifier(ToneModifier::Effect( Effect::Delay { delay, feedback }, )))) } 'l' => { let params = stream.comma_separated_n_numbers(1)?; let cut_off = params[0] as f32; Ok(Some(Instruction::ToneModifier(ToneModifier::Effect( Effect::LowPassFilter { cut_off }, )))) } 'h' => { let params = stream.comma_separated_n_numbers(1)?; let cut_off = params[0] as f32; Ok(Some(Instruction::ToneModifier(ToneModifier::Effect( Effect::HighPassFilter { cut_off }, )))) } _ => Err(ParseError::unexpected_char(effect_at, effect)), } } static BASE64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; pub fn base64_to_bits(ch: u8) -> usize { BASE64_CHARS.iter().position(|&x| x == ch).unwrap_or(0) } pub fn tone(stream: &mut RollbackableTokenStream) -> ParseResult { if stream.expect_character('@').is_err() { return Ok(None); } if let Ok((_, number)) = stream.take_number() { return Ok(Some(Instruction::ToneModifier(ToneModifier::Tone(number)))); } let (inst_at, inst) = stream.take_character()?; match inst { 'd' => { let params = stream.comma_separated_n_numbers(2)?; Ok(Some(Instruction::ToneModifier(ToneModifier::Detune( params[0], params[1] as f32 / 10000.0, )))) } 'e' => { let params = stream.comma_separated_n_numbers(4)?; let params: Vec<_> = params.iter().map(|&x| x as f32 / 100.0).collect(); let envelope = Instruction::ToneModifier(ToneModifier::Envelope( params[0], params[1], params[2], params[3], )); Ok(Some(envelope)) } 'h' => { let (_, string) = stream.take_brace_string()?; let pcm = string .bytes() .map(|byte| { hex_to_num(byte) .map(|x| (x as f32 - 8.0) / 8.0) .unwrap_or(0.0) }) .collect(); Ok(Some(Instruction::ToneModifier( ToneModifier::DefinePCMTone(pcm), ))) } 'n' => { let (_, string) = stream.take_brace_string()?; let pcm = string .bytes() .flat_map(|byte| { let bits = base64_to_bits(byte); (0..6) .rev() .map(move |i| if bits >> i & 1 == 0 { -1 } else { 1 }) }) .scan(0i8, |acc, x| { let (sum, _) = acc.overflowing_add(x); *acc = sum; Some(*acc) }) .map(|x| x as f32 / 128.0) .collect(); Ok(Some(Instruction::ToneModifier( ToneModifier::DefinePCMTone(pcm), ))) } 'p' => Ok(Some(Instruction::ToneModifier(ToneModifier::PCMTone( stream.take_number()?.1, )))), 'g' => { let (_, gate) = stream.take_number()?; Ok(Some(Instruction::ToneModifier(ToneModifier::Gate( gate as f32 / 1000.0, )))) } 'v' => { let (_, volume) = stream.take_number()?; Ok(Some(Instruction::ToneModifier(ToneModifier::Volume( volume as f32 / 100.0, )))) } 't' => { let (_, tune) = stream.take_number()?; Ok(Some(Instruction::ToneModifier(ToneModifier::Tune( tune as f32 / 1000.0, )))) } 'f' => effects(stream), _ => Err(ParseError::unexpected_char(inst_at, inst)), } } pub fn synthesize(stream: &mut RollbackableTokenStream) -> ParseResult { if stream.expect_character('@').is_err() || stream.expect_character('(').is_err() { return Ok(None); } let mut tones = vec![vec![]]; while stream.expect_character(')').is_err() { if stream.expect_character(',').is_ok() || stream.expect_character('|').is_ok() { tones.push(vec![]); continue; } if let Some(Instruction::ToneModifier(modifier)) = tone(stream)? { tones.last_mut().unwrap().push(modifier); } else { if let Some(token) = stream.next() { return Err(ParseError::UnexpectedToken(token.clone())); } else { return Err(ParseError::UnexpectedEOF); } } } Ok(Some(Instruction::Synthesize(tones))) }
use chrono; use failure::Error; use fern; use log; use std::net::SocketAddr; const ADDRESS: &str = "127.0.0.1:8080"; pub fn make_socket_address() -> SocketAddr { ADDRESS.parse().expect("Failed to parse address.") } pub fn configure_logging() -> Result<(), Error> { fern::Dispatch::new() .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}:{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.level(), record.target(), record.line().unwrap_or(0), message )); }) .level(log::LevelFilter::Debug) .level_for("tokio_core", log::LevelFilter::Warn) .level_for("tokio_reactor", log::LevelFilter::Warn) .chain(std::io::stdout()) .apply()?; Ok(()) }
use crate::{error::ClientError, network::request_async, Result}; use isahc::prelude::*; use serde_derive::Deserialize; const API_ENDPOINT: &str = "https://api.wowinterface.com/addons"; const DL_ENDPOINT: &str = "https://cdn.wowinterface.com/downloads/getfile.php?id="; #[derive(Clone, Debug, Deserialize)] /// Struct for applying tukui details to an `Addon`. pub struct Package { pub id: String, pub version: String, } /// Function to fetch remote addon packages which contains /// information about the addon on the repository. /// Note: More packages can be returned for a single `Addon` pub async fn fetch_remote_packages(id: &str, token: &str) -> Result<Vec<Package>> { let url = format!("{}/details/{}.json", API_ENDPOINT, id); let headers = vec![("x-api-token", token)]; let timeout = Some(30); let mut resp = request_async(url, headers, timeout).await?; if resp.status().is_success() { let addon_details: Vec<Package> = resp.json()?; Ok(addon_details) } else { Err(ClientError::Custom(format!( "Couldn't fetch details for addon. Server returned: {}", resp.text()? ))) } } /// Return the `remote_url` for a given `wowi_id`. pub fn remote_url(id: &str) -> String { format!("{}{}", DL_ENDPOINT, id) }
#[doc = "Reader of register SWPR"] pub type R = crate::R<u32, super::SWPR>; #[doc = "Writer for register SWPR"] pub type W = crate::W<u32, super::SWPR>; #[doc = "Register SWPR `reset()`'s with value 0"] impl crate::ResetValue for super::SWPR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `Page0_WP`"] pub type PAGE0_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page0_WP`"] pub struct PAGE0_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE0_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `Page1_WP`"] pub type PAGE1_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page1_WP`"] pub struct PAGE1_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE1_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `Page2_WP`"] pub type PAGE2_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page2_WP`"] pub struct PAGE2_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE2_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `Page3_WP`"] pub type PAGE3_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page3_WP`"] pub struct PAGE3_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE3_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `Page4_WP`"] pub type PAGE4_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page4_WP`"] pub struct PAGE4_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE4_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `Page5_WP`"] pub type PAGE5_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page5_WP`"] pub struct PAGE5_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE5_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `Page6_WP`"] pub type PAGE6_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page6_WP`"] pub struct PAGE6_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE6_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `Page7_WP`"] pub type PAGE7_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page7_WP`"] pub struct PAGE7_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE7_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `Page8_WP`"] pub type PAGE8_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page8_WP`"] pub struct PAGE8_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE8_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `Page9_WP`"] pub type PAGE9_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page9_WP`"] pub struct PAGE9_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE9_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `Page10_WP`"] pub type PAGE10_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page10_WP`"] pub struct PAGE10_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE10_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `Page11_WP`"] pub type PAGE11_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page11_WP`"] pub struct PAGE11_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE11_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `Page12_WP`"] pub type PAGE12_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page12_WP`"] pub struct PAGE12_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE12_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `Page13_WP`"] pub type PAGE13_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page13_WP`"] pub struct PAGE13_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE13_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `Page14_WP`"] pub type PAGE14_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page14_WP`"] pub struct PAGE14_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE14_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `Page15_WP`"] pub type PAGE15_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page15_WP`"] pub struct PAGE15_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE15_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `Page16_WP`"] pub type PAGE16_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page16_WP`"] pub struct PAGE16_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE16_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `Page17_WP`"] pub type PAGE17_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page17_WP`"] pub struct PAGE17_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE17_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `Page18_WP`"] pub type PAGE18_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page18_WP`"] pub struct PAGE18_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE18_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `Page19_WP`"] pub type PAGE19_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page19_WP`"] pub struct PAGE19_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE19_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `Page20_WP`"] pub type PAGE20_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page20_WP`"] pub struct PAGE20_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE20_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `Page21_WP`"] pub type PAGE21_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page21_WP`"] pub struct PAGE21_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE21_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `Page22_WP`"] pub type PAGE22_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page22_WP`"] pub struct PAGE22_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE22_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `Page23_WP`"] pub type PAGE23_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page23_WP`"] pub struct PAGE23_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE23_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `Page24_WP`"] pub type PAGE24_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page24_WP`"] pub struct PAGE24_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE24_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `Page25_WP`"] pub type PAGE25_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page25_WP`"] pub struct PAGE25_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE25_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `Page26_WP`"] pub type PAGE26_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page26_WP`"] pub struct PAGE26_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE26_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `Page27_WP`"] pub type PAGE27_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page27_WP`"] pub struct PAGE27_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE27_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `Page28_WP`"] pub type PAGE28_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page28_WP`"] pub struct PAGE28_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE28_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `Page29_WP`"] pub type PAGE29_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page29_WP`"] pub struct PAGE29_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE29_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `Page30_WP`"] pub type PAGE30_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page30_WP`"] pub struct PAGE30_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE30_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `Page31_WP`"] pub type PAGE31_WP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Page31_WP`"] pub struct PAGE31_WP_W<'a> { w: &'a mut W, } impl<'a> PAGE31_WP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 0 - Write protection"] #[inline(always)] pub fn page0_wp(&self) -> PAGE0_WP_R { PAGE0_WP_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Write protection"] #[inline(always)] pub fn page1_wp(&self) -> PAGE1_WP_R { PAGE1_WP_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Write protection"] #[inline(always)] pub fn page2_wp(&self) -> PAGE2_WP_R { PAGE2_WP_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Write protection"] #[inline(always)] pub fn page3_wp(&self) -> PAGE3_WP_R { PAGE3_WP_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Write protection"] #[inline(always)] pub fn page4_wp(&self) -> PAGE4_WP_R { PAGE4_WP_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - Write protection"] #[inline(always)] pub fn page5_wp(&self) -> PAGE5_WP_R { PAGE5_WP_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Write protection"] #[inline(always)] pub fn page6_wp(&self) -> PAGE6_WP_R { PAGE6_WP_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - Write protection"] #[inline(always)] pub fn page7_wp(&self) -> PAGE7_WP_R { PAGE7_WP_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - Write protection"] #[inline(always)] pub fn page8_wp(&self) -> PAGE8_WP_R { PAGE8_WP_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - Write protection"] #[inline(always)] pub fn page9_wp(&self) -> PAGE9_WP_R { PAGE9_WP_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - Write protection"] #[inline(always)] pub fn page10_wp(&self) -> PAGE10_WP_R { PAGE10_WP_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - Write protection"] #[inline(always)] pub fn page11_wp(&self) -> PAGE11_WP_R { PAGE11_WP_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - Write protection"] #[inline(always)] pub fn page12_wp(&self) -> PAGE12_WP_R { PAGE12_WP_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - Write protection"] #[inline(always)] pub fn page13_wp(&self) -> PAGE13_WP_R { PAGE13_WP_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - Write protection"] #[inline(always)] pub fn page14_wp(&self) -> PAGE14_WP_R { PAGE14_WP_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - Write protection"] #[inline(always)] pub fn page15_wp(&self) -> PAGE15_WP_R { PAGE15_WP_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - Write protection"] #[inline(always)] pub fn page16_wp(&self) -> PAGE16_WP_R { PAGE16_WP_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - Write protection"] #[inline(always)] pub fn page17_wp(&self) -> PAGE17_WP_R { PAGE17_WP_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - Write protection"] #[inline(always)] pub fn page18_wp(&self) -> PAGE18_WP_R { PAGE18_WP_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - Write protection"] #[inline(always)] pub fn page19_wp(&self) -> PAGE19_WP_R { PAGE19_WP_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - Write protection"] #[inline(always)] pub fn page20_wp(&self) -> PAGE20_WP_R { PAGE20_WP_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - Write protection"] #[inline(always)] pub fn page21_wp(&self) -> PAGE21_WP_R { PAGE21_WP_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - Write protection"] #[inline(always)] pub fn page22_wp(&self) -> PAGE22_WP_R { PAGE22_WP_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - Write protection"] #[inline(always)] pub fn page23_wp(&self) -> PAGE23_WP_R { PAGE23_WP_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - Write protection"] #[inline(always)] pub fn page24_wp(&self) -> PAGE24_WP_R { PAGE24_WP_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - Write protection"] #[inline(always)] pub fn page25_wp(&self) -> PAGE25_WP_R { PAGE25_WP_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - Write protection"] #[inline(always)] pub fn page26_wp(&self) -> PAGE26_WP_R { PAGE26_WP_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - Write protection"] #[inline(always)] pub fn page27_wp(&self) -> PAGE27_WP_R { PAGE27_WP_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 28 - Write protection"] #[inline(always)] pub fn page28_wp(&self) -> PAGE28_WP_R { PAGE28_WP_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - Write protection"] #[inline(always)] pub fn page29_wp(&self) -> PAGE29_WP_R { PAGE29_WP_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - Write protection"] #[inline(always)] pub fn page30_wp(&self) -> PAGE30_WP_R { PAGE30_WP_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - Write protection"] #[inline(always)] pub fn page31_wp(&self) -> PAGE31_WP_R { PAGE31_WP_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Write protection"] #[inline(always)] pub fn page0_wp(&mut self) -> PAGE0_WP_W { PAGE0_WP_W { w: self } } #[doc = "Bit 1 - Write protection"] #[inline(always)] pub fn page1_wp(&mut self) -> PAGE1_WP_W { PAGE1_WP_W { w: self } } #[doc = "Bit 2 - Write protection"] #[inline(always)] pub fn page2_wp(&mut self) -> PAGE2_WP_W { PAGE2_WP_W { w: self } } #[doc = "Bit 3 - Write protection"] #[inline(always)] pub fn page3_wp(&mut self) -> PAGE3_WP_W { PAGE3_WP_W { w: self } } #[doc = "Bit 4 - Write protection"] #[inline(always)] pub fn page4_wp(&mut self) -> PAGE4_WP_W { PAGE4_WP_W { w: self } } #[doc = "Bit 5 - Write protection"] #[inline(always)] pub fn page5_wp(&mut self) -> PAGE5_WP_W { PAGE5_WP_W { w: self } } #[doc = "Bit 6 - Write protection"] #[inline(always)] pub fn page6_wp(&mut self) -> PAGE6_WP_W { PAGE6_WP_W { w: self } } #[doc = "Bit 7 - Write protection"] #[inline(always)] pub fn page7_wp(&mut self) -> PAGE7_WP_W { PAGE7_WP_W { w: self } } #[doc = "Bit 8 - Write protection"] #[inline(always)] pub fn page8_wp(&mut self) -> PAGE8_WP_W { PAGE8_WP_W { w: self } } #[doc = "Bit 9 - Write protection"] #[inline(always)] pub fn page9_wp(&mut self) -> PAGE9_WP_W { PAGE9_WP_W { w: self } } #[doc = "Bit 10 - Write protection"] #[inline(always)] pub fn page10_wp(&mut self) -> PAGE10_WP_W { PAGE10_WP_W { w: self } } #[doc = "Bit 11 - Write protection"] #[inline(always)] pub fn page11_wp(&mut self) -> PAGE11_WP_W { PAGE11_WP_W { w: self } } #[doc = "Bit 12 - Write protection"] #[inline(always)] pub fn page12_wp(&mut self) -> PAGE12_WP_W { PAGE12_WP_W { w: self } } #[doc = "Bit 13 - Write protection"] #[inline(always)] pub fn page13_wp(&mut self) -> PAGE13_WP_W { PAGE13_WP_W { w: self } } #[doc = "Bit 14 - Write protection"] #[inline(always)] pub fn page14_wp(&mut self) -> PAGE14_WP_W { PAGE14_WP_W { w: self } } #[doc = "Bit 15 - Write protection"] #[inline(always)] pub fn page15_wp(&mut self) -> PAGE15_WP_W { PAGE15_WP_W { w: self } } #[doc = "Bit 16 - Write protection"] #[inline(always)] pub fn page16_wp(&mut self) -> PAGE16_WP_W { PAGE16_WP_W { w: self } } #[doc = "Bit 17 - Write protection"] #[inline(always)] pub fn page17_wp(&mut self) -> PAGE17_WP_W { PAGE17_WP_W { w: self } } #[doc = "Bit 18 - Write protection"] #[inline(always)] pub fn page18_wp(&mut self) -> PAGE18_WP_W { PAGE18_WP_W { w: self } } #[doc = "Bit 19 - Write protection"] #[inline(always)] pub fn page19_wp(&mut self) -> PAGE19_WP_W { PAGE19_WP_W { w: self } } #[doc = "Bit 20 - Write protection"] #[inline(always)] pub fn page20_wp(&mut self) -> PAGE20_WP_W { PAGE20_WP_W { w: self } } #[doc = "Bit 21 - Write protection"] #[inline(always)] pub fn page21_wp(&mut self) -> PAGE21_WP_W { PAGE21_WP_W { w: self } } #[doc = "Bit 22 - Write protection"] #[inline(always)] pub fn page22_wp(&mut self) -> PAGE22_WP_W { PAGE22_WP_W { w: self } } #[doc = "Bit 23 - Write protection"] #[inline(always)] pub fn page23_wp(&mut self) -> PAGE23_WP_W { PAGE23_WP_W { w: self } } #[doc = "Bit 24 - Write protection"] #[inline(always)] pub fn page24_wp(&mut self) -> PAGE24_WP_W { PAGE24_WP_W { w: self } } #[doc = "Bit 25 - Write protection"] #[inline(always)] pub fn page25_wp(&mut self) -> PAGE25_WP_W { PAGE25_WP_W { w: self } } #[doc = "Bit 26 - Write protection"] #[inline(always)] pub fn page26_wp(&mut self) -> PAGE26_WP_W { PAGE26_WP_W { w: self } } #[doc = "Bit 27 - Write protection"] #[inline(always)] pub fn page27_wp(&mut self) -> PAGE27_WP_W { PAGE27_WP_W { w: self } } #[doc = "Bit 28 - Write protection"] #[inline(always)] pub fn page28_wp(&mut self) -> PAGE28_WP_W { PAGE28_WP_W { w: self } } #[doc = "Bit 29 - Write protection"] #[inline(always)] pub fn page29_wp(&mut self) -> PAGE29_WP_W { PAGE29_WP_W { w: self } } #[doc = "Bit 30 - Write protection"] #[inline(always)] pub fn page30_wp(&mut self) -> PAGE30_WP_W { PAGE30_WP_W { w: self } } #[doc = "Bit 31 - Write protection"] #[inline(always)] pub fn page31_wp(&mut self) -> PAGE31_WP_W { PAGE31_WP_W { w: self } } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use fidl::encoding::OutOfLine; use fidl_fuchsia_ledger_cloud::{ CloudProviderRequest, CloudProviderRequestStream, DeviceSetRequest, DeviceSetRequestStream, DeviceSetWatcherProxy, PageCloudRequest, PageCloudRequestStream, PageCloudWatcherProxy, Status, }; use futures::future; use futures::future::LocalFutureObj; use futures::prelude::*; use futures::select; use futures::stream::FuturesUnordered; use std::cell::{Ref, RefCell}; use std::convert::{Into, TryFrom}; use std::rc::Rc; use crate::error::*; use crate::filter::{self, RequestFilter}; use crate::serialization::*; use crate::state::*; use crate::types::*; use crate::utils::{FutureOrEmpty, Signal, SignalWatcher}; /// Shared data accessible by any connection derived from a CloudSession. pub struct CloudSessionShared { pub storage: Rc<RefCell<Cloud>>, filter: RefCell<Box<dyn filter::RequestFilter>>, filter_change_signal: RefCell<Signal>, } impl CloudSessionShared { pub fn new(storage: Rc<RefCell<Cloud>>) -> CloudSessionShared { CloudSessionShared { storage, filter: RefCell::new(Box::new(filter::Always::new(filter::Status::Ok))), filter_change_signal: RefCell::new(Signal::new()), } } pub fn filter(&self) -> Ref<Box<dyn RequestFilter>> { self.filter.borrow() } pub fn set_filter(&self, new_state: Box<dyn RequestFilter>) { self.filter.replace(new_state); self.filter_change_signal.borrow_mut().signal_and_rearm() } /// Return a watcher that is trigerred when the network state changes. pub fn watch_filter(&self) -> SignalWatcher { self.filter_change_signal.borrow().watch() } } /// The state of a DeviceSet connection. struct DeviceSetSession { /// Shared state. shared: Rc<CloudSessionShared>, /// Stream of requests. requests: stream::Fuse<DeviceSetRequestStream>, /// If a watcher is set, contains the future from storage that /// completes when the cloud is erased, and the watcher to signal /// in that case. watcher: Option<(future::Fuse<DeviceSetWatcher>, DeviceSetWatcherProxy)>, /// Signals network state changes. network_watcher: SignalWatcher, } type DeviceSetSessionFuture = LocalFutureObj<'static, ()>; impl DeviceSetSession { fn new(shared: Rc<CloudSessionShared>, requests: DeviceSetRequestStream) -> DeviceSetSession { let network_watcher = shared.watch_filter(); DeviceSetSession { shared, requests: requests.fuse(), watcher: None, network_watcher } } fn handle_request_disconnected(&mut self, req: DeviceSetRequest) -> Result<(), fidl::Error> { match req { DeviceSetRequest::CheckFingerprint { responder, .. } => { responder.send(Status::NetworkError) } DeviceSetRequest::SetFingerprint { responder, .. } => { responder.send(Status::NetworkError) } DeviceSetRequest::Erase { responder } => responder.send(Status::NetworkError), DeviceSetRequest::SetWatcher { responder, watcher, .. } => { responder.send(Status::NetworkError)?; let proxy = watcher.into_proxy()?; proxy.on_error(Status::NetworkError) } } } fn handle_request(&mut self, req: DeviceSetRequest) -> Result<(), fidl::Error> { let mut storage = self.shared.storage.borrow_mut(); let device_set = storage.get_device_set(); match req { DeviceSetRequest::CheckFingerprint { fingerprint, responder } => { responder.send(if device_set.check_fingerprint(&Fingerprint::from(fingerprint)) { Status::Ok } else { Status::NotFound }) } DeviceSetRequest::SetFingerprint { fingerprint, responder } => { device_set.set_fingerprint(Fingerprint::from(fingerprint)); responder.send(Status::Ok) } DeviceSetRequest::Erase { responder } => { device_set.erase(); responder.send(Status::Ok) } DeviceSetRequest::SetWatcher { fingerprint, watcher: watcher_channel, responder } => { let proxy = watcher_channel.into_proxy()?; match device_set.watch(&Fingerprint::from(fingerprint)) { None => { responder.send(Status::NotFound)?; proxy.on_error(Status::NotFound) } Some(fut) => { self.watcher.replace((fut.fuse(), proxy)); responder.send(Status::Ok) } } } } } async fn handle_requests(mut self) -> Result<(), fidl::Error> { loop { select! { _ = &mut self.network_watcher => { self.network_watcher = self.shared.watch_filter(); if self.shared.filter().device_set_watcher_status() == filter::Status::NetworkError { if let Some((_watcher, proxy)) = self.watcher.take() { proxy.on_error(Status::NetworkError)? } } }, req = self.requests.try_next() => match req? { None => return Ok(()), Some(req) => { let connected = self.shared.filter().device_set_request_status(&req); match connected { filter::Status::Ok => self.handle_request(req)?, filter::Status::NetworkError => self.handle_request_disconnected(req)? } } }, _ = FutureOrEmpty(self.watcher.as_mut().map(|(w, _)| w)) => { // self.watcher cannot be None here. let (_, proxy) = self.watcher.take().unwrap(); proxy.on_cloud_erased()? } } } } /// Runs the device set. fn run(self) -> DeviceSetSessionFuture { LocalFutureObj::new(Box::new(self.handle_requests().map(|_| ()))) } } /// A future corresponding to a connection to a PageWatcher. type PageWatcherFuture = LocalFutureObj<'static, ()>; /// The state of a PageCloud connection. struct PageSession { /// Shared data. shared: Rc<CloudSessionShared>, /// Id of the page. page_id: PageId, /// The stream of requests on this connection. requests: stream::Fuse<PageCloudRequestStream>, /// If a watcher is set, the future that completes when the watcher disconnects. watcher: Option<(future::Fuse<PageWatcherFuture>, PageCloudWatcherProxy)>, /// Signals changes in network state. network_watcher: SignalWatcher, } /// The type of the future returned by `PageSession::run`. type PageSessionFuture = LocalFutureObj<'static, ()>; impl PageSession { fn new( shared: Rc<CloudSessionShared>, page_id: PageId, requests: PageCloudRequestStream, ) -> PageSession { let network_watcher = shared.watch_filter(); PageSession { shared, page_id, requests: requests.fuse(), watcher: None, network_watcher } } /// State machine for the page watcher. /// A page watcher connection is at any point: /// - waiting on new commits in storage /// - waiting for the watcher to acknowledge previously sent commits. async fn run_page_watcher( shared: Rc<CloudSessionShared>, page_id: PageId, mut position: Token, proxy: PageCloudWatcherProxy, ) { loop { let fut = shared.storage.borrow_mut().get_page(page_id.clone()).watch(position); if let Some(fut) = fut { fut.await.expect("Cloud state destoyed before PageSession"); } let mut exclusive_storage = shared.storage.borrow_mut(); if let Some((next_position, commits)) = exclusive_storage.get_page(page_id.clone()).get_commits(position) { position = next_position; let mut pack = Commit::serialize_pack(commits); // Release the storage before await-ing. std::mem::drop(exclusive_storage); match proxy.on_new_commits(&mut pack, &mut position.into()).await { Ok(()) => {} Err(_) => return (), // Assume the connection closed. } } } } fn handle_request(&mut self, request: PageCloudRequest) -> Result<(), fidl::Error> { let mut storage = self.shared.storage.borrow_mut(); let page = storage.get_page(self.page_id.clone()); match request { PageCloudRequest::AddCommits { commits, responder } => { match Commit::deserialize_pack(&commits) { Err(e) => responder.send(e.report()), Ok(commits) => responder.send(page.add_commits(commits).report_if_error()), } } PageCloudRequest::GetCommits { min_position_token, responder } => { match Token::try_from(min_position_token) { Err(_) => responder.send(Status::ParseError, None, None), Ok(position) => { let (position, commits) = match page.get_commits(position) { None => (None, Vec::new()), Some((position, commits)) => (Some(position), commits), }; let mut pack = Commit::serialize_pack(commits); // This must live until the end of the call. let mut position = position.map(Token::into); let position = position.as_mut().map(OutOfLine); responder.send(Status::Ok, Some(OutOfLine(&mut pack)), position) } } } PageCloudRequest::AddObject { id, buffer, references: _, responder } => { let mut data = Vec::new(); match read_buffer(&buffer, &mut data) { Err(_) => responder.send(Status::ArgumentError), Ok(()) => responder.send( page.add_object(ObjectId::from(id), Object { data }).report_if_error(), ), } } PageCloudRequest::GetObject { id, responder } => { match page.get_object(&ObjectId(id.clone())) { Err(e) => responder.send(e.report(), None), Ok(obj) => responder .send(Status::Ok, Some(OutOfLine(&mut write_buffer(obj.data.as_slice())))), } } PageCloudRequest::SetWatcher { min_position_token, watcher: watcher_channel, responder, } => match Token::try_from(min_position_token) { Err(_) => responder.send(Status::ParseError), Ok(position) => { let proxy = watcher_channel.into_proxy()?; let watcher = Self::run_page_watcher( Rc::clone(&self.shared), self.page_id.clone(), position, proxy.clone(), ); let watcher = LocalFutureObj::new(Box::new(watcher)).fuse(); self.watcher.replace((watcher, proxy)); responder.send(Status::Ok) } }, PageCloudRequest::GetDiff { commit_id, possible_bases, responder } => { let diff = page.get_diff( CommitId(commit_id), possible_bases.into_iter().map(CommitId).collect(), ); match diff { Err(e) => responder.send(e.report(), None), Ok(diff) => { let mut pack = Diff::serialize_pack(diff); responder.send(Status::Ok, Some(OutOfLine(&mut pack))) } } } } } fn handle_request_disconnected( &mut self, request: PageCloudRequest, ) -> Result<(), fidl::Error> { match request { PageCloudRequest::AddCommits { responder, .. } => responder.send(Status::NetworkError), PageCloudRequest::GetCommits { responder, .. } => { responder.send(Status::NetworkError, None, None) } PageCloudRequest::AddObject { responder, .. } => responder.send(Status::NetworkError), PageCloudRequest::GetObject { responder, .. } => { responder.send(Status::NetworkError, None) } PageCloudRequest::SetWatcher { responder, watcher, .. } => { // Ledger seems to require that we do not send an error here, but on the watcher instead. responder.send(Status::Ok)?; watcher.into_proxy()?.on_error(Status::NetworkError) } PageCloudRequest::GetDiff { responder, .. } => { responder.send(Status::NetworkError, None) } } } async fn handle_requests(mut self) -> Result<(), fidl::Error> { loop { select! { _ = &mut self.network_watcher => { self.network_watcher = self.shared.watch_filter(); if self.shared.filter().page_cloud_watcher_status() == filter::Status::NetworkError { if let Some((_watcher, proxy)) = self.watcher.take() { // Ignoring errors because they should only close the proxy connection. let _ = proxy.on_error(Status::NetworkError); } } }, req = self.requests.try_next() => { match req? { None => return Ok(()), Some(req) => { let connected = self.shared.filter().page_cloud_request_status(&req); match connected { filter::Status::Ok => self.handle_request(req)?, filter::Status::NetworkError => self.handle_request_disconnected(req)? } } } }, () = FutureOrEmpty(self.watcher.as_mut().map(|(w,_)| w)) => { // The watcher has been disconnected. self.watcher.take(); } } } } fn run(self) -> PageSessionFuture { LocalFutureObj::new(Box::new(self.handle_requests().map(|_| ()))) } } /// Holds the state of a PageCloud connection. pub struct CloudSession { /// Shared CloudSession data. shared: Rc<CloudSessionShared>, /// The stream of incoming requests. requests: stream::Fuse<CloudProviderRequestStream>, /// Futures for each active DeviceSet connection. device_sets: FuturesUnordered<DeviceSetSessionFuture>, /// Futures for each active PageCloud connection. pages: FuturesUnordered<PageSessionFuture>, } pub type CloudSessionFuture = LocalFutureObj<'static, ()>; impl CloudSession { pub fn new(state: Rc<CloudSessionShared>, stream: CloudProviderRequestStream) -> CloudSession { CloudSession { shared: state, requests: stream.fuse(), device_sets: FuturesUnordered::new(), pages: FuturesUnordered::new(), } } fn handle_request(&mut self, req: CloudProviderRequest) -> Result<(), fidl::Error> { match req { CloudProviderRequest::GetDeviceSet { device_set: device_set_channel, responder } => { let stream = device_set_channel.into_stream()?; self.device_sets.push(DeviceSetSession::new(Rc::clone(&self.shared), stream).run()); responder.send(Status::Ok) } CloudProviderRequest::GetPageCloud { app_id, page_id, page_cloud, responder } => { let stream = page_cloud.into_stream()?; let page_id = PageId::from(app_id, page_id); self.pages.push(PageSession::new(Rc::clone(&self.shared), page_id, stream).run()); responder.send(Status::Ok) } } } async fn handle_requests(mut self) -> Result<(), fidl::Error> { loop { select! { _ = self.device_sets.next() => {}, _ = self.pages.next() => {}, req = self.requests.try_next() => match req? { Some(req) => self.handle_request(req)?, None => return Ok(()) } } } } pub fn run(self) -> CloudSessionFuture { LocalFutureObj::new(Box::new(self.handle_requests().map(|_| ()))) } } #[cfg(test)] mod tests { use fidl::endpoints::create_endpoints; use fidl_fuchsia_ledger_cloud::{ DeviceSetMarker, DeviceSetWatcherMarker, DeviceSetWatcherRequest, PageCloudMarker, PageCloudWatcherMarker, PageCloudWatcherRequest, Status, }; use fuchsia_async as fasync; use pin_utils::pin_mut; use std::cell::Cell; use std::rc::Rc; use super::*; #[test] fn page_cloud_disconnection() { let mut exec = fasync::Executor::new().unwrap(); let (client, server) = create_endpoints::<PageCloudMarker>().unwrap(); let stream = server.into_stream().unwrap(); let server_state = Rc::new(CloudSessionShared::new(Rc::new(RefCell::new(Cloud::new())))); let server_fut = PageSession::new(Rc::clone(&server_state), PageId(vec![], vec![]), stream).run(); fasync::spawn_local(server_fut); let waiting_on_watcher = Rc::new(Cell::new(false)); let waiting_on_watcher_clone = Rc::clone(&waiting_on_watcher); let proxy = client.into_proxy().unwrap(); let client_fut = async move { let (status, _, _) = proxy.get_commits(None).await.unwrap(); assert_eq!(status, Status::Ok); let (watcher_client, watcher_server) = create_endpoints::<PageCloudWatcherMarker>().unwrap(); let status = proxy.set_watcher(None, watcher_client).await.unwrap(); assert_eq!(status, Status::Ok); // The watcher will stay still until the cloud provider gets disconnected. let mut watcher_stream = watcher_server.into_stream().unwrap(); waiting_on_watcher_clone.set(true); let message = watcher_stream.try_next().await.unwrap(); match message { Some(PageCloudWatcherRequest::OnError { status: Status::NetworkError, .. }) => {} _ => assert!(false), }; waiting_on_watcher_clone.set(false); let message = watcher_stream.try_next().await.unwrap(); assert!(message.is_none()); // Requests return NetworkError. let (status, _, _) = proxy.get_commits(None).await.unwrap(); assert_eq!(status, Status::NetworkError); let (watcher_client, watcher_server) = create_endpoints::<PageCloudWatcherMarker>().unwrap(); let status = proxy.set_watcher(None, watcher_client).await.unwrap(); assert_eq!(status, Status::Ok); // Setting a watcher returns Ok, but the watcher is immediately closed with a network error. let mut watcher_stream = watcher_server.into_stream().unwrap(); let message = watcher_stream.try_next().await.unwrap(); match message { Some(PageCloudWatcherRequest::OnError { status: Status::NetworkError, .. }) => {} _ => assert!(false), }; let message = watcher_stream.try_next().await.unwrap(); assert!(message.is_none()); }; pin_mut!(client_fut); assert!(exec.run_until_stalled(&mut client_fut).is_pending()); assert!(waiting_on_watcher.get()); server_state.set_filter(Box::new(filter::Always::new(filter::Status::NetworkError))); assert!(exec.run_until_stalled(&mut client_fut).is_ready()); } #[test] fn device_set_disconnection() { let mut exec = fasync::Executor::new().unwrap(); let (client, server) = create_endpoints::<DeviceSetMarker>().unwrap(); let stream = server.into_stream().unwrap(); let server_state = Rc::new(CloudSessionShared::new(Rc::new(RefCell::new(Cloud::new())))); let server_fut = DeviceSetSession::new(Rc::clone(&server_state), stream).run(); fasync::spawn_local(server_fut); let waiting_on_watcher = Rc::new(Cell::new(false)); let waiting_on_watcher_clone = Rc::clone(&waiting_on_watcher); let proxy = client.into_proxy().unwrap(); let client_fut = async move { let fingerprint: Vec<u8> = vec![1, 2, 3]; let status = proxy.set_fingerprint(&mut fingerprint.clone().into_iter()).await.unwrap(); assert_eq!(status, Status::Ok); let (watcher_client, watcher_server) = create_endpoints::<DeviceSetWatcherMarker>().unwrap(); let status = proxy .set_watcher(&mut fingerprint.clone().into_iter(), watcher_client) .await .unwrap(); assert_eq!(status, Status::Ok); // The watcher will stay still until the cloud provider gets disconnected. let mut watcher_stream = watcher_server.into_stream().unwrap(); waiting_on_watcher_clone.set(true); let message = watcher_stream.try_next().await.unwrap(); match message { Some(DeviceSetWatcherRequest::OnError { status: Status::NetworkError, .. }) => {} _ => assert!(false), }; waiting_on_watcher_clone.set(false); let message = watcher_stream.try_next().await.unwrap(); assert!(message.is_none()); // Requests return NetworkError. let status = proxy.set_fingerprint(&mut fingerprint.clone().into_iter()).await.unwrap(); assert_eq!(status, Status::NetworkError); let (watcher_client, watcher_server) = create_endpoints::<DeviceSetWatcherMarker>().unwrap(); let status = proxy .set_watcher(&mut fingerprint.clone().into_iter(), watcher_client) .await .unwrap(); assert_eq!(status, Status::NetworkError); // The watcher also gets NetworkError. let mut watcher_stream = watcher_server.into_stream().unwrap(); let message = watcher_stream.try_next().await.unwrap(); match message { Some(DeviceSetWatcherRequest::OnError { status: Status::NetworkError, .. }) => {} _ => assert!(false), }; let message = watcher_stream.try_next().await.unwrap(); assert!(message.is_none()); }; pin_mut!(client_fut); assert!(exec.run_until_stalled(&mut client_fut).is_pending()); assert!(waiting_on_watcher.get()); server_state.set_filter(Box::new(filter::Always::new(filter::Status::NetworkError))); assert!(exec.run_until_stalled(&mut client_fut).is_ready()); } /// Tests that error injection works as expected. #[test] fn error_injection() { let mut exec = fasync::Executor::new().unwrap(); let (client, server) = create_endpoints::<PageCloudMarker>().unwrap(); let stream = server.into_stream().unwrap(); let server_state = Rc::new(CloudSessionShared::new(Rc::new(RefCell::new(Cloud::new())))); let server_fut = PageSession::new(Rc::clone(&server_state), PageId(vec![], vec![]), stream).run(); server_state.set_filter(Box::new(filter::Flaky::new(2))); fasync::spawn_local(server_fut); let proxy = client.into_proxy().unwrap(); let client_fut = async move { // Query A fails twice. let (status, _, _) = proxy.get_commits(None).await.unwrap(); assert_eq!(status, Status::NetworkError); let (status, _, _) = proxy.get_commits(None).await.unwrap(); assert_eq!(status, Status::NetworkError); // Query B fails. let mut token = Token::into(Token(4)); let (status, _, _) = proxy.get_commits(Some(OutOfLine(&mut token))).await.unwrap(); assert_eq!(status, Status::NetworkError); // Query A succeeds on the third try. let (status, _, _) = proxy.get_commits(None).await.unwrap(); assert_eq!(status, Status::Ok); // Query A's count is reset and it fails again. let (status, _, _) = proxy.get_commits(None).await.unwrap(); assert_eq!(status, Status::NetworkError); let (status, _, _) = proxy.get_commits(None).await.unwrap(); assert_eq!(status, Status::NetworkError); let (status, _, _) = proxy.get_commits(None).await.unwrap(); assert_eq!(status, Status::Ok); }; pin_mut!(client_fut); assert!(exec.run_until_stalled(&mut client_fut).is_ready()); } }
use std::cmp::{max, min}; use std::collections::{HashMap, HashSet}; use itertools::Itertools; use whiteread::parse_line; const ten97: usize = 1000000007; fn alphabet2idx(c: char) -> usize { if c.is_ascii_lowercase() { c as u8 as usize - 'a' as u8 as usize } else if c.is_ascii_uppercase() { c as u8 as usize - 'A' as u8 as usize } else { panic!("wtf") } } fn main() { let n: usize = parse_line().unwrap(); let mut aa: Vec<usize> = parse_line().unwrap(); let q: usize = parse_line().unwrap(); let mut bb: Vec<usize> = vec![]; for _ in 0..q { bb.push(parse_line().unwrap()); } aa.sort(); for b in bb { let bi = aa.lower_bound(b); let mut ans = 0; if bi == n { ans = (aa[n - 1] as isize - b as isize).abs(); } else if bi == 0 { ans = (aa[bi] as isize - b as isize).abs(); } else { ans += min( (aa[bi] as isize - b as isize).abs(), (aa[bi - 1] as isize - b as isize).abs(), ); } println!("{}", ans); } } trait LUBound<T> { fn lower_bound(&self, value: T) -> usize where T: PartialOrd; fn upper_bound(&self, value: T) -> usize where T: PartialOrd; } impl<T> LUBound<T> for Vec<T> { fn lower_bound(&self, value: T) -> usize where T: PartialOrd, { let mut left = 0; let mut right = self.len(); while left < right { let pivot = (right + left) / 2; if value <= self[pivot] { right = pivot; } else { left = pivot + 1; } } return left; } fn upper_bound(&self, value: T) -> usize where T: PartialOrd, { let mut left = 0; let mut right = self.len(); while left < right { let pivot = (right + left) / 2; if value < self[pivot] { right = pivot; } else { left = pivot + 1; } } return left; } } #[cfg(test)] mod tests { use super::*; #[test] fn lower_bound() { let cases = vec![( vec![0, 1, 1, 1, 2, 2, 3, 5], (-1..=6), vec![0, 0, 1, 4, 6, 7, 7, 8], )]; for case in cases { for (value, expected) in case.1.zip(case.2.into_iter()) { assert_eq!(case.0.lower_bound(value), expected); } } } #[test] fn upper_bound() { let cases = vec![( vec![0, 1, 1, 1, 2, 2, 3, 5], (-1..=6), vec![0, 1, 4, 6, 7, 7, 8, 8], )]; for case in cases { for (value, expected) in case.1.zip(case.2.into_iter()) { assert_eq!(case.0.upper_bound(value), expected); } } } }
use super::tree::Node; /// Iterator type for a binary tree. /// This is a generator that progresses through an in-order traversal. pub struct NodeIterator<T> { branch_stack: Vec<Node<T>>, } impl<T> NodeIterator<T> where Node<T>: Clone, { /// Given a reference to a node, consume it and return an iterator over it /// and any of its branches in an in-order traversal. //TODO: Vec::with_capacity() fn new(root: Node<T>) -> Self { let mut iter = NodeIterator { branch_stack: vec![], }; iter.add_left_branches(root); iter } /// Given a node, traverse along its left branches and add all right /// branches to the `branch_stack` field. /// Set the current node to the left-most child. fn add_left_branches(&mut self, mut root: Node<T>) { self.branch_stack.push(root.clone()); while let Node { left: Some(left_branch), .. } = root { root = *left_branch; self.branch_stack.push(root.clone()); } } } impl<T> Iterator for NodeIterator<T> where Node<T>: Clone, { type Item = T; fn next(&mut self) -> Option<T> { if let Some(root) = self.branch_stack.pop() { if let Node { right: Some(right_branch), .. } = root { self.add_left_branches(*right_branch); } let Node { value: result, .. } = root; return Some(result); } None } } impl<T> IntoIterator for Node<T> where Node<T>: Clone, { type Item = T; type IntoIter = NodeIterator<T>; fn into_iter(self) -> NodeIterator<T> { NodeIterator::new(self) } } #[cfg(test)] mod test { use setup_test; #[test] fn test_iter() { setup_test!(,balanced_tree_base,,vec_base); let vec_test = balanced_tree_base.into_iter().collect::<Vec<i32>>(); assert_eq!(vec_base, vec_test); } }
use cw::Range; use dict::{Dict, PatternIter}; /// An iterator over all possibilities to fill one of the given ranges with a word from a set of /// dictionaries. pub struct WordRangeIter<'a> { ranges: Vec<(Range, Vec<char>)>, dicts: &'a [Dict], range_i: usize, dict_i: usize, pi: Option<PatternIter<'a>>, } impl<'a> WordRangeIter<'a> { pub fn new(ranges: Vec<(Range, Vec<char>)>, dicts: &'a [Dict]) -> WordRangeIter<'a> { WordRangeIter { ranges: ranges, dicts: dicts, range_i: 0, dict_i: 0, pi: None, } } #[inline] fn get_word(&mut self) -> Option<Vec<char>> { match self.pi { None => None, Some(ref mut iter) => iter.next().cloned(), } } fn advance(&mut self) -> bool { if self.pi.is_some() { self.range_i += 1; if self.range_i >= self.ranges.len() { self.range_i = 0; self.dict_i += 1; } } if let Some(&(_, ref pattern)) = self.ranges.get(self.range_i) { self.pi = self.dicts .get(self.dict_i) .map(|dict| dict.matching_words(pattern)); self.pi.is_some() } else { false } } } impl<'a> Iterator for WordRangeIter<'a> { type Item = (Range, Vec<char>); fn next(&mut self) -> Option<(Range, Vec<char>)> { let mut oword = self.get_word(); while oword.is_none() && self.advance() { oword = self.get_word(); } oword.map(|word| { let (range, _) = self.ranges[self.range_i]; (range, word) }) } } #[cfg(test)] mod tests { use super::*; use cw::{Dir, Point, Range}; use dict::Dict; use test_util::*; #[test] fn test_range_iter() { let point = Point::new(0, 0); let ranges = vec![(Range { point: point, dir: Dir::Right, len: 6, }, str_to_cvec("######")), (Range { point: point, dir: Dir::Right, len: 3, }, str_to_cvec("###")), (Range { point: point, dir: Dir::Right, len: 2, }, str_to_cvec("##"))]; let dicts = [Dict::new(strs_to_cvecs(&["FAV", "TOOLONG"])), Dict::new(strs_to_cvecs(&["YO", "FOO", "FOOBAR"]))]; let mut iter = WordRangeIter::new(ranges.clone(), &dicts); assert_eq!(Some((ranges[1].0, str_to_cvec("FAV"))), iter.next()); assert_eq!(Some((ranges[0].0, str_to_cvec("FOOBAR"))), iter.next()); assert_eq!(Some((ranges[1].0, str_to_cvec("FOO"))), iter.next()); assert_eq!(Some((ranges[2].0, str_to_cvec("YO"))), iter.next()); } }
use std::fmt; #[repr(transparent)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Mac([u8; 16]); impl Mac { pub fn get_raw(&self) -> &[u8; 16] { &self.0 } } impl From<[u8; 16]> for Mac { fn from(x: [u8; 16]) -> Self { Self(x) } } impl fmt::Display for Mac { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, &x) in self.0.iter().take(6).enumerate() { if i > 0 { write!(f, ":{:02X}", x)?; } else { write!(f, "{:02X}", x)?; } } Ok(()) } } // Combined hardware address and DHCP client ID #[derive(Debug, Clone, PartialEq, Eq)] pub struct ClientId { pub mac: Mac, pub ext: Vec<u8>, } impl fmt::Display for ClientId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.ext.is_empty() { self.mac.fmt(f) } else { write!(f, "{}\\", self.mac)?; for (_i, &x) in self.ext.iter().enumerate() { write!(f, "{:02X}", x)?; } Ok(()) } } }
extern crate clap; extern crate json; use self::clap::{Arg, App}; use std::fs; pub mod treenode; pub fn load_json_tests() -> (json::JsonValue, i32) { let matches = App::new("json test loader") .version("0.0.1") .author("Jean-Christophe Pince <jcpince@gmail.com>") .about("Load JSON descriptions of algorithms unit tests.") .arg(Arg::with_name("json_unittests") .short('j') .long("json_unittests") .takes_value(true) .required(true) .help("A json unit tests file")) .arg(Arg::with_name("index") .short('i') .long("index") .takes_value(true) .help("Run the test specified at index")) .get_matches(); let json_unittests = matches.value_of("json_unittests").unwrap(); println!("The json unit tests file passed is: {}", json_unittests); let test_idx : i32 = matches.value_of("index").unwrap_or("-1").parse().unwrap(); let data = fs::read_to_string(json_unittests).expect( "Unable to read json unit tests file."); match json::parse(&data) { Ok(json_dict) => { return (json_dict["tests"].clone(), test_idx); } Err(error) => panic!("Problem parsong the json data in {}: {:?}", json_unittests, error), }; }
// 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. #![feature(write_all_vectored)] mod cache; mod metrics; mod providers; mod read; pub use cache::CacheAccessor; pub use cache::Named; pub use cache::NamedCache; pub use providers::DiskCacheError; pub use providers::DiskCacheKey; pub use providers::DiskCacheResult; pub use providers::InMemoryBytesCacheHolder; pub use providers::InMemoryCacheBuilder; pub use providers::InMemoryItemCacheHolder; pub use providers::LruDiskCache; pub use providers::LruDiskCacheBuilder; pub use providers::LruDiskCacheHolder; pub use providers::TableDataCache; pub use providers::TableDataCacheBuilder; pub use providers::TableDataCacheKey; pub use read::CacheKey; pub use read::CachedReader; pub use read::InMemoryBytesCacheReader; pub use read::InMemoryItemCacheReader; pub use read::LoadParams; pub use read::Loader; pub use self::metrics::*;
use ecs::*; use engine::*; use std::cell::RefCell; use std::fmt::Debug; use std::ops::{Deref, DerefMut}; #[derive(Debug, Clone)] pub struct SingletonComponentManager<T> where T: Component<Manager=SingletonComponentManager<T>> + Debug + Clone + Default, T::Message: Message<Target=T>, { data: T, messages: RefCell<Vec<T::Message>>, } impl<T> SingletonComponentManager<T> where T: Component<Manager=SingletonComponentManager<T>> + Debug + Clone + Default, T::Message: Message<Target=T>, { pub fn new(data: T) -> SingletonComponentManager<T> { SingletonComponentManager { data: data, messages: RefCell::new(Vec::new()), } } pub fn send_message<U: Into<T::Message>>(&self, message: U) { self.messages.borrow_mut().push(message.into()); } } impl<T> Deref for SingletonComponentManager<T> where T: Component<Manager=SingletonComponentManager<T>> + Debug + Clone + Default, T::Message: Message<Target=T>, { type Target = T; fn deref(&self) -> &T { &self.data } } impl<T> DerefMut for SingletonComponentManager<T> where T: Component<Manager=SingletonComponentManager<T>> + Debug + Clone + Default, T::Message: Message<Target=T>, { fn deref_mut(&mut self) -> &mut T { &mut self.data } } impl<T, U> ComponentManagerBase for SingletonComponentManager<T> where T: Component<Manager=SingletonComponentManager<T>, Message=U> + Debug + Clone + Default, U: Message<Target=T>, { fn update(&mut self) { let mut messages = self.messages.borrow_mut(); for message in messages.drain(..) { message.apply(&mut self.data); } } } impl<T, U> ComponentManager for SingletonComponentManager<T> where T: Component<Manager=SingletonComponentManager<T>, Message=U> + Debug + Clone + Default, U: Message<Target=T>, { type Component = T; fn register(builder: &mut EngineBuilder) { builder.register_manager(SingletonComponentManager::new(T::default())); } fn get(&self, _entity: Entity) -> Option<&Self::Component> { panic!("Singleton components do not need to be retreived, they can be derefenced from the manager"); } fn destroy(&self, _: Entity) {} } // ======================================= // SINGLETON COMPONENT MANAGER WITH UPDATE // ======================================= // TODO: Having a separate type for this won't be necessary once specialization is implemented. #[derive(Debug, Clone)] pub struct SingletonComponentUpdateManager<T> where T: Component<Manager=SingletonComponentUpdateManager<T>> + ComponentUpdate + Debug + Clone + Default, T::Message: Message<Target=T>, { data: T, messages: RefCell<Vec<T::Message>>, } impl<T> SingletonComponentUpdateManager<T> where T: Component<Manager=SingletonComponentUpdateManager<T>> + ComponentUpdate + Debug + Clone + Default, T::Message: Message<Target=T>, { pub fn new(data: T) -> SingletonComponentUpdateManager<T> { SingletonComponentUpdateManager { data: data, messages: RefCell::new(Vec::new()), } } pub fn send_message<U: Into<T::Message>>(&self, message: U) { self.messages.borrow_mut().push(message.into()); } } impl<T> Deref for SingletonComponentUpdateManager<T> where T: Component<Manager=SingletonComponentUpdateManager<T>> + ComponentUpdate + Debug + Clone + Default, T::Message: Message<Target=T>, { type Target = T; fn deref(&self) -> &T { &self.data } } impl<T> DerefMut for SingletonComponentUpdateManager<T> where T: Component<Manager=SingletonComponentUpdateManager<T>> + ComponentUpdate + Debug + Clone + Default, T::Message: Message<Target=T>, { fn deref_mut(&mut self) -> &mut T { &mut self.data } } impl<T, U> ComponentManagerBase for SingletonComponentUpdateManager<T> where T: Component<Manager=SingletonComponentUpdateManager<T>, Message=U> + ComponentUpdate + Debug + Clone + Default, U: Message<Target=T>, { fn update(&mut self) { let mut messages = self.messages.borrow_mut(); for message in messages.drain(..) { message.apply(&mut self.data); } self.data.update(); } } impl<T, U> ComponentManager for SingletonComponentUpdateManager<T> where T: Component<Manager=SingletonComponentUpdateManager<T>, Message=U> + ComponentUpdate + Debug + Clone + Default, U: Message<Target=T>, { type Component = T; fn register(builder: &mut EngineBuilder) { builder.register_manager(SingletonComponentUpdateManager::new(T::default())); } fn get(&self, _entity: Entity) -> Option<&Self::Component> { panic!("Singleton components do not need to be retreived, they can be derefenced from the manager"); } fn destroy(&self, _: Entity) {} }
pub struct Solution; impl Solution { pub fn largest_number(nums: Vec<i32>) -> String { let mut bytes_vec = nums .iter() .map(|num| num.to_string().into_bytes()) .collect::<Vec<Vec<u8>>>(); bytes_vec.sort_by(new_cmp); if bytes_vec[0] == [b'0'] { return "0".to_string(); } let mut res = Vec::new(); for bytes in bytes_vec { res.extend_from_slice(&bytes); } String::from_utf8(res).unwrap() } } use std::cmp::Ordering; fn new_cmp(x: &Vec<u8>, y: &Vec<u8>) -> Ordering { if x.len() == y.len() { y.cmp(x) } else if x.len() < y.len() { let x: &[u8] = &*x; let y: &[u8] = &*y; match &y[..x.len()].cmp(x) { Ordering::Less => Ordering::Less, Ordering::Equal => match y[x.len()..].cmp(&y[..(y.len() - x.len())]) { Ordering::Less => Ordering::Less, Ordering::Equal => x.cmp(&y[(y.len() - x.len())..]), Ordering::Greater => Ordering::Greater, }, Ordering::Greater => Ordering::Greater, } } else { Ordering::Equal.cmp(&new_cmp(y, x)) } } #[test] fn test0179() { fn case(nums: Vec<i32>, want: &str) { assert_eq!(Solution::largest_number(nums), want); } case(vec![10, 2], "210"); case(vec![3, 30, 34, 5, 9], "9534330"); case(vec![0, 0], "0"); }
/// 页大小 pub const PAGE_SIZE: usize = 0x1000; /// DMA 分配的最大轮询次数 pub const MAX_DMA_ALLOC_COUNT: u32 = 0x10; /// 虚拟队列大小 pub const VIRT_QUEUE_SIZE: usize = 32; /// 块大小 pub const BLOCK_SIZE: usize = 512;
use std::ffi::{CStr, CString, IntoStringError}; use std::fmt::{self, Display, Formatter}; use std::io; use std::mem::{self, MaybeUninit}; use std::os::raw::{c_int, c_void}; use std::path::PathBuf; /// Error during working directory retrieval. #[derive(Debug)] pub enum Error { Io(io::Error), /// Error converting into utf8 string. IntoString(IntoStringError), /// Expected return size didn't match libproc's. InvalidSize, } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::InvalidSize => None, Error::Io(err) => err.source(), Error::IntoString(err) => err.source(), } } } impl Display for Error { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Error::InvalidSize => write!(f, "Invalid proc_pidinfo return size"), Error::Io(err) => write!(f, "Error getting current working directory: {}", err), Error::IntoString(err) => { write!(f, "Error when parsing current working directory: {}", err) }, } } } impl From<io::Error> for Error { fn from(val: io::Error) -> Self { Error::Io(val) } } impl From<IntoStringError> for Error { fn from(val: IntoStringError) -> Self { Error::IntoString(val) } } pub fn cwd(pid: c_int) -> Result<PathBuf, Error> { let mut info = MaybeUninit::<sys::proc_vnodepathinfo>::uninit(); let info_ptr = info.as_mut_ptr() as *mut c_void; let size = mem::size_of::<sys::proc_vnodepathinfo>() as c_int; let c_str = unsafe { let pidinfo_size = sys::proc_pidinfo(pid, sys::PROC_PIDVNODEPATHINFO, 0, info_ptr, size); match pidinfo_size { c if c < 0 => return Err(io::Error::last_os_error().into()), s if s != size => return Err(Error::InvalidSize), _ => CStr::from_ptr(info.assume_init().pvi_cdir.vip_path.as_ptr()), } }; Ok(CString::from(c_str).into_string().map(PathBuf::from)?) } /// Bindings for libproc. #[allow(non_camel_case_types)] mod sys { use std::os::raw::{c_char, c_int, c_longlong, c_void}; pub const PROC_PIDVNODEPATHINFO: c_int = 9; type gid_t = c_int; type off_t = c_longlong; type uid_t = c_int; type fsid_t = fsid; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct fsid { pub val: [i32; 2usize], } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct vinfo_stat { pub vst_dev: u32, pub vst_mode: u16, pub vst_nlink: u16, pub vst_ino: u64, pub vst_uid: uid_t, pub vst_gid: gid_t, pub vst_atime: i64, pub vst_atimensec: i64, pub vst_mtime: i64, pub vst_mtimensec: i64, pub vst_ctime: i64, pub vst_ctimensec: i64, pub vst_birthtime: i64, pub vst_birthtimensec: i64, pub vst_size: off_t, pub vst_blocks: i64, pub vst_blksize: i32, pub vst_flags: u32, pub vst_gen: u32, pub vst_rdev: u32, pub vst_qspare: [i64; 2usize], } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct vnode_info { pub vi_stat: vinfo_stat, pub vi_type: c_int, pub vi_pad: c_int, pub vi_fsid: fsid_t, } #[repr(C)] #[derive(Copy, Clone)] pub struct vnode_info_path { pub vip_vi: vnode_info, pub vip_path: [c_char; 1024usize], } #[repr(C)] #[derive(Copy, Clone)] pub struct proc_vnodepathinfo { pub pvi_cdir: vnode_info_path, pub pvi_rdir: vnode_info_path, } extern "C" { pub fn proc_pidinfo( pid: c_int, flavor: c_int, arg: u64, buffer: *mut c_void, buffersize: c_int, ) -> c_int; } } #[cfg(test)] mod tests { use super::*; use std::{env, process}; #[test] fn cwd_matches_current_dir() { assert_eq!(cwd(process::id() as i32).ok(), env::current_dir().ok()); } }
// Copyright © 2016-2017 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use std::convert::{From, Into}; use rabble::{self, Pid, CorrelationId, Envelope}; use msg::Msg; use NamespaceMsg; use vr::vr_fsm::{Transition, VrState, State}; use vr::vr_ctx::VrCtx; use vr::vr_msg::{VrMsg, EpochStarted, StartEpoch}; use vr::states::Shutdown; use vr::states::utils::QuorumTracker; /// The state where a replica is in the process of shutting down /// /// The replica received a reconfiguration request in its log and it is not in the new /// configuration. /// The replica is waiting for a quorum of EpochStarted messages from the new config so that it can /// shut down. state!(Leaving { ctx: VrCtx, msgs: QuorumTracker<EpochStarted> }); impl Transition for Leaving { fn handle(mut self, msg: VrMsg, from: Pid, _: CorrelationId, output: &mut Vec<Envelope<Msg>>) -> VrState { match msg { VrMsg::EpochStarted(msg) => { if msg.epoch > self.ctx.epoch { // There has already been *another* reconfiguration, // so just transition to shutdown state return Shutdown::enter(self.ctx); } self.msgs.insert(from, msg); if self.msgs.has_quorum() { let ns_msg = NamespaceMsg::Stop(self.ctx.pid.clone()); output.push(self.ctx.namespace_mgr_envelope(ns_msg)); return Shutdown::enter(self.ctx); } self.into() }, VrMsg::Tick => { if self.msgs.is_expired() { self.broadcast_start_epoch(output); } self.into() }, _ => self.into() } } } impl Leaving { pub fn leave(ctx: VrCtx) -> VrState { let quorum = ctx.quorum; Leaving { msgs: QuorumTracker::new(quorum, ctx.idle_timeout_ms), ctx: ctx }.into() } pub fn broadcast_start_epoch(&self, output: &mut Vec<Envelope<Msg>>) { let msg = self.start_epoch_msg(); let cid = CorrelationId::pid(self.ctx.pid.clone()); self.ctx.broadcast(msg, cid, output); } fn start_epoch_msg(&self) -> rabble::Msg<Msg> { StartEpoch { epoch: self.ctx.epoch, op: self.ctx.op, old_config: self.ctx.old_config.clone(), new_config: self.ctx.new_config.clone() }.into() } }
extern crate serde; use serde::{Serialize, Deserialize}; extern crate bincode; use bincode::{serialize, deserialize}; use crate::btree::key_value::{KeyType, ValueType}; use std::error::Error; use std::marker::PhantomData; use std::fs::File; use std::io::Write; use std::io::Read; use std::io::SeekFrom; use std::io::prelude::*; use std::fs::OpenOptions; use std::cmp::Ordering; const DB_NAME: &'static str = "chicchaidb"; const VERSION: u8 = 0x01; // FIXME: const BLOCK_SIZE: usize = 4096; /// /// file layout /// /// + 0 -----------------------------------------------+ /// metadata /// + 4095 --------------------------------------------+ /// + 4096 --------------------------------------------+ /// ...data /// +--------------------------------------------------+ /// struct BTree<'d, K: KeyType<'d>, V: ValueType<'d>> { root: Node<'d, K, V>, count: usize, file: File, } impl <'d, K: KeyType<'d>, V: ValueType<'d>> BTree<'d, K, V> { fn new(file_path: String) -> Result<BTree<'d, K, V>, Box<Error>> { //FIXME: not fix width. let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .open(file_path)?; let n = Node::<K, V>::new(&mut file, NodeID(1), 3, Vec::<Elm<'d, K, V>>::new())?; Ok(BTree { root: n, count: 1, file, }) } fn insert(&mut self, key: K, value: V) -> Result<(), Box<Error>> { let elm = Elm::<K, V>::new(key, value, Edge::Empty, Edge::Empty); let op_e = self.root.insert(&mut self.file, &mut self.count, elm)?; match op_e { None => Ok(()), Some(e) => { let elms = Vec::<Elm<'d, K, V>>::new(); elms.push(e); self.count += 1; let n = Node::<K, V>::new(&mut self.file, NodeID(self.count), 3, elms)?; self.root = n; Ok(()) }, } } } #[derive(Copy, Clone, Serialize, Deserialize)] struct NodeID(usize); impl NodeID { fn block_position(&self) -> u64 { let NodeID(u) = self; (u * BLOCK_SIZE) as u64 } } #[derive(Serialize, Deserialize)] struct Node<'d, K: KeyType<'d>, V: ValueType<'d>> { id: NodeID, width: usize, elms: Vec<Elm<'d, K, V>>, _key_marker: PhantomData<&'d K>, _value_marker: PhantomData<&'d V>, } impl <'d, K: KeyType<'d>, V: ValueType<'d>> Node<'d, K, V> { fn new(file: &mut File, id: NodeID, width: usize, elms: Vec<Elm<'d, K, V>>) -> Result<Node<'d, K, V>, Box<Error>> { let n = Node { id, width, elms, _key_marker: PhantomData, _value_marker: PhantomData, }; Node::save(file, &n)?; Ok(n) } fn insert(&mut self, file: &mut File, count: &mut usize, elm: Elm<'d, K, V>) -> Result<Option<Elm<'d, K, V>>, Box<Error>> { let (edge, index) = self.search(&elm); match edge { Edge::Empty => { self.elms.push(elm); self.elms.sort(); return Ok(self.balance(file, count)?); }, Edge::NotEmpty(id) => { let mut node = Node::<'d, K, V>::open(file, id)?; match node.insert(file, count, elm) { Ok(op_e) => { match op_e { None => Ok(None), Some(e) => { self.elms.insert(index, e); if let Some(left_e) = self.elms.iter_mut().nth(index-1) { left_e.right = self.elms[index].left; } if let Some(right_e) = self.elms.iter_mut().nth(index+1) { right_e.left = self.elms[index].right; } return Ok(self.balance(file, count)?); }, } } } }, } } fn balance(&mut self, file: &mut File, count: &mut usize) -> Result<Option<Elm<'d, K, V>>, Box<Error>>{ if self.elms.len() == self.width { let m = self.elms.len() / 2; let mut elm = self.elms.remove(m); let left_elms = self.elms.split_off(m); *count += 1; let mut left = Node::<'d, K, V>::new(file, NodeID(*count), self.width, left_elms)?; elm.left = Edge::NotEmpty(left.id); elm.right = Edge::NotEmpty(self.id); return Ok(Some(elm)); } Ok(None) } fn save(file: &mut File, node: &Node<'d, K, V>) -> Result<(), Box<Error>> { let mut buff = serialize(&node)?; if buff.len() > BLOCK_SIZE { return Err(From::from("invalid node size")); } else { let diff = BLOCK_SIZE - buff.len(); buff.extend(vec![0; diff]); } file.seek(SeekFrom::Start(node.id.block_position())); file.write_all(&buff)?; Ok(()) } fn open(file: &mut File, id: NodeID) -> Result<Node<'d, K, V>, Box<Error>> { let mut buff = vec![0; BLOCK_SIZE]; file.seek(SeekFrom::Start(id.block_position())); file.read_exact(&mut buff)?; match deserialize(&buff) { Ok(v) => Ok(v), Err(e) => Err(From::from(e)), } } fn search(&self, elm: &Elm<'d, K, V>) -> (Edge, usize) { for i in 0..self.elms.len() { let e = &self.elms[i]; if elm < e { return (e.left, i); } } let Some(e) = self.elms.last(); (e.right, self.elms.len() - 1) } } #[derive(Serialize, Deserialize, Copy, Clone)] enum Edge { Empty, NotEmpty(NodeID), } #[derive(Serialize, Deserialize, Clone)] struct Elm<'d, K: KeyType<'d>, V: ValueType<'d>> { key: &'d K, value: &'d V, right: Edge, left: Edge, } impl <'d, K: KeyType<'d>, V: ValueType<'d>> Elm<'d, K, V> { fn new(key: K, value: V, right: Edge, left: Edge) -> Elm<'d, K, V> { Elm { key, value, right, left, } } } impl <'d, K: KeyType<'d>, V: ValueType<'d>> Ord for Elm<'d, K, V> { fn cmp(&self, other: &Elm<'d, K, V>) -> Ordering { self.key.cmp(&other.key) } } impl <'d, K: KeyType<'d>, V: ValueType<'d>> PartialOrd for Elm<'d, K, V> { fn partial_cmp(&self, other: &Elm<'d, K, V>) -> Option<Ordering> { Some(self.cmp(other)) } } impl <'d, K: KeyType<'d>, V: ValueType<'d>> PartialEq for Elm<'d, K, V> { fn eq(&self, other: &Elm<'d, K, V>) -> bool { self.key == other.key } } impl <'d, K: KeyType<'d>, V: ValueType<'d>> Eq for Elm<'d, K, V> {} pub struct DiskBtree<'d, K: KeyType<'d>, V: ValueType<'d>> { file: File, key_size: usize, value_size: usize, _key_marker: PhantomData<&'d K>, _value_marker: PhantomData<&'d V>, } #[derive(Serialize, Deserialize)] struct MetaData { name: String, version: u8, } impl<'d, K: KeyType<'d>, V: ValueType<'d>> DiskBtree<'d, K, V> { pub fn new( file_path: &String, key_size: usize, value_size: usize, ) -> Result<DiskBtree<'d, K, V>, Box<Error>> { let file = OpenOptions::new() .read(true) .write(true) .create(true) .open(file_path)?; let mut b = DiskBtree { file, key_size, value_size, _key_marker: PhantomData, _value_marker: PhantomData, }; let is_new = match b.is_new() { Ok(v) => v, Err(e) => { return Err(e); } }; let meta= b.metadata()?; println!("db name: {}", meta.name); if is_new { if let Err(e) = b.initialize() { return Err(e); } println!("initializing success!") } Ok(b) } fn is_new(&self) -> Result<bool, Box<Error>> { let l = self.file.metadata()?; if l.len() == 0 { return Ok(true); } Ok(false) } fn initialize(&mut self) -> Result<(), Box<Error>> { let m = MetaData { name: DB_NAME.to_string(), version: VERSION, }; let mut buff = serialize(&m)?; if buff.len() > BLOCK_SIZE { return Err(From::from("invalid metadata")); } else { let diff = BLOCK_SIZE - buff.len(); buff.extend(vec![0; diff]); } match self.file.write_all(&buff) { Ok(_) => Ok(()), Err(e) => Err(From::from(e)), } } fn metadata(&mut self) -> Result<MetaData, Box<Error>> { let mut buff = vec![0; BLOCK_SIZE]; self.file.seek(SeekFrom::Start(0)); match self.file.read_exact(&mut buff) { Ok(_) => { match deserialize(&buff) { Ok(v) => Ok(v), Err(e) => Err(e), } }, Err(e) => { Err(Box::new(e)) } } } fn mapping(&self) -> Result<(), Box<Error>> { Ok(()) } }
use actix_web::{guard, web, App, HttpResponse, HttpServer, Result}; use async_graphql::http::{playground_source, GraphQLPlaygroundConfig}; use async_graphql::{EmptyMutation, EmptySubscription, Schema}; use async_graphql_actix_web::{Request, Response}; use async_graphql::extensions::ApolloTracing; use async_graphql::*; use actix_web::dev::Server; struct Query; type LocalSchema = Schema<Query, EmptyMutation, EmptySubscription>; #[Object] impl Query { async fn parameters(&self, context: &Context<'_>) -> Vec<MinizincParameter> { context.data_unchecked::<MinizincParameters>().list.clone() } } #[derive(SimpleObject, Clone, Debug, PartialEq, Eq)] pub struct MinizincBooleanParameter { pub name: String, pub value: Option<bool> } #[derive(SimpleObject, Clone, Debug, PartialEq, Eq)] pub struct MinizincIntegerParameter { pub name: String, pub value: Option<u32> // TODO: guessing a minizinc int is u32 } #[derive(SimpleObject, Clone, Debug, PartialEq)] pub struct MinizincFloatParameter { pub name: String, pub value: Option<f32> // TODO: guessing a minizinc int is f32 } #[derive(SimpleObject, Clone, Debug, PartialEq, Eq)] pub struct MinizincStringParameter { pub name: String, pub value: Option<String> } #[derive(Union, Clone, Debug, PartialEq)] pub enum MinizincParameter { Boolean(MinizincBooleanParameter), Integer(MinizincIntegerParameter), Float(MinizincFloatParameter), String(MinizincStringParameter) } #[derive(Clone, Debug, PartialEq)] pub struct MinizincParameters { pub list: Vec<MinizincParameter> } async fn index(schema: web::Data<LocalSchema>, req: Request) -> Response { schema.execute(req.into_inner()).await.into() } async fn index_playground() -> Result<HttpResponse> { Ok(HttpResponse::Ok() .content_type("text/html; charset=utf-8") .body(playground_source( GraphQLPlaygroundConfig::new("/").subscription_endpoint("/"), ))) } pub fn graphql_server(parameters: &MinizincParameters) -> Result<Server, std::io::Error> { let schema = Schema::build(Query, EmptyMutation, EmptySubscription) .data(parameters.clone()) .extension(ApolloTracing) .finish(); println!("{}", &schema.sdl()); println!("Playground: http://localhost:8080"); Ok(HttpServer::new(move || { App::new() .data(schema.clone()) .service(web::resource("/").guard(guard::Post()).to(index)) .service(web::resource("/").guard(guard::Get()).to(index_playground)) }) .bind("0.0.0.0:8080")? .run()) }
// Copyright 2019 // by Centrality Investments Ltd. // and Parity Technologies (UK) Ltd. // // 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. #![cfg_attr(not(feature = "std"), no_std)] //! Efficient and compact serialization of Rust types. //! //! This library provides structures to easily retrieve compile-time type information //! at runtime and also to serialize this information in a compact form. //! //! # Registry //! //! At the heart of its functionality is the `Registry` that acts as cache for //! known strings and types in order to efficiently deduplicate them and thus compactify //! the overall serialization. //! //! # Type Information //! //! Information about types is split into two halfs. //! //! 1. The type identifier or `TypeId` is accessed through the `HasTypeId` trait. //! 2. The type definition or `TypeDef` is accessed throught the `HasTypeDef` trait. //! //! Both traits shall be implemented for all types that are serializable. //! For this the library provides implementations for all commonly used Rust standard //! types and provides derive macros for simpler implementation of user provided //! custom types. //! //! # Compaction Forms //! //! There is an uncompact form, called `MetaForm` that acts as a bridge from compile-time //! type information at runtime in order to easily retrieve all information needed to //! uniquely identify types. //! The compact form is retrieved by the `IntoCompact` trait and internally used by the //! `Registry` in order to convert the uncompact strings and types into their compact form. //! //! # Symbols and Namespaces //! //! Since symbol names are often shared across type boundaries the `Registry` also deduplicates //! them. To differentiate two types sharing the same name namespaces are used. Commonly //! the namespace is equal to the one where the type has been defined in. For Rust prelude //! types such as `Option` and `Result` the root namespace (empty namespace) is used. //! //! To use this library simply use the `MetaForm` initially with your own data structures //! and at best make them generic over the `Form` trait just as has been done in this crate //! with `TypeId` and `TypeDef` in order to go for a simple implementation of `IntoCompact`. //! Use a single instance of the `Registry` for compaction and provide this registry instance //! upon serialization. Done. //! //! A usage example can be found in ink! here: //! https://github.com/paritytech/ink/blob/master/abi/src/specs.rs #[cfg(not(feature = "std"))] extern crate alloc; /// Takes a number of types and returns a vector that contains their respective `MetaType` instances. /// /// This is useful for places that require inputs of iterators over `MetaType` instances /// and provide a way out of code bloat in these scenarious. /// /// # Example /// /// ``` /// # use type_metadata::tuple_meta_type; /// assert_eq!( /// tuple_meta_type!(i32, [u8; 32], String), /// { /// use type_metadata::MetaType; /// let mut vec = Vec::new(); /// vec.push(MetaType::new::<i32>()); /// vec.push(MetaType::new::<[u8; 32]>()); /// vec.push(MetaType::new::<String>()); /// vec /// } /// ); /// ``` #[macro_export] macro_rules! tuple_meta_type { ( $($ty:ty),* ) => { { #[cfg(not(feature = "std"))] extern crate alloc as _alloc; #[cfg(not(feature = "std"))] #[allow(unused_mut)] let mut v = _alloc::vec![]; #[cfg(feature = "std")] #[allow(unused_mut)] let mut v = std::vec![]; $( v.push($crate::MetaType::new::<$ty>()); )* v } } } mod tm_std; pub mod form; mod impls; pub mod interner; mod meta_type; mod registry; mod type_def; mod type_id; mod utils; #[cfg(test)] mod tests; pub use self::{ meta_type::MetaType, registry::{IntoCompact, Registry}, type_def::*, type_id::*, }; #[cfg(feature = "derive")] pub use type_metadata_derive::{Metadata, TypeDef, TypeId}; /// A super trait that shall be implemented by all types implementing /// `HasTypeId` and `HasTypedef` in order to more easily manage them. /// /// This trait is automatically implemented for all `'static` type that /// also implement `HasTypeId` and `HasTypeDef`. Users of this library should /// use this trait directly instead of using the more fine grained /// `HasTypeId` and `HasTypeDef` traits. pub trait Metadata: HasTypeId + HasTypeDef { /// Returns the runtime bridge to the types compile-time type information. fn meta_type() -> MetaType; } impl<T> Metadata for T where T: ?Sized + HasTypeId + HasTypeDef + 'static, { fn meta_type() -> MetaType { MetaType::new::<T>() } }
//! # Library to work with the MARC 21 Format for Bibliographic Data //! //! ## Examples //! //! ### Reading //! //! ```rust //! # use marc::*; //! # use std::{io, fs}; //! # fn main() -> marc::Result<()> { //! let input = fs::File::open("test/fixtures/3records.mrc")?; //! let mut count = 0; //! //! for (i, record) in Records::new(input).enumerate() { //! let record = dbg!(record?); //! match i { //! 0 => assert_eq!(record.field(b"001")[0].get_data::<str>(), "000000002"), //! 1 => assert_eq!(record.field(b"001")[0].get_data::<str>(), "000000005"), //! 2 => assert_eq!(record.field(b"001")[0].get_data::<str>(), "000000009"), //! _ => panic!(), //! } //! count += 1; //! } //! //! assert_eq!(count, 3); //! # marc::Result::Ok(()) //! # } //! ``` //! //! ### Creating //! //! ```rust //! # use marc::*; //! # use std::{io, fs}; //! # fn main() -> marc::Result<()> { //! let mut builder = RecordBuilder::new(); //! let record = builder //! .add_fields(fields!( //! control fields: [ //! b"001" => "000000002", //! b"003" => "RuMoRGB", //! ]; //! data fields: [ //! b"979", b" ", [ //! b'a' => "autoref", //! b'a' => "dlopen", //! ], //! ]; //! ))? //! .get_record()?; //! assert_eq!(record.as_ref(), b"00100nam 2200061 i 4500001001000000003000800010\ //! 979002000018\x1E000000002\x1ERuMoRGB\x1E \x1Faautoref\x1Fadlopen\x1E\x1D"); //! # marc::Result::Ok(()) //! # } //! ``` //! //! ### Updating //! //! ```rust //! # use marc::*; //! # use std::{io, fs}; //! # fn main() -> marc::Result<()> { //! let input = fs::File::open("test/fixtures/3records.mrc")?; //! let orig_record = Records::new(input).next().expect("should be here")?; //! let mut builder = RecordBuilder::from_record(&orig_record); //! let record = builder //! // we'll replace `001` //! .filter_fields(|f| f.get_tag() != "001") //! .add_field((b"001", "foo"))? //! // we'll remove `979a` with value `dlopen` (note that an empty `979` will remain) //! .filter_subfields(|_, sf| sf.get_tag() != "979" || //! sf.get_identifier() != 'a' || //! sf.get_data::<str>() != "dlopen") //! .get_record()?; //! //! assert_eq!(record.as_ref(), "01339nam a2200301 i 45000010004000000030008000040050017000120080\ //! 041000290170023000700350025000930400026001180410008001440720019001520840027001710840029001\ //! 980840029002271000076002562450352003322600025006843000011007096500092007207870038008128520\ //! 03400850852003400884856010400918979001201022979000301034\x1efoo\x1eRuMoRGB\x1e201507161647\ //! 15.0\x1e911009s1990 ru |||| a |00 u rus d\x1e \x1fa91-8563А\x1fbRuMoRKP\x1e \x1fa\ //! (RuMoRGB)DIS-0000114\x1e \x1faRuMoRGB\x1fbrus\x1fcRuMoRGB\x1e0 \x1farus\x1e 7\x1fa07.00.0\ //! 3\x1f2nsnr\x1e \x1faЭ38-36-021.4,0\x1f2rubbk\x1e \x1faТ3(6Ег)63-4,02\x1f2rubbk\x1e \x1f\ //! aТ3(5Ср)63-4,02\x1f2rubbk\x1e1 \x1faАбдувахитов, Абдужабар Абдусаттарович\x1e00\x1fa\"Брат\ //! ья-мусульмане\" на общественно-политической арене Египта и Сирии в 1928-1963 гг. :\x1fbавт\ //! ореферат дис. ... кандидата исторических наук : 07.00.03\x1fcАбдувахитов Абдужабар Абдусат\ //! тарович ; Ташк. гос. ун-т\x1e \x1faТашкент\x1fc1990\x1e \x1fa17 с.\x1e 7\x1faВсеобщая ис\ //! тория (соответствующего периода)\x1f2nsnr\x1e18\x1fw008120708\x1fiДиссертация\x1e4 \x1faРГ\ //! Б\x1fbFB\x1fj9 91-4/2388-x\x1fx71\x1e4 \x1faРГБ\x1fbFB\x1fj9 91-4/2389-8\x1fx70\x1e41\x1fq\ //! application/pdf\x1fuhttp://dlib.rsl.ru/rsl01000000000/rsl01000000000/rsl01000000002/rsl010\ //! 00000002.pdf\x1e \x1faautoref\x1e \x1e\x1d".as_bytes()); //! //! # marc::Result::Ok(()) //! # } //! ``` #![warn(missing_debug_implementations, rust_2018_idioms, future_incompatible)] #![cfg_attr(feature = "nightly", feature(test))] #![recursion_limit = "1024"] #[cfg(feature = "nightly")] extern crate test; use std::{ borrow::{Borrow, Cow}, fmt, io, slice, }; mod directory; pub mod errors; mod field; mod identifier; mod indicator; mod misc; mod tag; #[cfg(feature = "xml")] mod xml; pub use errors::*; #[cfg(feature = "xml")] #[doc(inline)] pub use crate::xml::MarcXml; #[doc(inline)] pub use field::fields::Fields; #[doc(inline)] pub use field::subfield::subfields::Subfields; #[doc(inline)] pub use field::subfield::Subfield; #[doc(inline)] pub use field::Field; #[doc(inline)] pub use field::FieldRepr; #[doc(inline)] pub use field::FromFieldData; #[doc(inline)] pub use identifier::Identifier; #[doc(inline)] pub use indicator::Indicator; #[doc(inline)] pub use tag::Tag; use directory::Directory; const MAX_FIELD_LEN: usize = 9_999; const MAX_RECORD_LEN: usize = 99_999; const RECORD_TERMINATOR: u8 = 0x1D; const FIELD_TERMINATOR: u8 = 0x1E; const SUBFIELD_DELIMITER: u8 = 0x1F; macro_rules! get { ($name:ident, $sname:ident, $num:expr) => { pub fn $sname(&self) -> $name { self.data[$num].into() } }; } /// Parsed MARC Record. /// /// It could be borrowed if it was parsed from a buffer or it could be owned if it was read from an /// `io::Read` implementor. #[derive(Debug, Clone, Eq, PartialEq)] pub struct Record<'a> { data: Cow<'a, [u8]>, data_offset: usize, directory: Directory, } impl<'a> Record<'a> { /// Will try to parse record from a buffer. /// /// Will borrow an `input` for the lifetime of a produced record. pub fn parse(input: &[u8]) -> Result<Record<'_>> { let len = misc::read_dec_5(input)?; if input.len() < len { return Err(Error::UnexpectedEof); } let data = &input[..len]; if data[len - 1] != RECORD_TERMINATOR { return Err(Error::NoRecordTerminator); } let data_offset = misc::read_dec_5(&data[12..17])?; let directory = Directory::parse(&data[24..data_offset])?; Ok(Record { data: Cow::Borrowed(data), data_offset, directory, }) } /// Will crate owned record from vector of bytes. /// /// # Panic /// Will check that input length equals the record length. pub fn from_vec<I>(input: I) -> Result<Record<'static>> where I: Into<Vec<u8>>, { let input = input.into(); let (data_offset, directory) = { let Record { data_offset, directory, data, } = Record::parse(&input)?; assert_eq!(input.len(), data.as_ref().len()); (data_offset, directory) }; Ok(Record { data: Cow::Owned(input), data_offset, directory, }) } /// Will try to read a `Record` from an `io::Read` implementor. /// /// Will return `None` if reader is empty. pub fn read<T: io::Read>(input: &mut T) -> Result<Option<Record<'static>>> { let mut data = vec![0; 5]; if let 0 = input.read(&mut data[..1])? { return Ok(None); } input.read_exact(&mut data[1..])?; let len = misc::read_dec_5(&data)?; if len < 5 { return Err(Error::RecordTooShort(len)); } data.resize(len, 0); input.read_exact(&mut data[5..len])?; let data_offset = misc::read_dec_5(&data[12..17])?; let directory = Directory::parse(&data[24..data_offset])?; Ok(Some(Record { data: Cow::Owned(data), data_offset, directory, })) } /// Will return fields with tag == `Tag` pub fn field<T: Into<tag::Tag>>(&self, tag: T) -> Vec<Field<'_>> { let tag = tag.into(); let mut output = Vec::with_capacity(4); for entry in self.directory.entries.iter() { if entry.0 == tag { let offset = self.data_offset + entry.2; output.push(Field::new(tag, &self.data[offset..offset + entry.1 - 1])); } } output } /// Will return iterator over fields of a record pub fn fields(&self) -> Fields<'_> { Fields::new(self) } /// Asserts that record uses unicode character coding scheme. /// /// * returns `false` if character scheme is MARC-8. /// * returns error on unknown character coding scheme /// * returns error if character scheme is specified as UCS/Unicode but record contains /// non-unicode sequences. /// /// ```rust /// /// # use marc::*; /// # use std::{io, fs}; /// # fn main() -> marc::Result<()> { /// let input = fs::File::open("test/fixtures/3records.mrc")?; /// /// for record in Records::new(input) { /// assert!(record?.is_unicode().unwrap()); /// } /// /// let mut marc8 = fs::read("test/fixtures/marc-8.sample.mrc")?; /// let record = Record::parse(&marc8).unwrap(); /// assert!(!record.is_unicode().unwrap()); /// /// marc8[9] = b'a'; /// marc8[1024] = 0xCC; /// let record = Record::parse(&marc8).unwrap(); /// assert!( /// matches!( /// record.is_unicode().unwrap_err(), /// Error::NonUnicodeSequence(ptr) /// if ptr == Pointer::Subfield(Tag::from_slice(b"260"), Identifier(b'b')))); /// # Ok(()) } /// ``` pub fn is_unicode(&self) -> crate::Result<bool> { match self.character_coding_scheme() { CharacterCodingScheme::Marc8 => Ok(false), CharacterCodingScheme::Unknown(x) => Err(Error::UnknownCharacterCodingScheme(x)), CharacterCodingScheme::UcsUnicode => { std::str::from_utf8(&self.data[..24]) .map_err(|_| Error::NonUnicodeSequence(Pointer::Leader))?; for field in self.fields() { let tag = field.get_tag(); let data = field.get_data::<[u8]>(); if data.contains(&SUBFIELD_DELIMITER) { for subfield in field.subfields() { let data = subfield.get_data::<[u8]>(); std::str::from_utf8(data).map_err(|_| { Error::NonUnicodeSequence(Pointer::Subfield( tag, subfield.get_identifier(), )) })?; } std::str::from_utf8(data) .map_err(|_| Error::NonUnicodeSequence(Pointer::Field(tag)))?; } else { std::str::from_utf8(data) .map_err(|_| Error::NonUnicodeSequence(Pointer::Field(tag)))?; } } Ok(true) } } } get!(RecordStatus, record_status, 5); get!(TypeOfRecord, type_of_record, 6); get!(BibliographicLevel, bibliographic_level, 7); get!(TypeOfControl, type_of_control, 8); get!(CharacterCodingScheme, character_coding_scheme, 9); get!(EncodingLevel, encoding_level, 17); get!(DescriptiveCatalogingForm, descriptive_cataloging_form, 18); get!( MultipartResourceRecordLevel, multipart_resource_record_level, 19 ); } impl AsRef<[u8]> for Record<'_> { fn as_ref(&self) -> &[u8] { self.data.borrow() } } impl<'a> fmt::Display for Record<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let leader = &self.as_ref()[0..24]; writeln!(f, "=LDR {}", String::from_utf8_lossy(leader))?; for field in self.fields() { writeln!(f, "{}", field)?; } Ok(()) } } /// Write Record Extension on io::Write pub trait WriteRecordExt: io::Write { /// write a record to a io::Write implementor /// /// returns the length of the written record fn write_record(&mut self, record: Record<'_>) -> io::Result<()>; } impl<T> WriteRecordExt for T where T: io::Write, { fn write_record(&mut self, record: Record<'_>) -> io::Result<()> { self.write_all(record.as_ref()) } } /// Reads records from an `io::Read` implementor. #[derive(Debug, Clone)] pub struct Records<T>(T, bool); impl<T: io::Read> Records<T> { pub fn new(input: T) -> Records<T> { Records(input, false) } /// Unwraps `io::Read` implementor. pub fn unwrap(self) -> T { self.0 } } impl<T: io::Read> Iterator for Records<T> { type Item = Result<Record<'static>>; fn next(&mut self) -> Option<Result<Record<'static>>> { if self.1 { None } else { let result = Record::read(&mut self.0); match result { Ok(Some(record)) => Some(Ok(record)), Ok(None) => { self.1 = true; None } Err(err) => { self.1 = true; Some(Err(err)) } } } } } macro_rules! getset { ($name:ident, $geti:ident, $seti:ident, $num:expr) => { pub fn $geti(&self) -> $name { self.leader[$num].into() } pub fn $seti(&mut self, x: $name) -> &mut Self { self.leader[$num] = x.into(); self } }; } /// Record builder. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RecordBuilder { leader: [u8; 24], fields: Vec<FieldRepr>, } impl RecordBuilder { /// Creates default record builer pub fn new() -> RecordBuilder { RecordBuilder { leader: *b"00000nam 2200000 i 4500", fields: vec![], } } /// Creates record builder from existing record pub fn from_record(record: &Record<'_>) -> RecordBuilder { let mut leader = [0; 24]; leader.copy_from_slice(&record.as_ref()[0..24]); let fields = record.fields().map(FieldRepr::from).collect(); RecordBuilder { leader, fields } } /// Iterator over fields of this builder. pub fn iter_fields(&self) -> slice::Iter<'_, FieldRepr> { self.fields.iter() } /// A way to add field to this builder. /// /// ### Errors /// /// Will return error if field is larger than 9.999 bytes. pub fn add_field<T: Into<FieldRepr>>(&mut self, f: T) -> Result<&mut Self> { let repr = f.into(); if repr.get_data().len() + 1 > MAX_FIELD_LEN { return Err(Error::FieldTooLarge(repr.get_tag())); } self.fields.push(repr); self.fields.sort_by_key(|f| f.get_tag()); Ok(self) } /// A way to add multiple fileds to this builder. /// /// ### Errors /// /// Will return error if any of fields is larger than 9.999 bytes. pub fn add_fields<T: Into<FieldRepr>>(&mut self, fs: Vec<T>) -> Result<&mut Self> { for f in fs { self.add_field(f)?; } Ok(self) } /// Will filter fields of this builder by `fun` predicate. pub fn filter_fields<F>(&mut self, mut fun: F) -> &mut RecordBuilder where F: FnMut(&Field<'_>) -> bool, { let fields = self .fields .clone() .into_iter() .filter(|f| { let f = Field::from_repr(f); fun(&f) }) .collect(); self.fields = fields; self } /// Will filter subfields of this builder by `fun` predicate. pub fn filter_subfields<F>(&mut self, mut fun: F) -> &mut Self where F: FnMut(&Field<'_>, &Subfield<'_>) -> bool, { let fields = self .fields .clone() .into_iter() .map(|f| { let fld = Field::from_repr(&f); f.filter_subfields(|sf| fun(&fld, sf)) }) .collect(); self.fields = fields; self } /// Returns record. /// /// ### Errors /// /// Will return error if record length is greater than 99.999 bytes. pub fn get_record(&self) -> Result<Record<'static>> { let mut data: Vec<_> = self.leader.to_vec(); // leader + directory terminator + record terminator let mut size = 24 + 1 + 1; for f in self.fields.iter() { // directory entry + field data length + field terminator size += 12 + f.get_data().len() + 1; } if size > MAX_RECORD_LEN { return Err(Error::RecordTooLarge(size)); } // writing record length data[0..5].copy_from_slice(format!("{:05}", size).as_bytes()); // writing directory let mut offset = 0; for f in self.fields.iter() { data.extend_from_slice(f.get_tag().as_ref()); // field data length + field terminator data.extend_from_slice(format!("{:04}", f.get_data().len() + 1).as_bytes()); data.extend_from_slice(format!("{:05}", offset).as_bytes()); offset += f.get_data().len() + 1; } data.push(FIELD_TERMINATOR); // writing base address of data let len = data.len(); data[12..17].copy_from_slice(format!("{:05}", len).as_bytes()); // writing fields for f in self.fields.iter() { data.extend_from_slice(f.get_data()); data.push(FIELD_TERMINATOR); } data.push(RECORD_TERMINATOR); let (data_offset, directory) = match Record::parse(&data) { Ok(Record { data: _, data_offset, directory, }) => (data_offset, directory), Err(err) => return Err(err), }; Ok(Record { data: Cow::Owned(data), data_offset, directory, }) } getset!(RecordStatus, get_record_status, set_record_status, 5); getset!(TypeOfRecord, get_type_of_record, set_type_of_record, 6); getset!( BibliographicLevel, get_bibliographic_level, set_bibliographic_level, 7 ); getset!(TypeOfControl, get_type_of_control, set_type_of_control, 8); getset!( CharacterCodingScheme, get_character_coding_scheme, set_character_coding_scheme, 9 ); getset!(EncodingLevel, get_encoding_level, set_encoding_level, 17); getset!( DescriptiveCatalogingForm, get_descriptive_cataloging_form, set_descriptive_cataloging_form, 18 ); getset!( MultipartResourceRecordLevel, get_multipart_resource_record_level, set_multipart_resource_record_level, 19 ); } impl Default for RecordBuilder { fn default() -> Self { Self::new() } } macro_rules! leader_field( ($name:ident { $($val:expr => $kind:ident,)+ }) => ( #[derive(Debug, PartialEq, Clone)] pub enum $name { $($kind),+, Unknown(u8), } impl From<u8> for $name { fn from(x: u8) -> $name { match x { $($val => $name::$kind),+, b => $name::Unknown(b), } } } impl From<$name> for u8 { fn from(x: $name) -> u8 { match x { $($name::$kind => $val),+, $name::Unknown(b) => b, } } } ); ); leader_field! { RecordStatus { b'a' => IncreaseInEncodingLevel, b'c' => CorrectedOrRevised, b'd' => Deleted, b'n' => New, b'p' => IncreaseInEncodingLevelFromPrepublication, } } leader_field! { TypeOfRecord { b'a' => LanguageMaterial, b'c' => NotatedMusic, b'd' => ManuscriptNotatedMusic, b'e' => CartographicMaterial, b'f' => ManuscriptCartographicMaterial, b'g' => ProjectedMedium, b'i' => NonmusicalSoundRecording, b'j' => MusicalSoundRecording, b'k' => TwoDimensionalNonprojectableGraphic, b'm' => ComputerFile, b'o' => Kit, b'p' => MixedMaterials, b'r' => ThreeDimensionalArtifactOrNaturallyOccurringObject, b't' => ManuscriptLanguageMaterial, } } leader_field! { BibliographicLevel { b'a' => MonographicComponentPart, b'b' => SerialComponentPart, b'c' => Collection, b'd' => Subunit, b'i' => IntegratingResource, b'm' => MonographOrItem, b's' => Serial, } } leader_field! { TypeOfControl { b' ' => NoSpecifiedType, b'a' => Archival, } } leader_field! { CharacterCodingScheme { b' ' => Marc8, b'a' => UcsUnicode, } } leader_field! { EncodingLevel { b' ' => FullLevel, b'1' => FullLevelMaterialNotExamined, b'2' => LessThanFullLevelMaterialNotExamined, b'3' => AbbreviatedLevel, b'4' => CoreLevel, b'5' => PartialLevel, b'7' => MinimalLevel, b'8' => PrepublicationLevel, b'u' => UnknownEL, b'z' => NotApplicable, } } leader_field! { DescriptiveCatalogingForm { b' ' => NonIsbd, b'a' => Aacr2, b'c' => IsbdPunctuationOmitted, b'i' => IsbdPunctuationIncluded, b'u' => UnknownDCF, } } leader_field! { MultipartResourceRecordLevel { b' ' => NotSpecifiedOrNotApplicable, b'a' => Set, b'b' => PartWithIndependentTitle, b'c' => PartWithDependentTitle, } } #[macro_export] /// Intended to use with `RecordBuilder::add_fields`. /// /// ```rust /// # use marc::{fields, RecordBuilder}; /// # let mut builder = RecordBuilder::new(); /// builder.add_fields(fields!( /// control fields: [b"001" => "foo"]; /// data fields: [ /// b"856", b"41", [ /// b'q' => "bar", /// b'u' => "baz", /// ], /// ]; /// )); /// ``` macro_rules! fields { ( control fields: [$($ctag:expr => $cdata:expr),*]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ ]; ) ); ( control fields: [$($ctag:expr => $cdata:expr,)*]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ ]; ) ); ( data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr),*] ),* ]; ) => ( fields!( control fields: [ ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr,)*] ),* ]; ) => ( fields!( control fields: [ ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr),*],)* ]; ) => ( fields!( control fields: [ ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr,)*],)* ]; ) => ( fields!( control fields: [ ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr),*] ),* ]; control fields: [$($ctag:expr => $cdata:expr),*]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr),*] ),* ]; control fields: [$($ctag:expr => $cdata:expr,)*]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr,)*] ),* ]; control fields: [$($ctag:expr => $cdata:expr),*]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr,)*] ),* ]; control fields: [$($ctag:expr => $cdata:expr,)*]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr),*],)* ]; control fields: [$($ctag:expr => $cdata:expr),*]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr),*],)* ]; control fields: [$($ctag:expr => $cdata:expr,)*]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr,)*],)* ]; control fields: [$($ctag:expr => $cdata:expr),*]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr,)*], )* ]; control fields: [$($ctag:expr => $cdata:expr,)*]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( control fields: [$($ctag:expr => $cdata:expr),*]; data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr),*] ),* ]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( control fields: [$($ctag:expr => $cdata:expr,)*]; data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr),*] ),* ]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( control fields: [$($ctag:expr => $cdata:expr),*]; data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr,)*] ),* ]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( control fields: [$($ctag:expr => $cdata:expr,)*]; data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr,)*] ),* ]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( control fields: [$($ctag:expr => $cdata:expr),*]; data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr),*],)* ]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( control fields: [$($ctag:expr => $cdata:expr,)*]; data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr),*],)* ]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( control fields: [$($ctag:expr => $cdata:expr),*]; data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr,)*],)* ]; ) => ( fields!( control fields: [ $($ctag => $cdata,)* ]; data fields: [ $($dtag, $dind, [ $($sfident => $sfdata,)* ],)* ]; ) ); ( control fields: [$($ctag:expr => $cdata:expr,)*]; data fields: [ $( $dtag:expr, $dind:expr, [$($sfident:expr => $sfdata:expr,)*], )* ]; ) => ({ let mut out = vec![]; $(out.push( $crate::FieldRepr::from( ($crate::Tag::from($ctag), Vec::<u8>::from($cdata)) ) );)* $({ let mut sfs = vec![]; $(sfs.push(($crate::Identifier::from($sfident), Vec::<u8>::from($sfdata)));)* out.push( $crate::FieldRepr::from( ($crate::Tag::from($dtag), $crate::Indicator::from($dind), sfs) ) ) })* out }); } #[cfg(test)] mod tests { const RECS: &str = "00963nam a2200229 i 4500001001000000003000800010003000800018005001700026008004100043035002300084040002600107041000800133072001900141100005800160245028000218260004000498300001600538650004200554856010400596979001200700979002100712\ \x1e000000001\x1eRuMoRGB\x1eEnMoRGB\x1e20080528120000.0\x1e080528s1992 ru a||| a |00 u rus d\x1e \x1fa(RuMoEDL)-92k71098\x1e \x1faRuMoRGB\x1fbrus\x1fcRuMoRGB\x1e0 \x1farus\x1e 7\x1fa07.00.03\x1f2nsnr\x1e1 \x1fa'Абд Ал-'Азиз Джа'фар Бин 'Акид\x1e00\x1faЭтносоциальная структура и институты социальной защиты в Хадрамауте (19 - первая половина 20 вв.) :\x1fbавтореферат дис. ... кандидата исторических наук : 07.00.03\x1e \x1faСанкт-Петербург\x1fc1992\x1e \x1fa24 c.\x1fbил\x1e 7\x1faВсеобщая история\x1f2nsnr\x1e41\x1fqapplication/pdf\x1fuhttp://dlib.rsl.ru/rsl01000000000/rsl01000000000/rsl01000000001/rsl01000000001.pdf\x1e \x1faautoref\x1e \x1fbautoreg\x1fbautoreh\x1e\x1d\ 00963nam a2200229 i 4500001001000000003000800010003000800018005001700026008004100043035002300084040002600107041000800133072001900141100005800160245028000218260004000498300001600538650004200554856010400596979001200700979002100712\ \x1e000000002\x1eRuMoRGB\x1eEnMoRGB\x1e20080528120000.0\x1e080528s1992 ru a||| a |00 u rus d\x1e \x1fa(RuMoEDL)-92k71098\x1e \x1faRuMoRGB\x1fbrus\x1fcRuMoRGB\x1e0 \x1farus\x1e 7\x1fa07.00.03\x1f2nsnr\x1e1 \x1fa'Абд Ал-'Азиз Джа'фар Бин 'Акид\x1e00\x1faЭтносоциальная структура и институты социальной защиты в Хадрамауте (19 - первая половина 20 вв.) :\x1fbавтореферат дис. ... кандидата исторических наук : 07.00.03\x1e \x1faСанкт-Петербург\x1fc1992\x1e \x1fa24 c.\x1fbил\x1e 7\x1faВсеобщая история\x1f2nsnr\x1e41\x1fqapplication/pdf\x1fuhttp://dlib.rsl.ru/rsl01000000000/rsl01000000000/rsl01000000002/rsl01000000002.pdf\x1e \x1faautoref\x1e \x1fbautoreg\x1fbautoreh\x1e\x1d"; const REC_SIZE: u64 = 963; mod read { use super::{super::*, RECS, REC_SIZE}; use std::io; #[test] fn should_parse_record() { let record = Record::parse(&RECS.as_bytes()[..963]).unwrap(); assert_eq!(record.record_status(), RecordStatus::New); assert_eq!(record.type_of_record(), TypeOfRecord::LanguageMaterial); assert_eq!( record.bibliographic_level(), BibliographicLevel::MonographOrItem ); assert_eq!(record.type_of_control(), TypeOfControl::NoSpecifiedType); assert_eq!( record.character_coding_scheme(), CharacterCodingScheme::UcsUnicode ); assert_eq!(record.encoding_level(), EncodingLevel::FullLevel); assert_eq!( record.descriptive_cataloging_form(), DescriptiveCatalogingForm::IsbdPunctuationIncluded ); assert_eq!( record.multipart_resource_record_level(), MultipartResourceRecordLevel::NotSpecifiedOrNotApplicable ); assert_eq!(record.as_ref(), &RECS.as_bytes()[0..REC_SIZE as usize]); } #[test] fn should_create_record_from_vec() { let record = Record::from_vec((&RECS.as_bytes()[..963]).to_vec()).unwrap(); assert_eq!(record.record_status(), RecordStatus::New); assert_eq!(record.type_of_record(), TypeOfRecord::LanguageMaterial); assert_eq!( record.bibliographic_level(), BibliographicLevel::MonographOrItem ); assert_eq!(record.type_of_control(), TypeOfControl::NoSpecifiedType); assert_eq!( record.character_coding_scheme(), CharacterCodingScheme::UcsUnicode ); assert_eq!(record.encoding_level(), EncodingLevel::FullLevel); assert_eq!( record.descriptive_cataloging_form(), DescriptiveCatalogingForm::IsbdPunctuationIncluded ); assert_eq!( record.multipart_resource_record_level(), MultipartResourceRecordLevel::NotSpecifiedOrNotApplicable ); assert_eq!(record.as_ref(), &RECS.as_bytes()[0..REC_SIZE as usize]); } #[test] fn should_read_record() { let mut data = vec![]; data.extend_from_slice(RECS.as_bytes()); let mut input = io::Cursor::new(data); let record = Record::read(&mut input).unwrap(); let record = record.unwrap(); assert_eq!(record.record_status(), RecordStatus::New); assert_eq!(record.type_of_record(), TypeOfRecord::LanguageMaterial); assert_eq!( record.bibliographic_level(), BibliographicLevel::MonographOrItem ); assert_eq!(record.type_of_control(), TypeOfControl::NoSpecifiedType); assert_eq!( record.character_coding_scheme(), CharacterCodingScheme::UcsUnicode ); assert_eq!(record.encoding_level(), EncodingLevel::FullLevel); assert_eq!( record.descriptive_cataloging_form(), DescriptiveCatalogingForm::IsbdPunctuationIncluded ); assert_eq!( record.multipart_resource_record_level(), MultipartResourceRecordLevel::NotSpecifiedOrNotApplicable ); assert_eq!(record.as_ref(), &RECS.as_bytes()[0..REC_SIZE as usize]); let record = Record::read(&mut input).unwrap(); let record = record.unwrap(); assert_eq!(record.record_status(), RecordStatus::New); assert_eq!(record.type_of_record(), TypeOfRecord::LanguageMaterial); assert_eq!( record.bibliographic_level(), BibliographicLevel::MonographOrItem ); assert_eq!(record.type_of_control(), TypeOfControl::NoSpecifiedType); assert_eq!( record.character_coding_scheme(), CharacterCodingScheme::UcsUnicode ); assert_eq!(record.encoding_level(), EncodingLevel::FullLevel); assert_eq!( record.descriptive_cataloging_form(), DescriptiveCatalogingForm::IsbdPunctuationIncluded ); assert_eq!( record.multipart_resource_record_level(), MultipartResourceRecordLevel::NotSpecifiedOrNotApplicable ); assert_eq!(record.as_ref(), &RECS.as_bytes()[REC_SIZE as usize..]); let record = Record::read(&mut input).unwrap(); assert!(record.is_none()); } #[test] fn should_iterate_records() { let mut data = vec![]; data.extend_from_slice(RECS.as_bytes()); let input = io::Cursor::new(data); let mut records = Records::new(input); let record = records.next().unwrap().unwrap(); assert_eq!(record.record_status(), RecordStatus::New); assert_eq!(record.type_of_record(), TypeOfRecord::LanguageMaterial); assert_eq!( record.bibliographic_level(), BibliographicLevel::MonographOrItem ); assert_eq!(record.type_of_control(), TypeOfControl::NoSpecifiedType); assert_eq!( record.character_coding_scheme(), CharacterCodingScheme::UcsUnicode ); assert_eq!(record.encoding_level(), EncodingLevel::FullLevel); assert_eq!( record.descriptive_cataloging_form(), DescriptiveCatalogingForm::IsbdPunctuationIncluded ); assert_eq!( record.multipart_resource_record_level(), MultipartResourceRecordLevel::NotSpecifiedOrNotApplicable ); assert_eq!(record.as_ref(), &RECS.as_bytes()[0..REC_SIZE as usize]); let record = records.next().unwrap().unwrap(); assert_eq!(record.record_status(), RecordStatus::New); assert_eq!(record.type_of_record(), TypeOfRecord::LanguageMaterial); assert_eq!( record.bibliographic_level(), BibliographicLevel::MonographOrItem ); assert_eq!(record.type_of_control(), TypeOfControl::NoSpecifiedType); assert_eq!( record.character_coding_scheme(), CharacterCodingScheme::UcsUnicode ); assert_eq!(record.encoding_level(), EncodingLevel::FullLevel); assert_eq!( record.descriptive_cataloging_form(), DescriptiveCatalogingForm::IsbdPunctuationIncluded ); assert_eq!( record.multipart_resource_record_level(), MultipartResourceRecordLevel::NotSpecifiedOrNotApplicable ); assert_eq!(record.as_ref(), &RECS.as_bytes()[REC_SIZE as usize..]); assert!(records.next().is_none()); assert!(records.next().is_none()); let data = &[0x30; 10]; let input = io::Cursor::new(data); let mut records = Records::new(input); assert!(records.next().unwrap().is_err()); assert!(records.next().is_none()); } #[test] fn should_get_field() { let record = Record::parse(&RECS.as_bytes()[..963]).unwrap(); let repr = FieldRepr::from((b"001", "000000001")); let fields = record.field(b"001"); assert_eq!(fields, vec![Field::from_repr(&repr)]); let repr1 = FieldRepr::from((b"979", " \x1faautoref")); let repr2 = FieldRepr::from((b"979", " \x1fbautoreg\x1fbautoreh")); let fields = record.field(b"979"); assert_eq!( fields, vec![Field::from_repr(&repr1), Field::from_repr(&repr2),] ); let fields = record.field(b"999"); assert_eq!(fields, vec![]); } #[test] fn should_get_fields() { let record = Record::parse(&RECS.as_bytes()[..963]).unwrap(); let tags: Vec<Tag> = record.fields().map(|field| field.get_tag()).collect(); assert_eq!( tags, vec![ Tag::from(b"001"), Tag::from(b"003"), Tag::from(b"003"), Tag::from(b"005"), Tag::from(b"008"), Tag::from(b"035"), Tag::from(b"040"), Tag::from(b"041"), Tag::from(b"072"), Tag::from(b"100"), Tag::from(b"245"), Tag::from(b"260"), Tag::from(b"300"), Tag::from(b"650"), Tag::from(b"856"), Tag::from(b"979"), Tag::from(b"979"), ] ); } #[test] fn should_build_record() { let record = Record::parse(&RECS.as_bytes()[..963]).unwrap(); let mut builder = RecordBuilder::new(); builder.add_fields(fields!( data fields: [ b"979", b" ", [ b'a' => "autoref", ], b"979", b" ", [ b'b' => "autoreg", b'b' => "autoreh", ], b"856", b"41" , [ b'q' => "application/pdf", b'u' => "http://dlib.rsl.ru/rsl01000000000/rsl01000000000/rsl01000000001/rsl01000000001.pdf", ], b"650", b" 7", [ b'a' => "Всеобщая история", b'2' => "nsnr", ], b"300", b" ", [ b'a' => "24 c.", b'b' => "ил", ], b"260", b" ", [ b'a' => "Санкт-Петербург", b'c' => "1992", ], b"245", b"00", [ b'a' => "Этносоциальная структура и институты социальной защиты в Хадрамауте (19 - первая половина 20 вв.) :", b'b' => "автореферат дис. ... кандидата исторических наук : 07.00.03", ], b"100", b"1 ", [ b'a' => "'Абд Ал-'Азиз Джа'фар Бин 'Акид", ], b"072", b" 7", [ b'a' => "07.00.03", b'2' => "nsnr", ], b"041", b"0 ", [ b'a' => "rus", ], b"040", b" ", [ b'a' => "RuMoRGB", b'b' => "rus", b'c' => "RuMoRGB", ], b"035", b" ", [ b'a' => "(RuMoEDL)-92k71098", b'f' => "filter", ], ]; control fields: [ b"000" => "filter", b"008" => "080528s1992 ru a||| a |00 u rus d", b"005" => "20080528120000.0", b"003" => "RuMoRGB", b"003" => "EnMoRGB", b"001" => "000000001", ]; )).unwrap(); builder .set_record_status(record.record_status()) .set_type_of_record(record.type_of_record()) .set_bibliographic_level(record.bibliographic_level()) .set_type_of_control(record.type_of_control()) .set_character_coding_scheme(record.character_coding_scheme()) .set_encoding_level(record.encoding_level()) .set_descriptive_cataloging_form(record.descriptive_cataloging_form()) .set_multipart_resource_record_level(record.multipart_resource_record_level()); builder.filter_fields(|f| f.get_tag() != b"000"); builder.filter_subfields(|_, sf| sf.get_data::<[u8]>() != &b"filter"[..]); assert_eq!(builder.get_record().unwrap().as_ref(), record.as_ref()); } #[test] fn should_display_record() { let mut builder = RecordBuilder::new(); builder .add_fields(fields!( data fields: [ b"264", b" 1", [ b'a' => "León, Spain", ], b"245", b"00", [ b'a' => "Book title", b'b' => "Book Subtitle", ], b"100", b"1 ", [ b'a' => "Author Name", ], b"041", b"0 ", [ b'a' => "eng", ], ]; control fields: [ b"008" => "210128t20212021enka sb 000 0 eng d", b"001" => "000000001", ]; )) .unwrap(); let record = builder.get_record().unwrap(); let expected = "=LDR 00220nam 2200097 i 4500\n=001 000000001\n=008 210128t20212021enka\\\\\\\\sb\\\\\\\\000\\0\\eng\\d\n=041 0 $aeng\n=100 1 $aAuthor Name\n=245 00$aBook title$bBook Subtitle\n=264 1$aLeón, Spain\n".to_string(); assert_eq!(format!("{}", record), expected); } } mod write { use super::{super::*, RECS}; #[test] fn should_write_record() { let mut vec = Vec::new(); let record = Record::parse(&RECS.as_bytes()[..963]).unwrap(); match vec.write_record(record.clone()) { Err(why) => panic!("couldn't write file: {}", why), Ok(_) => (), } let record2 = Record::from_vec(vec).unwrap(); assert_eq!(record.as_ref(), record2.as_ref()); } } #[cfg(feature = "nightly")] mod bench { use super::{super::*, RECS, REC_SIZE}; use test; #[bench] fn read_record(b: &mut test::Bencher) { b.iter(|| { if let Ok(rec) = Record::read(&mut RECS.as_bytes()) { if let Some(rec) = rec { test::black_box(rec); } else { panic!(); } } }); b.bytes += REC_SIZE; } #[bench] fn parse_record(b: &mut test::Bencher) { b.iter(|| { if let Ok(rec) = Record::parse(RECS.as_bytes()) { test::black_box(rec); } else { panic!(); } }); b.bytes += REC_SIZE; } } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(feature = "Win32_Foundation")] pub fn HcsAttachLayerStorageFilter(layerpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; pub fn HcsCancelOperation(operation: HCS_OPERATION) -> ::windows_sys::core::HRESULT; pub fn HcsCloseComputeSystem(computesystem: HCS_SYSTEM); pub fn HcsCloseOperation(operation: HCS_OPERATION); pub fn HcsCloseProcess(process: HCS_PROCESS); #[cfg(feature = "Win32_Foundation")] pub fn HcsCrashComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub fn HcsCreateComputeSystem(id: super::super::Foundation::PWSTR, configuration: super::super::Foundation::PWSTR, operation: HCS_OPERATION, securitydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR, computesystem: *mut HCS_SYSTEM) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsCreateComputeSystemInNamespace(idnamespace: super::super::Foundation::PWSTR, id: super::super::Foundation::PWSTR, configuration: super::super::Foundation::PWSTR, operation: HCS_OPERATION, options: *const HCS_CREATE_OPTIONS, computesystem: *mut HCS_SYSTEM) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsCreateEmptyGuestStateFile(gueststatefilepath: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsCreateEmptyRuntimeStateFile(runtimestatefilepath: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; pub fn HcsCreateOperation(context: *const ::core::ffi::c_void, callback: HCS_OPERATION_COMPLETION) -> HCS_OPERATION; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub fn HcsCreateProcess(computesystem: HCS_SYSTEM, processparameters: super::super::Foundation::PWSTR, operation: HCS_OPERATION, securitydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR, process: *mut HCS_PROCESS) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsDestroyLayer(layerpath: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsDetachLayerStorageFilter(layerpath: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsEnumerateComputeSystems(query: super::super::Foundation::PWSTR, operation: HCS_OPERATION) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsEnumerateComputeSystemsInNamespace(idnamespace: super::super::Foundation::PWSTR, query: super::super::Foundation::PWSTR, operation: HCS_OPERATION) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsExportLayer(layerpath: super::super::Foundation::PWSTR, exportfolderpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::PWSTR, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsExportLegacyWritableLayer(writablelayermountpath: super::super::Foundation::PWSTR, writablelayerfolderpath: super::super::Foundation::PWSTR, exportfolderpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsFormatWritableLayerVhd(vhdhandle: super::super::Foundation::HANDLE) -> ::windows_sys::core::HRESULT; pub fn HcsGetComputeSystemFromOperation(operation: HCS_OPERATION) -> HCS_SYSTEM; #[cfg(feature = "Win32_Foundation")] pub fn HcsGetComputeSystemProperties(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, propertyquery: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsGetLayerVhdMountPath(vhdhandle: super::super::Foundation::HANDLE, mountpath: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; pub fn HcsGetOperationContext(operation: HCS_OPERATION) -> *mut ::core::ffi::c_void; pub fn HcsGetOperationId(operation: HCS_OPERATION) -> u64; #[cfg(feature = "Win32_Foundation")] pub fn HcsGetOperationResult(operation: HCS_OPERATION, resultdocument: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsGetOperationResultAndProcessInfo(operation: HCS_OPERATION, processinformation: *mut HCS_PROCESS_INFORMATION, resultdocument: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; pub fn HcsGetOperationType(operation: HCS_OPERATION) -> HCS_OPERATION_TYPE; pub fn HcsGetProcessFromOperation(operation: HCS_OPERATION) -> HCS_PROCESS; pub fn HcsGetProcessInfo(process: HCS_PROCESS, operation: HCS_OPERATION) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsGetProcessProperties(process: HCS_PROCESS, operation: HCS_OPERATION, propertyquery: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsGetProcessorCompatibilityFromSavedState(runtimefilename: super::super::Foundation::PWSTR, processorfeaturesstring: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsGetServiceProperties(propertyquery: super::super::Foundation::PWSTR, result: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsGrantVmAccess(vmid: super::super::Foundation::PWSTR, filepath: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsGrantVmGroupAccess(filepath: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsImportLayer(layerpath: super::super::Foundation::PWSTR, sourcefolderpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsInitializeLegacyWritableLayer(writablelayermountpath: super::super::Foundation::PWSTR, writablelayerfolderpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::PWSTR, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsInitializeWritableLayer(writablelayerpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::PWSTR, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsModifyComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, configuration: super::super::Foundation::PWSTR, identity: super::super::Foundation::HANDLE) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsModifyProcess(process: HCS_PROCESS, operation: HCS_OPERATION, settings: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsModifyServiceSettings(settings: super::super::Foundation::PWSTR, result: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsOpenComputeSystem(id: super::super::Foundation::PWSTR, requestedaccess: u32, computesystem: *mut HCS_SYSTEM) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsOpenComputeSystemInNamespace(idnamespace: super::super::Foundation::PWSTR, id: super::super::Foundation::PWSTR, requestedaccess: u32, computesystem: *mut HCS_SYSTEM) -> ::windows_sys::core::HRESULT; pub fn HcsOpenProcess(computesystem: HCS_SYSTEM, processid: u32, requestedaccess: u32, process: *mut HCS_PROCESS) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsPauseComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsResumeComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsRevokeVmAccess(vmid: super::super::Foundation::PWSTR, filepath: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsRevokeVmGroupAccess(filepath: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsSaveComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsSetComputeSystemCallback(computesystem: HCS_SYSTEM, callbackoptions: HCS_EVENT_OPTIONS, context: *const ::core::ffi::c_void, callback: HCS_EVENT_CALLBACK) -> ::windows_sys::core::HRESULT; pub fn HcsSetOperationCallback(operation: HCS_OPERATION, context: *const ::core::ffi::c_void, callback: HCS_OPERATION_COMPLETION) -> ::windows_sys::core::HRESULT; pub fn HcsSetOperationContext(operation: HCS_OPERATION, context: *const ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsSetProcessCallback(process: HCS_PROCESS, callbackoptions: HCS_EVENT_OPTIONS, context: *const ::core::ffi::c_void, callback: HCS_EVENT_CALLBACK) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsSetupBaseOSLayer(layerpath: super::super::Foundation::PWSTR, vhdhandle: super::super::Foundation::HANDLE, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsSetupBaseOSVolume(layerpath: super::super::Foundation::PWSTR, volumepath: super::super::Foundation::PWSTR, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsShutDownComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsSignalProcess(process: HCS_PROCESS, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsStartComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsSubmitWerReport(settings: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsTerminateComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsTerminateProcess(process: HCS_PROCESS, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsWaitForComputeSystemExit(computesystem: HCS_SYSTEM, timeoutms: u32, result: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsWaitForOperationResult(operation: HCS_OPERATION, timeoutms: u32, resultdocument: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsWaitForOperationResultAndProcessInfo(operation: HCS_OPERATION, timeoutms: u32, processinformation: *mut HCS_PROCESS_INFORMATION, resultdocument: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn HcsWaitForProcessExit(computesystem: HCS_PROCESS, timeoutms: u32, result: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; } pub type HCS_CREATE_OPTIONS = i32; pub const HcsCreateOptions_1: HCS_CREATE_OPTIONS = 65536i32; #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub struct HCS_CREATE_OPTIONS_1 { pub Version: HCS_CREATE_OPTIONS, pub UserToken: super::super::Foundation::HANDLE, pub SecurityDescriptor: *mut super::super::Security::SECURITY_DESCRIPTOR, pub CallbackOptions: HCS_EVENT_OPTIONS, pub CallbackContext: *mut ::core::ffi::c_void, pub Callback: HCS_EVENT_CALLBACK, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::marker::Copy for HCS_CREATE_OPTIONS_1 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::clone::Clone for HCS_CREATE_OPTIONS_1 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HCS_EVENT { pub Type: HCS_EVENT_TYPE, pub EventData: super::super::Foundation::PWSTR, pub Operation: HCS_OPERATION, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for HCS_EVENT {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for HCS_EVENT { fn clone(&self) -> Self { *self } } #[cfg(feature = "Win32_Foundation")] pub type HCS_EVENT_CALLBACK = ::core::option::Option<unsafe extern "system" fn(event: *const HCS_EVENT, context: *const ::core::ffi::c_void)>; pub type HCS_EVENT_OPTIONS = u32; pub const HcsEventOptionNone: HCS_EVENT_OPTIONS = 0u32; pub const HcsEventOptionEnableOperationCallbacks: HCS_EVENT_OPTIONS = 1u32; pub type HCS_EVENT_TYPE = i32; pub const HcsEventInvalid: HCS_EVENT_TYPE = 0i32; pub const HcsEventSystemExited: HCS_EVENT_TYPE = 1i32; pub const HcsEventSystemCrashInitiated: HCS_EVENT_TYPE = 2i32; pub const HcsEventSystemCrashReport: HCS_EVENT_TYPE = 3i32; pub const HcsEventSystemRdpEnhancedModeStateChanged: HCS_EVENT_TYPE = 4i32; pub const HcsEventSystemSiloJobCreated: HCS_EVENT_TYPE = 5i32; pub const HcsEventSystemGuestConnectionClosed: HCS_EVENT_TYPE = 6i32; pub const HcsEventProcessExited: HCS_EVENT_TYPE = 65536i32; pub const HcsEventOperationCallback: HCS_EVENT_TYPE = 16777216i32; pub const HcsEventServiceDisconnect: HCS_EVENT_TYPE = 33554432i32; pub type HCS_NOTIFICATIONS = i32; pub const HcsNotificationInvalid: HCS_NOTIFICATIONS = 0i32; pub const HcsNotificationSystemExited: HCS_NOTIFICATIONS = 1i32; pub const HcsNotificationSystemCreateCompleted: HCS_NOTIFICATIONS = 2i32; pub const HcsNotificationSystemStartCompleted: HCS_NOTIFICATIONS = 3i32; pub const HcsNotificationSystemPauseCompleted: HCS_NOTIFICATIONS = 4i32; pub const HcsNotificationSystemResumeCompleted: HCS_NOTIFICATIONS = 5i32; pub const HcsNotificationSystemCrashReport: HCS_NOTIFICATIONS = 6i32; pub const HcsNotificationSystemSiloJobCreated: HCS_NOTIFICATIONS = 7i32; pub const HcsNotificationSystemSaveCompleted: HCS_NOTIFICATIONS = 8i32; pub const HcsNotificationSystemRdpEnhancedModeStateChanged: HCS_NOTIFICATIONS = 9i32; pub const HcsNotificationSystemShutdownFailed: HCS_NOTIFICATIONS = 10i32; pub const HcsNotificationSystemShutdownCompleted: HCS_NOTIFICATIONS = 10i32; pub const HcsNotificationSystemGetPropertiesCompleted: HCS_NOTIFICATIONS = 11i32; pub const HcsNotificationSystemModifyCompleted: HCS_NOTIFICATIONS = 12i32; pub const HcsNotificationSystemCrashInitiated: HCS_NOTIFICATIONS = 13i32; pub const HcsNotificationSystemGuestConnectionClosed: HCS_NOTIFICATIONS = 14i32; pub const HcsNotificationSystemOperationCompletion: HCS_NOTIFICATIONS = 15i32; pub const HcsNotificationSystemPassThru: HCS_NOTIFICATIONS = 16i32; pub const HcsNotificationProcessExited: HCS_NOTIFICATIONS = 65536i32; pub const HcsNotificationServiceDisconnect: HCS_NOTIFICATIONS = 16777216i32; pub const HcsNotificationFlagsReserved: HCS_NOTIFICATIONS = -268435456i32; #[cfg(feature = "Win32_Foundation")] pub type HCS_NOTIFICATION_CALLBACK = ::core::option::Option<unsafe extern "system" fn(notificationtype: u32, context: *const ::core::ffi::c_void, notificationstatus: ::windows_sys::core::HRESULT, notificationdata: super::super::Foundation::PWSTR)>; pub type HCS_NOTIFICATION_FLAGS = i32; pub const HcsNotificationFlagSuccess: HCS_NOTIFICATION_FLAGS = 0i32; pub const HcsNotificationFlagFailure: HCS_NOTIFICATION_FLAGS = -2147483648i32; pub type HCS_OPERATION = isize; pub type HCS_OPERATION_COMPLETION = ::core::option::Option<unsafe extern "system" fn(operation: HCS_OPERATION, context: *const ::core::ffi::c_void)>; pub type HCS_OPERATION_TYPE = i32; pub const HcsOperationTypeNone: HCS_OPERATION_TYPE = -1i32; pub const HcsOperationTypeEnumerate: HCS_OPERATION_TYPE = 0i32; pub const HcsOperationTypeCreate: HCS_OPERATION_TYPE = 1i32; pub const HcsOperationTypeStart: HCS_OPERATION_TYPE = 2i32; pub const HcsOperationTypeShutdown: HCS_OPERATION_TYPE = 3i32; pub const HcsOperationTypePause: HCS_OPERATION_TYPE = 4i32; pub const HcsOperationTypeResume: HCS_OPERATION_TYPE = 5i32; pub const HcsOperationTypeSave: HCS_OPERATION_TYPE = 6i32; pub const HcsOperationTypeTerminate: HCS_OPERATION_TYPE = 7i32; pub const HcsOperationTypeModify: HCS_OPERATION_TYPE = 8i32; pub const HcsOperationTypeGetProperties: HCS_OPERATION_TYPE = 9i32; pub const HcsOperationTypeCreateProcess: HCS_OPERATION_TYPE = 10i32; pub const HcsOperationTypeSignalProcess: HCS_OPERATION_TYPE = 11i32; pub const HcsOperationTypeGetProcessInfo: HCS_OPERATION_TYPE = 12i32; pub const HcsOperationTypeGetProcessProperties: HCS_OPERATION_TYPE = 13i32; pub const HcsOperationTypeModifyProcess: HCS_OPERATION_TYPE = 14i32; pub const HcsOperationTypeCrash: HCS_OPERATION_TYPE = 15i32; pub type HCS_PROCESS = isize; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HCS_PROCESS_INFORMATION { pub ProcessId: u32, pub Reserved: u32, pub StdInput: super::super::Foundation::HANDLE, pub StdOutput: super::super::Foundation::HANDLE, pub StdError: super::super::Foundation::HANDLE, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for HCS_PROCESS_INFORMATION {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for HCS_PROCESS_INFORMATION { fn clone(&self) -> Self { *self } } pub type HCS_SYSTEM = isize;
use crate::errors::ErrorCx; use crate::grammar; use crate::lexer; use crate::raw; use crate::source_file::{FileMap, SourceFile}; use crate::span::{FileId, Span}; use crate::token::Token; use annotate_snippets::snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation}; use lalrpop_util; use std::fmt; use std::fs::File; use std::io::Read; pub fn parse_files(srcs: &mut FileMap, errors: &mut ErrorCx, paths: Vec<String>) -> Vec<raw::File> { let mut files = Vec::new(); for path in paths { let raw_contents = read_file(&path); let src_file = srcs.add_file(path, raw_contents); match parse(src_file) { Ok(file) => files.push(file), Err(err) => errors.push(err.into_snippet(&src_file)), } } files } pub fn parse(src: &SourceFile) -> Result<raw::File, Error> { grammar::FileParser::new() .parse(src.id, lexer::Lexer::new(src.id, src.contents())) .map_err(|err| err.into()) } fn read_file(path: &String) -> String { let file = File::open(path); assert!(file.is_ok(), "Could not open file: {}", path); let mut contents = String::new(); let read_result = file.unwrap().read_to_string(&mut contents); assert!(read_result.is_ok(), "Could not read file: {}", path); contents.replace('\r', "") } // TODO: follow rustc's parse error format: // this needs to be kept in sync with the grammar and lexer type ParseError<'input> = lalrpop_util::ParseError<usize, Token<'input>, lexer::SpannedError>; /// This is a wrapper around our instance of lalrpop_util::ParseError that removes /// all of the instances of Tokens. This avoids having to pipe through the /// Token lifetimes since they are not necessary for creating error messages. #[derive(Debug)] pub enum Error { InvalidToken(usize), UnrecognizedEOF { location: usize, expected: Vec<String>, }, UnrecognizedToken { start: usize, end: usize, expected: Vec<String>, }, ExtraToken { start: usize, end: usize, }, LexError(lexer::SpannedError), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use Error::*; match self { InvalidToken(_) => write!(f, "invalid token"), UnrecognizedEOF { location: _, expected, } => // TODO { write!(f, "unrecognized EOF, expected one of: {:?}", expected) } UnrecognizedToken { start: _, end: _, expected, } => // TODO { write!(f, "unrecognized token, expected one of : {:?}", expected) } ExtraToken { start: _, end: _ } => write!(f, "extra token"), LexError(err) => write!(f, "{}", err.value), } } } impl From<ParseError<'_>> for Error { fn from(err: ParseError) -> Self { match err { ParseError::InvalidToken { location } => Error::InvalidToken(location), ParseError::UnrecognizedEOF { location, expected } => { Error::UnrecognizedEOF { location, expected } } ParseError::UnrecognizedToken { token: (start, _, end), expected, } => Error::UnrecognizedToken { start, end, expected, }, ParseError::ExtraToken { token: (start, _, end), } => Error::ExtraToken { start, end }, ParseError::User { error } => Error::LexError(error), } } } impl Error { pub fn get_span(&self) -> Span<usize> { use Error::*; // this is not actually used in into_snippet, because it's provided // a specific file (parser errors are fixed per file anyway). so just use // a dummy file id let file = FileId(0); // TODO: there's probably a way to avoid the explicit dereferencing match self { InvalidToken(l) | UnrecognizedEOF { location: l, expected: _, } => Span { file, start: *l, end: *l, }, UnrecognizedToken { start, end, expected: _, } | ExtraToken { start, end } => Span { file, start: *start, end: *end, }, LexError(err) => // TODO: is it really useful to have Location during lexing? { Span { file, start: err.span.start.absolute, end: err.span.end.absolute, } } } } pub fn into_snippet(self, src: &SourceFile) -> Snippet { let span = self.get_span(); let error_msg = format!("{}", self); let (line_start, source) = src.surrounding_lines(span.start, span.end); let source_start = src.lines.offset_at_line_number(line_start); Snippet { title: Some(Annotation { label: Some("parse error:".to_string()), id: None, annotation_type: AnnotationType::Error, }), footer: vec![], slices: vec![Slice { source, line_start, origin: Some(src.path.clone()), fold: false, annotations: vec![SourceAnnotation { label: error_msg, annotation_type: AnnotationType::Error, range: (span.start - source_start, span.end - source_start), }], }], } } }
use std::{ collections::{BTreeSet, HashMap}, sync::{ atomic::{AtomicUsize, Ordering}, Arc, Mutex, }, }; use async_trait::async_trait; use data_types::{ColumnSet, CompactionLevel, ParquetFile, ParquetFileParams, Timestamp}; use datafusion::physical_plan::SendableRecordBatchStream; use iox_time::Time; use observability_deps::tracing::info; use uuid::Uuid; use compactor::{DynError, ParquetFilesSink, PartitionInfo, PlanIR}; use crate::{display::total_size, display_size, format_files}; /// Simulates the result of running a compaction plan that /// produces multiple parquet files. /// /// In general, since the Parquet format has high and variable /// compression, it is not possible to predict what the output size of /// a particular input will be, given just the schema and input /// sizes. The output size depends heavily on the actual input data as /// well as the parquet writer settings (e.g. row group size). /// /// Rather than writing actual files during compactor tests, this /// simulator produces [`ParquetFileParams`] describing a simulated /// output of compacting one or more input parquet files, using rules /// which can be alterted to testing how the compactor behaves /// in different scenarios. /// /// Scenarios that this simulator may offer in the future include: /// /// 1. The output file size is significantly smaller than the /// sum of the input files due to deduplication & delete application /// /// 2. The distribution of data is nonuniform between the start and /// end boundaries of the input files /// /// 3. The output file time ranges are different than the the union of /// the input files, due to delete predicate application or non /// uniform distribution. #[derive(Debug, Default)] pub struct ParquetFileSimulator { /// entries that are added to while running run_log: Arc<Mutex<Vec<String>>>, /// Used to generate run ids for display run_id_generator: AtomicUsize, /// Used to track total bytes written (to help judge efficiency changes) bytes_written: Arc<AtomicUsize>, /// map of bytes written per plan type bytes_written_per_plan: Arc<Mutex<HashMap<String, usize>>>, } impl std::fmt::Display for ParquetFileSimulator { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ParquetFileSimulator") } } impl ParquetFileSimulator { /// Create a new simulator for creating parquet files, which /// appends its output to `run_log` pub fn new( run_log: Arc<Mutex<Vec<String>>>, bytes_written: Arc<AtomicUsize>, bytes_written_per_plan: Arc<Mutex<HashMap<String, usize>>>, ) -> Self { Self { run_log, run_id_generator: AtomicUsize::new(0), bytes_written, bytes_written_per_plan, } } fn next_run_id(&self) -> usize { self.run_id_generator.fetch_add(1, Ordering::SeqCst) } } #[async_trait] impl ParquetFilesSink for ParquetFileSimulator { async fn stream_into_file_sink( &self, _streams: Vec<SendableRecordBatchStream>, partition_info: Arc<PartitionInfo>, target_level: CompactionLevel, plan_ir: &PlanIR, ) -> Result<Vec<ParquetFileParams>, DynError> { // compute max_l0_created_at let max_l0_created_at: Time = plan_ir .input_files() .iter() .map(|f| f.file.max_l0_created_at) .max() .expect("max_l0_created_at should have value") .into(); info!("Simulating {plan_ir}"); let (plan_type, split_times): (String, &[i64]) = match plan_ir { // pretend None and Compact are empty splits PlanIR::None { .. } => (plan_ir.to_string(), &[]), PlanIR::Compact { files: _, .. } => (plan_ir.to_string(), &[]), PlanIR::Split { files: _, split_times, .. } => { let plan_type = format!("{plan_ir}(split_times={split_times:?})"); (plan_type, split_times) } }; let input_files: Vec<_> = plan_ir .input_files() .iter() .map(|f| SimulatedFile::from(&f.file)) .collect(); let input_parquet_files: Vec<_> = plan_ir .input_files() .iter() .map(|f| f.file.clone()) .collect(); let column_set = overall_column_set(input_parquet_files.iter()); let output_files = even_time_split(&input_files, split_times, target_level); let partition_info = partition_info.as_ref(); let bytes_written: i64 = input_parquet_files.iter().map(|f| f.file_size_bytes).sum(); // Compute final output let output_params: Vec<_> = output_files .into_iter() .map(|f| { f.into_parquet_file_params(max_l0_created_at, column_set.clone(), partition_info) }) .collect(); // record what the simulator did let run = SimulatedRun { run_id: self.next_run_id(), plan_type, input_parquet_files, output_params: output_params.clone(), }; self.run_log.lock().unwrap().extend(run.into_strings()); self.bytes_written .fetch_add(bytes_written as usize, Ordering::Relaxed); self.bytes_written_per_plan .lock() .unwrap() .entry(plan_ir.to_string()) .and_modify(|e| *e += bytes_written as usize) .or_insert(bytes_written as usize); Ok(output_params) } fn as_any(&self) -> &dyn std::any::Any { self } } /// Parameters of a `ParquetFile` that are part of the simulation #[derive(Debug, Clone, Copy)] pub struct SimulatedFile { /// the min timestamp of data in this file pub min_time: Timestamp, /// the max timestamp of data in this file pub max_time: Timestamp, /// file size in bytes pub file_size_bytes: i64, /// the number of rows of data in this file pub row_count: i64, /// the compaction level of the file pub compaction_level: CompactionLevel, } impl From<&ParquetFile> for SimulatedFile { fn from(value: &ParquetFile) -> Self { Self { min_time: value.min_time, max_time: value.max_time, file_size_bytes: value.file_size_bytes, row_count: value.row_count, compaction_level: value.compaction_level, } } } impl std::fmt::Display for SimulatedFile { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ID.{}", self.compaction_level as i16) } } impl SimulatedFile { fn into_parquet_file_params( self, max_l0_created_at: Time, column_set: ColumnSet, partition_info: &PartitionInfo, ) -> ParquetFileParams { let Self { min_time, max_time, file_size_bytes, row_count, compaction_level, } = self; ParquetFileParams { namespace_id: partition_info.namespace_id, table_id: partition_info.table.id, partition_id: partition_info.partition_id(), object_store_id: Uuid::new_v4(), min_time, max_time, file_size_bytes, row_count, compaction_level, created_at: Timestamp::new(1), column_set, max_l0_created_at: max_l0_created_at.into(), } } } /// Records the information about what the simulator did, for testing /// purposes #[derive(Debug, Clone)] pub struct SimulatedRun { run_id: usize, // fields are used in testing plan_type: String, input_parquet_files: Vec<ParquetFile>, output_params: Vec<ParquetFileParams>, } impl SimulatedRun { /// Convert this simulated run into a set of human readable strings fn into_strings(self) -> impl Iterator<Item = String> { let Self { run_id, plan_type, input_parquet_files, output_params, } = self; let input_title = format!( "**** Simulation run {}, type={}. {} Input Files, {} total:", run_id, plan_type, input_parquet_files.len(), display_size(total_size(&input_parquet_files)) ); let output_title = format!( "**** {} Output Files (parquet_file_id not yet assigned), {} total:", output_params.len(), display_size(total_size(&output_params)) ); // hook up inputs and outputs format_files(input_title, &input_parquet_files) .into_iter() .chain(format_files(output_title, &output_params).into_iter()) } } fn overall_column_set<'a>(files: impl IntoIterator<Item = &'a ParquetFile>) -> ColumnSet { let all_columns = files .into_iter() .fold(BTreeSet::new(), |mut columns, file| { columns.extend(file.column_set.iter().cloned()); columns }); ColumnSet::new(all_columns) } /// Calculate simulated output files based on splitting files /// according to `split_times`, assuming the data is uniformly /// distributed between min and max times fn even_time_split( files: &[SimulatedFile], split_times: &[i64], target_level: CompactionLevel, ) -> Vec<SimulatedFile> { let overall_min_time = files.iter().map(|f| f.min_time).min().unwrap(); let overall_max_time = files.iter().map(|f| f.max_time).max().unwrap(); let overall_time_range = overall_max_time - overall_min_time + 1; let total_input_rows: i64 = files.iter().map(|f| f.row_count).sum(); let total_input_size: i64 = files.iter().map(|f| f.file_size_bytes).sum(); // verify split times invariants. let mut last_split = 0; for split in split_times { assert!( split > &last_split, "split times {last_split} {split} must be in ascending order", ); assert!( // split time is the last ns in the resulting 'left' file. If split time // matches the last ns of the input file, the input file does not need // split at this time. Timestamp::new(*split) < overall_max_time, "split time {} must be less than time range max {}", split, overall_max_time.get() ); last_split = *split; } // compute the timeranges data each file will have let mut last_time = overall_min_time; let mut time_ranges: Vec<_> = split_times .iter() .map(|time| { let time = Timestamp::new(*time); let ret = (last_time, time); last_time = time + 1; ret }) .collect(); // add the entry for the last bucket time_ranges.push((last_time, overall_max_time)); info!( ?overall_min_time, ?overall_max_time, ?overall_time_range, ?total_input_rows, ?total_input_size, ?time_ranges, "creating output file from input files" ); let mut simulated_files: Vec<_> = time_ranges .into_iter() .map(|(min_time, max_time)| { let p = ((max_time - min_time).get() as f64 + 1.0) / ((overall_time_range).get() as f64); let file_size_bytes = (total_input_size as f64 * p) as i64; let row_count = (total_input_rows as f64 * p) as i64; let compaction_level = target_level; info!( ?p, ?min_time, ?max_time, ?file_size_bytes, ?row_count, ?compaction_level, "creating output file with fraction of output" ); SimulatedFile { min_time, max_time, file_size_bytes, row_count, compaction_level, } }) .collect(); // make sure we have assigned all bytes and rows to one of the output files let total_output_size: i64 = simulated_files.iter().map(|f| f.file_size_bytes).sum(); let total_output_rows: i64 = simulated_files.iter().map(|f| f.row_count).sum(); // adjust the row counts / bytes in the final file to ensure that // the same number of bytes went in and went out let last_file = simulated_files.last_mut().unwrap(); last_file.file_size_bytes += total_input_size - total_output_size; last_file.row_count += total_input_rows - total_output_rows; simulated_files }
extern crate coinbase_pro_rs; extern crate futures; extern crate tokio; use coinbase_pro_rs::structs::wsfeed::*; use coinbase_pro_rs::{WSFeed, WS_SANDBOX_URL}; use futures::{Future, Stream}; fn main() { let stream = WSFeed::new(WS_SANDBOX_URL, &["BTC-USD"], &[ChannelType::Heartbeat]); let f = stream.take(10).for_each(|msg| { match msg { Message::Heartbeat { sequence, last_trade_id, time, .. } => println!("{}: seq:{} id{}", time, sequence, last_trade_id), Message::Error { message } => println!("Error: {}", message), Message::InternalError(_) => panic!("internal_error"), other => println!("{:?}", other), } Ok(()) }); tokio::run(f.map_err(|_| panic!("stream fail"))); }
use std::fs; use std::io::BufReader; use regex::Regex; use std::rc::Rc; use std::error; use std::fmt; mod constants { pub const MAGIC_SAZ: &[u8; 4] = b"\x50\x4B\x03\x04"; pub const MAGIC_SAZ_EMPTY: &[u8; 4] = b"\x50\x4B\x05\x06"; pub const MAGIC_SAZ_SPANNED: &[u8; 4] = b"\x50\x4B\x07\x08"; } type Result<T> = std::result::Result<T, SazError>; #[derive(Debug)] /// Library Error pub enum SazError { /// SAZ/ZIP file is empty Empty, /// SAZ/ZIP file is spanned Spanned, /// SAZ/ZIP file is invalid Invalid, /// Failure in reading file Error, } impl fmt::Display for SazError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SazError::Empty => write!(f, "SAZ file is empty"), SazError::Spanned => write!(f, "SAZ file is spanned"), SazError::Invalid => write!(f, "SAZ file is invalid"), SazError::Error => write!(f, "Error reading file"), } } } impl error::Error for SazError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match *self { SazError::Empty => None, SazError::Spanned => None, SazError::Invalid => None, SazError::Error => None, } } } #[derive(Clone, Debug)] struct SazFile { path: String, size: u64, contents: Rc<String>, } impl SazFile { fn new(path: &String, size: u64, contents: Rc<String>) -> SazFile { SazFile { path: path.to_string(), size: size, contents: contents.clone(), } } } #[derive(Clone, Debug)] /// This struct represent a single SAZ session pub struct SazSession { /// Identifier pub index: u32, /// Http Status Code pub result: u32, /// Request URL pub url: String, /// HTTP Body length in bytes pub body: u32, /// File with Request information pub file_request: String, /// File with Response information pub file_response: String, /// Contents of Request file pub file_request_contents: Rc<String>, /// Contents of Response file pub file_response_contents: Rc<String>, } impl SazSession { fn new( idx: u32, httpres: u32, httpurl: &str, httpbody: u32, frequest: &String, fresponse: &String, frequest_contents: &Rc<String>, fresponse_contents: &Rc<String>, ) -> SazSession { SazSession { index: idx, result: httpres, url: httpurl.to_string(), body: httpbody, file_request: frequest.clone(), file_response: fresponse.clone(), file_request_contents: frequest_contents.clone(), file_response_contents: fresponse_contents.clone(), } } } fn check_file_validity(filename: &str) -> Result<()> { let data = fs::read(filename); if let Ok(d) = data { let slice = &d[..4]; if slice == constants::MAGIC_SAZ { return Ok(()); } else if slice == constants::MAGIC_SAZ_EMPTY { return Err(SazError::Empty); } else if slice == constants::MAGIC_SAZ_SPANNED { return Err(SazError::Spanned); } else { return Err(SazError::Invalid); } } else { return Err(SazError::Error); } } fn zip_contents(filename: &str) -> Result<Vec<SazFile>> { check_file_validity(filename)?; let mut raw_folder: bool = false; let mut list: Vec<SazFile> = vec![]; let file = fs::File::open(filename).unwrap(); let reader = BufReader::new(file); let mut archive = zip::ZipArchive::new(reader).unwrap(); for i in 0..archive.len() { let mut zipped_file = archive.by_index(i).unwrap(); let outpath = match zipped_file.enclosed_name() { Some(path) => path, None => continue, }; if !zipped_file.name().ends_with('/') { let file_path = outpath.to_str().unwrap().to_string(); let file_size = zipped_file.size(); let mut writer: Vec<u8> = vec![]; let _ = std::io::copy(&mut zipped_file, &mut writer); let file_contents = unsafe { std::str::from_utf8_unchecked(&writer).to_string() }; let zippedfile = SazFile::new(&file_path, file_size, Rc::new(file_contents)); list.push(zippedfile); } else { if zipped_file.name() == "raw/" { raw_folder = true; } } } if !raw_folder { return Err(SazError::Invalid); } Ok(list) } fn get_file_from_list<'a>(list: &'a [SazFile], filename: &str) -> &'a SazFile { let result = list.iter().find(|&f| f.path == filename).unwrap(); result } fn get_sessions_total(list: &[SazFile]) -> (u32, usize) { let mut leading_zeroes: usize = 0; let mut sessions_total: u32 = 0; for zipped_file in list { let mut splitted = zipped_file.path.split('_'); let splitted2 = splitted.nth(0); match splitted2 { Some(inner) => { let number = inner.split('/').nth(1); match number { Some(inner2) => { leading_zeroes = inner2.len(); let parsed = inner2.parse::<u32>().unwrap(); if sessions_total < parsed { sessions_total = parsed; } } None => continue, } } None => continue, } } (sessions_total, leading_zeroes) } fn regex_get_url(contents: &str) -> &str { let re = Regex::new(r"(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE) (.*) HTTP/1.1").unwrap(); let capture = re.captures(contents).unwrap(); let value = capture.get(2).unwrap().as_str(); value } fn regex_get_http_status(contents: &str) -> u32 { let re = Regex::new(r"HTTP.*([0-9][0-9][0-9])").unwrap(); let capture = re.captures(contents).unwrap(); let value = capture.get(1).unwrap().as_str().parse::<u32>().unwrap(); value } fn regex_get_content_length(contents: &str) -> u32 { let mut value: u32 = 0; let re = Regex::new(r"Content-Length:\s(\d+)").unwrap(); let capture = re.captures(contents); match capture { Some(captured) => { value = captured.get(1).unwrap().as_str().parse::<u32>().unwrap(); } None => return value, } value } /// /// Parses given file. /// Returns Result<Vec<SazSession>> /// /// # Arguments /// /// * `fname` - File name that represents the SAZ file /// /// # Errors /// /// Errors out if not possible to read file. /// /// # Example /// /// ``` rust /// use std::env; /// /// use sazparser; /// /// fn main() { /// let args: Vec<String> = env::args().collect(); /// /// // args[1] will be the file to parse /// let saz = sazparser::parse(&*args[1]); /// /// match saz { /// Ok(v) => { /// // use parsed information /// println!("{:?}", v); /// }, /// Err(e) => { /// panic!("{}", e); /// }, /// } /// } ///``` /// pub fn parse(fname: &str) -> Result<Vec<SazSession>> { let mut entries: Vec<SazSession> = vec![]; let list = zip_contents(&fname)?; let (total_sessions, leading_zeroes) = get_sessions_total(&list); for n in 1..=total_sessions { let request_file_name = format!("raw/{:0fill$}_c.txt", n, fill = leading_zeroes); let response_file_name = format!("raw/{:0fill$}_s.txt", n, fill = leading_zeroes); let request_file = get_file_from_list(&list, &*request_file_name); let response_file = get_file_from_list(&list, &*response_file_name); let url = regex_get_url(&*request_file.contents); let httpstatus = regex_get_http_status(&*response_file.contents); let contentlength = regex_get_content_length(&*response_file.contents); let entry = SazSession::new( n, httpstatus, url, contentlength, &request_file_name, &response_file_name, &request_file.contents, &response_file.contents, ); entries.push(entry); } Ok(entries) }
use crate::ast::AST; use crate::lexer::LexerError; use crate::token::Token; use crate::Position; use std::error; use std::fmt; /// The `Result` of `Parser`. #[derive(Debug)] pub enum ParseResult<T> { /// A success value. Ok(T), /// An error value. Err(ParseError), /// No expressions found; `Eof` must be returned when the end of the file is reached. Eof, } impl<T> ParseResult<T> { /// Returns `true` if the result is `Ok`. pub fn is_ok(&self) -> bool { match self { ParseResult::Ok(_) => true, _ => false, } } /// Returns `true` if the result is `Err`. pub fn is_err(&self) -> bool { match self { ParseResult::Err(_) => true, _ => false, } } /// Returns `true` if the result is `Eof`. pub fn is_eof(&self) -> bool { match self { ParseResult::Eof => true, _ => false, } } /// Unwrap an `Ok` value. pub fn unwrap(self) -> T { match self { ParseResult::Ok(t) => t, ParseResult::Err(e) => panic!("unwrapped error value: {}", e), ParseResult::Eof => panic!("unwrapped end of file value"), } } /// Map an `Ok` value. pub fn map<U>(self, op: impl FnOnce(T) -> U) -> ParseResult<U> { match self { ParseResult::Ok(t) => ParseResult::Ok(op(t)), ParseResult::Err(e) => ParseResult::Err(e), ParseResult::Eof => ParseResult::Eof, } } } /// The error type of `Parser`. #[derive(Debug)] pub enum ParseError { /// The next token in the token stream was not expected. UnexpectedToken(Token), /// The next expression was not expected. UnexpectedExpression(AST), /// End of file found, but expected token. UnexpectedEof { expected: &'static str }, /// An error happened in the lexer. LexerError(LexerError), /// A different error. Other { /// The error value. error: Box<dyn error::Error>, /// The position at which the error happened. position: Position, }, } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::ParseError::*; match self { UnexpectedToken(Token { token, position }) => { write!(f, "unexpected token at {}: {}", position, token) } UnexpectedExpression(AST { ast, position }) => { write!(f, "unexpected expression at {}: {:?}", position, ast) } UnexpectedEof { expected } => write!(f, "found end of file, but expected {}", expected), LexerError(e) => write!(f, "{}", e), Other { error, position } => write!(f, "error at {}: {}", position, error), } } } impl error::Error for ParseError {}
fn to_string<T: Into<i64>>(num: T) -> String { format!("{}", num.into()) } fn main() { let foo = &*to_string(0); println!("{}", foo); }
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. /// Settings to apply to a connection established by `accept()`. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct StreamingServerListenerSocketSettings { /// Send buffer size (in bytes). pub send_buffer_size_in_bytes: usize, /// Receive buffer size (in bytes). pub receive_buffer_size_in_bytes: usize, /// Idle for how many seconds before TCP keep-alive is started? pub idles_before_keep_alive_seconds: u16, /// Interval in seconds between TCP keep-alive probes. pub keep_alive_interval_seconds: u16, /// Maximum number of TCP keep-alive probes to send. pub maximum_keep_alive_probes: u16, /// How long to linger (in seconds). pub linger_seconds: u16, /// How long to linger in the TCP FIN-WAIT2 state (in seconds). pub linger_in_FIN_WAIT2_seconds: u16, /// Zero is rounded up to one. /// /// How many TCP SYN segments to try to transmit before giving up on a connection attempt? pub maximum_SYN_transmits: u16, /// Back log of prior connections to honour (typically capped by Linux to 128). pub back_log: u32, } impl Default for StreamingServerListenerSocketSettings { #[inline(always)] fn default() -> Self { StreamingServerListenerSocketSettings { send_buffer_size_in_bytes: 64 * 1024, receive_buffer_size_in_bytes: 64 * 1024, idles_before_keep_alive_seconds: 60, keep_alive_interval_seconds: 5, maximum_keep_alive_probes: 5, linger_seconds: 60, linger_in_FIN_WAIT2_seconds: 0, maximum_SYN_transmits: 1, back_log: 128, } } }
#![allow(non_snake_case)] use evm::VMTestPatch; use jsontests::test_transaction; use serde_json::Value; // Log format is broken for input limits tests #[test] #[ignore] fn inputLimitsLight() { let TESTS: Value = serde_json::from_str(include_str!("../res/files/vmInputLimitsLight/vmInputLimitsLight.json")).unwrap(); for (name, value) in TESTS.as_object().unwrap().iter() { print!("\t{} ... ", name); match test_transaction(name, VMTestPatch::default(), value, true) { Ok(false) => panic!("test inputLimitsLight::{} failed", name), _ => (), } } } #[test] #[ignore] fn inputLimits() { let TESTS: Value = serde_json::from_str(include_str!("../res/files/vmInputLimits/vmInputLimits.json")).unwrap(); for (name, value) in TESTS.as_object().unwrap().iter() { print!("\t{} ... ", name); match test_transaction(name, VMTestPatch::default(), value, true) { Ok(false) => panic!("test inputLimits::{} failed", name), _ => (), } } }
use std::env; use std::os::unix::fs::PermissionsExt; fn main() -> std::io::Result<()> { let args: Vec<_> = env::args().collect(); if args.len() < 2 { panic!("Usage: {} file", args[0]); } let f = ::std::env::args().nth(1).unwrap(); let metadata = std::fs::metadata(f)?; let perm = metadata.permissions(); println!("{:o}", perm.mode()); Ok(()) }
/// Trait for fixed size arrays. pub unsafe trait Array { /// The array’s element type type Item; #[doc(hidden)] /// The smallest index type that indexes the array. type Index: Index; #[doc(hidden)] fn as_ptr(&self) -> *const Self::Item; #[doc(hidden)] fn as_mut_ptr(&mut self) -> *mut Self::Item; #[doc(hidden)] fn capacity() -> usize; } pub trait Index: PartialEq + Copy { fn to_usize(self) -> usize; fn from(usize) -> Self; } use std::slice::from_raw_parts; pub trait ArrayExt: Array { #[inline(always)] fn as_slice(&self) -> &[Self::Item] { unsafe { from_raw_parts(self.as_ptr(), Self::capacity()) } } } impl<A> ArrayExt for A where A: Array, { } impl Index for u8 { #[inline(always)] fn to_usize(self) -> usize { self as usize } #[inline(always)] fn from(ix: usize) -> Self { ix as u8 } } impl Index for u16 { #[inline(always)] fn to_usize(self) -> usize { self as usize } #[inline(always)] fn from(ix: usize) -> Self { ix as u16 } } impl Index for u32 { #[inline(always)] fn to_usize(self) -> usize { self as usize } #[inline(always)] fn from(ix: usize) -> Self { ix as u32 } } impl Index for usize { #[inline(always)] fn to_usize(self) -> usize { self } #[inline(always)] fn from(ix: usize) -> Self { ix } } macro_rules! fix_array_impl { ($index_type:ty, $len:expr ) => ( unsafe impl<T> Array for [T; $len] { type Item = T; type Index = $index_type; #[inline(always)] fn as_ptr(&self) -> *const T { self as *const _ as *const _ } #[inline(always)] fn as_mut_ptr(&mut self) -> *mut T { self as *mut _ as *mut _} #[inline(always)] fn capacity() -> usize { $len } } ) } macro_rules! fix_array_impl_recursive { ($index_type:ty, ) => (); ($index_type:ty, $len:expr, $($more:expr,)*) => ( fix_array_impl!($index_type, $len); fix_array_impl_recursive!($index_type, $($more,)*); ); } fix_array_impl_recursive!( u8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 40, 48, 50, 56, 64, 72, 96, 100, 128, 160, 192, 200, 224, ); fix_array_impl_recursive!( u16, 256, 384, 512, 768, 1024, 2048, 4096, 8192, 16384, 32768, ); // This array size doesn't exist on 16-bit #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] fix_array_impl_recursive!(u32, 1 << 16,);
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. /// Why was a `TLSA` or `SMIMEA` record ignored? #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum DnsBasedAuthenticationOfNamedEntitiesResourceRecordIgnoredBecauseReason { /// The certificate usage was unassigned. UnassignedCertificateUsage(u8), /// The certificate usage was private. PrivateCertificateUsage, /// The selector was unassigned. UnassignedSelector(u8), /// The selector was private. PrivateSelector, /// The matching type was unassigned. UnassignedMatchingType(u8), /// The matching type was private. PrivateMatchingType, }
use proconio::input; fn main() { input! { n: usize, m: usize, a: [i64; n], }; let mut cum_sum = vec![0; n + 1]; for i in 0..n { cum_sum[i+1] = cum_sum[i] + a[i]; } let mut s = 0; for i in 0..m { s += a[i] * (i + 1) as i64; } let mut ans = s; for i in m..n { s -= cum_sum[i] - cum_sum[i - m]; s += a[i] * m as i64; ans = ans.max(s); } println!("{}", ans); }
extern crate digest; extern crate skein; use digest::Digest; use digest::generic_array::typenum::{U32, U64}; fn read_files(path: &str) -> (Vec<u8>, Vec<u8>) { use std::io::Read; let mut input = std::fs::File::open(format!("tests/data/{}.input.bin", path)).unwrap(); let mut output = std::fs::File::open(format!("tests/data/{}.output.bin", path)).unwrap(); let mut buf = Vec::new(); input.read_to_end(&mut buf).unwrap(); let input = buf.clone(); buf.clear(); output.read_to_end(&mut buf).unwrap(); let output = buf; (input, output) } #[test] fn skein_256() { for path in &[ "skein_256/test32_0", "skein_256/test32_17", "skein_256/test32_64" ] { let (input, output) = read_files(path); let hash = skein::Skein256::<U32>::digest(&input); assert_eq!(&hash[..], &output[..]) } for path in &[ "skein_256/test64_0", "skein_256/test64_17", "skein_256/test64_64" ] { let (input, output) = read_files(path); let hash = skein::Skein256::<U64>::digest(&input); assert_eq!(&hash[..], &output[..]) } } #[test] fn skein_512() { for path in &[ "skein_512/test32_0", "skein_512/test32_17", "skein_512/test32_64" ] { let (input, output) = read_files(path); let hash = skein::Skein512::<U32>::digest(&input); assert_eq!(&hash[..], &output[..]) } for path in &[ "skein_512/test64_0", "skein_512/test64_17", "skein_512/test64_64" ] { let (input, output) = read_files(path); let hash = skein::Skein512::<U64>::digest(&input); assert_eq!(&hash[..], &output[..]) } } #[test] fn skein_1024() { for path in &[ "skein_1024/test32_0", "skein_1024/test32_17", "skein_1024/test32_64" ] { let (input, output) = read_files(path); let hash = skein::Skein1024::<U32>::digest(&input); assert_eq!(&hash[..], &output[..]) } for path in &[ "skein_1024/test64_0", "skein_1024/test64_17", "skein_1024/test64_64" ] { let (input, output) = read_files(path); let hash = skein::Skein1024::<U64>::digest(&input); assert_eq!(&hash[..], &output[..]) } }
fn give_closure() -> Box<Fn(u32) -> u32> { Box::new(move |x: u32| -> u32 { x + 2 }) } fn main() { let mut x = 3; { let mut addnum = move |number: u32| { x += number; println!("{}", x); }; addnum(10); } println!("{}", x); let result = give_closure(); println!("{}", result(10)); }
use std::sync::Arc; use sourcerenderer_core::graphics::{ Backend, BarrierAccess, BarrierSync, BindingFrequency, CommandBuffer, Format, PipelineBinding, SampleCount, Texture, TextureDimension, TextureInfo, TextureLayout, TextureUsage, TextureView, TextureViewInfo, }; use sourcerenderer_core::{ Platform, Vec2UI, }; use crate::renderer::render_path::RenderPassParameters; use crate::renderer::renderer_resources::{ HistoryResourceEntry, RendererResources, }; use crate::renderer::shader_manager::{ RayTracingPipelineHandle, RayTracingPipelineInfo, ShaderManager, }; pub struct RTShadowPass { pipeline: RayTracingPipelineHandle, } impl RTShadowPass { pub const SHADOWS_TEXTURE_NAME: &'static str = "RTShadow"; pub fn new<P: Platform>( resolution: Vec2UI, resources: &mut RendererResources<P::GraphicsBackend>, shader_manager: &mut ShaderManager<P>, ) -> Self { resources.create_texture( Self::SHADOWS_TEXTURE_NAME, &TextureInfo { dimension: TextureDimension::Dim2D, format: Format::RGBA8UNorm, width: resolution.x, height: resolution.y, depth: 1, mip_levels: 1, array_length: 1, samples: SampleCount::Samples1, usage: TextureUsage::STORAGE | TextureUsage::SAMPLED, supports_srgb: false, }, false, ); let pipeline = shader_manager.request_ray_tracing_pipeline(&RayTracingPipelineInfo { ray_gen_shader: "shaders/shadows.rgen.spv", closest_hit_shaders: &["shaders/shadows.rchit.spv"], miss_shaders: &["shaders/shadows.rmiss.spv"], }); Self { pipeline } } pub fn execute<P: Platform>( &mut self, cmd_buffer: &mut <P::GraphicsBackend as Backend>::CommandBuffer, pass_params: &RenderPassParameters<'_, P>, depth_name: &str, acceleration_structure: &Arc<<P::GraphicsBackend as Backend>::AccelerationStructure>, blue_noise: &Arc<<P::GraphicsBackend as Backend>::TextureView>, blue_noise_sampler: &Arc<<P::GraphicsBackend as Backend>::Sampler>, ) { let texture_uav = pass_params.resources.access_view( cmd_buffer, Self::SHADOWS_TEXTURE_NAME, BarrierSync::COMPUTE_SHADER | BarrierSync::RAY_TRACING, BarrierAccess::STORAGE_WRITE, TextureLayout::Storage, true, &TextureViewInfo::default(), HistoryResourceEntry::Current, ); let depth = pass_params.resources.access_view( cmd_buffer, depth_name, BarrierSync::RAY_TRACING | BarrierSync::COMPUTE_SHADER, BarrierAccess::SAMPLING_READ, TextureLayout::Sampled, false, &TextureViewInfo::default(), HistoryResourceEntry::Current, ); let pipeline = pass_params.shader_manager.get_ray_tracing_pipeline(self.pipeline); cmd_buffer.set_pipeline(PipelineBinding::RayTracing(&pipeline)); cmd_buffer.bind_acceleration_structure( BindingFrequency::Frequent, 0, acceleration_structure, ); cmd_buffer.bind_storage_texture(BindingFrequency::Frequent, 1, &*texture_uav); cmd_buffer.bind_sampling_view_and_sampler( BindingFrequency::Frequent, 2, &*depth, pass_params.resources.linear_sampler(), ); cmd_buffer.bind_sampling_view_and_sampler( BindingFrequency::Frequent, 3, blue_noise, blue_noise_sampler, ); let info = texture_uav.texture().info(); cmd_buffer.flush_barriers(); cmd_buffer.finish_binding(); cmd_buffer.trace_ray(info.width, info.height, 1); } }
use crate::error::BlobError; use serde::{Deserialize, Serialize}; pub fn read_u64<R: std::io::Read>(r: &mut R) -> Result<u64, BlobError> { let mut buf = [0u8; 8]; r.read_exact(&mut buf)?; Ok(bincode::deserialize(&buf[..])?) } pub fn write_u64<W: std::io::Write>(w: &mut W, dat: u64) -> anyhow::Result<()> { let ec = bincode::serialize(&dat)?; assert_eq!(ec.len(), 8); Ok(w.write_all(&ec)?) } #[derive(Debug, PartialEq)] pub struct Blob { k: Vec<u8>, v: Vec<u8>, } impl Blob { pub fn from<K: Serialize, V: Serialize>(k: &K, v: &V) -> Result<Blob, bincode::Error> { Ok(Blob { k: bincode::serialize(k)?, v: bincode::serialize(v)?, }) } pub fn out<W: std::io::Write>(&self, w: &mut W) -> std::io::Result<()> { //no way serializing a usize can fail let klen = bincode::serialize(&self.k.len()).unwrap(); let vlen = bincode::serialize(&self.v.len()).unwrap(); w.write_all(&klen)?; w.write_all(&vlen)?; w.write_all(&self.k)?; w.write_all(&self.v)?; Ok(()) } pub fn read<R: std::io::Read>(r: &mut R) -> anyhow::Result<Blob> { //if klen == 0, that is free space let klen = read_u64(r)? as usize; let vlen = read_u64(r)? as usize; let mut k = vec![0u8; klen]; let mut v = vec![0u8; vlen]; r.read_exact(&mut k)?; r.read_exact(&mut v)?; Ok(Blob { k, v }) } pub fn get_v<'a, V: Deserialize<'a>>(&'a self) -> Result<V, BlobError> { Ok(bincode::deserialize(&self.v[..])?) } pub fn len(&self) -> u64 { (16 + self.k.len() + self.v.len()) as u64 } //Note added [lib] name="d5_hashmap" and made hash pub pub fn k_hash(&self, seed: u64) -> u64 { d5_hashmap::hash(seed, &self.k) } pub fn key_match(&self, rhs: &Self) -> bool { self.k == rhs.k } } #[cfg(test)] mod test { use super::*; use serde_derive::*; #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct Point<T> { x: T, y: T, } #[test] fn test_read_write_string() { let k: i32 = 87; let v = "hello world"; let blob = Blob::from(&k, &v).unwrap(); { let mut fout = std::fs::OpenOptions::new() .write(true) .create(true) .open("test_data/t_rblob.dat") .unwrap(); blob.out(&mut fout).unwrap(); } let mut fin = std::fs::File::open("test_data/t_rblob.dat").unwrap(); let b2 = Blob::read(&mut fin).unwrap(); let v2: String = b2.get_v().unwrap(); assert_eq!(&v2, "hello world"); //It's just Bytes let p: Point<i32> = b2.get_v().unwrap(); assert_eq!(p, Point { x: 11, y: 0 }); } #[test] pub fn test_ser64() { let ndat = bincode::serialize(&0u64).unwrap(); assert_eq!(ndat.len(), 8); } }
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded FIXME #23616 // ignore-cloudabi no std::fs use std::{fs, net}; fn assert_both<T: Send + Sync>() {} fn assert_send<T: Send>() {} fn main() { assert_both::<fs::File>(); assert_both::<fs::Metadata>(); assert_both::<fs::ReadDir>(); assert_both::<fs::DirEntry>(); assert_both::<fs::OpenOptions>(); assert_both::<fs::Permissions>(); assert_both::<net::TcpStream>(); assert_both::<net::TcpListener>(); assert_both::<net::UdpSocket>(); assert_both::<net::SocketAddr>(); assert_both::<net::SocketAddrV4>(); assert_both::<net::SocketAddrV6>(); assert_both::<net::Ipv4Addr>(); assert_both::<net::Ipv6Addr>(); }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use hex; use std::fmt; use std::str; use crate::errors::BlobIdParseError; use fidl_fuchsia_pkg as fidl; #[cfg(test)] use proptest_derive::Arbitrary; pub(crate) const BLOB_ID_SIZE: usize = 32; //FIXME: wrap fidl::BlobId instead of the inner array when it implements Copy. /// Convenience wrapper type for the autogenerated FIDL `BlobId`. #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] #[cfg_attr(test, derive(Arbitrary))] pub struct BlobId([u8; BLOB_ID_SIZE]); impl BlobId { /// Parse a `BlobId` from a string containing 32 lower-case hex encoded bytes. /// /// # Examples /// ``` /// let s = "00112233445566778899aabbccddeeffffeeddccbbaa99887766554433221100"; /// assert_eq!( /// BlobId::parse(s), /// s.parse() /// ); /// ``` pub fn parse(s: &str) -> Result<Self, BlobIdParseError> { s.parse() } /// Obtain a slice of bytes representing the `BlobId`. pub fn as_bytes(&self) -> &[u8] { &self.0[..] } } impl str::FromStr for BlobId { type Err = BlobIdParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let bytes = hex::decode(s)?; if bytes.len() != BLOB_ID_SIZE { return Err(BlobIdParseError::InvalidLength(bytes.len())); } if s.chars().any(|c| c.is_uppercase()) { return Err(BlobIdParseError::CannotContainUppercase); } let mut res: [u8; BLOB_ID_SIZE] = [0; BLOB_ID_SIZE]; res.copy_from_slice(&bytes[..]); Ok(Self(res)) } } impl From<[u8; BLOB_ID_SIZE]> for BlobId { fn from(bytes: [u8; BLOB_ID_SIZE]) -> Self { Self(bytes) } } impl From<fidl::BlobId> for BlobId { fn from(id: fidl::BlobId) -> Self { Self(id.merkle_root) } } impl From<BlobId> for fidl::BlobId { fn from(id: BlobId) -> Self { Self { merkle_root: id.0 } } } impl fmt::Display for BlobId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&hex::encode(self.0)) } } impl fmt::Debug for BlobId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.to_string()) } } /// Convenience wrapper type for the autogenerated FIDL `BlobInfo`. #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct BlobInfo { pub blob_id: BlobId, pub length: u64, } impl BlobInfo { pub fn new(blob_id: BlobId, length: u64) -> Self { BlobInfo { blob_id: blob_id, length: length } } } impl From<fidl::BlobInfo> for BlobInfo { fn from(info: fidl::BlobInfo) -> Self { BlobInfo { blob_id: info.blob_id.into(), length: info.length } } } impl From<BlobInfo> for fidl::BlobInfo { fn from(info: BlobInfo) -> Self { Self { blob_id: info.blob_id.into(), length: info.length } } } #[cfg(test)] mod tests { use super::*; use proptest::prelude::*; prop_compose! { fn invalid_hex_char()(c in "[[:ascii:]&&[^0-9a-fA-F]]") -> char { assert_eq!(c.len(), 1); c.chars().next().unwrap() } } proptest! { #[test] fn parse_is_inverse_of_display(ref id in "[0-9a-f]{64}") { prop_assert_eq!( id, &format!("{}", id.parse::<BlobId>().unwrap()) ); } #[test] fn parse_is_inverse_of_debug(ref id in "[0-9a-f]{64}") { prop_assert_eq!( id, &format!("{:?}", id.parse::<BlobId>().unwrap()) ); } #[test] fn parse_rejects_uppercase(ref id in "[0-9A-F]{64}") { prop_assert_eq!( id.parse::<BlobId>(), Err(BlobIdParseError::CannotContainUppercase) ); } #[test] fn parse_rejects_unexpected_characters(mut id in "[0-9a-f]{64}", c in invalid_hex_char(), index in 0usize..63) { id.remove(index); id.insert(index, c); prop_assert_eq!( id.parse::<BlobId>(), Err(BlobIdParseError::FromHexError( hex::FromHexError::InvalidHexCharacter { c: c, index: index } )) ); } #[test] fn parse_expects_even_sized_strings(ref id in "[0-9a-f]([0-9a-f]{2})*") { prop_assert_eq!( id.parse::<BlobId>(), Err(BlobIdParseError::FromHexError(hex::FromHexError::OddLength)) ); } #[test] fn parse_expects_precise_count_of_bytes(ref id in "([0-9a-f]{2})*") { prop_assume!(id.len() != BLOB_ID_SIZE * 2); prop_assert_eq!( id.parse::<BlobId>(), Err(BlobIdParseError::InvalidLength(id.len() / 2)) ); } #[test] fn blobid_fidl_conversions_are_inverses(id: BlobId) { let temp : fidl::BlobId = id.into(); prop_assert_eq!( id, BlobId::from(temp) ); } } }
use traits::*; fn main() { implement_trait(); default_implementation(); trait_as_parameter(); bound_syntax_parameters(); multiple_trait_bounds(); where_clause(); return_implementation(); get_largest(); trait_bond_conditional_methods(); } fn implement_trait() { let tweet = Tweet { username: String::from("horse_ebooks"), content: String::from("of course, as you probably already know, people"), reply: false, retweet: false, }; println!("In implement_trait: 1 new tweet: {}", tweet.summarize()); } fn default_implementation() { let article = NewsArticle { headline: String::from("Penguins win the Stanley Cup Championship!"), location: String::from("Pittsburgh, PA, USA"), author: String::from("Iceburgh"), content: String::from("The Pittsburgh Penguins once again are the best hockey team in the NHL."), }; println!("default_implementation: New article available! {}", article.summarize()); } fn trait_as_parameter() { let article = NewsArticle { headline: String::from("Penguins win the Stanley Cup Championship!"), location: String::from("Pittsburgh, PA, USA"), author: String::from("Iceburgh"), content: String::from("The Pittsburgh Penguins once again are the best hockey team in the NHL."), }; println!("trait_as_parameter"); notify(article); } fn bound_syntax_parameters() { let tweet1 = Tweet { username: String::from("horse_ebooks"), content: String::from("of course, as you probably already know, people"), reply: false, retweet: false, }; let tweet2 = Tweet { username: String::from("dog_ebooks"), content: String::from("woof!"), reply: false, retweet: false, }; println!("bound_syntax_parameters"); // Both parameters sent to bound_syntax_notify must have the same type to // avoid compile error. bound_syntax_notify(tweet1, tweet2); } fn multiple_trait_bounds() { let email = Email { to: String::from("abc@example.com"), from: String::from("deg@example.com"), subject: String::from("hi"), body: String::from("hello there!") }; multiple_trait_notify(email); } fn where_clause() { let email = Email { to: String::from("abc@example.com"), from: String::from("deg@example.com"), subject: String::from("hi"), body: String::from("hello there!") }; let article = NewsArticle { headline: String::from("Penguins win the Stanley Cup Championship!"), location: String::from("Pittsburgh, PA, USA"), author: String::from("Iceburgh"), content: String::from("The Pittsburgh Penguins once again are the best hockey team in the NHL."), }; multiple_trait_where_clause(article, email); } fn return_implementation() { let tweet = returns_summarizable(); println!("return_implementation tweet summarized: {}", tweet.summarize()); } fn returns_summarizable() -> impl Summary { Tweet { username: String::from("horse_ebooks"), content: String::from("of course, as you probably already know, people"), reply: false, retweet: false, } } /* You can only use impl Trait if you’re returning a single type. For example, this code that returns either a NewsArticle or a Tweet with the return type specified as impl Summary wouldn’t work: fn returns_summarizable(switch: bool) -> impl Summary { if switch { NewsArticle { headline: String::from("Penguins win the Stanley Cup Championship!"), location: String::from("Pittsburgh, PA, USA"), author: String::from("Iceburgh"), content: String::from("The Pittsburgh Penguins once again are the best hockey team in the NHL."), } } else { Tweet { username: String::from("horse_ebooks"), content: String::from("of course, as you probably already know, people"), reply: false, retweet: false, } } } */ /* This version of the largest function fails to compile, because when we made the largest function generic, it became possible for the list parameter to have types in it that don’t implement the Copy trait. Consequently, we wouldn’t be able to move the value out of list[0] and into the largest variable, resulting in an error. To call this code with only those types that implement the Copy trait, we can add Copy to the trait bounds of T! fn largest<T: PartialOrd>(list: &[T]) -> T { let mut largest = list[0]; for &item in list.iter() { if item > largest { largest = item; } } largest } */ fn largest<T: PartialOrd + Copy>(list: &[T]) -> T { let mut largest = list[0]; for &item in list.iter() { if item > largest { largest = item; } } largest } fn get_largest() { let number_list = vec![34, 50, 25, 100, 65]; let result = largest(&number_list); println!("The largest number is {}", result); let char_list = vec!['y', 'm', 'a', 'q']; let result = largest(&char_list); println!("The largest char is {}", result); } /* If we don’t want to restrict the largest function to the types that implement the Copy trait, we could specify that T has the trait bound Clone instead of Copy. Then we could clone each value in the slice when we want the largest function to have ownership. Using the clone function means we’re potentially making more heap allocations in the case of types that own heap data like String, and heap allocations can be slow if we’re working with large amounts of data. Another way we could implement largest is for the function to return a reference to a T value in the slice. If we change the return type to &T instead of T, thereby changing the body of the function to return a reference, we wouldn’t need the Clone or Copy trait bounds and we could avoid heap allocations. */ fn trait_bond_conditional_methods() { let p = Pair::new(1, 2); p.cmp_display() }
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct PatternDto { pub pattern: String, }
//! Rule //! //! A [`Rule`] defines a set of checks to perform on a file. The [`Rule`] contains a `name` //! describing the [`Rule`] and the `severity` of a violation. The [`Rule`] also may contain a //! `path` and/or a `content`. //! //! If `path` **and** `content` are defined, a file violates the [`Rule`] if the file path matches //! the [`Rule`]'s `path` **and** the file content matches the [`Rule`]s `content`. //! //! If only `path` is defined, a matching file path violates the [`Rule`]. //! //! If only `content` is defined, a matching file content violates the [`Rule`]. mod builtin; mod pattern_rule; mod raw_path; mod raw_rule; mod reader; mod rule_path; mod rule_trait; pub use self::builtin::get_builtin_rules; pub use self::pattern_rule::PatternRule as Rule; pub use self::raw_path::RawPath; pub use self::rule_path::RulePath; use crate::errors::*; pub use rule_trait::RuleTrait; use std::path::Path; /// Read the `Rule`s from the given path and merge them with the builtin rules pub fn get_merged_rules<P: AsRef<Path>>(path: P) -> Result<Vec<Rule>, Error> { let path = path.as_ref(); let mut collection = reader::Reader::read_rules_from_file(path)?; info!( "Read {} custom rule(s) from '{}'", collection.len(), path.display() ); trace!("Custom rules: {:?}", collection); collection.append(&mut get_builtin_rules()); Ok(collection) }
use raylib::prelude::*; use std::io; use std::io::{Read, Write}; use std::net::TcpStream; use crate::imui::*; use crate::pong; use crate::scene::*; pub struct AwaitingOpponent { pub lobby_stream: TcpStream, pub lobby_code: i32, text_to_copy_to_clipboard: Option<String>, } impl AwaitingOpponent { pub fn new(stream: TcpStream, lobby_code: i32) -> Self { stream.set_nonblocking(true).unwrap(); AwaitingOpponent { lobby_stream: stream, lobby_code: lobby_code, text_to_copy_to_clipboard: None, } } } impl Scene for AwaitingOpponent { fn process(&mut self, _s: &mut SceneAPI, rl: &mut RaylibHandle) { let mut receive_buffer = [0]; match self.lobby_stream.read_exact(&mut receive_buffer) { Ok(_) => { if receive_buffer[0] == 1 { // player joined our lobby! _s.new_scene = Some(Box::new(pong::PongGame::new( self.lobby_stream.try_clone().unwrap(), true, ))); } else { println!("Wonky thing received from server: {}", receive_buffer[0]); } } Err(e) => match e.kind() { io::ErrorKind::WouldBlock => {} _ => { println!("Failed to receive data from server: {}", e); } }, } match &self.text_to_copy_to_clipboard { Some(text) => { rl.set_clipboard_text(&text).unwrap(); // TODO definitely need to let the user know if I couldn't copy the lobby code to clipboard self.text_to_copy_to_clipboard = None; } None => (), }; } fn draw(&mut self, _s: &mut SceneAPI, d: &mut RaylibDrawHandle) { d.clear_background(Color::GRAY); let screen_size = Vector2::new(d.get_screen_width() as f32, d.get_screen_height() as f32); let num_sections = 2; let section_size = Vector2::new(900.0, 60.0); let entire_size = section_size + Vector2::new(0.0, section_size.y * ((1 - num_sections) as f32)); let spacing = 10.0; let mut cur_place_pos = screen_size / 2.0 - entire_size / 2.0; if button( d, cur_place_pos, section_size, "COPY LOBBY CODE TO CLIPBOARD", ) { self.text_to_copy_to_clipboard = Some(self.lobby_code.to_string()); } cur_place_pos.y += section_size.y + spacing; d.draw_text_ex( d.get_font_default(), "WAITING FOR PLAYER TO JOIN...", cur_place_pos, 50.0, 1.0, Color::BLACK, ); } fn should_quit(&self) -> bool { false } }
//! Error types for runtimes. pub use oasis_core_runtime::types::Error as RuntimeError; use crate::{dispatcher, module::CallResult}; /// A runtime error that gets propagated to the caller. /// /// It extends `std::error::Error` with module name and error code so that errors can be easily /// serialized and transferred between different processes. /// /// This trait can be derived: /// ``` /// # #[cfg(feature = "oasis-runtime-sdk-macros")] /// # mod example { /// # use oasis_runtime_sdk_macros::Error; /// const MODULE_NAME: &str = "my-module"; /// #[derive(Clone, Debug, Error, thiserror::Error)] /// #[sdk_error(autonumber)] // `module_name` meta is required if `MODULE_NAME` isn't in scope /// enum Error { /// #[error("invalid argument")] /// InvalidArgument, // autonumbered to 0 /// /// #[error("forbidden")] /// #[sdk_error(code = 401)] // manually numbered to 403 (`code` or autonumbering is required) /// Forbidden, /// } /// # } /// ``` pub trait Error: std::error::Error { /// Name of the module that emitted the error. fn module_name(&self) -> &str; /// Error code uniquely identifying the error. fn code(&self) -> u32; /// Converts the error into a call result. fn into_call_result(self) -> CallResult where Self: Sized, { match self.into_abort() { Ok(err) => CallResult::Aborted(err), Err(failed) => CallResult::Failed { module: failed.module_name().to_owned(), code: failed.code(), message: failed.to_string(), }, } } /// Consumes self and returns either `Ok(err)` (where `err` is a dispatcher error) when batch /// should abort or `Err(self)` when this is just a regular error. fn into_abort(self) -> Result<dispatcher::Error, Self> where Self: Sized, { Err(self) } } impl Error for std::convert::Infallible { fn module_name(&self) -> &str { "(none)" } fn code(&self) -> u32 { Default::default() } } #[cfg(test)] mod test { use super::*; const MODULE_NAME_1: &str = "test1"; const MODULE_NAME_2: &str = "test2"; #[derive(thiserror::Error, Debug, oasis_runtime_sdk_macros::Error)] #[sdk_error(module_name = "MODULE_NAME_1")] enum ChildError { #[error("first error")] #[sdk_error(code = 1)] Error1, #[error("second error")] #[sdk_error(code = 2)] Error2, } #[derive(thiserror::Error, Debug, oasis_runtime_sdk_macros::Error)] #[sdk_error(module_name = "MODULE_NAME_2")] enum ParentError { #[error("first error")] #[sdk_error(code = 1)] NotForwarded(#[source] ChildError), #[error("nested error")] #[sdk_error(transparent)] Nested(#[source] ChildError), } #[derive(thiserror::Error, Debug, oasis_runtime_sdk_macros::Error)] enum ParentParentError { #[error("nested nested error")] #[sdk_error(transparent)] Nested(#[source] ParentError), } #[test] fn test_error_sources_1() { let err = ParentError::Nested(ChildError::Error1); let result = err.into_call_result(); match result { CallResult::Failed { module, code, message: _, } => { assert_eq!(module, "test1"); assert_eq!(code, 1); } _ => panic!("expected failed result, got: {:?}", result), } let err = ParentError::Nested(ChildError::Error2); let result = err.into_call_result(); match result { CallResult::Failed { module, code, message: _, } => { assert_eq!(module, "test1"); assert_eq!(code, 2); } _ => panic!("expected failed result, got: {:?}", result), } } #[test] fn test_error_sources_2() { let err = ParentError::NotForwarded(ChildError::Error1); let result = err.into_call_result(); match result { CallResult::Failed { module, code, message: _, } => { assert_eq!(module, "test2"); assert_eq!(code, 1); } _ => panic!("expected failed result, got: {:?}", result), } let err = ParentError::NotForwarded(ChildError::Error2); let result = err.into_call_result(); match result { CallResult::Failed { module, code, message: _, } => { assert_eq!(module, "test2"); assert_eq!(code, 1); } _ => panic!("expected failed result, got: {:?}", result), } } #[test] fn test_error_sources_3() { let err = ParentParentError::Nested(ParentError::Nested(ChildError::Error1)); let result = err.into_call_result(); match result { CallResult::Failed { module, code, message: _, } => { assert_eq!(module, "test1"); assert_eq!(code, 1); } _ => panic!("expected failed result, got: {:?}", result), } } }
// consumer_state.rs // // Internal handlers for managing static-scope (singleton) server state in a thread-safe manner. // // Static server state is guarded for thread-safe access using a blocking RwLock. This is definitely not optimal, and it'd probably be better to use tokio async locks and keep everything async, but I'm not sure what the best design for that is yet for a library receiving calls from the Python consumer thread. -Nick 2021-02-24 use std::{sync::{RwLock}}; use tokio::sync::{broadcast, mpsc, watch}; type CS<T> = RwLock<Option<T>>; type WsMessage = tokio_tungstenite::tungstenite::Message; // Lazy Static // ----------- // // Various RwLock<Option<T>>s (here short-handed to CS, for Consumer State) guard against thread-unsafe access to consumer state -- consisting mostly of channels used to communicate with the tokio runtime thread. Channels as a whole are thread-safe, but the channel ends -- Senders, Receivers -- are expected to be used from just one thread at a time! Hence the RwLock, so the consumer can't get cheeky with the channels when invoking library functions from different threads. // // However, it's totally OK for the consumer to access *different* channel ends from different threads; e.g., to check for client messages on one thread while sending server messages from another. lazy_static! { /// Consumer thread(s) receiver for whether the Tokio server thread is alive. pub static ref CS_SER_ALIVE_RX: CS<watch::Receiver<bool>> = RwLock::new(None); /// Consumer thread(s) receiver for events indicating newly-connected clients. The server-side consumer should drain this receiver regularly. pub static ref CS_CLI_CONN_RX: CS<mpsc::Receiver<String>> = RwLock::new(None); /// Consumer thread(s) clone of the server message transmitter, used to subscribe new receivers for any new connections. /// /// This is a clone of the Sender owned by the TokioState struct. pub static ref CS_SER_MSG_TX: CS<broadcast::Sender<Vec<WsMessage>>> = RwLock::new(None); /// Consumer thread(s) receiver for messages from any connected clients. The server-side consumer should drain this receiver regularly. pub static ref CS_CLI_MSG_RX: CS<mpsc::Receiver<WsMessage>> = RwLock::new(None); /// Consumer thread(s) transmitter for requesting tokio to shut down. pub static ref CS_SER_REQ_SHUTDOWN_TX: CS<watch::Sender<bool>> = RwLock::new(None); /// Very coarse way of providing some quick error reporting to the consumer without panicking. static ref LAST_ERROR: CS<String> = RwLock::new(None); } // Error API // --------- // // This is probably not a very good error API. -Nick 2021-04-21 /// Attempts to record the passed &str to the thread-safe LAST_ERROR storage. The method may fail silently if it can't get write access to LAST_ERROR, hence, "weakly". This is very likely to clobber errors if more than one propagates in short succession across more than one thread. pub fn weakly_record_error(msg: String) { let last_err = LAST_ERROR.try_write(); if last_err.is_err() { return; /* silently fail. */ } let mut last_err = last_err.unwrap(); *last_err = Some(msg); } /// Returns the last error if possible. Returns None only if there is no last error. pub fn try_get_last_error() -> Option<String> { // Attempt to lock and unwrap. let err_store = LAST_ERROR.read(); if err_store.is_err() { return Some("Couldn't get last error.".to_string()); } // Convert (possibly poisoned) lock into a Result. let err_store = err_store.as_deref(); if err_store.is_err() { return Some("Couldn't get last error.".to_string()); } // If the error is None, great! Otherwise return a copy of the string content. let err_store = err_store.unwrap().as_ref(); err_store.map_or(None, |s| Some(String::from(s))) } // State API // --------- // /// Pass one of the "CS_" (consumer state) statics available in the consumer_state module and an operating function to do something with read access to that static (e.g. receive a message from a consumer channel). pub fn read<T, U, R, F>(lazy_static_item: &R, f: F) -> Option<U> where F: FnOnce(&T) -> U, R: std::ops::Deref<Target = RwLock<Option<T>>> { let read_guard = lazy_static_item.read(); if read_guard.is_err() { weakly_record_error(format!("Failed to get read access to {}.", std::any::type_name::<R>())); return None; } let read_guard = read_guard.unwrap(); let item = read_guard.as_ref(); if item.is_none() { weakly_record_error(format!("Failed to get read access to {}, as it hasn't been created yet. Is the server running?", std::any::type_name::<R>())); return None; } let item = item.unwrap(); Some(f(item)) } /// Pass one of the "CS_" (consumer state) statics available in the consumer_state module and an operating function to do something with mutable access to that static (e.g. send a message using a Sender). pub fn mutate<T, U, R, F>(lazy_static_item: &R, f: F) -> Option<U> where F: FnOnce(&mut T) -> U, R: std::ops::Deref<Target = RwLock<Option<T>>> { let write_guard = lazy_static_item.write(); if write_guard.is_err() { weakly_record_error(format!("Failed to get write access to {}.", std::any::type_name::<R>())); return None; } let mut write_guard = write_guard.unwrap(); let state = write_guard.as_mut(); if state.is_none() { weakly_record_error(format!("Failed to mutable ref for {}, as it hasn't been created yet. Is the server running?", std::any::type_name::<R>())); return None; } let state = state.unwrap(); Some(f(state)) } /// Pass one of the "CS_" (consumer state) statics available in the consumer_state module and a value of the inner type to set the RwLock<Option<T>> with Some<T>. This is used internally by the server::start() function to initialize consumer-side channels. pub fn set_value<T, R>(lazy_static_item: &R, new_val: T) -> Result<(), ()> where R: std::ops::Deref<Target = RwLock<Option<T>>> { let write_guard = lazy_static_item.write(); if write_guard.is_err() { weakly_record_error(format!("Failed to get write access to {} to set its value.", std::any::type_name::<R>())); return Err(()); } let mut write_guard = write_guard.unwrap(); (*write_guard) = Some(new_val); Ok(()) }
use projecteuler::primes; fn main() { //gets optimized into a nop I think //helper::check_bench(|| {solve(1_000_000);}); assert_eq!(solve(), 748317); dbg!(solve()); } fn solve() -> usize { let single_digit_primes = [1, 2, 3, 5, 7, 9]; let mut pow = 1; let mut left_inc: Vec<_> = [2, 3, 5, 7].iter().cloned().collect(); let mut right_inc: Vec<_> = [2, 3, 5, 7].iter().cloned().collect(); let mut acc = Vec::new(); while !left_inc.is_empty() && !right_inc.is_empty() { //dbg!(&left_inc); //dbg!(&right_inc); pow *= 10; let new_left_inc: Vec<_> = left_inc .iter() .flat_map(|&p| single_digit_primes.iter().map(move |&d| p + d * pow)) //.filter(|p| right_inc.contains(p)) .filter(|&p| primes::is_prime(p)) .collect(); let new_right_inc: Vec<_> = right_inc .iter() .flat_map(|&p| single_digit_primes.iter().map(move |&d| p * 10 + d)) //.filter(|p| left_inc.contains(p)) .filter(|&p| primes::is_prime(p)) .collect(); for left_inc_p in &new_left_inc { let p = left_inc_p / 10; if right_inc.contains(&p) { dbg!(left_inc_p); acc.push(*left_inc_p); } } left_inc = new_left_inc; right_inc = new_right_inc; } acc.into_iter().sum() }
fn main() { let logical: bool = true; let a_float: f64 = 1.0; let an_integer = 5i32; // Suffix annotation let default_float = 3.0; // f64 let default_integer = 7; // i32 let mut inferred_type = 12; // Type i164 is inferred from another line inferred_type = 4294978697i64; let mut mutable = 12; // Mutable i32 mutable = 21; // mutable = true; // Error! The type of a variable can't be changed. // Variables can be overwritten with shadowing. let mutable = true; }
// 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. #![cfg(test)] use { difference::assert_diff, failure::{bail, format_err, Error}, fdio::{SpawnAction, SpawnOptions}, fidl_fuchsia_sys::ComponentControllerEvent, fuchsia_async as fasync, fuchsia_component::client::launch, fuchsia_component::server::ServiceFs, fuchsia_zircon::{self as zx, AsHandleRef}, futures::StreamExt, glob::glob, regex::Regex, std::{ ffi::{CStr, CString}, fs, io::{BufRead, BufReader}, os::unix::io::AsRawFd, }, tempfile::NamedTempFile, }; const GOLDEN_PATH: &str = "/pkg/data/iquery_goldens"; const SERVICE_URL: &str = "fuchsia-pkg://fuchsia.com/iquery_golden_tests#meta/iquery_example_component.cmx"; struct Golden { command_line: String, lines: Vec<String>, } impl Golden { fn load(filename: &str) -> Result<Self, Error> { // Read lines skipping all comments let file_content = fs::read_to_string(filename)?; let mut lines = file_content.lines().skip_while(|line| line.starts_with("#")).map(|s| s.to_string()); if let Some(command_line) = lines.next() { if command_line.starts_with("iquery") { return Ok(Self { command_line, lines: lines.collect() }); } } bail!("Bad golden file {}", filename) } } struct GoldenTest { golden: Golden, } impl GoldenTest { fn new(golden_name: &str) -> Result<Self, Error> { let golden_file = format!("{}/{}.txt", GOLDEN_PATH, golden_name.replace("_", "-")); let golden = Golden::load(&golden_file)?; Ok(Self { golden }) } async fn execute(self) -> Result<(), Error> { let mut service_fs = ServiceFs::new(); let arguments = vec!["--rows=5".to_string(), "--columns=3".to_string()]; let nested_environment = service_fs.create_nested_environment("test")?; let mut app = launch(nested_environment.launcher(), SERVICE_URL.to_string(), Some(arguments))?; fasync::spawn(service_fs.collect()); let mut component_stream = app.controller().take_event_stream(); match component_stream .next() .await .expect("component event stream ended before termination event")? { ComponentControllerEvent::OnDirectoryReady {} => { let hub_path = get_hub_path()?; self.validate(&hub_path)?; app.kill().map_err(|e| format_err!("failed to kill component: {}", e)) } ComponentControllerEvent::OnTerminated { return_code, termination_reason } => { bail!( "Component terminated unexpectedly. Code: {}. Reason: {:?}", return_code, termination_reason ); } } } fn validate(&self, hub_path: &str) -> Result<(), Error> { let output_file = NamedTempFile::new().expect("failed to create tempfile"); self.run_iquery(output_file.as_file(), hub_path)?; let reader = BufReader::new(output_file); let re = Regex::new("/\\d+/").unwrap(); for (golden_line, output_line) in self.golden.lines.iter().zip(reader.lines()) { // Replace paths containing ids with /*/ to remove process or realm ids. let output = re.replace_all(output_line.as_ref().unwrap(), "/*/"); // TODO: remove when renaming let output = output.replace("iquery", "iquery"); assert_diff!(golden_line, &output, "", 0); } Ok(()) } fn run_iquery(&self, output_file: &fs::File, hub_path: &str) -> Result<(), Error> { // Set the hub path as the dir in which iquery will be executed. let mut args = self.golden.command_line.split(" ").collect::<Vec<&str>>(); let dir_arg = format!("--dir={}", hub_path); args.insert(1, &dir_arg); // Ensure we use the iquery bundled in this package, not the global one. let command = format!("/pkg/bin/{}", args[0]); // Run let mut actions = [ SpawnAction::clone_fd(output_file, std::io::stdout().as_raw_fd()), SpawnAction::clone_fd(output_file, std::io::stderr().as_raw_fd()), ]; let argv_cstrings: Vec<CString> = args.into_iter().map(|a| CString::new(a).expect("CString: failed")).collect(); let argv: Vec<&CStr> = argv_cstrings.iter().map(|a| a.as_c_str()).collect(); let job = zx::Job::from(zx::Handle::invalid()); let process = fdio::spawn_etc( &job, SpawnOptions::CLONE_ALL, CString::new(command).expect("CString: failed").as_c_str(), &argv, None, &mut actions, ) .map_err(|(status, msg)| { format_err!("Failed to launch iquery process. status={}, msg={}", status, msg) })?; process .wait_handle(zx::Signals::PROCESS_TERMINATED, zx::Time::INFINITE) .expect("Wait for iquery process termination failed"); let info = process.info().expect("failed to get iquery process info"); if !info.exited || info.return_code != 0 { bail!("iquery process returned non-zero exit code ({})", info.return_code); } Ok(()) } } fn get_hub_path() -> Result<String, Error> { let glob_query = "/hub/r/test/*/c/iquery_example_component.cmx/*/out"; match glob(&glob_query)?.next() { Some(found_path_result) => found_path_result .map(|p| p.to_string_lossy().to_string()) .map_err(|e| format_err!("Failed reading out dir: {}", e)), None => bail!("Out dir not found"), } } macro_rules! tests { ($($test_name:ident,)*) => { $( #[fasync::run_singlethreaded(test)] async fn $test_name() -> Result<(), Error> { let test = GoldenTest::new(stringify!($test_name))?; test.execute().await } )* } } tests![ cat_recursive_absolute, cat_recursive_full, cat_recursive_json_absolute, cat_recursive_json_full, cat_recursive_json, cat_recursive, cat_single_absolute, cat_single_full, cat_single, explicit_file_full, explicit_file, find_recursive_json, find_recursive, find, ls_json_absolute, ls_json_full, ls_json, ls, report_json, report, vmo_cat_recursive_absolute, vmo_cat_recursive_full, vmo_cat_recursive_json_absolute, vmo_cat_recursive_json_full, vmo_cat_recursive_json, vmo_cat_recursive, vmo_cat_single_absolute, vmo_cat_single_full, vmo_cat_single, vmo_ls_json_absolute, vmo_ls_json_full, vmo_ls_json, vmo_ls, ];
pub const VIP_START: u32 = 0x00000000; pub const VIP_LENGTH: u32 = 0x01000000; pub const VIP_END: u32 = VIP_START + VIP_LENGTH - 1; pub const VSU_START: u32 = 0x01000000; pub const VSU_LENGTH: u32 = 0x01000000; pub const VSU_END: u32 = VSU_START + VSU_LENGTH - 1; pub const LINK_CONTROL_REG: u32 = 0x02000000; pub const AUX_LINK_REG: u32 = 0x02000004; pub const LINK_TRANSMIT_DATA_REG: u32 = 0x02000008; pub const LINK_RECEIVE_DATA_REG: u32 = 0x0200000c; pub const GAME_PAD_INPUT_LOW_REG: u32 = 0x02000010; pub const GAME_PAD_INPUT_HIGH_REG: u32 = 0x02000014; pub const TIMER_COUNTER_RELOAD_LOW_REG: u32 = 0x02000018; pub const TIMER_COUNTER_RELOAD_HIGH_REG: u32 = 0x0200001c; pub const TIMER_CONTROL_REG: u32 = 0x02000020; pub const WAIT_CONTROL_REG: u32 = 0x02000024; pub const GAME_PAD_INPUT_CONTROL_REG: u32 = 0x02000028; pub const CARTRIDGE_EXPANSION_START: u32 = 0x04000000; pub const CARTRIDGE_EXPANSION_LENGTH: u32 = 0x01000000; pub const CARTRIDGE_EXPANSION_END: u32 = CARTRIDGE_EXPANSION_START + CARTRIDGE_EXPANSION_LENGTH - 1; pub const WRAM_START: u32 = 0x05000000; pub const WRAM_LENGTH: u32 = 0x01000000; pub const WRAM_END: u32 = WRAM_START + WRAM_LENGTH - 1; pub const CARTRIDGE_RAM_START: u32 = 0x06000000; pub const CARTRIDGE_RAM_LENGTH: u32 = 0x01000000; pub const CARTRIDGE_RAM_END: u32 = CARTRIDGE_RAM_START + CARTRIDGE_RAM_LENGTH - 1; pub const CARTRIDGE_ROM_START: u32 = 0x07000000; pub const CARTRIDGE_ROM_LENGTH: u32 = 0x01000000; pub const CARTRIDGE_ROM_END: u32 = CARTRIDGE_ROM_START + CARTRIDGE_ROM_LENGTH - 1;
fn main(){ let a = [1,2,3,4,5,6,7,8,9,10]; let mut index = 0; while index<5 { println!("{}",a[index]); index +=1; } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use common_base::base::tokio; use common_exception::ErrorCode; use common_exception::Result; use common_grpc::RpcClientConf; use common_meta_app::principal::AuthInfo; use common_meta_app::principal::GrantObject; use common_meta_app::principal::PasswordHashMethod; use common_meta_app::principal::UserGrantSet; use common_meta_app::principal::UserIdentity; use common_meta_app::principal::UserInfo; use common_meta_app::principal::UserPrivilegeSet; use common_meta_app::principal::UserPrivilegeType; use common_users::UserApiProvider; use pretty_assertions::assert_eq; #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_user_manager() -> Result<()> { let conf = RpcClientConf::default(); let user_mgr = UserApiProvider::try_create_simple(conf).await?; let tenant = "test"; let username = "test-user1"; let hostname = "localhost"; let hostname2 = "%"; let pwd = "test-pwd"; let auth_info = AuthInfo::Password { hash_value: Vec::from(pwd), hash_method: PasswordHashMethod::Sha256, }; // add user hostname. { let user_info = UserInfo::new(username, hostname, auth_info.clone()); user_mgr.add_user(tenant, user_info, false).await?; } // add user hostname again, error. { let user_info = UserInfo::new(username, hostname, auth_info.clone()); let res = user_mgr.add_user(tenant, user_info, false).await; assert!(res.is_err()); assert_eq!(res.err().unwrap().code(), ErrorCode::USER_ALREADY_EXISTS); } // add user hostname again, ok. { let user_info = UserInfo::new(username, hostname, auth_info.clone()); user_mgr.add_user(tenant, user_info, true).await?; } // add user hostname2. { let user_info = UserInfo::new(username, hostname2, auth_info.clone()); user_mgr.add_user(tenant, user_info, false).await?; } // get all users. { let users = user_mgr.get_users(tenant).await?; assert_eq!(2, users.len()); assert_eq!(pwd.as_bytes(), users[0].auth_info.get_password().unwrap()); } // get user hostname. { let user_info = user_mgr .get_user(tenant, UserIdentity::new(username, hostname)) .await?; assert_eq!(hostname, user_info.hostname); assert_eq!(pwd.as_bytes(), user_info.auth_info.get_password().unwrap()); } // get user hostname2. { let user_info = user_mgr .get_user(tenant, UserIdentity::new(username, hostname2)) .await?; assert_eq!(hostname2, user_info.hostname); assert_eq!(pwd.as_bytes(), user_info.auth_info.get_password().unwrap()); } // drop. { user_mgr .drop_user(tenant, UserIdentity::new(username, hostname), false) .await?; let users = user_mgr.get_users(tenant).await?; assert_eq!(1, users.len()); } // repeat drop same user not with if exist. { let res = user_mgr .drop_user(tenant, UserIdentity::new(username, hostname), false) .await; assert!(res.is_err()); } // repeat drop same user with if exist. { let res = user_mgr .drop_user(tenant, UserIdentity::new(username, hostname), true) .await; assert!(res.is_ok()); } // grant privileges { let user_info: UserInfo = UserInfo::new(username, hostname, auth_info.clone()); user_mgr.add_user(tenant, user_info.clone(), false).await?; let old_user = user_mgr.get_user(tenant, user_info.identity()).await?; assert_eq!(old_user.grants, UserGrantSet::empty()); let mut add_priv = UserPrivilegeSet::empty(); add_priv.set_privilege(UserPrivilegeType::Set); user_mgr .grant_privileges_to_user(tenant, user_info.identity(), GrantObject::Global, add_priv) .await?; let new_user = user_mgr.get_user(tenant, user_info.identity()).await?; assert!( new_user .grants .verify_privilege(&GrantObject::Global, vec![UserPrivilegeType::Set]) ); assert!( !new_user .grants .verify_privilege(&GrantObject::Global, vec![UserPrivilegeType::Create]) ); user_mgr .drop_user(tenant, new_user.identity(), true) .await?; } // revoke privileges { let user_info: UserInfo = UserInfo::new(username, hostname, auth_info.clone()); user_mgr.add_user(tenant, user_info.clone(), false).await?; user_mgr .grant_privileges_to_user( tenant, user_info.identity(), GrantObject::Global, UserPrivilegeSet::all_privileges(), ) .await?; let user_info = user_mgr.get_user(tenant, user_info.identity()).await?; assert_eq!(user_info.grants.entries().len(), 1); user_mgr .revoke_privileges_from_user( tenant, user_info.identity(), GrantObject::Global, UserPrivilegeSet::all_privileges(), ) .await?; let user_info = user_mgr.get_user(tenant, user_info.identity()).await?; assert_eq!(user_info.grants.entries().len(), 0); user_mgr .drop_user(tenant, user_info.identity(), true) .await?; } // alter. { let user = "test"; let hostname = "localhost"; let pwd = "test"; let auth_info = AuthInfo::Password { hash_value: Vec::from(pwd), hash_method: PasswordHashMethod::Sha256, }; let user_info: UserInfo = UserInfo::new(user, hostname, auth_info.clone()); user_mgr.add_user(tenant, user_info.clone(), false).await?; let old_user = user_mgr.get_user(tenant, user_info.identity()).await?; assert_eq!(old_user.auth_info.get_password().unwrap(), Vec::from(pwd)); // alter both password & password_type let new_pwd = "test1"; let auth_info = AuthInfo::Password { hash_value: Vec::from(new_pwd), hash_method: PasswordHashMethod::Sha256, }; user_mgr .update_user(tenant, user_info.identity(), Some(auth_info), None) .await?; let new_user = user_mgr.get_user(tenant, user_info.identity()).await?; assert_eq!( new_user.auth_info.get_password().unwrap(), Vec::from(new_pwd) ); assert_eq!( new_user.auth_info.get_password_type().unwrap(), PasswordHashMethod::Sha256 ); // alter password only let new_new_pwd = "test2"; let auth_info = AuthInfo::Password { hash_value: Vec::from(new_new_pwd), hash_method: PasswordHashMethod::Sha256, }; user_mgr .update_user(tenant, user_info.identity(), Some(auth_info.clone()), None) .await?; let new_new_user = user_mgr.get_user(tenant, user_info.identity()).await?; assert_eq!( new_new_user.auth_info.get_password().unwrap(), Vec::from(new_new_pwd) ); let not_exist = user_mgr .update_user( tenant, UserIdentity::new("user", hostname), Some(auth_info.clone()), None, ) .await; // ErrorCode::UnknownUser assert_eq!(not_exist.err().unwrap().code(), 2201) } Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_user_manager_with_root_user() -> Result<()> { let conf = RpcClientConf::default(); let user_mgr = UserApiProvider::try_create_simple(conf).await?; let tenant = "test"; let username1 = "default"; let username2 = "root"; let hostname1 = "127.0.0.1"; let hostname2 = "localhost"; let hostname3 = "otherhost"; // Get user via username `default` and hostname `127.0.0.1`. { let user = user_mgr .get_user(tenant, UserIdentity::new(username1, hostname1)) .await?; assert_eq!(user.name, username1); assert_eq!(user.hostname, hostname1); assert!(user.grants.verify_privilege(&GrantObject::Global, vec![ UserPrivilegeType::Create, UserPrivilegeType::Select, UserPrivilegeType::Insert, UserPrivilegeType::Super ])); } // Get user via username `default` and hostname `localhost`. { let user = user_mgr .get_user(tenant, UserIdentity::new(username1, hostname2)) .await?; assert_eq!(user.name, username1); assert_eq!(user.hostname, hostname2); assert!(user.grants.verify_privilege(&GrantObject::Global, vec![ UserPrivilegeType::Create, UserPrivilegeType::Select, UserPrivilegeType::Insert, UserPrivilegeType::Super ])); } // Get user via username `default` and hostname `otherhost` will be denied. { let res = user_mgr .get_user(tenant, UserIdentity::new(username1, hostname3)) .await; assert!(res.is_err()); assert_eq!( "Code: 2201, displayText = only accept root from localhost, current: 'default'@'otherhost'.", res.err().unwrap().to_string() ); } // Get user via username `root` and hostname `127.0.0.1`. { let user = user_mgr .get_user(tenant, UserIdentity::new(username2, hostname1)) .await?; assert_eq!(user.name, username2); assert_eq!(user.hostname, hostname1); assert!(user.grants.verify_privilege(&GrantObject::Global, vec![ UserPrivilegeType::Create, UserPrivilegeType::Select, UserPrivilegeType::Insert, UserPrivilegeType::Super ])); } // Get user via username `root` and hostname `localhost`. { let user = user_mgr .get_user(tenant, UserIdentity::new(username2, hostname2)) .await?; assert_eq!(user.name, username2); assert_eq!(user.hostname, hostname2); assert!(user.grants.verify_privilege(&GrantObject::Global, vec![ UserPrivilegeType::Create, UserPrivilegeType::Select, UserPrivilegeType::Insert, UserPrivilegeType::Super ])); } // Get user via username `root` and hostname `otherhost` will be denied. { let res = user_mgr .get_user(tenant, UserIdentity::new(username2, hostname3)) .await; assert!(res.is_err()); assert_eq!( "Code: 2201, displayText = only accept root from localhost, current: 'root'@'otherhost'.", res.err().unwrap().to_string() ); } Ok(()) }
use yew::prelude::*; use yew_router::prelude::*; // use yew_router::components::RouterAnchor; use yew::services::{ ConsoleService, storage::{ StorageService, Area }, }; use yew::format::{ Json }; // use yewdux::prelude::*; use yewdux::prelude::WithDispatch; use yewdux::dispatch::Dispatcher; use yewtil::NeqAssign; // use yew_router::switch::{Permissive}; use yew_router::route::Route; use yew_router::service::RouteService; use crate::store::reducer_account::{ AppDispatch, DataAccountAction, // DataAccount, }; use crate::types::{ ResponseLogin, }; use crate::pages::{ outer::{ login_page::LoginPage, register_page::RegisterPage, password_page::RequestPassPage, }, home_page::HomePage, getting_started::GettingStarted, activity::Activity, applications::{ applications::home::ApplicationHome, apis::{ home::ApisHome, settings::ApisSettings, }, sso::{ home::SsoHome, create_sso::CreateSso, }, }, authentication::{ database::{ home::DatabaseHome, create_db::DbCreate, settings::DatabaseSettings, }, social::{ home::SocialHome, settings::SocialSettings, create::SocialCreate, }, enterprise::{ home::EnterpriseHome, google_apps::EnterpriseGoogle, google_apps_create::EnterpriseGoogleCreate, }, passwordless::home::AuthPasswordLess, }, settings::{ home::SettingsHome, }, management::{ users::{ home::UsersManagement, user_viewdetail::UserViewDetail, }, roles::{ // home::RolesManagement, role_created::RolesCreated, dropdown_viewdetail::ViewDetail, }, }, }; use crate::components::{ navtop::Navtop, sidebar::Sidebar, }; use crate::types::LocalStorage; use crate::types::LOCALSTORAGE_KEY; #[derive(Switch, Clone)] pub enum AppRoute { // MEMBER PAGES #[to = "/apis/settings"] ApisSettings, #[to = "/getting-started"] GettingStarted, #[to = "/{tenant_id}/apis"] ApisHome { tenant_id: String }, #[to = "/activity"] Activity, #[to = "/applications"] DatabaseSettings, #[to = "/authentication/database/settings"] DbCreate, #[to = "/authentication/database/create"] DatabaseHome, #[to = "/authentication/database"] ApplicationHome, #[to = "/authentication/passwordless"] AuthPasswordless, #[to = "/sso/create-sso"] CreateSso, #[to = "/sso"] SsoHome, #[to = "/social/create"] SocialCreate, #[to = "/social/settings"] SocialSettings, #[to = "/social"] SocialHome, #[to = "/user-management/roles/settings"] ViewDetail, #[to = "/user-management/roles"] RolesCreated, #[to="/user-management/users/setting"] UserViewDetail, #[to = "/user-management/users"] UsersManagement, #[to = "/enterprise/google-app/create"] EnterpriseGoogleCreate, #[to = "/enterprise/google-app"] EnterpriseGoogle, #[to = "/enterprise"] EnterpriseHome, #[to = "/tenant"] SettingsHome, // NOT LOGGED IN PAGES #[to = "/login/password"] RequestPassPage, #[to = "/login"] LoginPage, #[to = "/register"] RegisterPage, #[to = "/"] Home, } pub struct App { dispatch: AppDispatch, // link: ComponentLink<Self>, } pub enum Msg { AutoLogin(ResponseLogin), SetIsAuth(bool), } impl Component for App { type Message = Msg; type Properties = AppDispatch; fn create(dispatch: Self::Properties, link: ComponentLink<Self>) -> Self { let storage = StorageService::new(Area::Local).expect("storage was disabled"); // LOCALSTORAGE RESOURCE // https://github.com/yewstack/yew/issues/1287 // GET LOCALSTORAGE // NEED BETTER WAY TO PARSE JSON DATA let localstorage_data = { if let Json(Ok(data)) = storage.restore(LOCALSTORAGE_KEY) { // ConsoleService::info("get localstorage"); ConsoleService::info(&format!("{:?}", data)); data } else { ConsoleService::info("token does not exist"); LocalStorage { username: None, email: None, token: None, } } }; ConsoleService::info(&format!("{:?}", localstorage_data)); // IF LOCALSTORAGE EXISTS // UPDATE REDUCER if let Some(_) = localstorage_data.username { let data_account = ResponseLogin { // username: Some(String::from(data.username.unwrap())), // email: Some(String::from(data.email.unwrap())), // token: Some(String::from(data.token.unwrap())), username: localstorage_data.username.unwrap(), email: localstorage_data.email.unwrap(), token: localstorage_data.token.unwrap(), }; // dispatch.send(DataAccountAction::Update(data_account)); link.send_message(Msg::AutoLogin(data_account)); } else { link.send_message(Msg::SetIsAuth(false)); } App { dispatch, // link, } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::AutoLogin(user) => { ConsoleService::info("autologin"); self.dispatch.send(DataAccountAction::Update(user)); self.dispatch.send(DataAccountAction::SetIsAuth(false)); true } Msg::SetIsAuth(state) => { ConsoleService::info("set is auth from app"); self.dispatch.send(DataAccountAction::SetIsAuth(state)); true } } } fn change(&mut self, dispatch: Self::Properties) -> ShouldRender { self.dispatch.neq_assign(dispatch) } fn view(&self) -> Html { // let acc_ref = &account; let acc = self.dispatch.state().clone(); let is_auth = acc.is_auth; let is_logged_in = if acc.username == None {false} else {true}; // let route_service = RouteService::new(); let render = Router::render(move |switch: AppRoute| { let mut route_service = RouteService::new(); match switch { // NOT LOGGED IN ROUTES AppRoute::Home => { if is_logged_in { route_service.set_route("/manage", ()); html! {<GettingStarted/>} } else { html! {<HomePage/>} } }, AppRoute::LoginPage => { if is_logged_in { route_service.set_route("/manage", ()); html! {<GettingStarted/>} } else { html! {<WithDispatch<LoginPage>/>} } }, AppRoute::RegisterPage => { if is_logged_in { route_service.set_route("/manage", ()); html! {<GettingStarted/>} } else { html!{<RegisterPage/>} } }, AppRoute::RequestPassPage => { if is_logged_in { route_service.set_route("/manage", ()); html! {<GettingStarted/>} } else { html!{<RequestPassPage/>} } }, // LOGGED IN ROUTES AppRoute::Activity => { if is_logged_in { html!{<Activity/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::GettingStarted => { if is_logged_in { html! {<GettingStarted/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::ApisHome{ tenant_id } => { if is_logged_in { html! {<ApisHome tenant_id=tenant_id />} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::ApisSettings => { if is_logged_in { html! {<ApisSettings/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::ApplicationHome => { if is_logged_in { html! {<ApplicationHome/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::AuthPasswordless => { if is_logged_in { html! {<AuthPasswordLess/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::SsoHome => { if is_logged_in { html! {<SsoHome/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::CreateSso => { if is_logged_in { html! {<CreateSso/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::SocialHome => { if is_logged_in { html! {<SocialHome/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::SocialSettings => { if is_logged_in { html! {<SocialSettings/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::SocialCreate => { if is_logged_in { html! {<SocialCreate/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::RolesCreated => { if is_logged_in { html! {<RolesCreated/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::UsersManagement => { if is_logged_in { html! {<UsersManagement/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::UserViewDetail => { if is_logged_in { html! {<UserViewDetail/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } } AppRoute::EnterpriseHome => { if is_logged_in { html! {<EnterpriseHome/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::EnterpriseGoogle => { if is_logged_in { html! {<EnterpriseGoogle/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::EnterpriseGoogleCreate => { if is_logged_in { html! {<EnterpriseGoogleCreate/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::SettingsHome => { if is_logged_in { html! {<SettingsHome/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::ViewDetail => { if is_logged_in { html! {<ViewDetail/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::DatabaseHome => { if is_logged_in { html! {<DatabaseHome/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::DbCreate => { if is_logged_in { html! {<DbCreate/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, AppRoute::DatabaseSettings => { if is_logged_in { html! {<DatabaseSettings/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, // OTHER ROUTES _ => { if is_logged_in { route_service.set_route("/manage", ()); html! {<GettingStarted/>} } else { route_service.set_route("/", ()); html! {<HomePage/>} } }, } // if is_logged_in { // match switch { // AppRoute::Activity => html!{<Activity/>}, // AppRoute::GettingStarted => html! {<GettingStarted/>}, // AppRoute::ApisHome{ tenant_id } => html! {<ApisHome tenant_id=tenant_id />}, // AppRoute::ApisSettings => html! {<ApisSettings/>}, // AppRoute::ApplicationHome => html! {<ApplicationHome/>}, // AppRoute::AuthPasswordless => html! {<AuthPasswordLess/>}, // AppRoute::SsoHome => html! {<SsoHome/>}, // AppRoute::CreateSso => html! {<CreateSso/>}, // AppRoute::SocialHome => html! {<SocialHome/>}, // AppRoute::SocialSettings => html! {<SocialSettings/>}, // AppRoute::SocialCreate => html! {<SocialCreate/>}, // AppRoute::RolesCreated => html! {<RolesCreated/>}, // AppRoute::UsersManagement => html! {<UsersManagement/>}, // AppRoute::EnterpriseHome => html! {<EnterpriseHome/>}, // AppRoute::EnterpriseGoogle => html! {<EnterpriseGoogle/>}, // AppRoute::EnterpriseGoogleCreate => html! {<EnterpriseGoogleCreate/>}, // AppRoute::SettingsHome => html! {<SettingsHome/>}, // AppRoute::ViewDetail => html! {<ViewDetail/>}, // AppRoute::DatabaseHome => html! {<DatabaseHome/>}, // AppRoute::DbCreate => html! {<DbCreate/>}, // AppRoute::DatabaseSettings => html! {<DatabaseSettings/>}, // _ => { // // ConsoleService::info("SET ROUTE TO MANAGE"); // route_service.set_route("/manage", ()); // html! {<GettingStarted/>} // }, // } // } else { // match switch { // AppRoute::Home => { // // ConsoleService::info("ROUTE HOMEPAGE"); // html! {<HomePage/>} // }, // AppRoute::LoginPage => html! {<WithDispatch<LoginPage>/>}, // AppRoute::RegisterPage => html!{<RegisterPage/>}, // AppRoute::RequestPassPage => html!{<RequestPassPage/>}, // _ => { // // ConsoleService::info("SET ROUTE /"); // route_service.set_route("/", ()); // html! {<HomePage/>} // }, // } // } // match switch { // AppRoute::GettingStarted => html! {<GettingStarted/>}, // AppRoute::ApisHome if !is_logged_in => { // ConsoleService::info("redirect"); // route_service.set_route("/", ()); // html! {<HomePage/>} // }, // AppRoute::ApisHome => html! {<ApisHome/>}, // AppRoute::Settings => html! {<Settings/>}, // AppRoute::ApplicationHome => html! {<ApplicationHome/>}, // AppRoute::Home if !is_logged_in => html!{<HomePage/>}, // AppRoute::Home => { // route_service.set_route("/manage", ()); // html! {<GettingStarted/>} // }, // // html! {<HomePage/>}, // AppRoute::LoginPage if !is_logged_in => {html! {<WithDispatch<LoginPage>/>}}, // AppRoute::LoginPage => { // ConsoleService::info("redirect"); // // self.route_service.set_route("/manage", ()); // route_service.set_route("/manage", ()); // html! {<GettingStarted/>} // }, // AppRoute::RegisterPage => html!{<RegisterPage/>}, // AppRoute::RequestPassPage => html!{<RequestPassPage/>}, // // _ => html! { // // <GettingStarted/> // // }, // } }); let account = self.dispatch.state().clone(); if is_logged_in && !is_auth { html! { <> <WithDispatch<Navtop>/> <div class="container-fluid" > <div class="row flex-nowrap" > <WithDispatch<Sidebar>/> <div class="col" > <Router<AppRoute, ()> render=render // https://github.com/yewstack/yew_router/blob/master/examples/router_component/src/main.rs#L88 redirect = Router::redirect(|route: Route| { ConsoleService::info(&route.route); AppRoute::LoginPage // Route::PageNotFound(Permissive(Some(route.route))) }) /> </div> </div> </div> // <TestingFetch/> // <p></p> // <p>{"Reducer"}</p> // <WithDispatch<ReducerGlobal>/> // <WithDispatch<ReducerAccountView>/> </> } } else if !is_auth { html! { <> <main> <Router<AppRoute, ()> render=render redirect = Router::redirect(|route: Route| { ConsoleService::info(&route.route); AppRoute::LoginPage }) /> </main> </> } } else { html! { <div> {"LOADING..."} </div> } } } } // impl App { // fn navtop(&self, account: DataAccount) -> Html { // if account.name == None { // html! { // <> // <HomePage/> // </> // } // } else { // html! { // <Navtop/> // } // } // } // }
//! ```elixir //! # label 2 //! # pushed to stack: (before) //! # returned from call: value //! # full stack: (value, before) //! # returns: after //! after = :erlang.monotonic_time() //! duration = after - before //! time = :erlang.convert_time_unit(duration, :native, :microsecond) //! {time, value} //! ``` use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; use crate::erlang::monotonic_time_0; use super::label_3; // Private #[native_implemented::label] fn result(process: &Process, value: Term, before: Term) -> Term { assert!(before.is_integer()); process.queue_frame_with_arguments(monotonic_time_0::frame().with_arguments(false, &[])); process.queue_frame_with_arguments(label_3::frame().with_arguments(true, &[before, value])); Term::NONE }
use std::cmp::{min, max}; use std::collections::{HashMap, HashSet, VecDeque}; use std::cmp::Reverse; use itertools::Itertools; use whiteread::parse_line; const ten97: usize = 1000000007; fn alphabet2idx(c: char) -> usize { if c.is_ascii_lowercase() { c as u8 as usize - 'a' as u8 as usize } else if c.is_ascii_uppercase() { c as u8 as usize - 'A' as u8 as usize } else { panic!("wtf") } } fn main() { let q: usize = parse_line().unwrap(); let mut cards: VecDeque<usize> = VecDeque::new(); for _ in 0..q { let (t, x): (usize, usize) = parse_line().unwrap(); if t == 1 { cards.push_front(x); } else if t == 2 { cards.push_back(x); } else if t == 3 { println!("{}", cards[x - 1]); } } }
use error::*; use std::{ops::Range, ptr::NonNull}; /// Trait for memory allocation and mapping. pub trait Device: Sized { /// Memory type that can be used with this device. type Memory: 'static; /// Allocate memory object. /// /// # Parameters /// `size` - size of the memory object to allocate. /// `index` - memory type index. unsafe fn allocate(&self, index: u32, size: u64) -> Result<Self::Memory, AllocationError>; /// Free memory object. unsafe fn free(&self, memory: Self::Memory); /// Map memory range. /// Only one range for the given memory object can be mapped. unsafe fn map( &self, memory: &Self::Memory, range: Range<u64>, ) -> Result<NonNull<u8>, MappingError>; /// Unmap memory. unsafe fn unmap(&self, memory: &Self::Memory); /// Invalidate mapped regions guaranteeing that device writes to the memory, /// which have been made visible to the host-write and host-read access types, are made visible to the host unsafe fn invalidate<'a>( &self, regions: impl IntoIterator<Item = (&'a Self::Memory, Range<u64>)>, ) -> Result<(), OutOfMemoryError>; /// Flush mapped regions guaranteeing that host writes to the memory can be made available to device access unsafe fn flush<'a>( &self, regions: impl IntoIterator<Item = (&'a Self::Memory, Range<u64>)>, ) -> Result<(), OutOfMemoryError>; }
#[derive(Debug, Clone)] pub struct StatementPart (pub String); #[derive(Debug, Clone)] pub enum Statement { MacroCall(String), Normal(Vec<StatementPart>) } #[derive(Debug)] pub enum Expression { Statement(Statement), MacroDefinition(String, Vec<Statement>) }
use std::env; fn main() { let args: Vec<String> = env::args().collect(); let mut fin = String::from(""); // first arg is the name of the program so skip it for arg in args.iter().skip(1) { for (i, c) in arg.chars().enumerate() { if i % 2 == 0 { let a = c.to_string().to_uppercase(); fin = fin + &a; } else { fin = fin + &c.to_string(); } } fin = fin + &String::from(" "); } println!("{:?}", fin); }
fn main() { let fname = "Agus "; let lname = "Susilo"; let full_name = format!("{}{}", fname, lname); println!("{}", full_name); println!("{}", hello()); } fn hello() -> String { let fname = "Agus "; let lname = "Susilo"; format!("{}{}", fname, lname) }
use rand::prelude::*; use std::convert::TryInto; use std::fmt; use uuid::Uuid; /// Somebody who tries to hail a `Taxi` will issue a `Request`. /// A `Request` is therefore represents somebody's desire to be picked up by a `Taxi`. /// It has a `max_lifetime` which expires the `Request` as if it timed out because it didn't /// fulfilled quickly enough. #[derive(Debug, Clone)] pub struct Request { id: Uuid, remaining_waiting_time: u64, assigned_taxi: Option<Uuid>, fulfillment_time: u64, } impl Request { pub fn new() -> Request { Request { id: Uuid::new_v4(), remaining_waiting_time: 100, assigned_taxi: None, fulfillment_time: 100, } } pub fn is_alive(&self) -> bool { self.remaining_waiting_time > 0 && self.fulfillment_time > 0 } } #[derive(Debug)] pub struct Taxi { id: Uuid, is_occupied: bool, } impl Taxi { pub fn new() -> Taxi { Taxi { id: Uuid::new_v4(), is_occupied: false, } } } #[derive(Debug)] pub struct World { /// How long the `World` updates for in ticks/seconds. runtime: u64, /// How long the `World` has been running for. age: u64, /// Change to spawn a request per tick. request_spawn_chance: f64, /// When the number of `active_requests` reaches this number, no further requests will be /// allowed to spawn. max_active_requests: u32, /// Current `Taxi`s in the `World`. taxis: Vec<Taxi>, /// Currently active `Request`s in the `World`. These are either being waited for or are /// being driven. active_requests: Vec<Request>, /// Canceled or fulfilled requests. Append only. archived_requests: Vec<Request>, rng: SmallRng, } impl World { /// `runtime` is simulation seconds. pub fn new( runtime: u64, request_spawn_chance: f64, max_active_requests: u32, number_of_taxis: u32, ) -> World { let taxis = (0..number_of_taxis).map(|_| Taxi::new()).collect(); let rng = SmallRng::from_rng(thread_rng()).unwrap(); World { runtime, age: 0, request_spawn_chance, max_active_requests, taxis, active_requests: vec![], archived_requests: vec![], rng, } } /// Debug print `World` info. pub fn info(&self) { println!("{}", self); } /// Spawns requests with a small chance. pub fn maybe_spawn_request(&mut self) { if self.active_requests.len() < self.max_active_requests.try_into().unwrap() && self.rng.gen_bool(self.request_spawn_chance) { self.active_requests.push(Request::new()) } } /// Try to distribute all waiting `Request`s to unoccupied `Taxi`s. pub fn distribute_unfulfilled_requests(&mut self) { let waiting_requests = self .active_requests .iter_mut() .filter(|r| r.assigned_taxi.is_none()); for r in waiting_requests { let unoccupied_taxi = self.taxis.iter_mut().find(|t| !t.is_occupied); if let Some(taxi) = unoccupied_taxi { r.assigned_taxi = Some(taxi.id); taxi.is_occupied = true; } else { break; } } } /// Update and tick down all `Request`s. pub fn update_requests(&mut self) { for r in &mut self.active_requests { if r.assigned_taxi.is_some() { r.fulfillment_time -= 1; } else { r.remaining_waiting_time -= 1; } } } /// Moved `Request`s from `active_requests` to `archived_requests` if they have either: /// 1) reached their `fulfillment_time` or /// 2) reached their `remaining_waiting_time`. pub fn cleanup_requests(&mut self) { // First step is to clone all eligible `Request`s from `active_requests` to // `archived_requests`. for r in &self.active_requests { if !r.is_alive() { self.archived_requests.push(r.clone()); // Don't forget to reset the `Taxi` so that it may now take a `Request` again. // However, this is only important if this `Request` actually had a `Taxi` // assigned. In the case of a canceled `Request`, it didn't have a `Taxi`. if let Some(taxi_id) = r.assigned_taxi { let taxi = self .taxis .iter_mut() .find(|t| t.id == taxi_id) .expect("We expected to find a Taxi but didn't find one."); taxi.is_occupied = false; } } } // Second step is to bulk delete all th self.active_requests.retain(|r| r.is_alive()); } /// Runs until `age` reaches `runtime`. pub fn run_till_done(&mut self) { while self.age <= self.runtime { self.info(); self.age += 1; self.maybe_spawn_request(); self.distribute_unfulfilled_requests(); self.update_requests(); self.cleanup_requests(); } } } impl fmt::Display for World { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let num_occupied_taxis = self.taxis.iter().filter(|t| t.is_occupied).count(); let num_total_taxis = self.taxis.len(); let num_assigned_requests = self .active_requests .iter() .filter(|r| r.assigned_taxi.is_some()) .count(); let num_waiting_requests = self .active_requests .iter() .filter(|r| r.assigned_taxi.is_none()) .count(); let num_archived_requests = self.archived_requests.len(); write!( f, "Age: {}/{}, Taxis: {} Occ/{} Tot, Requests: {} Asnd/{} Wai/{} Arch", self.age, self.runtime, num_occupied_taxis, num_total_taxis, num_assigned_requests, num_waiting_requests, num_archived_requests, ) } } fn main() { let mut world = World::new(86400, 0.2, 2000, 200); world.run_till_done(); }
use std::cmp::{max, min}; use std::collections::HashMap; use std::convert::From; use std::ops::{Add, AddAssign}; #[macro_use] extern crate num_derive; use aoc2019::aoc_input::get_input; use aoc2019::intcode::*; use num_traits::{FromPrimitive, ToPrimitive}; #[derive(Debug, Copy, Clone, PartialEq, Eq, FromPrimitive, ToPrimitive)] enum Turn { Left = 0, Right = 1, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum Direction { Up, Right, Down, Left, } impl Direction { fn turn(self, to: Turn) -> Self { match (self, to) { (Direction::Up, Turn::Right) | (Direction::Down, Turn::Left) => Direction::Right, (Direction::Up, Turn::Left) | (Direction::Down, Turn::Right) => Direction::Left, (Direction::Left, Turn::Right) | (Direction::Right, Turn::Left) => Direction::Up, (Direction::Left, Turn::Left) | (Direction::Right, Turn::Right) => Direction::Down, } } } #[repr(u8)] #[derive(Debug, Copy, Clone, PartialEq, Eq, FromPrimitive, ToPrimitive)] enum PanelColor { Black = 0, White = 1, } struct Delta { dx: isize, dy: isize, } impl From<Direction> for Delta { fn from(d: Direction) -> Self { match d { Direction::Up => Delta { dx: 0, dy: -1 }, Direction::Right => Delta { dx: 1, dy: 0 }, Direction::Down => Delta { dx: 0, dy: 1 }, Direction::Left => Delta { dx: -1, dy: 0 }, } } } #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] struct Coordinate { x: isize, y: isize, } impl Coordinate { fn origin() -> Coordinate { Coordinate { x: 0, y: 0 } } } impl Add<Delta> for Coordinate { type Output = Coordinate; fn add(self, rhs: Delta) -> Self::Output { Coordinate { x: self.x + rhs.dx, y: self.y + rhs.dy, } } } impl AddAssign<Delta> for Coordinate { fn add_assign(&mut self, rhs: Delta) { *self = *self + rhs; } } enum RobotRunResult { Done, Paint(PanelColor), } struct Robot { brain: IntcodeMachine, location: Coordinate, direction: Direction, } impl Robot { fn new(program: Tape) -> Robot { Robot { brain: IntcodeMachine::new(program), location: Coordinate::origin(), direction: Direction::Up, } } fn feed_input(&mut self, value: isize) { self.brain.input.borrow_mut().push_back(value); } fn read_output(&mut self) -> isize { self.brain.output.borrow_mut().pop_front().unwrap() } fn step(&mut self, location_color: PanelColor) -> RobotRunResult { self.feed_input(location_color.to_isize().unwrap()); match self.brain.run().unwrap() { StopStatus::Halted => RobotRunResult::Done, StopStatus::BlockedOnInput => { let paint_request = self.read_output(); let paint_request = PanelColor::from_isize(paint_request).unwrap(); let turn = self.read_output(); self.direction = self.direction.turn(Turn::from_isize(turn).unwrap()); self.location += self.direction.into(); RobotRunResult::Paint(paint_request) } } } } struct Board { grid: HashMap<Coordinate, PanelColor>, robot: Robot, } impl Board { fn new(robot: Robot, origin_color: PanelColor) -> Board { let mut board = Board { grid: HashMap::new(), robot, }; board.grid.insert(Coordinate::origin(), origin_color); board } fn run_robot(&mut self) { loop { let entry = self.grid.entry(self.robot.location); let current_panel = entry.or_insert(PanelColor::Black); match self.robot.step(*current_panel) { RobotRunResult::Done => break, RobotRunResult::Paint(new_color) => *current_panel = new_color, } } } fn painted_panels(&self) -> usize { self.grid.len() } fn render_grid(&self) -> String { let mut min_x = 0; let mut min_y = 0; let mut max_x = 0; let mut max_y = 0; for key in self.grid.keys() { min_x = min(min_x, key.x); min_y = min(min_y, key.y); max_x = max(max_x, key.x); max_y = max(max_y, key.y); } let mut rendered = String::new(); for y in min_y..=max_y { let mut line = String::new(); for x in min_x..=max_x { let coord = Coordinate { x, y }; let color = *self.grid.get(&coord).unwrap_or(&PanelColor::Black); let ch = match color { PanelColor::Black => ' ', PanelColor::White => '*', }; line.push(ch) } line.push('\n'); rendered.push_str(&line); } rendered } } fn main() { let program = parse_intcode_program(&get_input(11)); let mut board = Board::new(Robot::new(program.clone()), PanelColor::Black); board.run_robot(); println!("Painted panels: {}", board.painted_panels()); let mut board = Board::new(Robot::new(program), PanelColor::White); board.run_robot(); println!( "Grid when origin starts colored white:\n{}", board.render_grid() ); }
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkWin32SurfaceCreateInfoKHR { pub sType: VkStructureType, pub pNext: *const c_void, pub flags: VkWin32SurfaceCreateFlagBitsKHR, pub hinstance: *mut c_void, pub hwnd: *mut c_void, } impl VkWin32SurfaceCreateInfoKHR { pub fn new<T, U, V>(flags: T, hinstance: &mut U, hwnd: &mut V) -> Self where T: Into<VkWin32SurfaceCreateFlagBitsKHR>, { VkWin32SurfaceCreateInfoKHR { sType: VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR, pNext: ptr::null(), flags: flags.into(), hinstance: hinstance as *mut U as *mut c_void, hwnd: hwnd as *mut V as *mut c_void, } } }
// Copyright 2018 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. #![feature(arbitrary_self_types, futures_api, pin)] #![allow(unused)] use std::boxed::PinBox; use std::future::Future; use std::mem::PinMut; use std::rc::Rc; use std::sync::{ Arc, atomic::{self, AtomicUsize}, }; use std::future::FutureObj; use std::task::{ Context, Poll, Wake, Waker, LocalWaker, Spawn, SpawnObjError, local_waker, local_waker_from_nonlocal, }; struct Counter { local_wakes: AtomicUsize, nonlocal_wakes: AtomicUsize, } impl Wake for Counter { fn wake(this: &Arc<Self>) { this.nonlocal_wakes.fetch_add(1, atomic::Ordering::SeqCst); } unsafe fn wake_local(this: &Arc<Self>) { this.local_wakes.fetch_add(1, atomic::Ordering::SeqCst); } } struct NoopSpawner; impl Spawn for NoopSpawner { fn spawn_obj(&mut self, _: FutureObj<'static, ()>) -> Result<(), SpawnObjError> { Ok(()) } } struct MyFuture; impl Future for MyFuture { type Output = (); fn poll(self: PinMut<Self>, cx: &mut Context) -> Poll<Self::Output> { // Ensure all the methods work appropriately cx.waker().wake(); cx.waker().wake(); cx.local_waker().wake(); cx.spawner().spawn_obj(PinBox::new(MyFuture).into()).unwrap(); Poll::Ready(()) } } fn test_local_waker() { let counter = Arc::new(Counter { local_wakes: AtomicUsize::new(0), nonlocal_wakes: AtomicUsize::new(0), }); let waker = unsafe { local_waker(counter.clone()) }; let spawner = &mut NoopSpawner; let cx = &mut Context::new(&waker, spawner); assert_eq!(Poll::Ready(()), PinMut::new(&mut MyFuture).poll(cx)); assert_eq!(1, counter.local_wakes.load(atomic::Ordering::SeqCst)); assert_eq!(2, counter.nonlocal_wakes.load(atomic::Ordering::SeqCst)); } fn test_local_as_nonlocal_waker() { let counter = Arc::new(Counter { local_wakes: AtomicUsize::new(0), nonlocal_wakes: AtomicUsize::new(0), }); let waker: LocalWaker = local_waker_from_nonlocal(counter.clone()); let spawner = &mut NoopSpawner; let cx = &mut Context::new(&waker, spawner); assert_eq!(Poll::Ready(()), PinMut::new(&mut MyFuture).poll(cx)); assert_eq!(0, counter.local_wakes.load(atomic::Ordering::SeqCst)); assert_eq!(3, counter.nonlocal_wakes.load(atomic::Ordering::SeqCst)); } fn main() { test_local_waker(); test_local_as_nonlocal_waker(); }
//! Platform-specific types are required to implement the following traits. use std::fmt::Debug; use std::rc::Rc; use num_traits::identities::Zero; use uom::si::time::{day, hour}; use crate::units::{Bound, ElectricPotential, Energy, Power, Ratio, ThermodynamicTemperature, Time}; use crate::{Result, State, Technology}; pub trait BatteryManager: Debug + Sized { type Iterator: BatteryIterator; fn new() -> Result<Self>; fn refresh(&self, battery: &mut <Self::Iterator as BatteryIterator>::Device) -> Result<()>; } pub trait BatteryIterator: Iterator<Item = Result<<Self as BatteryIterator>::Device>> + Debug + Sized { type Manager: BatteryManager<Iterator = Self>; type Device: BatteryDevice; /// Iterator is required to store reference to the `Self::Manager` type, /// even if it does not use it. /// In that case all iterator instances will be freed before the manager. /// /// Implemented `next()` for `<Self as Iterator>` must preload all needed battery data /// in this method, because `BatteryDevice` methods are infallible. fn new(manager: Rc<Self::Manager>) -> Result<Self>; } /// Underline type for `Battery`, different for each supported platform. pub trait BatteryDevice: Sized + Debug { fn state_of_health(&self) -> Ratio { // It it possible to get values greater that `1.0`, which is logical nonsense, // forcing the value to be in `0.0..=1.0` range (self.energy_full() / self.energy_full_design()).into_bounded() } fn state_of_charge(&self) -> Ratio { // It it possible to get values greater that `1.0`, which is logical nonsense, // forcing the value to be in `0.0..=1.0` range (self.energy() / self.energy_full()).into_bounded() } fn energy(&self) -> Energy; fn energy_full(&self) -> Energy; fn energy_full_design(&self) -> Energy; fn energy_rate(&self) -> Power; fn state(&self) -> State; fn voltage(&self) -> ElectricPotential; fn temperature(&self) -> Option<ThermodynamicTemperature>; fn vendor(&self) -> Option<&str>; fn model(&self) -> Option<&str>; fn serial_number(&self) -> Option<&str>; fn technology(&self) -> Technology; fn cycle_count(&self) -> Option<u32>; // Default implementation for `time_to_full` and `time_to_empty` // uses calculation based on the current energy flow, // but if device provides by itself provides these **instant** values (do not use average values), // it would be easier and cheaper to return them instead of making some calculations fn time_to_full(&self) -> Option<Time> { let energy_rate = self.energy_rate(); match self.state() { // In some cases energy_rate can be 0 while Charging, for example just after // plugging in the charger. Assume that the battery doesn't have time_to_full in such // cases, to avoid division by zero. See https://github.com/svartalf/rust-battery/pull/5 State::Charging if !energy_rate.is_zero() => { // Some drivers might report that `energy_full` is lower than `energy`, // but battery is still charging. What should we do in that case? // As for now, assuming that battery is fully charged, since we can't guess, // how much time left. let energy_left = match self.energy_full() - self.energy() { value if value.is_sign_positive() => value, _ => return None, }; let time_to_full = energy_left / energy_rate; if time_to_full.get::<hour>() > 10.0 { // Ten hours for charging is too much None } else { Some(time_to_full) } } _ => None, } } fn time_to_empty(&self) -> Option<Time> { let energy_rate = self.energy_rate(); match self.state() { // In some cases energy_rate can be 0 while Discharging, for example just after // unplugging the charger. Assume that the battery doesn't have time_to_empty in such // cases, to avoid divison by zero. See https://github.com/svartalf/rust-battery/pull/5 State::Discharging if !energy_rate.is_zero() => { let time_to_empty = self.energy() / energy_rate; if time_to_empty.get::<day>() > 10.0 { // Ten days for discharging is too much None } else { Some(time_to_empty) } } _ => None, } } }
#![cfg_attr(not(test), no_std)] #![cfg_attr(all(feature = "nightly"), feature(allow_internal_unstable, macro_vis_matcher))] #![forbid(missing_docs)] //! A library for defining enums that can be used in compact bit sets. It supports enums up to 128 //! variants, and has a macro to use these sets in constants. //! //! # Defining enums for use with EnumSet //! //! Enums to be used with [`EnumSet`] should be defined through the [`enum_set_type!`] macro: //! //! ```rust //! # #[macro_use] extern crate enumset; //! # use enumset::*; //! enum_set_type! { //! /// Documentation for the enum //! pub enum Enum { //! A, B, C, D, E, F, //! #[doc(hidden)] G, //! } //! } //! # fn main() { } //! ``` //! //! # Working with EnumSets //! //! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition, //! [`enum_set_type!`] creates operator overloads that allow you to create EnumSets like so: //! //! ```rust //! # #[macro_use] extern crate enumset; //! # use enumset::*; //! # enum_set_type! { //! # pub enum Enum { //! # A, B, C, D, E, F, G, //! # } //! # } //! let new_set = Enum::A | Enum::C | Enum::G; //! assert_eq!(new_set.len(), 3); //! ``` //! //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and //! enums wrapped with [`enum_set_type!`]: //! ``` //! # #[macro_use] extern crate enumset; //! # use enumset::*; //! # enum_set_type! { //! # pub enum Enum { //! # A, B, C, D, E, F, G, //! # } //! # } //! // Intersection of sets //! assert_eq!((Enum::A | Enum::B) & Enum::C, EnumSet::empty()); //! assert_eq!((Enum::A | Enum::B) & Enum::A, Enum::A); //! assert_eq!(Enum::A & Enum::B, EnumSet::empty()); //! //! // Symmetric difference of sets //! assert_eq!((Enum::A | Enum::B) ^ (Enum::B | Enum::C), Enum::A | Enum::C); //! assert_eq!(Enum::A ^ Enum::C, Enum::A | Enum::C); //! //! // Difference of sets //! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C); //! //! // Complement of sets //! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F); //! ``` //! //! The [`enum_set!`] macro allows you to create EnumSets in constant contexts: //! //! ```rust //! # #[macro_use] extern crate enumset; //! # use enumset::*; //! # enum_set_type! { //! # enum Enum { A, B, C } //! # } //! const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B); //! assert_eq!(CONST_SET, Enum::A | Enum::B); //! ``` //! //! Mutable operations on the [`EnumSet`] otherwise work basically as expected: //! //! ```rust //! # #[macro_use] extern crate enumset; //! # use enumset::*; //! # enum_set_type! { //! # pub enum Enum { //! # A, B, C, D, E, F, G, //! # } //! # } //! let mut set = EnumSet::new(); //! set.insert(Enum::A); //! set.insert_all(Enum::E | Enum::G); //! assert!(set.contains(Enum::A)); //! assert!(!set.contains(Enum::B)); //! assert_eq!(set, Enum::A | Enum::E | Enum::G); //! ``` #[cfg(test)] extern crate core; extern crate num_traits; use core::fmt; use core::fmt::{Debug, Formatter}; use core::hash::Hash; use core::ops::*; use num_traits::*; #[doc(hidden)] /// The trait used to define enum types. /// This is **NOT** public API and may change at any time. pub unsafe trait EnumSetType : Copy + Ord + Eq + Hash { type Repr: PrimInt + ToPrimitive + FromPrimitive + WrappingSub + CheckedShl + Debug + Hash; const VARIANT_COUNT: u8; fn enum_into_u8(self) -> u8; unsafe fn enum_from_u8(val: u8) -> Self; } #[doc(hidden)] /// A struct used to type check [`enum_set!`]. /// This is **NOT** public API and may change at any time. pub struct EnumSetSameTypeHack<'a, T: EnumSetType + 'static> { pub unified: &'a [T], pub enum_set: EnumSet<T>, } /// An efficient set type for enums created with the [`enum_set_type!`](./macro.enum_set_type.html) /// macro. #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct EnumSet<T : EnumSetType> { #[doc(hidden)] /// This is public due to the [`enum_set!`] macro. /// This is **NOT** public API and may change at any time. pub __enumset_underlying: T::Repr } impl <T : EnumSetType> EnumSet<T> { fn mask(bit: u8) -> T::Repr { T::Repr::one() << bit as usize } fn has_bit(&self, bit: u8) -> bool { let mask = Self::mask(bit); self.__enumset_underlying & mask == mask } fn partial_bits(bits: u8) -> T::Repr { assert!(bits != 0 && bits <= T::VARIANT_COUNT); T::Repr::one().checked_shl(bits.into()) .unwrap_or(T::Repr::zero()) .wrapping_sub(&T::Repr::one()) } // Returns all bits valid for the enum fn all_bits() -> T::Repr { Self::partial_bits(T::VARIANT_COUNT) } /// Returns an empty set. pub fn new() -> Self { EnumSet { __enumset_underlying: T::Repr::zero() } } /// Returns a set containing a single value. pub fn only(t: T) -> Self { EnumSet { __enumset_underlying: Self::mask(t.enum_into_u8()) } } /// Returns an empty set. pub fn empty() -> Self { Self::new() } /// Returns a set with all bits set. pub fn all() -> Self { EnumSet { __enumset_underlying: Self::all_bits() } } /// Total number of bits this enumset uses. Note that the actual amount of space used is /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`). pub fn bit_width() -> u8 { T::VARIANT_COUNT as u8 } /// Returns the raw bits of this set pub fn to_bits(&self) -> u128 { self.__enumset_underlying.to_u128() .expect("Impossible: Bits cannot be to converted into i128?") } /// Constructs a bitset from raw bits. /// /// # Panics /// If bits not in the enum are set. pub fn from_bits(bits: u128) -> Self { assert!((bits & !Self::all().to_bits()) == 0, "Bits not valid for the enum were set."); EnumSet { __enumset_underlying: T::Repr::from_u128(bits) .expect("Impossible: Valid bits too large to fit in repr?") } } /// Returns the number of values in this set. pub fn len(&self) -> usize { self.__enumset_underlying.count_ones() as usize } /// Checks if the set is empty. pub fn is_empty(&self) -> bool { self.__enumset_underlying.is_zero() } /// Removes all elements from the set. pub fn clear(&mut self) { self.__enumset_underlying = T::Repr::zero() } /// Checks if this set shares no elements with another. pub fn is_disjoint(&self, other: Self) -> bool { (*self & other).is_empty() } /// Checks if all elements in another set are in this set. pub fn is_superset(&self, other: Self) -> bool { *self & other == other } /// Checks if all elements of this set are in another set. pub fn is_subset(&self, other: Self) -> bool { other.is_superset(*self) } /// Returns a set containing the union of all elements in both sets. pub fn union(&self, other: Self) -> Self { EnumSet { __enumset_underlying: self.__enumset_underlying | other.__enumset_underlying } } /// Returns a set containing all elements in common with another set. pub fn intersection(&self, other: Self) -> Self { EnumSet { __enumset_underlying: self.__enumset_underlying & other.__enumset_underlying } } /// Returns a set with all elements of the other set removed. pub fn difference(&self, other: Self) -> Self { EnumSet { __enumset_underlying: self.__enumset_underlying & !other.__enumset_underlying } } /// Returns a set with all elements not contained in both sets. pub fn symmetrical_difference(&self, other: Self) -> Self { EnumSet { __enumset_underlying: self.__enumset_underlying ^ other.__enumset_underlying } } /// Returns a set containing all elements not in this set. pub fn complement(&self) -> Self { EnumSet { __enumset_underlying: !self.__enumset_underlying & Self::all_bits() } } /// Checks whether this set contains a value. pub fn contains(&self, value: T) -> bool { self.has_bit(value.enum_into_u8()) } /// Adds a value to this set. pub fn insert(&mut self, value: T) -> bool { let contains = self.contains(value); self.__enumset_underlying = self.__enumset_underlying | Self::mask(value.enum_into_u8()); contains } /// Removes a value from this set. pub fn remove(&mut self, value: T) -> bool { let contains = self.contains(value); self.__enumset_underlying = self.__enumset_underlying & !Self::mask(value.enum_into_u8()); contains } /// Adds all elements in another set to this one. pub fn insert_all(&mut self, other: Self) { self.__enumset_underlying = self.__enumset_underlying | other.__enumset_underlying } /// Removes all values in another set from this one. pub fn remove_all(&mut self, other: Self) { self.__enumset_underlying = self.__enumset_underlying & !other.__enumset_underlying } /// Creates an iterator over the values in this set. pub fn iter(&self) -> EnumSetIter<T> { EnumSetIter(*self, 0) } } impl <T : EnumSetType> IntoIterator for EnumSet<T> { type Item = T; type IntoIter = EnumSetIter<T>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl <T : EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> { type Output = Self; fn sub(self, other: O) -> Self::Output { self.difference(other.into()) } } impl <T : EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> { type Output = Self; fn bitand(self, other: O) -> Self::Output { self.intersection(other.into()) } } impl <T : EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> { type Output = Self; fn bitor(self, other: O) -> Self::Output { self.union(other.into()) } } impl <T : EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> { type Output = Self; fn bitxor(self, other: O) -> Self::Output { self.symmetrical_difference(other.into()) } } impl <T : EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> { fn sub_assign(&mut self, rhs: O) { *self = *self - rhs; } } impl <T : EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> { fn bitand_assign(&mut self, rhs: O) { *self = *self & rhs; } } impl <T : EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> { fn bitor_assign(&mut self, rhs: O) { *self = *self | rhs; } } impl <T : EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> { fn bitxor_assign(&mut self, rhs: O) { *self = *self ^ rhs; } } impl <T : EnumSetType> Not for EnumSet<T> { type Output = Self; fn not(self) -> Self::Output { self.complement() } } impl <T : EnumSetType> From<T> for EnumSet<T> { fn from(t: T) -> Self { EnumSet::only(t) } } impl <T : EnumSetType> PartialEq<T> for EnumSet<T> { fn eq(&self, other: &T) -> bool { *self == EnumSet::only(*other) } } impl <T : EnumSetType + Debug> Debug for EnumSet<T> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let mut is_first = true; f.write_str("EnumSet(")?; for v in self.iter() { if !is_first { f.write_str(" | ")?; } is_first = false; v.fmt(f)?; } f.write_str(")")?; Ok(()) } } /// The iterator used by [`EnumSet`](./struct.EnumSet.html). #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug)] pub struct EnumSetIter<T : EnumSetType>(EnumSet<T>, u8); impl <T : EnumSetType> Iterator for EnumSetIter<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { while self.1 < T::VARIANT_COUNT { let bit = self.1; self.1 += 1; if self.0.has_bit(bit) { return unsafe { Some(T::enum_from_u8(bit)) } } } None } fn size_hint(&self) -> (usize, Option<usize>) { let left_mask = EnumSet::<T>::partial_bits(self.1); let left = (self.0.__enumset_underlying & left_mask).count_ones() as usize; (left, Some(left)) } } #[macro_export] #[doc(hidden)] macro_rules! enum_set_type_internal_count_variants { ($next:ident ($($args:tt)*) $_00:ident $_01:ident $_02:ident $_03:ident $_04:ident $_05:ident $_06:ident $_07:ident $_10:ident $_11:ident $_12:ident $_13:ident $_14:ident $_15:ident $_16:ident $_17:ident $_20:ident $_21:ident $_22:ident $_23:ident $_24:ident $_25:ident $_26:ident $_27:ident $_30:ident $_31:ident $_32:ident $_33:ident $_34:ident $_35:ident $_36:ident $_37:ident $_40:ident $_41:ident $_42:ident $_43:ident $_44:ident $_45:ident $_46:ident $_47:ident $_50:ident $_51:ident $_52:ident $_53:ident $_54:ident $_55:ident $_56:ident $_57:ident $_60:ident $_61:ident $_62:ident $_63:ident $_64:ident $_65:ident $_66:ident $_67:ident $_70:ident $_71:ident $_72:ident $_73:ident $_74:ident $_75:ident $_76:ident $_77:ident $_80:ident $_81:ident $_82:ident $_83:ident $_84:ident $_85:ident $_86:ident $_87:ident $_90:ident $_91:ident $_92:ident $_93:ident $_94:ident $_95:ident $_96:ident $_97:ident $_a0:ident $_a1:ident $_a2:ident $_a3:ident $_a4:ident $_a5:ident $_a6:ident $_a7:ident $_b0:ident $_b1:ident $_b2:ident $_b3:ident $_b4:ident $_b5:ident $_b6:ident $_b7:ident $_c0:ident $_c1:ident $_c2:ident $_c3:ident $_c4:ident $_c5:ident $_c6:ident $_c7:ident $_d0:ident $_d1:ident $_d2:ident $_d3:ident $_d4:ident $_d5:ident $_d6:ident $_d7:ident $_e0:ident $_e1:ident $_e2:ident $_e3:ident $_e4:ident $_e5:ident $_e6:ident $_e7:ident $_f0:ident $_f1:ident $_f2:ident $_f3:ident $_f4:ident $_f5:ident $_f6:ident $_f7:ident $($rest:ident)+ ) => { compile_error!("enum_set_type! can only accept up to 128 variants.") }; ($next:ident ($($args:tt)*) $_00:ident $_01:ident $_02:ident $_03:ident $_04:ident $_05:ident $_06:ident $_07:ident $_10:ident $_11:ident $_12:ident $_13:ident $_14:ident $_15:ident $_16:ident $_17:ident $_20:ident $_21:ident $_22:ident $_23:ident $_24:ident $_25:ident $_26:ident $_27:ident $_30:ident $_31:ident $_32:ident $_33:ident $_34:ident $_35:ident $_36:ident $_37:ident $_40:ident $_41:ident $_42:ident $_43:ident $_44:ident $_45:ident $_46:ident $_47:ident $_50:ident $_51:ident $_52:ident $_53:ident $_54:ident $_55:ident $_56:ident $_57:ident $_60:ident $_61:ident $_62:ident $_63:ident $_64:ident $_65:ident $_66:ident $_67:ident $_70:ident $_71:ident $_72:ident $_73:ident $_74:ident $_75:ident $_76:ident $_77:ident $($rest:ident)+ ) => { enum_set_type_internal! { @$next u128 $($args)* } }; ($next:ident ($($args:tt)*) $_00:ident $_01:ident $_02:ident $_03:ident $_04:ident $_05:ident $_06:ident $_07:ident $_10:ident $_11:ident $_12:ident $_13:ident $_14:ident $_15:ident $_16:ident $_17:ident $_20:ident $_21:ident $_22:ident $_23:ident $_24:ident $_25:ident $_26:ident $_27:ident $_30:ident $_31:ident $_32:ident $_33:ident $_34:ident $_35:ident $_36:ident $_37:ident $($rest:ident)+ ) => { enum_set_type_internal! { @$next u64 $($args)* } }; ($next:ident ($($args:tt)*) $_00:ident $_01:ident $_02:ident $_03:ident $_04:ident $_05:ident $_06:ident $_07:ident $_10:ident $_11:ident $_12:ident $_13:ident $_14:ident $_15:ident $_16:ident $_17:ident $($rest:ident)+ ) => { enum_set_type_internal! { @$next u32 $($args)* } }; ($next:ident ($($args:tt)*) $_00:ident $_01:ident $_02:ident $_03:ident $_04:ident $_05:ident $_06:ident $_07:ident $($rest:ident)+ ) => { enum_set_type_internal! { @$next u16 $($args)* } }; ($next:ident ($($args:tt)*) $($rest:ident)*) => { enum_set_type_internal! { @$next u8 $($args)* } }; } #[macro_export] #[doc(hidden)] macro_rules! enum_set_type_internal { // Counting functions (@ident ($($random:tt)*) $value:expr) => { $value }; (@count $($value:tt)*) => { 0u8 $(+ enum_set_type_internal!(@ident ($value) 1u8))* }; // Codegen (@body $repr:ident ($(#[$enum_attr:meta])*) ($($vis:tt)*) $enum_name:ident { $($(#[$attr:meta])* $variant:ident,)* }) => { $(#[$enum_attr])* #[repr(u8)] #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug)] $($vis)* enum $enum_name { $($(#[$attr])* $variant,)* } unsafe impl $crate::EnumSetType for $enum_name { type Repr = $repr; const VARIANT_COUNT: u8 = enum_set_type_internal!(@count $($variant)*); fn enum_into_u8(self) -> u8 { self as u8 } unsafe fn enum_from_u8(val: u8) -> Self { ::std::mem::transmute(val) } } impl <O : Into<$crate::EnumSet<$enum_name>>> ::std::ops::Sub<O> for $enum_name { type Output = $crate::EnumSet<$enum_name>; fn sub(self, other: O) -> Self::Output { $crate::EnumSet::only(self) - other.into() } } impl <O : Into<$crate::EnumSet<$enum_name>>> ::std::ops::BitAnd<O> for $enum_name { type Output = $crate::EnumSet<$enum_name>; fn bitand(self, other: O) -> Self::Output { $crate::EnumSet::only(self) & other.into() } } impl <O : Into<$crate::EnumSet<$enum_name>>> ::std::ops::BitOr<O> for $enum_name { type Output = $crate::EnumSet<$enum_name>; fn bitor(self, other: O) -> Self::Output { $crate::EnumSet::only(self) | other.into() } } impl <O : Into<$crate::EnumSet<$enum_name>>> ::std::ops::BitXor<O> for $enum_name { type Output = $crate::EnumSet<$enum_name>; fn bitxor(self, other: O) -> Self::Output { $crate::EnumSet::only(self) ^ other.into() } } impl ::std::ops::Not for $enum_name { type Output = $crate::EnumSet<$enum_name>; fn not(self) -> Self::Output { !$crate::EnumSet::only(self) } } impl ::std::cmp::PartialEq<$crate::EnumSet<$enum_name>> for $enum_name { fn eq(&self, other: &$crate::EnumSet<$enum_name>) -> bool { $crate::EnumSet::only(*self) == *other } } }; } /// Defines enums which can be used with EnumSet. /// /// While attributes and documentation can be attached to the enum variants, the variants may not /// contain data. /// /// [`Copy`], [`Clone`], [`PartialOrd`], [`Ord`], [`PartialEq`], [`Eq`], [`Hash`], [`Debug`], /// [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] are automatically derived for the enum. /// /// These impls, in general, behave as if the enum variant was an [`EnumSet`] with a single value, /// as those created by [`EnumSet::only`]. /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate enumset; /// # use enumset::*; /// enum_set_type! { /// enum Enum { /// A, B, C, D, E, F, G /// } /// /// /// Documentation /// pub enum Enum2 { /// A, B, C, D, E, F, G, /// #[doc(hidden)] __NonExhaustive, /// } /// } /// # fn main() { } /// ``` #[macro_export] #[cfg(not(feature = "nightly"))] macro_rules! enum_set_type { ($(#[$enum_attr:meta])* pub enum $enum_name:ident { $($(#[$attr:meta])* $variant:ident),* $(,)* } $($rest:tt)*) => { enum_set_type_internal_count_variants!(body (($(#[$enum_attr])*) (pub) $enum_name { $($(#[$attr])* $variant,)* }) $($variant)*); enum_set_type!($($rest)*); }; ($(#[$enum_attr:meta])* enum $enum_name:ident { $($(#[$attr:meta])* $variant:ident),* $(,)* } $($rest:tt)*) => { enum_set_type_internal_count_variants!(body (($(#[$enum_attr])*) () $enum_name { $($(#[$attr])* $variant,)* }) $($variant)*); enum_set_type!($($rest)*); }; () => { }; } /// Defines enums which can be used with EnumSet. /// /// While attributes and documentation can be attached to the enum variants, the variants may not /// contain data. /// /// [`Copy`], [`Clone`], [`PartialOrd`], [`Ord`], [`PartialEq`], [`Eq`], [`Hash`], [`Debug`], /// [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] are automatically derived for the enum. /// /// These impls, in general, behave as if the enum variant was an [`EnumSet`] with a single value, /// as those created by [`EnumSet::only`]. /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate enumset; /// # use enumset::*; /// enum_set_type! { /// enum Enum { /// A, B, C, D, E, F, G /// } /// /// /// Documentation /// pub enum Enum2 { /// A, B, C, D, E, F, G, /// #[doc(hidden)] __NonExhaustive, /// } /// } /// # fn main() { } /// ``` #[macro_export] #[cfg(feature = "nightly")] #[allow_internal_unstable] macro_rules! enum_set_type { ($(#[$enum_attr:meta])* $vis:vis enum $enum_name:ident { $($(#[$attr:meta])* $variant:ident),* $(,)* } $($rest:tt)*) => { enum_set_type_internal_count_variants!(body (($(#[$enum_attr])*) ($vis) $enum_name { $($(#[$attr])* $variant,)* }) $($variant)*); enum_set_type!($($rest)*); }; () => { }; } /// Creates a EnumSet literal, which can be used in const contexts. /// /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same /// type, or a error will occur at compile-time. /// /// You may also explicitly state the type of the variants that follow, as in /// `enum_set!(Type, Type::A | Type::B | Type::C)`. /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate enumset; /// # use enumset::*; /// # enum_set_type! { /// # enum Enum { A, B, C } /// # } /// # fn main() { /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B); /// assert_eq!(CONST_SET, Enum::A | Enum::B); /// /// const EXPLICIT_CONST_SET: EnumSet<Enum> = enum_set!(Enum, Enum::A | Enum::B); /// assert_eq!(EXPLICIT_CONST_SET, Enum::A | Enum::B); /// # } /// ``` /// /// This macro is strongly typed. For example, the following will not compile: /// /// ```compile_fail /// # #[macro_use] extern crate enumset; /// # use enumset::*; /// # enum_set_type! { /// # enum Enum { A, B, C } /// # enum Enum2 { A, B, C } /// # } /// # fn main() { /// let type_error = enum_set!(Enum::A | Enum2::B); /// # } /// ``` #[macro_export] macro_rules! enum_set { () => { $crate::EnumSet { __enumset_underlying: 0 } }; ($($value:path)|* $(|)*) => { $crate::EnumSetSameTypeHack { unified: &[$($value,)*], enum_set: $crate::EnumSet { __enumset_underlying: 0 $(| (1 << ($value as u8)))* }, }.enum_set }; ($enum_name:ty, $($value:path)|* $(|)*) => { $crate::EnumSet::<$enum_name> { __enumset_underlying: 0 $(| (1 << ($value as $enum_name as u8)))* } } } #[cfg(test)] #[allow(dead_code)] mod test { use super::*; mod enums { enum_set_type! { pub enum SmallEnum { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } pub enum LargeEnum { _00, _01, _02, _03, _04, _05, _06, _07, _10, _11, _12, _13, _14, _15, _16, _17, _20, _21, _22, _23, _24, _25, _26, _27, _30, _31, _32, _33, _34, _35, _36, _37, _40, _41, _42, _43, _44, _45, _46, _47, _50, _51, _52, _53, _54, _55, _56, _57, _60, _61, _62, _63, _64, _65, _66, _67, _70, _71, _72, _73, _74, _75, _76, _77, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } pub enum Enum8 { A, B, C, D, E, F, G, H, } pub enum Enum128 { A, B, C, D, E, F, G, H, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, _71, _72, _73, _74, _75, _76, _77, _78, _79, _80, _81, _82, _83, _84, _85, _86, _87, _88, _89, _90, _91, _92, _93, _94, _95, _96, _97, _98, _99, _100, _101, _102, _103, _104, _105, _106, _107, _108, _109, _110, _111, _112, _113, _114, _115, _116, _117, _118, _119, _120, _121, _122, _123, _124, _125, _126, _127, } } } use self::enums::*; macro_rules! test_variants { ($enum_name:ident $variant_range:ident $all_empty_test:ident $($variant:ident,)*) => { #[test] fn $variant_range() { let count = enum_set_type_internal!(@count u8 $($variant)*); $( assert!(($enum_name::$variant as u8) < count); )* } #[test] fn $all_empty_test() { let all = EnumSet::<$enum_name>::all(); let empty = EnumSet::<$enum_name>::empty(); $( assert!(!empty.contains($enum_name::$variant)); assert!(all.contains($enum_name::$variant)); )* } } } test_variants! { SmallEnum enum_variant_range_test enum_all_empty A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } test_variants! { LargeEnum large_enum_variant_range_test large_enum_all_empty _00, _01, _02, _03, _04, _05, _06, _07, _10, _11, _12, _13, _14, _15, _16, _17, _20, _21, _22, _23, _24, _25, _26, _27, _30, _31, _32, _33, _34, _35, _36, _37, _40, _41, _42, _43, _44, _45, _46, _47, _50, _51, _52, _53, _54, _55, _56, _57, _60, _61, _62, _63, _64, _65, _66, _67, _70, _71, _72, _73, _74, _75, _76, _77, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } macro_rules! test_enum { ($e:ident, $m:ident) => { mod $m { use super::*; const CONST_SET: EnumSet<$e> = enum_set!($e, $e::A | $e::C); const EMPTY_SET: EnumSet<$e> = enum_set!(); #[test] fn const_set() { assert_eq!(CONST_SET.len(), 2); assert!(CONST_SET.contains($e::A)); assert!(CONST_SET.contains($e::C)); assert!(EMPTY_SET.is_empty()); } #[test] fn basic_add_remove() { let mut set = EnumSet::new(); set.insert($e::A); set.insert($e::B); set.insert($e::C); assert_eq!(set, $e::A | $e::B | $e::C); set.remove($e::B); assert_eq!(set, $e::A | $e::C); set.insert($e::D); assert_eq!(set, $e::A | $e::C | $e::D); set.insert_all($e::F | $e::E | $e::G); assert_eq!(set, $e::A | $e::C | $e::D | $e::F | $e::E | $e::G); set.remove_all($e::A | $e::D | $e::G); assert_eq!(set, $e::C | $e::F | $e::E); assert!(!set.is_empty()); set.clear(); assert!(set.is_empty()); } #[test] fn empty_is_empty() { assert_eq!(EnumSet::<$e>::empty().len(), 0) } #[test] fn all_len() { assert_eq!(EnumSet::<$e>::all().len(), EnumSet::<$e>::bit_width() as usize) } #[test] fn basic_iter_test() { let mut set = EnumSet::new(); set.insert($e::A); set.insert($e::B); set.insert($e::C); set.insert($e::E); let mut set_2 = EnumSet::new(); let vec: Vec<$e> = set.iter().collect(); for val in vec { assert!(!set_2.contains(val)); set_2.insert(val); } assert_eq!(set, set_2); let mut set_3 = EnumSet::new(); for val in set { assert!(!set_3.contains(val)); set_3.insert(val); } assert_eq!(set, set_3); } #[test] fn basic_ops_test() { assert_eq!(($e::A | $e::B) | ($e::B | $e::C), $e::A | $e::B | $e::C); assert_eq!(($e::A | $e::B) & ($e::B | $e::C), $e::B); assert_eq!(($e::A | $e::B) ^ ($e::B | $e::C), $e::A | $e::C); assert_eq!(($e::A | $e::B) - ($e::B | $e::C), $e::A); } #[test] fn basic_set_status() { assert!(($e::A | $e::B | $e::C).is_disjoint($e::D | $e::E | $e::F)); assert!(!($e::A | $e::B | $e::C | $e::D).is_disjoint($e::D | $e::E | $e::F)); assert!(($e::A | $e::B).is_subset($e::A | $e::B | $e::C)); assert!(!($e::A | $e::D).is_subset($e::A | $e::B | $e::C)); } #[test] fn debug_impl() { assert_eq!(format!("{:?}", $e::A | $e::B | $e::D), "EnumSet(A | B | D)"); } #[test] fn to_from_bits() { let value = $e::A | $e::C | $e::D | $e::F | $e::E | $e::G; assert_eq!(EnumSet::from_bits(value.to_bits()), value); } #[test] #[should_panic] fn too_many_bits() { if EnumSet::<$e>::bit_width() == 128 { panic!("(test skipped)") } EnumSet::<$e>::from_bits(!0); } } } } test_enum!(SmallEnum, small_enum); test_enum!(LargeEnum, large_enum); test_enum!(Enum8, enum8); test_enum!(Enum128, enum128); }
#[cfg(feature = "tokio")] #[path="simple_daemon_tokio/mod.rs"] mod simple_daemon_impl; #[cfg(feature = "tokio-core")] #[path="simple_daemon_tokio_core/mod.rs"] mod simple_daemon_impl; fn main() { simple_daemon_impl::main() }
use core::{ fmt, ops::{BitAnd, BitOr, BitXor, Not}, }; use crate::{ iter, parser::{ParseError, ParseHex, WriteHex}, }; /// Metadata for an individual flag. pub struct Flag<B> { name: &'static str, value: B, } impl<B> Flag<B> { /// Create a new flag with the given name and value. pub const fn new(name: &'static str, value: B) -> Self { Flag { name, value } } /// Get the name of this flag. pub const fn name(&self) -> &'static str { self.name } /// Get the value of this flag. pub const fn value(&self) -> &B { &self.value } } /// A set of flags. /// /// This trait is automatically implemented for flags types defined using the `bitflags!` macro. /// It can also be implemented manually for custom flags types. pub trait Flags: Sized + 'static { /// The set of available flags and their names. const FLAGS: &'static [Flag<Self>]; /// The underlying storage type. type Bits: Bits; /// Returns an empty set of flags. fn empty() -> Self { Self::from_bits_retain(Self::Bits::EMPTY) } /// Returns the set containing all flags. fn all() -> Self { Self::from_bits_truncate(Self::Bits::ALL) } /// Returns the raw value of the flags currently stored. fn bits(&self) -> Self::Bits; /// Convert from underlying bit representation, unless that /// representation contains bits that do not correspond to a flag. /// /// Note that each [multi-bit flag] is treated as a unit for this comparison. /// /// [multi-bit flag]: index.html#multi-bit-flags fn from_bits(bits: Self::Bits) -> Option<Self> { let truncated = Self::from_bits_truncate(bits); if truncated.bits() == bits { Some(truncated) } else { None } } /// Convert from underlying bit representation, dropping any bits /// that do not correspond to flags. /// /// Note that each [multi-bit flag] is treated as a unit for this comparison. /// /// [multi-bit flag]: index.html#multi-bit-flags fn from_bits_truncate(bits: Self::Bits) -> Self { if bits == Self::Bits::EMPTY { return Self::empty(); } let mut truncated = Self::Bits::EMPTY; for flag in Self::FLAGS.iter() { let flag = flag.value(); if bits & flag.bits() == flag.bits() { truncated = truncated | flag.bits(); } } Self::from_bits_retain(truncated) } /// Convert from underlying bit representation, preserving all /// bits (even those not corresponding to a defined flag). fn from_bits_retain(bits: Self::Bits) -> Self; /// Get the flag for a particular name. fn from_name(name: &str) -> Option<Self> { for flag in Self::FLAGS { if flag.name() == name { return Some(Self::from_bits_retain(flag.value().bits())); } } None } /// Iterate over enabled flag values. fn iter(&self) -> iter::Iter<Self> { iter::Iter::new(self) } /// Iterate over the raw names and bits for enabled flag values. fn iter_names(&self) -> iter::IterNames<Self> { iter::IterNames::new(self) } /// Returns `true` if no flags are currently stored. fn is_empty(&self) -> bool { self.bits() == Self::Bits::EMPTY } /// Returns `true` if all flags are currently set. fn is_all(&self) -> bool { // NOTE: We check against `Self::all` here, not `Self::Bits::ALL` // because the set of all flags may not use all bits Self::all().bits() | self.bits() == self.bits() } /// Returns `true` if there are flags common to both `self` and `other`. fn intersects(&self, other: Self) -> bool where Self: Sized, { self.bits() & other.bits() != Self::Bits::EMPTY } /// Returns `true` if all of the flags in `other` are contained within `self`. fn contains(&self, other: Self) -> bool where Self: Sized, { self.bits() & other.bits() == other.bits() } /// Inserts the specified flags in-place. /// /// This method is equivalent to `union`. fn insert(&mut self, other: Self) where Self: Sized, { *self = Self::from_bits_retain(self.bits() | other.bits()); } /// Removes the specified flags in-place. /// /// This method is equivalent to `difference`. fn remove(&mut self, other: Self) where Self: Sized, { *self = Self::from_bits_retain(self.bits() & !other.bits()); } /// Toggles the specified flags in-place. /// /// This method is equivalent to `symmetric_difference`. fn toggle(&mut self, other: Self) where Self: Sized, { *self = Self::from_bits_retain(self.bits() ^ other.bits()); } /// Inserts or removes the specified flags depending on the passed value. fn set(&mut self, other: Self, value: bool) where Self: Sized, { if value { self.insert(other); } else { self.remove(other); } } /// Returns the intersection between the flags in `self` and `other`. #[must_use] fn intersection(self, other: Self) -> Self { Self::from_bits_retain(self.bits() & other.bits()) } /// Returns the union of between the flags in `self` and `other`. #[must_use] fn union(self, other: Self) -> Self { Self::from_bits_retain(self.bits() | other.bits()) } /// Returns the difference between the flags in `self` and `other`. #[must_use] fn difference(self, other: Self) -> Self { Self::from_bits_retain(self.bits() & !other.bits()) } /// Returns the symmetric difference between the flags /// in `self` and `other`. #[must_use] fn symmetric_difference(self, other: Self) -> Self { Self::from_bits_retain(self.bits() ^ other.bits()) } /// Returns the complement of this set of flags. #[must_use] fn complement(self) -> Self { Self::from_bits_truncate(!self.bits()) } } /// Underlying storage for a flags type. pub trait Bits: Clone + Copy + PartialEq + BitAnd<Output = Self> + BitOr<Output = Self> + BitXor<Output = Self> + Not<Output = Self> + Sized + 'static { /// The value of `Self` where no bits are set. const EMPTY: Self; /// The value of `Self` where all bits are set. const ALL: Self; } // Not re-exported: prevent custom `Bits` impls being used in the `bitflags!` macro, // or they may fail to compile based on crate features pub trait Primitive {} macro_rules! impl_bits { ($($u:ty, $i:ty,)*) => { $( impl Bits for $u { const EMPTY: $u = 0; const ALL: $u = <$u>::MAX; } impl Bits for $i { const EMPTY: $i = 0; const ALL: $i = <$u>::MAX as $i; } impl ParseHex for $u { fn parse_hex(input: &str) -> Result<Self, ParseError> { <$u>::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input)) } } impl ParseHex for $i { fn parse_hex(input: &str) -> Result<Self, ParseError> { <$i>::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input)) } } impl WriteHex for $u { fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result { write!(writer, "{:x}", self) } } impl WriteHex for $i { fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result { write!(writer, "{:x}", self) } } impl Primitive for $i {} impl Primitive for $u {} )* } } impl_bits! { u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, usize, isize, } /// A trait for referencing the `bitflags`-owned internal type /// without exposing it publicly. pub trait PublicFlags { /// The type of the underlying storage. type Primitive: Primitive; /// The type of the internal field on the generated flags type. type Internal; } #[deprecated(note = "use the `Flags` trait instead")] pub trait BitFlags: ImplementedByBitFlagsMacro + Flags { /// An iterator over enabled flags in an instance of the type. type Iter: Iterator<Item = Self>; /// An iterator over the raw names and bits for enabled flags in an instance of the type. type IterNames: Iterator<Item = (&'static str, Self)>; } #[allow(deprecated)] impl<B: Flags> BitFlags for B { type Iter = iter::Iter<Self>; type IterNames = iter::IterNames<Self>; } impl<B: Flags> ImplementedByBitFlagsMacro for B {} /// A marker trait that signals that an implementation of `BitFlags` came from the `bitflags!` macro. /// /// There's nothing stopping an end-user from implementing this trait, but we don't guarantee their /// manual implementations won't break between non-breaking releases. #[doc(hidden)] pub trait ImplementedByBitFlagsMacro {} pub(crate) mod __private { pub use super::{ImplementedByBitFlagsMacro, PublicFlags}; }
use std::collections::BTreeSet; use join::Join; use proconio::input; fn main() { input! { n: usize, k: usize, }; if n / 2 < k { println!("-1"); return; } let mut ans = Vec::new(); let mut set = BTreeSet::new(); for i in (k + 1)..=n { set.insert(i); } let mut used = vec![false; n + 1]; let first = set.iter().next().copied().unwrap(); used[first] = true; ans.push(first); set.remove(&first); for i in 2..=n { if i > k { if !used[i - k] { let new = set.insert(i - k); assert_eq!(new, true); } } if i + k - 1 <= n { set.remove(&(i + k - 1)); } if n - k < i + k && i + k <= n { if !used[i + k] { used[i + k] = true; ans.push(i + k); set.remove(&(i + k)); continue; } } let min = set.iter().next().copied().unwrap(); used[min] = true; ans.push(min); set.remove(&min); } println!("{}", ans.iter().join(" ")); }
use std::collections::HashSet; fn main() { let input = include_str!("input.txt"); println!("{}", thingy_day2(&frequencies_from_string(&input))) } fn frequencies_from_string(freq_string: &str) -> Vec<i32> { let thing = freq_string.lines().map(|s| s.parse().unwrap()).collect::<Vec<i32>>(); thing } fn thingy(freq: &[i32]) -> i32 { let mut total = 0; for f in freq { total += f; } total } fn thingy_day2(freq: &[i32]) -> i32 { let mut set = HashSet::new(); set.insert(0); let mut total = 0; for f in freq.iter().cycle() { total += f; if set.contains(&total) { return total } set.insert(total); } 0 } #[test] fn day2_given_plusone_minusone_returns_0() { assert_eq!(thingy_day2(&[1, -1]), 0) } #[test] fn given_nothing_returns_zero() { assert_eq!(thingy(&[]), 0); } #[test] fn given_single_one_returns_one() { assert_eq!(thingy(&[1]), 1); } #[test] fn given_empty_string_returns_empty_list() { assert_eq!(frequencies_from_string(""), []); } #[test] fn given_single_number_string_returns_single_element() { assert_eq!(frequencies_from_string("1"), [1]); } #[test] fn given_test_cases() { assert_eq!(thingy(&[1, 1, 1]), 3); assert_eq!(thingy(&[1, 1, -2]), 0); assert_eq!(thingy(&[-1, -2, -3]), -6); }
//! Handles all REST endpoints use actix_web::web::ServiceConfig; use chrono; use futures_cpupool::CpuPool; use handlebars; use handlebars::Handlebars; use hyper_tls::HttpsConnector; use serde::Deserialize; use serde_json; use std::sync::Arc; use crate::db; mod api; mod auth; mod github_login; mod logger; mod static_files; mod web; use crate::github::GenericHttpClient; pub use self::auth::{AuthenticateUser, AuthenticatedUser}; pub use self::logger::MiddlewareLogger; /// Registers all servlets in this module with the HTTP app. pub fn register_servlets(config: &mut ServiceConfig, state: &AppState) { github_login::register_servlets(config); api::register_servlets(config); static_files::register_servlets(config, state); web::register_servlets(config) } // Holds the state for the shared state of the app. Gets cloned to each thread. #[derive(Clone)] pub struct AppState { pub database: Arc<dyn db::Database>, pub config: AppConfig, pub cpu_pool: futures_cpupool::CpuPool, pub handlebars: Arc<handlebars::Handlebars<'static>>, pub http_client: Arc<dyn GenericHttpClient>, } impl AppState { pub fn new( config: AppConfig, handlebars: Handlebars<'static>, database: impl db::Database + 'static, ) -> AppState { // Thread pool to use mainly for DB let cpu_pool = CpuPool::new_num_cpus(); // Set up HTTPS enabled HTTP client let https = HttpsConnector::new(); let http_client = hyper::Client::builder().build::<_, hyper::Body>(https); AppState { database: Arc::new(database), http_client: Arc::new(http_client), cpu_pool, config, handlebars: Arc::new(handlebars), } } pub fn with_http_client( config: AppConfig, handlebars: Handlebars<'static>, database: impl db::Database + 'static, http_client: impl GenericHttpClient + 'static, ) -> AppState { // Thread pool to use mainly for DB let cpu_pool = CpuPool::new_num_cpus(); AppState { database: Arc::new(database), http_client: Arc::new(http_client), cpu_pool, config, handlebars: Arc::new(handlebars), } } } /// Read only config for the app #[derive(Clone)] pub struct AppConfig { pub github_client_id: String, pub github_client_secret: String, pub github_state: String, pub web_root: String, pub required_org: String, pub resource_dir: String, } /// Formats the current time plus two weeks into a cookie expires field. pub fn get_expires_string() -> String { let dt = chrono::Utc::now() + chrono::Duration::weeks(2); const ITEMS: &[chrono::format::Item<'static>] = &[chrono::format::Item::Fixed(chrono::format::Fixed::RFC2822)]; dt.format_with_items(ITEMS.iter().cloned()).to_string() } /// Format pence into a pretty pounds string fn format_pence_as_pounds(pence: i64) -> String { if pence < 0 { format!("-£{:2}.{:02}", -pence / 100, -pence % 100) } else { format!("£{:2}.{:02}", pence / 100, pence % 100) } } /// Handlebars helper function for formatting pence as points. pub fn format_pence_as_pounds_helper( h: &handlebars::Helper, _: &handlebars::Handlebars, _: &handlebars::Context, _: &mut handlebars::RenderContext, out: &mut dyn handlebars::Output, ) -> Result<(), handlebars::RenderError> { let param = h.param(0).unwrap(); match *param.value() { serde_json::Value::Number(ref number) => { let pence = number .as_i64() .ok_or_else(|| handlebars::RenderError::new("Param must be a number"))?; out.write(&format_pence_as_pounds(pence))?; Ok(()) } _ => Err(handlebars::RenderError::new("Param must be a number")), } } /// The body of a incoming request shaft the given user. #[derive(Deserialize)] struct ShaftUserBody { /// The other party in the transaction. other_user: String, /// The amount in pence owed. Positive means shafter is owed money by other /// user, negative means shafer owes money. amount: i64, /// The human readable description of the transasction. reason: String, }
use super::transact::{TransactionConcurrency, TransactionIsolation}; pub(crate) const DEFAULT_TX_TIMEOUT: usize = 0_usize; pub(crate) const DEFAULT_TX_SERIALIZABLE_ENABLED: bool = false; pub(crate) const DEFAULT_TX_CONCURRENCY: TransactionConcurrency = TransactionConcurrency::Pessimistic; pub(crate) const DEFAULT_TX_ISOLATION: TransactionIsolation = TransactionIsolation::RepeatableRead;
//! rootrenderingcomponent.rs - renders the web page //region: use, const use crate::divcardmoniker; use crate::divfordebugging; use crate::divgridcontainer; use crate::divplayeractions; use crate::divplayersandscores; use crate::divrulesanddescription; use crate::gamedata::GameData; //use crate::logmod; use dodrio::builder::text; use dodrio::bumpalo::{self, Bump}; use dodrio::{Cached, Node, Render}; use mem4_common::GameStatus; use typed_html::dodrio; use web_sys::WebSocket; use conv::{ConvAsUtil}; //endregion ///Root Render Component: the card grid struct has all the needed data for play logic and rendering pub struct RootRenderingComponent { ///game data will be inside of Root, but reference for all other RenderingComponents pub game_data: GameData, ///subComponent: score pub cached_players_and_scores: Cached<divplayersandscores::PlayersAndScores>, ///subComponent: the static parts can be cached. /// I am not sure if a field in this struct is the best place to put it. pub cached_rules_and_description: Cached<divrulesanddescription::RulesAndDescription>, } //region:RootRenderingComponent struct is the only persistent data we have in Rust Virtual Dom.dodrio //in the constructor we initialize that data. //Later on click we change this data. //at every animation frame we use only this data to render the virtual Dom. //It knows nothing about HTML and Virtual dom. impl RootRenderingComponent { /// Construct a new `RootRenderingComponent` component. Only once at the beginning. pub fn new(ws: WebSocket, my_ws_uid: usize) -> Self { let game_data = GameData::new(ws, my_ws_uid); let game_rule_01 = divrulesanddescription::RulesAndDescription {}; let cached_rules_and_description = Cached::new(game_rule_01); let cached_players_and_scores = Cached::new(divplayersandscores::PlayersAndScores::new(my_ws_uid)); RootRenderingComponent { game_data, cached_players_and_scores, cached_rules_and_description, } } ///check invalidate render cache for all sub components pub fn check_invalidate_for_all_components(&mut self) { if self .cached_players_and_scores .update_intern_cache(&self.game_data) { Cached::invalidate(&mut self.cached_players_and_scores); } } ///prepares the game data pub fn game_data_init(&mut self) { self.game_data.content_folder_name = self.game_data.asked_folder_name.clone(); self.game_data.prepare_random_data(); self.game_data.game_status = GameStatus::PlayBefore1stCard; self.game_data.player_turn = 1; } ///reset the data to replay the game pub fn reset(&mut self) { self.game_data.card_grid_data = GameData::prepare_for_empty(); self.game_data.card_index_of_first_click = 0; self.game_data.card_index_of_second_click = 0; self.game_data.players.clear(); self.game_data.game_status = GameStatus::InviteAskBegin; self.game_data.content_folder_name = "alphabet".to_string(); self.game_data.asked_folder_name = "".to_string(); self.game_data.my_player_number = 1; self.game_data.player_turn = 0; self.game_data.game_config = None; self.check_invalidate_for_all_components(); } //region: all functions for receive message (like events) // I separate the code into functions to avoid looking at all that boilerplate in the big match around futures and components. // All the data changing must be encapsulated inside these functions. ///msg response with uid, just to check. because the WebSocket server ///gets the uid from the client in the url_param. The client generates a random number. pub fn on_response_ws_uid(&mut self, your_ws_uid: usize) { if self.game_data.my_ws_uid != your_ws_uid { self.game_data.error_text = "my_ws_uid is incorrect!".to_string(); } } ///on game data init pub fn on_msg_game_data_init( &mut self, card_grid_data: &str, game_config: &str, players: &str, ) { self.game_data.content_folder_name = self.game_data.asked_folder_name.clone(); self.game_data.game_status = GameStatus::PlayBefore1stCard; self.game_data.player_turn = 1; self.game_data.card_grid_data = unwrap!( serde_json::from_str(card_grid_data), "error serde_json::from_str(card_grid_data)" ); self.game_data.game_config = unwrap!( serde_json::from_str(game_config), "error serde_json::from_str(game_config)" ); self.game_data.players = unwrap!( serde_json::from_str(players), "error serde_json::from_str(players)" ); //find my player number for index in 0..self.game_data.players.len() { if unwrap!( self.game_data.players.get_mut(index), "self.game_data.players.get_mut(index)" ) .ws_uid == self.game_data.my_ws_uid { self.game_data.my_player_number = unwrap!(index.checked_add(1)); } } self.check_invalidate_for_all_components(); } //endregion } //endregion //region: `Render` trait implementation on RootRenderingComponent struct ///It is called for every Dodrio animation frame to render the vdom. ///Probably only when something changes. Here it is a click on the cards. ///Not sure about that, but I don't see a reason to make execute it otherwise. ///It is the only place where I create HTML elements in Virtual Dom. impl Render for RootRenderingComponent { #[inline] fn render<'a, 'bump>(&'a self, bump: &'bump Bump) -> Node<'bump> where 'a: 'bump, { //the card grid is a html css grid object (like a table) with <img> inside //other html elements are pretty simple. //region: private helper fn for Render() //here I use private functions for readability only, to avoid deep code nesting. //I don't understand closures enough to use them properly. //These private functions are not in the "impl Render forRootRenderingComponent" because of the error //method `from_card_number_to_img_src` is not a member of trait `Render` //there is not possible to write private and public methods in one impl block there are only pub methods. //`pub` not permitted there because it's implied //so I have to write functions outside of the impl block but inside my "module" //region: create the whole virtual dom. The verbose stuff is in private functions if self.game_data.error_text == "" { let xmax_grid_size = divgridcontainer::max_grid_size(self); let xmax_grid_size_add_two = unwrap!(xmax_grid_size.hor.checked_add(2)); let xstyle2 = format!("width:{}px;", xmax_grid_size_add_two); //logmod::log1_str(&format!("width m_container {}", xmax_grid_size_add_two)); //the main HTML render dodrio!(bump, <div class= "m_container" style={xstyle2}> {vec![divcardmoniker::div_grid_card_moniker(self, bump)]} {vec![divgridcontainer::div_grid_container(self,bump,&xmax_grid_size)]} {vec![divplayeractions::div_player_actions_from_game_status(self, bump)]} {vec![self.cached_players_and_scores.render(bump)]} {vec![divfordebugging::div_for_debugging(self, bump)]} {vec![self.cached_rules_and_description.render(bump)]} </div> ) } else { //render only the error text to the screen. //because I want to debug the WebSocket lost connection dodrio!(bump, <div> <h1 style= "color:red;" > {vec![text( bumpalo::format!(in bump, "error_text {} !", self.game_data.error_text) .into_bump_str(), )]} </h1> </div> ) } //endregion } } //endregion /// return window inner height /// the size of the visible part of the window pub fn usize_window_inner_height() -> usize { let window = unwrap!(web_sys::window(), "error: web_sys::window"); let jsvalue_inner_height = unwrap!(window.inner_height(), "window.inner_height"); let f64_inner_height = unwrap!( jsvalue_inner_height.as_f64(), "jsValue_inner_height.as_f64()" ); let usize_inner_height: usize = unwrap!(f64_inner_height.approx()); //return usize_inner_height } /// return window inner width /// the size of the visible part of the window pub fn usize_window_inner_width() -> usize { let window = unwrap!(web_sys::window(), "error: web_sys::window"); let jsvalue_inner_width = unwrap!(window.inner_width(), "window.inner_width"); let f64_inner_width = unwrap!( jsvalue_inner_width.as_f64(), "jsValue_inner_width.as_string()" ); let usize_inner_width: usize = unwrap!(f64_inner_width.approx()); //return usize_inner_width } /// return window inner width, but maximum 600px /// the size of the visible part of the window pub fn usize_window_inner_width_but_max_600() -> usize { let x = usize_window_inner_width(); if x > 600 { //return 600 } else { //return x } }
fn main() { println!("Documents were generated at compile time. Look into project outputs 'book' directory!"); open::that( concat!(env!("CARGO_MANIFEST_DIR"), "/target/book/index.html") ).expect("Should have opened documentation in web browser!"); }
use crate::{ builtins::PyIntRef, function::OptionalArg, sliceable::SequenceIndexOp, types::PyComparisonOp, vm::VirtualMachine, AsObject, PyObject, PyObjectRef, PyResult, }; use optional::Optioned; use std::ops::Range; pub trait MutObjectSequenceOp { type Guard<'a>: 'a; fn do_get<'a>(index: usize, guard: &'a Self::Guard<'_>) -> Option<&'a PyObjectRef>; fn do_lock(&self) -> Self::Guard<'_>; fn mut_count(&self, vm: &VirtualMachine, needle: &PyObject) -> PyResult<usize> { let mut count = 0; self._mut_iter_equal_skeleton::<_, false>(vm, needle, 0..isize::MAX as usize, || { count += 1 })?; Ok(count) } fn mut_index_range( &self, vm: &VirtualMachine, needle: &PyObject, range: Range<usize>, ) -> PyResult<Optioned<usize>> { self._mut_iter_equal_skeleton::<_, true>(vm, needle, range, || {}) } fn mut_index(&self, vm: &VirtualMachine, needle: &PyObject) -> PyResult<Optioned<usize>> { self.mut_index_range(vm, needle, 0..isize::MAX as usize) } fn mut_contains(&self, vm: &VirtualMachine, needle: &PyObject) -> PyResult<bool> { self.mut_index(vm, needle).map(|x| x.is_some()) } fn _mut_iter_equal_skeleton<F, const SHORT: bool>( &self, vm: &VirtualMachine, needle: &PyObject, range: Range<usize>, mut f: F, ) -> PyResult<Optioned<usize>> where F: FnMut(), { let mut borrower = None; let mut i = range.start; let index = loop { if i >= range.end { break Optioned::<usize>::none(); } let guard = if let Some(x) = borrower.take() { x } else { self.do_lock() }; let elem = if let Some(x) = Self::do_get(i, &guard) { x } else { break Optioned::<usize>::none(); }; if elem.is(needle) { f(); if SHORT { break Optioned::<usize>::some(i); } borrower = Some(guard); } else { let elem = elem.clone(); drop(guard); if elem.rich_compare_bool(needle, PyComparisonOp::Eq, vm)? { f(); if SHORT { break Optioned::<usize>::some(i); } } } i += 1; }; Ok(index) } } pub trait SequenceExt<T: Clone> where Self: AsRef<[T]>, { fn mul(&self, vm: &VirtualMachine, n: isize) -> PyResult<Vec<T>> { let n = vm.check_repeat_or_overflow_error(self.as_ref().len(), n)?; let mut v = Vec::with_capacity(n * self.as_ref().len()); for _ in 0..n { v.extend_from_slice(self.as_ref()); } Ok(v) } } impl<T: Clone> SequenceExt<T> for [T] {} pub trait SequenceMutExt<T: Clone> where Self: AsRef<[T]>, { fn as_vec_mut(&mut self) -> &mut Vec<T>; fn imul(&mut self, vm: &VirtualMachine, n: isize) -> PyResult<()> { let n = vm.check_repeat_or_overflow_error(self.as_ref().len(), n)?; if n == 0 { self.as_vec_mut().clear(); } else if n != 1 { let mut sample = self.as_vec_mut().clone(); if n != 2 { self.as_vec_mut().reserve(sample.len() * (n - 1)); for _ in 0..n - 2 { self.as_vec_mut().extend_from_slice(&sample); } } self.as_vec_mut().append(&mut sample); } Ok(()) } } impl<T: Clone> SequenceMutExt<T> for Vec<T> { fn as_vec_mut(&mut self) -> &mut Vec<T> { self } } #[derive(FromArgs)] pub struct OptionalRangeArgs { #[pyarg(positional, optional)] start: OptionalArg<PyObjectRef>, #[pyarg(positional, optional)] stop: OptionalArg<PyObjectRef>, } impl OptionalRangeArgs { pub fn saturate(self, len: usize, vm: &VirtualMachine) -> PyResult<(usize, usize)> { let saturate = |obj: PyObjectRef| -> PyResult<_> { obj.try_into_value(vm) .map(|int: PyIntRef| int.as_bigint().saturated_at(len)) }; let start = self.start.map_or(Ok(0), saturate)?; let stop = self.stop.map_or(Ok(len), saturate)?; Ok((start, stop)) } }
use winnow::prelude::*; mod parser; mod parser_str; fn main() -> Result<(), lexopt::Error> { let args = Args::parse()?; let input = args.input.as_deref().unwrap_or("1 + 1"); if args.binary { match parser::categories.parse(input.as_bytes()) { Ok(result) => { println!(" {:?}", result); } Err(err) => { println!(" {:?}", err); } } } else { match parser_str::categories.parse(input) { Ok(result) => { println!(" {:?}", result); } Err(err) => { println!(" {}", err); } } } Ok(()) } #[derive(Default)] struct Args { input: Option<String>, binary: bool, } impl Args { fn parse() -> Result<Self, lexopt::Error> { use lexopt::prelude::*; let mut res = Args::default(); let mut args = lexopt::Parser::from_env(); while let Some(arg) = args.next()? { match arg { Long("binary") => { res.binary = true; } Value(input) => { res.input = Some(input.string()?); } _ => return Err(arg.unexpected()), } } Ok(res) } }