text stringlengths 8 4.13M |
|---|
/// Like mem::epoch::AtomicPtr, but provides an ll/sc based api on x86, powerpc, arm, aarch64
use std::mem;
use std::marker::PhantomData;
use std::sync::atomic::{Ordering, AtomicUsize};
use std::sync::atomic::Ordering::*;
#[cfg(target_arch = "aarch64")]
mod multi_arch {
#[inline(awlays)]
unsafe fn load_exc(ptr: *const usize, ord: Ordering, _: bool) {
let rval: usize;
match ord {
Relaxed => {
asm!("ldxr %1, [%0]"
: "=r" (rval)
: "r" (ptr)
: "volatile")
},
Acquire | SeqCst => {
asm!("ldaxr %1, [%0]"
: "=r" (rval)
: "r" (ptr)
: "volatile")
},
Release | AcqRel => panic!("Invalid load ordering"),
}
rval
}
#[inline(always)]
unsafe fn store_exc(ptr: *const usize, val: usize, ord: Ordering,
rord: Ordering, reload: bool) -> (bool, usize) {
let succ: bool;
match ord {
Relaxed => {
asm!("stxr %0 %1 [%2]"
: "=r" (succ)
: "r" (val), "r" (ptr)
: "memory"
: "volatile")
},
Release | SeqCst => {
asm!("stlxr %0 %1 [%2]"
: "=r" (succ)
: "r" (val), "r" (ptr)
: "memory"
: "volatile")
},
Acquire | AcqRel => panic("Invalid Store Ordering"),
}
if succ {
(true, mem::uninitialized() )
}
else {
(false, if reload { load_exc(ptr, rord, false) }
else { mem::uninitialized() })
}
}
}
#[cfg(target_arch = "arm")]
mod multi_arch {
// This may be able to eliminate a dmb sy in the mismatched seqcst case?
#[inline(awlays)]
unsafe fn load_exc(ptr: *const usize, ord: Ordering, rseqcst: bool) {
let rval: usize;
// This flag allows more efficient ll/sc loops when the ll/sc
// flag reloads!
if rseqcst && ord == SeqCst { asm!("dmb sy":::"memory":"volatile") }
asm!("ldxr %1, [%0]"
: "=r" (rval)
: "r" (ptr)
: "volatile");
match ord {
Relaxed => (),
Acquire | SeqCst => asm!("dmb sy":::"memory":"volatile"),
Release | AcqRel => panic!("Invalid load ordering"),
}
rval
}
#[inline(always)]
unsafe fn store_exc(ptr: *const usize, val: usize, ord: Ordering,
rord: Ordering, reload: bool) -> (bool, usize) {
let succ: bool;
match ord {
Relaxed => (),
Release | SeqCst => asm!("dmb sy":::"memory":"volatile"),
Acquire | AcqRel => panic("Invalid Store Ordering"),
}
asm!("strex %0 %1 [%2]"
: "=r" (succ)
: "r" (val), "r" (ptr)
: "memory"
: "volatile");
if ord == SeqCst { asm!("dmb sy":::"memory":"volatile") }
if succ {
(true, mem::uninitialized() )
}
else {
(false, if reload { load_exc(ptr, rord, ord != SeqCst) }
else { mem::uninitialized() })
}
}
}
#[cfg(target_arch = "powerpc")]
mod multi_arch {
#[inline(awlays)]
unsafe fn load_exc(ptr: *const usize, ord: Ordering, _: bool) {
let rval: usize;
// This flag allows more efficient ll/sc loops when the ll/sc
// flag reloads!
if ord == SeqCst { asm!("sync":::"memory":"volatile") }
match ord {
Relaxed => asm!("lwarx $0, 0, $1"
: "=r" (rval)
: "r" (ptr)
: "volatile"),
Acquire | SeqCst => asm!("lwarx $0, 0, $1
cmpw $1, $1
bne- $+4
isync"
: "=r" (rval)
: "r" (ptr)
: "memory"
: "volatile"),
Release | AcqRel => panic!("Invalid load ordering"),
}
rval
}
#[inline(always)]
unsafe fn store_exc(ptr: *const usize, val: usize, ord: Ordering,
rord: Ordering, reload: bool) -> (bool, usize) {
let succ: usize;
match ord {
Relaxed => (),
Release => asm!("lwsync":::"memory":"volatile"),
SeqCst => asm!("sync":::"memory":"volatile"),
Acquire | AcqRel => panic("Invalid Store Ordering"),
}
// The docs for powerpc condition register
// and stwcx are absolute nonsense...
// just copying from gcc and hoping that it works...
asm!("stwcx. %1, 0, %2
mfcr %0
rlwinm %0, %0, 3, 1"
: "=r" (succ)
: "r" (val), "r" (ptr)
: "memory"
: "volatile");
if succ == 0 {
(true, mem::uninitialized() )
}
else {
(false, if reload { load_exc(ptr, rord, false) }
else { mem::uninitialized() })
}
}
}
#[inline(always)]
unsafe fn load_from(ptr: *const usize, ord: Ordering) -> usize {
let ptr: *const AtomicUsize = mem::transmute(ptr);
(&*ptr).load(ord) as usize
}
#[inline(always)]
unsafe fn store_to(ptr: *const usize, n: usize, ord: Ordering) {
let ptr: *const AtomicUsize = mem::transmute(ptr);
(&*ptr).store(n as usize, ord)
}
#[inline(always)]
unsafe fn exchange_to(ptr: *const usize, n: usize, ord: Ordering) -> usize {
let ptr: *const AtomicUsize = mem::transmute(ptr);
(&*ptr).swap(n as usize, ord) as usize
}
#[inline(always)]
unsafe fn cas_to(ptr: *const usize, o: usize, n: usize, ord: Ordering) -> usize {
let ptr: *const AtomicUsize = mem::transmute(ptr);
(&*ptr).compare_and_swap(o as usize, n as usize, ord) as usize
}
pub trait Isusize {
fn from_usize(val: usize) -> Self;
fn to_usize(&self) -> usize;
}
impl Isusize for usize {
fn from_usize(val: usize) -> usize {
val as usize
}
fn to_usize(&self) -> usize {
*self as usize
}
}
impl Isusize for isize {
fn from_usize(val: usize) -> isize {
val as isize
}
fn to_usize(&self) -> usize {
*self as usize
}
}
impl<T> Isusize for *mut T {
fn from_usize(val: usize) -> *mut T {
val as *mut T
}
fn to_usize(&self) -> usize {
*self as usize
}
}
impl Isusize for bool {
fn from_usize(val: usize) -> bool {
val == 0
}
fn to_usize(&self) -> usize {
*self as usize
}
}
pub struct ExclusiveData<T: Isusize> {
data: usize,
marker: PhantomData<T>,
}
pub struct LinkedData<'a, T: 'a + Isusize> {
data: usize,
ptr: *const usize,
ord: Ordering,
marker: PhantomData<'a, T>,
}
impl<T: Isusize> ExclusiveData<T> {
pub fn new(val: T) -> ExclusiveData<T> {
ExclusiveData {
data: val.to_usize(),
marker: PhantomData,
}
}
/// Loads the value from the pointer with the given ordering
pub fn load(&self, ord: Ordering) -> T {
unsafe { T::from_usize(load_from(&self.data, ord)) }
}
/// Stores directly to the pointer without updating the counter
///
/// This function can still leave one vulnerable to the ABA problem,
/// But is useful when only used to store to say a null value.
/// Be careful when using, this must always cause a store_conditional to fail
pub fn store_direct(&self, val: T, ord: Ordering) {
unsafe { store_to(&self.data, val.to_usize(), ord) };
}
/// Swaps directly to the pointer without updating the counter
///
/// This function can still leave one vulnerable to the ABA problem,
/// But is useful when only used to store to say a null value.
/// Be careful when using, this must always cause a store_conditional to fail
pub fn swap_direct(&self, val: T, ord: Ordering) -> T {
unsafe { T::from_usize(exchange_to(&self.data, val.to_usize(), ord)) }
}
/// Cas's directly to the pointer without updating the counter
///
/// This function can still leave one vulnerable to the ABA problem,
/// But is useful when only used to store to say a null value.
/// Be careful when using, this must always cause a store_conditional to fail
pub fn cas_direct(&self, old: T, val: T, ord: Ordering) -> T {
unsafe { T::from_usize(cas_to(&self.data, old.to_usize(),
val.to_usize(), ord)) }
}
/// Performs an exclusive load on the pointer
///
/// If the pointer is modified by a different store_conditional in between the load_linked
/// and store_conditional, this will always fail. This is stronger the cas
/// since cas can succedd when modifications have occured as long as the end
/// result is the same. However, this will always fail in a scenario where cas would fail.
pub fn load_linked(&self, ord: Ordering) -> LinkedData<T> {
unsafe {
LinkedData {
data: load_from(&self.data, ord),
ptr: &self.data,
ord: ord,
marker: PhantomData,
}
}
}
}
impl<'a, T: Isusize> LinkedData<'a, T> {
pub fn get(&self) -> T {
T::from_usize(self.data)
}
/// Performs a conditional store on the pointer, conditional on no modifications occurring
///
/// If the pointer is modified by a different store_conditional in between the load_linked
/// and store_conditional, this will always fail. This is stronger the cas
/// since cas can succedd when modifications have occured as long as the end
/// result is the same. However, this will always fail in a scenario where cas would fail.
pub fn store_conditional(self, val: T, ord: Ordering) -> Option<LinkedData<'a, T>> {
unsafe {
let (succ, res) = store_exc(self.ptr, val.to_usize(), ord,
self.ord, true);
match succ {
true => None,
false => Some(LinkedData {
data: res,
ptr: self.ptr,
marker: PhantomData,
})
}
}
}
/// Performs a conditional store on the pointer, conditional on no modifications occurring
///
/// If the pointer is modified by a different store_conditional in between the load_linked
/// and store_conditional, this will always fail. This is stronger the cas
/// since cas can succedd when modifications have occured as long as the end
/// result is the same. However, this will always fail in a scenario where cas would fail.
pub fn try_store_conditional(self, val: T, _: Ordering) -> bool {
unsafe { store_exc(self.ptr, val.to_usize(), ord, self.ord, false).0 }
}
}
unsafe impl<T: Isusize> Send for ExclusiveData<T> {}
unsafe impl<T: Isusize> Sync for ExclusiveData<T> {}
pub type ExclusivePtr<T> = ExclusiveData<*mut T>;
pub type ExclusiveUsize = ExclusiveData<usize>;
pub type ExclusiveIsize = ExclusiveData<isize>;
// This could be more efficient, by doing normal cas and packing
// as usize. BUT! That's code bloat for the time being
pub type ExclusiveBool = ExclusiveData<bool>;
pub type LinkedPtr<'a, T> = LinkedData<'a, *mut T>;
pub type LinkedUsize<'a> = LinkedData<'a, usize>;
pub type LinkedIsize<'a> = LinkedData<'a, isize>;
pub type LinkedBool<'a> = LinkedData<'a, bool>;
|
pub mod constants;
pub mod exits;
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate sync15_adapter as sync;
extern crate libc;
extern crate serde_json;
extern crate failure;
use std::ffi::{CStr, CString};
use std::{ptr, mem};
use sync::{
Payload,
Sync15Service,
Sync15ServiceInit,
IncomingChangeset,
OutgoingChangeset,
ServerTimestamp,
Store,
ErrorKind
};
use libc::{c_char, c_double, size_t};
fn c_str_to_string(cs: *const c_char) -> String {
let c_str = unsafe { CStr::from_ptr(cs) };
let r_str = c_str.to_str().unwrap_or("");
r_str.to_string()
}
fn string_to_c_str(s: String) -> *mut c_char {
CString::new(s).unwrap().into_raw()
}
fn drop_c_str(cs: *mut c_char) {
if !cs.is_null() {
unsafe {
CString::from_raw(cs);
}
}
}
fn drop_and_null_c_str(cs: &mut *mut c_char) {
drop_c_str(mem::replace(cs, ptr::null_mut()));
}
#[repr(C)]
pub struct CleartextBsoC {
pub server_modified: c_double,
pub payload_str: *mut c_char,
}
impl Drop for CleartextBsoC {
fn drop(&mut self) {
drop_and_null_c_str(&mut self.payload_str);
}
}
impl CleartextBsoC {
pub fn new(bso_data: &(Payload, ServerTimestamp)) -> Box<CleartextBsoC> {
Box::new(CleartextBsoC {
payload_str: string_to_c_str(bso_data.0.clone().into_json_string()),
server_modified: bso_data.1.into(),
})
}
}
/// Create a new Sync15Service instance.
#[no_mangle]
pub extern "C" fn sync15_service_create(
key_id: *const c_char,
access_token: *const c_char,
sync_key: *const c_char,
tokenserver_base_url: *const c_char
) -> *mut Sync15Service {
let params = Sync15ServiceInit {
key_id: c_str_to_string(key_id),
access_token: c_str_to_string(access_token),
sync_key: c_str_to_string(sync_key),
tokenserver_base_url: c_str_to_string(tokenserver_base_url),
};
let mut boxed = match Sync15Service::new(params) {
Ok(svc) => Box::new(svc),
Err(e) => {
eprintln!("Unexpected error initializing Sync15Service: {}", e);
// TODO: have thoughts about error handling.
return ptr::null_mut();
}
};
if let Err(e) = boxed.remote_setup() {
eprintln!("Unexpected error performing remote sync setup: {}", e);
// TODO: have thoughts about error handling here too.
return ptr::null_mut();
}
Box::into_raw(boxed)
}
/// Free a `Sync15Service` returned by `sync15_service_create`
#[no_mangle]
pub unsafe extern "C" fn sync15_service_destroy(svc: *mut Sync15Service) {
let _ = Box::from_raw(svc);
}
/// Free an inbound changeset previously returned by `sync15_incoming_changeset_fetch`
#[no_mangle]
pub unsafe extern "C" fn sync15_incoming_changeset_destroy(changeset: *mut IncomingChangeset) {
let _ = Box::from_raw(changeset);
}
#[no_mangle]
pub unsafe extern "C" fn sync15_outgoing_changeset_destroy(changeset: *mut OutgoingChangeset) {
let _ = Box::from_raw(changeset);
}
/// Free a record previously returned by `sync15_changeset_get_record_at`.
#[no_mangle]
pub unsafe extern "C" fn sync15_record_destroy(bso: *mut CleartextBsoC) {
let _ = Box::from_raw(bso);
}
/// Create a new outgoing changeset, which requires that the server have not been
/// modified since it returned the provided `timestamp`.
#[no_mangle]
pub extern "C" fn sync15_outbound_changeset_create(
collection: *const c_char,
timestamp: c_double,
) -> *mut OutgoingChangeset {
assert!(timestamp >= 0.0);
Box::into_raw(Box::new(
OutgoingChangeset::new(c_str_to_string(collection),
ServerTimestamp(timestamp))))
}
/// Get all the changes for the requested collection that have occurred since last_sync.
/// Important: Caller frees!
#[no_mangle]
pub extern "C" fn sync15_incoming_changeset_fetch(
svc: *const Sync15Service,
collection_c: *const c_char,
last_sync: c_double,
) -> *mut IncomingChangeset {
let service = unsafe { &*svc };
let collection = c_str_to_string(collection_c);
let result = IncomingChangeset::fetch(service, collection, ServerTimestamp(last_sync as f64));
let fetched = match result {
Ok(r) => Box::new(r),
Err(e) => {
eprintln!("Unexpected error fetching collection: {}", e);
return ptr::null_mut();
}
};
Box::into_raw(fetched)
}
/// Get the last_sync timestamp for an inbound changeset.
#[no_mangle]
pub extern "C" fn sync15_incoming_changeset_get_timestamp(changeset: *const IncomingChangeset) -> c_double {
let changeset = unsafe { &*changeset };
changeset.timestamp.0 as c_double
}
/// Get the number of records from an inbound changeset.
#[no_mangle]
pub extern "C" fn sync15_incoming_changeset_get_len(changeset: *const IncomingChangeset) -> size_t {
let changeset = unsafe { &*changeset };
changeset.changes.len()
}
/// Get the requested record from the changeset. `index` should be less than
/// `sync15_changeset_get_record_count`, or NULL will be returned and a
/// message logged to stderr.
///
/// Important: Caller needs to free the returned value using `sync15_record_destroy`
#[no_mangle]
pub extern "C" fn sync15_incoming_changeset_get_at(
changeset: *const IncomingChangeset,
index: size_t
) -> *mut CleartextBsoC {
let changeset = unsafe { &*changeset };
if index >= changeset.changes.len() {
eprintln!("sync15_changeset_get_record_at was given an invalid index");
return ptr::null_mut();
}
Box::into_raw(CleartextBsoC::new(&changeset.changes[index]))
}
fn c_str_to_payload(json: *const c_char) -> sync::Result<Payload> {
let s = unsafe { CStr::from_ptr(json) };
Ok(Payload::from_json(
serde_json::from_slice(s.to_bytes())?)?)
}
/// Add a record to an outgoing changeset. Returns false in the case that
/// we were unable to add the record for some reason (typically the json
/// string provided was not well-formed json).
///
/// Note that The `record_json` should only be the record payload, and
/// should not include the BSO envelope.
#[no_mangle]
pub extern "C" fn sync15_outgoing_changeset_add_record(
changeset: *mut OutgoingChangeset,
record_json: *const c_char
) -> bool {
let changeset = unsafe { &mut *changeset };
assert!(!record_json.is_null());
let cleartext = match c_str_to_payload(record_json) {
Ok(ct) => ct,
Err(e) => {
eprintln!("Could not add record to changeset: {}", e);
return false;
}
};
changeset.changes.push(cleartext);
true
}
/// Add a tombstone to an outgoing changeset. This is equivalent to using
/// `sync15_outgoing_changeset_add_record` with a record that represents a tombstone.
#[no_mangle]
pub extern "C" fn sync15_outgoing_changeset_add_tombstone(
changeset: *mut OutgoingChangeset,
record_id: *const c_char
) {
let changeset = unsafe { &mut *changeset };
let payload = Payload::new_tombstone(c_str_to_string(record_id).into());
changeset.changes.push(payload);
}
pub type StoreApplyIncoming = unsafe extern "C" fn(
self_: *mut libc::c_void,
incoming: *const IncomingChangeset
) -> *mut OutgoingChangeset;
pub type StoreSyncFinished = unsafe extern "C" fn(
self_: *mut libc::c_void,
new_last_sync: c_double,
synced_ids: *const *const c_char,
num_synced_ids: size_t
) -> bool;
#[repr(C)]
pub struct FFIStore {
user_data: *mut libc::c_void,
apply_incoming_cb: StoreApplyIncoming,
sync_finished_cb: StoreSyncFinished,
}
struct DropCStrs<'a>(&'a mut [*mut c_char]);
impl<'a> Drop for DropCStrs<'a> {
fn drop(&mut self) {
for &c in self.0.iter() {
drop_c_str(c);
}
}
}
impl FFIStore {
fn call_apply_incoming(
&self,
incoming: &IncomingChangeset
) -> sync::Result<Box<OutgoingChangeset>> {
let this = self.user_data;
let res = unsafe {
(self.apply_incoming_cb)(this, incoming as *const IncomingChangeset)
};
if res.is_null() {
return Err(ErrorKind::StoreError(
failure::err_msg("FFI store failed to apply and fetch changes")).into());
}
Ok(unsafe { Box::from_raw(res) })
}
fn call_sync_finished(&self, ls: ServerTimestamp, ids: &[*mut c_char]) -> sync::Result<()> {
let this = self.user_data;
let ok = unsafe {
let ptr_to_mut: *const *mut c_char = ids.as_ptr();
let ptr_as_const: *const *const c_char = mem::transmute(ptr_to_mut);
(self.sync_finished_cb)(this, ls.0 as c_double, ptr_as_const, ids.len() as size_t)
};
if !ok {
return Err(ErrorKind::StoreError(
failure::err_msg("FFI store failed to note sync finished")).into());
}
Ok(())
}
}
// TODO: better error handling...
impl Store for FFIStore {
type Error = sync::Error;
fn apply_incoming(&mut self, incoming: IncomingChangeset) -> sync::Result<OutgoingChangeset> {
Ok(*self.call_apply_incoming(&incoming)?)
}
/// Called when a sync finishes successfully. The store should remove all items in
/// `synced_ids` from the set of items that need to be synced. and update
fn sync_finished(&mut self, new_last_sync: ServerTimestamp, synced_ids: &[String]) -> sync::Result<()> {
let mut buf = Vec::with_capacity(synced_ids.len());
for id in synced_ids {
buf.push(CString::new(&id[..]).unwrap().into_raw());
}
// More verbose but less error prone than just cleaning up at the end.
let dropper = DropCStrs(&mut buf);
self.call_sync_finished(new_last_sync, &dropper.0)?;
Ok(())
}
}
#[no_mangle]
pub extern "C" fn sync15_store_create(
user_data: *mut libc::c_void,
apply_incoming_cb: StoreApplyIncoming,
sync_finished_cb: StoreSyncFinished,
) -> *mut FFIStore {
let store = Box::new(FFIStore {
user_data,
apply_incoming_cb,
sync_finished_cb
});
Box::into_raw(store)
}
#[no_mangle]
pub unsafe extern "C" fn sync15_store_destroy(store: *mut FFIStore) {
assert!(!store.is_null());
let _ = Box::from_raw(store);
}
#[no_mangle]
pub extern "C" fn sync15_synchronize(
svc: *const Sync15Service,
store: *mut FFIStore,
collection: *const c_char,
timestamp: c_double,
fully_atomic: bool
) -> bool {
assert!(!svc.is_null());
assert!(!store.is_null());
let svc = unsafe { &*svc };
let store = unsafe { &mut *store };
sync::synchronize(
svc,
store,
c_str_to_string(collection),
ServerTimestamp(timestamp as f64),
fully_atomic
).is_ok()
}
|
#[doc = "Reader of register DOUTR6"]
pub type R = crate::R<u32, super::DOUTR6>;
#[doc = "Writer for register DOUTR6"]
pub type W = crate::W<u32, super::DOUTR6>;
#[doc = "Register DOUTR6 `reset()`'s with value 0"]
impl crate::ResetValue for super::DOUTR6 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `DOUT6`"]
pub type DOUT6_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `DOUT6`"]
pub struct DOUT6_W<'a> {
w: &'a mut W,
}
impl<'a> DOUT6_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - Output data sent to MDIO Master during read frames"]
#[inline(always)]
pub fn dout6(&self) -> DOUT6_R {
DOUT6_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - Output data sent to MDIO Master during read frames"]
#[inline(always)]
pub fn dout6(&mut self) -> DOUT6_W {
DOUT6_W { w: self }
}
}
|
use serde::Serialize;
#[derive(Clone, Debug, Serialize)]
pub struct GoogleId(String);
impl GoogleId {
pub fn new(id: String) -> Self {
GoogleId(id)
}
}
use std::fmt;
impl fmt::Display for GoogleId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
|
use anyhow::{anyhow, Result};
use clap::{AppSettings, Clap};
use reqwest::{Url, header, Client, Response};
use std::str::FromStr;
use std::collections::HashMap;
use colored::*;
use mime::{Mime, APPLICATION_JSON};
// 定义 HTTPie 的 CLI 的主入口,它包含若干个子命令
// 下面 /// 的注释是文档,clap 会将其作为 CLI 的帮助
/// A naive httpie implementation with Rust, can you imagine how easy it is?
#[derive(Clap, Debug)]
#[clap(version = "1.0", author = "Bryan")]
#[clap(setting = AppSettings::ColoredHelp)]
struct Opts {
#[clap(subcommand)]
subcmd: SubCommand,
}
// 子命令分别对应不同的 HTTP 方法,目前只支持 get / post
#[derive(Clap, Debug)]
enum SubCommand {
Get(Get),
Post(Post),
// 我们暂且不支持其它 HTTP 方法
}
// get 子命令
/// feed get with an url and we will retrieve the response for you
#[derive(Clap, Debug)]
struct Get {
/// HTTP 请求的 URL
#[clap(parse(try_from_str = parse_url))]
url: String,
}
// post 子命令。需要输入一个 URL,和若干个可选的 key=value,用于提供 json body
/// feed post with an url and optional key=value pairs. We will post the data
/// as JSON, and retrieve the response for you
#[derive(Clap, Debug)]
struct Post {
/// HTTP 请求的 URL
#[clap(parse(try_from_str = parse_url))]
url: String,
/// HTTP 请求的 body
#[clap(parse(try_from_str = parse_kv_pair))]
body: Vec<KvPair>,
}
fn parse_url(s: &str) -> Result<String> {
// 这里我们仅仅检查一下 URL 是否合法
let _url: Url = s.parse()?;
Ok(s.into())
}
#[derive(Debug, PartialEq)]
struct KvPair {
k: String,
v: String,
}
impl FromStr for KvPair {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut split = s.split("=");
let err = || anyhow!("Failed to parse {}", s);
Ok(Self {
k: split.next().ok_or_else(err)?.to_string(),
v: split.next().ok_or_else(err)?.to_string(),
})
}
}
fn parse_kv_pair(s: &str) -> Result<KvPair> {
Ok(s.parse()?)
}
async fn get(client: Client, args: &Get) -> Result<()> {
let resp = client.get(&args.url).send().await?;
print_response(resp).await?;
Ok(())
}
async fn post(client: Client, args: &Post) -> Result<()> {
let body = {
let mut body = HashMap::with_capacity(args.body.len());
for pair in args.body.iter() {
body.insert(&pair.k, &pair.v);
}
body
};
let resp = client.post(&args.url).json(&body).send().await?;
print_response(resp).await?;
Ok(())
}
fn print_response_line(resp: &Response) {
println!("{}", (format!("{:?} {}", resp.version(), resp.status())).blue());
}
fn print_response_headers(resp: &Response) {
let headers = resp.headers();
for (name, value) in headers {
println!("{}: {:?}", name.to_string().green(), value);
}
}
fn print_body(m: Option<Mime>, body: &str) {
if matches!(m, Some(v) if v == APPLICATION_JSON) {
let j_text = jsonxf::pretty_print(body);
if let Ok(j_text) = j_text {
println!("{}", j_text.cyan());
return;
}
}
println!("{}", body);
}
async fn print_response(resp: Response) -> Result<()> {
print_response_line(&resp);
print_response_headers(&resp);
let ct = get_content_type(&resp);
let body = resp.text().await?;
print_body(ct, &body);
Ok(())
}
fn get_content_type(resp: &Response) -> Option<Mime> {
resp.headers().get(header::CONTENT_TYPE).map(|v| v.to_str().unwrap().parse().unwrap())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_url_works() {
assert!(parse_url("").is_err());
assert!(parse_url("abc").is_err());
assert!(parse_url("baidu.com").is_err());
assert!(parse_url("http://baidu.com").is_ok());
assert!(parse_url("http://baidu.com/").is_ok());
assert!(parse_url("https://baidu.com/a/bc").is_ok());
}
#[test]
fn parse_kv_pair_works() {
assert!(parse_kv_pair("").is_err());
assert!(parse_kv_pair("a").is_err());
assert_eq!(parse_kv_pair("a=").ok(), Some(KvPair { k: "a".to_string(), v: "".to_string() }));
assert_eq!(parse_kv_pair("a=b").ok(), Some(KvPair { k: "a".to_string(), v: "b".to_string() }));
}
}
#[tokio::main]
async fn main() -> Result<()> {
let opts: Opts = Opts::parse();
// println!("{:?}", opts);
let client = Client::new();
match opts.subcmd {
SubCommand::Get(ref args) => get(client, args).await?,
SubCommand::Post(ref args) => post(client, args).await?,
};
Ok(())
}
|
use std::net::{TcpListener, TcpStream};
pub fn init(port: &String) ->Result<TcpListener, String>{
let addr = String::from("127.0.0.1:");
match TcpListener::bind(addr + port) {
Ok(listener) => Ok(listener),
Err(_) => Err(String::from("fail to bind")),
}
}
use std::fs::File;
pub struct HttpResponse {
pub filetype: HttpType,
pub fhandler: File,
pub socket_handler: TcpStream,
}
use std::io::{Read, Write};
use std::io::Error;
impl HttpResponse {
pub fn new(prefix: &String, filename: &str, socket_handler: TcpStream) ->Result<HttpResponse, Error> {
let filetype = HttpType::from_name(filename);
let mut fullpath = prefix.clone();
fullpath.push_str(filename);
println!("{}", fullpath);
match File::open(fullpath) {
Ok(fhandler) => Ok(HttpResponse{
filetype,
fhandler,
socket_handler,
}),
Err(e) => {
HttpResponse::send_failmsg(socket_handler).unwrap();
Err(e)
},
}
}
pub fn solve(&mut self) ->Result<(), Error> {
let filesize = self.fhandler
.metadata()
.unwrap()
.len() as usize; // use the metadata to get file size
// send the HTTP packet header
HttpResponse::send_head(&mut self.socket_handler,
&self.filetype, filesize)?;
// send the file
let mut sent_size = 0usize;
let mut buf = [0u8; 1024];
while sent_size < filesize {
self.fhandler.read(&mut buf)?;
sent_size += self.socket_handler.write(&buf)?;
}
Ok(())
}
fn send_head(socket: &mut TcpStream, filetype: &HttpType, filesize: usize) ->Result<(), Error> {
let status = if let HttpType::ERR = filetype {
"404 Not Found"
} else { "200 Ok"};
socket.write_fmt(format_args!(
"HTTP/1.1 {}\r\n\
Content-Type: {}; charset=utf-8\r\n\
Content-Length: {}\r\n\r\n",
status, filetype.as_str(), filesize
))?;
socket.flush()?;
Ok(())
}
fn send_failmsg(mut socket: TcpStream) ->Result<(), Error> {
let fail_html = "\
<!DOCTYPE html>\r\n\
<html><head>\r\n\
<title>Page not found</title>\r\n\
</head><body>\r\n\
<h1>Not Found</h1>\r\n\
<p>The requested URL is not found on this server</p>\r\n\
</body></html>\r\n\
";
let size = fail_html.len();
HttpResponse::send_head(&mut socket, &HttpType::ERR, size)?;
socket.write(fail_html.as_bytes())?;
socket.flush()?;
Ok(())
}
}
pub enum HttpType {
ERR,
HTML,
JPG,
PNG,
GIF,
CSS,
}
impl HttpType {
pub fn from_name(filename: &str) ->HttpType {
if filename.ends_with(".html") {
HttpType::HTML
}
else if filename.ends_with(".jpg") {
HttpType::JPG
}
else if filename.ends_with(".png") {
HttpType::PNG
}
else if filename.ends_with(".gif") {
HttpType::GIF
}
else if filename.ends_with(".css") {
HttpType::CSS
}
else {
HttpType::ERR
}
}
pub fn as_str(&self) ->&'static str {
match self {
HttpType::ERR => "",
HttpType::HTML => "text/html",
HttpType::JPG => "image/jpg",
HttpType::PNG => "image/png",
HttpType::GIF => "image/gif",
HttpType::CSS => "text/css",
}
}
}
// Move TcpStream in instead of borrowing it.
// That's because we won't be using the TcpStream obj after
// we resolve it.
pub fn resolve_request(prefix: &String, mut incoming: TcpStream) ->Option<HttpResponse>{
let mut buf = [0; 1024];
// If an error happens, return None, so that melantha does
// nothing about the TCP connection.
if let Err(_) = incoming.read(&mut buf) {
return None;
}
let buf = buf; // now it should not be mutable
let mut filename = String::new();
// search for required filename
let mut i: usize = 0;
while 1020 > i {
if b'G' == buf[i] && b'E' == buf[i+1] && b'T' == buf[i+2] && b' ' == buf[i+3] {
i += 4;
while b' ' != buf[i] {
filename.push(buf[i] as char);
i += 1;
}
if String::from("/") == filename {
filename = String::from("/index.html");
}
return match HttpResponse::new(
prefix,
&filename,
incoming
) {
Ok(res) => Some(res),
Err(_) => None, // error handled during `new`
};
}
i += 1;
}
None
}
|
// FeLEO
//
// bencode.rs
// imports here
pub fn be_decode(data: &str, data_len: i64) -> &str {
let mut ret = "";
if data_len == 0 {
return ret;
}
// match is similar to a switch statement
match data {
// integers
"i" => {
// indexing string by character doesn't work in rust
let mut i = 0;
let mut decoded_int: str = "";
while i < data.len() {
let CharRange {ch, next} = data.char_range_at(i);
decoded_int = concat!(decoded_int, ch);
i = next;
}
//let decoded_int: &str = &data[1..data_len-1];
let CharRange {after_int, next} = data.char_range_at(i);
if after_int != "e" {
println!("invalid value; rejecting it");
return "";
}
return decoded_int;
}
// strings
"0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9" => { ; } // do a thing
// lists
"l" => { ; } // do a thing
// dictionaries
"d" => { ; } // do a thing
// else: error
_ => { println!("error: bencoded string not recognized"); }
}
ret
}
|
pub use VkAccelerationStructureTypeNV::*;
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VkAccelerationStructureTypeNV {
VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV = 0,
VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV = 1,
}
|
use std::sync::Arc;
use crate::buffer::VkBufferSlice;
use crate::rt::VkAccelerationStructure;
use crate::texture::{
VkSampler,
VkTextureView,
};
use crate::{
VkCommandBufferSubmission,
VkFrameBuffer,
VkPipeline,
VkRenderPass,
VkTexture, VkTimelineSemaphore,
};
pub struct VkLifetimeTrackers {
semaphores: Vec<Arc<VkTimelineSemaphore>>,
buffers: Vec<Arc<VkBufferSlice>>,
textures: Vec<Arc<VkTexture>>,
texture_views: Vec<Arc<VkTextureView>>,
render_passes: Vec<Arc<VkRenderPass>>,
frame_buffers: Vec<Arc<VkFrameBuffer>>,
samplers: Vec<Arc<VkSampler>>,
pipelines: Vec<Arc<VkPipeline>>,
acceleration_structures: Vec<Arc<VkAccelerationStructure>>,
inner_command_buffers: Vec<VkCommandBufferSubmission>,
}
impl VkLifetimeTrackers {
pub(crate) fn new() -> Self {
Self {
semaphores: Vec::new(),
buffers: Vec::new(),
textures: Vec::new(),
texture_views: Vec::new(),
render_passes: Vec::new(),
frame_buffers: Vec::new(),
samplers: Vec::new(),
pipelines: Vec::new(),
acceleration_structures: Vec::new(),
inner_command_buffers: Vec::new(),
}
}
pub(crate) fn reset(&mut self) {
self.semaphores.clear();
self.buffers.clear();
self.textures.clear();
self.texture_views.clear();
self.render_passes.clear();
self.frame_buffers.clear();
self.samplers.clear();
self.pipelines.clear();
self.acceleration_structures.clear();
self.inner_command_buffers.clear();
}
pub(crate) fn track_semaphore(&mut self, semaphore: &Arc<VkTimelineSemaphore>) {
self.semaphores.push(semaphore.clone());
}
pub(crate) fn track_buffer(&mut self, buffer: &Arc<VkBufferSlice>) {
self.buffers.push(buffer.clone());
}
pub(crate) fn track_texture(&mut self, texture: &Arc<VkTexture>) {
self.textures.push(texture.clone());
}
pub(crate) fn track_render_pass(&mut self, render_pass: &Arc<VkRenderPass>) {
self.render_passes.push(render_pass.clone());
}
pub(crate) fn track_frame_buffer(&mut self, frame_buffer: &Arc<VkFrameBuffer>) {
self.frame_buffers.push(frame_buffer.clone());
}
pub(crate) fn track_texture_view(&mut self, texture_view: &Arc<VkTextureView>) {
self.texture_views.push(texture_view.clone());
}
pub(crate) fn track_sampler(&mut self, sampler: &Arc<VkSampler>) {
self.samplers.push(sampler.clone());
}
pub(crate) fn track_pipeline(&mut self, pipeline: &Arc<VkPipeline>) {
self.pipelines.push(pipeline.clone());
}
pub(crate) fn track_acceleration_structure(
&mut self,
acceleration_structure: &Arc<VkAccelerationStructure>,
) {
self.acceleration_structures
.push(acceleration_structure.clone());
}
pub(crate) fn track_inner_command_buffer(&mut self, command_buffer: VkCommandBufferSubmission) {
self.inner_command_buffers.push(command_buffer);
}
pub(crate) fn is_empty(&self) -> bool {
self.texture_views.is_empty()
&& self.semaphores.is_empty()
&& self.buffers.is_empty()
&& self.textures.is_empty()
&& self.render_passes.is_empty()
&& self.frame_buffers.is_empty()
&& self.samplers.is_empty()
&& self.pipelines.is_empty()
&& self.acceleration_structures.is_empty()
&& self.inner_command_buffers.is_empty()
}
}
|
use chrono::{DateTime, TimeZone, Utc};
use rust_decimal::Decimal;
use sqlx::postgres::PgRow;
use sqlx::{Done, Row};
use super::Db;
#[derive(Debug, serde::Serialize)]
pub struct Transaction {
pub id: String,
pub account_id: String,
pub timestamp: DateTime<Utc>,
pub amount: Decimal,
pub currency: String,
pub transaction_type: Option<String>,
pub category: Option<String>,
pub description: Option<String>,
pub merchant_name: Option<String>,
}
/// Returns true if there are any recorded transactions
/// for the specified account.
pub async fn has_any(db: &Db, account: &str) -> anyhow::Result<bool> {
let res: Option<i32> = sqlx::query("SELECT 1 FROM transactions WHERE account_id = $1")
.bind(account)
.try_map(|row: PgRow| Ok(row.get(0)))
.fetch_optional(db.pool())
.await?;
Ok(res.is_some())
}
/// Returns all transactions for the given account.
pub async fn all(db: &Db, account: &str) -> anyhow::Result<Vec<Transaction>> {
let query = "
SELECT id, account_id, timestamp, amount, currency,
type, category, description, merchant_name
FROM transactions
WHERE account_id = $1
ORDER BY timestamp DESC
";
let transactions = sqlx::query(query)
.bind(account)
.try_map(|row: PgRow| {
Ok(Transaction {
id: row.get(0),
account_id: row.get(1),
timestamp: Utc.from_utc_datetime(&row.get(2)),
amount: row.get(3),
currency: row.get(4),
transaction_type: row.get(5),
category: row.get(6),
description: row.get(7),
merchant_name: row.get(8),
})
})
.fetch_all(db.pool())
.await?;
Ok(transactions)
}
/// Returns a list of transaction ids for all transactions
/// made since the specified timestamp.
pub async fn ids_after(
db: &Db,
account: &str,
timestamp: DateTime<Utc>,
) -> anyhow::Result<Vec<String>> {
let sql = "
SELECT id FROM transactions
WHERE account_id = $1 AND timestamp >= $2
";
let transactions = sqlx::query(sql)
.bind(account)
.bind(timestamp)
.try_map(|row: PgRow| Ok(row.get(0)))
.fetch_all(db.pool())
.await?;
Ok(transactions)
}
/// Inserts multiple transaction records into the database.
pub async fn insert_many(db: &Db, transactions: &[Transaction]) -> anyhow::Result<()> {
for chunk in transactions.chunks(100) {
let mut sql = "
INSERT INTO transactions (
id, account_id, timestamp, amount, currency,
type, category, description, merchant_name
) VALUES
"
.to_owned();
// FIXME: Well this is horrible
for i in 0..chunk.len() {
sql += " (";
for j in 0..9 {
sql += "$";
itoa::fmt(&mut sql, i * 9 + j + 1)?;
if j < 8 {
sql += ", ";
}
}
sql += ")";
if i != chunk.len() - 1 {
sql += ", ";
}
}
chunk
.iter()
.fold(sqlx::query(&sql), |query, t| {
query
.bind(&t.id)
.bind(&t.account_id)
.bind(t.timestamp)
.bind(t.amount)
.bind(&t.currency)
.bind(&t.transaction_type)
.bind(&t.category)
.bind(&t.description)
.bind(&t.merchant_name)
})
.execute(db.pool())
.await?;
}
Ok(())
}
/// Deletes ***all*** transactions from the database.
pub async fn delete_all(db: &Db) -> anyhow::Result<()> {
sqlx::query("DELETE FROM transactions")
.execute(db.pool())
.await?;
log::info!("all transactions deleted from db");
Ok(())
}
/// Deletes all transactions for the specified account that were
/// made since the given timestamp.
pub async fn delete_after(db: &Db, account: &str, timestamp: DateTime<Utc>) -> anyhow::Result<()> {
let sql = "
DELETE FROM transactions
WHERE account_id = $1 AND timestamp >= $2
";
let count = sqlx::query(sql)
.bind(account)
.bind(timestamp.date().and_hms(0, 0, 0))
.execute(db.pool())
.await?
.rows_affected();
log::info!("{} transactions deleted from db", count);
Ok(())
}
|
use datastore::{key::Key, Batch, Txn};
use matches::matches;
use rand::{self, Rng};
use std::collections::HashMap;
use tempfile::TempDir;
use super::*;
macro_rules! map (
{ $($key:expr => $value:expr),+ } => {
{
let mut m = ::std::collections::HashMap::new();
$(
m.insert($key, $value);
)+
m
}
};
);
fn testcase() -> HashMap<&'static str, &'static str> {
map! {
"/a" => "a",
"/a/b" => "ab",
"/a/b/c" => "abc",
"/a/b/d" => "a/b/d",
"/a/c" => "ac",
"/a/d" => "ad",
"/e" => "e",
"/f" => "f",
"/g" => ""
}
}
fn new_db() -> (RocksDB, TempDir) {
let tempdir = tempfile::Builder::new()
.prefix("rocksdb")
.tempdir()
.unwrap();
let db = RocksDB::new_with_default(tempdir.path().to_str().unwrap()).unwrap();
(db, tempdir)
}
// immutable db is also ok
fn add_test_cases(db: &RocksDB, testcase: &HashMap<&'static str, &'static str>) {
for (k, v) in testcase.iter() {
let k = Key::new(k);
db.put(k, v.as_bytes().into()).unwrap();
}
for (k, v) in testcase.iter() {
let k = Key::new(k);
let v2 = db.get(&k).unwrap();
assert_eq!(v2.as_slice(), v.as_bytes());
}
}
#[test]
fn test_query() {
// todo
}
#[test]
fn test_has() {
let (db, _) = new_db();
add_test_cases(&db, &testcase());
let key = Key::new("/a/b/c");
let has = db.has(&key).unwrap();
assert!(has);
let has = db.has(&Key::new("/a/b/c/d")).unwrap();
assert!(!has);
}
#[test]
fn test_gat_size() {
let (db, _) = new_db();
let m = testcase();
add_test_cases(&db, &m);
let key = Key::new("/a/b/c");
let size = db.get_size(&key).unwrap();
assert_eq!(size, m["/a/b/c"].len());
let r = db.get_size(&Key::new("/a/b/c/d"));
assert!(matches!(r, Err(datastore::DSError::NotFound(_))));
}
#[test]
fn test_not_exist_get() {
let (db, _) = new_db();
add_test_cases(&db, &testcase());
let k = Key::new("/a/b/c/d");
let has = db.has(&k).unwrap();
assert!(!has);
let r = db.get(&k);
assert!(matches!(r, Err(datastore::DSError::NotFound(_))));
}
#[test]
fn test_delete() {
let (db, _) = new_db();
add_test_cases(&db, &testcase());
let key = Key::new("/a/b/c");
let has = db.has(&key).unwrap();
assert!(has);
db.delete(&key).unwrap();
let has = db.has(&key).unwrap();
assert!(!has);
}
#[test]
fn test_get_empty() {
let (db, _) = new_db();
add_test_cases(&db, &testcase());
let k = Key::new("/a");
db.put(k.clone(), "".into()).unwrap();
let v = db.get(&k).unwrap();
assert!(v.is_empty());
}
#[test]
fn test_batching() {
let (db, _) = new_db();
let mut b = db.batch().unwrap();
for (k, v) in testcase() {
b.put(Key::new(k), v.into()).unwrap();
}
db.commit(b).unwrap();
for (k, v) in testcase() {
let val = db.get(&Key::new(k)).unwrap();
assert_eq!(val.as_slice(), v.as_bytes());
}
// test delete
let mut b = db.batch().unwrap();
b.delete(&Key::new("/a/b")).unwrap();
b.delete(&Key::new("/a/b/c")).unwrap();
db.commit(b).unwrap();
// todo query
}
#[test]
fn test_basic_put_get() {
let (db, _) = new_db();
let k = Key::new("foo");
let v = "Hello Datastore!";
db.put(k.clone(), v.into()).unwrap();
let has = db.has(&k).unwrap();
assert!(has);
let out = db.get(&k).unwrap();
assert_eq!(out.as_slice(), v.as_bytes());
let has = db.has(&k).unwrap();
assert!(has);
db.delete(&k).unwrap();
let has = db.has(&k).unwrap();
assert!(!has);
}
#[test]
fn test_not_founds() {
let (db, _) = new_db();
let k = Key::new("notreal");
let out = db.get(&k);
assert!(matches!(out, Err(datastore::DSError::NotFound(_))));
let has = db.has(&k).unwrap();
assert!(!has);
}
#[test]
fn test_many_keys_and_query() {
let (db, _) = new_db();
let mut keys = vec![];
let mut keystrs = vec![];
let mut values = vec![];
for i in 0..100 {
let s = format!("{}key{}", i, i);
let dsk = Key::new(s.to_owned());
keystrs.push(s);
keys.push(dsk);
let random_bytes = rand::thread_rng().gen::<[u8; 32]>();
values.push(random_bytes);
}
for (i, k) in keys.iter().enumerate() {
db.put(k.clone(), values[i].as_ref().into()).unwrap();
}
for (i, k) in keys.iter().enumerate() {
let val = db.get(k).unwrap();
assert_eq!(val.as_slice(), values[i].as_ref())
}
// TODO query
}
#[test]
fn test_disk_usage() {
// todo
}
#[test]
fn test_txn_discard() {
let (db, _) = new_db();
let mut txn = db.new_transaction(false).unwrap();
let key = Key::new("/test/thing");
txn.put(key.clone(), [1_u8, 2, 3].as_ref().into()).unwrap();
txn.discard();
let r = txn.get(&key);
assert!(matches!(r, Err(datastore::DSError::NotFound(_))));
db.commit(txn).unwrap();
let r = db.get(&key);
assert!(matches!(r, Err(datastore::DSError::NotFound(_))));
let has = db.has(&key).unwrap();
assert!(!has);
}
#[test]
fn test_txn_commit() {
let (db, _) = new_db();
let mut txn = db.new_transaction(false).unwrap();
let key = Key::new("/test/thing");
txn.put(key.clone(), [1_u8, 2, 3].as_ref().into()).unwrap();
db.commit(txn).unwrap();
let has = db.has(&key).unwrap();
assert!(has)
}
#[test]
fn test_txn_batch() {
let (db, _) = new_db();
let mut txn = db.new_transaction(false).unwrap();
let mut data = HashMap::new();
for i in 0..10 {
let key = Key::new(format!("{}key{}", i, i));
let random_bytes = rand::thread_rng().gen::<[u8; 16]>();
data.insert(key.clone(), random_bytes);
txn.put(key, random_bytes.as_ref().into()).unwrap();
}
db.commit(txn).unwrap();
for (key, bytes) in data {
let retrieved = db.get(&key).unwrap();
assert_eq!(retrieved.as_slice(), bytes.as_ref());
}
}
#[test]
fn test_add_and_remove_column() {
let dir = tempfile::Builder::new()
.prefix("rocksdb")
.tempdir()
.unwrap();
unsafe {
let config = DatabaseConfig::with_columns(vec!["/1".to_owned()]);
let db = RocksDB::new(dir.path().to_str().unwrap(), &config).unwrap();
db.add_column("/1").unwrap();
db.put(Key::new("/1/123"), vec![]).unwrap();
let it = db.inner.db.iter("/1");
for i in it {
println!("{:?} {:?}", i.0, i.1);
}
}
unsafe {
let config = DatabaseConfig::default();
let db = RocksDB::new(dir.path().to_str().unwrap(), &config).unwrap();
db.add_column("/1").unwrap();
db.put(Key::new("/1/234"), vec![]).unwrap();
}
{
let config = DatabaseConfig::with_columns(vec!["/1".to_owned()]);
let db = RocksDB::new(dir.path().to_str().unwrap(), &config).unwrap();
let it = db.inner.db.iter("/1");
for i in it {
println!("{:?} {:?}", i.0, i.1);
}
let v: Vec<u8> = db.get(&Key::new("/1/123")).unwrap();
assert_eq!(v, vec![]);
let v: Vec<u8> = db.get(&Key::new("/1/234")).unwrap();
assert_eq!(v, vec![]);
}
{
let config = DatabaseConfig::with_columns(vec![]);
let db = RocksDB::new(dir.path().to_str().unwrap(), &config).unwrap();
let v = db.get(&Key::new("/1/123")).unwrap();
assert_eq!(v, vec![]);
let v = db.get(&Key::new("/1/234")).unwrap();
assert_eq!(v, vec![]);
unsafe { db.remove_column("/1").unwrap() };
let r = db.get(&Key::new("/1/123"));
assert!(matches!(r, Err(datastore::DSError::NotFound(_))));
let r = db.get(&Key::new("/1/234"));
assert!(matches!(r, Err(datastore::DSError::NotFound(_))));
}
}
#[test]
fn test_column_names() {
let names = [
"/block",
"/",
"block",
"/block/foo",
"block/foo",
"/block/foo/bar",
"block/foo/bar",
DEFAULT_COLUMN_NAME,
];
let len = names.len();
for (index, s) in names.iter().enumerate() {
// current database would be removed after this block
let dir = tempfile::Builder::new()
.prefix("rocksdb")
.tempdir()
.unwrap();
let config = DatabaseConfig::with_columns(vec![(*s).to_string()]);
let db = RocksDB::new(dir.path().to_str().unwrap(), &config);
let db = if index == 0 || index == (len - 1) {
db.unwrap()
} else {
assert!(matches!(db, Err(RocksDBError::InvalidColumnName(_))));
let config = DatabaseConfig::default();
RocksDB::new(dir.path().to_str().unwrap(), &config).unwrap()
};
unsafe {
if index == 0 {
db.remove_column(s).unwrap();
db.add_column(s).unwrap();
} else {
let r = db.remove_column(s);
assert!(matches!(r, Err(RocksDBError::InvalidColumnName(_))));
let r = db.add_column(s);
assert!(matches!(r, Err(RocksDBError::InvalidColumnName(_))));
}
}
}
}
|
fn main() {
let x = 1;
let y = 4;
let z = 5;
let Point { x, .. } = new_point(x, y, z);
println!("x: {}", x);
}
struct Point {
x: i64,
y: i64,
z: i64,
}
fn new_point(x: i64, y: i64, z: i64) -> Point {
Point { x, y, z }
}
|
#![feature(io, std_misc)]
mod format_strings;
mod chat_server;
mod connection;
fn main() {
chat_server::start();
}
|
use std::io;
use std::fs;
use std::iter;
use std::path::Path;
use crate::Battery;
use crate::platform::traits::BatteryIterator;
use super::SysFsDevice;
#[derive(Debug)]
pub struct SysFsIterator {
// TODO: It is not cool to store all results at once, should keep iterator instead
entries: Vec<io::Result<fs::DirEntry>>,
}
impl SysFsIterator {
pub fn from_path<T>(root: T) -> SysFsIterator where T: AsRef<Path> {
let entries = match fs::read_dir(root.as_ref()) {
Ok(entries) => entries.collect(),
Err(_) => vec![],
};
SysFsIterator {
entries,
}
}
}
impl iter::Iterator for SysFsIterator {
type Item = Battery;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.entries.pop() {
None => return None, // Nothing to iterate anymore
Some(Err(_)) => continue, // Unable to access the sysfs somehow // TODO: trace!()
Some(Ok(entry)) => {
let path = entry.path();
match fs::read_to_string(path.join("type")) {
Ok(ref content) if content == "Battery\n" => {
let inner = SysFsDevice::new(path);
return Some(Battery::from(inner));
},
_ => continue, // it is not a battery
}
}
}
}
}
}
impl BatteryIterator for SysFsIterator {}
|
use serde::{Deserialize, Serialize};
/// Denotes the intended role of the module.
///
/// This type is used as part of the [`Registration`](guest::Registration) process.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(C)]
pub enum Role {
/// A transform.
Transform = 0,
/// A source.
Source = 1,
/// A sink.
Sink = 2,
}
impl Role {
/// Cheaply turn into a `&'static str` so you don't need to format it for metrics.
pub fn as_const_str(self) -> &'static str {
match self {
Role::Transform => TRANSFORM,
Role::Source => SOURCE,
Role::Sink => SINK,
}
}
}
pub const TRANSFORM: &str = "transform";
pub const SOURCE: &str = "source";
pub const SINK: &str = "sink";
|
//! Listener and connections.
//!
//! This module implements the RTR listener socket and the high-level
//! connection handling.
use std::mem;
use std::net::SocketAddr;
use std::time::SystemTime;
use futures::future;
use futures::{Async, Future, IntoFuture, Stream};
use tokio;
use tokio::io::{AsyncRead, ReadHalf, WriteHalf};
use tokio::net::{TcpListener, TcpStream};
use crate::config::Config;
use crate::origins::OriginsHistory;
use super::send::{Sender, Timing};
use super::query::{Input, InputStream, Query};
use super::notify::{Dispatch, NotifyReceiver, NotifySender};
//------------ rtr_listener --------------------------------------------------
/// Returns a future for the RTR server.
///
/// The server will be configured according to `config` including creating
/// listener sockets for all the listen addresses mentioned.
/// The data exchanged with the clients is taken from `history`.
///
/// In order to be able to send notifications, the function also creates a
/// channel. It returns the sending half of that channel together with the
/// future.
pub fn rtr_listener(
history: OriginsHistory,
config: &Config,
) -> (NotifySender, impl Future<Item=(), Error=()>) {
let session = session_id();
let (dispatch, dispatch_fut) = Dispatch::new();
let timing = Timing::new(config);
let fut = dispatch_fut.select(
future::select_all(
config.tcp_listen.iter().map(|addr| {
single_listener(
*addr, session, history.clone(),
dispatch.clone(), timing
)
})
).then(|_| Ok(()))
).then(|_| Ok(()));
(dispatch.get_sender(), fut)
}
/// Creates a session ID based on the current Unix time.
fn session_id() -> u16 {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH).unwrap()
.as_secs() as u16
}
/// Creates the future for a single RTR TCP listener.
///
/// The future binds to `addr` and then spawns a new `Connection` for every
/// incoming connection on the default Tokio runtime.
fn single_listener(
addr: SocketAddr,
session: u16,
history: OriginsHistory,
mut dispatch: Dispatch,
timing: Timing,
) -> impl Future<Item=(), Error=()> {
TcpListener::bind(&addr).into_future()
.then(move |res| {
match res {
Ok(some) => {
info!("RTR: Listening on {}.", addr);
Ok(some)
}
Err(err) => {
error!("Failed to bind RTR listener {}: {}", addr, err);
Err(())
}
}
})
.and_then(move |listener| {
listener.incoming()
.map_err(|err| {
error!("Failed to accept RTR connection: {}", err);
})
.for_each(move |sock| {
let notify = dispatch.get_receiver();
tokio::spawn(
Connection::new(
sock, session, history.clone(), notify,
timing,
)
)
})
})
}
//------------ Connection ----------------------------------------------------
/// The future for an RTR connection.
struct Connection {
/// The input stream.
///
/// Contains both the input half of the TCP stream and the notifier.
input: InputStream<ReadHalf<TcpStream>>,
/// The output half of the socket as well as the state of the connection.
output: OutputState,
/// The session ID to be used in the RTR PDUs.
session: u16,
/// The validated RPKI data.
history: OriginsHistory,
/// The timing information for the End-of-data PDU.
timing: Timing,
}
/// The output state of the connection.
///
/// This enum also determines where we are in the cycle.
enum OutputState {
/// Not currently sending.
///
/// Which means that we are actually waiting to receive something or
/// being notified.
Idle(WriteHalf<TcpStream>),
/// We are currently sending something.
Sending(Sender<WriteHalf<TcpStream>>),
/// We are, like, totally done.
Done
}
impl Connection {
/// Creates a new connection for the given socket.
pub fn new(
sock: TcpStream,
session: u16,
history: OriginsHistory,
notify: NotifyReceiver,
timing: Timing,
) -> Self {
let (read, write) = sock.split();
Connection {
input: InputStream::new(read, notify),
output: OutputState::Idle(write),
session, history, timing
}
}
fn send(&mut self, input: Input) {
let sock = match mem::replace(&mut self.output, OutputState::Done) {
OutputState::Idle(sock) => sock,
_ => panic!("illegal output state"),
};
let send = match input {
Input::Query(Query::Serial { session, serial }) => {
let diff = if session == self.session {
self.history.get(serial)
}
else { None };
match diff {
Some(diff) => {
Sender::diff(
sock, self.input.version(), session, diff,
self.timing
)
}
None => {
Sender::reset(sock, self.input.version())
}
}
}
Input::Query(Query::Reset) => {
let (current, serial) = self.history.current_and_serial();
Sender::full(
sock, self.input.version(), self.session, serial, current,
self.timing
)
}
Input::Query(Query::Error(err)) => Sender::error(sock, err),
Input::Notify => {
let serial = self.history.serial();
Sender::notify(
sock, self.input.version(),self.session, serial
)
}
};
self.output = OutputState::Sending(send);
}
}
impl Future for Connection {
type Item = ();
type Error = ();
fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> {
loop {
let next = match self.output {
OutputState::Sending(ref mut send) => {
let sock = try_ready!(send.poll());
Err(sock)
}
OutputState::Idle(_) => {
// We need to wait for input.
match try_ready!(self.input.poll()) {
Some(input) => Ok(input),
None => return Ok(Async::Ready(()))
}
}
OutputState::Done => panic!("illegal output state")
};
match next {
Err(sock) => {
self.output = OutputState::Idle(sock);
}
Ok(input) => {
self.send(input)
}
}
}
}
}
|
use crate::audio::AudioEngine;
use crate::robot::{send_robot_to_label, update_robot, BuiltInLabel, RobotId, Robots};
use crate::{
adjust_coordinate, bullet_from_param, Board, ByteString, CardinalDirection, Coordinate,
Counters, Explosion, ExplosionResult, ExtendedColorValue, ExtendedParam, KeyPress,
MessageBoxLine, Robot, RunStatus, Thing, WorldState, World
};
use crate::sprite::Sprite;
use num_traits::ToPrimitive;
use std::iter;
use std::path::Path;
pub const NORTH: (i8, i8) = (0, -1);
pub const SOUTH: (i8, i8) = (0, 1);
pub const EAST: (i8, i8) = (1, 0);
pub const WEST: (i8, i8) = (-1, 0);
pub const IDLE: (i8, i8) = (0, 0);
pub enum GameStateChange {
Teleport(ByteString, Coordinate<u16>),
Restore(usize, Coordinate<u16>),
MessageBox(Vec<MessageBoxLine>, ByteString, Option<RobotId>),
}
#[derive(PartialEq)]
pub enum LabelAction {
RunJustEntered,
RunJustLoadedAndJustEntered,
Nothing,
}
pub fn enter_board(
state: &mut WorldState,
audio: &dyn AudioEngine,
board: &mut Board,
player_pos: Coordinate<u16>,
robots: &mut Vec<Robot>,
global_robot: &mut Robot,
label_action: LabelAction,
reenter: bool,
) {
reset_update_done(board, &mut state.update_done);
if board.mod_file != "*" {
audio.load_module(&board.mod_file);
}
let old_pos = board.player_pos;
if old_pos != player_pos {
move_level_to(
board,
robots,
&old_pos,
&player_pos,
&mut *state.update_done,
).unwrap();
}
board.player_pos = player_pos;
reset_view(board);
state.scroll_locked = false;
Robots::new(robots, global_robot).foreach(|robot, _id| {
if reenter {
// XXX: This feels hacky.
robot.current_loc = 0;
robot.current_line = 0;
}
if label_action == LabelAction::RunJustLoadedAndJustEntered {
if send_robot_to_label(robot, BuiltInLabel::JustLoaded) {
return;
}
}
if label_action != LabelAction::Nothing {
send_robot_to_label(robot, BuiltInLabel::JustEntered);
}
})
}
pub fn reset_view(board: &mut Board) {
let vwidth = board.viewport_size.0 as u16;
let vheight = board.viewport_size.1 as u16;
let xpos = (board.player_pos.0.checked_sub(vwidth / 2))
.unwrap_or(0)
.min(board.width as u16 - vwidth);
let ypos = (board.player_pos.1.checked_sub(vheight / 2))
.unwrap_or(0)
.min(board.height as u16 - vheight);
board.scroll_offset = Coordinate(xpos, ypos);
}
pub enum ExternalStateChange {
MessageBox(Vec<MessageBoxLine>, ByteString, Option<RobotId>),
}
pub fn run_board_update(
world: &mut World,
audio: &dyn AudioEngine,
world_path: &Path,
counters: &mut Counters,
boards: &[ByteString],
board_id: &mut usize,
key: Option<KeyPress>,
) -> Option<ExternalStateChange> {
let (ref mut board, ref mut robots) = world.boards[*board_id];
let orig_player_pos = board.player_pos;
let change = update_board(
&mut world.state,
audio,
key,
world_path,
counters,
boards,
board,
*board_id,
robots,
&mut world.global_robot,
);
// A robot could have moved the player.
if board.player_pos != orig_player_pos &&
!world.state.scroll_locked
{
reset_view(board);
}
if let Some(change) = change {
let new_board = match change {
GameStateChange::Teleport(board, coord) => {
let id = world.boards.iter().position(|(b, _)| b.title == board);
if let Some(id) = id {
Some((id, coord))
} else {
warn!("Couldn't find board {:?}", board);
None
}
}
GameStateChange::Restore(id, coord) => {
Some((id, coord))
}
GameStateChange::MessageBox(lines, title, rid) => {
return Some(ExternalStateChange::MessageBox(lines, title, rid));
}
};
if let Some((id, coord)) = new_board {
*board_id = id;
let (ref mut board, ref mut robots) = world.boards[id];
enter_board(&mut world.state, audio, board, coord, robots, &mut world.global_robot, LabelAction::RunJustEntered, false);
}
}
None
}
pub fn reset_update_done(board: &Board, update_done: &mut Vec<bool>) {
update_done.clear();
let total_size = (board.width * board.height) as usize;
update_done.reserve(total_size);
update_done.extend(iter::repeat(false).take(total_size));
}
pub(crate) fn put_thing(
board: &mut Board,
sprites: &mut [Sprite],
color: ExtendedColorValue,
thing: Thing,
param: ExtendedParam,
pos: Coordinate<u16>,
update_done: &mut [bool],
) -> Result<(), ()> {
let color = match color {
ExtendedColorValue::Known(c) => c.0,
// TODO: have a table of default foreground colors for things,
// get the current background color at destination.
ExtendedColorValue::Unknown(Some(_), None)
| ExtendedColorValue::Unknown(None, Some(_))
| ExtendedColorValue::Unknown(None, None)
| ExtendedColorValue::Unknown(Some(_), Some(_)) => 0x07, //HACK
};
// TODO: have a table of default parameters for things.
let param = match param {
ExtendedParam::Specific(p) => p.0,
ExtendedParam::Any => 0x00, //HACK
};
if thing == Thing::Sprite {
sprites[param as usize].enabled = true;
sprites[param as usize].pos = Coordinate(pos.0 as i32, pos.1 as i32);
return Ok(());
}
put_at(board, &pos, color, thing, param, update_done)
}
pub fn put_at(
board: &mut Board,
pos: &Coordinate<u16>,
color: u8,
thing: Thing,
param: u8,
update_done: &mut [bool],
) -> Result<(), ()> {
board.put_at(&pos, thing.to_u8().unwrap(), color, param)?;
update_done[pos.1 as usize * board.width + pos.0 as usize] = true;
Ok(())
}
pub fn move_level_to(
board: &mut Board,
robots: &mut [Robot],
from: &Coordinate<u16>,
to: &Coordinate<u16>,
update_done: &mut [bool],
) -> Result<(), ()> {
board.move_level_to(robots, from, to)?;
update_done[to.1 as usize * board.width + to.0 as usize] = true;
Ok(())
}
pub fn move_level(
board: &mut Board,
robots: &mut [Robot],
pos: &Coordinate<u16>,
xdiff: i8,
ydiff: i8,
update_done: &mut [bool],
) -> Result<(), ()> {
board.move_level(robots, pos, xdiff, ydiff)?;
let x = (pos.0 as i16 + xdiff as i16) as usize;
let y = (pos.1 as i16 + ydiff as i16) as usize;
update_done[y * board.width + x] = true;
Ok(())
}
pub fn update_board(
state: &mut WorldState,
audio: &dyn AudioEngine,
key: Option<KeyPress>,
world_path: &Path,
counters: &mut Counters,
boards: &[ByteString],
board: &mut Board,
board_id: usize,
all_robots: &mut Vec<Robot>,
global_robot: &mut Robot,
) -> Option<GameStateChange> {
debug!("running global robot");
let change = update_robot(
state,
audio,
key,
world_path,
counters,
boards,
board,
board_id,
Robots::new(all_robots, global_robot),
RobotId::Global,
false,
);
if change.is_some() {
return change;
}
debug!("updating board: {},{}", board.width, board.height);
for y in 0..board.height {
for x in 0..board.width {
if state.update_done[y * board.width + x] {
debug!("already updated {},{}", x, y);
continue;
}
let coord = Coordinate(x as u16, y as u16);
let level_param = board.level_at(&coord).unwrap().2;
match board.thing_at(&coord).unwrap() {
Thing::Robot | Thing::RobotPushable => {
let robots = Robots::new(all_robots, global_robot);
let robot_id = RobotId::from(level_param);
assert_eq!(robots.get(robot_id).position, coord, "robot {:?}", robot_id);
debug!("running robot at {},{}", x, y);
let change = update_robot(
state,
audio,
key,
world_path,
counters,
boards,
board,
board_id,
robots,
RobotId::from(level_param),
false,
);
if change.is_some() {
return change;
}
}
Thing::Explosion => {
let mut explosion = Explosion::from_param(level_param);
if explosion.stage == 0 {
if explosion.size > 0 {
explosion.size -= 1;
board.level_at_mut(&coord).unwrap().2 = explosion.to_param();
let dirs = [
CardinalDirection::North,
CardinalDirection::South,
CardinalDirection::East,
CardinalDirection::West,
];
for dir in &dirs {
let adjusted = adjust_coordinate(coord, board, *dir);
let coord = match adjusted {
Some(coord) => coord,
None => continue,
};
let thing = board.thing_at(&coord).unwrap();
if !thing.is_solid() && thing != Thing::Explosion {
put_at(
board,
&coord,
0x00,
Thing::Explosion,
explosion.to_param(),
&mut *state.update_done,
).unwrap();
} else if thing.is_robot() {
let robot_id = RobotId::from(board.level_at(&coord).unwrap().2);
let mut robots = Robots::new(all_robots, global_robot);
let robot = robots.get_mut(robot_id);
send_robot_to_label(robot, BuiltInLabel::Bombed);
}
// TODO: hurt player.
}
}
}
if explosion.stage == 3 {
let (thing, color) = match board.explosion_result {
ExplosionResult::Nothing => (Thing::Space, 0x07),
ExplosionResult::Ash => (Thing::Floor, 0x08),
ExplosionResult::Fire => (Thing::Fire, 0x0C),
};
put_at(board, &coord, color, thing, 0x00, &mut *state.update_done).unwrap();
} else {
explosion.stage += 1;
board.level_at_mut(&coord).unwrap().2 = explosion.to_param();
}
}
Thing::Fire => {
if rand::random::<u8>() >= 20 {
let cur_param = level_param;
if cur_param < 5 {
board.level_at_mut(&coord).unwrap().2 += 1;
} else {
board.level_at_mut(&coord).unwrap().2 = 0;
}
}
let rval = rand::random::<u8>();
if rval < 8 {
if rval == 1 && !board.fire_burns_forever {
put_at(
board,
&coord,
0x08,
Thing::Floor,
0x00,
&mut *state.update_done,
).unwrap();
}
let dirs = [
CardinalDirection::North,
CardinalDirection::South,
CardinalDirection::East,
CardinalDirection::West,
];
for dir in &dirs {
let adjusted = adjust_coordinate(coord, board, *dir);
let coord = match adjusted {
Some(coord) => coord,
None => continue,
};
let thing = board.thing_at(&coord).unwrap();
let level = board.level_at(&coord).unwrap();
let thing_id = level.0;
let spread = (thing == Thing::Space && board.fire_burns_space)
|| (thing_id >= Thing::Fake.to_u8().unwrap()
&& thing_id <= Thing::ThickWeb.to_u8().unwrap()
&& board.fire_burns_fakes)
|| (thing == Thing::Tree && board.fire_burns_trees)
|| (level.1 == 0x06
&& board.fire_burns_brown
&& thing_id < Thing::Sensor.to_u8().unwrap());
if spread {
put_at(
board,
&coord,
0x0C,
Thing::Fire,
0x00,
&mut *state.update_done,
).unwrap();
}
}
}
}
Thing::OpenGate => {
let param = level_param;
if param == 0 {
board.level_at_mut(&coord).unwrap().0 = Thing::Gate.to_u8().unwrap();
} else {
board.level_at_mut(&coord).unwrap().2 -= 1;
}
}
Thing::OpenDoor => {
let param = level_param;
let cur_wait = param & 0xE0;
let stage = param & 0x1F;
const OPEN_DOOR_MOVE: &[(i8, i8)] = &[
WEST, NORTH, EAST, NORTH, WEST, SOUTH, EAST, SOUTH, IDLE, IDLE, IDLE, IDLE,
IDLE, IDLE, IDLE, IDLE, EAST, SOUTH, WEST, SOUTH, EAST, NORTH, WEST, NORTH,
SOUTH, EAST, SOUTH, WEST, NORTH, EAST, NORTH, WEST,
];
const OPEN_DOOR_WAIT: &[u8] = &[
32, 32, 32, 32, 32, 32, 32, 32, 224, 224, 224, 224, 224, 224, 224, 224,
224, 224, 224, 224, 224, 224, 224, 224, 32, 32, 32, 32, 32, 32, 32, 32,
];
let door_wait = OPEN_DOOR_WAIT[stage as usize];
let door_move = OPEN_DOOR_MOVE[stage as usize];
// TODO: less magic numbers.
if cur_wait == door_wait {
if param & 0x18 == 0x18 {
let (ref mut id, _, ref mut param) = board.level_at_mut(&coord).unwrap();
*param &= 0x07;
*id = Thing::Door.to_u8().unwrap();
} else {
board.level_at_mut(&coord).unwrap().2 = stage + 8;
}
if door_move != IDLE {
// FIXME: support pushing
// FIXME: check for blocked, act appropriately.
move_level(
board,
all_robots,
&coord,
door_move.0,
door_move.1,
&mut *state.update_done,
).unwrap();
}
} else {
board.level_at_mut(&coord).unwrap().2 = param + 0x20;
}
}
Thing::Bullet => {
let param = board.level_at(&coord).unwrap().2;
let (_type_, dir) = bullet_from_param(param);
let new_pos = adjust_coordinate(coord, board, dir);
if let Some(ref new_pos) = new_pos {
// TODO: shot behaviour
let dest_thing = board.thing_at(new_pos).unwrap();
if dest_thing.is_solid() {
board.remove_thing_at(&coord).unwrap();
match dest_thing {
Thing::Bullet => { board.remove_thing_at(&new_pos).unwrap(); }
Thing::Robot | Thing::RobotPushable => {
let robot_id = RobotId::from(board.level_at(&new_pos).unwrap().2);
let mut robots = Robots::new(all_robots, global_robot);
let robot = robots.get_mut(robot_id);
send_robot_to_label(robot, BuiltInLabel::Shot);
}
// TODO: player, bombs, mines, etc.
_ => (),
}
} else {
let _ = move_level_to(
board,
all_robots,
&coord,
&new_pos,
&mut *state.update_done,
);
}
} else {
let _ = board.remove_thing_at(&coord);
}
}
Thing::LitBomb => {
let param = level_param;
if param & 0x7f == 7 {
let size = if param & 0x80 != 0 { 7 } else { 4 };
let explosion = Explosion { stage: 0, size };
put_at(
board,
&coord,
0x00,
Thing::Explosion,
explosion.to_param(),
&mut *state.update_done,
).unwrap();
} else {
board.level_at_mut(&coord).unwrap().2 = param + 1;
}
}
_ => (),
}
}
}
debug!(
"updating board in reverse: {},{}",
board.width, board.height
);
for y in (0..board.height).rev() {
for x in (0..board.width).rev() {
let coord = Coordinate(x as u16, y as u16);
match board.thing_at(&coord).unwrap() {
Thing::Robot | Thing::RobotPushable => {
let robots = Robots::new(all_robots, global_robot);
debug!("running robot at {},{}", x, y);
let change = update_robot(
state,
audio,
key,
world_path,
counters,
boards,
board,
board_id,
robots,
RobotId::from(board.level_at(&coord).unwrap().2),
true,
);
if change.is_some() {
return change;
}
}
_ => (),
}
}
}
state.message_color += 1;
if state.message_color > 0x0F {
state.message_color = 0x01;
}
if board.remaining_message_cycles > 0 {
board.remaining_message_cycles -= 1;
}
reset_update_done(board, &mut state.update_done);
let mut robots = Robots::new(all_robots, global_robot);
robots.foreach(|robot, _| {
robot.status = RunStatus::NotRun;
});
None
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
#[repr(transparent)]
pub struct HingeState(pub i32);
impl HingeState {
pub const Unknown: Self = Self(0i32);
pub const Closed: Self = Self(1i32);
pub const Concave: Self = Self(2i32);
pub const Flat: Self = Self(3i32);
pub const Convex: Self = Self(4i32);
pub const Full: Self = Self(5i32);
}
impl ::core::marker::Copy for HingeState {}
impl ::core::clone::Clone for HingeState {
fn clone(&self) -> Self {
*self
}
}
pub type TwoPanelHingedDevicePosturePreview = *mut ::core::ffi::c_void;
pub type TwoPanelHingedDevicePosturePreviewReading = *mut ::core::ffi::c_void;
pub type TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs = *mut ::core::ffi::c_void;
|
use std::path::Path;
use deck_core::FilesystemId;
use super::path::{DirectoryPath, LockedPath};
use super::Directory;
#[derive(Debug)]
pub struct State<D> {
directory: D,
}
impl<D> State<D>
where
D: Directory + 'static,
D::Id: 'static,
D::Input: 'static,
D::Output: 'static,
{
pub fn new(directory: D) -> Self {
State { directory }
}
pub fn contains(&self, prefix: &Path, id: &D::Id) -> bool {
let path = prefix.join(D::NAME).join(id.to_path());
path.exists()
}
pub async fn read<'a>(
&'a self,
prefix: &'a Path,
id: &'a D::Id,
) -> Result<Option<D::Output>, ()> {
let path = DirectoryPath::new(prefix, D::NAME, id.clone());
if let Some(read_path) = await!(path.lock_reading())? {
await!(self.directory.read(&read_path))
} else {
Ok(None)
}
}
pub async fn write<'a>(
&'a self,
prefix: &'a Path,
input: D::Input,
) -> Result<(D::Id, D::Output), ()> {
// Since the `D::Id` of a given `D::Input` is not known ahead of time, we compute a
// temporary one here and use it to mark ourselves as writing. A new `D::Id`, which may be
// different from the temporary one, will be returned from `Directory::write()` along with
// the `D::Output`.
let temp_id = await!(self.directory.precompute_id(&input))?;
let path = DirectoryPath::new(prefix, D::NAME, temp_id.clone());
let locked = await!(path.lock_writing())?;
match locked {
LockedPath::ReadExisting(path) => {
println!("already in store");
let output = await!(self.directory.read(&path))?;
Ok((temp_id, output.unwrap()))
}
LockedPath::WriteNew(mut path) => {
let output = await!(self.directory.write(&mut path, input))?;
let read_only = path.to_read_only();
let new_id = await!(self.directory.compute_id(&read_only))?;
// TODO: Register paths in database transaction here.
await!(path.normalize_and_rename())?;
Ok((new_id, output))
}
}
}
}
|
/*
Copyright 2020 Timo Saarinen
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 super::*;
/// AIS VDM/VDO type 27: Long Range AIS Broadcast message
pub(crate) fn handle(
bv: &BitVec,
station: Station,
own_vessel: bool,
) -> Result<ParsedMessage, ParseError> {
Ok(ParsedMessage::VesselDynamicData(VesselDynamicData {
own_vessel: { own_vessel },
station: { station },
ais_type: { AisClass::ClassA },
mmsi: { pick_u64(&bv, 8, 30) as u32 },
nav_status: { NavigationStatus::new(pick_u64(&bv, 40, 4) as u8) },
rot: { None },
rot_direction: { None },
sog_knots: {
let sog_raw = pick_u64(&bv, 62, 6);
if sog_raw != 63 {
Some(sog_raw as f64)
} else {
None
}
},
high_position_accuracy: { pick_u64(&bv, 38, 1) != 0 },
latitude: {
let lat_raw = pick_i64(&bv, 44, 18) as i32;
if lat_raw != 181000 {
Some((lat_raw as f64) / 600.0)
} else {
None
}
},
longitude: {
let lon_raw = pick_i64(&bv, 62, 17) as i32;
if lon_raw != 181000 {
Some((lon_raw as f64) / 600.0)
} else {
None
}
},
cog: {
let cog_raw = pick_u64(&bv, 62, 17);
if cog_raw != 91000 {
Some(cog_raw as f64 * 0.1)
} else {
None
}
},
heading_true: None,
timestamp_seconds: 0,
positioning_system_meta: None,
current_gnss_position: Some(pick_u64(&bv, 62, 1) == 0),
special_manoeuvre: None,
raim_flag: pick_u64(&bv, 39, 1) != 0,
class_b_unit_flag: None,
class_b_display: None,
class_b_dsc: None,
class_b_band_flag: None,
class_b_msg22_flag: None,
class_b_mode_flag: None,
class_b_css_flag: None,
radio_status: None,
}))
}
// -------------------------------------------------------------------------------------------------
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_vdm_type27() {
let mut p = NmeaParser::new();
match p.parse_sentence("!AIVDM,1,1,,B,KC5E2b@U19PFdLbMuc5=ROv62<7m,0*16") {
Ok(ps) => {
match ps {
// The expected result
ParsedMessage::VesselDynamicData(vdd) => {
assert_eq!(vdd.mmsi, 206914217);
assert_eq!(vdd.nav_status, NavigationStatus::NotUnderCommand);
assert_eq!(vdd.rot, None);
assert_eq!(vdd.rot_direction, None);
assert_eq!(vdd.sog_knots, Some(1.0));
assert_eq!(vdd.high_position_accuracy, false);
assert::close(vdd.latitude.unwrap_or(0.0), 137.0, 0.1);
assert::close(vdd.longitude.unwrap_or(0.0), 4.8, 0.1);
assert::close(vdd.cog.unwrap_or(0.0), 290.0, 1.0);
assert_eq!(vdd.timestamp_seconds, 0);
assert_eq!(vdd.current_gnss_position, Some(true));
assert_eq!(vdd.raim_flag, false);
}
ParsedMessage::Incomplete => {
assert!(false);
}
_ => {
assert!(false);
}
}
}
Err(e) => {
assert_eq!(e.to_string(), "OK");
}
}
}
}
|
// Copyright 2018 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(missing_docs)]
use std;
use sys;
#[derive(Copy, Clone, PartialEq, PartialOrd)]
pub struct Language {
/// The underlying `hb_language_t` from the `harfbuzz-sys` crate.
///
/// This isn't commonly needed unless interfacing directly with
/// functions from the `harfbuzz-sys` crate that haven't been
/// safely exposed.
raw: sys::hb_language_t,
}
impl Language {
pub fn from_string(lang: &str) -> Self {
Language {
raw: unsafe {
sys::hb_language_from_string(
lang.as_ptr() as *const std::os::raw::c_char,
lang.len() as std::os::raw::c_int,
)
},
}
}
pub fn to_string(&self) -> &str {
unsafe { std::ffi::CStr::from_ptr(sys::hb_language_to_string(self.raw)) }
.to_str()
.unwrap()
}
pub unsafe fn from_raw(raw: sys::hb_language_t) -> Self {
Language { raw }
}
pub fn as_raw(self) -> sys::hb_language_t {
self.raw
}
pub fn get_process_default() -> Self {
Language {
raw: unsafe { sys::hb_language_get_default() },
}
}
pub fn is_valid(self) -> bool {
!self.raw.is_null()
}
}
impl std::fmt::Debug for Language {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
fmt.write_str(self.to_string())
}
}
#[cfg(test)]
mod tests {
use super::Language;
#[test]
fn test_lookup() {
let en = Language::from_string("en_US");
assert!(en.is_valid());
}
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
executor::Executor,
mock_executor::{get_signed_txn, MockExecutor},
TransactionExecutor,
};
use anyhow::Result;
use compiler::Compiler;
use crypto::keygen::KeyGen;
use logger::prelude::*;
use starcoin_config::ChainNetwork;
use starcoin_state_api::{ChainState, ChainStateWriter};
use state_tree::mock::MockStateNodeStore;
use statedb::ChainStateDB;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use types::{
access_path::AccessPath,
account_address::AccountAddress,
account_config,
account_config::AccountResource,
account_config::BalanceResource,
block_metadata::BlockMetadata,
transaction::Transaction,
transaction::{Module, TransactionPayload},
vm_error::{StatusCode, VMStatus},
};
use vm_runtime::mock_vm::{
encode_mint_transaction, encode_transfer_program, encode_transfer_transaction, KEEP_STATUS,
};
use vm_runtime::{
account::Account,
common_transactions::{create_account_txn_sent_as_association, peer_to_peer_txn},
};
#[stest::test]
fn test_execute_mint_txn() -> Result<()> {
let storage = MockStateNodeStore::new();
let chain_state = ChainStateDB::new(Arc::new(storage), None);
let account = Account::new();
let receiver_account_address = account.address().clone();
chain_state.create_account(AccountAddress::default())?;
chain_state.create_account(receiver_account_address)?;
let txn = MockExecutor::build_mint_txn(
account.address().clone(),
account.auth_key_prefix(),
1,
1000,
);
let output = MockExecutor::execute_transaction(&chain_state, txn).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output.status());
Ok(())
}
#[stest::test]
fn test_execute_transfer_txn() -> Result<()> {
let storage = MockStateNodeStore::new();
let chain_state = ChainStateDB::new(Arc::new(storage), None);
let sender_account_address = AccountAddress::random();
let receiver_account_address = AccountAddress::random();
chain_state.create_account(sender_account_address)?;
chain_state.create_account(receiver_account_address)?;
let mint_txn = encode_mint_transaction(sender_account_address, 10000);
let transfer_txn =
encode_transfer_transaction(sender_account_address, receiver_account_address, 100);
let output1 = MockExecutor::execute_transaction(&chain_state, mint_txn).unwrap();
let output2 = MockExecutor::execute_transaction(&chain_state, transfer_txn).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output1.status());
assert_eq!(KEEP_STATUS.clone(), *output2.status());
Ok(())
}
#[stest::test]
fn test_validate_txn() -> Result<()> {
let storage = MockStateNodeStore::new();
let chain_state = ChainStateDB::new(Arc::new(storage), None);
let sender_account_address = AccountAddress::random();
let receiver_account_address = AccountAddress::random();
let (private_key, public_key) = KeyGen::from_os_rng().generate_keypair();
let program = encode_transfer_program(receiver_account_address, 100);
let txn = get_signed_txn(sender_account_address, 0, &private_key, public_key, program);
let output = MockExecutor::validate_transaction(&chain_state, txn);
assert_eq!(
output,
Some(VMStatus::new(StatusCode::SENDING_ACCOUNT_DOES_NOT_EXIST))
);
// now we create the account
chain_state.create_account(sender_account_address)?;
chain_state.create_account(receiver_account_address)?;
let (private_key, public_key) = KeyGen::from_os_rng().generate_keypair();
let program = encode_transfer_program(receiver_account_address, 100);
let txn = get_signed_txn(sender_account_address, 0, &private_key, public_key, program);
// validate again
let output = MockExecutor::validate_transaction(&chain_state, txn);
assert_eq!(output, None);
// now we execute it
let mint_txn = encode_mint_transaction(sender_account_address, 10000);
let transfer_txn =
encode_transfer_transaction(sender_account_address, receiver_account_address, 100);
let output1 = MockExecutor::execute_transaction(&chain_state, mint_txn).unwrap();
let output2 = MockExecutor::execute_transaction(&chain_state, transfer_txn).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output1.status());
assert_eq!(KEEP_STATUS.clone(), *output2.status());
// after execute, the seq numebr should be 2.
// and then validate again
let (private_key, public_key) = KeyGen::from_os_rng().generate_keypair();
let program = encode_transfer_program(receiver_account_address, 100);
let txn = get_signed_txn(
sender_account_address,
0,
&private_key,
public_key.clone(),
program.clone(),
);
// validate again
let output = MockExecutor::validate_transaction(&chain_state, txn);
assert_eq!(
output,
Some(VMStatus::new(StatusCode::SEQUENCE_NUMBER_TOO_OLD))
);
// use right seq number
let txn = get_signed_txn(
sender_account_address,
2,
&private_key,
public_key.clone(),
program.clone(),
);
let output = MockExecutor::validate_transaction(&chain_state, txn);
assert_eq!(output, None);
Ok(())
}
#[stest::test]
fn test_validate_txn_with_starcoin_vm() -> Result<()> {
let (_hash, state_set) = Executor::init_genesis(ChainNetwork::Dev.get_config()).unwrap();
let storage = MockStateNodeStore::new();
let chain_state = ChainStateDB::new(Arc::new(storage), None);
chain_state
.apply(state_set)
.unwrap_or_else(|e| panic!("Failure to apply state set: {}", e));
let account1 = Account::new();
let txn1 = Transaction::UserTransaction(create_account_txn_sent_as_association(
&account1, 1, // fix me
50_000_000,
));
let output1 = Executor::execute_transaction(&chain_state, txn1).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output1.status());
let account2 = Account::new();
let raw_txn = Executor::build_transfer_txn(
account1.address().clone(),
account1.auth_key_prefix(),
account2.address().clone(),
account2.auth_key_prefix(),
0,
1000,
);
let txn2 = account1.create_user_txn_from_raw_txn(raw_txn);
let output = Executor::validate_transaction(&chain_state, txn2);
assert_eq!(output, None);
Ok(())
}
#[stest::test]
fn test_execute_real_txn_with_starcoin_vm() -> Result<()> {
let (_hash, state_set) = Executor::init_genesis(ChainNetwork::Dev.get_config()).unwrap();
let storage = MockStateNodeStore::new();
let chain_state = ChainStateDB::new(Arc::new(storage), None);
chain_state
.apply(state_set)
.unwrap_or_else(|e| panic!("Failure to apply state set: {}", e));
let sequence_number1 = get_sequence_number(account_config::association_address(), &chain_state);
let account1 = Account::new();
let txn1 = Transaction::UserTransaction(create_account_txn_sent_as_association(
&account1,
sequence_number1, // fix me
50_000_000,
));
let output1 = Executor::execute_transaction(&chain_state, txn1).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output1.status());
let sequence_number2 = get_sequence_number(account_config::association_address(), &chain_state);
let account2 = Account::new();
let txn2 = Transaction::UserTransaction(create_account_txn_sent_as_association(
&account2,
sequence_number2, // fix me
1_000,
));
let output2 = Executor::execute_transaction(&chain_state, txn2).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output2.status());
let sequence_number3 = get_sequence_number(account1.address().clone(), &chain_state);
let txn3 = Transaction::UserTransaction(peer_to_peer_txn(
&account1,
&account2,
sequence_number3, // fix me
100,
));
let output3 = Executor::execute_transaction(&chain_state, txn3).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output3.status());
Ok(())
}
#[stest::test]
fn test_execute_mint_txn_with_starcoin_vm() -> Result<()> {
let (_hash, state_set) = Executor::init_genesis(ChainNetwork::Dev.get_config()).unwrap();
let storage = MockStateNodeStore::new();
let chain_state = ChainStateDB::new(Arc::new(storage), None);
chain_state
.apply(state_set)
.unwrap_or_else(|e| panic!("Failure to apply state set: {}", e));
let account = Account::new();
let txn = Executor::build_mint_txn(
account.address().clone(),
account.auth_key_prefix(),
1,
1000,
);
let output = Executor::execute_transaction(&chain_state, txn).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output.status());
Ok(())
}
#[stest::test]
fn test_execute_transfer_txn_with_starcoin_vm() -> Result<()> {
let (_hash, state_set) = Executor::init_genesis(ChainNetwork::Dev.get_config()).unwrap();
let storage = MockStateNodeStore::new();
let chain_state = ChainStateDB::new(Arc::new(storage), None);
chain_state
.apply(state_set)
.unwrap_or_else(|e| panic!("Failure to apply state set: {}", e));
let account1 = Account::new();
let txn1 = Transaction::UserTransaction(create_account_txn_sent_as_association(
&account1, 1, // fix me
50_000_000,
));
let output1 = Executor::execute_transaction(&chain_state, txn1).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output1.status());
let account2 = Account::new();
let raw_txn = Executor::build_transfer_txn(
account1.address().clone(),
account1.auth_key_prefix(),
account2.address().clone(),
account2.auth_key_prefix(),
0,
1000,
);
let txn2 = Transaction::UserTransaction(account1.create_user_txn_from_raw_txn(raw_txn));
let output = Executor::execute_transaction(&chain_state, txn2).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output.status());
Ok(())
}
#[stest::test]
fn test_sequence_number() -> Result<()> {
let (_hash, state_set) = Executor::init_genesis(ChainNetwork::Dev.get_config()).unwrap();
let storage = MockStateNodeStore::new();
let chain_state = ChainStateDB::new(Arc::new(storage), None);
chain_state
.apply(state_set)
.unwrap_or_else(|e| panic!("Failure to apply state set: {}", e));
let old_balance = get_balance(account_config::association_address(), &chain_state);
info!("old balance: {:?}", old_balance);
let old_sequence_number =
get_sequence_number(account_config::association_address(), &chain_state);
let account = Account::new();
let txn = Executor::build_mint_txn(
account.address().clone(),
account.auth_key_prefix(),
1,
1000,
);
let output = Executor::execute_transaction(&chain_state, txn).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output.status());
let new_sequence_number =
get_sequence_number(account_config::association_address(), &chain_state);
assert_eq!(new_sequence_number, old_sequence_number + 1);
Ok(())
}
fn get_sequence_number(addr: AccountAddress, chain_state: &dyn ChainState) -> u64 {
let access_path = AccessPath::new_for_account(addr);
let state = chain_state
.get(&access_path)
.expect("read account state should ok");
match state {
None => 0u64,
Some(s) => AccountResource::make_from(&s)
.expect("account resource decode ok")
.sequence_number(),
}
}
fn get_balance(address: AccountAddress, state_db: &dyn ChainState) -> u64 {
let ap = AccessPath::new_for_balance(address);
let balance_resource = state_db.get(&ap).expect("read balance resource should ok");
match balance_resource {
None => 0u64,
Some(b) => BalanceResource::make_from(b.as_slice())
.expect("decode balance resource should ok")
.coin(),
}
}
pub fn compile_module_with_address(
address: &AccountAddress,
file_name: &str,
code: &str,
) -> TransactionPayload {
let addr = address.clone().into();
let compiler = Compiler {
address: addr,
..Compiler::default()
};
TransactionPayload::Module(Module::new(
compiler.into_module_blob(file_name, code).unwrap(),
))
}
#[stest::test]
fn test_publish_module() -> Result<()> {
let (_hash, state_set) = Executor::init_genesis(ChainNetwork::Dev.get_config()).unwrap();
let storage = MockStateNodeStore::new();
let chain_state = ChainStateDB::new(Arc::new(storage), None);
chain_state
.apply(state_set)
.unwrap_or_else(|e| panic!("Failure to apply state set: {}", e));
let account1 = Account::new();
let txn1 = Transaction::UserTransaction(create_account_txn_sent_as_association(
&account1, 1, // fix me
50_000_000,
));
let output1 = Executor::execute_transaction(&chain_state, txn1).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output1.status());
let program = String::from(
"
module M {
}
",
);
// compile with account 1's address
let compiled_module = compile_module_with_address(account1.address(), "file_name", &program);
let txn = Transaction::UserTransaction(account1.create_signed_txn_impl(
*account1.address(),
compiled_module.into(),
0,
100_000,
1,
account_config::starcoin_type_tag().into(),
));
let output = Executor::execute_transaction(&chain_state, txn).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output.status());
for _i in 0..10 {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let txn2 = Transaction::BlockMetadata(BlockMetadata::new(
crypto::HashValue::zero(),
timestamp,
account1.address().clone(),
Some(account1.auth_key_prefix()),
));
let output2 = Executor::execute_transaction(&chain_state, txn2).unwrap();
assert_eq!(KEEP_STATUS.clone(), *output2.status());
let balance = get_balance(account1.address().clone(), &chain_state);
debug!("balance= {:?}", balance);
}
Ok(())
}
|
use core::convert::TryFrom;
use crate::util::{
bytes::{DeserializeError, SerializeError},
DebugByte,
};
/// Unit represents a single unit of input for DFA based regex engines.
///
/// **NOTE:** It is not expected for consumers of this crate to need to use
/// this type unless they are implementing their own DFA. And even then, it's
/// not required: implementors may use other techniques to handle input.
///
/// Typically, a single unit of input for a DFA would be a single byte.
/// However, for the DFAs in this crate, matches are delayed by a single byte
/// in order to handle look-ahead assertions (`\b`, `$` and `\z`). Thus, once
/// we have consumed the haystack, we must run the DFA through one additional
/// transition using an input that indicates the haystack has ended.
///
/// Since there is no way to represent a sentinel with a `u8` since all
/// possible values *may* be valid inputs to a DFA, this type explicitly adds
/// room for a sentinel value.
///
/// The sentinel EOI value is always its own equivalence class and is
/// ultimately represented by adding 1 to the maximum equivalence class value.
/// So for example, the regex `^[a-z]+$` might be split into the following
/// equivalence classes:
///
/// ```text
/// 0 => [\x00-`]
/// 1 => [a-z]
/// 2 => [{-\xFF]
/// 3 => [EOI]
/// ```
///
/// Where EOI is the special sentinel value that is always in its own
/// singleton equivalence class.
#[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Ord)]
pub enum Unit {
U8(u8),
EOI(u16),
}
impl Unit {
/// Create a new input unit from a byte value.
///
/// All possible byte values are legal. However, when creating an input
/// unit for a specific DFA, one should be careful to only construct input
/// units that are in that DFA's alphabet. Namely, one way to compact a
/// DFA's in-memory representation is to collapse its transitions to a set
/// of equivalence classes into a set of all possible byte values. If a
/// DFA uses equivalence classes instead of byte values, then the byte
/// given here should be the equivalence class.
pub fn u8(byte: u8) -> Unit {
Unit::U8(byte)
}
pub fn eoi(num_byte_equiv_classes: usize) -> Unit {
assert!(
num_byte_equiv_classes <= 256,
"max number of byte-based equivalent classes is 256, but got {}",
num_byte_equiv_classes,
);
Unit::EOI(u16::try_from(num_byte_equiv_classes).unwrap())
}
pub fn as_u8(self) -> Option<u8> {
match self {
Unit::U8(b) => Some(b),
Unit::EOI(_) => None,
}
}
#[cfg(feature = "alloc")]
pub fn as_eoi(self) -> Option<usize> {
match self {
Unit::U8(_) => None,
Unit::EOI(eoi) => Some(eoi as usize),
}
}
pub fn as_usize(self) -> usize {
match self {
Unit::U8(b) => b as usize,
Unit::EOI(eoi) => eoi as usize,
}
}
pub fn is_eoi(&self) -> bool {
match *self {
Unit::EOI(_) => true,
_ => false,
}
}
#[cfg(feature = "alloc")]
pub fn is_word_byte(&self) -> bool {
self.as_u8().map_or(false, crate::util::is_word_byte)
}
}
impl core::fmt::Debug for Unit {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
match *self {
Unit::U8(b) => write!(f, "{:?}", DebugByte(b)),
Unit::EOI(_) => write!(f, "EOI"),
}
}
}
/// A representation of byte oriented equivalence classes.
///
/// This is used in a DFA to reduce the size of the transition table. This can
/// have a particularly large impact not only on the total size of a dense DFA,
/// but also on compile times.
#[derive(Clone, Copy)]
pub struct ByteClasses([u8; 256]);
impl ByteClasses {
/// Creates a new set of equivalence classes where all bytes are mapped to
/// the same class.
pub fn empty() -> ByteClasses {
ByteClasses([0; 256])
}
/// Creates a new set of equivalence classes where each byte belongs to
/// its own equivalence class.
#[cfg(feature = "alloc")]
pub fn singletons() -> ByteClasses {
let mut classes = ByteClasses::empty();
for i in 0..256 {
classes.set(i as u8, i as u8);
}
classes
}
/// Deserializes a byte class map from the given slice. If the slice is of
/// insufficient length or otherwise contains an impossible mapping, then
/// an error is returned. Upon success, the number of bytes read along with
/// the map are returned. The number of bytes read is always a multiple of
/// 8.
pub fn from_bytes(
slice: &[u8],
) -> Result<(ByteClasses, usize), DeserializeError> {
if slice.len() < 256 {
return Err(DeserializeError::buffer_too_small("byte class map"));
}
let mut classes = ByteClasses::empty();
for (b, &class) in slice[..256].iter().enumerate() {
classes.set(b as u8, class);
}
for b in classes.iter() {
if b.as_usize() >= classes.alphabet_len() {
return Err(DeserializeError::generic(
"found equivalence class greater than alphabet len",
));
}
}
Ok((classes, 256))
}
/// Writes this byte class map to the given byte buffer. if the given
/// buffer is too small, then an error is returned. Upon success, the total
/// number of bytes written is returned. The number of bytes written is
/// guaranteed to be a multiple of 8.
pub fn write_to(
&self,
mut dst: &mut [u8],
) -> Result<usize, SerializeError> {
let nwrite = self.write_to_len();
if dst.len() < nwrite {
return Err(SerializeError::buffer_too_small("byte class map"));
}
for b in 0..=255 {
dst[0] = self.get(b);
dst = &mut dst[1..];
}
Ok(nwrite)
}
/// Returns the total number of bytes written by `write_to`.
pub fn write_to_len(&self) -> usize {
256
}
/// Set the equivalence class for the given byte.
#[inline]
pub fn set(&mut self, byte: u8, class: u8) {
self.0[byte as usize] = class;
}
/// Get the equivalence class for the given byte.
#[inline]
pub fn get(&self, byte: u8) -> u8 {
self.0[byte as usize]
}
/// Get the equivalence class for the given byte while forcefully
/// eliding bounds checks.
#[inline]
pub unsafe fn get_unchecked(&self, byte: u8) -> u8 {
*self.0.get_unchecked(byte as usize)
}
/// Get the equivalence class for the given input unit and return the
/// class as a `usize`.
#[inline]
pub fn get_by_unit(&self, unit: Unit) -> usize {
match unit {
Unit::U8(b) => usize::try_from(self.get(b)).unwrap(),
Unit::EOI(b) => usize::try_from(b).unwrap(),
}
}
#[inline]
pub fn eoi(&self) -> Unit {
Unit::eoi(self.alphabet_len().checked_sub(1).unwrap())
}
/// Return the total number of elements in the alphabet represented by
/// these equivalence classes. Equivalently, this returns the total number
/// of equivalence classes.
#[inline]
pub fn alphabet_len(&self) -> usize {
// Add one since the number of equivalence classes is one bigger than
// the last one. But add another to account for the final EOI class
// that isn't explicitly represented.
self.0[255] as usize + 1 + 1
}
/// Returns the stride, as a base-2 exponent, required for these
/// equivalence classes.
///
/// The stride is always the smallest power of 2 that is greater than or
/// equal to the alphabet length. This is done so that converting between
/// state IDs and indices can be done with shifts alone, which is much
/// faster than integer division.
#[cfg(feature = "alloc")]
pub fn stride2(&self) -> usize {
self.alphabet_len().next_power_of_two().trailing_zeros() as usize
}
/// Returns true if and only if every byte in this class maps to its own
/// equivalence class. Equivalently, there are 257 equivalence classes
/// and each class contains exactly one byte (plus the special EOI class).
#[inline]
pub fn is_singleton(&self) -> bool {
self.alphabet_len() == 257
}
/// Returns an iterator over all equivalence classes in this set.
pub fn iter(&self) -> ByteClassIter<'_> {
ByteClassIter { classes: self, i: 0 }
}
/// Returns an iterator over a sequence of representative bytes from each
/// equivalence class. Namely, this yields exactly N items, where N is
/// equivalent to the number of equivalence classes. Each item is an
/// arbitrary byte drawn from each equivalence class.
///
/// This is useful when one is determinizing an NFA and the NFA's alphabet
/// hasn't been converted to equivalence classes yet. Picking an arbitrary
/// byte from each equivalence class then permits a full exploration of
/// the NFA instead of using every possible byte value.
#[cfg(feature = "alloc")]
pub fn representatives(&self) -> ByteClassRepresentatives<'_> {
ByteClassRepresentatives { classes: self, byte: 0, last_class: None }
}
/// Returns an iterator of the bytes in the given equivalence class.
pub fn elements(&self, class: Unit) -> ByteClassElements {
ByteClassElements { classes: self, class, byte: 0 }
}
/// Returns an iterator of byte ranges in the given equivalence class.
///
/// That is, a sequence of contiguous ranges are returned. Typically, every
/// class maps to a single contiguous range.
fn element_ranges(&self, class: Unit) -> ByteClassElementRanges {
ByteClassElementRanges { elements: self.elements(class), range: None }
}
}
impl core::fmt::Debug for ByteClasses {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if self.is_singleton() {
write!(f, "ByteClasses({{singletons}})")
} else {
write!(f, "ByteClasses(")?;
for (i, class) in self.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{:?} => [", class.as_usize())?;
for (start, end) in self.element_ranges(class) {
if start == end {
write!(f, "{:?}", start)?;
} else {
write!(f, "{:?}-{:?}", start, end)?;
}
}
write!(f, "]")?;
}
write!(f, ")")
}
}
}
/// An iterator over each equivalence class.
#[derive(Debug)]
pub struct ByteClassIter<'a> {
classes: &'a ByteClasses,
i: usize,
}
impl<'a> Iterator for ByteClassIter<'a> {
type Item = Unit;
fn next(&mut self) -> Option<Unit> {
if self.i + 1 == self.classes.alphabet_len() {
self.i += 1;
Some(self.classes.eoi())
} else if self.i < self.classes.alphabet_len() {
let class = self.i as u8;
self.i += 1;
Some(Unit::u8(class))
} else {
None
}
}
}
/// An iterator over representative bytes from each equivalence class.
#[cfg(feature = "alloc")]
#[derive(Debug)]
pub struct ByteClassRepresentatives<'a> {
classes: &'a ByteClasses,
byte: usize,
last_class: Option<u8>,
}
#[cfg(feature = "alloc")]
impl<'a> Iterator for ByteClassRepresentatives<'a> {
type Item = Unit;
fn next(&mut self) -> Option<Unit> {
while self.byte < 256 {
let byte = self.byte as u8;
let class = self.classes.get(byte);
self.byte += 1;
if self.last_class != Some(class) {
self.last_class = Some(class);
return Some(Unit::u8(byte));
}
}
if self.byte == 256 {
self.byte += 1;
return Some(self.classes.eoi());
}
None
}
}
/// An iterator over all elements in an equivalence class.
#[derive(Debug)]
pub struct ByteClassElements<'a> {
classes: &'a ByteClasses,
class: Unit,
byte: usize,
}
impl<'a> Iterator for ByteClassElements<'a> {
type Item = Unit;
fn next(&mut self) -> Option<Unit> {
while self.byte < 256 {
let byte = self.byte as u8;
self.byte += 1;
if self.class.as_u8() == Some(self.classes.get(byte)) {
return Some(Unit::u8(byte));
}
}
if self.byte < 257 {
self.byte += 1;
if self.class.is_eoi() {
return Some(Unit::eoi(256));
}
}
None
}
}
/// An iterator over all elements in an equivalence class expressed as a
/// sequence of contiguous ranges.
#[derive(Debug)]
pub struct ByteClassElementRanges<'a> {
elements: ByteClassElements<'a>,
range: Option<(Unit, Unit)>,
}
impl<'a> Iterator for ByteClassElementRanges<'a> {
type Item = (Unit, Unit);
fn next(&mut self) -> Option<(Unit, Unit)> {
loop {
let element = match self.elements.next() {
None => return self.range.take(),
Some(element) => element,
};
match self.range.take() {
None => {
self.range = Some((element, element));
}
Some((start, end)) => {
if end.as_usize() + 1 != element.as_usize()
|| element.is_eoi()
{
self.range = Some((element, element));
return Some((start, end));
}
self.range = Some((start, element));
}
}
}
}
}
/// A byte class set keeps track of an *approximation* of equivalence classes
/// of bytes during NFA construction. That is, every byte in an equivalence
/// class cannot discriminate between a match and a non-match.
///
/// For example, in the regex `[ab]+`, the bytes `a` and `b` would be in the
/// same equivalence class because it never matters whether an `a` or a `b` is
/// seen, and no combination of `a`s and `b`s in the text can discriminate a
/// match.
///
/// Note though that this does not compute the minimal set of equivalence
/// classes. For example, in the regex `[ac]+`, both `a` and `c` are in the
/// same equivalence class for the same reason that `a` and `b` are in the
/// same equivalence class in the aforementioned regex. However, in this
/// implementation, `a` and `c` are put into distinct equivalence classes. The
/// reason for this is implementation complexity. In the future, we should
/// endeavor to compute the minimal equivalence classes since they can have a
/// rather large impact on the size of the DFA. (Doing this will likely require
/// rethinking how equivalence classes are computed, including changing the
/// representation here, which is only able to group contiguous bytes into the
/// same equivalence class.)
#[derive(Clone, Debug)]
pub struct ByteClassSet(ByteSet);
impl ByteClassSet {
/// Create a new set of byte classes where all bytes are part of the same
/// equivalence class.
#[cfg(feature = "alloc")]
pub fn empty() -> Self {
ByteClassSet(ByteSet::empty())
}
/// Indicate the the range of byte given (inclusive) can discriminate a
/// match between it and all other bytes outside of the range.
#[cfg(feature = "alloc")]
pub fn set_range(&mut self, start: u8, end: u8) {
debug_assert!(start <= end);
if start > 0 {
self.0.add(start - 1);
}
self.0.add(end);
}
/// Add the contiguous ranges in the set given to this byte class set.
#[cfg(feature = "alloc")]
pub fn add_set(&mut self, set: &ByteSet) {
for (start, end) in set.iter_ranges() {
self.set_range(start, end);
}
}
/// Convert this boolean set to a map that maps all byte values to their
/// corresponding equivalence class. The last mapping indicates the largest
/// equivalence class identifier (which is never bigger than 255).
#[cfg(feature = "alloc")]
pub fn byte_classes(&self) -> ByteClasses {
let mut classes = ByteClasses::empty();
let mut class = 0u8;
let mut b = 0u8;
loop {
classes.set(b, class);
if b == 255 {
break;
}
if self.0.contains(b) {
class = class.checked_add(1).unwrap();
}
b = b.checked_add(1).unwrap();
}
classes
}
}
/// A simple set of bytes that is reasonably cheap to copy and allocation free.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ByteSet {
bits: BitSet,
}
/// The representation of a byte set. Split out so that we can define a
/// convenient Debug impl for it while keeping "ByteSet" in the output.
#[derive(Clone, Copy, Default, Eq, PartialEq)]
struct BitSet([u128; 2]);
impl ByteSet {
/// Create an empty set of bytes.
#[cfg(feature = "alloc")]
pub fn empty() -> ByteSet {
ByteSet { bits: BitSet([0; 2]) }
}
/// Add a byte to this set.
///
/// If the given byte already belongs to this set, then this is a no-op.
#[cfg(feature = "alloc")]
pub fn add(&mut self, byte: u8) {
let bucket = byte / 128;
let bit = byte % 128;
self.bits.0[bucket as usize] |= 1 << bit;
}
/// Add an inclusive range of bytes.
#[cfg(feature = "alloc")]
pub fn add_all(&mut self, start: u8, end: u8) {
for b in start..=end {
self.add(b);
}
}
/// Remove a byte from this set.
///
/// If the given byte is not in this set, then this is a no-op.
#[cfg(feature = "alloc")]
pub fn remove(&mut self, byte: u8) {
let bucket = byte / 128;
let bit = byte % 128;
self.bits.0[bucket as usize] &= !(1 << bit);
}
/// Remove an inclusive range of bytes.
#[cfg(feature = "alloc")]
pub fn remove_all(&mut self, start: u8, end: u8) {
for b in start..=end {
self.remove(b);
}
}
/// Return true if and only if the given byte is in this set.
pub fn contains(&self, byte: u8) -> bool {
let bucket = byte / 128;
let bit = byte % 128;
self.bits.0[bucket as usize] & (1 << bit) > 0
}
/// Return true if and only if the given inclusive range of bytes is in
/// this set.
#[cfg(feature = "alloc")]
pub fn contains_range(&self, start: u8, end: u8) -> bool {
(start..=end).all(|b| self.contains(b))
}
/// Returns an iterator over all bytes in this set.
#[cfg(feature = "alloc")]
pub fn iter(&self) -> ByteSetIter {
ByteSetIter { set: self, b: 0 }
}
/// Returns an iterator over all contiguous ranges of bytes in this set.
#[cfg(feature = "alloc")]
pub fn iter_ranges(&self) -> ByteSetRangeIter {
ByteSetRangeIter { set: self, b: 0 }
}
/// Return the number of bytes in this set.
#[cfg(feature = "alloc")]
pub fn len(&self) -> usize {
(self.bits.0[0].count_ones() + self.bits.0[1].count_ones()) as usize
}
/// Return true if and only if this set is empty.
#[cfg(feature = "alloc")]
pub fn is_empty(&self) -> bool {
self.bits.0 == [0, 0]
}
}
impl core::fmt::Debug for BitSet {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
let mut fmtd = f.debug_set();
for b in (0..256).map(|b| b as u8) {
if (ByteSet { bits: *self }).contains(b) {
fmtd.entry(&b);
}
}
fmtd.finish()
}
}
#[derive(Debug)]
pub struct ByteSetIter<'a> {
set: &'a ByteSet,
b: usize,
}
impl<'a> Iterator for ByteSetIter<'a> {
type Item = u8;
fn next(&mut self) -> Option<u8> {
while self.b <= 255 {
let b = self.b as u8;
self.b += 1;
if self.set.contains(b) {
return Some(b);
}
}
None
}
}
#[derive(Debug)]
pub struct ByteSetRangeIter<'a> {
set: &'a ByteSet,
b: usize,
}
impl<'a> Iterator for ByteSetRangeIter<'a> {
type Item = (u8, u8);
fn next(&mut self) -> Option<(u8, u8)> {
while self.b <= 255 {
let start = self.b as u8;
self.b += 1;
if !self.set.contains(start) {
continue;
}
let mut end = start;
while self.b <= 255 && self.set.contains(self.b as u8) {
end = self.b as u8;
self.b += 1;
}
return Some((start, end));
}
None
}
}
#[cfg(test)]
#[cfg(feature = "alloc")]
mod tests {
use alloc::{vec, vec::Vec};
use super::*;
#[test]
fn byte_classes() {
let mut set = ByteClassSet::empty();
set.set_range(b'a', b'z');
let classes = set.byte_classes();
assert_eq!(classes.get(0), 0);
assert_eq!(classes.get(1), 0);
assert_eq!(classes.get(2), 0);
assert_eq!(classes.get(b'a' - 1), 0);
assert_eq!(classes.get(b'a'), 1);
assert_eq!(classes.get(b'm'), 1);
assert_eq!(classes.get(b'z'), 1);
assert_eq!(classes.get(b'z' + 1), 2);
assert_eq!(classes.get(254), 2);
assert_eq!(classes.get(255), 2);
let mut set = ByteClassSet::empty();
set.set_range(0, 2);
set.set_range(4, 6);
let classes = set.byte_classes();
assert_eq!(classes.get(0), 0);
assert_eq!(classes.get(1), 0);
assert_eq!(classes.get(2), 0);
assert_eq!(classes.get(3), 1);
assert_eq!(classes.get(4), 2);
assert_eq!(classes.get(5), 2);
assert_eq!(classes.get(6), 2);
assert_eq!(classes.get(7), 3);
assert_eq!(classes.get(255), 3);
}
#[test]
fn full_byte_classes() {
let mut set = ByteClassSet::empty();
for i in 0..256u16 {
set.set_range(i as u8, i as u8);
}
assert_eq!(set.byte_classes().alphabet_len(), 257);
}
#[test]
fn elements_typical() {
let mut set = ByteClassSet::empty();
set.set_range(b'b', b'd');
set.set_range(b'g', b'm');
set.set_range(b'z', b'z');
let classes = set.byte_classes();
// class 0: \x00-a
// class 1: b-d
// class 2: e-f
// class 3: g-m
// class 4: n-y
// class 5: z-z
// class 6: \x7B-\xFF
// class 7: EOI
assert_eq!(classes.alphabet_len(), 8);
let elements = classes.elements(Unit::u8(0)).collect::<Vec<_>>();
assert_eq!(elements.len(), 98);
assert_eq!(elements[0], Unit::u8(b'\x00'));
assert_eq!(elements[97], Unit::u8(b'a'));
let elements = classes.elements(Unit::u8(1)).collect::<Vec<_>>();
assert_eq!(
elements,
vec![Unit::u8(b'b'), Unit::u8(b'c'), Unit::u8(b'd')],
);
let elements = classes.elements(Unit::u8(2)).collect::<Vec<_>>();
assert_eq!(elements, vec![Unit::u8(b'e'), Unit::u8(b'f')],);
let elements = classes.elements(Unit::u8(3)).collect::<Vec<_>>();
assert_eq!(
elements,
vec![
Unit::u8(b'g'),
Unit::u8(b'h'),
Unit::u8(b'i'),
Unit::u8(b'j'),
Unit::u8(b'k'),
Unit::u8(b'l'),
Unit::u8(b'm'),
],
);
let elements = classes.elements(Unit::u8(4)).collect::<Vec<_>>();
assert_eq!(elements.len(), 12);
assert_eq!(elements[0], Unit::u8(b'n'));
assert_eq!(elements[11], Unit::u8(b'y'));
let elements = classes.elements(Unit::u8(5)).collect::<Vec<_>>();
assert_eq!(elements, vec![Unit::u8(b'z')]);
let elements = classes.elements(Unit::u8(6)).collect::<Vec<_>>();
assert_eq!(elements.len(), 133);
assert_eq!(elements[0], Unit::u8(b'\x7B'));
assert_eq!(elements[132], Unit::u8(b'\xFF'));
let elements = classes.elements(Unit::eoi(7)).collect::<Vec<_>>();
assert_eq!(elements, vec![Unit::eoi(256)]);
}
#[test]
fn elements_singletons() {
let classes = ByteClasses::singletons();
assert_eq!(classes.alphabet_len(), 257);
let elements = classes.elements(Unit::u8(b'a')).collect::<Vec<_>>();
assert_eq!(elements, vec![Unit::u8(b'a')]);
let elements = classes.elements(Unit::eoi(5)).collect::<Vec<_>>();
assert_eq!(elements, vec![Unit::eoi(256)]);
}
#[test]
fn elements_empty() {
let classes = ByteClasses::empty();
assert_eq!(classes.alphabet_len(), 2);
let elements = classes.elements(Unit::u8(0)).collect::<Vec<_>>();
assert_eq!(elements.len(), 256);
assert_eq!(elements[0], Unit::u8(b'\x00'));
assert_eq!(elements[255], Unit::u8(b'\xFF'));
let elements = classes.elements(Unit::eoi(1)).collect::<Vec<_>>();
assert_eq!(elements, vec![Unit::eoi(256)]);
}
}
|
//! Sx128x Radio Driver
// Copyright 2018 Ryan Kurte
#![no_std]
use core::marker::PhantomData;
use core::convert::TryFrom;
extern crate libc;
#[macro_use]
extern crate log;
#[cfg(any(test, feature = "util"))]
#[macro_use]
extern crate std;
#[cfg(feature = "serde")]
extern crate serde;
#[cfg(feature = "util")]
#[macro_use]
extern crate structopt;
#[macro_use]
extern crate bitflags;
#[cfg(feature = "util")]
extern crate pcap_file;
extern crate embedded_hal as hal;
use hal::blocking::{delay};
use hal::digital::v2::{InputPin, OutputPin};
use hal::spi::{Mode as SpiMode, Phase, Polarity};
use hal::blocking::spi::{Transfer, Write, Transactional};
extern crate embedded_spi;
use embedded_spi::{Error as WrapError, wrapper::Wrapper as SpiWrapper};
extern crate radio;
pub use radio::{State as _, Interrupts as _, Channel as _};
pub mod base;
pub mod device;
pub use device::{State, Config};
use device::*;
pub mod prelude;
/// Sx128x Spi operating mode
pub const SPI_MODE: SpiMode = SpiMode {
polarity: Polarity::IdleLow,
phase: Phase::CaptureOnFirstTransition,
};
/// Sx128x device object
pub struct Sx128x<Base, CommsError, PinError> {
config: Config,
packet_type: PacketType,
hal: Base,
_ce: PhantomData<CommsError>,
_pe: PhantomData<PinError>,
}
pub const FREQ_MIN: u32 = 2_400_000_000;
pub const FREQ_MAX: u32 = 2_500_000_000;
/// Sx128x error type
#[derive(Debug, Clone, PartialEq)]
pub enum Error<CommsError, PinError> {
/// Communications (SPI or UART) error
Comms(CommsError),
/// Pin control error
Pin(PinError),
/// Transaction aborted
Aborted,
/// Timeout by device
Timeout,
BusyTimeout,
/// CRC error on received message
InvalidCrc,
/// TODO
InvalidLength,
/// TODO
InvalidSync,
/// TODO
Abort,
/// TODO
InvalidState(State, State),
/// Radio returned an invalid device firmware version
InvalidDevice(u16),
/// Radio returned an invalid response
InvalidResponse(u8),
/// Invalid configuration option provided
InvalidConfiguration,
/// Frequency out of range
InvalidFrequency,
/// No SPI communication detected
NoComms,
}
impl <CommsError, PinError> From<WrapError<CommsError, PinError>> for Error<CommsError, PinError> {
fn from(e: WrapError<CommsError, PinError>) -> Self {
match e {
WrapError::Spi(e) => Error::Comms(e),
WrapError::Pin(e) => Error::Pin(e),
WrapError::Aborted => Error::Aborted,
}
}
}
pub type Sx128xSpi<Spi, SpiError, Output, Input, PinError, Delay> = Sx128x<SpiWrapper<Spi, SpiError, Output, Input, (), Output, PinError, Delay>, SpiError, PinError>;
impl<Spi, CommsError, Output, Input, PinError, Delay> Sx128x<SpiWrapper<Spi, CommsError, Output, Input, (), Output, PinError, Delay>, CommsError, PinError>
where
Spi: Transfer<u8, Error = CommsError> + Write<u8, Error = CommsError> + Transactional<u8, Error = CommsError>,
Output: OutputPin<Error = PinError>,
Input: InputPin<Error = PinError>,
Delay: delay::DelayMs<u32>,
{
/// Create an Sx128x with the provided `Spi` implementation and pins
pub fn spi(spi: Spi, cs: Output, busy: Input, sdn: Output, delay: Delay, config: &Config) -> Result<Self, Error<CommsError, PinError>> {
// Create SpiWrapper over spi/cs/busy
let hal = SpiWrapper::new(spi, cs, sdn, busy, (), delay);
// Create instance with new hal
Self::new(hal, config)
}
}
impl<Hal, CommsError, PinError> Sx128x<Hal, CommsError, PinError>
where
Hal: base::Hal<CommsError, PinError>,
{
/// Create a new Sx128x instance over a generic Hal implementation
pub fn new(hal: Hal, config: &Config) -> Result<Self, Error<CommsError, PinError>> {
let mut sx128x = Self::build(hal);
debug!("Resetting device");
// Reset IC
sx128x.hal.reset()?;
debug!("Checking firmware version");
// Check communication with the radio
let firmware_version = sx128x.firmware_version()?;
if firmware_version == 0xFFFF || firmware_version == 0x0000 {
return Err(Error::NoComms)
} else if firmware_version != 0xA9B5 {
warn!("Invalid firmware version! expected: 0x{:x} actual: 0x{:x}", 0xA9B5, firmware_version);
}
if firmware_version != 0xA9B5 && !config.skip_version_check {
return Err(Error::InvalidDevice(firmware_version));
}
// TODO: do we need to calibrate things here?
//sx128x.calibrate(CalibrationParams::default())?;
debug!("Configuring device");
// Configure device prior to use
sx128x.configure(config)?;
// Ensure state is idle
sx128x.set_state(State::StandbyRc)?;
Ok(sx128x)
}
pub fn reset(&mut self) -> Result<(), Error<CommsError, PinError>> {
self.hal.reset()?;
Ok(())
}
pub(crate) fn build(hal: Hal) -> Self {
Sx128x {
config: Config::default(),
packet_type: PacketType::None,
hal,
_ce: PhantomData,
_pe: PhantomData,
}
}
pub fn configure(&mut self, config: &Config) -> Result<(), Error<CommsError, PinError>> {
// Switch to standby mode
self.set_state(State::StandbyRc)?;
// Check configs match
match (&config.modem, &config.channel) {
(Modem::LoRa(_), Channel::LoRa(_)) => (),
(Modem::Flrc(_), Channel::Flrc(_)) => (),
(Modem::Gfsk(_), Channel::Gfsk(_)) => (),
_ => return Err(Error::InvalidConfiguration)
}
// Update regulator mode
self.set_regulator_mode(config.regulator_mode)?;
self.config.regulator_mode = config.regulator_mode;
// Update modem and channel configuration
self.set_channel(&config.channel)?;
self.config.channel = config.channel.clone();
self.configure_modem(&config.modem)?;
self.config.modem = config.modem.clone();
// Update power amplifier configuration
self.set_power_ramp(config.pa_config.power, config.pa_config.ramp_time)?;
self.config.pa_config = config.pa_config.clone();
Ok(())
}
pub fn firmware_version(&mut self) -> Result<u16, Error<CommsError, PinError>> {
let mut d = [0u8; 2];
self.hal.read_regs(Registers::LrFirmwareVersionMsb as u16, &mut d)?;
Ok((d[0] as u16) << 8 | (d[1] as u16))
}
pub fn set_frequency(&mut self, f: u32) -> Result<(), Error<CommsError, PinError>> {
let c = self.config.freq_to_steps(f as f32) as u32;
debug!("Setting frequency ({:?} MHz, {} index)", f / 1000 / 1000, c);
let data: [u8; 3] = [
(c >> 16) as u8,
(c >> 8) as u8,
(c >> 0) as u8,
];
self.hal.write_cmd(Commands::SetRfFrequency as u8, &data)
}
pub (crate) fn set_power_ramp(&mut self, power: i8, ramp: RampTime) -> Result<(), Error<CommsError, PinError>> {
if power > 13 || power < -18 {
warn!("TX power out of range (-18 < p < 13)");
}
// Limit to -18 to +13 dBm
let power = core::cmp::max(power, -18);
let power = core::cmp::min(power, 13);
let power_reg = (power + 18) as u8;
debug!("Setting TX power to {} dBm {:?} ramp ({}, {})", power, ramp, power_reg, ramp as u8);
self.config.pa_config.power = power;
self.config.pa_config.ramp_time = ramp;
self.hal.write_cmd(Commands::SetTxParams as u8, &[ power_reg, ramp as u8 ])
}
pub fn set_irq_mask(&mut self, irq: Irq) -> Result<(), Error<CommsError, PinError>> {
debug!("Setting IRQ mask: {:?}", irq);
let raw = irq.bits();
self.hal.write_cmd(Commands::SetDioIrqParams as u8, &[ (raw >> 8) as u8, (raw & 0xff) as u8])
}
pub(crate) fn configure_modem(&mut self, config: &Modem) -> Result<(), Error<CommsError, PinError>> {
use Modem::*;
debug!("Setting modem config: {:?}", config);
// First update packet type (if required)
let packet_type = PacketType::from(config);
if self.packet_type != packet_type {
debug!("Setting packet type: {:?}", packet_type);
self.hal.write_cmd(Commands::SetPacketType as u8, &[ packet_type.clone() as u8 ] )?;
self.packet_type = packet_type;
}
let data = match config {
Gfsk(c) => [c.preamble_length as u8, c.sync_word_length as u8, c.sync_word_match as u8, c.header_type as u8, c.payload_length as u8, c.crc_mode as u8, c.whitening as u8],
LoRa(c) | Ranging(c) => [c.preamble_length as u8, c.header_type as u8, c.payload_length as u8, c.crc_mode as u8, c.invert_iq as u8, 0u8, 0u8],
Flrc(c) => [c.preamble_length as u8, c.sync_word_length as u8, c.sync_word_match as u8, c.header_type as u8, c.payload_length as u8, c.crc_mode as u8, c.whitening as u8],
Ble(c) => [c.connection_state as u8, c.crc_field as u8, c.packet_type as u8, c.whitening as u8, 0u8, 0u8, 0u8],
None => [0u8; 7],
};
self.hal.write_cmd(Commands::SetPacketParams as u8, &data)?;
if let Flrc(c) = config {
if let Some(v) = c.sync_word_value {
self.set_syncword(1, &v)?;
}
}
Ok(())
}
pub(crate) fn get_rx_buffer_status(&mut self) -> Result<(u8, u8), Error<CommsError, PinError>> {
use device::lora::LoRaHeader;
let mut status = [0u8; 2];
self.hal.read_cmd(Commands::GetRxBufferStatus as u8, &mut status)?;
let len = match &self.config.modem {
Modem::LoRa(c) => {
match c.header_type {
LoRaHeader::Implicit => self.hal.read_reg(Registers::LrPayloadLength as u16)?,
LoRaHeader::Explicit => status[0],
}
},
// BLE status[0] does not include 2-byte PDU header
Modem::Ble(_) => status[0] + 2,
_ => status[0]
};
let rx_buff_ptr = status[1];
debug!("RX buffer ptr: {} len: {}", rx_buff_ptr, len);
Ok((rx_buff_ptr, len))
}
pub(crate) fn get_packet_info(&mut self, info: &mut PacketInfo) -> Result<(), Error<CommsError, PinError>> {
let mut data = [0u8; 5];
self.hal.read_cmd(Commands::GetPacketStatus as u8, &mut data)?;
info.packet_status = PacketStatus::from_bits_truncate(data[2]);
info.tx_rx_status = TxRxStatus::from_bits_truncate(data[3]);
info.sync_addr_status = data[4] & 0b0111;
match self.packet_type {
PacketType::Gfsk | PacketType::Flrc | PacketType::Ble => {
info.rssi = -(data[1] as i16) / 2;
let rssi_avg = -(data[0] as i16) / 2;
debug!("Raw RSSI: {}", info.rssi);
debug!("Average RSSI: {}", rssi_avg);
},
PacketType::LoRa | PacketType::Ranging => {
info.rssi = -(data[0] as i16) / 2;
info.snr = Some(match data[1] < 128 {
true => data[1] as i16 / 4,
false => ( data[1] as i16 - 256 ) / 4
});
},
PacketType::None => unimplemented!(),
}
Ok(())
}
pub fn calibrate(&mut self, c: CalibrationParams) -> Result<(), Error<CommsError, PinError>> {
debug!("Calibrate {:?}", c);
self.hal.write_cmd(Commands::Calibrate as u8, &[ c.bits() ])
}
pub(crate) fn set_regulator_mode(&mut self, r: RegulatorMode) -> Result<(), Error<CommsError, PinError>> {
debug!("Set regulator mode {:?}", r);
self.hal.write_cmd(Commands::SetRegulatorMode as u8, &[ r as u8 ])
}
// TODO: this could got into a mode config object maybe?
#[allow(dead_code)]
pub(crate) fn set_auto_tx(&mut self, a: AutoTx) -> Result<(), Error<CommsError, PinError>> {
let data = match a {
AutoTx::Enabled(timeout_us) => {
let compensated = timeout_us - AUTO_RX_TX_OFFSET;
[(compensated >> 8) as u8, (compensated & 0xff) as u8]
},
AutoTx::Disabled => [0u8; 2],
};
self.hal.write_cmd(Commands::SetAutoTx as u8, &data)
}
pub(crate) fn set_buff_base_addr(&mut self, tx: u8, rx: u8) -> Result<(), Error<CommsError, PinError>> {
debug!("Set buff base address (tx: {}, rx: {})", tx, rx);
self.hal.write_cmd(Commands::SetBufferBaseAddress as u8, &[ tx, rx ])
}
/// Set the sychronization mode for a given index (1-3).
/// This is 5-bytes for GFSK mode and 4-bytes for FLRC and BLE modes.
pub fn set_syncword(&mut self, index: u8, value: &[u8]) -> Result<(), Error<CommsError, PinError>> {
debug!("Attempting to set sync word index: {} to: {:?}", index, value);
// Calculate sync word base address and expected length
let (addr, len) = match (&self.packet_type, index) {
(PacketType::Gfsk, 1) => (Registers::LrSyncWordBaseAddress1 as u16, 5),
(PacketType::Gfsk, 2) => (Registers::LrSyncWordBaseAddress2 as u16, 5),
(PacketType::Gfsk, 3) => (Registers::LrSyncWordBaseAddress3 as u16, 5),
(PacketType::Flrc, 1) => (Registers::LrSyncWordBaseAddress1 as u16 + 1, 4),
(PacketType::Flrc, 2) => (Registers::LrSyncWordBaseAddress2 as u16 + 1, 4),
(PacketType::Flrc, 3) => (Registers::LrSyncWordBaseAddress3 as u16 + 1, 4),
(PacketType::Ble, _) => (Registers::LrSyncWordBaseAddress1 as u16 + 1, 4),
_ => {
warn!("Invalid sync word configuration (mode: {:?} index: {} value: {:?}", self.config.modem, index, value);
return Err(Error::InvalidConfiguration)
}
};
// Check length is correct
if value.len() != len {
warn!("Incorrect sync word length for mode: {:?} (actual: {}, expected: {})", self.config.modem, value.len(), len);
return Err(Error::InvalidConfiguration)
}
// Write sync word
self.hal.write_regs(addr, value)?;
// If we're in FLRC mode, patch to force 100% match on syncwords
// because otherwise the 4 bit threshold is too low
if let PacketType::Flrc = &self.packet_type {
let r = self.hal.read_reg(Registers::LrSyncWordTolerance as u16)?;
self.hal.write_reg(Registers::LrSyncWordTolerance as u16, r & 0xF0)?;
}
Ok(())
}
}
impl<Hal, CommsError, PinError> delay::DelayMs<u32> for Sx128x<Hal, CommsError, PinError>
where
Hal: base::Hal<CommsError, PinError>,
{
fn delay_ms(&mut self, t: u32) {
self.hal.delay_ms(t)
}
}
/// `radio::State` implementation for the SX128x
impl<Hal, CommsError, PinError> radio::State for Sx128x<Hal, CommsError, PinError>
where
Hal: base::Hal<CommsError, PinError>,
{
type State = State;
type Error = Error<CommsError, PinError>;
/// Fetch device state
fn get_state(&mut self) -> Result<Self::State, Self::Error> {
let mut d = [0u8; 1];
self.hal.read_cmd(Commands::GetStatus as u8, &mut d)?;
trace!("raw state: 0x{:.2x}", d[0]);
let mode = (d[0] & 0b1110_0000) >> 5;
let m = State::try_from(mode).map_err(|_| Error::InvalidResponse(d[0]) )?;
let status = (d[0] & 0b0001_1100) >> 2;
let s = CommandStatus::try_from(status).map_err(|_| Error::InvalidResponse(d[0]) )?;
debug!("state: {:?} status: {:?}", m, s);
Ok(m)
}
/// Set device state
fn set_state(&mut self, state: Self::State) -> Result<(), Self::Error> {
let command = match state {
State::Tx => Commands::SetTx,
State::Rx => Commands::SetRx,
//State::Cad => Commands::SetCad,
State::Fs => Commands::SetFs,
State::StandbyRc | State::StandbyXosc => Commands::SetStandby,
State::Sleep => Commands::SetSleep,
};
self.hal.write_cmd(command as u8, &[ 0u8 ])
}
}
/// `radio::Channel` implementation for the SX128x
impl<Hal, CommsError, PinError> radio::Channel for Sx128x<Hal, CommsError, PinError>
where
Hal: base::Hal<CommsError, PinError>,
{
/// Channel consists of an operating frequency and packet mode
type Channel = Channel;
type Error = Error<CommsError, PinError>;
/// Set operating channel
fn set_channel(&mut self, ch: &Self::Channel) -> Result<(), Self::Error> {
use Channel::*;
debug!("Setting channel config: {:?}", ch);
// Set frequency
let freq = ch.frequency();
if freq < FREQ_MIN || freq > FREQ_MAX {
return Err(Error::InvalidFrequency)
}
self.set_frequency(freq)?;
// First update packet type (if required)
let packet_type = PacketType::from(ch);
if self.packet_type != packet_type {
self.hal.write_cmd(Commands::SetPacketType as u8, &[ packet_type.clone() as u8 ] )?;
self.packet_type = packet_type;
}
// Then write modulation configuration
let data = match ch {
Gfsk(c) => [c.br_bw as u8, c.mi as u8, c.ms as u8],
LoRa(c) | Ranging(c) => [c.sf as u8, c.bw as u8, c.cr as u8],
Flrc(c) => [c.br_bw as u8, c.cr as u8, c.ms as u8],
Ble(c) => [c.br_bw as u8, c.mi as u8, c.ms as u8],
};
self.hal.write_cmd(Commands::SetModulationParams as u8, &data)
}
}
/// `radio::Power` implementation for the SX128x
impl<Hal, CommsError, PinError> radio::Power for Sx128x<Hal, CommsError, PinError>
where
Hal: base::Hal<CommsError, PinError>,
{
type Error = Error<CommsError, PinError>;
/// Set TX power in dBm
fn set_power(&mut self, power: i8) -> Result<(), Error<CommsError, PinError>> {
let ramp_time = self.config.pa_config.ramp_time;
self.set_power_ramp(power, ramp_time)
}
}
/// `radio::Interrupts` implementation for the SX128x
impl<Hal, CommsError, PinError> radio::Interrupts for Sx128x<Hal, CommsError, PinError>
where
Hal: base::Hal<CommsError, PinError>,
{
type Irq = Irq;
type Error = Error<CommsError, PinError>;
/// Fetch (and optionally clear) current interrupts
fn get_interrupts(&mut self, clear: bool) -> Result<Self::Irq, Self::Error> {
let mut data = [0u8; 2];
self.hal.read_cmd(Commands::GetIrqStatus as u8, &mut data)?;
let irq = Irq::from_bits((data[0] as u16) << 8 | data[1] as u16).unwrap();
if clear && !irq.is_empty() {
self.hal.write_cmd(Commands::ClearIrqStatus as u8, &data)?;
}
if !irq.is_empty() {
debug!("irq: {:?}", irq);
}
Ok(irq)
}
}
/// `radio::Transmit` implementation for the SX128x
impl<Hal, CommsError, PinError> radio::Transmit for Sx128x<Hal, CommsError, PinError>
where
Hal: base::Hal<CommsError, PinError>,
{
type Error = Error<CommsError, PinError>;
/// Start transmitting a packet
fn start_transmit(&mut self, data: &[u8]) -> Result<(), Self::Error> {
debug!("TX start");
// Set packet mode
let mut modem_config = self.config.modem.clone();
modem_config.set_payload_len(data.len() as u8);
self.configure_modem(&modem_config)?;
// Reset buffer addr
self.set_buff_base_addr(0, 0)?;
// Write data to be sent
debug!("TX data: {:?}", data);
self.hal.write_buff(0, data)?;
// Configure ranging if used
if PacketType::Ranging == self.packet_type {
self.hal.write_cmd(Commands::SetRangingRole as u8, &[ RangingRole::Initiator as u8 ])?;
}
// Setup timout
let config = [
self.config.rf_timeout.step() as u8,
(( self.config.rf_timeout.count() >> 8 ) & 0x00FF ) as u8,
(self.config.rf_timeout.count() & 0x00FF ) as u8,
];
// Enable IRQs
self.set_irq_mask(Irq::TX_DONE | Irq::CRC_ERROR | Irq::RX_TX_TIMEOUT)?;
// Enter transmit mode
self.hal.write_cmd(Commands::SetTx as u8, &config)?;
debug!("TX start issued");
let state = self.get_state()?;
debug!("State: {:?}", state);
Ok(())
}
/// Check for transmit completion
fn check_transmit(&mut self) -> Result<bool, Self::Error> {
let irq = self.get_interrupts(true)?;
let state = self.get_state()?;
trace!("TX poll (irq: {:?}, state: {:?})", irq, state);
if irq.contains(Irq::TX_DONE) {
debug!("TX complete");
Ok(true)
} else if irq.contains(Irq::RX_TX_TIMEOUT) {
debug!("TX timeout");
Err(Error::Timeout)
} else {
Ok(false)
}
}
}
/// `radio::Receive` implementation for the SX128x
impl<Hal, CommsError, PinError> radio::Receive for Sx128x<Hal, CommsError, PinError>
where
Hal: base::Hal<CommsError, PinError>,
{
/// Receive info structure
type Info = PacketInfo;
/// RF Error object
type Error = Error<CommsError, PinError>;
/// Start radio in receive mode
fn start_receive(&mut self) -> Result<(), Self::Error> {
debug!("RX start");
// Reset buffer addr
self.set_buff_base_addr(0, 0)?;
// Set packet mode
// TODO: surely this should not bre required _every_ receive?
let modem_config = self.config.modem.clone();
self.configure_modem(&modem_config)?;
// Configure ranging if used
if PacketType::Ranging == self.packet_type {
self.hal.write_cmd(Commands::SetRangingRole as u8, &[ RangingRole::Responder as u8 ])?;
}
// Setup timout
let config = [
self.config.rf_timeout.step() as u8,
(( self.config.rf_timeout.count() >> 8 ) & 0x00FF ) as u8,
(self.config.rf_timeout.count() & 0x00FF ) as u8,
];
// Enable IRQs
self.set_irq_mask(
Irq::RX_DONE | Irq::CRC_ERROR | Irq::RX_TX_TIMEOUT
| Irq::SYNCWORD_VALID
| Irq::SYNCWORD_ERROR
| Irq::HEADER_VALID
| Irq::HEADER_ERROR
| Irq::PREAMBLE_DETECTED
)?;
// Enter transmit mode
self.hal.write_cmd(Commands::SetRx as u8, &config)?;
let state = self.get_state()?;
debug!("RX started (state: {:?})", state);
Ok(())
}
/// Check for a received packet
fn check_receive(&mut self, restart: bool) -> Result<bool, Self::Error> {
let irq = self.get_interrupts(true)?;
let mut res = Ok(false);
// Process flags
if irq.contains(Irq::CRC_ERROR) {
debug!("RX CRC error");
res = Err(Error::InvalidCrc);
} else if irq.contains(Irq::RX_TX_TIMEOUT) {
debug!("RX timeout");
res = Err(Error::Timeout);
} else if irq.contains(Irq::RX_DONE) {
debug!("RX complete");
res = Ok(true);
}
// Auto-restart on failure if enabled
match (restart, res) {
(true, Err(_)) => {
debug!("RX restarting");
self.start_receive()?;
Ok(false)
},
(_, r) => r
}
}
/// Fetch a received packet
fn get_received<'a>(&mut self, info: &mut Self::Info, data: &'a mut [u8]) -> Result<usize, Self::Error> {
// Fetch RX buffer information
let (ptr, len) = self.get_rx_buffer_status()?;
debug!("RX get received, ptr: {} len: {}", ptr, len);
// Read from the buffer at the provided pointer
self.hal.read_buff(ptr, &mut data[..len as usize])?;
// Fetch related information
self.get_packet_info(info)?;
debug!("RX data: {:?} info: {:?}", &data[..len as usize], info);
// Return read length
Ok(len as usize)
}
}
/// `radio::Rssi` implementation for the SX128x
impl<Hal, CommsError, PinError> radio::Rssi for Sx128x<Hal, CommsError, PinError>
where
Hal: base::Hal<CommsError, PinError>,
{
type Error = Error<CommsError, PinError>;
/// Poll for the current channel RSSI
/// This should only be called when in receive mode
fn poll_rssi(&mut self) -> Result<i16, Error<CommsError, PinError>> {
let mut raw = [0u8; 1];
self.hal.read_cmd(Commands::GetRssiInst as u8, &mut raw)?;
Ok(-(raw[0] as i16) / 2)
}
}
#[cfg(test)]
mod tests {
use crate::{Sx128x};
use crate::base::Hal;
use crate::device::RampTime;
extern crate embedded_spi;
use self::embedded_spi::mock::{Mock, Spi};
use radio::{State as _};
pub mod vectors;
#[test]
fn test_api_reset() {
let mut m = Mock::new();
let (spi, sdn, _busy, delay) = (m.spi(), m.pin(), m.pin(), m.delay());
let mut radio = Sx128x::<Spi, _, _>::build(spi.clone());
m.expect(vectors::reset(&spi, &sdn, &delay));
radio.hal.reset().unwrap();
m.finalise();
}
#[test]
fn test_api_status() {
let mut m = Mock::new();
let (spi, sdn, _busy, delay) = (m.spi(), m.pin(), m.pin(), m.delay());
let mut radio = Sx128x::<Spi, _, _>::build(spi.clone());
m.expect(vectors::status(&spi, &sdn, &delay));
radio.get_state().unwrap();
m.finalise();
}
#[test]
fn test_api_firmware_version() {
let mut m = Mock::new();
let (spi, sdn, _busy, delay) = (m.spi(), m.pin(), m.pin(), m.delay());
let mut radio = Sx128x::<Spi, _, _>::build(spi.clone());
m.expect(vectors::firmware_version(&spi, &sdn, &delay, 16));
let version = radio.firmware_version().unwrap();
m.finalise();
assert_eq!(version, 16);
}
#[test]
fn test_api_power_ramp() {
let mut m = Mock::new();
let (spi, sdn, _busy, delay) = (m.spi(), m.pin(), m.pin(), m.delay());
let mut radio = Sx128x::<Spi, _, _>::build(spi.clone());
m.expect(vectors::set_power_ramp(&spi, &sdn, &delay, 0x1f, 0xe0));
radio.set_power_ramp(13, RampTime::Ramp20Us).unwrap();
m.finalise();
}
}
|
// 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 {
serde_derive::{Deserialize, Serialize},
std::slice::Iter,
};
/// The type of operations that can be performed using odu. Not all targets may
/// implement all the operations.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OperationType {
// Persist a buffer onto target that can be read at a later point in time.
Write,
// "Open" target for other IO operations. This is not implement at the
// moment but is used to unit test some of the generate functionality.
Open,
// Meta operations
// Finish all outstanding operations and forward the command to next stage
// of the pipeline before exiting gracefully.
Exit,
// Abort all outstanding operations and exit as soon as possible.
Abort,
// Read,
// LSeek,
// Truncate,
// Close,
// FSync,
//
// /// DirOps
// Create,
// Unlink,
// CreateDir,
// DeleteDir,
// ReadDir,
// OpenDir,
// Link, /// This is for hard links only. Symlinks are small files.
//
// /// FsOps
// Mount,
// Unmount,
//
}
/// These functions makes better indexing and walking stages a bit better.
impl OperationType {
pub const fn operations_count() -> usize {
4 // number of entries in OperationType.
}
pub fn operation_number(self) -> usize {
self as usize
}
pub fn iterator() -> Iter<'static, OperationType> {
static OPERATIONS: [OperationType; OperationType::operations_count()] =
[OperationType::Write, OperationType::Open, OperationType::Exit, OperationType::Abort];
OPERATIONS.into_iter()
}
}
/// IoPackets go through different stages in pipeline. These stages help track
// the IO and also are indicative of how loaded different parts of the app is.
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum PipelineStages {
/// IoPacket is in generator stage
Generate = 0,
/// IoPacket is in issuer stage
Issue = 1,
/// IoPacket is in verifier stage
Verify = 2,
}
/// These functions makes better indexing and walking stages a bit better.
impl PipelineStages {
pub const fn stage_count() -> usize {
3 // number of entries in PipelineStages.
}
pub fn stage_number(self) -> usize {
self as usize
}
pub fn iterator() -> Iter<'static, PipelineStages> {
static STAGES: [PipelineStages; PipelineStages::stage_count()] =
[PipelineStages::Generate, PipelineStages::Issue, PipelineStages::Verify];
STAGES.into_iter()
}
}
#[cfg(test)]
mod tests {
use crate::operations::OperationType;
#[test]
fn operation_count_test() {
assert_eq!(OperationType::operations_count(), 4);
}
#[test]
fn operation_iterator_count_test() {
assert_eq!(OperationType::operations_count(), OperationType::iterator().count());
}
#[test]
fn operation_iterator_uniqueness() {
for (i, operation) in OperationType::iterator().enumerate() {
assert!(i == operation.operation_number());
}
}
}
|
//
// gash.rs
//
// Starting code for PS2
// Running on Rust 0.9
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.4
//
/*
Vikram Bhasin vb8nd and Justin Ingram jci5kb
*/
extern mod extra;
use std::{io, run, os};
use std::io::buffered::BufferedReader;
use std::io::stdin;
use std::os::getcwd;
use extra::getopts;
use std::run::Process;
use std::run::ProcessOutput;
use std::run::ProcessOptions;
use std::option::{Option, None, Some};
use std::io::buffered::BufferedWriter;
use std::io::File;
use std::comm::Chan;
use std::io::signal::Listener;
use std::io::signal::{Interrupt};
use std::libc;
use std::io::stdio;
use std::os::Pipe;
struct Shell {
cmd_prompt: ~str,
hist: ~[~str],
}
impl Shell {
fn new(prompt_str: &str) -> Shell {
Shell {
cmd_prompt: prompt_str.to_owned(),
hist: ~[],
}
}
fn listen(&mut self, list: Listener) {
spawn(proc() {
loop {
match list.port.recv() {
Interrupt => { }
_ => { println("THERE WAS DERP"); }
}
}
});
}
fn run(&mut self) {
let mut stdin = BufferedReader::new(stdin());
let mut x = Listener::new();
let reg = x.register(Interrupt);
if reg {
self.listen(x);
} else {
println("Failed to register listener");
}
loop {
print(self.cmd_prompt);
io::stdio::flush();
let line = stdin.read_line().unwrap();
let cmd_line = line.trim().to_owned();
let program = cmd_line.splitn(' ', 1).nth(0).expect("no program");
self.hist.push(line);
match program {
"" => { continue; }
"exit" => { return; }
"cd" => { self.changeDir(cmd_line); }
"history" =>{ self.history(); }
"gcowsay" => { self.cowsay(cmd_line); }
_ => { self.split_semi(cmd_line); }
}
}
}
fn split_semi(&mut self, cmd_line: &str) {
let mut commands: ~[~str] = cmd_line.split(';').filter_map(|x| if x != "" { Some(x.trim().to_owned()) } else { None }).to_owned_vec();
for stringy in commands.clone().move_iter() {
self.pipe_syntax(stringy);
}
}
fn pipe_syntax(&mut self, cmd_line: &str) {
let mut commands: ~[~str] = cmd_line.split('|').filter_map(|x| if x != "" { Some(x.trim().to_owned()) } else { None }).to_owned_vec();
let mut count = 0;
let mut infd: libc::c_int = 0;
let mut outfd: libc::c_int = 0;
for stringy in commands.clone().move_iter() {
// println(stringy);
let mut argv: ~[~str] = stringy.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
let program: ~str = argv.remove(0);
if count == 0 && commands.len() == 1 {
self.run_cmdline(stringy);
} else if count == 0 {
if stringy.contains("<"){
let mut filename = ~"";
let mut x = 0;
for string1 in argv.clone().move_iter() {
if string1.eq(&~"<") {
break;
}
x += 1;
}
match argv.get_opt(x+1) {
Some(text) => { filename = text.to_owned(); }
None => {}
}
argv.remove(x+1);
argv.remove(x);
let pi = std::os::pipe();
infd = pi.input;
outfd = pi.out;
if commands.len() > 1 {
self.run_cmd_pipe_in(program, argv, pi.out, filename, false);
} else {
self.run_cmd_in(program, argv, filename, false);
}
}else{
let pi = std::os::pipe();
infd = pi.input;
outfd = pi.out;
if commands.len() > 1 {
self.run_cmd_pipe(program, argv, 0, pi.out, false);
}else{
self.run_cmd(program, argv, false);
}
}
} else if count == (commands.len() - 1) {
if stringy.contains(">") {
let mut filename = ~"";
let mut x = 0;
for string1 in argv.clone().move_iter() {
if string1.eq(&~"<") {
break;
}
x += 1;
}
match argv.get_opt(x+1) {
Some(text) => { filename = text.to_owned(); }
None => {}
}
argv.remove(x+1);
argv.remove(x);
self.run_cmd_pipe_out(program, argv, outfd, filename, false);
} else {
self.run_cmd_pipe(program, argv, outfd, 0, false);
}
} else {
let pi = std::os::pipe();
infd = pi.input;
self.run_cmd_pipe(program, argv, outfd, pi.input, false);
outfd = pi.out;
}
}
count += 1;
}
}
fn run_cmdline(&mut self, cmd_line: &str) {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 0 {
let program: ~str = argv.remove(0);
//Let's process the argv
let endopt = argv.pop_opt();
let end = match endopt {
Some(stringy) => { stringy }
None => { ~"" }
};
if end.eq(&~"&") {
// println("Start in a new process" + end);
if argv.contains(&~">") && argv.contains(&~"<") {
// println("In and out");
let mut x = 0;
let mut filein = ~"";
let mut fileout = ~"";
for stringy in argv.clone().move_iter() {
if stringy.eq(&~"<") {
break;
}
x += 1;
}
match argv.get_opt(x+1) {
Some(text) => { filein = text.to_owned(); }
None => {}
}
argv.remove(x+1);
argv.remove(x);
x = 0;
for stringy in argv.clone().move_iter() {
if stringy.eq(&~">") {
break;
}
x += 1;
}
match argv.get_opt(x+1) {
Some(text) => { fileout = text.to_owned(); }
None => {}
}
argv.remove(x+1);
argv.remove(x);
self.run_cmd_in_out(program, argv, filein, fileout, true);
} else if argv.contains(&~"<") {
if argv.contains(&~"<") {
let mut filename = ~"";
let mut x = 0;
for stringy in argv.clone().move_iter() {
if stringy.eq(&~"<") {
break;
}
x += 1;
}
match argv.get_opt(x+1) {
Some(text) => { filename = text.to_owned(); }
None => {}
}
argv.remove(x+1);
argv.remove(x);
self.run_cmd_in(program, argv, filename, true);
}else {
self.run_cmd(program, argv, true);
}
} else if argv.contains(&~">") {
// println("Contains >");
if argv.contains(&~">") {
//println("Contains >");
let mut filename = ~"";
let mut x = 0;
for stringy in argv.clone().move_iter() {
if stringy.eq(&~">") {
break;
}
x += 1;
}
match argv.get_opt(x+1) {
Some(text) => { filename = text.to_owned(); }
None => {}
}
argv.remove(x+1);
argv.remove(x);
self.run_cmd_out(program, argv, filename, true);
} else {
self.run_cmd(program, argv, true);
}
}
self.run_cmd(program, argv, true);
} else {
//println("No new process");
if !end.eq(&~"") {
argv.push(end.to_owned());
}
if argv.contains(&~">") && argv.contains(&~"<") {
// println("In and out");
let mut x = 0;
let mut filein = ~"";
let mut fileout = ~"";
for stringy in argv.clone().move_iter() {
if stringy.eq(&~"<") {
break;
}
x += 1;
}
match argv.get_opt(x+1) {
Some(text) => { filein = text.to_owned(); }
None => {}
}
argv.remove(x+1);
argv.remove(x);
x = 0;
for stringy in argv.clone().move_iter() {
if stringy.eq(&~">") {
break;
}
x += 1;
}
match argv.get_opt(x+1) {
Some(text) => { fileout = text.to_owned(); }
None => {}
}
argv.remove(x+1);
argv.remove(x);
self.run_cmd_in_out(program, argv, filein, fileout, false);
}else if argv.contains(&~"<") {
let mut filename = ~"";
let mut x = 0;
for stringy in argv.clone().move_iter() {
if stringy.eq(&~"<") {
break;
}
x += 1;
}
match argv.get_opt(x+1) {
Some(text) => { filename = text.to_owned(); }
None => {}
}
argv.remove(x+1);
argv.remove(x);
self.run_cmd_in(program, argv, filename, false);
} else if argv.contains(&~">") {
//println("Contains >");
let mut filename = ~"";
let mut x = 0;
for stringy in argv.clone().move_iter() {
if stringy.eq(&~">") {
break;
}
x += 1;
}
match argv.get_opt(x+1) {
Some(text) => { filename = text.to_owned(); }
None => {}
}
argv.remove(x+1);
argv.remove(x);
self.run_cmd_out(program, argv, filename, false);
} else {
self.run_cmd(program, argv, false);
}
}
}
}
fn run_cmd_pipe(&mut self, program: &str, argv: &[~str], fdin: libc::c_int, fdout: libc::c_int, bg: bool) {
if self.cmd_exists(program) {
if !bg {
// run::process_status(program, argv);
let mut whichprocop = ProcessOptions::new();
unsafe {
if (fdin != 0) {
whichprocop.in_fd = Some(fdin);
}
if (fdout != 0) {
whichprocop.out_fd = Some(fdout);
}
}
match(Process::new(program, argv, whichprocop)) {
Some(mut process) => {
process.finish();
//println("process finished");
}
None => { println("ERROR"); }
}
} else {
//let f = self.makefunky(program, argv);
//let (recvp, recvc): (Port<~str>, Chan<~str>) = Chan::new();
//spawn(expr(f(program, argv)));
let x = program.clone().to_owned();
let y = argv.clone().to_owned();
spawn(proc() {
let mut whichprocop = ProcessOptions::new();
unsafe {
whichprocop.in_fd = Some(fdin);
whichprocop.out_fd = Some(fdout);
}
match(Process::new(x, y, whichprocop)) {
Some(mut process) => {
process.finish();
}
None => { println("ERROR"); }
}
});
}
} else {
println!("{:s}: command not found", program);
}
}
fn run_cmd_pipe_in(&mut self, program: &str, argv: &[~str], fdout: libc::c_int, filein: &str, bg: bool){
if self.cmd_exists(program) {
if !bg {
// run::process_status(program, argv);
let mut whichprocop = ProcessOptions::new();
unsafe {
whichprocop.in_fd = Some(libc::fileno(libc::fopen(filein.to_c_str().unwrap(), "r".to_c_str().unwrap())));
whichprocop.out_fd = Some(fdout);
}
match(Process::new(program, argv, whichprocop)) {
Some(mut process) => {
process.finish();
//println("process finished");
}
None => { println("ERROR"); }
}
} else {
//let f = self.makefunky(program, argv);
//let (recvp, recvc): (Port<~str>, Chan<~str>) = Chan::new();
//spawn(expr(f(program, argv)));
let x = program.clone().to_owned();
let y = argv.clone().to_owned();
let f = filein.clone().to_owned();
spawn(proc() {
let mut whichprocop = ProcessOptions::new();
unsafe {
whichprocop.in_fd = Some(libc::fileno(libc::fopen(f.to_c_str().unwrap(), "r".to_c_str().unwrap())));
whichprocop.out_fd = Some(fdout);
}
match(Process::new(x, y, whichprocop)) {
Some(mut process) => {
process.finish();
}
None => { println("ERROR"); }
}
});
}
} else {
println!("{:s}: command not found", program);
}
}
fn run_cmd_pipe_out(&mut self, program: &str, argv: &[~str], fdin: libc::c_int, fileout: &str, bg: bool) {
if self.cmd_exists(program) {
if !bg {
// run::process_status(program, argv);
let mut whichprocop = ProcessOptions::new();
unsafe {
whichprocop.in_fd = Some(fdin);
whichprocop.out_fd = Some(libc::fileno(libc::fopen(fileout.to_c_str().unwrap(), "w".to_c_str().unwrap())));
}
match(Process::new(program, argv, whichprocop)) {
Some(mut process) => {
process.finish();
//println("process finished");
}
None => { println("ERROR"); }
}
} else {
//let f = self.makefunky(program, argv);
//let (recvp, recvc): (Port<~str>, Chan<~str>) = Chan::new();
//spawn(expr(f(program, argv)));
let x = program.clone().to_owned();
let y = argv.clone().to_owned();
let f = fileout.clone().to_owned();
spawn(proc() {
let mut whichprocop = ProcessOptions::new();
unsafe {
whichprocop.in_fd = Some(fdin);
whichprocop.out_fd = Some(libc::fileno(libc::fopen(f.to_c_str().unwrap(), "w".to_c_str().unwrap())));
}
match(Process::new(x, y, whichprocop)) {
Some(mut process) => {
process.finish();
}
None => { println("ERROR"); }
}
});
}
} else {
println!("{:s}: command not found", program);
}
}
fn run_cmd_in_out(&mut self, program: &str, argv: &[~str], filein: &str, fileout: &str, bg: bool) {
if self.cmd_exists(program) {
// Old stuff
//println("Run command hit");
//println(program);
if !bg {
// run::process_status(program, argv);
let mut whichprocop = ProcessOptions::new();
unsafe {
whichprocop.in_fd = Some(libc::fileno(libc::fopen(filein.to_c_str().unwrap(), "r".to_c_str().unwrap())));
whichprocop.out_fd = Some(libc::fileno(libc::fopen(fileout.to_c_str().unwrap(), "w".to_c_str().unwrap())));
}
match(Process::new(program, argv, whichprocop)) {
Some(mut process) => {
process.finish();
std::io::stdio::flush();
//println("process finished");
}
None => { println("ERROR"); }
}
} else {
//let f = self.makefunky(program, argv);
//let (recvp, recvc): (Port<~str>, Chan<~str>) = Chan::new();
//spawn(expr(f(program, argv)));
let x = program.clone().to_owned();
let y = argv.clone().to_owned();
let f = filein.clone().to_owned();
let g = fileout.clone().to_owned();
spawn(proc() {
let mut whichprocop = ProcessOptions::new();
unsafe {
whichprocop.in_fd = Some(libc::fileno(libc::fopen(f.to_c_str().unwrap(), "r".to_c_str().unwrap())));
whichprocop.out_fd = Some(libc::fileno(libc::fopen(g.to_c_str().unwrap(), "w".to_c_str().unwrap())));
}
match(Process::new(x, y, whichprocop)) {
Some(mut process) => {
process.finish();
std::io::stdio::flush();
}
None => { println("ERROR"); }
}
});
}
} else {
println!("{:s}: command not found", program);
}
}
fn run_cmd_in(&mut self, program: &str, argv: &[~str], filename: &str, bg: bool) {
if self.cmd_exists(program) {
// Old stuff
//println("Run command hit");
//println(program);
if !bg {
// run::process_status(program, argv);
let mut whichprocop = ProcessOptions::new();
unsafe {
whichprocop.in_fd = Some(libc::fileno(libc::fopen(filename.to_c_str().unwrap(), "r".to_c_str().unwrap())));
}
whichprocop.out_fd = Some(1);
match(Process::new(program, argv, whichprocop)) {
Some(mut process) => {
process.finish();
std::io::stdio::flush();
//println("process finished");
}
None => { println("ERROR"); }
}
} else {
//let f = self.makefunky(program, argv);
//let (recvp, recvc): (Port<~str>, Chan<~str>) = Chan::new();
//spawn(expr(f(program, argv)));
let x = program.clone().to_owned();
let y = argv.clone().to_owned();
let f = filename.clone().to_owned();
spawn(proc() {
let mut whichprocop = ProcessOptions::new();
unsafe {
whichprocop.in_fd = Some(libc::fileno(libc::fopen(f.to_c_str().unwrap(), "r".to_c_str().unwrap())));
}
match(Process::new(x, y, whichprocop)) {
Some(mut process) => {
process.finish();
std::io::stdio::flush();
}
None => { println("ERROR"); }
}
});
}
} else {
println!("{:s}: command not found", program);
}
}
fn run_cmd_out(&mut self, program: &str, argv: &[~str], filename: &str, bg: bool) {
if self.cmd_exists(program) {
// Old stuff
//println("Run command hit");
//println(program);
if !bg {
// run::process_status(program, argv);
let mut whichprocop = ProcessOptions::new();
unsafe {
whichprocop.out_fd = Some(libc::fileno(libc::fopen(filename.to_c_str().unwrap(), "w".to_c_str().unwrap())));
}
match(Process::new(program, argv, whichprocop)) {
Some(mut process) => {
process.finish();
}
None => { println("ERROR"); }
}
} else {
//let f = self.makefunky(program, argv);
//let (recvp, recvc): (Port<~str>, Chan<~str>) = Chan::new();
//spawn(expr(f(program, argv)));
let x = program.clone().to_owned();
let y = argv.clone().to_owned();
let f = filename.clone().to_owned();
spawn(proc() {
let mut whichprocop = ProcessOptions::new();
unsafe {
whichprocop.out_fd = Some(libc::fileno(libc::fopen(f.to_c_str().unwrap(), "w".to_c_str().unwrap())));
}
match(Process::new(x, y, whichprocop)) {
Some(mut process) => {
process.finish();
}
None => { println("ERROR"); }
}
});
}
} else {
println!("{:s}: command not found", program);
}
}
fn run_cmd(&mut self, program: &str, argv: &[~str], bg: bool) {
if self.cmd_exists(program) {
// Old stuff
//println("Run command hit");
//println(program);
if !bg {
run::process_status(program, argv);
} else {
//let f = self.makefunky(program, argv);
//let (recvp, recvc): (Port<~str>, Chan<~str>) = Chan::new();
//spawn(expr(f(program, argv)));
let x = program.clone().to_owned();
let y = argv.clone().to_owned();
spawn(proc() {
let mut whichprocop = ProcessOptions::new();
match(Process::new(x, y, whichprocop)) {
Some(mut process) => {
process.finish();
}
None => { println("ERROR"); }
}
});
}
} else {
println!("{:s}: command not found", program);
}
}
/*
fn makefunky(&mut self, program: &str, argv: &[~str]) -> (proc(&str, &[~str])) {
proc(program: &str, argv: &[~str]) {
// whichprocop.dir = self.cwdopt.as_ref();
let mut whichproc = Process::new(program, argv, whichprocop);
let mut process = whichproc.unwrap();
let mut procout = process.finish_with_output();
println(std::str::from_utf8(procout.output));
}
}
*/
fn cmd_exists(&mut self, cmd_path: &str) -> bool {
let ret = run::process_output("which", [cmd_path.to_owned()]);
return ret.expect("exit code error.").status.success();
}
//Justin's function for cd
fn changeDir(&mut self, cmd_line: &str) {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
if argv.len() > 1 {
let pstring: ~str = argv.remove(1);
//println!("You want to change cwd to {:s}", pstring);
let npath = Path::new(pstring);
let mut cpath = getcwd();
cpath.push(npath);
if cpath.exists() {
let mut cpathforopt = cpath.clone();
std::os::change_dir(&cpath);
// self.cwd = cpath;
} else {
println("Path does not exist!");
}
}
let x = getcwd();
match x.as_str() {
Some(path_str) => {println!("{:s}", path_str); }
None => {println("Path not representable as string!"); }
}
}
fn history(&mut self) {
let mut n :int = 1;
for stringy in self.hist.iter() {
let x = stringy.clone();
print("[" + n.to_str() + "]" + ~"\t" + x);
n += 1;
}
}
fn cowsay(&mut self, cmd_line: &str) {
let mut argv: ~[~str] =
cmd_line.split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();
let mut stringer = ~"";
if argv.len() > 1 {
argv.remove(0);
}
for stringy in argv.iter() {
stringer = stringer + ~" " + stringy.to_owned();
}
println(" _______");
println("< " + stringer + " >");
println(" -------");
println(" \\ ^__^");
println(" \\ (oo)\\_______");
println(" (__)\\ )\\/\\");
println(" ||----w |");
println(" || ||");
}
}
fn get_cmdline_from_args() -> Option<~str> {
/* Begin processing program arguments and initiate the parameters. */
let args = os::args();
let opts = ~[
getopts::optopt("c")
];
let matches = match getopts::getopts(args.tail(), opts) {
Ok(m) => { m }
Err(f) => { fail!(f.to_err_msg()) }
};
if matches.opt_present("c") {
let cmd_str = match matches.opt_str("c") {
Some(cmd_str) => {cmd_str.to_owned()},
None => {~""}
};
return Some(cmd_str);
} else {
return None;
}
}
fn main() {
let opt_cmd_line = get_cmdline_from_args();
match opt_cmd_line {
Some(cmd_line) => Shell::new("").run_cmdline(cmd_line),
None => Shell::new("gash > ").run()
}
}
|
#![feature(decl_macro, proc_macro_hygiene, custom_attribute)]
#![allow(proc_macro_derive_resolution_fallback)]
extern crate bcrypt;
extern crate dotenv;
extern crate rocket_contrib;
extern crate serde;
extern crate serde_json;
extern crate validator;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate validator_derive;
#[macro_use]
extern crate serde_derive;
mod accounts;
mod db;
mod deals;
mod housekeeping;
mod result;
mod schema;
mod web;
fn main() {
let _ = housekeeping::run();
web::launch();
}
|
use syntex_syntax::ast::*;
use syntex_syntax::visit::*;
use syntex_pos::Span;
use syntex_syntax::print::pprust;
use gtk::prelude::*;
use gtk::{ListStore, TreeStore, TreeIter};
use ast_model_extensions::{AstModelExt, AstStoreExt, AstPropertiesStoreExt};
pub(crate) struct TreeVisitor {
pub tree: TreeStore,
pub iters: Vec<TreeIter>
}
macro_rules! visit {
($self:ident, $props:ident, ($type:expr, $kind:expr) => $walk:block) => {
let iter = $self.tree.insert_node($self.iters.last(), $type, $kind, None);
let $props = $self.tree.get_properties_list(&iter);
$self.iters.push(iter);
$walk;
$self.iters.pop();
};
($self:ident, $props:ident, ($type:expr, $kind:expr, $span:expr) => $walk:block) => {
let iter = $self.tree.insert_node($self.iters.last(), $type, $kind, Some($span));
let $props = $self.tree.get_properties_list(&iter);
$self.iters.push(iter);
$walk;
$self.iters.pop();
};
}
impl TreeVisitor {
pub fn new() -> TreeVisitor {
TreeVisitor{
tree: TreeStore::new_ast_store(),
iters: vec![]
}
}
fn _visit_path(&mut self, path: &Path) {
visit!(self, path_props, ("Path", "", path.span) => {
walk_path(self, path);
});
}
}
impl<'ast> Visitor<'ast> for TreeVisitor {
fn visit_name(&mut self, span: Span, name: Name) {
let iter = self.tree.insert_node(self.iters.last(), "Name", "", Some(span));
let props = self.tree.get_properties_list(&iter);
props.insert_property("Name", &name.as_str());
}
fn visit_ident(&mut self, span: Span, ident: Ident) {
visit!(self, props, ("Ident", "", span) => {
props.insert_property("Name", &pprust::ident_to_string(ident));
walk_ident(self, span, ident);
});
}
fn visit_mod(&mut self, m: &'ast Mod, _span: Span, _attrs: &[Attribute], _n: NodeId) {
visit!(self, props, ("Mod", "", m.inner)/*span*/ => {
walk_mod(self, m);
});
}
// fn visit_global_asm(&mut self, ga: &'ast GlobalAsm) { walk_global_asm(self, ga) }
fn visit_foreign_item(&mut self, i: &'ast ForeignItem) {
visit!(self, props, ("ForeignItem", "") => {
walk_foreign_item(self, i);
});
}
fn visit_item(&mut self, i: &'ast Item) {
let kind = match i.node {
ItemKind::ExternCrate(..) => "ExternCrate",
ItemKind::Use(..) => "Use",
ItemKind::Static(..) => "Static",
ItemKind::Const(..) => "Const",
ItemKind::Fn(..) => "Fn",
ItemKind::Mod(..) => "Mod",
ItemKind::ForeignMod(..) => "ForeignMod",
ItemKind::GlobalAsm(..) => "GlobalAsm",
ItemKind::Ty(..) => "Ty",
ItemKind::Enum(..) => "Enum",
ItemKind::Struct(..) => "Struct",
ItemKind::Union(..) => "Union",
ItemKind::Trait(..) => "Trait",
ItemKind::DefaultImpl(..) => "DefaultImpl",
ItemKind::Impl(..) => "Impl",
ItemKind::Mac(..) => "Mac",
ItemKind::MacroDef(..) => "MacroDef",
};
visit!(self, props, ("Item", kind) => {
walk_item(self, i);
});
}
fn visit_local(&mut self, l: &'ast Local) {
visit!(self, props, ("Local", "", l.span) => {
walk_local(self, l);
});
}
fn visit_block(&mut self, b: &'ast Block) {
visit!(self, props, ("Block", "", b.span) => {
walk_block(self, b);
});
}
fn visit_stmt(&mut self, s: &'ast Stmt) {
let kind = match s.node {
StmtKind::Local(..) => "Local",
StmtKind::Item(..) => "Item",
StmtKind::Expr(..) => "Expr",
StmtKind::Semi(..) => "Semi",
StmtKind::Mac(..) => "Mac",
};
visit!(self, props, ("Stmt", kind, s.span) => {
walk_stmt(self, s);
});
}
fn visit_arm(&mut self, a: &'ast Arm) {
visit!(self, props, ("Arm", "") => {
walk_arm(self, a);
});
}
fn visit_pat(&mut self, p: &'ast Pat) {
let kind = match p.node {
PatKind::Wild => "Wild",
PatKind::Ident(..) => "Ident",
PatKind::Struct(..) => "Struct",
PatKind::TupleStruct(..) => "TupleStruct",
PatKind::Path(..) => "Path",
PatKind::Tuple(..) => "Tuple",
PatKind::Box(..) => "Box",
PatKind::Ref(..) => "Ref",
PatKind::Lit(..) => "Lit",
PatKind::Range(..) => "Range",
PatKind::Slice(..) => "Slice",
PatKind::Mac(..) => "Mac",
};
visit!(self, props, ("Pat", kind, p.span) => {
walk_pat(self, p);
});
}
fn visit_expr(&mut self, ex: &'ast Expr) {
let kind = match ex.node {
ExprKind::Box(..) => "Box",
ExprKind::InPlace(..) => "InPlace",
ExprKind::Array(..) => "Array",
ExprKind::Call(..) => "Call",
ExprKind::MethodCall(..) => "MethodCall",
ExprKind::Tup(..) => "Tup",
ExprKind::Binary(..) => "Binary",
ExprKind::Unary(..) => "Unary",
ExprKind::Lit(..) => "Lit",
ExprKind::Cast(..) => "Cast",
ExprKind::Type(..) => "Type",
ExprKind::If(..) => "If",
ExprKind::IfLet(..) => "IfLet",
ExprKind::While(..) => "While",
ExprKind::WhileLet(..) => "WhileLet",
ExprKind::ForLoop(..) => "ForLoop",
ExprKind::Loop(..) => "Loop",
ExprKind::Match(..) => "Match",
ExprKind::Closure(..) => "Closure",
ExprKind::Block(..) => "Block",
ExprKind::Catch(..) => "Catch",
ExprKind::Assign(..) => "Assign",
ExprKind::AssignOp(..) => "AssignOp",
ExprKind::Field(..) => "Field",
ExprKind::TupField(..) => "TupField",
ExprKind::Index(..) => "Index",
ExprKind::Range(..) => "Range",
ExprKind::Path(..) => "Path",
ExprKind::AddrOf(..) => "AddrOf",
ExprKind::Break(..) => "Break",
ExprKind::Continue(..) => "Continue",
ExprKind::Ret(..) => "Ret",
ExprKind::InlineAsm(..) => "InlineAsm",
ExprKind::Mac(..) => "Mac",
ExprKind::Struct(..) => "Struct",
ExprKind::Repeat(..) => "Repeat",
ExprKind::Paren(..) => "Paren",
ExprKind::Try(..) => "Try",
};
visit!(self, props, ("Expr", kind, ex.span) => {
walk_expr(self, ex);
});
}
// fn visit_expr_post(&mut self, _ex: &'ast Expr) {
// }
fn visit_ty(&mut self, t: &'ast Ty) {
let kind = match t.node {
TyKind::Slice(..) => "Slice",
TyKind::Array(..) => "Array",
TyKind::Ptr(..) => "Ptr",
TyKind::Rptr(..) => "Rptr",
TyKind::BareFn(..) => "BareFn",
TyKind::Never => "Never",
TyKind::Tup(..) => "Tup",
TyKind::Path(..) => "Path",
TyKind::TraitObject(..) => "TraitObject",
TyKind::ImplTrait(..) => "ImplTrait",
TyKind::Paren(..) => "Paren",
TyKind::Typeof(..) => "Typeof",
TyKind::Infer => "Infer",
TyKind::ImplicitSelf => "ImplicitSelf",
TyKind::Mac(..) => "Mac",
TyKind::Err => "Err",
};
visit!(self, props, ("Ty", kind, t.span) => {
walk_ty(self, t);
});
}
fn visit_generics(&mut self, g: &'ast Generics) {
visit!(self, props, ("Generics", "", g.span) => {
walk_generics(self, g);
});
}
fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
visit!(self, props, ("WherePredicate", "") => {
walk_where_predicate(self, p);
});
}
fn visit_fn(&mut self, fk: FnKind<'ast>, fd: &'ast FnDecl, s: Span, _: NodeId) {
let kind = match fk {
FnKind::ItemFn(..) => "ItemFn",
FnKind::Method(..) => "Method",
FnKind::Closure(..) => "Closure",
};
visit!(self, props, ("Fn", kind, s) => {
walk_fn(self, fk, fd, s);
});
}
fn visit_trait_item(&mut self, ti: &'ast TraitItem) {
visit!(self, props, ("TraitItem", "", ti.span) => {
walk_trait_item(self, ti);
});
}
fn visit_impl_item(&mut self, ii: &'ast ImplItem) {
visit!(self, props, ("ImplItem", "", ii.span) => {
walk_impl_item(self, ii);
});
}
fn visit_trait_ref(&mut self, t: &'ast TraitRef) {
visit!(self, props, ("TraitRef", "") => {
walk_trait_ref(self, t);
});
}
fn visit_ty_param_bound(&mut self, bounds: &'ast TyParamBound) {
visit!(self, props, ("TyParamBound", "") => {
walk_ty_param_bound(self, bounds);
});
}
fn visit_poly_trait_ref(&mut self, t: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) {
visit!(self, props, ("PolyTraitRef", "") => {
walk_poly_trait_ref(self, t, m);
});
}
fn visit_variant_data(&mut self, s: &'ast VariantData, _: Ident,
_: &'ast Generics, _: NodeId, span: Span) {
visit!(self, props, ("VariantData", "", span) => {
walk_struct_def(self, s);
});
}
fn visit_struct_field(&mut self, s: &'ast StructField) {
visit!(self, props, ("StructField", "", s.span) => {walk_struct_field(self, s)});
}
fn visit_enum_def(&mut self, enum_definition: &'ast EnumDef,
generics: &'ast Generics, item_id: NodeId, span: Span) {
visit!(self, props, ("EnumDef", "", span) => {
walk_enum_def(self, enum_definition, generics, item_id);
});
}
fn visit_variant(&mut self, v: &'ast Variant, g: &'ast Generics, item_id: NodeId) {
visit!(self, props, ("Variant", "") => {
walk_variant(self, v, g, item_id);
});
}
fn visit_lifetime(&mut self, lifetime: &'ast Lifetime) {
visit!(self, props, ("Lifetime", "", lifetime.span) => {
walk_lifetime(self, lifetime);
});
}
fn visit_lifetime_def(&mut self, lifetime: &'ast LifetimeDef) {
visit!(self, props, ("LifetimeDef", "") => {
walk_lifetime_def(self, lifetime);
});
}
fn visit_mac(&mut self, _mac: &'ast Mac) {
// visit::walk_mac(self, _mac)
}
fn visit_mac_def(&mut self, _mac: &'ast MacroDef, _id: NodeId) {
// Nothing to do
}
fn visit_path(&mut self, path: &'ast Path, _id: NodeId) {
self._visit_path(path);
}
fn visit_path_list_item(&mut self, prefix: &'ast Path, item: &'ast PathListItem) {
visit!(self, props, ("ListItem", "") => {
walk_path_list_item(self, prefix, item);
});
}
fn visit_path_segment(&mut self, path_span: Span, path_segment: &'ast PathSegment) {
visit!(self, props, ("PathSegment", "", path_segment.span) => {
walk_path_segment(self, path_span, path_segment);
});
}
fn visit_path_parameters(&mut self, path_span: Span, path_parameters: &'ast PathParameters) {
//FIXME: add span if match Parenthesized()
visit!(self, props, ("PathParameters", "", path_span) => {
walk_path_parameters(self, path_span, path_parameters);
});
}
fn visit_assoc_type_binding(&mut self, type_binding: &'ast TypeBinding) {
visit!(self, props, ("TypeBinding", "") => {
walk_assoc_type_binding(self, type_binding);
});
}
fn visit_attribute(&mut self, attr: &'ast Attribute) {
visit!(self, attr_props, ("Attribute", "", attr.span) => {
self._visit_path(&attr.path);
});
}
fn visit_vis(&mut self, vis: &'ast Visibility) {
let kind = match *vis {
Visibility::Crate(_span) => "Crate",
Visibility::Inherited => "Inherited",
Visibility::Public => "Public",
Visibility::Restricted{..} => "Restricted"
};
visit!(self, props, ("Vis", kind) => {
walk_vis(self, vis);
});
}
fn visit_fn_ret_ty(&mut self, ret_ty: &'ast FunctionRetTy) {
visit!(self, props, ("FnRetTy", "", ret_ty.span()) => {
walk_fn_ret_ty(self, ret_ty);
});
}
}
|
#![allow(clippy::unused_unit)]
#[macro_use]
extern crate enum_primitive;
#[macro_use]
extern crate serde_derive;
extern crate slog;
#[macro_use]
extern crate slog_scope;
mod context;
mod controller;
mod diagnostics;
mod editor_transport;
mod general;
mod language_features;
mod language_server_transport;
mod position;
mod project_root;
mod session;
mod text_edit;
mod text_sync;
mod thread_worker;
mod types;
mod util;
mod workspace;
use crate::types::*;
use crate::util::*;
use clap::{crate_version, App, Arg, ArgMatches};
use daemonize::Daemonize;
use itertools::Itertools;
use sloggers::file::FileLoggerBuilder;
use sloggers::terminal::{Destination, TerminalLoggerBuilder};
use sloggers::types::Severity;
use sloggers::Build;
use std::borrow::Cow;
use std::env;
use std::fs;
use std::io::{stdin, Read, Write};
use std::os::unix::net::UnixStream;
use std::panic;
use std::path::Path;
use std::process::{Command, Stdio};
fn main() {
let matches = App::new("kak-lsp")
.version(crate_version!())
.author("Ruslan Prokopchuk <fer.obbee@gmail.com>")
.about("Kakoune Language Server Protocol Client")
.arg(
Arg::with_name("kakoune")
.long("kakoune")
.help("Generate commands for Kakoune to plug in kak-lsp"),
)
.arg(
Arg::with_name("request")
.long("request")
.help("Forward stdin to kak-lsp server"),
)
.arg(
Arg::with_name("config")
.short("c")
.long("config")
.value_name("FILE")
.help("Read config from FILE")
.takes_value(true),
)
.arg(
Arg::with_name("daemonize")
.short("d")
.long("daemonize")
.help("Daemonize kak-lsp process (server only)"),
)
.arg(
Arg::with_name("session")
.short("s")
.long("session")
.value_name("SESSION")
.help("Session id to communicate via unix socket")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("timeout")
.short("t")
.long("timeout")
.value_name("TIMEOUT")
.help("Session timeout in seconds (default 1800)")
.takes_value(true),
)
.arg(
Arg::with_name("initial-request")
.long("initial-request")
.help("Read initial request from stdin"),
)
.arg(
Arg::with_name("v")
.short("v")
.multiple(true)
.help("Sets the level of verbosity (use up to 4 times)"),
)
.arg(
Arg::with_name("log")
.long("log")
.value_name("PATH")
.help("File to write the log into instead of stderr")
.takes_value(true),
)
.get_matches();
if matches.is_present("kakoune") {
return kakoune();
}
let mut config = include_str!("../kak-lsp.toml").to_string();
let config_path = matches
.value_of("config")
.map(|config| Path::new(&config).to_owned())
.or_else(|| {
dirs::config_dir().and_then(|config_dir| {
let path = Path::new(&config_dir.join("kak-lsp/kak-lsp.toml")).to_owned();
if path.exists() {
Some(path)
} else {
None
}
})
});
if let Some(config_path) = config_path {
config = fs::read_to_string(config_path).expect("Failed to read config");
}
let session = String::from(matches.value_of("session").unwrap());
let mut config: Config = match toml::from_str(&config) {
Ok(cfg) => cfg,
Err(err) => {
report_config_error(&matches, &session, &err);
panic!("{}", err)
}
};
config.server.session = session;
if let Some(timeout) = matches.value_of("timeout") {
config.server.timeout = timeout.parse().unwrap();
}
if matches.is_present("request") {
request(&config);
} else {
// It's important to read input before daemonizing even if we don't use it.
// Otherwise it will be empty.
let initial_request = if matches.is_present("initial-request") {
let mut input = Vec::new();
stdin()
.read_to_end(&mut input)
.expect("Failed to read stdin");
Some(String::from_utf8_lossy(&input).to_string())
} else {
None
};
let mut pid_path = util::temp_dir();
pid_path.push(format!("{}.pid", config.server.session));
if matches.is_present("daemonize") {
if let Err(e) = Daemonize::new()
.pid_file(&pid_path)
.working_directory(std::env::current_dir().unwrap())
.start()
{
println!("Failed to daemonize process: {:?}", e);
goodbye(&config.server.session, 1);
}
}
// Setting up the logger after potential daemonization,
// otherwise it refuses to work properly.
let _guard = setup_logger(&config, &matches);
let code = session::start(&config, initial_request);
goodbye(&config.server.session, code);
}
}
fn kakoune() {
let script: &str = include_str!("../rc/lsp.kak");
let args = env::args()
.skip(1)
.filter(|arg| arg != "--kakoune")
.join(" ");
let cmd = env::current_exe().unwrap();
let cmd = cmd.to_str().unwrap();
let lsp_cmd = format!(
"set global lsp_cmd '{} {}'",
editor_escape(cmd),
editor_escape(&args)
);
println!("{}\n{}", script, lsp_cmd);
}
fn request(config: &Config) {
let mut input = Vec::new();
stdin()
.read_to_end(&mut input)
.expect("Failed to read stdin");
let mut path = util::temp_dir();
path.push(&config.server.session);
if let Ok(mut stream) = UnixStream::connect(&path) {
stream
.write_all(&input)
.expect("Failed to send stdin to server");
} else {
spin_up_server(&input);
}
}
fn spin_up_server(input: &[u8]) {
let args = env::args()
.filter(|arg| arg != "--request")
.collect::<Vec<_>>();
let mut cmd = Command::new(&args[0]);
let mut child = cmd
.args(&args[1..])
.args(&["--daemonize", "--initial-request"])
.stdin(Stdio::piped())
.spawn()
.expect("Failed to run server");
child
.stdin
.as_mut()
.unwrap()
.write_all(input)
.expect("Failed to write initial request");
child.wait().expect("Failed to daemonize server");
}
fn setup_logger(config: &Config, matches: &clap::ArgMatches<'_>) -> slog_scope::GlobalLoggerGuard {
let mut verbosity = matches.occurrences_of("v") as u8;
if verbosity == 0 {
verbosity = config.verbosity
}
let level = match verbosity {
0 => Severity::Error,
1 => Severity::Warning,
2 => Severity::Info,
3 => Severity::Debug,
_ => Severity::Trace,
};
let logger = if let Some(log_path) = matches.value_of("log") {
let mut builder = FileLoggerBuilder::new(log_path);
builder.level(level);
builder.build().unwrap()
} else {
let mut builder = TerminalLoggerBuilder::new();
builder.level(level);
builder.destination(Destination::Stderr);
builder.build().unwrap()
};
panic::set_hook(Box::new(|panic_info| {
error!("panic: {}", panic_info);
}));
slog_scope::set_global_logger(logger)
}
fn report_config_error(matches: &ArgMatches, session: &str, error: &toml::de::Error) {
if !matches.is_present("initial-request") && !matches.is_present("request") {
return; // Don't know how to reach the editor.
}
let mut input = Vec::new();
stdin()
.read_to_end(&mut input)
.expect("Failed to read stdin");
let data = String::from_utf8_lossy(&input).to_string();
let request: EditorRequest = toml::from_str(&data).expect("Failed to parse request");
assert!(request.meta.session == session);
let editor = match editor_transport::start(&session, None) {
Ok(ed) => ed,
Err(_code) => return,
};
let command = format!(
"lsp-show-error {}",
editor_quote(&format!("Failed to parse config file: {}", error)),
);
if editor
.to_editor
.sender()
.send(EditorResponse {
meta: request.meta,
command: Cow::from(command),
})
.is_err()
{
error!("Failed to send command to editor");
}
}
|
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
#[macro_use] extern crate rocket_contrib;
extern crate serde_derive;
#[macro_use] extern crate lazy_static;
mod store;
mod routes;
fn main() {
rocket::ignite().mount("/",
routes![
routes::index,
routes::get_json,
routes::add_new_item,
routes::get_item,
routes::get_all_items,
routes::modify_item ,
routes::delete_item,
routes::delete_all_items
]
)
.launch();
}
|
pub mod amd;
pub mod core;
pub mod ext;
pub mod khr;
pub mod nv;
pub mod prelude;
pub trait PNext<T> {
fn chain(&mut self, p_next: &T);
}
#[macro_export]
macro_rules! impl_pnext {
($implementor: ty, $struct_name: ident) => {
impl PNext<$struct_name> for $implementor {
fn chain(&mut self, p_next: &$struct_name) {
self.pNext = p_next as *const $struct_name as *const c_void;
}
}
};
($implementor: ty, $struct_name: ident, $block: block) => {
impl PNext<$struct_name> for $implementor {
fn chain(&mut self, p_next: &$struct_name) {
$block
self.pNext = p_next as *const $struct_name as *const c_void;
}
}
};
}
use crate::prelude::*;
use std::ffi::CStr;
use std::os::raw::c_char;
use std::slice;
fn c_char_to_vkstring(text: *const c_char) -> Result<VkString, String> {
let cstr = unsafe { CStr::from_ptr(text) };
let str_ = match cstr.to_str() {
Ok(str_) => str_,
Err(_) => return Err("failed converting *const c_char".to_string()),
};
Ok(VkString::new(str_))
}
fn raw_to_slice<'a, T: Clone>(pointer: *const T, size: u32) -> &'a [T] {
unsafe { slice::from_raw_parts(pointer, size as usize) }
}
|
use super::*;
pub struct BinaryPushBuilder;
impl BinaryPushBuilder {
pub fn build<'f, 'o>(
builder: &mut ScopedFunctionBuilder<'f, 'o>,
op: BinaryPush,
) -> Result<Option<Value>> {
todo!("build binary push {:#?}", op);
}
}
|
use trybuild::TestCases;
#[test]
#[cfg_attr(miri, ignore)]
fn compile_fail() {
let cases = TestCases::new();
cases.compile_fail("tests/compile_fail/runtime/*.rs");
cases.compile_fail("tests/compile_fail/scoped/*.rs");
cases.compile_fail("tests/compile_fail/immovable/*.rs");
cases.compile_fail("tests/compile_fail/typeid/*.rs");
#[cfg(feature = "std")]
cases.compile_fail("tests/compile_fail/typeid-tl/*.rs");
}
|
use crate::value::Value;
use parser::types::{ProgramError, SourceCodeLocation, Statement};
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::{Debug, Error, Formatter};
use std::rc::Rc;
use crate::interpreter::Interpreter;
#[derive(Clone, PartialEq)]
pub struct LoxFunction<'a> {
pub arguments: Vec<&'a str>,
pub environments: Vec<Rc<RefCell<HashMap<&'a str, Value<'a>>>>>,
pub body: Vec<&'a Statement<'a>>,
pub location: SourceCodeLocation<'a>,
}
impl<'a> LoxFunction<'a> {
pub fn eval(
&self,
values: &[Value<'a>],
interpreter: &'a Interpreter<'a>,
) -> Result<Value<'a>, ProgramError<'a>> {
if self.arguments.len() != values.len() {
return Err(ProgramError {
message: format!(
"Wrong number of arguments: Received {}, expected {}",
values.len(),
self.arguments.len(),
),
location: self.location.clone(),
});
}
let prev_margin = interpreter.state.borrow().view_margin;
{
let mut s = interpreter.state.borrow_mut();
s.environments.extend_from_slice(&self.environments);
s.view_margin = s.environments.len() - self.environments.len();
s.push();
for (name, value) in self.arguments.iter().zip(values.iter().cloned()) {
s.insert_top(name, value);
}
s.in_function = true;
}
let mut value = Value::Nil;
for st in self.body.iter() {
interpreter.evaluate(st)?;
if let Some(box return_value) = &interpreter.state.borrow().return_value {
value = return_value.clone();
break;
}
}
{
let mut s = interpreter.state.borrow_mut();
s.return_value = None;
s.in_function = false;
s.pop();
let current_len = s.environments.len();
s.view_margin = prev_margin;
s.environments.resize_with(
current_len - self.environments.len(),
|| unreachable!(),
);
}
Ok(value)
}
}
impl<'a> Debug for LoxFunction<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
f.write_str(
format!(
"[Function: Arguments {:?} Body {:?} Location {:?} Env Size {:?}",
self.arguments,
self.body,
self.location,
self.environments.len()
)
.as_str(),
)
}
}
|
//! Scripting runtime types and helpers for interacting with it.
mod runtime;
mod value;
pub use self::runtime::{ScriptRuntime};
pub use self::value::{ScriptTable, ScriptValue};
|
/*
The math was taken and adapted from various places on the internet
Specifically, from gl-matrix and the gltf-rs crate (which in turn took from cg_math)
The idea is that we have a very minimal math lib with no dependencies for small projects
Currently there's a ton of stuff missing
*/
mod aliases;
mod matrix4;
mod vec3;
mod vec4;
pub use aliases::*;
pub use matrix4::*;
pub use vec3::*;
pub use vec4::*;
|
#![no_std]
#![feature(link_cfg)]
#![feature(c_unwind)]
#![cfg_attr(not(target_env = "msvc"), feature(libc))]
cfg_if::cfg_if! {
if #[cfg(target_env = "msvc")] {
// no extra unwinder support needed
} else if #[cfg(any(
target_os = "l4re",
target_os = "none",
))] {
// These "unix" family members do not have unwinder.
// Note this also matches x86_64-linux-kernel.
} else if #[cfg(any(
unix,
windows,
target_os = "cloudabi",
all(target_vendor = "fortanix", target_env = "sgx"),
))] {
mod libunwind;
pub use libunwind::*;
} else {
// no unwinder on the system!
// - wasm32 (not emscripten, which is "unix" family)
// - os=none ("bare metal" targets)
// - os=hermit
// - os=uefi
// - os=cuda
// - nvptx64-nvidia-cuda
// - mipsel-sony-psp
// - Any new targets not listed above.
}
}
#[cfg(target_env = "musl")]
#[link(name = "unwind", kind = "static", modifiers = "-bundle", cfg(target_feature = "crt-static"))]
#[link(name = "gcc_s", cfg(not(target_feature = "crt-static")))]
extern "C" {}
#[cfg(target_os = "redox")]
#[link(
name = "gcc_eh",
kind = "static",
modifiers = "-bundle",
cfg(target_feature = "crt-static")
)]
#[link(name = "gcc_s", cfg(not(target_feature = "crt-static")))]
extern "C" {}
#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))]
#[link(name = "unwind", kind = "static", modifiers = "-bundle")]
extern "C" {}
|
use serde::{Deserialize, Serialize};
use crate::domain::code_function::CodeFunction;
use crate::domain::CodePoint;
#[repr(C)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CodeClass {
pub name: String,
pub package: String,
pub extends: Vec<String>,
pub implements: Vec<String>,
pub constant: Vec<ClassConstant>,
pub functions: Vec<CodeFunction>,
pub start: CodePoint,
pub end: CodePoint
}
impl Default for CodeClass {
fn default() -> Self {
CodeClass {
name: "".to_string(),
package: "".to_string(),
extends: vec![],
implements: vec![],
constant: vec![],
functions: vec![],
start: Default::default(),
end: Default::default()
}
}
}
#[repr(C)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ClassConstant {
pub name: String,
pub typ: String,
}
|
use bintree::Tree;
use std::fmt;
pub fn leaf_list<T: Copy + fmt::Display>(tree: &Tree<T>) -> Vec<T> {
match tree {
Tree::Node { value, left, right } => match (left.as_ref(), right.as_ref()) {
(Tree::End, Tree::End) => vec![*value],
_ => {
let mut leaves = leaf_list(left);
leaves.extend_from_slice(&leaf_list(right));
leaves
}
},
Tree::End => vec![],
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_leaf_list() {
assert_eq!(leaf_list(&Tree::<char>::end()), vec![]);
assert_eq!(leaf_list(&Tree::leaf('a')), vec!['a']);
assert_eq!(
leaf_list(&Tree::node(
'a',
Tree::leaf('b'),
Tree::node('c', Tree::leaf('d'), Tree::leaf('e'))
)),
vec!['b', 'd', 'e']
);
}
}
|
#![deny(missing_debug_implementations)]
#![feature(async_await, await_macro, futures_api)]
#![forbid(unsafe_code)]
pub extern crate deck_core as core;
#[cfg(feature = "local")]
pub use self::local::LocalCache;
#[cfg(feature = "s3")]
pub use self::s3::S3Cache;
use std::fmt::Debug;
use std::future::Future;
use std::pin::Pin;
use deck_core::OutputId;
use futures::stream::Stream;
mod https;
#[cfg(feature = "local")]
mod local;
#[cfg(feature = "s3")]
mod s3;
// NOTE: All this noise has been to work fine with a simple `async fn`, with no need for associated
// types, this type alias, or `Pin<Box<_>>`. Replace _immediately_ once `async fn` in traits is
// stabilized in Rust.
pub type BinaryCacheFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, ()>> + Send + 'a>>;
pub type OutputStream<'a> = Pin<Box<dyn Stream<Item = Result<Vec<u8>, ()>> + Send + 'a>>;
pub trait BinaryCache: Debug {
fn query_outputs<'a>(&'a mut self, id: &'a OutputId) -> BinaryCacheFuture<'a, ()>;
fn fetch_output<'a>(&'a mut self, id: &'a OutputId) -> OutputStream<'a>;
}
|
#![feature(test)]
// FIXME: `get_test_addresses` doesn't work on macos.
#![cfg(not(target_os = "macos"))]
extern crate addr2line;
extern crate memmap;
extern crate object;
extern crate test;
use std::env;
use std::path::{self, PathBuf};
use std::process;
fn release_fixture_path() -> PathBuf {
let mut path = PathBuf::new();
if let Ok(dir) = env::var("CARGO_MANIFEST_DIR") {
path.push(dir);
}
path.push("fixtures");
path.push("addr2line-release");
path
}
fn with_file<F: FnOnce(&object::File)>(target: &path::Path, f: F) {
let map = memmap::Mmap::open_path(target, memmap::Protection::Read).unwrap();
let file = object::File::parse(unsafe { map.as_slice() }).unwrap();
f(&file)
}
/// Obtain a list of addresses contained within the text section of the `target` executable.
// TODO: use object crate instead of nm
fn get_test_addresses(target: &path::Path) -> Vec<u64> {
let names = process::Command::new("/usr/bin/nm")
.arg("-S")
.arg(target)
.output()
.expect("failed to execute nm");
let symbols = String::from_utf8_lossy(&names.stdout);
let mut addresses = Vec::new();
for line in symbols.lines().take(200) {
let fields: Vec<_> = line.split_whitespace().take(4).collect();
if fields.len() >= 4 && (fields[2] == "T" || fields[2] == "t") {
let mut addr = u64::from_str_radix(fields[0], 16).unwrap();
let size = u64::from_str_radix(fields[1], 16).unwrap();
let end = addr + size;
while addr < end {
addresses.push(addr);
addr += 5;
}
}
}
addresses
}
#[bench]
fn context_new_location(b: &mut test::Bencher) {
let target = release_fixture_path();
with_file(&target, |file| {
b.iter(|| {
addr2line::Context::new(file).unwrap();
});
});
}
#[bench]
fn context_new_with_functions(b: &mut test::Bencher) {
let target = release_fixture_path();
with_file(&target, |file| {
b.iter(|| {
addr2line::Context::new(file)
.unwrap()
.parse_functions()
.unwrap();
});
});
}
#[bench]
fn context_query_location(b: &mut test::Bencher) {
let target = release_fixture_path();
let addresses = get_test_addresses(target.as_path());
with_file(&target, |file| {
let ctx = addr2line::Context::new(file).unwrap();
// Ensure nothing is lazily loaded.
for addr in &addresses {
test::black_box(ctx.find_location(*addr)).ok();
}
b.iter(|| {
for addr in &addresses {
test::black_box(ctx.find_location(*addr)).ok();
}
});
});
}
#[bench]
fn context_query_with_functions(b: &mut test::Bencher) {
let target = release_fixture_path();
let addresses = get_test_addresses(target.as_path());
with_file(&target, |file| {
let ctx = addr2line::Context::new(file)
.unwrap()
.parse_functions()
.unwrap();
// Ensure nothing is lazily loaded.
for addr in &addresses {
test::black_box(ctx.query(*addr)).ok();
}
b.iter(|| {
for addr in &addresses {
test::black_box(ctx.query(*addr)).ok();
}
});
});
}
#[bench]
fn context_new_and_query_location(b: &mut test::Bencher) {
let target = release_fixture_path();
let addresses = get_test_addresses(target.as_path());
with_file(&target, |file| {
b.iter(|| {
let ctx = addr2line::Context::new(file).unwrap();
for addr in addresses.iter().take(100) {
test::black_box(ctx.find_location(*addr)).ok();
}
});
});
}
#[bench]
fn context_new_and_query_with_functions(b: &mut test::Bencher) {
let target = release_fixture_path();
let addresses = get_test_addresses(target.as_path());
with_file(&target, |file| {
b.iter(|| {
let ctx = addr2line::Context::new(file)
.unwrap()
.parse_functions()
.unwrap();
for addr in addresses.iter().take(100) {
test::black_box(ctx.query(*addr)).ok();
}
});
});
}
|
extern crate graph_layout;
use graph_layout::layout::*;
use graph_layout::compression::*;
#[test]
fn encode_decode_byte() {
let hilbert = Hilbert::new();
for i in 0 .. (1 << 20) {
assert_eq!(hilbert.entangle(hilbert.detangle(i)), i);
}
}
#[test]
fn compress_decompress() {
let source = vec![0,1,2,4, 100, 123412, 1543245423];
let compressed = Compressed::from(source.iter().map(|&x|x));
let decompressor = compressed.decompress();
let result = decompressor.collect::<Vec<_>>();
assert_eq!(result, source);
}
|
use bytes::Bytes;
use futures::SinkExt;
use serde::{Deserialize, Serialize};
use std::panic;
use std::{time};
use tokio::net::TcpStream;
use tokio::stream::StreamExt;
use tokio_util::codec::{Framed, LengthDelimitedCodec};
mod common;
static LOCAL_REMITS: &str = "localhost:4243";
static OK_RESP: &[u8] = &[0x62, 0x6F, 0x6B];
#[tokio::test]
async fn integration_tests() {
let _ = tokio::spawn(common::start_server());
let five = time::Duration::from_secs(5);
std::thread::sleep(five);
let stream = TcpStream::connect(LOCAL_REMITS)
.await
.expect("could not connect to localhost:4243");
let framer = &mut Framed::new(stream, LengthDelimitedCodec::new());
//let framer = &mut common::start_server().await;
println!("test: should be able to add a log");
let (kind, code, payload) = send_req(framer, new_log_add_req("test")).await;
assert_eq!(kind, 0x01);
assert_eq!(code, 0x00);
assert_eq!(payload, OK_RESP);
println!("test: re-adding an existing log should be a noop and still return ok");
let (kind, code, payload) = send_req(framer, new_log_add_req("test")).await;
assert_eq!(kind, 0x01);
assert_eq!(code, 0x00);
assert_eq!(payload, OK_RESP);
println!("test: invalid iterator types should return an error");
let (kind, code, payload) =
send_req(framer, new_itr_add_req("test", "itr", "NOT_A_VALID_TYPE")).await;
assert_eq!(kind, 0x03);
assert_eq!(code, 0x0B);
assert_eq!(payload, serde_cbor::to_vec(&"CouldNotReadPayload").unwrap());
println!("test: should be able to add an iterator");
let (kind, code, payload) = send_req(framer, new_itr_add_req("test", "itr", "map")).await;
assert_eq!(kind, 0x01);
assert_eq!(code, 0x00);
assert_eq!(payload, OK_RESP);
println!("test: should not be able to send a message as invalid cbor");
let (kind, code, payload) =
send_req(framer, new_msg_add_req("test", b"\x93\x00\x2a".to_vec())).await;
assert_eq!(kind, 0x03);
assert_eq!(code, 0x03);
assert_eq!(payload, serde_cbor::to_vec(&"MsgNotValidCbor").unwrap());
println!("test: can add valid message");
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
struct Msg {
number: usize,
word: String,
}
let test_msg = Msg {
number: 42,
word: "wat".into(),
};
let cbor = serde_cbor::to_vec(&test_msg).unwrap();
println!("{:?}", cbor);
let (kind, code, payload) = send_req(framer, new_msg_add_req("test", cbor.clone())).await;
assert_eq!(kind, 0x01);
assert_eq!(code, 0x00);
assert_eq!(payload, OK_RESP);
let (kind, code, payload) = send_req(framer, new_itr_next_req("itr", 0, 1)).await;
assert_eq!(kind, 0x02);
assert_eq!(code, 0x00);
// Remove byte length
let mut msg = &payload[4..];
let resp: Msg = serde_cbor::from_reader(&mut msg).unwrap();
assert_eq!(resp, test_msg);
let (kind, code, payload) = send_req(framer, new_log_list_req()).await;
assert_eq!(kind, 0x02);
assert_eq!(code, 0x00);
let out: Vec<String> = serde_cbor::from_slice(&payload[4..]).unwrap();
assert_eq!(out, vec!("test"));
//b.await;
}
fn new_log_add_req(name: &str) -> Vec<u8> {
#[derive(Serialize)]
struct Body {
log_name: String,
}
let mut body = vec![0x00, 0x01];
let req = serde_cbor::to_vec(&Body {
log_name: name.into(),
})
.unwrap();
body.extend(req);
body
}
fn new_itr_add_req(name: &str, itr_name: &str, typ: &str) -> Vec<u8> {
#[derive(Serialize)]
struct Body {
log_name: String,
iterator_name: String,
iterator_kind: String,
iterator_func: String,
}
let mut body = vec![0x00, 0x05];
let req = serde_cbor::to_vec(&Body {
log_name: name.into(),
iterator_name: itr_name.into(),
iterator_kind: typ.into(),
iterator_func: "return msg".into(),
})
.unwrap();
body.extend(req);
body
}
fn new_msg_add_req(name: &str, message: Vec<u8>) -> Vec<u8> {
#[derive(Serialize)]
struct Body {
log_name: String,
message: serde_cbor::Value,
}
let mut body = vec![0x00, 0x04];
let req = serde_cbor::to_vec(&Body {
log_name: name.into(),
message: serde_cbor::Value::Bytes(message),
})
.unwrap();
body.extend(req);
body
}
fn new_log_list_req() -> Vec<u8> {
vec![0x00, 0x03]
}
fn new_itr_next_req(name: &str, message_id: usize, count: usize) -> Vec<u8> {
#[derive(Serialize)]
struct Body {
iterator_name: String,
message_id: usize,
count: usize,
}
let mut body = vec![0x00, 0x07];
let req = serde_cbor::to_vec(&Body {
iterator_name: name.into(),
message_id,
count,
})
.unwrap();
body.extend(req);
body
}
// returns Kind, Code, and Payload
async fn send_req(
framer: &mut Framed<TcpStream, LengthDelimitedCodec>,
bytes: Vec<u8>,
) -> (u8, u8, Vec<u8>) {
framer
.send(Bytes::from(bytes))
.await
.expect("could not send command");
let result = framer
.next()
.await
.expect("no response from remits")
.expect("could not understand response");
(result[0], result[1], result[2..].to_vec())
}
|
use std::fs::File;
use std::io::BufReader;
use std::io::BufWriter;
use obj::*;
#[test]
fn load() {
let mut expected = ObjData::new();
expected.vertices = vec![(1.,-1.,-1.,1.),
(1.,-1.,1.,1.),
(-1.,-1.,1.,1.),
(-1.,-1.,-1.,1.),
(1.,1.,-1.,1.),
(1.,1.,1.,1.),
(-1.,1.,1.,1.),
(-1.,1.,-1.,1.)];
expected.normals = vec![(0.,-1.,0.),
(0.,1.,0.),
(1.,0.,0.),
(0.,0.,1.),
(-1.,0.,0.),
(0.,0.,-1.)];
expected.faces = vec![ vec![(1,None,Some(0)), (3,None,Some(0)), (0,None,Some(0))],
vec![(7,None,Some(1)), (5,None,Some(1)), (4,None,Some(1))],
vec![(4,None,Some(2)), (1,None,Some(2)), (0,None,Some(2))],
vec![(5,None,Some(3)), (2,None,Some(3)), (1,None,Some(3))],
vec![(2,None,Some(4)), (7,None,Some(4)), (3,None,Some(4))],
vec![(0,None,Some(5)), (7,None,Some(5)), (4,None,Some(5))],
vec![(1,None,Some(0)), (2,None,Some(0)), (3,None,Some(0))],
vec![(7,None,Some(1)), (6,None,Some(1)), (5,None,Some(1))],
vec![(4,None,Some(2)), (5,None,Some(2)), (1,None,Some(2))],
vec![(5,None,Some(3)), (6,None,Some(3)), (2,None,Some(3))],
vec![(2,None,Some(4)), (6,None,Some(4)), (7,None,Some(4))],
vec![(0,None,Some(5)), (3,None,Some(5)), (7,None,Some(5))],
];
let obj = Object {
name : String::from("Cube"),
primitives : vec![0,1,2,3,4,5,6,7,8,9,10,11]
};
expected.objects = vec![obj];
let gr1 = Group {
name : String::from("group1"),
indexes : vec!(3,4,5,6,7,8).into_iter().collect()
};
let gr2 = Group {
name : String::from("group2"),
indexes : vec!(3,4,5).into_iter().collect()
};
let gr3 = Group {
name : String::from("group3"),
indexes : vec!(9,10,11).into_iter().collect()
};
expected.groups = vec![gr1,gr2,gr3];
let f = File::open("cube.obj").unwrap();
let mut input = BufReader::new(f);
let data = ObjData::load(&mut input).ok().unwrap();
assert_eq!(expected.vertices,data.vertices);
assert_eq!(expected.normals,data.normals);
assert_eq!(expected.texcoords,data.texcoords);
assert_eq!(expected.faces,data.faces);
assert_eq!(expected.objects,data.objects);
assert_eq!(expected.groups,data.groups);
}
#[test]
fn write() {
let mut expected = ObjData::new();
expected.vertices = vec![(1.,-1.,-1.,1.),
(1.,-1.,1.,1.),
(-1.,-1.,1.,1.),
(-1.,-1.,-1.,1.),
(1.,1.,-1.,1.),
(1.,1.,1.,1.),
(-1.,1.,1.,1.),
(-1.,1.,-1.,1.)];
expected.normals = vec![(0.,-1.,0.),
(0.,1.,0.),
(1.,0.,0.),
(0.,0.,1.),
(-1.,0.,0.),
(0.,0.,-1.)];
expected.faces = vec![ vec![(1,None,Some(0)), (3,None,Some(0)), (0,None,Some(0))],
vec![(7,None,Some(1)), (5,None,Some(1)), (4,None,Some(1))],
vec![(4,None,Some(2)), (1,None,Some(2)), (0,None,Some(2))],
vec![(5,None,Some(3)), (2,None,Some(3)), (1,None,Some(3))],
vec![(2,None,Some(4)), (7,None,Some(4)), (3,None,Some(4))],
vec![(0,None,Some(5)), (7,None,Some(5)), (4,None,Some(5))],
vec![(1,None,Some(0)), (2,None,Some(0)), (3,None,Some(0))],
vec![(7,None,Some(1)), (6,None,Some(1)), (5,None,Some(1))],
vec![(4,None,Some(2)), (5,None,Some(2)), (1,None,Some(2))],
vec![(5,None,Some(3)), (6,None,Some(3)), (2,None,Some(3))],
vec![(2,None,Some(4)), (6,None,Some(4)), (7,None,Some(4))],
vec![(0,None,Some(5)), (3,None,Some(5)), (7,None,Some(5))],
];
let obj = Object {
name : String::from("Cube"),
primitives : vec![0,1,2,3,4,5,6,7,8,9,10,11]
};
expected.objects = vec![obj];
let gr1 = Group {
name : String::from("group1"),
indexes : vec!(3,4,5,6,7,8).into_iter().collect()
};
let gr2 = Group {
name : String::from("group2"),
indexes : vec!(3,4,5).into_iter().collect()
};
let gr3 = Group {
name : String::from("group3"),
indexes : vec!(9,10,11).into_iter().collect()
};
expected.groups = vec![gr1,gr2,gr3];
{
let f2 = File::create("tmp.obj").unwrap();
let mut output = BufWriter::new(f2);
assert!(expected.write(&mut output).is_ok());
}
let f1 = File::open("tmp.obj").unwrap();
let mut input = BufReader::new(f1);
let data = ObjData::load(&mut input).ok().unwrap();
assert_eq!(expected.vertices,data.vertices);
assert_eq!(expected.normals,data.normals);
assert_eq!(expected.texcoords,data.texcoords);
assert_eq!(expected.faces,data.faces);
assert_eq!(expected.objects,data.objects);
assert_eq!(expected.groups,data.groups);
}
#[test]
fn read_write_read() {
let f = File::open("cube.obj").unwrap();
let mut input = BufReader::new(f);
let data = ObjData::load(&mut input).ok().unwrap();
{
let f2 = File::create("rwr.obj").unwrap();
let mut output = BufWriter::new(f2);
assert!(data.write(&mut output).is_ok());
}
let f1 = File::open("rwr.obj").unwrap();
let mut input = BufReader::new(f1);
let reload = ObjData::load(&mut input).ok().unwrap();
assert_eq!(reload.vertices,data.vertices);
assert_eq!(reload.normals,data.normals);
assert_eq!(reload.texcoords,data.texcoords);
assert_eq!(reload.faces,data.faces);
assert_eq!(reload.objects,data.objects);
assert_eq!(reload.groups,data.groups);
}
|
use bevy::{pbr::AmbientLight, prelude::*};
mod camera;
mod city;
mod connect_ui;
mod info;
mod screenspace;
mod units;
mod world;
#[derive(Clone, Eq, PartialEq, Debug, Hash)]
pub enum GameState {
Loading,
Account,
Playing,
}
fn main() {
App::new()
.add_state(GameState::Loading)
.insert_resource(WindowDescriptor {
title: "Cerium".to_string(),
..Default::default()
})
.insert_resource(Msaa { samples: 4 })
.add_plugins(DefaultPlugins)
.add_plugin(camera::CameraPlugin)
.add_plugin(world::WorldPlugin)
.add_plugin(city::CityPlugin)
.add_plugin(units::UnitPlugin)
.add_plugin(info::InfoPlugin)
.add_plugin(connect_ui::ConnectUIPlugin)
.add_startup_system(setup)
.run();
}
/// set up a simple 3D scene
fn setup(mut ambient_light: ResMut<AmbientLight>) {
// light
ambient_light.brightness = 0.5;
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_exception::Span;
use common_meta_app::principal::FileFormatOptions;
use common_meta_app::principal::PrincipalIdentity;
use common_meta_app::principal::UserIdentity;
use super::walk_mut::walk_cte_mut;
use super::walk_mut::walk_expr_mut;
use super::walk_mut::walk_identifier_mut;
use super::walk_mut::walk_join_condition_mut;
use super::walk_mut::walk_query_mut;
use super::walk_mut::walk_select_target_mut;
use super::walk_mut::walk_set_expr_mut;
use super::walk_mut::walk_statement_mut;
use super::walk_mut::walk_table_reference_mut;
use super::walk_time_travel_point_mut;
use crate::ast::*;
pub trait VisitorMut: Sized {
fn visit_expr(&mut self, expr: &mut Expr) {
walk_expr_mut(self, expr);
}
fn visit_identifier(&mut self, _ident: &mut Identifier) {}
fn visit_database_ref(&mut self, catalog: &mut Option<Identifier>, database: &mut Identifier) {
if let Some(catalog) = catalog {
walk_identifier_mut(self, catalog);
}
walk_identifier_mut(self, database);
}
fn visit_table_ref(
&mut self,
catalog: &mut Option<Identifier>,
database: &mut Option<Identifier>,
table: &mut Identifier,
) {
if let Some(catalog) = catalog {
walk_identifier_mut(self, catalog);
}
if let Some(database) = database {
walk_identifier_mut(self, database);
}
walk_identifier_mut(self, table);
}
fn visit_column_ref(
&mut self,
_span: Span,
database: &mut Option<Identifier>,
table: &mut Option<Identifier>,
column: &mut Identifier,
) {
if let Some(database) = database {
walk_identifier_mut(self, database);
}
if let Some(table) = table {
walk_identifier_mut(self, table);
}
walk_identifier_mut(self, column);
}
fn visit_is_null(&mut self, _span: Span, expr: &mut Expr, _not: bool) {
walk_expr_mut(self, expr);
}
fn visit_is_distinct_from(
&mut self,
_span: Span,
left: &mut Expr,
right: &mut Expr,
_not: bool,
) {
walk_expr_mut(self, left);
walk_expr_mut(self, right);
}
fn visit_in_list(&mut self, _span: Span, expr: &mut Expr, list: &mut [Expr], _not: bool) {
walk_expr_mut(self, expr);
for expr in list {
walk_expr_mut(self, expr);
}
}
fn visit_in_subquery(
&mut self,
_span: Span,
expr: &mut Expr,
subquery: &mut Query,
_not: bool,
) {
walk_expr_mut(self, expr);
walk_query_mut(self, subquery);
}
fn visit_between(
&mut self,
_span: Span,
expr: &mut Expr,
low: &mut Expr,
high: &mut Expr,
_not: bool,
) {
walk_expr_mut(self, expr);
walk_expr_mut(self, low);
walk_expr_mut(self, high);
}
fn visit_binary_op(
&mut self,
_span: Span,
_op: &mut BinaryOperator,
left: &mut Expr,
right: &mut Expr,
) {
walk_expr_mut(self, left);
walk_expr_mut(self, right);
}
fn visit_unary_op(&mut self, _span: Span, _op: &mut UnaryOperator, expr: &mut Expr) {
walk_expr_mut(self, expr);
}
fn visit_cast(
&mut self,
_span: Span,
expr: &mut Expr,
_target_type: &mut TypeName,
_pg_style: bool,
) {
walk_expr_mut(self, expr);
}
fn visit_try_cast(&mut self, _span: Span, expr: &mut Expr, _target_type: &mut TypeName) {
walk_expr_mut(self, expr);
}
fn visit_extract(&mut self, _span: Span, _kind: &mut IntervalKind, expr: &mut Expr) {
walk_expr_mut(self, expr);
}
fn visit_position(&mut self, _span: Span, substr_expr: &mut Expr, str_expr: &mut Expr) {
walk_expr_mut(self, substr_expr);
walk_expr_mut(self, str_expr);
}
fn visit_substring(
&mut self,
_span: Span,
expr: &mut Expr,
substring_from: &mut Box<Expr>,
substring_for: &mut Option<Box<Expr>>,
) {
walk_expr_mut(self, expr);
walk_expr_mut(self, substring_from);
if let Some(substring_for) = substring_for {
walk_expr_mut(self, substring_for);
}
}
fn visit_trim(
&mut self,
_span: Span,
expr: &mut Expr,
trim_where: &mut Option<(TrimWhere, Box<Expr>)>,
) {
walk_expr_mut(self, expr);
if let Some((_, trim_where_expr)) = trim_where {
walk_expr_mut(self, trim_where_expr);
}
}
fn visit_literal(&mut self, _span: Span, _lit: &mut Literal) {}
fn visit_count_all(&mut self, _span: Span) {}
fn visit_tuple(&mut self, _span: Span, elements: &mut [Expr]) {
for elem in elements.iter_mut() {
walk_expr_mut(self, elem);
}
}
fn visit_function_call(
&mut self,
_span: Span,
_distinct: bool,
_name: &mut Identifier,
args: &mut [Expr],
_params: &mut [Literal],
over: &mut Option<WindowSpec>,
) {
for arg in args.iter_mut() {
walk_expr_mut(self, arg);
}
if let Some(over) = over {
over.partition_by
.iter_mut()
.for_each(|expr| walk_expr_mut(self, expr));
over.order_by
.iter_mut()
.for_each(|expr| walk_expr_mut(self, &mut expr.expr));
if let Some(frame) = &mut over.window_frame {
self.visit_frame_bound(&mut frame.start_bound);
self.visit_frame_bound(&mut frame.end_bound);
}
}
}
fn visit_frame_bound(&mut self, bound: &mut WindowFrameBound) {
match bound {
WindowFrameBound::Preceding(Some(expr)) => walk_expr_mut(self, expr.as_mut()),
WindowFrameBound::Following(Some(expr)) => walk_expr_mut(self, expr.as_mut()),
_ => {}
}
}
fn visit_case_when(
&mut self,
_span: Span,
operand: &mut Option<Box<Expr>>,
conditions: &mut [Expr],
results: &mut [Expr],
else_result: &mut Option<Box<Expr>>,
) {
if let Some(operand) = operand {
walk_expr_mut(self, operand);
}
for condition in conditions.iter_mut() {
walk_expr_mut(self, condition);
}
for result in results.iter_mut() {
walk_expr_mut(self, result);
}
if let Some(else_result) = else_result {
walk_expr_mut(self, else_result);
}
}
fn visit_exists(&mut self, _span: Span, _not: bool, subquery: &mut Query) {
walk_query_mut(self, subquery);
}
fn visit_subquery(
&mut self,
_span: Span,
_modifier: &mut Option<SubqueryModifier>,
subquery: &mut Query,
) {
walk_query_mut(self, subquery);
}
fn visit_map_access(&mut self, _span: Span, expr: &mut Expr, _accessor: &mut MapAccessor) {
walk_expr_mut(self, expr);
}
fn visit_array(&mut self, _span: Span, elements: &mut [Expr]) {
for elem in elements.iter_mut() {
walk_expr_mut(self, elem);
}
}
fn visit_array_sort(&mut self, _span: Span, expr: &mut Expr, _asc: bool, _null_first: bool) {
walk_expr_mut(self, expr);
}
fn visit_map(&mut self, _span: Span, kvs: &mut [(Expr, Expr)]) {
for (key_expr, val_expr) in kvs {
walk_expr_mut(self, key_expr);
walk_expr_mut(self, val_expr);
}
}
fn visit_interval(&mut self, _span: Span, expr: &mut Expr, _unit: &mut IntervalKind) {
walk_expr_mut(self, expr);
}
fn visit_date_add(
&mut self,
_span: Span,
_unit: &mut IntervalKind,
interval: &mut Expr,
date: &mut Expr,
) {
walk_expr_mut(self, date);
walk_expr_mut(self, interval);
}
fn visit_date_sub(
&mut self,
_span: Span,
_unit: &mut IntervalKind,
interval: &mut Expr,
date: &mut Expr,
) {
walk_expr_mut(self, date);
walk_expr_mut(self, interval);
}
fn visit_date_trunc(&mut self, _span: Span, _unit: &mut IntervalKind, date: &mut Expr) {
walk_expr_mut(self, date);
}
fn visit_statement(&mut self, statement: &mut Statement) {
walk_statement_mut(self, statement);
}
fn visit_query(&mut self, query: &mut Query) {
walk_query_mut(self, query);
}
fn visit_explain(&mut self, _kind: &mut ExplainKind, stmt: &mut Statement) {
walk_statement_mut(self, stmt);
}
fn visit_copy(&mut self, _copy: &mut CopyStmt) {}
fn visit_copy_unit(&mut self, _copy_unit: &mut CopyUnit) {}
fn visit_call(&mut self, _call: &mut CallStmt) {}
fn visit_show_settings(&mut self, _like: &mut Option<String>) {}
fn visit_show_process_list(&mut self) {}
fn visit_show_metrics(&mut self) {}
fn visit_show_engines(&mut self) {}
fn visit_show_functions(&mut self, _limit: &mut Option<ShowLimit>) {}
fn visit_show_table_functions(&mut self, _limit: &mut Option<ShowLimit>) {}
fn visit_show_limit(&mut self, _limit: &mut ShowLimit) {}
fn visit_kill(&mut self, _kill_target: &mut KillTarget, _object_id: &mut String) {}
fn visit_set_variable(
&mut self,
_is_global: bool,
_variable: &mut Identifier,
_value: &mut Box<Expr>,
) {
}
fn visit_unset_variable(&mut self, _stmt: &mut UnSetStmt) {}
fn visit_set_role(&mut self, _is_default: bool, _role_name: &mut String) {}
fn visit_insert(&mut self, _insert: &mut InsertStmt) {}
fn visit_replace(&mut self, _replace: &mut ReplaceStmt) {}
fn visit_insert_source(&mut self, _insert_source: &mut InsertSource) {}
fn visit_delete(
&mut self,
_table_reference: &mut TableReference,
_selection: &mut Option<Expr>,
) {
}
fn visit_update(&mut self, _update: &mut UpdateStmt) {}
fn visit_show_catalogs(&mut self, _stmt: &mut ShowCatalogsStmt) {}
fn visit_show_create_catalog(&mut self, _stmt: &mut ShowCreateCatalogStmt) {}
fn visit_create_catalog(&mut self, _stmt: &mut CreateCatalogStmt) {}
fn visit_drop_catalog(&mut self, _stmt: &mut DropCatalogStmt) {}
fn visit_show_databases(&mut self, _stmt: &mut ShowDatabasesStmt) {}
fn visit_show_create_databases(&mut self, _stmt: &mut ShowCreateDatabaseStmt) {}
fn visit_create_database(&mut self, _stmt: &mut CreateDatabaseStmt) {}
fn visit_drop_database(&mut self, _stmt: &mut DropDatabaseStmt) {}
fn visit_undrop_database(&mut self, _stmt: &mut UndropDatabaseStmt) {}
fn visit_alter_database(&mut self, _stmt: &mut AlterDatabaseStmt) {}
fn visit_use_database(&mut self, _database: &mut Identifier) {}
fn visit_show_tables(&mut self, _stmt: &mut ShowTablesStmt) {}
fn visit_show_columns(&mut self, _stmt: &mut ShowColumnsStmt) {}
fn visit_show_create_table(&mut self, _stmt: &mut ShowCreateTableStmt) {}
fn visit_describe_table(&mut self, _stmt: &mut DescribeTableStmt) {}
fn visit_show_tables_status(&mut self, _stmt: &mut ShowTablesStatusStmt) {}
fn visit_create_table(&mut self, _stmt: &mut CreateTableStmt) {}
fn visit_create_table_source(&mut self, _source: &mut CreateTableSource) {}
fn visit_column_definition(&mut self, _column_definition: &mut ColumnDefinition) {}
fn visit_drop_table(&mut self, _stmt: &mut DropTableStmt) {}
fn visit_undrop_table(&mut self, _stmt: &mut UndropTableStmt) {}
fn visit_alter_table(&mut self, _stmt: &mut AlterTableStmt) {}
fn visit_rename_table(&mut self, _stmt: &mut RenameTableStmt) {}
fn visit_truncate_table(&mut self, _stmt: &mut TruncateTableStmt) {}
fn visit_optimize_table(&mut self, _stmt: &mut OptimizeTableStmt) {}
fn visit_analyze_table(&mut self, _stmt: &mut AnalyzeTableStmt) {}
fn visit_exists_table(&mut self, _stmt: &mut ExistsTableStmt) {}
fn visit_create_view(&mut self, _stmt: &mut CreateViewStmt) {}
fn visit_alter_view(&mut self, _stmt: &mut AlterViewStmt) {}
fn visit_drop_view(&mut self, _stmt: &mut DropViewStmt) {}
fn visit_show_users(&mut self) {}
fn visit_create_user(&mut self, _stmt: &mut CreateUserStmt) {}
fn visit_alter_user(&mut self, _stmt: &mut AlterUserStmt) {}
fn visit_drop_user(&mut self, _if_exists: bool, _user: &mut UserIdentity) {}
fn visit_show_roles(&mut self) {}
fn visit_create_role(&mut self, _if_not_exists: bool, _role_name: &mut String) {}
fn visit_drop_role(&mut self, _if_exists: bool, _role_name: &mut String) {}
fn visit_grant(&mut self, _grant: &mut GrantStmt) {}
fn visit_show_grant(&mut self, _principal: &mut Option<PrincipalIdentity>) {}
fn visit_revoke(&mut self, _revoke: &mut RevokeStmt) {}
fn visit_create_udf(
&mut self,
_if_not_exists: bool,
_udf_name: &mut Identifier,
_parameters: &mut [Identifier],
_definition: &mut Expr,
_description: &mut Option<String>,
) {
}
fn visit_drop_udf(&mut self, _if_exists: bool, _udf_name: &mut Identifier) {}
fn visit_alter_udf(
&mut self,
_udf_name: &mut Identifier,
_parameters: &mut [Identifier],
_definition: &mut Expr,
_description: &mut Option<String>,
) {
}
fn visit_create_stage(&mut self, _stmt: &mut CreateStageStmt) {}
fn visit_show_stages(&mut self) {}
fn visit_drop_stage(&mut self, _if_exists: bool, _stage_name: &mut String) {}
fn visit_describe_stage(&mut self, _stage_name: &mut String) {}
fn visit_remove_stage(&mut self, _location: &mut String, _pattern: &mut String) {}
fn visit_list_stage(&mut self, _location: &mut String, _pattern: &mut String) {}
fn visit_create_file_format(
&mut self,
_if_not_exists: bool,
_name: &mut String,
_file_format_options: &mut FileFormatOptions,
) {
}
fn visit_drop_file_format(&mut self, _if_exists: bool, _name: &mut String) {}
fn visit_show_file_formats(&mut self) {}
fn visit_presign(&mut self, _presign: &mut PresignStmt) {}
fn visit_create_share(&mut self, _stmt: &mut CreateShareStmt) {}
fn visit_drop_share(&mut self, _stmt: &mut DropShareStmt) {}
fn visit_grant_share_object(&mut self, _stmt: &mut GrantShareObjectStmt) {}
fn visit_revoke_share_object(&mut self, _stmt: &mut RevokeShareObjectStmt) {}
fn visit_alter_share_tenants(&mut self, _stmt: &mut AlterShareTenantsStmt) {}
fn visit_desc_share(&mut self, _stmt: &mut DescShareStmt) {}
fn visit_show_shares(&mut self, _stmt: &mut ShowSharesStmt) {}
fn visit_show_object_grant_privileges(&mut self, _stmt: &mut ShowObjectGrantPrivilegesStmt) {}
fn visit_show_grants_of_share(&mut self, _stmt: &mut ShowGrantsOfShareStmt) {}
fn visit_with(&mut self, with: &mut With) {
let With { ctes, .. } = with;
for cte in ctes.iter_mut() {
walk_cte_mut(self, cte);
}
}
fn visit_set_expr(&mut self, expr: &mut SetExpr) {
walk_set_expr_mut(self, expr);
}
fn visit_set_operation(&mut self, op: &mut SetOperation) {
let SetOperation { left, right, .. } = op;
walk_set_expr_mut(self, left);
walk_set_expr_mut(self, right);
}
fn visit_order_by(&mut self, order_by: &mut OrderByExpr) {
let OrderByExpr { expr, .. } = order_by;
walk_expr_mut(self, expr);
}
fn visit_select_stmt(&mut self, stmt: &mut SelectStmt) {
let SelectStmt {
select_list,
from,
selection,
group_by,
having,
..
} = stmt;
for target in select_list.iter_mut() {
walk_select_target_mut(self, target);
}
for table_ref in from.iter_mut() {
walk_table_reference_mut(self, table_ref);
}
if let Some(selection) = selection {
walk_expr_mut(self, selection);
}
match group_by {
Some(GroupBy::Normal(exprs)) => {
for expr in exprs {
walk_expr_mut(self, expr);
}
}
Some(GroupBy::GroupingSets(sets)) => {
for set in sets {
for expr in set {
walk_expr_mut(self, expr);
}
}
}
_ => {}
}
if let Some(having) = having {
walk_expr_mut(self, having);
}
}
fn visit_select_target(&mut self, target: &mut SelectTarget) {
walk_select_target_mut(self, target);
}
fn visit_table_reference(&mut self, table: &mut TableReference) {
walk_table_reference_mut(self, table);
}
fn visit_time_travel_point(&mut self, time: &mut TimeTravelPoint) {
walk_time_travel_point_mut(self, time);
}
fn visit_join(&mut self, join: &mut Join) {
let Join {
left,
right,
condition,
..
} = join;
walk_table_reference_mut(self, left);
walk_table_reference_mut(self, right);
walk_join_condition_mut(self, condition);
}
}
|
#[doc = "Reader of register ISR"]
pub type R = crate::R<u32, super::ISR>;
#[doc = "Channel x transfer error flag (x = 1 ..7)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TEIF7_A {
#[doc = "0: No transfer error"]
NOERROR = 0,
#[doc = "1: A transfer error has occured"]
ERROR = 1,
}
impl From<TEIF7_A> for bool {
#[inline(always)]
fn from(variant: TEIF7_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TEIF7`"]
pub type TEIF7_R = crate::R<bool, TEIF7_A>;
impl TEIF7_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TEIF7_A {
match self.bits {
false => TEIF7_A::NOERROR,
true => TEIF7_A::ERROR,
}
}
#[doc = "Checks if the value of the field is `NOERROR`"]
#[inline(always)]
pub fn is_no_error(&self) -> bool {
*self == TEIF7_A::NOERROR
}
#[doc = "Checks if the value of the field is `ERROR`"]
#[inline(always)]
pub fn is_error(&self) -> bool {
*self == TEIF7_A::ERROR
}
}
#[doc = "Channel x half transfer flag (x = 1 ..7)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HTIF7_A {
#[doc = "0: No half transfer event"]
NOTHALF = 0,
#[doc = "1: A half transfer event has occured"]
HALF = 1,
}
impl From<HTIF7_A> for bool {
#[inline(always)]
fn from(variant: HTIF7_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `HTIF7`"]
pub type HTIF7_R = crate::R<bool, HTIF7_A>;
impl HTIF7_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> HTIF7_A {
match self.bits {
false => HTIF7_A::NOTHALF,
true => HTIF7_A::HALF,
}
}
#[doc = "Checks if the value of the field is `NOTHALF`"]
#[inline(always)]
pub fn is_not_half(&self) -> bool {
*self == HTIF7_A::NOTHALF
}
#[doc = "Checks if the value of the field is `HALF`"]
#[inline(always)]
pub fn is_half(&self) -> bool {
*self == HTIF7_A::HALF
}
}
#[doc = "Channel x transfer complete flag (x = 1 ..7)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TCIF7_A {
#[doc = "0: No transfer complete event"]
NOTCOMPLETE = 0,
#[doc = "1: A transfer complete event has occured"]
COMPLETE = 1,
}
impl From<TCIF7_A> for bool {
#[inline(always)]
fn from(variant: TCIF7_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TCIF7`"]
pub type TCIF7_R = crate::R<bool, TCIF7_A>;
impl TCIF7_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TCIF7_A {
match self.bits {
false => TCIF7_A::NOTCOMPLETE,
true => TCIF7_A::COMPLETE,
}
}
#[doc = "Checks if the value of the field is `NOTCOMPLETE`"]
#[inline(always)]
pub fn is_not_complete(&self) -> bool {
*self == TCIF7_A::NOTCOMPLETE
}
#[doc = "Checks if the value of the field is `COMPLETE`"]
#[inline(always)]
pub fn is_complete(&self) -> bool {
*self == TCIF7_A::COMPLETE
}
}
#[doc = "Channel x global interrupt flag (x = 1 ..7)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GIF7_A {
#[doc = "0: No transfer error, half event, complete event"]
NOEVENT = 0,
#[doc = "1: A transfer error, half event or complete event has occured"]
EVENT = 1,
}
impl From<GIF7_A> for bool {
#[inline(always)]
fn from(variant: GIF7_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `GIF7`"]
pub type GIF7_R = crate::R<bool, GIF7_A>;
impl GIF7_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> GIF7_A {
match self.bits {
false => GIF7_A::NOEVENT,
true => GIF7_A::EVENT,
}
}
#[doc = "Checks if the value of the field is `NOEVENT`"]
#[inline(always)]
pub fn is_no_event(&self) -> bool {
*self == GIF7_A::NOEVENT
}
#[doc = "Checks if the value of the field is `EVENT`"]
#[inline(always)]
pub fn is_event(&self) -> bool {
*self == GIF7_A::EVENT
}
}
#[doc = "Channel x transfer error flag (x = 1 ..7)"]
pub type TEIF6_A = TEIF7_A;
#[doc = "Reader of field `TEIF6`"]
pub type TEIF6_R = crate::R<bool, TEIF7_A>;
#[doc = "Channel x half transfer flag (x = 1 ..7)"]
pub type HTIF6_A = HTIF7_A;
#[doc = "Reader of field `HTIF6`"]
pub type HTIF6_R = crate::R<bool, HTIF7_A>;
#[doc = "Channel x transfer complete flag (x = 1 ..7)"]
pub type TCIF6_A = TCIF7_A;
#[doc = "Reader of field `TCIF6`"]
pub type TCIF6_R = crate::R<bool, TCIF7_A>;
#[doc = "Channel x global interrupt flag (x = 1 ..7)"]
pub type GIF6_A = GIF7_A;
#[doc = "Reader of field `GIF6`"]
pub type GIF6_R = crate::R<bool, GIF7_A>;
#[doc = "Channel x transfer error flag (x = 1 ..7)"]
pub type TEIF5_A = TEIF7_A;
#[doc = "Reader of field `TEIF5`"]
pub type TEIF5_R = crate::R<bool, TEIF7_A>;
#[doc = "Channel x half transfer flag (x = 1 ..7)"]
pub type HTIF5_A = HTIF7_A;
#[doc = "Reader of field `HTIF5`"]
pub type HTIF5_R = crate::R<bool, HTIF7_A>;
#[doc = "Channel x transfer complete flag (x = 1 ..7)"]
pub type TCIF5_A = TCIF7_A;
#[doc = "Reader of field `TCIF5`"]
pub type TCIF5_R = crate::R<bool, TCIF7_A>;
#[doc = "Channel x global interrupt flag (x = 1 ..7)"]
pub type GIF5_A = GIF7_A;
#[doc = "Reader of field `GIF5`"]
pub type GIF5_R = crate::R<bool, GIF7_A>;
#[doc = "Channel x transfer error flag (x = 1 ..7)"]
pub type TEIF4_A = TEIF7_A;
#[doc = "Reader of field `TEIF4`"]
pub type TEIF4_R = crate::R<bool, TEIF7_A>;
#[doc = "Channel x half transfer flag (x = 1 ..7)"]
pub type HTIF4_A = HTIF7_A;
#[doc = "Reader of field `HTIF4`"]
pub type HTIF4_R = crate::R<bool, HTIF7_A>;
#[doc = "Channel x transfer complete flag (x = 1 ..7)"]
pub type TCIF4_A = TCIF7_A;
#[doc = "Reader of field `TCIF4`"]
pub type TCIF4_R = crate::R<bool, TCIF7_A>;
#[doc = "Channel x global interrupt flag (x = 1 ..7)"]
pub type GIF4_A = GIF7_A;
#[doc = "Reader of field `GIF4`"]
pub type GIF4_R = crate::R<bool, GIF7_A>;
#[doc = "Channel x transfer error flag (x = 1 ..7)"]
pub type TEIF3_A = TEIF7_A;
#[doc = "Reader of field `TEIF3`"]
pub type TEIF3_R = crate::R<bool, TEIF7_A>;
#[doc = "Channel x half transfer flag (x = 1 ..7)"]
pub type HTIF3_A = HTIF7_A;
#[doc = "Reader of field `HTIF3`"]
pub type HTIF3_R = crate::R<bool, HTIF7_A>;
#[doc = "Channel x transfer complete flag (x = 1 ..7)"]
pub type TCIF3_A = TCIF7_A;
#[doc = "Reader of field `TCIF3`"]
pub type TCIF3_R = crate::R<bool, TCIF7_A>;
#[doc = "Channel x global interrupt flag (x = 1 ..7)"]
pub type GIF3_A = GIF7_A;
#[doc = "Reader of field `GIF3`"]
pub type GIF3_R = crate::R<bool, GIF7_A>;
#[doc = "Channel x transfer error flag (x = 1 ..7)"]
pub type TEIF2_A = TEIF7_A;
#[doc = "Reader of field `TEIF2`"]
pub type TEIF2_R = crate::R<bool, TEIF7_A>;
#[doc = "Channel x half transfer flag (x = 1 ..7)"]
pub type HTIF2_A = HTIF7_A;
#[doc = "Reader of field `HTIF2`"]
pub type HTIF2_R = crate::R<bool, HTIF7_A>;
#[doc = "Channel x transfer complete flag (x = 1 ..7)"]
pub type TCIF2_A = TCIF7_A;
#[doc = "Reader of field `TCIF2`"]
pub type TCIF2_R = crate::R<bool, TCIF7_A>;
#[doc = "Channel x global interrupt flag (x = 1 ..7)"]
pub type GIF2_A = GIF7_A;
#[doc = "Reader of field `GIF2`"]
pub type GIF2_R = crate::R<bool, GIF7_A>;
#[doc = "Channel x transfer error flag (x = 1 ..7)"]
pub type TEIF1_A = TEIF7_A;
#[doc = "Reader of field `TEIF1`"]
pub type TEIF1_R = crate::R<bool, TEIF7_A>;
#[doc = "Channel x half transfer flag (x = 1 ..7)"]
pub type HTIF1_A = HTIF7_A;
#[doc = "Reader of field `HTIF1`"]
pub type HTIF1_R = crate::R<bool, HTIF7_A>;
#[doc = "Channel x transfer complete flag (x = 1 ..7)"]
pub type TCIF1_A = TCIF7_A;
#[doc = "Reader of field `TCIF1`"]
pub type TCIF1_R = crate::R<bool, TCIF7_A>;
#[doc = "Channel x global interrupt flag (x = 1 ..7)"]
pub type GIF1_A = GIF7_A;
#[doc = "Reader of field `GIF1`"]
pub type GIF1_R = crate::R<bool, GIF7_A>;
impl R {
#[doc = "Bit 27 - Channel x transfer error flag (x = 1 ..7)"]
#[inline(always)]
pub fn teif7(&self) -> TEIF7_R {
TEIF7_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 26 - Channel x half transfer flag (x = 1 ..7)"]
#[inline(always)]
pub fn htif7(&self) -> HTIF7_R {
HTIF7_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 25 - Channel x transfer complete flag (x = 1 ..7)"]
#[inline(always)]
pub fn tcif7(&self) -> TCIF7_R {
TCIF7_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 24 - Channel x global interrupt flag (x = 1 ..7)"]
#[inline(always)]
pub fn gif7(&self) -> GIF7_R {
GIF7_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 23 - Channel x transfer error flag (x = 1 ..7)"]
#[inline(always)]
pub fn teif6(&self) -> TEIF6_R {
TEIF6_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 22 - Channel x half transfer flag (x = 1 ..7)"]
#[inline(always)]
pub fn htif6(&self) -> HTIF6_R {
HTIF6_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 21 - Channel x transfer complete flag (x = 1 ..7)"]
#[inline(always)]
pub fn tcif6(&self) -> TCIF6_R {
TCIF6_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 20 - Channel x global interrupt flag (x = 1 ..7)"]
#[inline(always)]
pub fn gif6(&self) -> GIF6_R {
GIF6_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 19 - Channel x transfer error flag (x = 1 ..7)"]
#[inline(always)]
pub fn teif5(&self) -> TEIF5_R {
TEIF5_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 18 - Channel x half transfer flag (x = 1 ..7)"]
#[inline(always)]
pub fn htif5(&self) -> HTIF5_R {
HTIF5_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 17 - Channel x transfer complete flag (x = 1 ..7)"]
#[inline(always)]
pub fn tcif5(&self) -> TCIF5_R {
TCIF5_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 16 - Channel x global interrupt flag (x = 1 ..7)"]
#[inline(always)]
pub fn gif5(&self) -> GIF5_R {
GIF5_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 15 - Channel x transfer error flag (x = 1 ..7)"]
#[inline(always)]
pub fn teif4(&self) -> TEIF4_R {
TEIF4_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 14 - Channel x half transfer flag (x = 1 ..7)"]
#[inline(always)]
pub fn htif4(&self) -> HTIF4_R {
HTIF4_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 13 - Channel x transfer complete flag (x = 1 ..7)"]
#[inline(always)]
pub fn tcif4(&self) -> TCIF4_R {
TCIF4_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 12 - Channel x global interrupt flag (x = 1 ..7)"]
#[inline(always)]
pub fn gif4(&self) -> GIF4_R {
GIF4_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 11 - Channel x transfer error flag (x = 1 ..7)"]
#[inline(always)]
pub fn teif3(&self) -> TEIF3_R {
TEIF3_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 10 - Channel x half transfer flag (x = 1 ..7)"]
#[inline(always)]
pub fn htif3(&self) -> HTIF3_R {
HTIF3_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 9 - Channel x transfer complete flag (x = 1 ..7)"]
#[inline(always)]
pub fn tcif3(&self) -> TCIF3_R {
TCIF3_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 8 - Channel x global interrupt flag (x = 1 ..7)"]
#[inline(always)]
pub fn gif3(&self) -> GIF3_R {
GIF3_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 7 - Channel x transfer error flag (x = 1 ..7)"]
#[inline(always)]
pub fn teif2(&self) -> TEIF2_R {
TEIF2_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 6 - Channel x half transfer flag (x = 1 ..7)"]
#[inline(always)]
pub fn htif2(&self) -> HTIF2_R {
HTIF2_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 5 - Channel x transfer complete flag (x = 1 ..7)"]
#[inline(always)]
pub fn tcif2(&self) -> TCIF2_R {
TCIF2_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4 - Channel x global interrupt flag (x = 1 ..7)"]
#[inline(always)]
pub fn gif2(&self) -> GIF2_R {
GIF2_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 3 - Channel x transfer error flag (x = 1 ..7)"]
#[inline(always)]
pub fn teif1(&self) -> TEIF1_R {
TEIF1_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 2 - Channel x half transfer flag (x = 1 ..7)"]
#[inline(always)]
pub fn htif1(&self) -> HTIF1_R {
HTIF1_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1 - Channel x transfer complete flag (x = 1 ..7)"]
#[inline(always)]
pub fn tcif1(&self) -> TCIF1_R {
TCIF1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - Channel x global interrupt flag (x = 1 ..7)"]
#[inline(always)]
pub fn gif1(&self) -> GIF1_R {
GIF1_R::new((self.bits & 0x01) != 0)
}
}
|
#[cfg(test)]
mod tests {
use super::connection_lib::*;
#[test]
fn test() {
macro_rules! assert_message_code {
($msg:expr, $res:expr) => {{
let msg = $msg;
let res = $res;
assert_eq!(msg.code(), res);
assert_eq!(Message::from_code(&res).code(), res);
}};
}
// from the protocol
assert_message_code!(
Message::Move(Move::Standard {
origin: Position::new(0, 1),
target: Position::new(0, 2),
}),
[0x01, 0x00, 0x08, 0x10]
);
assert_message_code!(
Message::Move(Move::Promotion {
origin: Position::new(1, 6),
target: Position::new(1, 7),
kind: PieceType::Queen,
}),
[0x01, 0x02, 0x31, 0x39, 0x03]
);
assert_message_code!(Message::Decline, [0x00]);
}
}
/// host: player who listens for a connection
/// host: white player, responsible for sending first move message
/// message: has to be minimum size in bytes
/// message: every one declinable with Decline
/// message: on unknown, respond with Decline
pub mod connection_lib {
#[derive(Debug)]
pub enum MessageType {
/// in response to illigal or unwanted action
Decline,
/// contains MoveType (as appended byte)
Move,
Undo,
/// in response to Undo or Draw
Accept,
/// in response to a Move that results in a checkmate
Checkmate,
/// in response to a Move that results in a draw, or to request a draw
Draw,
/// in response to a Move in order to resign the match
Resign,
}
#[derive(Debug)]
pub enum Message {
Decline,
Move(Move),
Undo,
Accept,
Checkmate,
Draw,
Resign,
}
impl Message {
pub fn get_type(&self) -> MessageType {
match self {
Self::Decline => MessageType::Decline,
Self::Move(_) => MessageType::Move,
Self::Undo => MessageType::Undo,
Self::Accept => MessageType::Accept,
Self::Checkmate => MessageType::Checkmate,
Self::Draw => MessageType::Draw,
Self::Resign => MessageType::Resign,
}
}
pub fn code(&self) -> Vec<u8> {
match self {
Message::Move(m) => {
let mut v = m.code();
v.insert(0, self.get_type().code());
v
}
_ => vec![self.get_type().code()],
}
}
pub fn from_code(code: &[u8]) -> Self {
let type_code = code.get(0).expect("faulty code for Message");
let r#type = MessageType::from_code(*type_code);
match r#type {
MessageType::Decline => Self::Decline,
MessageType::Move => Self::Move(Move::from_code(&code[1..])),
MessageType::Undo => Self::Undo,
MessageType::Accept => Self::Accept,
MessageType::Checkmate => Self::Checkmate,
MessageType::Draw => Self::Draw,
MessageType::Resign => Self::Resign,
}
}
}
impl MessageType {
pub fn code(&self) -> u8 {
match self {
Self::Decline => 0x00,
Self::Move => 0x01,
Self::Undo => 0x02,
Self::Accept => 0x03,
Self::Checkmate => 0x04,
Self::Draw => 0x05,
Self::Resign => 0x06,
}
}
pub fn from_code(code: u8) -> Self {
match code {
0x00 => Self::Decline,
0x01 => Self::Move,
0x02 => Self::Undo,
0x03 => Self::Accept,
0x04 => Self::Checkmate,
0x05 => Self::Draw,
0x06 => Self::Resign,
_ => panic!("falty code for MessageType"),
}
}
}
#[derive(Debug)]
pub enum MoveType {
Standard,
EnPassant,
Promotion,
CastleKingside,
CastleQueenside,
}
#[derive(Debug)]
pub struct Position {
pub x: u8,
pub y: u8,
}
impl Position {
pub fn new(x: u8, y: u8) -> Self {
Self { x, y }
}
pub fn code(&self) -> u8 {
(self.x & 0b111u8) | ((self.y << 3) & (0b111000u8))
}
pub fn from_code(code: u8) -> Self {
Self {
x: code & 0b111u8,
y: (code >> 3) & (0b111u8),
}
}
}
#[derive(Debug)]
pub enum Move {
Standard {
origin: Position,
target: Position,
},
EnPassant {
origin: Position,
target: Position,
},
Promotion {
origin: Position,
target: Position,
kind: PieceType,
},
CastleKingside,
CastleQueenside,
}
impl Move {
pub fn get_type(&self) -> MoveType {
match self {
Move::Standard {
origin: _,
target: _,
} => MoveType::Standard,
Move::EnPassant {
origin: _,
target: _,
} => MoveType::EnPassant,
Move::Promotion {
origin: _,
target: _,
kind: _,
} => MoveType::Promotion,
Move::CastleKingside => MoveType::CastleKingside,
Move::CastleQueenside => MoveType::CastleQueenside,
}
}
pub fn code(&self) -> Vec<u8> {
let mut data = vec![self.get_type().code()];
match self {
Move::Standard { origin, target } => {
data.push(origin.code());
data.push(target.code());
}
Move::EnPassant { origin, target } => {
data.push(origin.code());
data.push(target.code());
}
Move::Promotion {
origin,
target,
kind,
} => {
data.push(origin.code());
data.push(target.code());
data.push(kind.code());
}
Move::CastleKingside => (),
Move::CastleQueenside => (),
};
data
}
pub fn from_code(code: &[u8]) -> Self {
let type_code = code.get(0).expect("faulty code for Move");
let r#type = MoveType::from_code(*type_code);
match r#type {
MoveType::Standard => Self::Standard {
origin: Position::from_code(*code.get(1).expect("faulty code for Move, expected origin")),
target: Position::from_code(*code.get(2).expect("faulty code for Move, expected target")),
},
MoveType::EnPassant => Self::EnPassant {
origin: Position::from_code(*code.get(1).expect("faulty code for Move, expected origin")),
target: Position::from_code(*code.get(2).expect("faulty code for Move, expected target")),
},
MoveType::Promotion => Self::Promotion {
origin: Position::from_code(*code.get(1).expect("faulty code for Move, expected origin")),
target: Position::from_code(*code.get(2).expect("faulty code for Move, expected target")),
kind: PieceType::from_code(*code.get(3).expect("faulty code for Move, expected kind")),
},
MoveType::CastleKingside => Self::CastleKingside,
MoveType::CastleQueenside => Self::CastleQueenside,
}
}
}
impl MoveType {
pub fn code(&self) -> u8 {
match self {
Self::Standard => 0x00,
Self::EnPassant => 0x01,
Self::Promotion => 0x02,
Self::CastleKingside => 0x03,
Self::CastleQueenside => 0x04,
}
}
pub fn from_code(code: u8) -> Self {
match code {
0x00 => Self::Standard,
0x01 => Self::EnPassant,
0x02 => Self::Promotion,
0x03 => Self::CastleKingside,
0x04 => Self::CastleQueenside,
_ => panic!("invalid code for MoveType"),
}
}
}
#[derive(Debug)]
pub enum PieceType {
Knight,
Bishop,
Rook,
Queen,
}
impl PieceType {
pub fn code(&self) -> u8 {
match self {
Self::Knight => 0x00,
Self::Bishop => 0x01,
Self::Rook => 0x02,
Self::Queen => 0x03,
}
}
pub fn from_code(code: u8) -> Self {
match code {
0x00 => Self::Knight,
0x01 => Self::Bishop,
0x02 => Self::Rook,
0x03 => Self::Queen,
_ => panic!("invalid code for PieceType"),
}
}
}
}
|
fn dfs(i: usize, p: usize, g: &[Vec<usize>], par: &mut Vec<usize>) {
par[i] = p;
for &j in &g[i] {
if j != p {
dfs(j, i, g, par);
}
}
}
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let ab: Vec<(usize, usize)> = (0..(n - 1))
.map(|_| {
let a: usize = rd.get();
let b: usize = rd.get();
(a - 1, b - 1)
})
.collect();
let mut g = vec![vec![]; n];
for i in 0..(n - 1) {
let (a, b) = ab[i];
g[a].push(b);
g[b].push(a);
}
let mut par = vec![!0; n];
dfs(0, !0, &g, &mut par);
let mut ans = vec![0; n];
let q: usize = rd.get();
for _ in 0..q {
let t: usize = rd.get();
match t {
1 => {
let i: usize = rd.get();
let x: i64 = rd.get();
let (a, b) = ab[i - 1];
// a -> b
if par[a] == b {
ans[a] += x;
} else {
ans[0] += x;
ans[b] -= x;
}
}
2 => {
let i: usize = rd.get();
let x: i64 = rd.get();
let (a, b) = ab[i - 1];
// b -> a
if par[b] == a {
ans[b] += x;
} else {
ans[0] += x;
ans[a] -= x;
}
}
_ => unreachable!(),
}
}
// println!("{:?}", down);
use std::collections::VecDeque;
let mut q = VecDeque::new();
q.push_back((0, !0));
while let Some((i, p)) = q.pop_front() {
for &j in &g[i] {
if j != p {
ans[j] += ans[i];
q.push_back((j, i));
}
}
}
for ans in ans {
println!("{}", ans);
}
}
pub struct ProconReader<R> {
r: R,
line: String,
i: usize,
}
impl<R: std::io::BufRead> ProconReader<R> {
pub fn new(reader: R) -> Self {
Self {
r: reader,
line: String::new(),
i: 0,
}
}
pub fn get<T>(&mut self) -> T
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Debug,
{
self.skip_blanks();
assert!(self.i < self.line.len());
assert_ne!(&self.line[self.i..=self.i], " ");
let line = &self.line[self.i..];
let end = line.find(' ').unwrap_or_else(|| line.len());
let s = &line[..end];
self.i += end;
s.parse()
.unwrap_or_else(|_| panic!("parse error `{}`", self.line))
}
fn skip_blanks(&mut self) {
loop {
let start = self.line[self.i..].find(|ch| ch != ' ');
match start {
Some(j) => {
self.i += j;
break;
}
None => {
self.line.clear();
self.i = 0;
let num_bytes = self.r.read_line(&mut self.line).unwrap();
assert!(num_bytes > 0, "reached EOF :(");
self.line = self.line.trim_end_matches(&['\r', '\n'][..]).to_string();
}
}
}
}
pub fn get_vec<T>(&mut self, n: usize) -> Vec<T>
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Debug,
{
(0..n).map(|_| self.get()).collect()
}
}
|
//! Handles configuration
use serde::Deserialize;
use std::{collections::HashMap, fs::read_to_string, path::PathBuf};
use crate::IronCarrierError;
fn default_port() -> u32 {
8090
}
fn default_enable_watcher() -> bool {
true
}
fn default_watcher_debounce() -> u64 {
10
}
// Represents file names and paths that should be ignored
#[derive(Clone, PartialEq, Deserialize)]
pub struct Ignore {
pub name: Option<Vec<String>>,
pub path: Option<Vec<String>>,
}
const MAX_PORT: u32 = 65535;
/// Represents the configuration for the current machine
#[derive(Deserialize)]
pub struct Config {
/// Contains the folder that will be watched for synchronization
/// **Key** is the path alias
/// **Value** is the path itself
pub paths: HashMap<String, PathBuf>,
/// contains the address for the other peers
/// in the format IPV4:PORT (**192.168.1.1:9090**)
pub peers: Option<Vec<String>>,
/// contains files and paths to ignore
/// with glob support
pub ignore: Ignore,
/// Port to listen to connections, defaults to 8090
#[serde(default = "default_port")]
pub port: u32,
/// Enable file watchers for real time syncs, defaults to true
#[serde(default = "default_enable_watcher")]
pub enable_file_watcher: bool,
/// Seconds to debounce file events, defaults to 10 seconds
#[serde(default = "default_watcher_debounce")]
pub delay_watcher_events: u64,
}
impl Config {
/// creates a new [Config] reading the contents from the given path
///
/// [Ok]`(`[Config]`)` if successful
/// [IronCarrierError::ConfigFileNotFound] if the provided path doesn't exists
/// [IronCarrierError::ConfigFileIsInvalid] if the provided configuration is not valid
pub fn new(config_path: &str) -> crate::Result<Self> {
log::debug!("reading config file {}", config_path);
Config::parse_content(read_to_string(config_path)?)
}
/// Parses the given content into [Config]
pub(crate) fn parse_content(content: String) -> crate::Result<Self> {
toml::from_str::<Config>(&content)?.validate()
}
fn validate(self) -> crate::Result<Self> {
if 0 == self.port || self.port > MAX_PORT {
log::error!("Invalid port number");
return Err(IronCarrierError::ConfigFileIsInvalid("invalid port number".into()).into());
}
for (alias, path) in &self.paths {
if !path.exists() {
log::info!("creating directory for alias {}", alias);
std::fs::create_dir_all(path)?;
}
if !path.is_dir() {
log::error!("provided path for alias {} is invalid", alias);
return Err(IronCarrierError::ConfigFileIsInvalid(format!(
"invalid path: {}",
alias
))
.into());
}
}
Ok(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn can_parse_config() -> crate::Result<()> {
let config_content = "
peers = [
\"127.0.0.1:8888\"
]
[paths]
a = \"./tmp\"
"
.to_owned();
let config = Config::parse_content(config_content)?;
let peers = config.peers.unwrap();
assert_eq!(1, peers.len());
assert_eq!("127.0.0.1:8888", peers[0]);
let paths = config.paths;
assert_eq!(1, paths.len());
assert_eq!(PathBuf::from("./tmp"), paths["a"]);
Ok(())
}
}
|
// Copyright 2020-2021, The Tremor Team
//
// 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.
// This file is urely for testing w/ EQC
#![cfg(not(tarpaulin_include))]
use crate::prelude::*;
use crate::{
errors::{Error, Result},
registry::{self, Registry},
script::{AggrType, Return, Script},
EventContext, Value,
};
use std::ffi::CStr;
use std::os::raw::c_char;
use std::ptr;
fn eval(src: &str) -> Result<String> {
let reg: Registry = registry::registry();
// let aggr_reg: AggrRegistry = registry::aggr_registry();
let script = Script::parse(&crate::path::load(), "<eval>", src.to_string(), ®)
.map_err(|e| e.error)?;
let mut event = Value::object();
let mut meta = Value::object();
let mut state = Value::null();
let value = script.run(
&EventContext::new(0, None),
AggrType::Emit,
&mut event,
&mut state,
&mut meta,
)?;
Ok(match value {
Return::Drop => String::from(r#"{"drop": null}"#),
Return::Emit { value, .. } => format!(r#"{{"emit": {}}}"#, value.encode()),
Return::EmitEvent { .. } => format!(r#"{{"emit": {}}}"#, event.encode()),
})
}
#[no_mangle]
pub extern "C" fn tremor_script_c_eval(script: *const c_char, dst: *mut u8, len: usize) -> usize {
let cstr = unsafe { CStr::from_ptr(script) };
match cstr
.to_str()
.map_err(Error::from)
.and_then(|ref mut s| eval(s))
{
Ok(result) => {
if result.len() < len {
unsafe {
let src = result.as_ptr().cast::<u8>();
ptr::copy_nonoverlapping(src, dst, result.len());
*dst.add(result.len()) = 0;
0
}
} else {
result.len()
}
}
Err(e) => {
eprintln!("ERROR: {}", e);
1
}
}
}
|
#![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 ActivateActCtx(hactctx: super::super::Foundation::HANDLE, lpcookie: *mut usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn AddRefActCtx(hactctx: super::super::Foundation::HANDLE);
#[cfg(feature = "Win32_Foundation")]
pub fn ApplyDeltaA(applyflags: i64, lpsourcename: super::super::Foundation::PSTR, lpdeltaname: super::super::Foundation::PSTR, lptargetname: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ApplyDeltaB(applyflags: i64, source: DELTA_INPUT, delta: DELTA_INPUT, lptarget: *mut DELTA_OUTPUT) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ApplyDeltaGetReverseB(applyflags: i64, source: DELTA_INPUT, delta: DELTA_INPUT, lpreversefiletime: *const super::super::Foundation::FILETIME, lptarget: *mut DELTA_OUTPUT, lptargetreverse: *mut DELTA_OUTPUT) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ApplyDeltaProvidedB(applyflags: i64, source: DELTA_INPUT, delta: DELTA_INPUT, lptarget: *mut ::core::ffi::c_void, utargetsize: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ApplyDeltaW(applyflags: i64, lpsourcename: super::super::Foundation::PWSTR, lpdeltaname: super::super::Foundation::PWSTR, lptargetname: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ApplyPatchToFileA(patchfilename: super::super::Foundation::PSTR, oldfilename: super::super::Foundation::PSTR, newfilename: super::super::Foundation::PSTR, applyoptionflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ApplyPatchToFileByBuffers(patchfilemapped: *const u8, patchfilesize: u32, oldfilemapped: *const u8, oldfilesize: u32, newfilebuffer: *mut *mut u8, newfilebuffersize: u32, newfileactualsize: *mut u32, newfiletime: *mut super::super::Foundation::FILETIME, applyoptionflags: u32, progresscallback: PPATCH_PROGRESS_CALLBACK, callbackcontext: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ApplyPatchToFileByHandles(patchfilehandle: super::super::Foundation::HANDLE, oldfilehandle: super::super::Foundation::HANDLE, newfilehandle: super::super::Foundation::HANDLE, applyoptionflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ApplyPatchToFileByHandlesEx(patchfilehandle: super::super::Foundation::HANDLE, oldfilehandle: super::super::Foundation::HANDLE, newfilehandle: super::super::Foundation::HANDLE, applyoptionflags: u32, progresscallback: PPATCH_PROGRESS_CALLBACK, callbackcontext: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ApplyPatchToFileExA(patchfilename: super::super::Foundation::PSTR, oldfilename: super::super::Foundation::PSTR, newfilename: super::super::Foundation::PSTR, applyoptionflags: u32, progresscallback: PPATCH_PROGRESS_CALLBACK, callbackcontext: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ApplyPatchToFileExW(patchfilename: super::super::Foundation::PWSTR, oldfilename: super::super::Foundation::PWSTR, newfilename: super::super::Foundation::PWSTR, applyoptionflags: u32, progresscallback: PPATCH_PROGRESS_CALLBACK, callbackcontext: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ApplyPatchToFileW(patchfilename: super::super::Foundation::PWSTR, oldfilename: super::super::Foundation::PWSTR, newfilename: super::super::Foundation::PWSTR, applyoptionflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreateActCtxA(pactctx: *const ACTCTXA) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn CreateActCtxW(pactctx: *const ACTCTXW) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn CreateDeltaA(filetypeset: i64, setflags: i64, resetflags: i64, lpsourcename: super::super::Foundation::PSTR, lptargetname: super::super::Foundation::PSTR, lpsourceoptionsname: super::super::Foundation::PSTR, lptargetoptionsname: super::super::Foundation::PSTR, globaloptions: DELTA_INPUT, lptargetfiletime: *const super::super::Foundation::FILETIME, hashalgid: u32, lpdeltaname: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreateDeltaB(filetypeset: i64, setflags: i64, resetflags: i64, source: DELTA_INPUT, target: DELTA_INPUT, sourceoptions: DELTA_INPUT, targetoptions: DELTA_INPUT, globaloptions: DELTA_INPUT, lptargetfiletime: *const super::super::Foundation::FILETIME, hashalgid: u32, lpdelta: *mut DELTA_OUTPUT) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreateDeltaW(filetypeset: i64, setflags: i64, resetflags: i64, lpsourcename: super::super::Foundation::PWSTR, lptargetname: super::super::Foundation::PWSTR, lpsourceoptionsname: super::super::Foundation::PWSTR, lptargetoptionsname: super::super::Foundation::PWSTR, globaloptions: DELTA_INPUT, lptargetfiletime: *const super::super::Foundation::FILETIME, hashalgid: u32, lpdeltaname: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreatePatchFileA(oldfilename: super::super::Foundation::PSTR, newfilename: super::super::Foundation::PSTR, patchfilename: super::super::Foundation::PSTR, optionflags: u32, optiondata: *const PATCH_OPTION_DATA) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreatePatchFileByHandles(oldfilehandle: super::super::Foundation::HANDLE, newfilehandle: super::super::Foundation::HANDLE, patchfilehandle: super::super::Foundation::HANDLE, optionflags: u32, optiondata: *const PATCH_OPTION_DATA) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreatePatchFileByHandlesEx(oldfilecount: u32, oldfileinfoarray: *const PATCH_OLD_FILE_INFO_H, newfilehandle: super::super::Foundation::HANDLE, patchfilehandle: super::super::Foundation::HANDLE, optionflags: u32, optiondata: *const PATCH_OPTION_DATA, progresscallback: PPATCH_PROGRESS_CALLBACK, callbackcontext: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreatePatchFileExA(oldfilecount: u32, oldfileinfoarray: *const PATCH_OLD_FILE_INFO_A, newfilename: super::super::Foundation::PSTR, patchfilename: super::super::Foundation::PSTR, optionflags: u32, optiondata: *const PATCH_OPTION_DATA, progresscallback: PPATCH_PROGRESS_CALLBACK, callbackcontext: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreatePatchFileExW(oldfilecount: u32, oldfileinfoarray: *const PATCH_OLD_FILE_INFO_W, newfilename: super::super::Foundation::PWSTR, patchfilename: super::super::Foundation::PWSTR, optionflags: u32, optiondata: *const PATCH_OPTION_DATA, progresscallback: PPATCH_PROGRESS_CALLBACK, callbackcontext: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreatePatchFileW(oldfilename: super::super::Foundation::PWSTR, newfilename: super::super::Foundation::PWSTR, patchfilename: super::super::Foundation::PWSTR, optionflags: u32, optiondata: *const PATCH_OPTION_DATA) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DeactivateActCtx(dwflags: u32, ulcookie: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DeltaFree(lpmemory: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DeltaNormalizeProvidedB(filetypeset: i64, normalizeflags: i64, normalizeoptions: DELTA_INPUT, lpsource: *mut ::core::ffi::c_void, usourcesize: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ExtractPatchHeaderToFileA(patchfilename: super::super::Foundation::PSTR, patchheaderfilename: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ExtractPatchHeaderToFileByHandles(patchfilehandle: super::super::Foundation::HANDLE, patchheaderfilehandle: super::super::Foundation::HANDLE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ExtractPatchHeaderToFileW(patchfilename: super::super::Foundation::PWSTR, patchheaderfilename: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_WindowsProgramming"))]
pub fn FindActCtxSectionGuid(dwflags: u32, lpextensionguid: *const ::windows_sys::core::GUID, ulsectionid: u32, lpguidtofind: *const ::windows_sys::core::GUID, returneddata: *mut ACTCTX_SECTION_KEYED_DATA) -> super::super::Foundation::BOOL;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_WindowsProgramming"))]
pub fn FindActCtxSectionStringA(dwflags: u32, lpextensionguid: *const ::windows_sys::core::GUID, ulsectionid: u32, lpstringtofind: super::super::Foundation::PSTR, returneddata: *mut ACTCTX_SECTION_KEYED_DATA) -> super::super::Foundation::BOOL;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_WindowsProgramming"))]
pub fn FindActCtxSectionStringW(dwflags: u32, lpextensionguid: *const ::windows_sys::core::GUID, ulsectionid: u32, lpstringtofind: super::super::Foundation::PWSTR, returneddata: *mut ACTCTX_SECTION_KEYED_DATA) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetCurrentActCtx(lphactctx: *mut super::super::Foundation::HANDLE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetDeltaInfoA(lpdeltaname: super::super::Foundation::PSTR, lpheaderinfo: *mut DELTA_HEADER_INFO) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetDeltaInfoB(delta: DELTA_INPUT, lpheaderinfo: *mut DELTA_HEADER_INFO) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetDeltaInfoW(lpdeltaname: super::super::Foundation::PWSTR, lpheaderinfo: *mut DELTA_HEADER_INFO) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetDeltaSignatureA(filetypeset: i64, hashalgid: u32, lpsourcename: super::super::Foundation::PSTR, lphash: *mut DELTA_HASH) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetDeltaSignatureB(filetypeset: i64, hashalgid: u32, source: DELTA_INPUT, lphash: *mut DELTA_HASH) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetDeltaSignatureW(filetypeset: i64, hashalgid: u32, lpsourcename: super::super::Foundation::PWSTR, lphash: *mut DELTA_HASH) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetFilePatchSignatureA(filename: super::super::Foundation::PSTR, optionflags: u32, optiondata: *const ::core::ffi::c_void, ignorerangecount: u32, ignorerangearray: *const PATCH_IGNORE_RANGE, retainrangecount: u32, retainrangearray: *const PATCH_RETAIN_RANGE, signaturebuffersize: u32, signaturebuffer: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetFilePatchSignatureByBuffer(filebufferwritable: *mut u8, filesize: u32, optionflags: u32, optiondata: *const ::core::ffi::c_void, ignorerangecount: u32, ignorerangearray: *const PATCH_IGNORE_RANGE, retainrangecount: u32, retainrangearray: *const PATCH_RETAIN_RANGE, signaturebuffersize: u32, signaturebuffer: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetFilePatchSignatureByHandle(filehandle: super::super::Foundation::HANDLE, optionflags: u32, optiondata: *const ::core::ffi::c_void, ignorerangecount: u32, ignorerangearray: *const PATCH_IGNORE_RANGE, retainrangecount: u32, retainrangearray: *const PATCH_RETAIN_RANGE, signaturebuffersize: u32, signaturebuffer: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetFilePatchSignatureW(filename: super::super::Foundation::PWSTR, optionflags: u32, optiondata: *const ::core::ffi::c_void, ignorerangecount: u32, ignorerangearray: *const PATCH_IGNORE_RANGE, retainrangecount: u32, retainrangearray: *const PATCH_RETAIN_RANGE, signaturebuffersize: u32, signaturebuffer: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiAdvertiseProductA(szpackagepath: super::super::Foundation::PSTR, szscriptfilepath: super::super::Foundation::PSTR, sztransforms: super::super::Foundation::PSTR, lgidlanguage: u16) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiAdvertiseProductExA(szpackagepath: super::super::Foundation::PSTR, szscriptfilepath: super::super::Foundation::PSTR, sztransforms: super::super::Foundation::PSTR, lgidlanguage: u16, dwplatform: u32, dwoptions: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiAdvertiseProductExW(szpackagepath: super::super::Foundation::PWSTR, szscriptfilepath: super::super::Foundation::PWSTR, sztransforms: super::super::Foundation::PWSTR, lgidlanguage: u16, dwplatform: u32, dwoptions: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiAdvertiseProductW(szpackagepath: super::super::Foundation::PWSTR, szscriptfilepath: super::super::Foundation::PWSTR, sztransforms: super::super::Foundation::PWSTR, lgidlanguage: u16) -> u32;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry"))]
pub fn MsiAdvertiseScriptA(szscriptfile: super::super::Foundation::PSTR, dwflags: u32, phregdata: *const super::Registry::HKEY, fremoveitems: super::super::Foundation::BOOL) -> u32;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry"))]
pub fn MsiAdvertiseScriptW(szscriptfile: super::super::Foundation::PWSTR, dwflags: u32, phregdata: *const super::Registry::HKEY, fremoveitems: super::super::Foundation::BOOL) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiApplyMultiplePatchesA(szpatchpackages: super::super::Foundation::PSTR, szproductcode: super::super::Foundation::PSTR, szpropertieslist: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiApplyMultiplePatchesW(szpatchpackages: super::super::Foundation::PWSTR, szproductcode: super::super::Foundation::PWSTR, szpropertieslist: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiApplyPatchA(szpatchpackage: super::super::Foundation::PSTR, szinstallpackage: super::super::Foundation::PSTR, einstalltype: INSTALLTYPE, szcommandline: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiApplyPatchW(szpatchpackage: super::super::Foundation::PWSTR, szinstallpackage: super::super::Foundation::PWSTR, einstalltype: INSTALLTYPE, szcommandline: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiBeginTransactionA(szname: super::super::Foundation::PSTR, dwtransactionattributes: u32, phtransactionhandle: *mut MSIHANDLE, phchangeofownerevent: *mut super::super::Foundation::HANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiBeginTransactionW(szname: super::super::Foundation::PWSTR, dwtransactionattributes: u32, phtransactionhandle: *mut MSIHANDLE, phchangeofownerevent: *mut super::super::Foundation::HANDLE) -> u32;
pub fn MsiCloseAllHandles() -> u32;
pub fn MsiCloseHandle(hany: MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiCollectUserInfoA(szproduct: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiCollectUserInfoW(szproduct: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiConfigureFeatureA(szproduct: super::super::Foundation::PSTR, szfeature: super::super::Foundation::PSTR, einstallstate: INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiConfigureFeatureW(szproduct: super::super::Foundation::PWSTR, szfeature: super::super::Foundation::PWSTR, einstallstate: INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiConfigureProductA(szproduct: super::super::Foundation::PSTR, iinstalllevel: INSTALLLEVEL, einstallstate: INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiConfigureProductExA(szproduct: super::super::Foundation::PSTR, iinstalllevel: INSTALLLEVEL, einstallstate: INSTALLSTATE, szcommandline: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiConfigureProductExW(szproduct: super::super::Foundation::PWSTR, iinstalllevel: INSTALLLEVEL, einstallstate: INSTALLSTATE, szcommandline: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiConfigureProductW(szproduct: super::super::Foundation::PWSTR, iinstalllevel: INSTALLLEVEL, einstallstate: INSTALLSTATE) -> u32;
pub fn MsiCreateRecord(cparams: u32) -> MSIHANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiCreateTransformSummaryInfoA(hdatabase: MSIHANDLE, hdatabasereference: MSIHANDLE, sztransformfile: super::super::Foundation::PSTR, ierrorconditions: MSITRANSFORM_ERROR, ivalidation: MSITRANSFORM_VALIDATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiCreateTransformSummaryInfoW(hdatabase: MSIHANDLE, hdatabasereference: MSIHANDLE, sztransformfile: super::super::Foundation::PWSTR, ierrorconditions: MSITRANSFORM_ERROR, ivalidation: MSITRANSFORM_VALIDATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseApplyTransformA(hdatabase: MSIHANDLE, sztransformfile: super::super::Foundation::PSTR, ierrorconditions: MSITRANSFORM_ERROR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseApplyTransformW(hdatabase: MSIHANDLE, sztransformfile: super::super::Foundation::PWSTR, ierrorconditions: MSITRANSFORM_ERROR) -> u32;
pub fn MsiDatabaseCommit(hdatabase: MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseExportA(hdatabase: MSIHANDLE, sztablename: super::super::Foundation::PSTR, szfolderpath: super::super::Foundation::PSTR, szfilename: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseExportW(hdatabase: MSIHANDLE, sztablename: super::super::Foundation::PWSTR, szfolderpath: super::super::Foundation::PWSTR, szfilename: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseGenerateTransformA(hdatabase: MSIHANDLE, hdatabasereference: MSIHANDLE, sztransformfile: super::super::Foundation::PSTR, ireserved1: i32, ireserved2: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseGenerateTransformW(hdatabase: MSIHANDLE, hdatabasereference: MSIHANDLE, sztransformfile: super::super::Foundation::PWSTR, ireserved1: i32, ireserved2: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseGetPrimaryKeysA(hdatabase: MSIHANDLE, sztablename: super::super::Foundation::PSTR, phrecord: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseGetPrimaryKeysW(hdatabase: MSIHANDLE, sztablename: super::super::Foundation::PWSTR, phrecord: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseImportA(hdatabase: MSIHANDLE, szfolderpath: super::super::Foundation::PSTR, szfilename: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseImportW(hdatabase: MSIHANDLE, szfolderpath: super::super::Foundation::PWSTR, szfilename: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseIsTablePersistentA(hdatabase: MSIHANDLE, sztablename: super::super::Foundation::PSTR) -> MSICONDITION;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseIsTablePersistentW(hdatabase: MSIHANDLE, sztablename: super::super::Foundation::PWSTR) -> MSICONDITION;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseMergeA(hdatabase: MSIHANDLE, hdatabasemerge: MSIHANDLE, sztablename: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseMergeW(hdatabase: MSIHANDLE, hdatabasemerge: MSIHANDLE, sztablename: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseOpenViewA(hdatabase: MSIHANDLE, szquery: super::super::Foundation::PSTR, phview: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDatabaseOpenViewW(hdatabase: MSIHANDLE, szquery: super::super::Foundation::PWSTR, phview: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDetermineApplicablePatchesA(szproductpackagepath: super::super::Foundation::PSTR, cpatchinfo: u32, ppatchinfo: *mut MSIPATCHSEQUENCEINFOA) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDetermineApplicablePatchesW(szproductpackagepath: super::super::Foundation::PWSTR, cpatchinfo: u32, ppatchinfo: *mut MSIPATCHSEQUENCEINFOW) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDeterminePatchSequenceA(szproductcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, cpatchinfo: u32, ppatchinfo: *mut MSIPATCHSEQUENCEINFOA) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDeterminePatchSequenceW(szproductcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, cpatchinfo: u32, ppatchinfo: *mut MSIPATCHSEQUENCEINFOW) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDoActionA(hinstall: MSIHANDLE, szaction: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiDoActionW(hinstall: MSIHANDLE, szaction: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnableLogA(dwlogmode: INSTALLOGMODE, szlogfile: super::super::Foundation::PSTR, dwlogattributes: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnableLogW(dwlogmode: INSTALLOGMODE, szlogfile: super::super::Foundation::PWSTR, dwlogattributes: u32) -> u32;
pub fn MsiEnableUIPreview(hdatabase: MSIHANDLE, phpreview: *mut MSIHANDLE) -> u32;
pub fn MsiEndTransaction(dwtransactionstate: MSITRANSACTIONSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumClientsA(szcomponent: super::super::Foundation::PSTR, iproductindex: u32, lpproductbuf: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumClientsExA(szcomponent: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, dwproductindex: u32, szproductbuf: super::super::Foundation::PSTR, pdwinstalledcontext: *mut MSIINSTALLCONTEXT, szsid: super::super::Foundation::PSTR, pcchsid: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumClientsExW(szcomponent: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, dwproductindex: u32, szproductbuf: super::super::Foundation::PWSTR, pdwinstalledcontext: *mut MSIINSTALLCONTEXT, szsid: super::super::Foundation::PWSTR, pcchsid: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumClientsW(szcomponent: super::super::Foundation::PWSTR, iproductindex: u32, lpproductbuf: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumComponentCostsA(hinstall: MSIHANDLE, szcomponent: super::super::Foundation::PSTR, dwindex: u32, istate: INSTALLSTATE, szdrivebuf: super::super::Foundation::PSTR, pcchdrivebuf: *mut u32, picost: *mut i32, pitempcost: *mut i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumComponentCostsW(hinstall: MSIHANDLE, szcomponent: super::super::Foundation::PWSTR, dwindex: u32, istate: INSTALLSTATE, szdrivebuf: super::super::Foundation::PWSTR, pcchdrivebuf: *mut u32, picost: *mut i32, pitempcost: *mut i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumComponentQualifiersA(szcomponent: super::super::Foundation::PSTR, iindex: u32, lpqualifierbuf: super::super::Foundation::PSTR, pcchqualifierbuf: *mut u32, lpapplicationdatabuf: super::super::Foundation::PSTR, pcchapplicationdatabuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumComponentQualifiersW(szcomponent: super::super::Foundation::PWSTR, iindex: u32, lpqualifierbuf: super::super::Foundation::PWSTR, pcchqualifierbuf: *mut u32, lpapplicationdatabuf: super::super::Foundation::PWSTR, pcchapplicationdatabuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumComponentsA(icomponentindex: u32, lpcomponentbuf: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumComponentsExA(szusersid: super::super::Foundation::PSTR, dwcontext: u32, dwindex: u32, szinstalledcomponentcode: super::super::Foundation::PSTR, pdwinstalledcontext: *mut MSIINSTALLCONTEXT, szsid: super::super::Foundation::PSTR, pcchsid: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumComponentsExW(szusersid: super::super::Foundation::PWSTR, dwcontext: u32, dwindex: u32, szinstalledcomponentcode: super::super::Foundation::PWSTR, pdwinstalledcontext: *mut MSIINSTALLCONTEXT, szsid: super::super::Foundation::PWSTR, pcchsid: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumComponentsW(icomponentindex: u32, lpcomponentbuf: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumFeaturesA(szproduct: super::super::Foundation::PSTR, ifeatureindex: u32, lpfeaturebuf: super::super::Foundation::PSTR, lpparentbuf: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumFeaturesW(szproduct: super::super::Foundation::PWSTR, ifeatureindex: u32, lpfeaturebuf: super::super::Foundation::PWSTR, lpparentbuf: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumPatchesA(szproduct: super::super::Foundation::PSTR, ipatchindex: u32, lppatchbuf: super::super::Foundation::PSTR, lptransformsbuf: super::super::Foundation::PSTR, pcchtransformsbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumPatchesExA(szproductcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: u32, dwfilter: u32, dwindex: u32, szpatchcode: super::super::Foundation::PSTR, sztargetproductcode: super::super::Foundation::PSTR, pdwtargetproductcontext: *mut MSIINSTALLCONTEXT, sztargetusersid: super::super::Foundation::PSTR, pcchtargetusersid: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumPatchesExW(szproductcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: u32, dwfilter: u32, dwindex: u32, szpatchcode: super::super::Foundation::PWSTR, sztargetproductcode: super::super::Foundation::PWSTR, pdwtargetproductcontext: *mut MSIINSTALLCONTEXT, sztargetusersid: super::super::Foundation::PWSTR, pcchtargetusersid: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumPatchesW(szproduct: super::super::Foundation::PWSTR, ipatchindex: u32, lppatchbuf: super::super::Foundation::PWSTR, lptransformsbuf: super::super::Foundation::PWSTR, pcchtransformsbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumProductsA(iproductindex: u32, lpproductbuf: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumProductsExA(szproductcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: u32, dwindex: u32, szinstalledproductcode: super::super::Foundation::PSTR, pdwinstalledcontext: *mut MSIINSTALLCONTEXT, szsid: super::super::Foundation::PSTR, pcchsid: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumProductsExW(szproductcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: u32, dwindex: u32, szinstalledproductcode: super::super::Foundation::PWSTR, pdwinstalledcontext: *mut MSIINSTALLCONTEXT, szsid: super::super::Foundation::PWSTR, pcchsid: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumProductsW(iproductindex: u32, lpproductbuf: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumRelatedProductsA(lpupgradecode: super::super::Foundation::PSTR, dwreserved: u32, iproductindex: u32, lpproductbuf: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEnumRelatedProductsW(lpupgradecode: super::super::Foundation::PWSTR, dwreserved: u32, iproductindex: u32, lpproductbuf: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEvaluateConditionA(hinstall: MSIHANDLE, szcondition: super::super::Foundation::PSTR) -> MSICONDITION;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiEvaluateConditionW(hinstall: MSIHANDLE, szcondition: super::super::Foundation::PWSTR) -> MSICONDITION;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiExtractPatchXMLDataA(szpatchpath: super::super::Foundation::PSTR, dwreserved: u32, szxmldata: super::super::Foundation::PSTR, pcchxmldata: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiExtractPatchXMLDataW(szpatchpath: super::super::Foundation::PWSTR, dwreserved: u32, szxmldata: super::super::Foundation::PWSTR, pcchxmldata: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiFormatRecordA(hinstall: MSIHANDLE, hrecord: MSIHANDLE, szresultbuf: super::super::Foundation::PSTR, pcchresultbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiFormatRecordW(hinstall: MSIHANDLE, hrecord: MSIHANDLE, szresultbuf: super::super::Foundation::PWSTR, pcchresultbuf: *mut u32) -> u32;
pub fn MsiGetActiveDatabase(hinstall: MSIHANDLE) -> MSIHANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetComponentPathA(szproduct: super::super::Foundation::PSTR, szcomponent: super::super::Foundation::PSTR, lppathbuf: super::super::Foundation::PSTR, pcchbuf: *mut u32) -> INSTALLSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetComponentPathExA(szproductcode: super::super::Foundation::PSTR, szcomponentcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, lpoutpathbuffer: super::super::Foundation::PSTR, pcchoutpathbuffer: *mut u32) -> INSTALLSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetComponentPathExW(szproductcode: super::super::Foundation::PWSTR, szcomponentcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, lpoutpathbuffer: super::super::Foundation::PWSTR, pcchoutpathbuffer: *mut u32) -> INSTALLSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetComponentPathW(szproduct: super::super::Foundation::PWSTR, szcomponent: super::super::Foundation::PWSTR, lppathbuf: super::super::Foundation::PWSTR, pcchbuf: *mut u32) -> INSTALLSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetComponentStateA(hinstall: MSIHANDLE, szcomponent: super::super::Foundation::PSTR, piinstalled: *mut INSTALLSTATE, piaction: *mut INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetComponentStateW(hinstall: MSIHANDLE, szcomponent: super::super::Foundation::PWSTR, piinstalled: *mut INSTALLSTATE, piaction: *mut INSTALLSTATE) -> u32;
pub fn MsiGetDatabaseState(hdatabase: MSIHANDLE) -> MSIDBSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFeatureCostA(hinstall: MSIHANDLE, szfeature: super::super::Foundation::PSTR, icosttree: MSICOSTTREE, istate: INSTALLSTATE, picost: *mut i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFeatureCostW(hinstall: MSIHANDLE, szfeature: super::super::Foundation::PWSTR, icosttree: MSICOSTTREE, istate: INSTALLSTATE, picost: *mut i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFeatureInfoA(hproduct: MSIHANDLE, szfeature: super::super::Foundation::PSTR, lpattributes: *mut u32, lptitlebuf: super::super::Foundation::PSTR, pcchtitlebuf: *mut u32, lphelpbuf: super::super::Foundation::PSTR, pcchhelpbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFeatureInfoW(hproduct: MSIHANDLE, szfeature: super::super::Foundation::PWSTR, lpattributes: *mut u32, lptitlebuf: super::super::Foundation::PWSTR, pcchtitlebuf: *mut u32, lphelpbuf: super::super::Foundation::PWSTR, pcchhelpbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFeatureStateA(hinstall: MSIHANDLE, szfeature: super::super::Foundation::PSTR, piinstalled: *mut INSTALLSTATE, piaction: *mut INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFeatureStateW(hinstall: MSIHANDLE, szfeature: super::super::Foundation::PWSTR, piinstalled: *mut INSTALLSTATE, piaction: *mut INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFeatureUsageA(szproduct: super::super::Foundation::PSTR, szfeature: super::super::Foundation::PSTR, pdwusecount: *mut u32, pwdateused: *mut u16) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFeatureUsageW(szproduct: super::super::Foundation::PWSTR, szfeature: super::super::Foundation::PWSTR, pdwusecount: *mut u32, pwdateused: *mut u16) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFeatureValidStatesA(hinstall: MSIHANDLE, szfeature: super::super::Foundation::PSTR, lpinstallstates: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFeatureValidStatesW(hinstall: MSIHANDLE, szfeature: super::super::Foundation::PWSTR, lpinstallstates: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFileHashA(szfilepath: super::super::Foundation::PSTR, dwoptions: u32, phash: *mut MSIFILEHASHINFO) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFileHashW(szfilepath: super::super::Foundation::PWSTR, dwoptions: u32, phash: *mut MSIFILEHASHINFO) -> u32;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography"))]
pub fn MsiGetFileSignatureInformationA(szsignedobjectpath: super::super::Foundation::PSTR, dwflags: u32, ppccertcontext: *mut *mut super::super::Security::Cryptography::CERT_CONTEXT, pbhashdata: *mut u8, pcbhashdata: *mut u32) -> ::windows_sys::core::HRESULT;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography"))]
pub fn MsiGetFileSignatureInformationW(szsignedobjectpath: super::super::Foundation::PWSTR, dwflags: u32, ppccertcontext: *mut *mut super::super::Security::Cryptography::CERT_CONTEXT, pbhashdata: *mut u8, pcbhashdata: *mut u32) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFileVersionA(szfilepath: super::super::Foundation::PSTR, lpversionbuf: super::super::Foundation::PSTR, pcchversionbuf: *mut u32, lplangbuf: super::super::Foundation::PSTR, pcchlangbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetFileVersionW(szfilepath: super::super::Foundation::PWSTR, lpversionbuf: super::super::Foundation::PWSTR, pcchversionbuf: *mut u32, lplangbuf: super::super::Foundation::PWSTR, pcchlangbuf: *mut u32) -> u32;
pub fn MsiGetLanguage(hinstall: MSIHANDLE) -> u16;
pub fn MsiGetLastErrorRecord() -> MSIHANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetMode(hinstall: MSIHANDLE, erunmode: MSIRUNMODE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetPatchFileListA(szproductcode: super::super::Foundation::PSTR, szpatchpackages: super::super::Foundation::PSTR, pcfiles: *mut u32, pphfilerecords: *mut *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetPatchFileListW(szproductcode: super::super::Foundation::PWSTR, szpatchpackages: super::super::Foundation::PWSTR, pcfiles: *mut u32, pphfilerecords: *mut *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetPatchInfoA(szpatch: super::super::Foundation::PSTR, szattribute: super::super::Foundation::PSTR, lpvaluebuf: super::super::Foundation::PSTR, pcchvaluebuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetPatchInfoExA(szpatchcode: super::super::Foundation::PSTR, szproductcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, szproperty: super::super::Foundation::PSTR, lpvalue: super::super::Foundation::PSTR, pcchvalue: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetPatchInfoExW(szpatchcode: super::super::Foundation::PWSTR, szproductcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, szproperty: super::super::Foundation::PWSTR, lpvalue: super::super::Foundation::PWSTR, pcchvalue: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetPatchInfoW(szpatch: super::super::Foundation::PWSTR, szattribute: super::super::Foundation::PWSTR, lpvaluebuf: super::super::Foundation::PWSTR, pcchvaluebuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetProductCodeA(szcomponent: super::super::Foundation::PSTR, lpbuf39: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetProductCodeW(szcomponent: super::super::Foundation::PWSTR, lpbuf39: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetProductInfoA(szproduct: super::super::Foundation::PSTR, szattribute: super::super::Foundation::PSTR, lpvaluebuf: super::super::Foundation::PSTR, pcchvaluebuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetProductInfoExA(szproductcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, szproperty: super::super::Foundation::PSTR, szvalue: super::super::Foundation::PSTR, pcchvalue: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetProductInfoExW(szproductcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, szproperty: super::super::Foundation::PWSTR, szvalue: super::super::Foundation::PWSTR, pcchvalue: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetProductInfoFromScriptA(szscriptfile: super::super::Foundation::PSTR, lpproductbuf39: super::super::Foundation::PSTR, plgidlanguage: *mut u16, pdwversion: *mut u32, lpnamebuf: super::super::Foundation::PSTR, pcchnamebuf: *mut u32, lppackagebuf: super::super::Foundation::PSTR, pcchpackagebuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetProductInfoFromScriptW(szscriptfile: super::super::Foundation::PWSTR, lpproductbuf39: super::super::Foundation::PWSTR, plgidlanguage: *mut u16, pdwversion: *mut u32, lpnamebuf: super::super::Foundation::PWSTR, pcchnamebuf: *mut u32, lppackagebuf: super::super::Foundation::PWSTR, pcchpackagebuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetProductInfoW(szproduct: super::super::Foundation::PWSTR, szattribute: super::super::Foundation::PWSTR, lpvaluebuf: super::super::Foundation::PWSTR, pcchvaluebuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetProductPropertyA(hproduct: MSIHANDLE, szproperty: super::super::Foundation::PSTR, lpvaluebuf: super::super::Foundation::PSTR, pcchvaluebuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetProductPropertyW(hproduct: MSIHANDLE, szproperty: super::super::Foundation::PWSTR, lpvaluebuf: super::super::Foundation::PWSTR, pcchvaluebuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetPropertyA(hinstall: MSIHANDLE, szname: super::super::Foundation::PSTR, szvaluebuf: super::super::Foundation::PSTR, pcchvaluebuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetPropertyW(hinstall: MSIHANDLE, szname: super::super::Foundation::PWSTR, szvaluebuf: super::super::Foundation::PWSTR, pcchvaluebuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetShortcutTargetA(szshortcutpath: super::super::Foundation::PSTR, szproductcode: super::super::Foundation::PSTR, szfeatureid: super::super::Foundation::PSTR, szcomponentcode: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetShortcutTargetW(szshortcutpath: super::super::Foundation::PWSTR, szproductcode: super::super::Foundation::PWSTR, szfeatureid: super::super::Foundation::PWSTR, szcomponentcode: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetSourcePathA(hinstall: MSIHANDLE, szfolder: super::super::Foundation::PSTR, szpathbuf: super::super::Foundation::PSTR, pcchpathbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetSourcePathW(hinstall: MSIHANDLE, szfolder: super::super::Foundation::PWSTR, szpathbuf: super::super::Foundation::PWSTR, pcchpathbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetSummaryInformationA(hdatabase: MSIHANDLE, szdatabasepath: super::super::Foundation::PSTR, uiupdatecount: u32, phsummaryinfo: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetSummaryInformationW(hdatabase: MSIHANDLE, szdatabasepath: super::super::Foundation::PWSTR, uiupdatecount: u32, phsummaryinfo: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetTargetPathA(hinstall: MSIHANDLE, szfolder: super::super::Foundation::PSTR, szpathbuf: super::super::Foundation::PSTR, pcchpathbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetTargetPathW(hinstall: MSIHANDLE, szfolder: super::super::Foundation::PWSTR, szpathbuf: super::super::Foundation::PWSTR, pcchpathbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetUserInfoA(szproduct: super::super::Foundation::PSTR, lpusernamebuf: super::super::Foundation::PSTR, pcchusernamebuf: *mut u32, lporgnamebuf: super::super::Foundation::PSTR, pcchorgnamebuf: *mut u32, lpserialbuf: super::super::Foundation::PSTR, pcchserialbuf: *mut u32) -> USERINFOSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiGetUserInfoW(szproduct: super::super::Foundation::PWSTR, lpusernamebuf: super::super::Foundation::PWSTR, pcchusernamebuf: *mut u32, lporgnamebuf: super::super::Foundation::PWSTR, pcchorgnamebuf: *mut u32, lpserialbuf: super::super::Foundation::PWSTR, pcchserialbuf: *mut u32) -> USERINFOSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiInstallMissingComponentA(szproduct: super::super::Foundation::PSTR, szcomponent: super::super::Foundation::PSTR, einstallstate: INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiInstallMissingComponentW(szproduct: super::super::Foundation::PWSTR, szcomponent: super::super::Foundation::PWSTR, einstallstate: INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiInstallMissingFileA(szproduct: super::super::Foundation::PSTR, szfile: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiInstallMissingFileW(szproduct: super::super::Foundation::PWSTR, szfile: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiInstallProductA(szpackagepath: super::super::Foundation::PSTR, szcommandline: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiInstallProductW(szpackagepath: super::super::Foundation::PWSTR, szcommandline: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiIsProductElevatedA(szproduct: super::super::Foundation::PSTR, pfelevated: *mut super::super::Foundation::BOOL) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiIsProductElevatedW(szproduct: super::super::Foundation::PWSTR, pfelevated: *mut super::super::Foundation::BOOL) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiJoinTransaction(htransactionhandle: MSIHANDLE, dwtransactionattributes: u32, phchangeofownerevent: *mut super::super::Foundation::HANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiLocateComponentA(szcomponent: super::super::Foundation::PSTR, lppathbuf: super::super::Foundation::PSTR, pcchbuf: *mut u32) -> INSTALLSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiLocateComponentW(szcomponent: super::super::Foundation::PWSTR, lppathbuf: super::super::Foundation::PWSTR, pcchbuf: *mut u32) -> INSTALLSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiNotifySidChangeA(poldsid: super::super::Foundation::PSTR, pnewsid: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiNotifySidChangeW(poldsid: super::super::Foundation::PWSTR, pnewsid: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiOpenDatabaseA(szdatabasepath: super::super::Foundation::PSTR, szpersist: super::super::Foundation::PSTR, phdatabase: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiOpenDatabaseW(szdatabasepath: super::super::Foundation::PWSTR, szpersist: super::super::Foundation::PWSTR, phdatabase: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiOpenPackageA(szpackagepath: super::super::Foundation::PSTR, hproduct: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiOpenPackageExA(szpackagepath: super::super::Foundation::PSTR, dwoptions: u32, hproduct: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiOpenPackageExW(szpackagepath: super::super::Foundation::PWSTR, dwoptions: u32, hproduct: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiOpenPackageW(szpackagepath: super::super::Foundation::PWSTR, hproduct: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiOpenProductA(szproduct: super::super::Foundation::PSTR, hproduct: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiOpenProductW(szproduct: super::super::Foundation::PWSTR, hproduct: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiPreviewBillboardA(hpreview: MSIHANDLE, szcontrolname: super::super::Foundation::PSTR, szbillboard: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiPreviewBillboardW(hpreview: MSIHANDLE, szcontrolname: super::super::Foundation::PWSTR, szbillboard: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiPreviewDialogA(hpreview: MSIHANDLE, szdialogname: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiPreviewDialogW(hpreview: MSIHANDLE, szdialogname: super::super::Foundation::PWSTR) -> u32;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry"))]
pub fn MsiProcessAdvertiseScriptA(szscriptfile: super::super::Foundation::PSTR, sziconfolder: super::super::Foundation::PSTR, hregdata: super::Registry::HKEY, fshortcuts: super::super::Foundation::BOOL, fremoveitems: super::super::Foundation::BOOL) -> u32;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry"))]
pub fn MsiProcessAdvertiseScriptW(szscriptfile: super::super::Foundation::PWSTR, sziconfolder: super::super::Foundation::PWSTR, hregdata: super::Registry::HKEY, fshortcuts: super::super::Foundation::BOOL, fremoveitems: super::super::Foundation::BOOL) -> u32;
pub fn MsiProcessMessage(hinstall: MSIHANDLE, emessagetype: INSTALLMESSAGE, hrecord: MSIHANDLE) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiProvideAssemblyA(szassemblyname: super::super::Foundation::PSTR, szappcontext: super::super::Foundation::PSTR, dwinstallmode: INSTALLMODE, dwassemblyinfo: MSIASSEMBLYINFO, lppathbuf: super::super::Foundation::PSTR, pcchpathbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiProvideAssemblyW(szassemblyname: super::super::Foundation::PWSTR, szappcontext: super::super::Foundation::PWSTR, dwinstallmode: INSTALLMODE, dwassemblyinfo: MSIASSEMBLYINFO, lppathbuf: super::super::Foundation::PWSTR, pcchpathbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiProvideComponentA(szproduct: super::super::Foundation::PSTR, szfeature: super::super::Foundation::PSTR, szcomponent: super::super::Foundation::PSTR, dwinstallmode: INSTALLMODE, lppathbuf: super::super::Foundation::PSTR, pcchpathbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiProvideComponentW(szproduct: super::super::Foundation::PWSTR, szfeature: super::super::Foundation::PWSTR, szcomponent: super::super::Foundation::PWSTR, dwinstallmode: INSTALLMODE, lppathbuf: super::super::Foundation::PWSTR, pcchpathbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiProvideQualifiedComponentA(szcategory: super::super::Foundation::PSTR, szqualifier: super::super::Foundation::PSTR, dwinstallmode: INSTALLMODE, lppathbuf: super::super::Foundation::PSTR, pcchpathbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiProvideQualifiedComponentExA(szcategory: super::super::Foundation::PSTR, szqualifier: super::super::Foundation::PSTR, dwinstallmode: INSTALLMODE, szproduct: super::super::Foundation::PSTR, dwunused1: u32, dwunused2: u32, lppathbuf: super::super::Foundation::PSTR, pcchpathbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiProvideQualifiedComponentExW(szcategory: super::super::Foundation::PWSTR, szqualifier: super::super::Foundation::PWSTR, dwinstallmode: INSTALLMODE, szproduct: super::super::Foundation::PWSTR, dwunused1: u32, dwunused2: u32, lppathbuf: super::super::Foundation::PWSTR, pcchpathbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiProvideQualifiedComponentW(szcategory: super::super::Foundation::PWSTR, szqualifier: super::super::Foundation::PWSTR, dwinstallmode: INSTALLMODE, lppathbuf: super::super::Foundation::PWSTR, pcchpathbuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiQueryComponentStateA(szproductcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, szcomponentcode: super::super::Foundation::PSTR, pdwstate: *mut INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiQueryComponentStateW(szproductcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, szcomponentcode: super::super::Foundation::PWSTR, pdwstate: *mut INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiQueryFeatureStateA(szproduct: super::super::Foundation::PSTR, szfeature: super::super::Foundation::PSTR) -> INSTALLSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiQueryFeatureStateExA(szproductcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, szfeature: super::super::Foundation::PSTR, pdwstate: *mut INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiQueryFeatureStateExW(szproductcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, szfeature: super::super::Foundation::PWSTR, pdwstate: *mut INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiQueryFeatureStateW(szproduct: super::super::Foundation::PWSTR, szfeature: super::super::Foundation::PWSTR) -> INSTALLSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiQueryProductStateA(szproduct: super::super::Foundation::PSTR) -> INSTALLSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiQueryProductStateW(szproduct: super::super::Foundation::PWSTR) -> INSTALLSTATE;
pub fn MsiRecordClearData(hrecord: MSIHANDLE) -> u32;
pub fn MsiRecordDataSize(hrecord: MSIHANDLE, ifield: u32) -> u32;
pub fn MsiRecordGetFieldCount(hrecord: MSIHANDLE) -> u32;
pub fn MsiRecordGetInteger(hrecord: MSIHANDLE, ifield: u32) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiRecordGetStringA(hrecord: MSIHANDLE, ifield: u32, szvaluebuf: super::super::Foundation::PSTR, pcchvaluebuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiRecordGetStringW(hrecord: MSIHANDLE, ifield: u32, szvaluebuf: super::super::Foundation::PWSTR, pcchvaluebuf: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiRecordIsNull(hrecord: MSIHANDLE, ifield: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiRecordReadStream(hrecord: MSIHANDLE, ifield: u32, szdatabuf: super::super::Foundation::PSTR, pcbdatabuf: *mut u32) -> u32;
pub fn MsiRecordSetInteger(hrecord: MSIHANDLE, ifield: u32, ivalue: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiRecordSetStreamA(hrecord: MSIHANDLE, ifield: u32, szfilepath: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiRecordSetStreamW(hrecord: MSIHANDLE, ifield: u32, szfilepath: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiRecordSetStringA(hrecord: MSIHANDLE, ifield: u32, szvalue: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiRecordSetStringW(hrecord: MSIHANDLE, ifield: u32, szvalue: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiReinstallFeatureA(szproduct: super::super::Foundation::PSTR, szfeature: super::super::Foundation::PSTR, dwreinstallmode: REINSTALLMODE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiReinstallFeatureW(szproduct: super::super::Foundation::PWSTR, szfeature: super::super::Foundation::PWSTR, dwreinstallmode: REINSTALLMODE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiReinstallProductA(szproduct: super::super::Foundation::PSTR, szreinstallmode: REINSTALLMODE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiReinstallProductW(szproduct: super::super::Foundation::PWSTR, szreinstallmode: REINSTALLMODE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiRemovePatchesA(szpatchlist: super::super::Foundation::PSTR, szproductcode: super::super::Foundation::PSTR, euninstalltype: INSTALLTYPE, szpropertylist: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiRemovePatchesW(szpatchlist: super::super::Foundation::PWSTR, szproductcode: super::super::Foundation::PWSTR, euninstalltype: INSTALLTYPE, szpropertylist: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSequenceA(hinstall: MSIHANDLE, sztable: super::super::Foundation::PSTR, isequencemode: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSequenceW(hinstall: MSIHANDLE, sztable: super::super::Foundation::PWSTR, isequencemode: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetComponentStateA(hinstall: MSIHANDLE, szcomponent: super::super::Foundation::PSTR, istate: INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetComponentStateW(hinstall: MSIHANDLE, szcomponent: super::super::Foundation::PWSTR, istate: INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetExternalUIA(puihandler: INSTALLUI_HANDLERA, dwmessagefilter: u32, pvcontext: *const ::core::ffi::c_void) -> INSTALLUI_HANDLERA;
pub fn MsiSetExternalUIRecord(puihandler: PINSTALLUI_HANDLER_RECORD, dwmessagefilter: u32, pvcontext: *const ::core::ffi::c_void, ppuiprevhandler: PINSTALLUI_HANDLER_RECORD) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetExternalUIW(puihandler: INSTALLUI_HANDLERW, dwmessagefilter: u32, pvcontext: *const ::core::ffi::c_void) -> INSTALLUI_HANDLERW;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetFeatureAttributesA(hinstall: MSIHANDLE, szfeature: super::super::Foundation::PSTR, dwattributes: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetFeatureAttributesW(hinstall: MSIHANDLE, szfeature: super::super::Foundation::PWSTR, dwattributes: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetFeatureStateA(hinstall: MSIHANDLE, szfeature: super::super::Foundation::PSTR, istate: INSTALLSTATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetFeatureStateW(hinstall: MSIHANDLE, szfeature: super::super::Foundation::PWSTR, istate: INSTALLSTATE) -> u32;
pub fn MsiSetInstallLevel(hinstall: MSIHANDLE, iinstalllevel: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetInternalUI(dwuilevel: INSTALLUILEVEL, phwnd: *mut super::super::Foundation::HWND) -> INSTALLUILEVEL;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetMode(hinstall: MSIHANDLE, erunmode: MSIRUNMODE, fstate: super::super::Foundation::BOOL) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetPropertyA(hinstall: MSIHANDLE, szname: super::super::Foundation::PSTR, szvalue: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetPropertyW(hinstall: MSIHANDLE, szname: super::super::Foundation::PWSTR, szvalue: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetTargetPathA(hinstall: MSIHANDLE, szfolder: super::super::Foundation::PSTR, szfolderpath: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSetTargetPathW(hinstall: MSIHANDLE, szfolder: super::super::Foundation::PWSTR, szfolderpath: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListAddMediaDiskA(szproductcodeorpatchcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, dwdiskid: u32, szvolumelabel: super::super::Foundation::PSTR, szdiskprompt: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListAddMediaDiskW(szproductcodeorpatchcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, dwdiskid: u32, szvolumelabel: super::super::Foundation::PWSTR, szdiskprompt: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListAddSourceA(szproduct: super::super::Foundation::PSTR, szusername: super::super::Foundation::PSTR, dwreserved: u32, szsource: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListAddSourceExA(szproductcodeorpatchcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, szsource: super::super::Foundation::PSTR, dwindex: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListAddSourceExW(szproductcodeorpatchcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, szsource: super::super::Foundation::PWSTR, dwindex: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListAddSourceW(szproduct: super::super::Foundation::PWSTR, szusername: super::super::Foundation::PWSTR, dwreserved: u32, szsource: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListClearAllA(szproduct: super::super::Foundation::PSTR, szusername: super::super::Foundation::PSTR, dwreserved: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListClearAllExA(szproductcodeorpatchcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListClearAllExW(szproductcodeorpatchcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListClearAllW(szproduct: super::super::Foundation::PWSTR, szusername: super::super::Foundation::PWSTR, dwreserved: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListClearMediaDiskA(szproductcodeorpatchcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, dwdiskid: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListClearMediaDiskW(szproductcodeorpatchcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, dwdiskid: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListClearSourceA(szproductcodeorpatchcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, szsource: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListClearSourceW(szproductcodeorpatchcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, szsource: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListEnumMediaDisksA(szproductcodeorpatchcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, dwindex: u32, pdwdiskid: *mut u32, szvolumelabel: super::super::Foundation::PSTR, pcchvolumelabel: *mut u32, szdiskprompt: super::super::Foundation::PSTR, pcchdiskprompt: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListEnumMediaDisksW(szproductcodeorpatchcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, dwindex: u32, pdwdiskid: *mut u32, szvolumelabel: super::super::Foundation::PWSTR, pcchvolumelabel: *mut u32, szdiskprompt: super::super::Foundation::PWSTR, pcchdiskprompt: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListEnumSourcesA(szproductcodeorpatchcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, dwindex: u32, szsource: super::super::Foundation::PSTR, pcchsource: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListEnumSourcesW(szproductcodeorpatchcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, dwindex: u32, szsource: super::super::Foundation::PWSTR, pcchsource: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListForceResolutionA(szproduct: super::super::Foundation::PSTR, szusername: super::super::Foundation::PSTR, dwreserved: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListForceResolutionExA(szproductcodeorpatchcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListForceResolutionExW(szproductcodeorpatchcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListForceResolutionW(szproduct: super::super::Foundation::PWSTR, szusername: super::super::Foundation::PWSTR, dwreserved: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListGetInfoA(szproductcodeorpatchcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, szproperty: super::super::Foundation::PSTR, szvalue: super::super::Foundation::PSTR, pcchvalue: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListGetInfoW(szproductcodeorpatchcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, szproperty: super::super::Foundation::PWSTR, szvalue: super::super::Foundation::PWSTR, pcchvalue: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListSetInfoA(szproductcodeorpatchcode: super::super::Foundation::PSTR, szusersid: super::super::Foundation::PSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, szproperty: super::super::Foundation::PSTR, szvalue: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSourceListSetInfoW(szproductcodeorpatchcode: super::super::Foundation::PWSTR, szusersid: super::super::Foundation::PWSTR, dwcontext: MSIINSTALLCONTEXT, dwoptions: u32, szproperty: super::super::Foundation::PWSTR, szvalue: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSummaryInfoGetPropertyA(hsummaryinfo: MSIHANDLE, uiproperty: u32, puidatatype: *mut u32, pivalue: *mut i32, pftvalue: *mut super::super::Foundation::FILETIME, szvaluebuf: super::super::Foundation::PSTR, pcchvaluebuf: *mut u32) -> u32;
pub fn MsiSummaryInfoGetPropertyCount(hsummaryinfo: MSIHANDLE, puipropertycount: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSummaryInfoGetPropertyW(hsummaryinfo: MSIHANDLE, uiproperty: u32, puidatatype: *mut u32, pivalue: *mut i32, pftvalue: *mut super::super::Foundation::FILETIME, szvaluebuf: super::super::Foundation::PWSTR, pcchvaluebuf: *mut u32) -> u32;
pub fn MsiSummaryInfoPersist(hsummaryinfo: MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSummaryInfoSetPropertyA(hsummaryinfo: MSIHANDLE, uiproperty: u32, uidatatype: u32, ivalue: i32, pftvalue: *mut super::super::Foundation::FILETIME, szvalue: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiSummaryInfoSetPropertyW(hsummaryinfo: MSIHANDLE, uiproperty: u32, uidatatype: u32, ivalue: i32, pftvalue: *mut super::super::Foundation::FILETIME, szvalue: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiUseFeatureA(szproduct: super::super::Foundation::PSTR, szfeature: super::super::Foundation::PSTR) -> INSTALLSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiUseFeatureExA(szproduct: super::super::Foundation::PSTR, szfeature: super::super::Foundation::PSTR, dwinstallmode: u32, dwreserved: u32) -> INSTALLSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiUseFeatureExW(szproduct: super::super::Foundation::PWSTR, szfeature: super::super::Foundation::PWSTR, dwinstallmode: u32, dwreserved: u32) -> INSTALLSTATE;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiUseFeatureW(szproduct: super::super::Foundation::PWSTR, szfeature: super::super::Foundation::PWSTR) -> INSTALLSTATE;
pub fn MsiVerifyDiskSpace(hinstall: MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiVerifyPackageA(szpackagepath: super::super::Foundation::PSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiVerifyPackageW(szpackagepath: super::super::Foundation::PWSTR) -> u32;
pub fn MsiViewClose(hview: MSIHANDLE) -> u32;
pub fn MsiViewExecute(hview: MSIHANDLE, hrecord: MSIHANDLE) -> u32;
pub fn MsiViewFetch(hview: MSIHANDLE, phrecord: *mut MSIHANDLE) -> u32;
pub fn MsiViewGetColumnInfo(hview: MSIHANDLE, ecolumninfo: MSICOLINFO, phrecord: *mut MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiViewGetErrorA(hview: MSIHANDLE, szcolumnnamebuffer: super::super::Foundation::PSTR, pcchbuf: *mut u32) -> MSIDBERROR;
#[cfg(feature = "Win32_Foundation")]
pub fn MsiViewGetErrorW(hview: MSIHANDLE, szcolumnnamebuffer: super::super::Foundation::PWSTR, pcchbuf: *mut u32) -> MSIDBERROR;
pub fn MsiViewModify(hview: MSIHANDLE, emodifymode: MSIMODIFY, hrecord: MSIHANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn NormalizeFileForPatchSignature(filebuffer: *mut ::core::ffi::c_void, filesize: u32, optionflags: u32, optiondata: *const PATCH_OPTION_DATA, newfilecoffbase: u32, newfilecofftime: u32, ignorerangecount: u32, ignorerangearray: *const PATCH_IGNORE_RANGE, retainrangecount: u32, retainrangearray: *const PATCH_RETAIN_RANGE) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn QueryActCtxSettingsW(dwflags: u32, hactctx: super::super::Foundation::HANDLE, settingsnamespace: super::super::Foundation::PWSTR, settingname: super::super::Foundation::PWSTR, pvbuffer: super::super::Foundation::PWSTR, dwbuffer: usize, pdwwrittenorrequired: *mut usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn QueryActCtxW(dwflags: u32, hactctx: super::super::Foundation::HANDLE, pvsubinstance: *const ::core::ffi::c_void, ulinfoclass: u32, pvbuffer: *mut ::core::ffi::c_void, cbbuffer: usize, pcbwrittenorrequired: *mut usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ReleaseActCtx(hactctx: super::super::Foundation::HANDLE);
#[cfg(feature = "Win32_Foundation")]
pub fn SfcGetNextProtectedFile(rpchandle: super::super::Foundation::HANDLE, protfiledata: *mut PROTECTED_FILE_DATA) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SfcIsFileProtected(rpchandle: super::super::Foundation::HANDLE, protfilename: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry"))]
pub fn SfcIsKeyProtected(keyhandle: super::Registry::HKEY, subkeyname: super::super::Foundation::PWSTR, keysam: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SfpVerifyFile(pszfilename: super::super::Foundation::PSTR, pszerror: super::super::Foundation::PSTR, dwerrsize: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn TestApplyPatchToFileA(patchfilename: super::super::Foundation::PSTR, oldfilename: super::super::Foundation::PSTR, applyoptionflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn TestApplyPatchToFileByBuffers(patchfilebuffer: *const u8, patchfilesize: u32, oldfilebuffer: *const u8, oldfilesize: u32, newfilesize: *mut u32, applyoptionflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn TestApplyPatchToFileByHandles(patchfilehandle: super::super::Foundation::HANDLE, oldfilehandle: super::super::Foundation::HANDLE, applyoptionflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn TestApplyPatchToFileW(patchfilename: super::super::Foundation::PWSTR, oldfilename: super::super::Foundation::PWSTR, applyoptionflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ZombifyActCtx(hactctx: super::super::Foundation::HANDLE) -> super::super::Foundation::BOOL;
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct ACTCTXA {
pub cbSize: u32,
pub dwFlags: u32,
pub lpSource: super::super::Foundation::PSTR,
pub wProcessorArchitecture: u16,
pub wLangId: u16,
pub lpAssemblyDirectory: super::super::Foundation::PSTR,
pub lpResourceName: super::super::Foundation::PSTR,
pub lpApplicationName: super::super::Foundation::PSTR,
pub hModule: super::super::Foundation::HINSTANCE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for ACTCTXA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for ACTCTXA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct ACTCTXW {
pub cbSize: u32,
pub dwFlags: u32,
pub lpSource: super::super::Foundation::PWSTR,
pub wProcessorArchitecture: u16,
pub wLangId: u16,
pub lpAssemblyDirectory: super::super::Foundation::PWSTR,
pub lpResourceName: super::super::Foundation::PWSTR,
pub lpApplicationName: super::super::Foundation::PWSTR,
pub hModule: super::super::Foundation::HINSTANCE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for ACTCTXW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for ACTCTXW {
fn clone(&self) -> Self {
*self
}
}
pub type ACTCTX_COMPATIBILITY_ELEMENT_TYPE = i32;
pub const ACTCTX_COMPATIBILITY_ELEMENT_TYPE_UNKNOWN: ACTCTX_COMPATIBILITY_ELEMENT_TYPE = 0i32;
pub const ACTCTX_COMPATIBILITY_ELEMENT_TYPE_OS: ACTCTX_COMPATIBILITY_ELEMENT_TYPE = 1i32;
pub const ACTCTX_COMPATIBILITY_ELEMENT_TYPE_MITIGATION: ACTCTX_COMPATIBILITY_ELEMENT_TYPE = 2i32;
pub const ACTCTX_COMPATIBILITY_ELEMENT_TYPE_MAXVERSIONTESTED: ACTCTX_COMPATIBILITY_ELEMENT_TYPE = 3i32;
pub type ACTCTX_REQUESTED_RUN_LEVEL = i32;
pub const ACTCTX_RUN_LEVEL_UNSPECIFIED: ACTCTX_REQUESTED_RUN_LEVEL = 0i32;
pub const ACTCTX_RUN_LEVEL_AS_INVOKER: ACTCTX_REQUESTED_RUN_LEVEL = 1i32;
pub const ACTCTX_RUN_LEVEL_HIGHEST_AVAILABLE: ACTCTX_REQUESTED_RUN_LEVEL = 2i32;
pub const ACTCTX_RUN_LEVEL_REQUIRE_ADMIN: ACTCTX_REQUESTED_RUN_LEVEL = 3i32;
pub const ACTCTX_RUN_LEVEL_NUMBERS: ACTCTX_REQUESTED_RUN_LEVEL = 4i32;
#[repr(C)]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_WindowsProgramming"))]
pub struct ACTCTX_SECTION_KEYED_DATA {
pub cbSize: u32,
pub ulDataFormatVersion: u32,
pub lpData: *mut ::core::ffi::c_void,
pub ulLength: u32,
pub lpSectionGlobalData: *mut ::core::ffi::c_void,
pub ulSectionGlobalDataLength: u32,
pub lpSectionBase: *mut ::core::ffi::c_void,
pub ulSectionTotalLength: u32,
pub hActCtx: super::super::Foundation::HANDLE,
pub ulAssemblyRosterIndex: u32,
pub ulFlags: u32,
pub AssemblyMetadata: super::WindowsProgramming::ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_WindowsProgramming"))]
impl ::core::marker::Copy for ACTCTX_SECTION_KEYED_DATA {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_WindowsProgramming"))]
impl ::core::clone::Clone for ACTCTX_SECTION_KEYED_DATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION {
pub ulFlags: u32,
pub ulEncodedAssemblyIdentityLength: u32,
pub ulManifestPathType: u32,
pub ulManifestPathLength: u32,
pub liManifestLastWriteTime: i64,
pub ulPolicyPathType: u32,
pub ulPolicyPathLength: u32,
pub liPolicyLastWriteTime: i64,
pub ulMetadataSatelliteRosterIndex: u32,
pub ulManifestVersionMajor: u32,
pub ulManifestVersionMinor: u32,
pub ulPolicyVersionMajor: u32,
pub ulPolicyVersionMinor: u32,
pub ulAssemblyDirectoryNameLength: u32,
pub lpAssemblyEncodedAssemblyIdentity: super::super::Foundation::PWSTR,
pub lpAssemblyManifestPath: super::super::Foundation::PWSTR,
pub lpAssemblyPolicyPath: super::super::Foundation::PWSTR,
pub lpAssemblyDirectoryName: super::super::Foundation::PWSTR,
pub ulFileCount: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct ACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION {
pub ElementCount: u32,
pub Elements: [COMPATIBILITY_CONTEXT_ELEMENT; 1],
}
impl ::core::marker::Copy for ACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION {}
impl ::core::clone::Clone for ACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct ACTIVATION_CONTEXT_DETAILED_INFORMATION {
pub dwFlags: u32,
pub ulFormatVersion: u32,
pub ulAssemblyCount: u32,
pub ulRootManifestPathType: u32,
pub ulRootManifestPathChars: u32,
pub ulRootConfigurationPathType: u32,
pub ulRootConfigurationPathChars: u32,
pub ulAppDirPathType: u32,
pub ulAppDirPathChars: u32,
pub lpRootManifestPath: super::super::Foundation::PWSTR,
pub lpRootConfigurationPath: super::super::Foundation::PWSTR,
pub lpAppDirPath: super::super::Foundation::PWSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for ACTIVATION_CONTEXT_DETAILED_INFORMATION {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for ACTIVATION_CONTEXT_DETAILED_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct ACTIVATION_CONTEXT_QUERY_INDEX {
pub ulAssemblyIndex: u32,
pub ulFileIndexInAssembly: u32,
}
impl ::core::marker::Copy for ACTIVATION_CONTEXT_QUERY_INDEX {}
impl ::core::clone::Clone for ACTIVATION_CONTEXT_QUERY_INDEX {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct ACTIVATION_CONTEXT_RUN_LEVEL_INFORMATION {
pub ulFlags: u32,
pub RunLevel: ACTCTX_REQUESTED_RUN_LEVEL,
pub UiAccess: u32,
}
impl ::core::marker::Copy for ACTIVATION_CONTEXT_RUN_LEVEL_INFORMATION {}
impl ::core::clone::Clone for ACTIVATION_CONTEXT_RUN_LEVEL_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
pub type ADVERTISEFLAGS = i32;
pub const ADVERTISEFLAGS_MACHINEASSIGN: ADVERTISEFLAGS = 0i32;
pub const ADVERTISEFLAGS_USERASSIGN: ADVERTISEFLAGS = 1i32;
pub const APPLY_OPTION_FAIL_IF_CLOSE: u32 = 2u32;
pub const APPLY_OPTION_FAIL_IF_EXACT: u32 = 1u32;
pub const APPLY_OPTION_TEST_ONLY: u32 = 4u32;
pub const APPLY_OPTION_VALID_FLAGS: u32 = 7u32;
pub type ASM_BIND_FLAGS = u32;
pub const ASM_BINDF_FORCE_CACHE_INSTALL: ASM_BIND_FLAGS = 1u32;
pub const ASM_BINDF_RFS_INTEGRITY_CHECK: ASM_BIND_FLAGS = 2u32;
pub const ASM_BINDF_RFS_MODULE_CHECK: ASM_BIND_FLAGS = 4u32;
pub const ASM_BINDF_BINPATH_PROBE_ONLY: ASM_BIND_FLAGS = 8u32;
pub const ASM_BINDF_SHARED_BINPATH_HINT: ASM_BIND_FLAGS = 16u32;
pub const ASM_BINDF_PARENT_ASM_HINT: ASM_BIND_FLAGS = 32u32;
pub type ASM_CMP_FLAGS = i32;
pub const ASM_CMPF_NAME: ASM_CMP_FLAGS = 1i32;
pub const ASM_CMPF_MAJOR_VERSION: ASM_CMP_FLAGS = 2i32;
pub const ASM_CMPF_MINOR_VERSION: ASM_CMP_FLAGS = 4i32;
pub const ASM_CMPF_BUILD_NUMBER: ASM_CMP_FLAGS = 8i32;
pub const ASM_CMPF_REVISION_NUMBER: ASM_CMP_FLAGS = 16i32;
pub const ASM_CMPF_PUBLIC_KEY_TOKEN: ASM_CMP_FLAGS = 32i32;
pub const ASM_CMPF_CULTURE: ASM_CMP_FLAGS = 64i32;
pub const ASM_CMPF_CUSTOM: ASM_CMP_FLAGS = 128i32;
pub const ASM_CMPF_ALL: ASM_CMP_FLAGS = 255i32;
pub const ASM_CMPF_DEFAULT: ASM_CMP_FLAGS = 256i32;
pub type ASM_DISPLAY_FLAGS = i32;
pub const ASM_DISPLAYF_VERSION: ASM_DISPLAY_FLAGS = 1i32;
pub const ASM_DISPLAYF_CULTURE: ASM_DISPLAY_FLAGS = 2i32;
pub const ASM_DISPLAYF_PUBLIC_KEY_TOKEN: ASM_DISPLAY_FLAGS = 4i32;
pub const ASM_DISPLAYF_PUBLIC_KEY: ASM_DISPLAY_FLAGS = 8i32;
pub const ASM_DISPLAYF_CUSTOM: ASM_DISPLAY_FLAGS = 16i32;
pub const ASM_DISPLAYF_PROCESSORARCHITECTURE: ASM_DISPLAY_FLAGS = 32i32;
pub const ASM_DISPLAYF_LANGUAGEID: ASM_DISPLAY_FLAGS = 64i32;
pub type ASM_NAME = i32;
pub const ASM_NAME_PUBLIC_KEY: ASM_NAME = 0i32;
pub const ASM_NAME_PUBLIC_KEY_TOKEN: ASM_NAME = 1i32;
pub const ASM_NAME_HASH_VALUE: ASM_NAME = 2i32;
pub const ASM_NAME_NAME: ASM_NAME = 3i32;
pub const ASM_NAME_MAJOR_VERSION: ASM_NAME = 4i32;
pub const ASM_NAME_MINOR_VERSION: ASM_NAME = 5i32;
pub const ASM_NAME_BUILD_NUMBER: ASM_NAME = 6i32;
pub const ASM_NAME_REVISION_NUMBER: ASM_NAME = 7i32;
pub const ASM_NAME_CULTURE: ASM_NAME = 8i32;
pub const ASM_NAME_PROCESSOR_ID_ARRAY: ASM_NAME = 9i32;
pub const ASM_NAME_OSINFO_ARRAY: ASM_NAME = 10i32;
pub const ASM_NAME_HASH_ALGID: ASM_NAME = 11i32;
pub const ASM_NAME_ALIAS: ASM_NAME = 12i32;
pub const ASM_NAME_CODEBASE_URL: ASM_NAME = 13i32;
pub const ASM_NAME_CODEBASE_LASTMOD: ASM_NAME = 14i32;
pub const ASM_NAME_NULL_PUBLIC_KEY: ASM_NAME = 15i32;
pub const ASM_NAME_NULL_PUBLIC_KEY_TOKEN: ASM_NAME = 16i32;
pub const ASM_NAME_CUSTOM: ASM_NAME = 17i32;
pub const ASM_NAME_NULL_CUSTOM: ASM_NAME = 18i32;
pub const ASM_NAME_MVID: ASM_NAME = 19i32;
pub const ASM_NAME_MAX_PARAMS: ASM_NAME = 20i32;
pub const ASSEMBLYINFO_FLAG_INSTALLED: u32 = 1u32;
pub const ASSEMBLYINFO_FLAG_PAYLOADRESIDENT: u32 = 2u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct ASSEMBLY_FILE_DETAILED_INFORMATION {
pub ulFlags: u32,
pub ulFilenameLength: u32,
pub ulPathLength: u32,
pub lpFileName: super::super::Foundation::PWSTR,
pub lpFilePath: super::super::Foundation::PWSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for ASSEMBLY_FILE_DETAILED_INFORMATION {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for ASSEMBLY_FILE_DETAILED_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct ASSEMBLY_INFO {
pub cbAssemblyInfo: u32,
pub dwAssemblyFlags: u32,
pub uliAssemblySizeInKB: u64,
pub pszCurrentAssemblyPathBuf: super::super::Foundation::PWSTR,
pub cchBuf: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for ASSEMBLY_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for ASSEMBLY_INFO {
fn clone(&self) -> Self {
*self
}
}
pub const CLSID_EvalCom2: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1851660560, data2: 32851, data3: 18016, data4: [183, 149, 107, 97, 46, 41, 188, 88] };
pub const CLSID_MsmMerge2: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4182345173, data2: 10745, data3: 18243, data4: [152, 5, 153, 188, 63, 53, 182, 120] };
#[repr(C)]
pub struct COMPATIBILITY_CONTEXT_ELEMENT {
pub Id: ::windows_sys::core::GUID,
pub Type: ACTCTX_COMPATIBILITY_ELEMENT_TYPE,
pub MaxVersionTested: u64,
}
impl ::core::marker::Copy for COMPATIBILITY_CONTEXT_ELEMENT {}
impl ::core::clone::Clone for COMPATIBILITY_CONTEXT_ELEMENT {
fn clone(&self) -> Self {
*self
}
}
pub type CREATE_ASM_NAME_OBJ_FLAGS = i32;
pub const CANOF_PARSE_DISPLAY_NAME: CREATE_ASM_NAME_OBJ_FLAGS = 1i32;
pub const CANOF_SET_DEFAULT_VALUES: CREATE_ASM_NAME_OBJ_FLAGS = 2i32;
pub const DEFAULT_DISK_ID: u32 = 2u32;
pub const DEFAULT_FILE_SEQUENCE_START: u32 = 2u32;
pub const DEFAULT_MINIMUM_REQUIRED_MSI_VERSION: u32 = 100u32;
#[repr(C)]
pub struct DELTA_HASH {
pub HashSize: u32,
pub HashValue: [u8; 32],
}
impl ::core::marker::Copy for DELTA_HASH {}
impl ::core::clone::Clone for DELTA_HASH {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct DELTA_HEADER_INFO {
pub FileTypeSet: i64,
pub FileType: i64,
pub Flags: i64,
pub TargetSize: usize,
pub TargetFileTime: super::super::Foundation::FILETIME,
pub TargetHashAlgId: u32,
pub TargetHash: DELTA_HASH,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for DELTA_HEADER_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for DELTA_HEADER_INFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct DELTA_INPUT {
pub Anonymous: DELTA_INPUT_0,
pub uSize: usize,
pub Editable: super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for DELTA_INPUT {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for DELTA_INPUT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union DELTA_INPUT_0 {
pub lpcStart: *mut ::core::ffi::c_void,
pub lpStart: *mut ::core::ffi::c_void,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for DELTA_INPUT_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for DELTA_INPUT_0 {
fn clone(&self) -> Self {
*self
}
}
pub const DELTA_MAX_HASH_SIZE: u32 = 32u32;
#[repr(C)]
pub struct DELTA_OUTPUT {
pub lpStart: *mut ::core::ffi::c_void,
pub uSize: usize,
}
impl ::core::marker::Copy for DELTA_OUTPUT {}
impl ::core::clone::Clone for DELTA_OUTPUT {
fn clone(&self) -> Self {
*self
}
}
pub const ERROR_PATCH_BIGGER_THAN_COMPRESSED: u32 = 3222155525u32;
pub const ERROR_PATCH_CORRUPT: u32 = 3222159618u32;
pub const ERROR_PATCH_DECODE_FAILURE: u32 = 3222159617u32;
pub const ERROR_PATCH_ENCODE_FAILURE: u32 = 3222155521u32;
pub const ERROR_PATCH_IMAGEHLP_FAILURE: u32 = 3222155526u32;
pub const ERROR_PATCH_INVALID_OPTIONS: u32 = 3222155522u32;
pub const ERROR_PATCH_NEWER_FORMAT: u32 = 3222159619u32;
pub const ERROR_PATCH_NOT_AVAILABLE: u32 = 3222159622u32;
pub const ERROR_PATCH_NOT_NECESSARY: u32 = 3222159621u32;
pub const ERROR_PATCH_RETAIN_RANGES_DIFFER: u32 = 3222155524u32;
pub const ERROR_PATCH_SAME_FILE: u32 = 3222155523u32;
pub const ERROR_PATCH_WRONG_FILE: u32 = 3222159620u32;
pub const ERROR_PCW_BAD_API_PATCHING_SYMBOL_FLAGS: u32 = 3222163725u32;
pub const ERROR_PCW_BAD_FAMILY_RANGE_NAME: u32 = 3222163801u32;
pub const ERROR_PCW_BAD_FILE_SEQUENCE_START: u32 = 3222163770u32;
pub const ERROR_PCW_BAD_GUIDS_TO_REPLACE: u32 = 3222163721u32;
pub const ERROR_PCW_BAD_IMAGE_FAMILY_DISKID: u32 = 3222163773u32;
pub const ERROR_PCW_BAD_IMAGE_FAMILY_FILESEQSTART: u32 = 3222163774u32;
pub const ERROR_PCW_BAD_IMAGE_FAMILY_NAME: u32 = 3222163748u32;
pub const ERROR_PCW_BAD_IMAGE_FAMILY_SRC_PROP: u32 = 3222163750u32;
pub const ERROR_PCW_BAD_MAJOR_VERSION: u32 = 3222163853u32;
pub const ERROR_PCW_BAD_PATCH_GUID: u32 = 3222163720u32;
pub const ERROR_PCW_BAD_PRODUCTVERSION_VALIDATION: u32 = 3222163844u32;
pub const ERROR_PCW_BAD_SEQUENCE: u32 = 3222163848u32;
pub const ERROR_PCW_BAD_SUPERCEDENCE: u32 = 3222163847u32;
pub const ERROR_PCW_BAD_TARGET: u32 = 3222163849u32;
pub const ERROR_PCW_BAD_TARGET_IMAGE_NAME: u32 = 3222163736u32;
pub const ERROR_PCW_BAD_TARGET_IMAGE_PRODUCT_CODE: u32 = 3222163834u32;
pub const ERROR_PCW_BAD_TARGET_IMAGE_PRODUCT_VERSION: u32 = 3222163835u32;
pub const ERROR_PCW_BAD_TARGET_IMAGE_UPGRADED: u32 = 3222163776u32;
pub const ERROR_PCW_BAD_TARGET_IMAGE_UPGRADE_CODE: u32 = 3222163836u32;
pub const ERROR_PCW_BAD_TARGET_PRODUCT_CODE_LIST: u32 = 3222163722u32;
pub const ERROR_PCW_BAD_TGT_UPD_IMAGES: u32 = 3222163846u32;
pub const ERROR_PCW_BAD_TRANSFORMSET: u32 = 3222163845u32;
pub const ERROR_PCW_BAD_UPGRADED_IMAGE_FAMILY: u32 = 3222163775u32;
pub const ERROR_PCW_BAD_UPGRADED_IMAGE_NAME: u32 = 3222163728u32;
pub const ERROR_PCW_BAD_UPGRADED_IMAGE_PRODUCT_CODE: u32 = 3222163831u32;
pub const ERROR_PCW_BAD_UPGRADED_IMAGE_PRODUCT_VERSION: u32 = 3222163832u32;
pub const ERROR_PCW_BAD_UPGRADED_IMAGE_UPGRADE_CODE: u32 = 3222163833u32;
pub const ERROR_PCW_BAD_VERSION_STRING: u32 = 3222163852u32;
pub const ERROR_PCW_BASE: u32 = 3222163713u32;
pub const ERROR_PCW_CANNOT_CREATE_TABLE: u32 = 3222163841u32;
pub const ERROR_PCW_CANNOT_RUN_MAKECAB: u32 = 3222163782u32;
pub const ERROR_PCW_CANNOT_WRITE_DDF: u32 = 3222163781u32;
pub const ERROR_PCW_CANT_COPY_FILE_TO_TEMP_FOLDER: u32 = 3222163771u32;
pub const ERROR_PCW_CANT_CREATE_ONE_PATCH_FILE: u32 = 3222163772u32;
pub const ERROR_PCW_CANT_CREATE_PATCH_FILE: u32 = 3222163718u32;
pub const ERROR_PCW_CANT_CREATE_SUMMARY_INFO: u32 = 3222163828u32;
pub const ERROR_PCW_CANT_CREATE_SUMMARY_INFO_POUND: u32 = 3222163830u32;
pub const ERROR_PCW_CANT_CREATE_TEMP_FOLDER: u32 = 3222163715u32;
pub const ERROR_PCW_CANT_DELETE_TEMP_FOLDER: u32 = 3222163974u32;
pub const ERROR_PCW_CANT_GENERATE_SEQUENCEINFO_MAJORUPGD: u32 = 3222163842u32;
pub const ERROR_PCW_CANT_GENERATE_TRANSFORM: u32 = 3222163827u32;
pub const ERROR_PCW_CANT_GENERATE_TRANSFORM_POUND: u32 = 3222163829u32;
pub const ERROR_PCW_CANT_OVERWRITE_PATCH: u32 = 3222163717u32;
pub const ERROR_PCW_CANT_READ_FILE: u32 = 3222163978u32;
pub const ERROR_PCW_CREATEFILE_LOG_FAILED: u32 = 3222163861u32;
pub const ERROR_PCW_DUPLICATE_SEQUENCE_RECORD: u32 = 3222163858u32;
pub const ERROR_PCW_DUP_IMAGE_FAMILY_NAME: u32 = 3222163749u32;
pub const ERROR_PCW_DUP_TARGET_IMAGE_NAME: u32 = 3222163737u32;
pub const ERROR_PCW_DUP_TARGET_IMAGE_PACKCODE: u32 = 3222163777u32;
pub const ERROR_PCW_DUP_UPGRADED_IMAGE_NAME: u32 = 3222163729u32;
pub const ERROR_PCW_DUP_UPGRADED_IMAGE_PACKCODE: u32 = 3222163795u32;
pub const ERROR_PCW_ERROR_WRITING_TO_LOG: u32 = 3222163864u32;
pub const ERROR_PCW_EXECUTE_VIEW: u32 = 3222163870u32;
pub const ERROR_PCW_EXTFILE_BAD_FAMILY_FIELD: u32 = 3222163756u32;
pub const ERROR_PCW_EXTFILE_BAD_IGNORE_LENGTHS: u32 = 3222163814u32;
pub const ERROR_PCW_EXTFILE_BAD_IGNORE_OFFSETS: u32 = 3222163812u32;
pub const ERROR_PCW_EXTFILE_BAD_RETAIN_OFFSETS: u32 = 3222163817u32;
pub const ERROR_PCW_EXTFILE_BLANK_FILE_TABLE_KEY: u32 = 3222163755u32;
pub const ERROR_PCW_EXTFILE_BLANK_PATH_TO_FILE: u32 = 3222163758u32;
pub const ERROR_PCW_EXTFILE_IGNORE_COUNT_MISMATCH: u32 = 3222163815u32;
pub const ERROR_PCW_EXTFILE_LONG_FILE_TABLE_KEY: u32 = 3222163754u32;
pub const ERROR_PCW_EXTFILE_LONG_IGNORE_LENGTHS: u32 = 3222163813u32;
pub const ERROR_PCW_EXTFILE_LONG_IGNORE_OFFSETS: u32 = 3222163811u32;
pub const ERROR_PCW_EXTFILE_LONG_PATH_TO_FILE: u32 = 3222163757u32;
pub const ERROR_PCW_EXTFILE_LONG_RETAIN_OFFSETS: u32 = 3222163816u32;
pub const ERROR_PCW_EXTFILE_MISSING_FILE: u32 = 3222163759u32;
pub const ERROR_PCW_FAILED_CREATE_TRANSFORM: u32 = 3222163973u32;
pub const ERROR_PCW_FAILED_EXPAND_PATH: u32 = 3222163872u32;
pub const ERROR_PCW_FAMILY_RANGE_BAD_RETAIN_LENGTHS: u32 = 3222163809u32;
pub const ERROR_PCW_FAMILY_RANGE_BAD_RETAIN_OFFSETS: u32 = 3222163806u32;
pub const ERROR_PCW_FAMILY_RANGE_BLANK_FILE_TABLE_KEY: u32 = 3222163803u32;
pub const ERROR_PCW_FAMILY_RANGE_BLANK_RETAIN_LENGTHS: u32 = 3222163808u32;
pub const ERROR_PCW_FAMILY_RANGE_BLANK_RETAIN_OFFSETS: u32 = 3222163805u32;
pub const ERROR_PCW_FAMILY_RANGE_COUNT_MISMATCH: u32 = 3222163810u32;
pub const ERROR_PCW_FAMILY_RANGE_LONG_FILE_TABLE_KEY: u32 = 3222163802u32;
pub const ERROR_PCW_FAMILY_RANGE_LONG_RETAIN_LENGTHS: u32 = 3222163807u32;
pub const ERROR_PCW_FAMILY_RANGE_LONG_RETAIN_OFFSETS: u32 = 3222163804u32;
pub const ERROR_PCW_FAMILY_RANGE_NAME_TOO_LONG: u32 = 3222163800u32;
pub const ERROR_PCW_IMAGE_FAMILY_NAME_TOO_LONG: u32 = 3222163747u32;
pub const ERROR_PCW_IMAGE_PATH_NOT_EXIST: u32 = 3222163988u32;
pub const ERROR_PCW_INTERNAL_ERROR: u32 = 3222163969u32;
pub const ERROR_PCW_INVALID_LOG_LEVEL: u32 = 3222163862u32;
pub const ERROR_PCW_INVALID_MAJOR_VERSION: u32 = 3222163990u32;
pub const ERROR_PCW_INVALID_PARAMETER: u32 = 3222163860u32;
pub const ERROR_PCW_INVALID_PATCHMETADATA_PROP: u32 = 3222163856u32;
pub const ERROR_PCW_INVALID_PATCH_TYPE_SEQUENCING: u32 = 3222163977u32;
pub const ERROR_PCW_INVALID_PCP_EXTERNALFILES: u32 = 3222163982u32;
pub const ERROR_PCW_INVALID_PCP_FAMILYFILERANGES: u32 = 3222163992u32;
pub const ERROR_PCW_INVALID_PCP_IMAGEFAMILIES: u32 = 3222163983u32;
pub const ERROR_PCW_INVALID_PCP_PATCHSEQUENCE: u32 = 3222163984u32;
pub const ERROR_PCW_INVALID_PCP_PROPERTIES: u32 = 3222163991u32;
pub const ERROR_PCW_INVALID_PCP_PROPERTY: u32 = 3222163970u32;
pub const ERROR_PCW_INVALID_PCP_TARGETFILES_OPTIONALDATA: u32 = 3222163985u32;
pub const ERROR_PCW_INVALID_PCP_TARGETIMAGES: u32 = 3222163971u32;
pub const ERROR_PCW_INVALID_PCP_UPGRADEDFILESTOIGNORE: u32 = 3222163980u32;
pub const ERROR_PCW_INVALID_PCP_UPGRADEDFILES_OPTIONALDATA: u32 = 3222163986u32;
pub const ERROR_PCW_INVALID_PCP_UPGRADEDIMAGES: u32 = 3222163981u32;
pub const ERROR_PCW_INVALID_RANGE_ELEMENT: u32 = 3222163989u32;
pub const ERROR_PCW_INVALID_SUPERCEDENCE: u32 = 3222163857u32;
pub const ERROR_PCW_INVALID_SUPERSEDENCE_VALUE: u32 = 3222163976u32;
pub const ERROR_PCW_INVALID_UI_LEVEL: u32 = 3222163863u32;
pub const ERROR_PCW_LAX_VALIDATION_FLAGS: u32 = 3222163972u32;
pub const ERROR_PCW_MAJOR_UPGD_WITHOUT_SEQUENCING: u32 = 3222163843u32;
pub const ERROR_PCW_MATCHED_PRODUCT_VERSIONS: u32 = 3222163837u32;
pub const ERROR_PCW_MISMATCHED_PRODUCT_CODES: u32 = 3222163779u32;
pub const ERROR_PCW_MISMATCHED_PRODUCT_VERSIONS: u32 = 3222163780u32;
pub const ERROR_PCW_MISSING_DIRECTORY_TABLE: u32 = 3222163975u32;
pub const ERROR_PCW_MISSING_PATCHMETADATA: u32 = 3222163987u32;
pub const ERROR_PCW_MISSING_PATCH_GUID: u32 = 3222163719u32;
pub const ERROR_PCW_MISSING_PATCH_PATH: u32 = 3222163716u32;
pub const ERROR_PCW_NO_UPGRADED_IMAGES_TO_PATCH: u32 = 3222163723u32;
pub const ERROR_PCW_NULL_PATCHFAMILY: u32 = 3222163850u32;
pub const ERROR_PCW_NULL_SEQUENCE_NUMBER: u32 = 3222163851u32;
pub const ERROR_PCW_OBSOLETION_WITH_MSI30: u32 = 3222163839u32;
pub const ERROR_PCW_OBSOLETION_WITH_PATCHSEQUENCE: u32 = 3222163840u32;
pub const ERROR_PCW_OBSOLETION_WITH_SEQUENCE_DATA: u32 = 3222163838u32;
pub const ERROR_PCW_OODS_COPYING_MSI: u32 = 3222163726u32;
pub const ERROR_PCW_OPEN_VIEW: u32 = 3222163869u32;
pub const ERROR_PCW_OUT_OF_MEMORY: u32 = 3222163865u32;
pub const ERROR_PCW_PATCHMETADATA_PROP_NOT_SET: u32 = 3222163855u32;
pub const ERROR_PCW_PCP_BAD_FORMAT: u32 = 3222163714u32;
pub const ERROR_PCW_PCP_DOESNT_EXIST: u32 = 3222163713u32;
pub const ERROR_PCW_SEQUENCING_BAD_TARGET: u32 = 3222163854u32;
pub const ERROR_PCW_TARGET_BAD_PROD_CODE_VAL: u32 = 3222163744u32;
pub const ERROR_PCW_TARGET_BAD_PROD_VALIDATE: u32 = 3222163743u32;
pub const ERROR_PCW_TARGET_IMAGE_COMPRESSED: u32 = 3222163742u32;
pub const ERROR_PCW_TARGET_IMAGE_NAME_TOO_LONG: u32 = 3222163735u32;
pub const ERROR_PCW_TARGET_IMAGE_PATH_EMPTY: u32 = 3222163739u32;
pub const ERROR_PCW_TARGET_IMAGE_PATH_NOT_EXIST: u32 = 3222163740u32;
pub const ERROR_PCW_TARGET_IMAGE_PATH_NOT_MSI: u32 = 3222163741u32;
pub const ERROR_PCW_TARGET_IMAGE_PATH_TOO_LONG: u32 = 3222163738u32;
pub const ERROR_PCW_TARGET_MISSING_SRC_FILES: u32 = 3222163746u32;
pub const ERROR_PCW_TARGET_WRONG_PRODUCT_VERSION_COMP: u32 = 3222163979u32;
pub const ERROR_PCW_TFILEDATA_BAD_IGNORE_LENGTHS: u32 = 3222163822u32;
pub const ERROR_PCW_TFILEDATA_BAD_IGNORE_OFFSETS: u32 = 3222163820u32;
pub const ERROR_PCW_TFILEDATA_BAD_RETAIN_OFFSETS: u32 = 3222163825u32;
pub const ERROR_PCW_TFILEDATA_BAD_TARGET_FIELD: u32 = 3222163791u32;
pub const ERROR_PCW_TFILEDATA_BLANK_FILE_TABLE_KEY: u32 = 3222163789u32;
pub const ERROR_PCW_TFILEDATA_IGNORE_COUNT_MISMATCH: u32 = 3222163823u32;
pub const ERROR_PCW_TFILEDATA_LONG_FILE_TABLE_KEY: u32 = 3222163788u32;
pub const ERROR_PCW_TFILEDATA_LONG_IGNORE_LENGTHS: u32 = 3222163821u32;
pub const ERROR_PCW_TFILEDATA_LONG_IGNORE_OFFSETS: u32 = 3222163819u32;
pub const ERROR_PCW_TFILEDATA_LONG_RETAIN_OFFSETS: u32 = 3222163824u32;
pub const ERROR_PCW_TFILEDATA_MISSING_FILE_TABLE_KEY: u32 = 3222163790u32;
pub const ERROR_PCW_UFILEDATA_BAD_UPGRADED_FIELD: u32 = 3222163778u32;
pub const ERROR_PCW_UFILEDATA_BLANK_FILE_TABLE_KEY: u32 = 3222163752u32;
pub const ERROR_PCW_UFILEDATA_LONG_FILE_TABLE_KEY: u32 = 3222163751u32;
pub const ERROR_PCW_UFILEDATA_MISSING_FILE_TABLE_KEY: u32 = 3222163753u32;
pub const ERROR_PCW_UFILEIGNORE_BAD_FILE_TABLE_KEY: u32 = 3222163799u32;
pub const ERROR_PCW_UFILEIGNORE_BAD_UPGRADED_FIELD: u32 = 3222163796u32;
pub const ERROR_PCW_UFILEIGNORE_BLANK_FILE_TABLE_KEY: u32 = 3222163798u32;
pub const ERROR_PCW_UFILEIGNORE_LONG_FILE_TABLE_KEY: u32 = 3222163797u32;
pub const ERROR_PCW_UNKNOWN_ERROR: u32 = 3222163866u32;
pub const ERROR_PCW_UNKNOWN_INFO: u32 = 3222163867u32;
pub const ERROR_PCW_UNKNOWN_WARN: u32 = 3222163868u32;
pub const ERROR_PCW_UPGRADED_IMAGE_COMPRESSED: u32 = 3222163734u32;
pub const ERROR_PCW_UPGRADED_IMAGE_NAME_TOO_LONG: u32 = 3222163727u32;
pub const ERROR_PCW_UPGRADED_IMAGE_PATCH_PATH_NOT_EXIST: u32 = 3222163793u32;
pub const ERROR_PCW_UPGRADED_IMAGE_PATCH_PATH_NOT_MSI: u32 = 3222163794u32;
pub const ERROR_PCW_UPGRADED_IMAGE_PATCH_PATH_TOO_LONG: u32 = 3222163792u32;
pub const ERROR_PCW_UPGRADED_IMAGE_PATH_EMPTY: u32 = 3222163731u32;
pub const ERROR_PCW_UPGRADED_IMAGE_PATH_NOT_EXIST: u32 = 3222163732u32;
pub const ERROR_PCW_UPGRADED_IMAGE_PATH_NOT_MSI: u32 = 3222163733u32;
pub const ERROR_PCW_UPGRADED_IMAGE_PATH_TOO_LONG: u32 = 3222163730u32;
pub const ERROR_PCW_UPGRADED_MISSING_SRC_FILES: u32 = 3222163745u32;
pub const ERROR_PCW_VIEW_FETCH: u32 = 3222163871u32;
pub const ERROR_PCW_WRITE_SUMMARY_PROPERTIES: u32 = 3222163787u32;
pub const ERROR_PCW_WRONG_PATCHMETADATA_STRD_PROP: u32 = 3222163859u32;
pub const ERROR_ROLLBACK_DISABLED: u32 = 1653u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct FUSION_INSTALL_REFERENCE {
pub cbSize: u32,
pub dwFlags: u32,
pub guidScheme: ::windows_sys::core::GUID,
pub szIdentifier: super::super::Foundation::PWSTR,
pub szNonCannonicalData: super::super::Foundation::PWSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for FUSION_INSTALL_REFERENCE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for FUSION_INSTALL_REFERENCE {
fn clone(&self) -> Self {
*self
}
}
pub const FUSION_REFCOUNT_FILEPATH_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2955910501,
data2: 64375,
data3: 20346,
data4: [175, 165, 179, 145, 48, 159, 17, 201],
};
pub const FUSION_REFCOUNT_OPAQUE_STRING_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 784938083,
data2: 45251,
data3: 17889,
data4: [131, 100, 50, 126, 150, 174, 168, 86],
};
pub const FUSION_REFCOUNT_UNINSTALL_SUBKEY_GUID: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2364391957,
data2: 44107,
data3: 18571,
data4: [147, 192, 165, 10, 73, 203, 47, 184],
};
pub const IASSEMBLYCACHEITEM_COMMIT_DISPOSITION_ALREADY_INSTALLED: u32 = 3u32;
pub const IASSEMBLYCACHEITEM_COMMIT_DISPOSITION_INSTALLED: u32 = 1u32;
pub const IASSEMBLYCACHEITEM_COMMIT_DISPOSITION_REFRESHED: u32 = 2u32;
pub const IASSEMBLYCACHEITEM_COMMIT_FLAG_REFRESH: u32 = 1u32;
pub type IASSEMBLYCACHE_UNINSTALL_DISPOSITION = u32;
pub const IASSEMBLYCACHE_UNINSTALL_DISPOSITION_UNINSTALLED: IASSEMBLYCACHE_UNINSTALL_DISPOSITION = 1u32;
pub const IASSEMBLYCACHE_UNINSTALL_DISPOSITION_STILL_IN_USE: IASSEMBLYCACHE_UNINSTALL_DISPOSITION = 2u32;
pub const IASSEMBLYCACHE_UNINSTALL_DISPOSITION_ALREADY_UNINSTALLED: IASSEMBLYCACHE_UNINSTALL_DISPOSITION = 3u32;
pub const IASSEMBLYCACHE_UNINSTALL_DISPOSITION_DELETE_PENDING: IASSEMBLYCACHE_UNINSTALL_DISPOSITION = 4u32;
pub type IAssemblyCache = *mut ::core::ffi::c_void;
pub type IAssemblyCacheItem = *mut ::core::ffi::c_void;
pub type IAssemblyName = *mut ::core::ffi::c_void;
pub type IEnumMsmDependency = *mut ::core::ffi::c_void;
pub type IEnumMsmError = *mut ::core::ffi::c_void;
pub type IEnumMsmString = *mut ::core::ffi::c_void;
pub type IMsmDependencies = *mut ::core::ffi::c_void;
pub type IMsmDependency = *mut ::core::ffi::c_void;
pub type IMsmError = *mut ::core::ffi::c_void;
pub type IMsmErrors = *mut ::core::ffi::c_void;
pub type IMsmGetFiles = *mut ::core::ffi::c_void;
pub type IMsmMerge = *mut ::core::ffi::c_void;
pub type IMsmStrings = *mut ::core::ffi::c_void;
pub const INFO_BASE: u32 = 3222229249u32;
pub const INFO_ENTERING_PHASE_I: u32 = 3222229251u32;
pub const INFO_ENTERING_PHASE_II: u32 = 3222229256u32;
pub const INFO_ENTERING_PHASE_III: u32 = 3222229257u32;
pub const INFO_ENTERING_PHASE_IV: u32 = 3222229258u32;
pub const INFO_ENTERING_PHASE_I_VALIDATION: u32 = 3222229250u32;
pub const INFO_ENTERING_PHASE_V: u32 = 3222229259u32;
pub const INFO_GENERATING_METADATA: u32 = 3222229265u32;
pub const INFO_PASSED_MAIN_CONTROL: u32 = 3222229249u32;
pub const INFO_PATCHCACHE_FILEINFO_FAILURE: u32 = 3222229267u32;
pub const INFO_PATCHCACHE_PCI_READFAILURE: u32 = 3222229268u32;
pub const INFO_PATCHCACHE_PCI_WRITEFAILURE: u32 = 3222229269u32;
pub const INFO_PCP_PATH: u32 = 3222229252u32;
pub const INFO_PROPERTY: u32 = 3222229255u32;
pub const INFO_SET_OPTIONS: u32 = 3222229254u32;
pub const INFO_SUCCESSFUL_PATCH_CREATION: u32 = 3222229271u32;
pub const INFO_TEMP_DIR: u32 = 3222229253u32;
pub const INFO_TEMP_DIR_CLEANUP: u32 = 3222229266u32;
pub const INFO_USING_USER_MSI_FOR_PATCH_TABLES: u32 = 3222229270u32;
pub type INSTALLFEATUREATTRIBUTE = i32;
pub const INSTALLFEATUREATTRIBUTE_FAVORLOCAL: INSTALLFEATUREATTRIBUTE = 1i32;
pub const INSTALLFEATUREATTRIBUTE_FAVORSOURCE: INSTALLFEATUREATTRIBUTE = 2i32;
pub const INSTALLFEATUREATTRIBUTE_FOLLOWPARENT: INSTALLFEATUREATTRIBUTE = 4i32;
pub const INSTALLFEATUREATTRIBUTE_FAVORADVERTISE: INSTALLFEATUREATTRIBUTE = 8i32;
pub const INSTALLFEATUREATTRIBUTE_DISALLOWADVERTISE: INSTALLFEATUREATTRIBUTE = 16i32;
pub const INSTALLFEATUREATTRIBUTE_NOUNSUPPORTEDADVERTISE: INSTALLFEATUREATTRIBUTE = 32i32;
pub type INSTALLLEVEL = i32;
pub const INSTALLLEVEL_DEFAULT: INSTALLLEVEL = 0i32;
pub const INSTALLLEVEL_MINIMUM: INSTALLLEVEL = 1i32;
pub const INSTALLLEVEL_MAXIMUM: INSTALLLEVEL = 65535i32;
pub type INSTALLLOGATTRIBUTES = i32;
pub const INSTALLLOGATTRIBUTES_APPEND: INSTALLLOGATTRIBUTES = 1i32;
pub const INSTALLLOGATTRIBUTES_FLUSHEACHLINE: INSTALLLOGATTRIBUTES = 2i32;
pub type INSTALLMESSAGE = i32;
pub const INSTALLMESSAGE_FATALEXIT: INSTALLMESSAGE = 0i32;
pub const INSTALLMESSAGE_ERROR: INSTALLMESSAGE = 16777216i32;
pub const INSTALLMESSAGE_WARNING: INSTALLMESSAGE = 33554432i32;
pub const INSTALLMESSAGE_USER: INSTALLMESSAGE = 50331648i32;
pub const INSTALLMESSAGE_INFO: INSTALLMESSAGE = 67108864i32;
pub const INSTALLMESSAGE_FILESINUSE: INSTALLMESSAGE = 83886080i32;
pub const INSTALLMESSAGE_RESOLVESOURCE: INSTALLMESSAGE = 100663296i32;
pub const INSTALLMESSAGE_OUTOFDISKSPACE: INSTALLMESSAGE = 117440512i32;
pub const INSTALLMESSAGE_ACTIONSTART: INSTALLMESSAGE = 134217728i32;
pub const INSTALLMESSAGE_ACTIONDATA: INSTALLMESSAGE = 150994944i32;
pub const INSTALLMESSAGE_PROGRESS: INSTALLMESSAGE = 167772160i32;
pub const INSTALLMESSAGE_COMMONDATA: INSTALLMESSAGE = 184549376i32;
pub const INSTALLMESSAGE_INITIALIZE: INSTALLMESSAGE = 201326592i32;
pub const INSTALLMESSAGE_TERMINATE: INSTALLMESSAGE = 218103808i32;
pub const INSTALLMESSAGE_SHOWDIALOG: INSTALLMESSAGE = 234881024i32;
pub const INSTALLMESSAGE_PERFORMANCE: INSTALLMESSAGE = 251658240i32;
pub const INSTALLMESSAGE_RMFILESINUSE: INSTALLMESSAGE = 419430400i32;
pub const INSTALLMESSAGE_INSTALLSTART: INSTALLMESSAGE = 436207616i32;
pub const INSTALLMESSAGE_INSTALLEND: INSTALLMESSAGE = 452984832i32;
pub const INSTALLMESSAGE_TYPEMASK: i32 = -16777216i32;
pub type INSTALLMODE = i32;
pub const INSTALLMODE_NODETECTION_ANY: INSTALLMODE = -4i32;
pub const INSTALLMODE_NOSOURCERESOLUTION: INSTALLMODE = -3i32;
pub const INSTALLMODE_NODETECTION: INSTALLMODE = -2i32;
pub const INSTALLMODE_EXISTING: INSTALLMODE = -1i32;
pub const INSTALLMODE_DEFAULT: INSTALLMODE = 0i32;
pub type INSTALLOGMODE = i32;
pub const INSTALLLOGMODE_FATALEXIT: INSTALLOGMODE = 1i32;
pub const INSTALLLOGMODE_ERROR: INSTALLOGMODE = 2i32;
pub const INSTALLLOGMODE_WARNING: INSTALLOGMODE = 4i32;
pub const INSTALLLOGMODE_USER: INSTALLOGMODE = 8i32;
pub const INSTALLLOGMODE_INFO: INSTALLOGMODE = 16i32;
pub const INSTALLLOGMODE_RESOLVESOURCE: INSTALLOGMODE = 64i32;
pub const INSTALLLOGMODE_OUTOFDISKSPACE: INSTALLOGMODE = 128i32;
pub const INSTALLLOGMODE_ACTIONSTART: INSTALLOGMODE = 256i32;
pub const INSTALLLOGMODE_ACTIONDATA: INSTALLOGMODE = 512i32;
pub const INSTALLLOGMODE_COMMONDATA: INSTALLOGMODE = 2048i32;
pub const INSTALLLOGMODE_PROPERTYDUMP: INSTALLOGMODE = 1024i32;
pub const INSTALLLOGMODE_VERBOSE: INSTALLOGMODE = 4096i32;
pub const INSTALLLOGMODE_EXTRADEBUG: INSTALLOGMODE = 8192i32;
pub const INSTALLLOGMODE_LOGONLYONERROR: INSTALLOGMODE = 16384i32;
pub const INSTALLLOGMODE_LOGPERFORMANCE: INSTALLOGMODE = 32768i32;
pub const INSTALLLOGMODE_PROGRESS: INSTALLOGMODE = 1024i32;
pub const INSTALLLOGMODE_INITIALIZE: INSTALLOGMODE = 4096i32;
pub const INSTALLLOGMODE_TERMINATE: INSTALLOGMODE = 8192i32;
pub const INSTALLLOGMODE_SHOWDIALOG: INSTALLOGMODE = 16384i32;
pub const INSTALLLOGMODE_FILESINUSE: INSTALLOGMODE = 32i32;
pub const INSTALLLOGMODE_RMFILESINUSE: INSTALLOGMODE = 33554432i32;
pub const INSTALLLOGMODE_INSTALLSTART: INSTALLOGMODE = 67108864i32;
pub const INSTALLLOGMODE_INSTALLEND: INSTALLOGMODE = 134217728i32;
pub type INSTALLSTATE = i32;
pub const INSTALLSTATE_NOTUSED: INSTALLSTATE = -7i32;
pub const INSTALLSTATE_BADCONFIG: INSTALLSTATE = -6i32;
pub const INSTALLSTATE_INCOMPLETE: INSTALLSTATE = -5i32;
pub const INSTALLSTATE_SOURCEABSENT: INSTALLSTATE = -4i32;
pub const INSTALLSTATE_MOREDATA: INSTALLSTATE = -3i32;
pub const INSTALLSTATE_INVALIDARG: INSTALLSTATE = -2i32;
pub const INSTALLSTATE_UNKNOWN: INSTALLSTATE = -1i32;
pub const INSTALLSTATE_BROKEN: INSTALLSTATE = 0i32;
pub const INSTALLSTATE_ADVERTISED: INSTALLSTATE = 1i32;
pub const INSTALLSTATE_REMOVED: INSTALLSTATE = 1i32;
pub const INSTALLSTATE_ABSENT: INSTALLSTATE = 2i32;
pub const INSTALLSTATE_LOCAL: INSTALLSTATE = 3i32;
pub const INSTALLSTATE_SOURCE: INSTALLSTATE = 4i32;
pub const INSTALLSTATE_DEFAULT: INSTALLSTATE = 5i32;
pub type INSTALLTYPE = i32;
pub const INSTALLTYPE_DEFAULT: INSTALLTYPE = 0i32;
pub const INSTALLTYPE_NETWORK_IMAGE: INSTALLTYPE = 1i32;
pub const INSTALLTYPE_SINGLE_INSTANCE: INSTALLTYPE = 2i32;
pub type INSTALLUILEVEL = i32;
pub const INSTALLUILEVEL_NOCHANGE: INSTALLUILEVEL = 0i32;
pub const INSTALLUILEVEL_DEFAULT: INSTALLUILEVEL = 1i32;
pub const INSTALLUILEVEL_NONE: INSTALLUILEVEL = 2i32;
pub const INSTALLUILEVEL_BASIC: INSTALLUILEVEL = 3i32;
pub const INSTALLUILEVEL_REDUCED: INSTALLUILEVEL = 4i32;
pub const INSTALLUILEVEL_FULL: INSTALLUILEVEL = 5i32;
pub const INSTALLUILEVEL_ENDDIALOG: INSTALLUILEVEL = 128i32;
pub const INSTALLUILEVEL_PROGRESSONLY: INSTALLUILEVEL = 64i32;
pub const INSTALLUILEVEL_HIDECANCEL: INSTALLUILEVEL = 32i32;
pub const INSTALLUILEVEL_SOURCERESONLY: INSTALLUILEVEL = 256i32;
pub const INSTALLUILEVEL_UACONLY: INSTALLUILEVEL = 512i32;
#[cfg(feature = "Win32_Foundation")]
pub type INSTALLUI_HANDLERA = ::core::option::Option<unsafe extern "system" fn(pvcontext: *mut ::core::ffi::c_void, imessagetype: u32, szmessage: super::super::Foundation::PSTR) -> i32>;
#[cfg(feature = "Win32_Foundation")]
pub type INSTALLUI_HANDLERW = ::core::option::Option<unsafe extern "system" fn(pvcontext: *mut ::core::ffi::c_void, imessagetype: u32, szmessage: super::super::Foundation::PWSTR) -> i32>;
pub type IPMApplicationInfo = *mut ::core::ffi::c_void;
pub type IPMApplicationInfoEnumerator = *mut ::core::ffi::c_void;
pub type IPMBackgroundServiceAgentInfo = *mut ::core::ffi::c_void;
pub type IPMBackgroundServiceAgentInfoEnumerator = *mut ::core::ffi::c_void;
pub type IPMBackgroundWorkerInfo = *mut ::core::ffi::c_void;
pub type IPMBackgroundWorkerInfoEnumerator = *mut ::core::ffi::c_void;
pub type IPMDeploymentManager = *mut ::core::ffi::c_void;
pub type IPMEnumerationManager = *mut ::core::ffi::c_void;
pub type IPMExtensionCachedFileUpdaterInfo = *mut ::core::ffi::c_void;
pub type IPMExtensionContractInfo = *mut ::core::ffi::c_void;
pub type IPMExtensionFileExtensionInfo = *mut ::core::ffi::c_void;
pub type IPMExtensionFileOpenPickerInfo = *mut ::core::ffi::c_void;
pub type IPMExtensionFileSavePickerInfo = *mut ::core::ffi::c_void;
pub type IPMExtensionInfo = *mut ::core::ffi::c_void;
pub type IPMExtensionInfoEnumerator = *mut ::core::ffi::c_void;
pub type IPMExtensionProtocolInfo = *mut ::core::ffi::c_void;
pub type IPMExtensionShareTargetInfo = *mut ::core::ffi::c_void;
pub type IPMLiveTileJobInfo = *mut ::core::ffi::c_void;
pub type IPMLiveTileJobInfoEnumerator = *mut ::core::ffi::c_void;
pub type IPMTaskInfo = *mut ::core::ffi::c_void;
pub type IPMTaskInfoEnumerator = *mut ::core::ffi::c_void;
pub type IPMTileInfo = *mut ::core::ffi::c_void;
pub type IPMTileInfoEnumerator = *mut ::core::ffi::c_void;
pub type IPMTilePropertyEnumerator = *mut ::core::ffi::c_void;
pub type IPMTilePropertyInfo = *mut ::core::ffi::c_void;
pub type IValidate = *mut ::core::ffi::c_void;
pub const LIBID_MsmMergeTypeLib: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 182298671, data2: 11302, data3: 4562, data4: [173, 101, 0, 160, 201, 175, 17, 166] };
pub const LOGALL: u32 = 15u32;
pub const LOGERR: u32 = 4u32;
pub const LOGINFO: u32 = 1u32;
pub const LOGNONE: u32 = 0u32;
pub const LOGPERFMESSAGES: u32 = 8u32;
pub const LOGTOKEN_NO_LOG: u32 = 1u32;
pub const LOGTOKEN_SETUPAPI_APPLOG: u32 = 2u32;
pub const LOGTOKEN_SETUPAPI_DEVLOG: u32 = 3u32;
pub const LOGTOKEN_TYPE_MASK: u32 = 3u32;
pub const LOGTOKEN_UNSPECIFIED: u32 = 0u32;
pub const LOGWARN: u32 = 2u32;
#[cfg(feature = "Win32_Foundation")]
pub type LPDISPLAYVAL = ::core::option::Option<unsafe extern "system" fn(pcontext: *mut ::core::ffi::c_void, uitype: RESULTTYPES, szwval: super::super::Foundation::PWSTR, szwdescription: super::super::Foundation::PWSTR, szwlocation: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL>;
#[cfg(feature = "Win32_Foundation")]
pub type LPEVALCOMCALLBACK = ::core::option::Option<unsafe extern "system" fn(istatus: STATUSTYPES, szdata: super::super::Foundation::PWSTR, pcontext: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL>;
pub const MAX_FEATURE_CHARS: u32 = 38u32;
pub const MAX_GUID_CHARS: u32 = 38u32;
pub type MSIADVERTISEOPTIONFLAGS = i32;
pub const MSIADVERTISEOPTIONFLAGS_INSTANCE: MSIADVERTISEOPTIONFLAGS = 1i32;
pub type MSIARCHITECTUREFLAGS = i32;
pub const MSIARCHITECTUREFLAGS_X86: MSIARCHITECTUREFLAGS = 1i32;
pub const MSIARCHITECTUREFLAGS_IA64: MSIARCHITECTUREFLAGS = 2i32;
pub const MSIARCHITECTUREFLAGS_AMD64: MSIARCHITECTUREFLAGS = 4i32;
pub const MSIARCHITECTUREFLAGS_ARM: MSIARCHITECTUREFLAGS = 8i32;
pub type MSIASSEMBLYINFO = u32;
pub const MSIASSEMBLYINFO_NETASSEMBLY: MSIASSEMBLYINFO = 0u32;
pub const MSIASSEMBLYINFO_WIN32ASSEMBLY: MSIASSEMBLYINFO = 1u32;
pub type MSICODE = i32;
pub const MSICODE_PRODUCT: MSICODE = 0i32;
pub const MSICODE_PATCH: MSICODE = 1073741824i32;
pub type MSICOLINFO = i32;
pub const MSICOLINFO_NAMES: MSICOLINFO = 0i32;
pub const MSICOLINFO_TYPES: MSICOLINFO = 1i32;
pub type MSICONDITION = i32;
pub const MSICONDITION_FALSE: MSICONDITION = 0i32;
pub const MSICONDITION_TRUE: MSICONDITION = 1i32;
pub const MSICONDITION_NONE: MSICONDITION = 2i32;
pub const MSICONDITION_ERROR: MSICONDITION = 3i32;
pub type MSICOSTTREE = i32;
pub const MSICOSTTREE_SELFONLY: MSICOSTTREE = 0i32;
pub const MSICOSTTREE_CHILDREN: MSICOSTTREE = 1i32;
pub const MSICOSTTREE_PARENTS: MSICOSTTREE = 2i32;
pub const MSICOSTTREE_RESERVED: MSICOSTTREE = 3i32;
pub type MSIDBERROR = i32;
pub const MSIDBERROR_INVALIDARG: MSIDBERROR = -3i32;
pub const MSIDBERROR_MOREDATA: MSIDBERROR = -2i32;
pub const MSIDBERROR_FUNCTIONERROR: MSIDBERROR = -1i32;
pub const MSIDBERROR_NOERROR: MSIDBERROR = 0i32;
pub const MSIDBERROR_DUPLICATEKEY: MSIDBERROR = 1i32;
pub const MSIDBERROR_REQUIRED: MSIDBERROR = 2i32;
pub const MSIDBERROR_BADLINK: MSIDBERROR = 3i32;
pub const MSIDBERROR_OVERFLOW: MSIDBERROR = 4i32;
pub const MSIDBERROR_UNDERFLOW: MSIDBERROR = 5i32;
pub const MSIDBERROR_NOTINSET: MSIDBERROR = 6i32;
pub const MSIDBERROR_BADVERSION: MSIDBERROR = 7i32;
pub const MSIDBERROR_BADCASE: MSIDBERROR = 8i32;
pub const MSIDBERROR_BADGUID: MSIDBERROR = 9i32;
pub const MSIDBERROR_BADWILDCARD: MSIDBERROR = 10i32;
pub const MSIDBERROR_BADIDENTIFIER: MSIDBERROR = 11i32;
pub const MSIDBERROR_BADLANGUAGE: MSIDBERROR = 12i32;
pub const MSIDBERROR_BADFILENAME: MSIDBERROR = 13i32;
pub const MSIDBERROR_BADPATH: MSIDBERROR = 14i32;
pub const MSIDBERROR_BADCONDITION: MSIDBERROR = 15i32;
pub const MSIDBERROR_BADFORMATTED: MSIDBERROR = 16i32;
pub const MSIDBERROR_BADTEMPLATE: MSIDBERROR = 17i32;
pub const MSIDBERROR_BADDEFAULTDIR: MSIDBERROR = 18i32;
pub const MSIDBERROR_BADREGPATH: MSIDBERROR = 19i32;
pub const MSIDBERROR_BADCUSTOMSOURCE: MSIDBERROR = 20i32;
pub const MSIDBERROR_BADPROPERTY: MSIDBERROR = 21i32;
pub const MSIDBERROR_MISSINGDATA: MSIDBERROR = 22i32;
pub const MSIDBERROR_BADCATEGORY: MSIDBERROR = 23i32;
pub const MSIDBERROR_BADKEYTABLE: MSIDBERROR = 24i32;
pub const MSIDBERROR_BADMAXMINVALUES: MSIDBERROR = 25i32;
pub const MSIDBERROR_BADCABINET: MSIDBERROR = 26i32;
pub const MSIDBERROR_BADSHORTCUT: MSIDBERROR = 27i32;
pub const MSIDBERROR_STRINGOVERFLOW: MSIDBERROR = 28i32;
pub const MSIDBERROR_BADLOCALIZEATTRIB: MSIDBERROR = 29i32;
pub type MSIDBSTATE = i32;
pub const MSIDBSTATE_ERROR: MSIDBSTATE = -1i32;
pub const MSIDBSTATE_READ: MSIDBSTATE = 0i32;
pub const MSIDBSTATE_WRITE: MSIDBSTATE = 1i32;
#[repr(C)]
pub struct MSIFILEHASHINFO {
pub dwFileHashInfoSize: u32,
pub dwData: [u32; 4],
}
impl ::core::marker::Copy for MSIFILEHASHINFO {}
impl ::core::clone::Clone for MSIFILEHASHINFO {
fn clone(&self) -> Self {
*self
}
}
pub type MSIHANDLE = u32;
pub type MSIINSTALLCONTEXT = i32;
pub const MSIINSTALLCONTEXT_FIRSTVISIBLE: MSIINSTALLCONTEXT = 0i32;
pub const MSIINSTALLCONTEXT_NONE: MSIINSTALLCONTEXT = 0i32;
pub const MSIINSTALLCONTEXT_USERMANAGED: MSIINSTALLCONTEXT = 1i32;
pub const MSIINSTALLCONTEXT_USERUNMANAGED: MSIINSTALLCONTEXT = 2i32;
pub const MSIINSTALLCONTEXT_MACHINE: MSIINSTALLCONTEXT = 4i32;
pub const MSIINSTALLCONTEXT_ALL: MSIINSTALLCONTEXT = 7i32;
pub const MSIINSTALLCONTEXT_ALLUSERMANAGED: MSIINSTALLCONTEXT = 8i32;
pub type MSIMODIFY = i32;
pub const MSIMODIFY_SEEK: MSIMODIFY = -1i32;
pub const MSIMODIFY_REFRESH: MSIMODIFY = 0i32;
pub const MSIMODIFY_INSERT: MSIMODIFY = 1i32;
pub const MSIMODIFY_UPDATE: MSIMODIFY = 2i32;
pub const MSIMODIFY_ASSIGN: MSIMODIFY = 3i32;
pub const MSIMODIFY_REPLACE: MSIMODIFY = 4i32;
pub const MSIMODIFY_MERGE: MSIMODIFY = 5i32;
pub const MSIMODIFY_DELETE: MSIMODIFY = 6i32;
pub const MSIMODIFY_INSERT_TEMPORARY: MSIMODIFY = 7i32;
pub const MSIMODIFY_VALIDATE: MSIMODIFY = 8i32;
pub const MSIMODIFY_VALIDATE_NEW: MSIMODIFY = 9i32;
pub const MSIMODIFY_VALIDATE_FIELD: MSIMODIFY = 10i32;
pub const MSIMODIFY_VALIDATE_DELETE: MSIMODIFY = 11i32;
pub type MSIOPENPACKAGEFLAGS = i32;
pub const MSIOPENPACKAGEFLAGS_IGNOREMACHINESTATE: MSIOPENPACKAGEFLAGS = 1i32;
pub type MSIPATCHDATATYPE = i32;
pub const MSIPATCH_DATATYPE_PATCHFILE: MSIPATCHDATATYPE = 0i32;
pub const MSIPATCH_DATATYPE_XMLPATH: MSIPATCHDATATYPE = 1i32;
pub const MSIPATCH_DATATYPE_XMLBLOB: MSIPATCHDATATYPE = 2i32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct MSIPATCHSEQUENCEINFOA {
pub szPatchData: super::super::Foundation::PSTR,
pub ePatchDataType: MSIPATCHDATATYPE,
pub dwOrder: u32,
pub uStatus: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for MSIPATCHSEQUENCEINFOA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for MSIPATCHSEQUENCEINFOA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct MSIPATCHSEQUENCEINFOW {
pub szPatchData: super::super::Foundation::PWSTR,
pub ePatchDataType: MSIPATCHDATATYPE,
pub dwOrder: u32,
pub uStatus: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for MSIPATCHSEQUENCEINFOW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for MSIPATCHSEQUENCEINFOW {
fn clone(&self) -> Self {
*self
}
}
pub type MSIPATCHSTATE = i32;
pub const MSIPATCHSTATE_INVALID: MSIPATCHSTATE = 0i32;
pub const MSIPATCHSTATE_APPLIED: MSIPATCHSTATE = 1i32;
pub const MSIPATCHSTATE_SUPERSEDED: MSIPATCHSTATE = 2i32;
pub const MSIPATCHSTATE_OBSOLETED: MSIPATCHSTATE = 4i32;
pub const MSIPATCHSTATE_REGISTERED: MSIPATCHSTATE = 8i32;
pub const MSIPATCHSTATE_ALL: MSIPATCHSTATE = 15i32;
pub type MSIRUNMODE = i32;
pub const MSIRUNMODE_ADMIN: MSIRUNMODE = 0i32;
pub const MSIRUNMODE_ADVERTISE: MSIRUNMODE = 1i32;
pub const MSIRUNMODE_MAINTENANCE: MSIRUNMODE = 2i32;
pub const MSIRUNMODE_ROLLBACKENABLED: MSIRUNMODE = 3i32;
pub const MSIRUNMODE_LOGENABLED: MSIRUNMODE = 4i32;
pub const MSIRUNMODE_OPERATIONS: MSIRUNMODE = 5i32;
pub const MSIRUNMODE_REBOOTATEND: MSIRUNMODE = 6i32;
pub const MSIRUNMODE_REBOOTNOW: MSIRUNMODE = 7i32;
pub const MSIRUNMODE_CABINET: MSIRUNMODE = 8i32;
pub const MSIRUNMODE_SOURCESHORTNAMES: MSIRUNMODE = 9i32;
pub const MSIRUNMODE_TARGETSHORTNAMES: MSIRUNMODE = 10i32;
pub const MSIRUNMODE_RESERVED11: MSIRUNMODE = 11i32;
pub const MSIRUNMODE_WINDOWS9X: MSIRUNMODE = 12i32;
pub const MSIRUNMODE_ZAWENABLED: MSIRUNMODE = 13i32;
pub const MSIRUNMODE_RESERVED14: MSIRUNMODE = 14i32;
pub const MSIRUNMODE_RESERVED15: MSIRUNMODE = 15i32;
pub const MSIRUNMODE_SCHEDULED: MSIRUNMODE = 16i32;
pub const MSIRUNMODE_ROLLBACK: MSIRUNMODE = 17i32;
pub const MSIRUNMODE_COMMIT: MSIRUNMODE = 18i32;
pub type MSISOURCETYPE = i32;
pub const MSISOURCETYPE_UNKNOWN: MSISOURCETYPE = 0i32;
pub const MSISOURCETYPE_NETWORK: MSISOURCETYPE = 1i32;
pub const MSISOURCETYPE_URL: MSISOURCETYPE = 2i32;
pub const MSISOURCETYPE_MEDIA: MSISOURCETYPE = 4i32;
pub type MSITRANSACTION = i32;
pub const MSITRANSACTION_CHAIN_EMBEDDEDUI: MSITRANSACTION = 1i32;
pub const MSITRANSACTION_JOIN_EXISTING_EMBEDDEDUI: MSITRANSACTION = 2i32;
pub type MSITRANSACTIONSTATE = u32;
pub const MSITRANSACTIONSTATE_ROLLBACK: MSITRANSACTIONSTATE = 0u32;
pub const MSITRANSACTIONSTATE_COMMIT: MSITRANSACTIONSTATE = 1u32;
pub type MSITRANSFORM_ERROR = i32;
pub const MSITRANSFORM_ERROR_ADDEXISTINGROW: MSITRANSFORM_ERROR = 1i32;
pub const MSITRANSFORM_ERROR_DELMISSINGROW: MSITRANSFORM_ERROR = 2i32;
pub const MSITRANSFORM_ERROR_ADDEXISTINGTABLE: MSITRANSFORM_ERROR = 4i32;
pub const MSITRANSFORM_ERROR_DELMISSINGTABLE: MSITRANSFORM_ERROR = 8i32;
pub const MSITRANSFORM_ERROR_UPDATEMISSINGROW: MSITRANSFORM_ERROR = 16i32;
pub const MSITRANSFORM_ERROR_CHANGECODEPAGE: MSITRANSFORM_ERROR = 32i32;
pub const MSITRANSFORM_ERROR_VIEWTRANSFORM: MSITRANSFORM_ERROR = 256i32;
pub const MSITRANSFORM_ERROR_NONE: MSITRANSFORM_ERROR = 0i32;
pub type MSITRANSFORM_VALIDATE = i32;
pub const MSITRANSFORM_VALIDATE_LANGUAGE: MSITRANSFORM_VALIDATE = 1i32;
pub const MSITRANSFORM_VALIDATE_PRODUCT: MSITRANSFORM_VALIDATE = 2i32;
pub const MSITRANSFORM_VALIDATE_PLATFORM: MSITRANSFORM_VALIDATE = 4i32;
pub const MSITRANSFORM_VALIDATE_MAJORVERSION: MSITRANSFORM_VALIDATE = 8i32;
pub const MSITRANSFORM_VALIDATE_MINORVERSION: MSITRANSFORM_VALIDATE = 16i32;
pub const MSITRANSFORM_VALIDATE_UPDATEVERSION: MSITRANSFORM_VALIDATE = 32i32;
pub const MSITRANSFORM_VALIDATE_NEWLESSBASEVERSION: MSITRANSFORM_VALIDATE = 64i32;
pub const MSITRANSFORM_VALIDATE_NEWLESSEQUALBASEVERSION: MSITRANSFORM_VALIDATE = 128i32;
pub const MSITRANSFORM_VALIDATE_NEWEQUALBASEVERSION: MSITRANSFORM_VALIDATE = 256i32;
pub const MSITRANSFORM_VALIDATE_NEWGREATEREQUALBASEVERSION: MSITRANSFORM_VALIDATE = 512i32;
pub const MSITRANSFORM_VALIDATE_NEWGREATERBASEVERSION: MSITRANSFORM_VALIDATE = 1024i32;
pub const MSITRANSFORM_VALIDATE_UPGRADECODE: MSITRANSFORM_VALIDATE = 2048i32;
pub const MSI_INVALID_HASH_IS_FATAL: u32 = 1u32;
pub const MSI_NULL_INTEGER: u32 = 2147483648u32;
pub const MsmMerge: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 182298672, data2: 11302, data3: 4562, data4: [173, 101, 0, 160, 201, 175, 17, 166] };
pub type PACKMAN_RUNTIME = i32;
pub const PACKMAN_RUNTIME_NATIVE: PACKMAN_RUNTIME = 1i32;
pub const PACKMAN_RUNTIME_SILVERLIGHTMOBILE: PACKMAN_RUNTIME = 2i32;
pub const PACKMAN_RUNTIME_XNA: PACKMAN_RUNTIME = 3i32;
pub const PACKMAN_RUNTIME_MODERN_NATIVE: PACKMAN_RUNTIME = 4i32;
pub const PACKMAN_RUNTIME_JUPITER: PACKMAN_RUNTIME = 5i32;
pub const PACKMAN_RUNTIME_INVALID: PACKMAN_RUNTIME = 6i32;
#[repr(C)]
pub struct PATCH_IGNORE_RANGE {
pub OffsetInOldFile: u32,
pub LengthInBytes: u32,
}
impl ::core::marker::Copy for PATCH_IGNORE_RANGE {}
impl ::core::clone::Clone for PATCH_IGNORE_RANGE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct PATCH_INTERLEAVE_MAP {
pub CountRanges: u32,
pub Range: [PATCH_INTERLEAVE_MAP_0; 1],
}
impl ::core::marker::Copy for PATCH_INTERLEAVE_MAP {}
impl ::core::clone::Clone for PATCH_INTERLEAVE_MAP {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct PATCH_INTERLEAVE_MAP_0 {
pub OldOffset: u32,
pub OldLength: u32,
pub NewLength: u32,
}
impl ::core::marker::Copy for PATCH_INTERLEAVE_MAP_0 {}
impl ::core::clone::Clone for PATCH_INTERLEAVE_MAP_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PATCH_OLD_FILE_INFO {
pub SizeOfThisStruct: u32,
pub Anonymous: PATCH_OLD_FILE_INFO_0,
pub IgnoreRangeCount: u32,
pub IgnoreRangeArray: *mut PATCH_IGNORE_RANGE,
pub RetainRangeCount: u32,
pub RetainRangeArray: *mut PATCH_RETAIN_RANGE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PATCH_OLD_FILE_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PATCH_OLD_FILE_INFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union PATCH_OLD_FILE_INFO_0 {
pub OldFileNameA: super::super::Foundation::PSTR,
pub OldFileNameW: super::super::Foundation::PWSTR,
pub OldFileHandle: super::super::Foundation::HANDLE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PATCH_OLD_FILE_INFO_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PATCH_OLD_FILE_INFO_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PATCH_OLD_FILE_INFO_A {
pub SizeOfThisStruct: u32,
pub OldFileName: super::super::Foundation::PSTR,
pub IgnoreRangeCount: u32,
pub IgnoreRangeArray: *mut PATCH_IGNORE_RANGE,
pub RetainRangeCount: u32,
pub RetainRangeArray: *mut PATCH_RETAIN_RANGE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PATCH_OLD_FILE_INFO_A {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PATCH_OLD_FILE_INFO_A {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PATCH_OLD_FILE_INFO_H {
pub SizeOfThisStruct: u32,
pub OldFileHandle: super::super::Foundation::HANDLE,
pub IgnoreRangeCount: u32,
pub IgnoreRangeArray: *mut PATCH_IGNORE_RANGE,
pub RetainRangeCount: u32,
pub RetainRangeArray: *mut PATCH_RETAIN_RANGE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PATCH_OLD_FILE_INFO_H {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PATCH_OLD_FILE_INFO_H {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PATCH_OLD_FILE_INFO_W {
pub SizeOfThisStruct: u32,
pub OldFileName: super::super::Foundation::PWSTR,
pub IgnoreRangeCount: u32,
pub IgnoreRangeArray: *mut PATCH_IGNORE_RANGE,
pub RetainRangeCount: u32,
pub RetainRangeArray: *mut PATCH_RETAIN_RANGE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PATCH_OLD_FILE_INFO_W {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PATCH_OLD_FILE_INFO_W {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PATCH_OPTION_DATA {
pub SizeOfThisStruct: u32,
pub SymbolOptionFlags: u32,
pub NewFileSymbolPath: super::super::Foundation::PSTR,
pub OldFileSymbolPathArray: *mut super::super::Foundation::PSTR,
pub ExtendedOptionFlags: u32,
pub SymLoadCallback: PPATCH_SYMLOAD_CALLBACK,
pub SymLoadContext: *mut ::core::ffi::c_void,
pub InterleaveMapArray: *mut *mut PATCH_INTERLEAVE_MAP,
pub MaxLzxWindowSize: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PATCH_OPTION_DATA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PATCH_OPTION_DATA {
fn clone(&self) -> Self {
*self
}
}
pub const PATCH_OPTION_FAIL_IF_BIGGER: u32 = 1048576u32;
pub const PATCH_OPTION_FAIL_IF_SAME_FILE: u32 = 524288u32;
pub const PATCH_OPTION_INTERLEAVE_FILES: u32 = 1073741824u32;
pub const PATCH_OPTION_NO_BINDFIX: u32 = 65536u32;
pub const PATCH_OPTION_NO_CHECKSUM: u32 = 2097152u32;
pub const PATCH_OPTION_NO_LOCKFIX: u32 = 131072u32;
pub const PATCH_OPTION_NO_REBASE: u32 = 262144u32;
pub const PATCH_OPTION_NO_RESTIMEFIX: u32 = 4194304u32;
pub const PATCH_OPTION_NO_TIMESTAMP: u32 = 8388608u32;
pub const PATCH_OPTION_RESERVED1: u32 = 2147483648u32;
pub const PATCH_OPTION_SIGNATURE_MD5: u32 = 16777216u32;
pub const PATCH_OPTION_USE_BEST: u32 = 0u32;
pub const PATCH_OPTION_USE_LZX_A: u32 = 1u32;
pub const PATCH_OPTION_USE_LZX_B: u32 = 2u32;
pub const PATCH_OPTION_USE_LZX_BEST: u32 = 3u32;
pub const PATCH_OPTION_USE_LZX_LARGE: u32 = 4u32;
pub const PATCH_OPTION_VALID_FLAGS: u32 = 3237937159u32;
#[repr(C)]
pub struct PATCH_RETAIN_RANGE {
pub OffsetInOldFile: u32,
pub LengthInBytes: u32,
pub OffsetInNewFile: u32,
}
impl ::core::marker::Copy for PATCH_RETAIN_RANGE {}
impl ::core::clone::Clone for PATCH_RETAIN_RANGE {
fn clone(&self) -> Self {
*self
}
}
pub const PATCH_SYMBOL_NO_FAILURES: u32 = 2u32;
pub const PATCH_SYMBOL_NO_IMAGEHLP: u32 = 1u32;
pub const PATCH_SYMBOL_RESERVED1: u32 = 2147483648u32;
pub const PATCH_SYMBOL_UNDECORATED_TOO: u32 = 4u32;
pub const PATCH_TRANSFORM_PE_IRELOC_2: u32 = 512u32;
pub const PATCH_TRANSFORM_PE_RESOURCE_2: u32 = 256u32;
pub const PID_APPNAME: u32 = 18u32;
pub const PID_AUTHOR: u32 = 4u32;
pub const PID_CHARCOUNT: u32 = 16u32;
pub const PID_COMMENTS: u32 = 6u32;
pub const PID_CREATE_DTM: u32 = 12u32;
pub const PID_EDITTIME: u32 = 10u32;
pub const PID_KEYWORDS: u32 = 5u32;
pub const PID_LASTAUTHOR: u32 = 8u32;
pub const PID_LASTPRINTED: u32 = 11u32;
pub const PID_LASTSAVE_DTM: u32 = 13u32;
pub const PID_MSIRESTRICT: u32 = 16u32;
pub const PID_MSISOURCE: u32 = 15u32;
pub const PID_MSIVERSION: u32 = 14u32;
pub const PID_PAGECOUNT: u32 = 14u32;
pub const PID_REVNUMBER: u32 = 9u32;
pub const PID_SUBJECT: u32 = 3u32;
pub const PID_TEMPLATE: u32 = 7u32;
pub const PID_THUMBNAIL: u32 = 17u32;
pub const PID_TITLE: u32 = 2u32;
pub const PID_WORDCOUNT: u32 = 15u32;
pub type PINSTALLUI_HANDLER_RECORD = ::core::option::Option<unsafe extern "system" fn(pvcontext: *mut ::core::ffi::c_void, imessagetype: u32, hrecord: MSIHANDLE) -> i32>;
#[repr(C)]
pub struct PMSIHANDLE {
pub m_h: MSIHANDLE,
}
impl ::core::marker::Copy for PMSIHANDLE {}
impl ::core::clone::Clone for PMSIHANDLE {
fn clone(&self) -> Self {
*self
}
}
pub const PMSvc: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3118797308,
data2: 58212,
data3: 18810,
data4: [161, 33, 183, 179, 97, 44, 237, 206],
};
pub type PM_ACTIVATION_POLICY = i32;
pub const PM_ACTIVATION_POLICY_RESUME: PM_ACTIVATION_POLICY = 0i32;
pub const PM_ACTIVATION_POLICY_RESUMESAMEPARAMS: PM_ACTIVATION_POLICY = 1i32;
pub const PM_ACTIVATION_POLICY_REPLACE: PM_ACTIVATION_POLICY = 2i32;
pub const PM_ACTIVATION_POLICY_REPLACESAMEPARAMS: PM_ACTIVATION_POLICY = 3i32;
pub const PM_ACTIVATION_POLICY_MULTISESSION: PM_ACTIVATION_POLICY = 4i32;
pub const PM_ACTIVATION_POLICY_REPLACE_IGNOREFOREGROUND: PM_ACTIVATION_POLICY = 5i32;
pub const PM_ACTIVATION_POLICY_UNKNOWN: PM_ACTIVATION_POLICY = 6i32;
pub const PM_ACTIVATION_POLICY_INVALID: PM_ACTIVATION_POLICY = 7i32;
pub type PM_APPLICATION_HUBTYPE = i32;
pub const PM_APPLICATION_HUBTYPE_NONMUSIC: PM_APPLICATION_HUBTYPE = 0i32;
pub const PM_APPLICATION_HUBTYPE_MUSIC: PM_APPLICATION_HUBTYPE = 1i32;
pub const PM_APPLICATION_HUBTYPE_INVALID: PM_APPLICATION_HUBTYPE = 2i32;
pub type PM_APPLICATION_INSTALL_TYPE = i32;
pub const PM_APPLICATION_INSTALL_NORMAL: PM_APPLICATION_INSTALL_TYPE = 0i32;
pub const PM_APPLICATION_INSTALL_IN_ROM: PM_APPLICATION_INSTALL_TYPE = 1i32;
pub const PM_APPLICATION_INSTALL_PA: PM_APPLICATION_INSTALL_TYPE = 2i32;
pub const PM_APPLICATION_INSTALL_DEBUG: PM_APPLICATION_INSTALL_TYPE = 3i32;
pub const PM_APPLICATION_INSTALL_ENTERPRISE: PM_APPLICATION_INSTALL_TYPE = 4i32;
pub const PM_APPLICATION_INSTALL_INVALID: PM_APPLICATION_INSTALL_TYPE = 5i32;
pub type PM_APPLICATION_STATE = i32;
pub const PM_APPLICATION_STATE_MIN: PM_APPLICATION_STATE = 0i32;
pub const PM_APPLICATION_STATE_INSTALLED: PM_APPLICATION_STATE = 1i32;
pub const PM_APPLICATION_STATE_INSTALLING: PM_APPLICATION_STATE = 2i32;
pub const PM_APPLICATION_STATE_UPDATING: PM_APPLICATION_STATE = 3i32;
pub const PM_APPLICATION_STATE_UNINSTALLING: PM_APPLICATION_STATE = 4i32;
pub const PM_APPLICATION_STATE_LICENSE_UPDATING: PM_APPLICATION_STATE = 5i32;
pub const PM_APPLICATION_STATE_MOVING: PM_APPLICATION_STATE = 6i32;
pub const PM_APPLICATION_STATE_DISABLED_SD_CARD: PM_APPLICATION_STATE = 7i32;
pub const PM_APPLICATION_STATE_DISABLED_ENTERPRISE: PM_APPLICATION_STATE = 8i32;
pub const PM_APPLICATION_STATE_DISABLED_BACKING_UP: PM_APPLICATION_STATE = 9i32;
pub const PM_APPLICATION_STATE_DISABLED_MDIL_BINDING: PM_APPLICATION_STATE = 10i32;
pub const PM_APPLICATION_STATE_MAX: PM_APPLICATION_STATE = 10i32;
pub const PM_APPLICATION_STATE_INVALID: PM_APPLICATION_STATE = 11i32;
pub type PM_APP_GENRE = i32;
pub const PM_APP_GENRE_GAMES: PM_APP_GENRE = 0i32;
pub const PM_APP_GENRE_OTHER: PM_APP_GENRE = 1i32;
pub const PM_APP_GENRE_INVALID: PM_APP_GENRE = 2i32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PM_BSATASKID {
pub ProductID: ::windows_sys::core::GUID,
pub TaskID: super::super::Foundation::BSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PM_BSATASKID {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PM_BSATASKID {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PM_BWTASKID {
pub ProductID: ::windows_sys::core::GUID,
pub TaskID: super::super::Foundation::BSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PM_BWTASKID {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PM_BWTASKID {
fn clone(&self) -> Self {
*self
}
}
pub type PM_ENUM_APP_FILTER = i32;
pub const PM_APP_FILTER_ALL: PM_ENUM_APP_FILTER = 0i32;
pub const PM_APP_FILTER_VISIBLE: PM_ENUM_APP_FILTER = 1i32;
pub const PM_APP_FILTER_GENRE: PM_ENUM_APP_FILTER = 2i32;
pub const PM_APP_FILTER_NONGAMES: PM_ENUM_APP_FILTER = 3i32;
pub const PM_APP_FILTER_HUBTYPE: PM_ENUM_APP_FILTER = 4i32;
pub const PM_APP_FILTER_PINABLEONKIDZONE: PM_ENUM_APP_FILTER = 5i32;
pub const PM_APP_FILTER_ALL_INCLUDE_MODERN: PM_ENUM_APP_FILTER = 6i32;
pub const PM_APP_FILTER_FRAMEWORK: PM_ENUM_APP_FILTER = 7i32;
pub const PM_APP_FILTER_MAX: PM_ENUM_APP_FILTER = 8i32;
pub type PM_ENUM_BSA_FILTER = i32;
pub const PM_ENUM_BSA_FILTER_ALL: PM_ENUM_BSA_FILTER = 26i32;
pub const PM_ENUM_BSA_FILTER_BY_TASKID: PM_ENUM_BSA_FILTER = 27i32;
pub const PM_ENUM_BSA_FILTER_BY_PRODUCTID: PM_ENUM_BSA_FILTER = 28i32;
pub const PM_ENUM_BSA_FILTER_BY_PERIODIC: PM_ENUM_BSA_FILTER = 29i32;
pub const PM_ENUM_BSA_FILTER_BY_ALL_LAUNCHONBOOT: PM_ENUM_BSA_FILTER = 30i32;
pub const PM_ENUM_BSA_FILTER_MAX: PM_ENUM_BSA_FILTER = 31i32;
pub type PM_ENUM_BW_FILTER = i32;
pub const PM_ENUM_BW_FILTER_BOOTWORKER_ALL: PM_ENUM_BW_FILTER = 31i32;
pub const PM_ENUM_BW_FILTER_BY_TASKID: PM_ENUM_BW_FILTER = 32i32;
pub const PM_ENUM_BW_FILTER_MAX: PM_ENUM_BW_FILTER = 33i32;
pub type PM_ENUM_EXTENSION_FILTER = i32;
pub const PM_ENUM_EXTENSION_FILTER_BY_CONSUMER: PM_ENUM_EXTENSION_FILTER = 17i32;
pub const PM_ENUM_EXTENSION_FILTER_APPCONNECT: PM_ENUM_EXTENSION_FILTER = 17i32;
pub const PM_ENUM_EXTENSION_FILTER_PROTOCOL_ALL: PM_ENUM_EXTENSION_FILTER = 18i32;
pub const PM_ENUM_EXTENSION_FILTER_FTASSOC_FILETYPE_ALL: PM_ENUM_EXTENSION_FILTER = 19i32;
pub const PM_ENUM_EXTENSION_FILTER_FTASSOC_CONTENTTYPE_ALL: PM_ENUM_EXTENSION_FILTER = 20i32;
pub const PM_ENUM_EXTENSION_FILTER_FTASSOC_APPLICATION_ALL: PM_ENUM_EXTENSION_FILTER = 21i32;
pub const PM_ENUM_EXTENSION_FILTER_SHARETARGET_ALL: PM_ENUM_EXTENSION_FILTER = 22i32;
pub const PM_ENUM_EXTENSION_FILTER_FILEOPENPICKER_ALL: PM_ENUM_EXTENSION_FILTER = 23i32;
pub const PM_ENUM_EXTENSION_FILTER_FILESAVEPICKER_ALL: PM_ENUM_EXTENSION_FILTER = 24i32;
pub const PM_ENUM_EXTENSION_FILTER_CACHEDFILEUPDATER_ALL: PM_ENUM_EXTENSION_FILTER = 25i32;
pub const PM_ENUM_EXTENSION_FILTER_MAX: PM_ENUM_EXTENSION_FILTER = 26i32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PM_ENUM_FILTER {
pub FilterType: i32,
pub FilterParameter: PM_ENUM_FILTER_0,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PM_ENUM_FILTER {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PM_ENUM_FILTER {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union PM_ENUM_FILTER_0 {
pub Dummy: i32,
pub Genre: PM_APP_GENRE,
pub AppHubType: PM_APPLICATION_HUBTYPE,
pub HubType: PM_TILE_HUBTYPE,
pub Tasktype: PM_TASK_TYPE,
pub TaskProductID: ::windows_sys::core::GUID,
pub TileProductID: ::windows_sys::core::GUID,
pub AppTaskType: _tagAPPTASKTYPE,
pub Consumer: PM_EXTENSIONCONSUMER,
pub BSATask: PM_BSATASKID,
pub BSAProductID: ::windows_sys::core::GUID,
pub BWTask: PM_BWTASKID,
pub ProtocolName: super::super::Foundation::BSTR,
pub FileType: super::super::Foundation::BSTR,
pub ContentType: super::super::Foundation::BSTR,
pub AppSupportedFileExtPID: ::windows_sys::core::GUID,
pub ShareTargetFileType: super::super::Foundation::BSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PM_ENUM_FILTER_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PM_ENUM_FILTER_0 {
fn clone(&self) -> Self {
*self
}
}
pub type PM_ENUM_TASK_FILTER = i32;
pub const PM_TASK_FILTER_APP_ALL: PM_ENUM_TASK_FILTER = 12i32;
pub const PM_TASK_FILTER_TASK_TYPE: PM_ENUM_TASK_FILTER = 13i32;
pub const PM_TASK_FILTER_DEHYD_SUPRESSING: PM_ENUM_TASK_FILTER = 14i32;
pub const PM_TASK_FILTER_APP_TASK_TYPE: PM_ENUM_TASK_FILTER = 15i32;
pub const PM_TASK_FILTER_BGEXECUTION: PM_ENUM_TASK_FILTER = 16i32;
pub const PM_TASK_FILTER_MAX: PM_ENUM_TASK_FILTER = 17i32;
pub type PM_ENUM_TILE_FILTER = i32;
pub const PM_TILE_FILTER_APPLIST: PM_ENUM_TILE_FILTER = 8i32;
pub const PM_TILE_FILTER_PINNED: PM_ENUM_TILE_FILTER = 9i32;
pub const PM_TILE_FILTER_HUBTYPE: PM_ENUM_TILE_FILTER = 10i32;
pub const PM_TILE_FILTER_APP_ALL: PM_ENUM_TILE_FILTER = 11i32;
pub const PM_TILE_FILTER_MAX: PM_ENUM_TILE_FILTER = 12i32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PM_EXTENSIONCONSUMER {
pub ConsumerPID: ::windows_sys::core::GUID,
pub ExtensionID: super::super::Foundation::BSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PM_EXTENSIONCONSUMER {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PM_EXTENSIONCONSUMER {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PM_INSTALLINFO {
pub ProductID: ::windows_sys::core::GUID,
pub PackagePath: super::super::Foundation::BSTR,
pub InstanceID: ::windows_sys::core::GUID,
pub pbLicense: *mut u8,
pub cbLicense: u32,
pub IsUninstallDisabled: super::super::Foundation::BOOL,
pub DeploymentOptions: u32,
pub OfferID: ::windows_sys::core::GUID,
pub MarketplaceAppVersion: super::super::Foundation::BSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PM_INSTALLINFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PM_INSTALLINFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PM_INVOCATIONINFO {
pub URIBaseOrAUMID: super::super::Foundation::BSTR,
pub URIFragmentOrArgs: super::super::Foundation::BSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PM_INVOCATIONINFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PM_INVOCATIONINFO {
fn clone(&self) -> Self {
*self
}
}
pub type PM_LIVETILE_RECURRENCE_TYPE = i32;
pub const PM_LIVETILE_RECURRENCE_TYPE_INSTANT: PM_LIVETILE_RECURRENCE_TYPE = 0i32;
pub const PM_LIVETILE_RECURRENCE_TYPE_ONETIME: PM_LIVETILE_RECURRENCE_TYPE = 1i32;
pub const PM_LIVETILE_RECURRENCE_TYPE_INTERVAL: PM_LIVETILE_RECURRENCE_TYPE = 2i32;
pub const PM_LIVETILE_RECURRENCE_TYPE_MAX: PM_LIVETILE_RECURRENCE_TYPE = 2i32;
pub type PM_LOGO_SIZE = i32;
pub const PM_LOGO_SIZE_SMALL: PM_LOGO_SIZE = 0i32;
pub const PM_LOGO_SIZE_MEDIUM: PM_LOGO_SIZE = 1i32;
pub const PM_LOGO_SIZE_LARGE: PM_LOGO_SIZE = 2i32;
pub const PM_LOGO_SIZE_INVALID: PM_LOGO_SIZE = 3i32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PM_STARTAPPBLOB {
pub cbSize: u32,
pub ProductID: ::windows_sys::core::GUID,
pub AppTitle: super::super::Foundation::BSTR,
pub IconPath: super::super::Foundation::BSTR,
pub IsUninstallable: super::super::Foundation::BOOL,
pub AppInstallType: PM_APPLICATION_INSTALL_TYPE,
pub InstanceID: ::windows_sys::core::GUID,
pub State: PM_APPLICATION_STATE,
pub IsModern: super::super::Foundation::BOOL,
pub IsModernLightUp: super::super::Foundation::BOOL,
pub LightUpSupportMask: u16,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PM_STARTAPPBLOB {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PM_STARTAPPBLOB {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PM_STARTTILEBLOB {
pub cbSize: u32,
pub ProductID: ::windows_sys::core::GUID,
pub TileID: super::super::Foundation::BSTR,
pub TemplateType: TILE_TEMPLATE_TYPE,
pub HubPosition: [u32; 32],
pub HubVisibilityBitmask: u32,
pub IsDefault: super::super::Foundation::BOOL,
pub TileType: PM_STARTTILE_TYPE,
pub pbPropBlob: *mut u8,
pub cbPropBlob: u32,
pub IsRestoring: super::super::Foundation::BOOL,
pub IsModern: super::super::Foundation::BOOL,
pub InvocationInfo: PM_INVOCATIONINFO,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PM_STARTTILEBLOB {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PM_STARTTILEBLOB {
fn clone(&self) -> Self {
*self
}
}
pub type PM_STARTTILE_TYPE = i32;
pub const PM_STARTTILE_TYPE_PRIMARY: PM_STARTTILE_TYPE = 1i32;
pub const PM_STARTTILE_TYPE_SECONDARY: PM_STARTTILE_TYPE = 2i32;
pub const PM_STARTTILE_TYPE_APPLIST: PM_STARTTILE_TYPE = 3i32;
pub const PM_STARTTILE_TYPE_APPLISTPRIMARY: PM_STARTTILE_TYPE = 4i32;
pub const PM_STARTTILE_TYPE_INVALID: PM_STARTTILE_TYPE = 5i32;
pub type PM_TASK_TRANSITION = i32;
pub const PM_TASK_TRANSITION_DEFAULT: PM_TASK_TRANSITION = 0i32;
pub const PM_TASK_TRANSITION_NONE: PM_TASK_TRANSITION = 1i32;
pub const PM_TASK_TRANSITION_TURNSTILE: PM_TASK_TRANSITION = 2i32;
pub const PM_TASK_TRANSITION_SLIDE: PM_TASK_TRANSITION = 3i32;
pub const PM_TASK_TRANSITION_SWIVEL: PM_TASK_TRANSITION = 4i32;
pub const PM_TASK_TRANSITION_READERBOARD: PM_TASK_TRANSITION = 5i32;
pub const PM_TASK_TRANSITION_CUSTOM: PM_TASK_TRANSITION = 6i32;
pub const PM_TASK_TRANSITION_INVALID: PM_TASK_TRANSITION = 7i32;
pub type PM_TASK_TYPE = i32;
pub const PM_TASK_TYPE_NORMAL: PM_TASK_TYPE = 0i32;
pub const PM_TASK_TYPE_DEFAULT: PM_TASK_TYPE = 1i32;
pub const PM_TASK_TYPE_SETTINGS: PM_TASK_TYPE = 2i32;
pub const PM_TASK_TYPE_BACKGROUNDSERVICEAGENT: PM_TASK_TYPE = 3i32;
pub const PM_TASK_TYPE_BACKGROUNDWORKER: PM_TASK_TYPE = 4i32;
pub const PM_TASK_TYPE_INVALID: PM_TASK_TYPE = 5i32;
pub type PM_TILE_HUBTYPE = i32;
pub const PM_TILE_HUBTYPE_MUSIC: PM_TILE_HUBTYPE = 1i32;
pub const PM_TILE_HUBTYPE_MOSETTINGS: PM_TILE_HUBTYPE = 268435456i32;
pub const PM_TILE_HUBTYPE_GAMES: PM_TILE_HUBTYPE = 536870912i32;
pub const PM_TILE_HUBTYPE_APPLIST: PM_TILE_HUBTYPE = 1073741824i32;
pub const PM_TILE_HUBTYPE_STARTMENU: PM_TILE_HUBTYPE = -2147483648i32;
pub const PM_TILE_HUBTYPE_LOCKSCREEN: PM_TILE_HUBTYPE = 16777216i32;
pub const PM_TILE_HUBTYPE_KIDZONE: PM_TILE_HUBTYPE = 33554432i32;
pub const PM_TILE_HUBTYPE_CACHED: PM_TILE_HUBTYPE = 67108864i32;
pub const PM_TILE_HUBTYPE_INVALID: PM_TILE_HUBTYPE = 67108865i32;
pub type PM_TILE_SIZE = i32;
pub const PM_TILE_SIZE_SMALL: PM_TILE_SIZE = 0i32;
pub const PM_TILE_SIZE_MEDIUM: PM_TILE_SIZE = 1i32;
pub const PM_TILE_SIZE_LARGE: PM_TILE_SIZE = 2i32;
pub const PM_TILE_SIZE_SQUARE310X310: PM_TILE_SIZE = 3i32;
pub const PM_TILE_SIZE_TALL150X310: PM_TILE_SIZE = 4i32;
pub const PM_TILE_SIZE_INVALID: PM_TILE_SIZE = 5i32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PM_UPDATEINFO {
pub ProductID: ::windows_sys::core::GUID,
pub PackagePath: super::super::Foundation::BSTR,
pub InstanceID: ::windows_sys::core::GUID,
pub pbLicense: *mut u8,
pub cbLicense: u32,
pub MarketplaceAppVersion: super::super::Foundation::BSTR,
pub DeploymentOptions: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PM_UPDATEINFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PM_UPDATEINFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct PM_UPDATEINFO_LEGACY {
pub ProductID: ::windows_sys::core::GUID,
pub PackagePath: super::super::Foundation::BSTR,
pub InstanceID: ::windows_sys::core::GUID,
pub pbLicense: *mut u8,
pub cbLicense: u32,
pub MarketplaceAppVersion: super::super::Foundation::BSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PM_UPDATEINFO_LEGACY {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PM_UPDATEINFO_LEGACY {
fn clone(&self) -> Self {
*self
}
}
#[cfg(feature = "Win32_Foundation")]
pub type PPATCH_PROGRESS_CALLBACK = ::core::option::Option<unsafe extern "system" fn(callbackcontext: *mut ::core::ffi::c_void, currentposition: u32, maximumposition: u32) -> super::super::Foundation::BOOL>;
#[cfg(feature = "Win32_Foundation")]
pub type PPATCH_SYMLOAD_CALLBACK = ::core::option::Option<unsafe extern "system" fn(whichfile: u32, symbolfilename: super::super::Foundation::PSTR, symtype: u32, symbolfilechecksum: u32, symbolfiletimedate: u32, imagefilechecksum: u32, imagefiletimedate: u32, callbackcontext: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL>;
#[repr(C)]
pub struct PROTECTED_FILE_DATA {
pub FileName: [u16; 260],
pub FileNumber: u32,
}
impl ::core::marker::Copy for PROTECTED_FILE_DATA {}
impl ::core::clone::Clone for PROTECTED_FILE_DATA {
fn clone(&self) -> Self {
*self
}
}
pub type QUERYASMINFO_FLAGS = u32;
pub const QUERYASMINFO_FLAG_VALIDATE: QUERYASMINFO_FLAGS = 1u32;
pub type REINSTALLMODE = i32;
pub const REINSTALLMODE_REPAIR: REINSTALLMODE = 1i32;
pub const REINSTALLMODE_FILEMISSING: REINSTALLMODE = 2i32;
pub const REINSTALLMODE_FILEOLDERVERSION: REINSTALLMODE = 4i32;
pub const REINSTALLMODE_FILEEQUALVERSION: REINSTALLMODE = 8i32;
pub const REINSTALLMODE_FILEEXACT: REINSTALLMODE = 16i32;
pub const REINSTALLMODE_FILEVERIFY: REINSTALLMODE = 32i32;
pub const REINSTALLMODE_FILEREPLACE: REINSTALLMODE = 64i32;
pub const REINSTALLMODE_MACHINEDATA: REINSTALLMODE = 128i32;
pub const REINSTALLMODE_USERDATA: REINSTALLMODE = 256i32;
pub const REINSTALLMODE_SHORTCUT: REINSTALLMODE = 512i32;
pub const REINSTALLMODE_PACKAGE: REINSTALLMODE = 1024i32;
pub type RESULTTYPES = i32;
pub const ieUnknown: RESULTTYPES = 0i32;
pub const ieError: RESULTTYPES = 1i32;
pub const ieWarning: RESULTTYPES = 2i32;
pub const ieInfo: RESULTTYPES = 3i32;
pub type SCRIPTFLAGS = i32;
pub const SCRIPTFLAGS_CACHEINFO: SCRIPTFLAGS = 1i32;
pub const SCRIPTFLAGS_SHORTCUTS: SCRIPTFLAGS = 4i32;
pub const SCRIPTFLAGS_MACHINEASSIGN: SCRIPTFLAGS = 8i32;
pub const SCRIPTFLAGS_REGDATA_CNFGINFO: SCRIPTFLAGS = 32i32;
pub const SCRIPTFLAGS_VALIDATE_TRANSFORMS_LIST: SCRIPTFLAGS = 64i32;
pub const SCRIPTFLAGS_REGDATA_CLASSINFO: SCRIPTFLAGS = 128i32;
pub const SCRIPTFLAGS_REGDATA_EXTENSIONINFO: SCRIPTFLAGS = 256i32;
pub const SCRIPTFLAGS_REGDATA_APPINFO: SCRIPTFLAGS = 384i32;
pub const SCRIPTFLAGS_REGDATA: SCRIPTFLAGS = 416i32;
pub const SFC_DISABLE_ASK: u32 = 1u32;
pub const SFC_DISABLE_NOPOPUPS: u32 = 4u32;
pub const SFC_DISABLE_NORMAL: u32 = 0u32;
pub const SFC_DISABLE_ONCE: u32 = 2u32;
pub const SFC_DISABLE_SETUP: u32 = 3u32;
pub const SFC_QUOTA_DEFAULT: u32 = 50u32;
pub const SFC_SCAN_ALWAYS: u32 = 1u32;
pub const SFC_SCAN_IMMEDIATE: u32 = 3u32;
pub const SFC_SCAN_NORMAL: u32 = 0u32;
pub const SFC_SCAN_ONCE: u32 = 2u32;
pub type STATUSTYPES = i32;
pub const ieStatusGetCUB: STATUSTYPES = 0i32;
pub const ieStatusICECount: STATUSTYPES = 1i32;
pub const ieStatusMerge: STATUSTYPES = 2i32;
pub const ieStatusSummaryInfo: STATUSTYPES = 3i32;
pub const ieStatusCreateEngine: STATUSTYPES = 4i32;
pub const ieStatusStarting: STATUSTYPES = 5i32;
pub const ieStatusRunICE: STATUSTYPES = 6i32;
pub const ieStatusShutdown: STATUSTYPES = 7i32;
pub const ieStatusSuccess: STATUSTYPES = 8i32;
pub const ieStatusFail: STATUSTYPES = 9i32;
pub const ieStatusCancel: STATUSTYPES = 10i32;
pub const STREAM_FORMAT_COMPLIB_MANIFEST: u32 = 1u32;
pub const STREAM_FORMAT_COMPLIB_MODULE: u32 = 0u32;
pub const STREAM_FORMAT_WIN32_MANIFEST: u32 = 4u32;
pub const STREAM_FORMAT_WIN32_MODULE: u32 = 2u32;
pub type TILE_TEMPLATE_TYPE = i32;
pub const TILE_TEMPLATE_INVALID: TILE_TEMPLATE_TYPE = 0i32;
pub const TILE_TEMPLATE_FLIP: TILE_TEMPLATE_TYPE = 5i32;
pub const TILE_TEMPLATE_DEEPLINK: TILE_TEMPLATE_TYPE = 13i32;
pub const TILE_TEMPLATE_CYCLE: TILE_TEMPLATE_TYPE = 14i32;
pub const TILE_TEMPLATE_METROCOUNT: TILE_TEMPLATE_TYPE = 1i32;
pub const TILE_TEMPLATE_AGILESTORE: TILE_TEMPLATE_TYPE = 2i32;
pub const TILE_TEMPLATE_GAMES: TILE_TEMPLATE_TYPE = 3i32;
pub const TILE_TEMPLATE_CALENDAR: TILE_TEMPLATE_TYPE = 4i32;
pub const TILE_TEMPLATE_MUSICVIDEO: TILE_TEMPLATE_TYPE = 7i32;
pub const TILE_TEMPLATE_PEOPLE: TILE_TEMPLATE_TYPE = 10i32;
pub const TILE_TEMPLATE_CONTACT: TILE_TEMPLATE_TYPE = 11i32;
pub const TILE_TEMPLATE_GROUP: TILE_TEMPLATE_TYPE = 12i32;
pub const TILE_TEMPLATE_DEFAULT: TILE_TEMPLATE_TYPE = 15i32;
pub const TILE_TEMPLATE_BADGE: TILE_TEMPLATE_TYPE = 16i32;
pub const TILE_TEMPLATE_BLOCK: TILE_TEMPLATE_TYPE = 17i32;
pub const TILE_TEMPLATE_TEXT01: TILE_TEMPLATE_TYPE = 18i32;
pub const TILE_TEMPLATE_TEXT02: TILE_TEMPLATE_TYPE = 19i32;
pub const TILE_TEMPLATE_TEXT03: TILE_TEMPLATE_TYPE = 20i32;
pub const TILE_TEMPLATE_TEXT04: TILE_TEMPLATE_TYPE = 21i32;
pub const TILE_TEMPLATE_TEXT05: TILE_TEMPLATE_TYPE = 22i32;
pub const TILE_TEMPLATE_TEXT06: TILE_TEMPLATE_TYPE = 23i32;
pub const TILE_TEMPLATE_TEXT07: TILE_TEMPLATE_TYPE = 24i32;
pub const TILE_TEMPLATE_TEXT08: TILE_TEMPLATE_TYPE = 25i32;
pub const TILE_TEMPLATE_TEXT09: TILE_TEMPLATE_TYPE = 26i32;
pub const TILE_TEMPLATE_TEXT10: TILE_TEMPLATE_TYPE = 27i32;
pub const TILE_TEMPLATE_TEXT11: TILE_TEMPLATE_TYPE = 28i32;
pub const TILE_TEMPLATE_IMAGE: TILE_TEMPLATE_TYPE = 29i32;
pub const TILE_TEMPLATE_IMAGECOLLECTION: TILE_TEMPLATE_TYPE = 30i32;
pub const TILE_TEMPLATE_IMAGEANDTEXT01: TILE_TEMPLATE_TYPE = 31i32;
pub const TILE_TEMPLATE_IMAGEANDTEXT02: TILE_TEMPLATE_TYPE = 32i32;
pub const TILE_TEMPLATE_BLOCKANDTEXT01: TILE_TEMPLATE_TYPE = 33i32;
pub const TILE_TEMPLATE_BLOCKANDTEXT02: TILE_TEMPLATE_TYPE = 34i32;
pub const TILE_TEMPLATE_PEEKIMAGEANDTEXT01: TILE_TEMPLATE_TYPE = 35i32;
pub const TILE_TEMPLATE_PEEKIMAGEANDTEXT02: TILE_TEMPLATE_TYPE = 36i32;
pub const TILE_TEMPLATE_PEEKIMAGEANDTEXT03: TILE_TEMPLATE_TYPE = 37i32;
pub const TILE_TEMPLATE_PEEKIMAGEANDTEXT04: TILE_TEMPLATE_TYPE = 38i32;
pub const TILE_TEMPLATE_PEEKIMAGE01: TILE_TEMPLATE_TYPE = 39i32;
pub const TILE_TEMPLATE_PEEKIMAGE02: TILE_TEMPLATE_TYPE = 40i32;
pub const TILE_TEMPLATE_PEEKIMAGE03: TILE_TEMPLATE_TYPE = 41i32;
pub const TILE_TEMPLATE_PEEKIMAGE04: TILE_TEMPLATE_TYPE = 42i32;
pub const TILE_TEMPLATE_PEEKIMAGE05: TILE_TEMPLATE_TYPE = 43i32;
pub const TILE_TEMPLATE_PEEKIMAGE06: TILE_TEMPLATE_TYPE = 44i32;
pub const TILE_TEMPLATE_PEEKIMAGECOLLECTION01: TILE_TEMPLATE_TYPE = 45i32;
pub const TILE_TEMPLATE_PEEKIMAGECOLLECTION02: TILE_TEMPLATE_TYPE = 46i32;
pub const TILE_TEMPLATE_PEEKIMAGECOLLECTION03: TILE_TEMPLATE_TYPE = 47i32;
pub const TILE_TEMPLATE_PEEKIMAGECOLLECTION04: TILE_TEMPLATE_TYPE = 48i32;
pub const TILE_TEMPLATE_PEEKIMAGECOLLECTION05: TILE_TEMPLATE_TYPE = 49i32;
pub const TILE_TEMPLATE_PEEKIMAGECOLLECTION06: TILE_TEMPLATE_TYPE = 50i32;
pub const TILE_TEMPLATE_SMALLIMAGEANDTEXT01: TILE_TEMPLATE_TYPE = 51i32;
pub const TILE_TEMPLATE_SMALLIMAGEANDTEXT02: TILE_TEMPLATE_TYPE = 52i32;
pub const TILE_TEMPLATE_SMALLIMAGEANDTEXT03: TILE_TEMPLATE_TYPE = 53i32;
pub const TILE_TEMPLATE_SMALLIMAGEANDTEXT04: TILE_TEMPLATE_TYPE = 54i32;
pub const TILE_TEMPLATE_SMALLIMAGEANDTEXT05: TILE_TEMPLATE_TYPE = 55i32;
pub const TILE_TEMPLATE_METROCOUNTQUEUE: TILE_TEMPLATE_TYPE = 56i32;
pub const TILE_TEMPLATE_SEARCH: TILE_TEMPLATE_TYPE = 57i32;
pub const TILE_TEMPLATE_TILEFLYOUT01: TILE_TEMPLATE_TYPE = 58i32;
pub const TILE_TEMPLATE_FOLDER: TILE_TEMPLATE_TYPE = 59i32;
pub const TILE_TEMPLATE_ALL: TILE_TEMPLATE_TYPE = 100i32;
pub const TXTLOG_BACKUP: u32 = 128u32;
pub const TXTLOG_CMI: u32 = 268435456u32;
pub const TXTLOG_COPYFILES: u32 = 8u32;
pub const TXTLOG_DEPTH_DECR: u32 = 262144u32;
pub const TXTLOG_DEPTH_INCR: u32 = 131072u32;
pub const TXTLOG_DETAILS: u32 = 5u32;
pub const TXTLOG_DEVINST: u32 = 1u32;
pub const TXTLOG_DEVMGR: u32 = 536870912u32;
pub const TXTLOG_DRIVER_STORE: u32 = 67108864u32;
pub const TXTLOG_DRVSETUP: u32 = 4194304u32;
pub const TXTLOG_ERROR: u32 = 1u32;
pub const TXTLOG_FILEQ: u32 = 4u32;
pub const TXTLOG_FLUSH_FILE: u32 = 1048576u32;
pub const TXTLOG_INF: u32 = 2u32;
pub const TXTLOG_INFDB: u32 = 1024u32;
pub const TXTLOG_INSTALLER: u32 = 1073741824u32;
pub const TXTLOG_NEWDEV: u32 = 16777216u32;
pub const TXTLOG_POLICY: u32 = 8388608u32;
pub const TXTLOG_RESERVED_FLAGS: u32 = 65520u32;
pub const TXTLOG_SETUP: u32 = 134217728u32;
pub const TXTLOG_SETUPAPI_BITS: u32 = 3u32;
pub const TXTLOG_SETUPAPI_CMDLINE: u32 = 2u32;
pub const TXTLOG_SETUPAPI_DEVLOG: u32 = 1u32;
pub const TXTLOG_SIGVERIF: u32 = 32u32;
pub const TXTLOG_SUMMARY: u32 = 4u32;
pub const TXTLOG_SYSTEM_STATE_CHANGE: u32 = 3u32;
pub const TXTLOG_TAB_1: u32 = 524288u32;
pub const TXTLOG_TIMESTAMP: u32 = 65536u32;
pub const TXTLOG_UI: u32 = 256u32;
pub const TXTLOG_UMPNPMGR: u32 = 33554432u32;
pub const TXTLOG_UTIL: u32 = 512u32;
pub const TXTLOG_VENDOR: u32 = 2147483648u32;
pub const TXTLOG_VERBOSE: u32 = 6u32;
pub const TXTLOG_VERY_VERBOSE: u32 = 7u32;
pub const TXTLOG_WARNING: u32 = 2u32;
pub const UIALL: u32 = 32768u32;
pub const UILOGBITS: u32 = 15u32;
pub const UINONE: u32 = 0u32;
pub type USERINFOSTATE = i32;
pub const USERINFOSTATE_MOREDATA: USERINFOSTATE = -3i32;
pub const USERINFOSTATE_INVALIDARG: USERINFOSTATE = -2i32;
pub const USERINFOSTATE_UNKNOWN: USERINFOSTATE = -1i32;
pub const USERINFOSTATE_ABSENT: USERINFOSTATE = 0i32;
pub const USERINFOSTATE_PRESENT: USERINFOSTATE = 1i32;
pub const WARN_BAD_MAJOR_VERSION: u32 = 3222294792u32;
pub const WARN_BASE: u32 = 3222294785u32;
pub const WARN_EQUAL_FILE_VERSION: u32 = 3222294794u32;
pub const WARN_FILE_VERSION_DOWNREV: u32 = 3222294793u32;
pub const WARN_IMPROPER_TRANSFORM_VALIDATION: u32 = 3222294788u32;
pub const WARN_INVALID_TRANSFORM_VALIDATION: u32 = 3222294791u32;
pub const WARN_MAJOR_UPGRADE_PATCH: u32 = 3222294785u32;
pub const WARN_OBSOLETION_WITH_MSI30: u32 = 3222294801u32;
pub const WARN_OBSOLETION_WITH_PATCHSEQUENCE: u32 = 3222294803u32;
pub const WARN_OBSOLETION_WITH_SEQUENCE_DATA: u32 = 3222294802u32;
pub const WARN_PATCHPROPERTYNOTSET: u32 = 3222294795u32;
pub const WARN_PCW_MISMATCHED_PRODUCT_CODES: u32 = 3222294789u32;
pub const WARN_PCW_MISMATCHED_PRODUCT_VERSIONS: u32 = 3222294790u32;
pub const WARN_SEQUENCE_DATA_GENERATION_DISABLED: u32 = 3222294786u32;
pub const WARN_SEQUENCE_DATA_SUPERSEDENCE_IGNORED: u32 = 3222294787u32;
pub const _WIN32_MSI: u32 = 500u32;
pub const _WIN32_MSM: u32 = 100u32;
#[repr(C)]
pub struct _tagAPPTASKTYPE {
pub ProductID: ::windows_sys::core::GUID,
pub TaskType: PM_TASK_TYPE,
}
impl ::core::marker::Copy for _tagAPPTASKTYPE {}
impl ::core::clone::Clone for _tagAPPTASKTYPE {
fn clone(&self) -> Self {
*self
}
}
pub const cchMaxInteger: i32 = 12i32;
pub type msidbAssemblyAttributes = i32;
pub const msidbAssemblyAttributesURT: msidbAssemblyAttributes = 0i32;
pub const msidbAssemblyAttributesWin32: msidbAssemblyAttributes = 1i32;
pub type msidbClassAttributes = i32;
pub const msidbClassAttributesRelativePath: msidbClassAttributes = 1i32;
pub type msidbComponentAttributes = i32;
pub const msidbComponentAttributesLocalOnly: msidbComponentAttributes = 0i32;
pub const msidbComponentAttributesSourceOnly: msidbComponentAttributes = 1i32;
pub const msidbComponentAttributesOptional: msidbComponentAttributes = 2i32;
pub const msidbComponentAttributesRegistryKeyPath: msidbComponentAttributes = 4i32;
pub const msidbComponentAttributesSharedDllRefCount: msidbComponentAttributes = 8i32;
pub const msidbComponentAttributesPermanent: msidbComponentAttributes = 16i32;
pub const msidbComponentAttributesODBCDataSource: msidbComponentAttributes = 32i32;
pub const msidbComponentAttributesTransitive: msidbComponentAttributes = 64i32;
pub const msidbComponentAttributesNeverOverwrite: msidbComponentAttributes = 128i32;
pub const msidbComponentAttributes64bit: msidbComponentAttributes = 256i32;
pub const msidbComponentAttributesDisableRegistryReflection: msidbComponentAttributes = 512i32;
pub const msidbComponentAttributesUninstallOnSupersedence: msidbComponentAttributes = 1024i32;
pub const msidbComponentAttributesShared: msidbComponentAttributes = 2048i32;
pub type msidbControlAttributes = i32;
pub const msidbControlAttributesVisible: msidbControlAttributes = 1i32;
pub const msidbControlAttributesEnabled: msidbControlAttributes = 2i32;
pub const msidbControlAttributesSunken: msidbControlAttributes = 4i32;
pub const msidbControlAttributesIndirect: msidbControlAttributes = 8i32;
pub const msidbControlAttributesInteger: msidbControlAttributes = 16i32;
pub const msidbControlAttributesRTLRO: msidbControlAttributes = 32i32;
pub const msidbControlAttributesRightAligned: msidbControlAttributes = 64i32;
pub const msidbControlAttributesLeftScroll: msidbControlAttributes = 128i32;
pub const msidbControlAttributesBiDi: msidbControlAttributes = 224i32;
pub const msidbControlAttributesTransparent: msidbControlAttributes = 65536i32;
pub const msidbControlAttributesNoPrefix: msidbControlAttributes = 131072i32;
pub const msidbControlAttributesNoWrap: msidbControlAttributes = 262144i32;
pub const msidbControlAttributesFormatSize: msidbControlAttributes = 524288i32;
pub const msidbControlAttributesUsersLanguage: msidbControlAttributes = 1048576i32;
pub const msidbControlAttributesMultiline: msidbControlAttributes = 65536i32;
pub const msidbControlAttributesPasswordInput: msidbControlAttributes = 2097152i32;
pub const msidbControlAttributesProgress95: msidbControlAttributes = 65536i32;
pub const msidbControlAttributesRemovableVolume: msidbControlAttributes = 65536i32;
pub const msidbControlAttributesFixedVolume: msidbControlAttributes = 131072i32;
pub const msidbControlAttributesRemoteVolume: msidbControlAttributes = 262144i32;
pub const msidbControlAttributesCDROMVolume: msidbControlAttributes = 524288i32;
pub const msidbControlAttributesRAMDiskVolume: msidbControlAttributes = 1048576i32;
pub const msidbControlAttributesFloppyVolume: msidbControlAttributes = 2097152i32;
pub const msidbControlShowRollbackCost: msidbControlAttributes = 4194304i32;
pub const msidbControlAttributesSorted: msidbControlAttributes = 65536i32;
pub const msidbControlAttributesComboList: msidbControlAttributes = 131072i32;
pub const msidbControlAttributesImageHandle: msidbControlAttributes = 65536i32;
pub const msidbControlAttributesPushLike: msidbControlAttributes = 131072i32;
pub const msidbControlAttributesBitmap: msidbControlAttributes = 262144i32;
pub const msidbControlAttributesIcon: msidbControlAttributes = 524288i32;
pub const msidbControlAttributesFixedSize: msidbControlAttributes = 1048576i32;
pub const msidbControlAttributesIconSize16: msidbControlAttributes = 2097152i32;
pub const msidbControlAttributesIconSize32: msidbControlAttributes = 4194304i32;
pub const msidbControlAttributesIconSize48: msidbControlAttributes = 6291456i32;
pub const msidbControlAttributesElevationShield: msidbControlAttributes = 8388608i32;
pub const msidbControlAttributesHasBorder: msidbControlAttributes = 16777216i32;
pub type msidbCustomActionType = i32;
pub const msidbCustomActionTypeDll: msidbCustomActionType = 1i32;
pub const msidbCustomActionTypeExe: msidbCustomActionType = 2i32;
pub const msidbCustomActionTypeTextData: msidbCustomActionType = 3i32;
pub const msidbCustomActionTypeJScript: msidbCustomActionType = 5i32;
pub const msidbCustomActionTypeVBScript: msidbCustomActionType = 6i32;
pub const msidbCustomActionTypeInstall: msidbCustomActionType = 7i32;
pub const msidbCustomActionTypeBinaryData: msidbCustomActionType = 0i32;
pub const msidbCustomActionTypeSourceFile: msidbCustomActionType = 16i32;
pub const msidbCustomActionTypeDirectory: msidbCustomActionType = 32i32;
pub const msidbCustomActionTypeProperty: msidbCustomActionType = 48i32;
pub const msidbCustomActionTypeContinue: msidbCustomActionType = 64i32;
pub const msidbCustomActionTypeAsync: msidbCustomActionType = 128i32;
pub const msidbCustomActionTypeFirstSequence: msidbCustomActionType = 256i32;
pub const msidbCustomActionTypeOncePerProcess: msidbCustomActionType = 512i32;
pub const msidbCustomActionTypeClientRepeat: msidbCustomActionType = 768i32;
pub const msidbCustomActionTypeInScript: msidbCustomActionType = 1024i32;
pub const msidbCustomActionTypeRollback: msidbCustomActionType = 256i32;
pub const msidbCustomActionTypeCommit: msidbCustomActionType = 512i32;
pub const msidbCustomActionTypeNoImpersonate: msidbCustomActionType = 2048i32;
pub const msidbCustomActionTypeTSAware: msidbCustomActionType = 16384i32;
pub const msidbCustomActionType64BitScript: msidbCustomActionType = 4096i32;
pub const msidbCustomActionTypeHideTarget: msidbCustomActionType = 8192i32;
pub const msidbCustomActionTypePatchUninstall: msidbCustomActionType = 32768i32;
pub type msidbDialogAttributes = i32;
pub const msidbDialogAttributesVisible: msidbDialogAttributes = 1i32;
pub const msidbDialogAttributesModal: msidbDialogAttributes = 2i32;
pub const msidbDialogAttributesMinimize: msidbDialogAttributes = 4i32;
pub const msidbDialogAttributesSysModal: msidbDialogAttributes = 8i32;
pub const msidbDialogAttributesKeepModeless: msidbDialogAttributes = 16i32;
pub const msidbDialogAttributesTrackDiskSpace: msidbDialogAttributes = 32i32;
pub const msidbDialogAttributesUseCustomPalette: msidbDialogAttributes = 64i32;
pub const msidbDialogAttributesRTLRO: msidbDialogAttributes = 128i32;
pub const msidbDialogAttributesRightAligned: msidbDialogAttributes = 256i32;
pub const msidbDialogAttributesLeftScroll: msidbDialogAttributes = 512i32;
pub const msidbDialogAttributesBiDi: msidbDialogAttributes = 896i32;
pub const msidbDialogAttributesError: msidbDialogAttributes = 65536i32;
pub type msidbEmbeddedUIAttributes = i32;
pub const msidbEmbeddedUI: msidbEmbeddedUIAttributes = 1i32;
pub const msidbEmbeddedHandlesBasic: msidbEmbeddedUIAttributes = 2i32;
pub type msidbFeatureAttributes = i32;
pub const msidbFeatureAttributesFavorLocal: msidbFeatureAttributes = 0i32;
pub const msidbFeatureAttributesFavorSource: msidbFeatureAttributes = 1i32;
pub const msidbFeatureAttributesFollowParent: msidbFeatureAttributes = 2i32;
pub const msidbFeatureAttributesFavorAdvertise: msidbFeatureAttributes = 4i32;
pub const msidbFeatureAttributesDisallowAdvertise: msidbFeatureAttributes = 8i32;
pub const msidbFeatureAttributesUIDisallowAbsent: msidbFeatureAttributes = 16i32;
pub const msidbFeatureAttributesNoUnsupportedAdvertise: msidbFeatureAttributes = 32i32;
pub type msidbFileAttributes = i32;
pub const msidbFileAttributesReadOnly: msidbFileAttributes = 1i32;
pub const msidbFileAttributesHidden: msidbFileAttributes = 2i32;
pub const msidbFileAttributesSystem: msidbFileAttributes = 4i32;
pub const msidbFileAttributesReserved0: msidbFileAttributes = 8i32;
pub const msidbFileAttributesIsolatedComp: msidbFileAttributes = 16i32;
pub const msidbFileAttributesReserved1: msidbFileAttributes = 64i32;
pub const msidbFileAttributesReserved2: msidbFileAttributes = 128i32;
pub const msidbFileAttributesReserved3: msidbFileAttributes = 256i32;
pub const msidbFileAttributesVital: msidbFileAttributes = 512i32;
pub const msidbFileAttributesChecksum: msidbFileAttributes = 1024i32;
pub const msidbFileAttributesPatchAdded: msidbFileAttributes = 4096i32;
pub const msidbFileAttributesNoncompressed: msidbFileAttributes = 8192i32;
pub const msidbFileAttributesCompressed: msidbFileAttributes = 16384i32;
pub const msidbFileAttributesReserved4: msidbFileAttributes = 32768i32;
pub type msidbIniFileAction = i32;
pub const msidbIniFileActionAddLine: msidbIniFileAction = 0i32;
pub const msidbIniFileActionCreateLine: msidbIniFileAction = 1i32;
pub const msidbIniFileActionRemoveLine: msidbIniFileAction = 2i32;
pub const msidbIniFileActionAddTag: msidbIniFileAction = 3i32;
pub const msidbIniFileActionRemoveTag: msidbIniFileAction = 4i32;
pub type msidbLocatorType = i32;
pub const msidbLocatorTypeDirectory: msidbLocatorType = 0i32;
pub const msidbLocatorTypeFileName: msidbLocatorType = 1i32;
pub const msidbLocatorTypeRawValue: msidbLocatorType = 2i32;
pub const msidbLocatorType64bit: msidbLocatorType = 16i32;
pub type msidbMoveFileOptions = i32;
pub const msidbMoveFileOptionsMove: msidbMoveFileOptions = 1i32;
pub type msidbODBCDataSourceRegistration = i32;
pub const msidbODBCDataSourceRegistrationPerMachine: msidbODBCDataSourceRegistration = 0i32;
pub const msidbODBCDataSourceRegistrationPerUser: msidbODBCDataSourceRegistration = 1i32;
pub type msidbPatchAttributes = i32;
pub const msidbPatchAttributesNonVital: msidbPatchAttributes = 1i32;
pub type msidbRegistryRoot = i32;
pub const msidbRegistryRootClassesRoot: msidbRegistryRoot = 0i32;
pub const msidbRegistryRootCurrentUser: msidbRegistryRoot = 1i32;
pub const msidbRegistryRootLocalMachine: msidbRegistryRoot = 2i32;
pub const msidbRegistryRootUsers: msidbRegistryRoot = 3i32;
pub type msidbRemoveFileInstallMode = i32;
pub const msidbRemoveFileInstallModeOnInstall: msidbRemoveFileInstallMode = 1i32;
pub const msidbRemoveFileInstallModeOnRemove: msidbRemoveFileInstallMode = 2i32;
pub const msidbRemoveFileInstallModeOnBoth: msidbRemoveFileInstallMode = 3i32;
pub type msidbServiceConfigEvent = i32;
pub const msidbServiceConfigEventInstall: msidbServiceConfigEvent = 1i32;
pub const msidbServiceConfigEventUninstall: msidbServiceConfigEvent = 2i32;
pub const msidbServiceConfigEventReinstall: msidbServiceConfigEvent = 4i32;
pub type msidbServiceControlEvent = i32;
pub const msidbServiceControlEventStart: msidbServiceControlEvent = 1i32;
pub const msidbServiceControlEventStop: msidbServiceControlEvent = 2i32;
pub const msidbServiceControlEventDelete: msidbServiceControlEvent = 8i32;
pub const msidbServiceControlEventUninstallStart: msidbServiceControlEvent = 16i32;
pub const msidbServiceControlEventUninstallStop: msidbServiceControlEvent = 32i32;
pub const msidbServiceControlEventUninstallDelete: msidbServiceControlEvent = 128i32;
pub type msidbServiceInstallErrorControl = i32;
pub const msidbServiceInstallErrorControlVital: msidbServiceInstallErrorControl = 32768i32;
pub type msidbSumInfoSourceType = i32;
pub const msidbSumInfoSourceTypeSFN: msidbSumInfoSourceType = 1i32;
pub const msidbSumInfoSourceTypeCompressed: msidbSumInfoSourceType = 2i32;
pub const msidbSumInfoSourceTypeAdminImage: msidbSumInfoSourceType = 4i32;
pub const msidbSumInfoSourceTypeLUAPackage: msidbSumInfoSourceType = 8i32;
pub type msidbTextStyleStyleBits = i32;
pub const msidbTextStyleStyleBitsBold: msidbTextStyleStyleBits = 1i32;
pub const msidbTextStyleStyleBitsItalic: msidbTextStyleStyleBits = 2i32;
pub const msidbTextStyleStyleBitsUnderline: msidbTextStyleStyleBits = 4i32;
pub const msidbTextStyleStyleBitsStrike: msidbTextStyleStyleBits = 8i32;
pub type msidbUpgradeAttributes = i32;
pub const msidbUpgradeAttributesMigrateFeatures: msidbUpgradeAttributes = 1i32;
pub const msidbUpgradeAttributesOnlyDetect: msidbUpgradeAttributes = 2i32;
pub const msidbUpgradeAttributesIgnoreRemoveFailure: msidbUpgradeAttributes = 4i32;
pub const msidbUpgradeAttributesVersionMinInclusive: msidbUpgradeAttributes = 256i32;
pub const msidbUpgradeAttributesVersionMaxInclusive: msidbUpgradeAttributes = 512i32;
pub const msidbUpgradeAttributesLanguagesExclusive: msidbUpgradeAttributes = 1024i32;
pub type msifiFastInstallBits = i32;
pub const msifiFastInstallNoSR: msifiFastInstallBits = 1i32;
pub const msifiFastInstallQuickCosting: msifiFastInstallBits = 2i32;
pub const msifiFastInstallLessPrgMsg: msifiFastInstallBits = 4i32;
pub type msirbRebootReason = i32;
pub const msirbRebootUndeterminedReason: msirbRebootReason = 0i32;
pub const msirbRebootInUseFilesReason: msirbRebootReason = 1i32;
pub const msirbRebootScheduleRebootReason: msirbRebootReason = 2i32;
pub const msirbRebootForceRebootReason: msirbRebootReason = 3i32;
pub const msirbRebootCustomActionReason: msirbRebootReason = 4i32;
pub type msirbRebootType = i32;
pub const msirbRebootImmediate: msirbRebootType = 1i32;
pub const msirbRebootDeferred: msirbRebootType = 2i32;
pub type msmErrorType = i32;
pub const msmErrorLanguageUnsupported: msmErrorType = 1i32;
pub const msmErrorLanguageFailed: msmErrorType = 2i32;
pub const msmErrorExclusion: msmErrorType = 3i32;
pub const msmErrorTableMerge: msmErrorType = 4i32;
pub const msmErrorResequenceMerge: msmErrorType = 5i32;
pub const msmErrorFileCreate: msmErrorType = 6i32;
pub const msmErrorDirCreate: msmErrorType = 7i32;
pub const msmErrorFeatureRequired: msmErrorType = 8i32;
|
use prelude::*;
mod clump;
mod kmer;
mod nucl;
mod prelude;
pub use clump::clumps;
pub use kmer::Kmer;
pub use nucl::Nucl;
pub fn frequency_table(text: &[Nucl], k: usize) -> BTreeMap<usize, usize> {
let mut table = BTreeMap::new();
for w in text.windows(k) {
let kmer = Kmer::new(w);
table
.entry(kmer.to_id())
.and_modify(|count| *count += 1)
.or_insert(1);
}
table
}
#[cfg(test)]
fn pretty_table(table: &BTreeMap<usize, usize>, k: usize) -> String {
use prettytable::*;
let mut result = Table::new();
let mut titles = Row::empty();
let mut freqs = Row::empty();
for (t, f) in table.iter() {
let cell = Cell::new(&Kmer::from_id(*t, k).to_string());
titles.add_cell(cell);
freqs.add_cell(Cell::new(&f.to_string()));
}
result.add_row(titles);
result.add_row(freqs);
result.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
fn seq(str: &str) -> Vec<Nucl> {
str.chars().map(|c| c.into()).collect()
}
#[test]
fn test_frequency_table() {
let text = seq("ACGTTTCACGTTTTACGG");
let freqs = frequency_table(&text, 3);
println!("{}", pretty_table(&freqs, 3));
panic!();
// assert_eq!(0, count);
}
}
|
// Copyright (c) 2021 Quark Container Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::collections::btree_map::BTreeMap;
use alloc::collections::btree_set::BTreeSet;
use core::cmp::Ordering;
use core::ops::Deref;
use spin::Mutex;
use alloc::string::String;
use super::super::super::IOURING;
use super::*;
#[derive(Debug, Copy, Clone)]
pub struct TimerUnit {
pub timerId: u64,
pub seqNo: u64,
pub expire: i64,
}
impl TimerUnit {
pub fn New(taskId: u64, seqNo: u64, expire: i64) -> Self {
return Self {
timerId: taskId,
seqNo: seqNo,
expire: expire,
}
}
pub fn Fire(&self) {
super::FireTimer(self.timerId, self.seqNo);
}
}
impl Ord for TimerUnit {
fn cmp(&self, other: &Self) -> Ordering {
if self.expire != other.expire {
return self.expire.cmp(&other.expire)
} else {
return self.timerId.cmp(&other.timerId)
}
}
}
impl PartialOrd for TimerUnit {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for TimerUnit {}
impl PartialEq for TimerUnit {
fn eq(&self, other: &Self) -> bool {
self.timerId == other.timerId && self.seqNo == other.seqNo
}
}
#[derive(Default)]
pub struct TimerStore(Mutex<TimerStoreIntern>);
impl Deref for TimerStore {
type Target = Mutex<TimerStoreIntern>;
fn deref(&self) -> &Mutex<TimerStoreIntern> {
&self.0
}
}
impl TimerStore {
// the timeout need to process a timer, <PROCESS_TIME means the timer will be triggered immediatelyfa
pub const PROCESS_TIME : i64 = 30_000;
pub fn Print(&self) -> String {
let ts = self.lock();
return format!("expire:{:?} {:?} ", ts.nextExpire, &ts.timerSeq);
}
pub fn Trigger(&self, expire: i64) {
let mut now;
loop {
now = MONOTONIC_CLOCK.Now().0 + Self::PROCESS_TIME;
let tu = self.lock().GetFirst(now);
match tu {
Some(tu) => {
tu.Fire();
}
None => break,
}
}
{
let mut tm = self.lock();
// triggered by the the timer's timeout: No need to RemoveUringTimer
if expire == tm.nextExpire {
let firstExpire = match tm.timerSeq.first() {
None => {
core::mem::drop(&tm);
return
},
Some(t) => t.expire,
};
tm.nextExpire = 0;
tm.SetUringTimer(firstExpire);
core::mem::drop(&tm);
return
}
// the nextExpire has passed and processed
if expire != tm.nextExpire // not triggered by the the timer's timeout
&& now > tm.nextExpire { // the nextExpire has passed and processed
tm.RemoveUringTimer();
let firstExpire = match tm.timerSeq.first() {
None => {
return
},
Some(t) => t.expire,
};
tm.SetUringTimer(firstExpire);
return
}
let firstExpire = match tm.timerSeq.first() {
None => {
return
},
Some(t) => t.expire,
};
// the new added timer is early than the last expire time: RemoveUringTimer and set the new expire
if firstExpire < tm.nextExpire || tm.nextExpire == 0 {
tm.RemoveUringTimer();
tm.SetUringTimer(firstExpire);
}
}
}
pub fn ResetTimer(&mut self, timerId: u64, seqNo: u64, timeout: i64) {
self.lock().ResetTimerLocked(timerId, seqNo, timeout);
self.Trigger(0);
}
pub fn CancelTimer(&self, timerId: u64, seqNo: u64) {
self.lock().RemoveTimer(timerId, seqNo);
self.Trigger(0);
}
}
#[derive(Default)]
pub struct TimerStoreIntern {
pub timerSeq: BTreeSet<TimerUnit>, // order by expire time
pub timers: BTreeMap<u64, TimerUnit>, // timerid -> TimerUnit
pub nextExpire: i64,
pub uringId: u64,
}
impl TimerStoreIntern {
// return: existing or not
pub fn RemoveTimer(&mut self, timerId: u64, seqNo: u64) -> bool {
let tu = match self.timers.remove(&timerId) {
None => {
return false
},
Some(tu) => tu,
};
assert!(tu.seqNo == seqNo, "TimerStoreIntern::RemoveTimer doesn't match tu.seqNo is {}, expect {}", tu.seqNo, seqNo);
self.timerSeq.remove(&tu);
return true;
}
pub fn ResetTimerLocked(&mut self, timerId: u64, seqNo: u64, timeout: i64) {
if seqNo > 0 {
self.RemoveTimer(timerId, seqNo - 1);
}
let current = MONOTONIC_CLOCK.Now().0;
let expire = current + timeout;
let tu = TimerUnit {
expire: expire,
timerId: timerId,
seqNo: seqNo,
};
self.timerSeq.insert(tu.clone());
self.timers.insert(timerId, tu);
}
pub fn RemoveUringTimer(&mut self) {
if self.nextExpire != 0 {
IOURING.AsyncTimerRemove(self.uringId);
self.nextExpire = 0;
}
}
pub fn SetUringTimer(&mut self, expire: i64) {
let now = MONOTONIC_CLOCK.Now().0;
let expire = if expire < now {
now + 2000
} else {
expire
};
assert!(self.nextExpire == 0);
self.nextExpire = expire;
self.uringId = IOURING.Timeout(expire, expire - now) as u64;
}
pub fn GetFirst(&mut self, now: i64) -> Option<TimerUnit> {
let tu = match self.timerSeq.first() {
None => return None,
Some(t) => *t,
};
if tu.expire > now {
return None;
}
let timerId = tu.timerId;
self.RemoveTimer(timerId, tu.seqNo);
return Some(tu)
}
} |
use crate::{InputValueResult, Value};
/// A GraphQL scalar.
///
/// You can implement the trait to create a custom scalar.
///
/// # Examples
///
/// ```rust
/// use async_graphql::*;
///
/// struct MyInt(i32);
///
/// #[Scalar]
/// impl ScalarType for MyInt {
/// fn parse(value: Value) -> InputValueResult<Self> {
/// if let Value::Number(n) = &value {
/// if let Some(n) = n.as_i64() {
/// return Ok(MyInt(n as i32));
/// }
/// }
/// Err(InputValueError::expected_type(value))
/// }
///
/// fn to_value(&self) -> Value {
/// Value::Number(self.0.into())
/// }
/// }
/// ```
pub trait ScalarType: Sized + Send {
/// Parse a scalar value.
fn parse(value: Value) -> InputValueResult<Self>;
/// Checks for a valid scalar value.
///
/// Implementing this function can find incorrect input values during the
/// verification phase, which can improve performance.
fn is_valid(_value: &Value) -> bool {
true
}
/// Convert the scalar to `Value`.
fn to_value(&self) -> Value;
}
/// Define a scalar
///
/// If your type implemented `serde::Serialize` and `serde::Deserialize`, then
/// you can use this macro to define a scalar more simply. It helps you
/// implement the `ScalarType::parse` and `ScalarType::to_value` functions by
/// calling the [from_value](fn.from_value.html) and
/// [to_value](fn.to_value.html) functions.
///
/// # Examples
///
/// ```rust
/// use async_graphql::*;
/// use serde::{Serialize, Deserialize};
/// use std::collections::HashMap;
///
/// #[derive(Serialize, Deserialize)]
/// struct MyValue {
/// a: i32,
/// b: HashMap<String, i32>,
/// }
///
/// scalar!(MyValue);
///
/// // Rename to `MV`.
/// // scalar!(MyValue, "MV");
///
/// // Rename to `MV` and add description.
/// // scalar!(MyValue, "MV", "This is my value");
///
/// // Rename to `MV`, add description and specifiedByURL.
/// // scalar!(MyValue, "MV", "This is my value", "https://tools.ietf.org/html/rfc4122");
///
/// struct Query;
///
/// #[Object]
/// impl Query {
/// async fn value(&self, input: MyValue) -> MyValue {
/// input
/// }
/// }
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async move {
/// let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
/// let res = schema.execute(r#"{ value(input: {a: 10, b: {v1: 1, v2: 2} }) }"#).await.into_result().unwrap().data;
/// assert_eq!(res, value!({
/// "value": {
/// "a": 10,
/// "b": {"v1": 1, "v2": 2},
/// }
/// }));
/// # });
/// ```
#[macro_export]
macro_rules! scalar {
($ty:ty, $name:literal, $desc:literal, $specified_by_url:literal) => {
$crate::scalar_internal!(
$ty,
$name,
::std::option::Option::Some(::std::string::ToString::to_string($desc)),
::std::option::Option::Some(::std::string::ToString::to_string($specified_by_url))
);
};
($ty:ty, $name:literal, $desc:literal) => {
$crate::scalar_internal!(
$ty,
$name,
::std::option::Option::Some(::std::string::ToString::to_string($desc)),
::std::option::Option::None
);
};
($ty:ty, $name:literal) => {
$crate::scalar_internal!(
$ty,
$name,
::std::option::Option::None,
::std::option::Option::None
);
};
($ty:ty) => {
$crate::scalar_internal!(
$ty,
::std::stringify!($ty),
::std::option::Option::None,
::std::option::Option::None
);
};
}
#[macro_export]
#[doc(hidden)]
macro_rules! scalar_internal {
($ty:ty, $name:expr, $desc:expr, $specified_by_url:expr) => {
impl $crate::ScalarType for $ty {
fn parse(value: $crate::Value) -> $crate::InputValueResult<Self> {
::std::result::Result::Ok($crate::from_value(value)?)
}
fn to_value(&self) -> $crate::Value {
$crate::to_value(self).unwrap_or_else(|_| $crate::Value::Null)
}
}
impl $crate::InputType for $ty {
type RawValueType = Self;
fn type_name() -> ::std::borrow::Cow<'static, ::std::primitive::str> {
::std::borrow::Cow::Borrowed($name)
}
fn create_type_info(
registry: &mut $crate::registry::Registry,
) -> ::std::string::String {
registry.create_input_type::<$ty, _>($crate::registry::MetaTypeId::Scalar, |_| {
$crate::registry::MetaType::Scalar {
name: ::std::borrow::ToOwned::to_owned($name),
description: $desc,
is_valid: ::std::option::Option::Some(::std::sync::Arc::new(|value| {
<$ty as $crate::ScalarType>::is_valid(value)
})),
visible: ::std::option::Option::None,
inaccessible: false,
tags: ::std::default::Default::default(),
specified_by_url: $specified_by_url,
}
})
}
fn parse(
value: ::std::option::Option<$crate::Value>,
) -> $crate::InputValueResult<Self> {
<$ty as $crate::ScalarType>::parse(value.unwrap_or_default())
}
fn to_value(&self) -> $crate::Value {
<$ty as $crate::ScalarType>::to_value(self)
}
fn as_raw_value(&self) -> ::std::option::Option<&Self::RawValueType> {
::std::option::Option::Some(self)
}
}
#[$crate::async_trait::async_trait]
impl $crate::OutputType for $ty {
fn type_name() -> ::std::borrow::Cow<'static, ::std::primitive::str> {
::std::borrow::Cow::Borrowed($name)
}
fn create_type_info(
registry: &mut $crate::registry::Registry,
) -> ::std::string::String {
registry.create_output_type::<$ty, _>($crate::registry::MetaTypeId::Scalar, |_| {
$crate::registry::MetaType::Scalar {
name: ::std::borrow::ToOwned::to_owned($name),
description: $desc,
is_valid: ::std::option::Option::Some(::std::sync::Arc::new(|value| {
<$ty as $crate::ScalarType>::is_valid(value)
})),
visible: ::std::option::Option::None,
inaccessible: false,
tags: ::std::default::Default::default(),
specified_by_url: $specified_by_url,
}
})
}
async fn resolve(
&self,
_: &$crate::ContextSelectionSet<'_>,
_field: &$crate::Positioned<$crate::parser::types::Field>,
) -> $crate::ServerResult<$crate::Value> {
::std::result::Result::Ok($crate::ScalarType::to_value(self))
}
}
};
}
|
use super::*;
#[test]
fn with_positive_index_greater_than_length_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
(1_usize..3_usize),
strategy::term(arc_process.clone()),
(1_usize..3_usize),
strategy::term(arc_process),
)
.prop_map(
|(arc_process, len, default_value, index_offset, index_element)| {
(
arc_process.clone(),
len,
default_value,
arc_process.integer(len + index_offset),
index_element,
)
},
)
},
|(arc_process, arity_usize, default_value, position, element)| {
let arity = arc_process.integer(arity_usize);
let init = arc_process.tuple_from_slice(&[position, element]);
let init_list = arc_process.list_from_slice(&[init]);
prop_assert_badarg!(
result(&arc_process, arity, default_value, init_list),
format!("position ({}) cannot be set", position)
);
Ok(())
},
);
}
#[test]
fn with_positive_index_less_than_or_equal_to_length_replaces_default_value_at_index_with_init_list_element(
) {
TestRunner::new(Config::with_source_file(file!()))
.run(
&strategy::process()
.prop_flat_map(|arc_process| {
(
Just(arc_process.clone()),
(1_usize..3_usize),
strategy::term(arc_process),
)
})
.prop_flat_map(|(arc_process, len, default_value)| {
(
Just(arc_process.clone()),
Just(len),
Just(default_value),
0..len,
strategy::term(arc_process),
)
}),
|(arc_process, arity_usize, default_value, zero_based_index, init_list_element)| {
let arity = arc_process.integer(arity_usize);
let one_based_index = arc_process.integer(zero_based_index + 1);
let init_list = arc_process.list_from_slice(&[
arc_process.tuple_from_slice(&[one_based_index, init_list_element])
]);
let result = result(&arc_process, arity, default_value, init_list);
prop_assert!(result.is_ok());
let tuple_term = result.unwrap();
prop_assert!(tuple_term.is_boxed());
let boxed_tuple: Result<Boxed<Tuple>, _> = tuple_term.try_into();
prop_assert!(boxed_tuple.is_ok());
let tuple = boxed_tuple.unwrap();
prop_assert_eq!(tuple.len(), arity_usize);
for (index, element) in tuple.iter().enumerate() {
if index == zero_based_index {
prop_assert_eq!(element, &init_list_element);
} else {
prop_assert_eq!(element, &default_value);
}
}
Ok(())
},
)
.unwrap();
}
// > If a position occurs more than once in the list, the term corresponding to the last occurrence
// > is used.
// - http://erlang.org/doc/man/erlang.html#make_tuple-3
#[test]
fn with_multiple_values_at_same_index_then_last_value_is_used() {
TestRunner::new(Config::with_source_file(file!()))
.run(
&strategy::process()
.prop_flat_map(|arc_process| {
(
Just(arc_process.clone()),
(1_usize..3_usize),
strategy::term(arc_process),
)
})
.prop_flat_map(|(arc_process, len, default_value)| {
(
Just(arc_process.clone()),
Just(len),
Just(default_value),
0..len,
strategy::term(arc_process.clone()),
strategy::term(arc_process),
)
}),
|(
arc_process,
arity_usize,
default_value,
init_list_zero_based_index,
init_list_ignored_element,
init_list_used_element,
)| {
let arity = arc_process.integer(arity_usize);
let init_list_one_base_index = arc_process.integer(init_list_zero_based_index + 1);
let init_list = arc_process.list_from_slice(&[
arc_process
.tuple_from_slice(&[init_list_one_base_index, init_list_ignored_element]),
arc_process
.tuple_from_slice(&[init_list_one_base_index, init_list_used_element]),
]);
let result = result(&arc_process, arity, default_value, init_list);
prop_assert!(result.is_ok());
let tuple_term = result.unwrap();
prop_assert!(tuple_term.is_boxed());
let boxed_tuple: Result<Boxed<Tuple>, _> = tuple_term.try_into();
prop_assert!(boxed_tuple.is_ok());
let tuple = boxed_tuple.unwrap();
prop_assert_eq!(tuple.len(), arity_usize);
for (index, element) in tuple.iter().enumerate() {
if index == init_list_zero_based_index {
prop_assert_eq!(element, &init_list_used_element);
} else {
prop_assert_eq!(element, &default_value);
}
}
Ok(())
},
)
.unwrap();
}
|
//use std::fs::File;
//use std::io::Write;
//use std::path::Path;
//use std::env;
//use std::process::Command;
fn main() {
// let out_dir = env::var("OUT_DIR").unwrap();
//
// Command::new("upx").args(&["src/hello.c", "-c", "-fPIC", "-o"])
// .arg(&format!("{}/hello.o", out_dir));
} |
use std::time::Duration;
use crate::{
HistogramObservation, MakeMetricObserver, MetricKind, MetricObserver, Observation,
ObservationBucket, U64Counter, U64Gauge, U64Histogram,
};
use std::convert::TryInto;
/// The maximum duration that can be stored in the duration measurements
pub const DURATION_MAX: Duration = Duration::from_nanos(u64::MAX);
/// A monotonic counter of `std::time::Duration`
#[derive(Debug, Clone, Default)]
pub struct DurationCounter {
inner: U64Counter,
}
impl DurationCounter {
pub fn inc(&self, duration: Duration) {
self.inner.inc(
duration
.as_nanos()
.try_into()
.expect("cannot fit duration into u64"),
)
}
pub fn fetch(&self) -> Duration {
Duration::from_nanos(self.inner.fetch())
}
}
impl MetricObserver for DurationCounter {
type Recorder = Self;
fn kind() -> MetricKind {
MetricKind::DurationCounter
}
fn recorder(&self) -> Self::Recorder {
self.clone()
}
fn observe(&self) -> Observation {
Observation::DurationCounter(self.fetch())
}
}
/// An observation of a single `std::time::Duration`
///
/// NOTE: If the same `DurationGauge` is used in multiple locations, e.g. a non-unique set
/// of attributes is provided to `Metric<DurationGauge>::recorder`, the reported value
/// will oscillate between those reported by the separate locations
#[derive(Debug, Clone, Default)]
pub struct DurationGauge {
inner: U64Gauge,
}
impl DurationGauge {
pub fn set(&self, value: Duration) {
self.inner.set(
value
.as_nanos()
.try_into()
.expect("cannot fit duration into u64"),
)
}
pub fn fetch(&self) -> Duration {
Duration::from_nanos(self.inner.fetch())
}
}
impl MetricObserver for DurationGauge {
type Recorder = Self;
fn kind() -> MetricKind {
MetricKind::DurationGauge
}
fn recorder(&self) -> Self::Recorder {
self.clone()
}
fn observe(&self) -> Observation {
Observation::DurationGauge(self.fetch())
}
}
/// A `DurationHistogram` provides bucketed observations of `Durations`
///
/// This provides insight into the distribution beyond a simple count or total
#[derive(Debug, Clone)]
pub struct DurationHistogram {
inner: U64Histogram,
}
impl DurationHistogram {
pub fn fetch(&self) -> HistogramObservation<Duration> {
let inner = self.inner.fetch();
HistogramObservation {
total: Duration::from_nanos(inner.total),
buckets: inner
.buckets
.into_iter()
.map(|bucket| ObservationBucket {
le: Duration::from_nanos(bucket.le),
count: bucket.count,
})
.collect(),
}
}
pub fn record(&self, value: Duration) {
self.record_multiple(value, 1)
}
pub fn record_multiple(&self, value: Duration, count: u64) {
self.inner.record_multiple(
value
.as_nanos()
.try_into()
.expect("cannot fit duration into u64"),
count,
)
}
}
/// `DurationHistogramOptions` allows configuring the buckets used by `DurationHistogram`
#[derive(Debug, Clone)]
pub struct DurationHistogramOptions {
buckets: Vec<Duration>,
}
impl DurationHistogramOptions {
/// Create a new `DurationHistogramOptions` with a list of thresholds to delimit the buckets
pub fn new(thresholds: impl IntoIterator<Item = Duration>) -> Self {
let mut buckets: Vec<_> = thresholds.into_iter().collect();
buckets.sort_unstable();
Self { buckets }
}
}
impl Default for DurationHistogramOptions {
fn default() -> Self {
Self {
buckets: vec![
Duration::from_millis(1),
Duration::from_micros(2_500),
Duration::from_millis(5),
Duration::from_millis(10),
Duration::from_millis(25),
Duration::from_millis(50),
Duration::from_millis(100),
Duration::from_millis(250),
Duration::from_millis(500),
Duration::from_millis(1000),
Duration::from_millis(2500),
Duration::from_millis(5000),
Duration::from_millis(10000),
DURATION_MAX,
],
}
}
}
impl MakeMetricObserver for DurationHistogram {
type Options = DurationHistogramOptions;
fn create(options: &DurationHistogramOptions) -> Self {
Self {
inner: U64Histogram::new(options.buckets.iter().map(|duration| {
duration
.as_nanos()
.try_into()
.expect("cannot fit duration into u64")
})),
}
}
}
impl MetricObserver for DurationHistogram {
type Recorder = Self;
fn kind() -> MetricKind {
MetricKind::DurationHistogram
}
fn recorder(&self) -> Self::Recorder {
self.clone()
}
fn observe(&self) -> Observation {
Observation::DurationHistogram(self.fetch())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn test_gauge() {
let gauge = DurationGauge::default();
assert_eq!(
gauge.observe(),
Observation::DurationGauge(Duration::from_nanos(0))
);
gauge.set(Duration::from_nanos(10002));
assert_eq!(
gauge.observe(),
Observation::DurationGauge(Duration::from_nanos(10002))
);
gauge.set(Duration::from_nanos(12));
assert_eq!(
gauge.observe(),
Observation::DurationGauge(Duration::from_nanos(12))
);
let r2 = gauge.recorder();
gauge.set(Duration::from_secs(12));
assert_eq!(
gauge.observe(),
Observation::DurationGauge(Duration::from_secs(12))
);
std::mem::drop(r2);
assert_eq!(
gauge.observe(),
Observation::DurationGauge(Duration::from_secs(12))
);
}
#[test]
fn test_counter() {
let counter = DurationCounter::default();
assert_eq!(counter.fetch(), Duration::from_nanos(0));
counter.inc(Duration::from_nanos(120));
assert_eq!(counter.fetch(), Duration::from_nanos(120));
counter.inc(Duration::from_secs(1));
assert_eq!(counter.fetch(), Duration::from_nanos(1_000_000_120));
assert_eq!(
counter.observe(),
Observation::DurationCounter(Duration::from_nanos(1_000_000_120))
)
}
#[test]
#[should_panic(expected = "cannot fit duration into u64: TryFromIntError(())")]
fn test_bucket_overflow() {
let options = DurationHistogramOptions::new([Duration::MAX]);
DurationHistogram::create(&options);
}
#[test]
#[should_panic(expected = "cannot fit duration into u64: TryFromIntError(())")]
fn test_record_overflow() {
let histogram = DurationHistogram::create(&Default::default());
histogram.record(Duration::MAX);
}
#[test]
fn test_histogram() {
let buckets = [
Duration::from_millis(10),
Duration::from_millis(15),
Duration::from_millis(100),
DURATION_MAX,
];
let options = DurationHistogramOptions::new(buckets);
let histogram = DurationHistogram::create(&options);
let buckets = |expected: &[u64; 4], total| -> Observation {
Observation::DurationHistogram(HistogramObservation {
total,
buckets: expected
.iter()
.cloned()
.zip(buckets)
.map(|(count, le)| ObservationBucket { le, count })
.collect(),
})
};
assert_eq!(
histogram.observe(),
buckets(&[0, 0, 0, 0], Duration::from_millis(0))
);
histogram.record(Duration::from_millis(20));
assert_eq!(
histogram.observe(),
buckets(&[0, 0, 1, 0], Duration::from_millis(20))
);
histogram.record(Duration::from_millis(0));
assert_eq!(
histogram.observe(),
buckets(&[1, 0, 1, 0], Duration::from_millis(20))
);
histogram.record(DURATION_MAX);
// Expect total to overflow and wrap around
assert_eq!(
histogram.observe(),
buckets(
&[1, 0, 1, 1],
Duration::from_millis(20) - Duration::from_nanos(1)
)
);
}
}
|
use log::LevelFilter;
use rraw::auth::AnonymousAuthenticator;
use rraw::Client;
fn init() {
if let Err(error) = env_logger::builder()
.is_test(true)
.filter_level(LevelFilter::Debug)
.try_init()
{
println!("Logger Failed to Init Error: {}", error);
}
}
#[ignore]
#[tokio::test]
async fn generic() -> anyhow::Result<()> {
init();
let client = Client::login(AnonymousAuthenticator::new(), "RRAW Test (by u/KingTuxWH)").await?;
let subreddit = client.subreddit("askreddit").await;
assert!(subreddit.is_ok());
let data = subreddit.unwrap();
for (id, value) in data.subreddit.other.iter() {
println!("{id}: {value:?}");
}
return Ok(());
}
|
use std::fs::File;
use std::io::prelude::*;
// --- file read
fn read_file(filename: &str) -> std::io::Result<String> {
let mut file = File::open(filename)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn exec_line(program_code: String, pc:usize, counter: i32)->(usize, i32){
let mut next_pc = pc;
let mut next_counter = counter;
let opcode_arg: Vec<String> = program_code.split(" ").map(|s|s.to_string()).collect();
if opcode_arg[0] == "nop"{
next_pc +=1;
println!("{:<10} \x1b[0;36m PC:{:<7}\x1b[0m \x1b[0;32mCOUNTER:{}\x1b[0m", program_code, pc, counter);
}else if opcode_arg[0] == "jmp"{
let arg: String = opcode_arg[1].to_string();
let sign_s = arg.chars().nth(0).expect("char not found");
let arg:usize = opcode_arg[1].trim_start_matches(sign_s).to_string().parse().unwrap();
if sign_s == '-'{
next_pc -= arg;
}
else {
next_pc += arg;
}
println!("\x1b[0;35m{:<10}\x1b[0m \x1b[0;36m PC:{:<7}\x1b[0m \x1b[0;32mCOUNTER:{}\x1b[0m", program_code, pc, counter);
}else if opcode_arg[0] == "acc"{
next_pc +=1;
let arg: String = opcode_arg[1].to_string();
let sign_s = arg.chars().nth(0).expect("char not found");
let arg:i32 = opcode_arg[1].trim_start_matches(sign_s).to_string().parse().unwrap();
if sign_s == '-'{
next_counter -= arg;
}
else {
next_counter += arg;
}
//println!("{}", sign);
println!("\x1b[0;33m{:<10}\x1b[0m \x1b[0;36m PC:{:<7}\x1b[0m \x1b[0;32mCOUNTER:{}\x1b[0m", program_code, pc, counter);
}
(next_pc,next_counter)
}
fn main(){
let input:String = read_file("../input.txt").expect("Errore nella lettura file");
let program_code: Vec<String> = input.lines().map(|line|line.to_string()).collect();
let mut pc_history: Vec<usize> = Vec::<usize>::new();
let mut pc: usize = 0;
let mut counter: i32 = 0;
while !pc_history.contains(&pc) && pc < program_code.len(){
pc_history.push(pc);
let (ret_pc, ret_counter) = exec_line(program_code[pc].to_string(), pc, counter);
pc = ret_pc;
counter = ret_counter;
//println!("{:?}", pc_history);
//println!("{:?}", !pc_history.contains(&pc));
//println!("{:?}", (pc < program_code.len()));
}
} |
//! This file contains an operator which internally uses an arena allocator
//! for all local allocations.
use arcon::prelude::*;
use arcon_macros::Arcon;
use arcon_state::Backend;
use bumpalo::boxed::Box;
use bumpalo::collections::String;
use bumpalo::collections::Vec;
use kompact::prelude::ComponentDefinition;
pub(crate) struct MyOperator {
arena: bumpalo::Bump,
}
#[cfg_attr(feature = "arcon_serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Arcon, prost::Message, Copy, Clone, abomonation_derive::Abomonation)]
#[arcon(unsafe_ser_id = 12, reliable_ser_id = 13, version = 1)]
pub(crate) struct MyData {
#[prost(int32, tag = "1")]
pub i: i32,
}
impl Operator for MyOperator {
type IN = MyData;
type OUT = MyData;
type TimerState = ArconNever;
type OperatorState = ();
fn handle_element(
&mut self,
element: ArconElement<Self::IN>,
mut ctx: OperatorContext<Self, impl Backend, impl ComponentDefinition>,
) -> ArconResult<()> {
// Always begin by resetting the allocator to 0.
self.arena.reset();
// Demonstration code (Probably a bit too complicated to generate directly)
test_list(self, element.clone(), &mut ctx);
test_vec(self, element.clone(), &mut ctx);
test_string(self, element.clone(), &mut ctx);
Ok(())
}
arcon::ignore_timeout!();
arcon::ignore_persist!();
}
enum List<'i, T> {
Cons(T, Box<'i, List<'i, T>>),
Nil,
}
/// Tests arena-allocating a custom linked-list
fn test_list(
op: &mut MyOperator,
element: ArconElement<MyData>,
ctx: &mut OperatorContext<MyOperator, impl Backend, impl ComponentDefinition>,
) {
// Create a big linked list in a single allocation.
let mut list = List::Nil;
for i in 0..element.data.i {
list = List::Cons(i, Box::new_in(list, &op.arena));
}
// Fold the thing imperatively while emitting output.
let mut sum = 0;
let mut iter = &list;
while let List::Cons(i, tail) = iter {
sum += i;
iter = tail;
ctx.output(ArconElement {
timestamp: element.timestamp,
data: MyData { i: sum },
});
}
}
/// Tests arena-allocating a vector
fn test_vec(
op: &mut MyOperator,
element: ArconElement<MyData>,
ctx: &mut OperatorContext<MyOperator, impl Backend, impl ComponentDefinition>,
) {
// Same code as test_list
let mut vec = Vec::new_in(&op.arena);
for i in 0..element.data.i {
vec.push(i);
}
let mut sum = 0;
while let Some(i) = vec.pop() {
sum += i;
ctx.output(ArconElement {
timestamp: element.timestamp,
data: MyData { i: sum },
});
}
}
/// Tests arena-allocating a string
fn test_string(
op: &mut MyOperator,
element: ArconElement<MyData>,
ctx: &mut OperatorContext<MyOperator, impl Backend, impl ComponentDefinition>,
) {
let mut string = String::new_in(&op.arena);
for _ in 0..element.data.i {
string.push('a');
}
while let Some(c) = string.pop() {
ctx.output(ArconElement {
timestamp: element.timestamp,
data: MyData { i: c as i32 },
});
}
}
|
use super::is_transient_error;
use crate::listener::Listener;
use crate::{log, Server};
use std::fmt::{self, Display, Formatter};
use async_std::os::unix::net::{self, SocketAddr, UnixStream};
use async_std::prelude::*;
use async_std::{io, path::PathBuf, task};
/// This represents a tide [Listener](crate::listener::Listener) that
/// wraps an [async_std::os::unix::net::UnixListener]. It is implemented as an
/// enum in order to allow creation of a tide::listener::UnixListener
/// from a [PathBuf] that has not yet been opened/bound OR from a bound
/// [async_std::os::unix::net::UnixListener].
///
/// This is currently crate-visible only, and tide users are expected
/// to create these through [ToListener](crate::ToListener) conversions.
#[derive(Debug)]
pub enum UnixListener {
FromPath(PathBuf, Option<net::UnixListener>),
FromListener(net::UnixListener),
}
impl UnixListener {
pub fn from_path(path: impl Into<PathBuf>) -> Self {
Self::FromPath(path.into(), None)
}
pub fn from_listener(listener: impl Into<net::UnixListener>) -> Self {
Self::FromListener(listener.into())
}
fn listener(&self) -> io::Result<&net::UnixListener> {
match self {
Self::FromPath(_, Some(listener)) => Ok(listener),
Self::FromListener(listener) => Ok(listener),
Self::FromPath(path, None) => Err(io::Error::new(
io::ErrorKind::AddrNotAvailable,
format!(
"unable to connect to {}",
path.to_str().unwrap_or("[unknown]")
),
)),
}
}
async fn connect(&mut self) -> io::Result<()> {
if let Self::FromPath(path, listener @ None) = self {
*listener = Some(net::UnixListener::bind(path).await?);
}
Ok(())
}
}
fn unix_socket_addr_to_string(result: io::Result<SocketAddr>) -> Option<String> {
result.ok().and_then(|addr| {
if let Some(pathname) = addr.as_pathname().and_then(|p| p.canonicalize().ok()) {
Some(format!("http+unix://{}", pathname.display()))
} else {
None
}
})
}
fn handle_unix<State: Clone + Send + Sync + 'static>(app: Server<State>, stream: UnixStream) {
task::spawn(async move {
let local_addr = unix_socket_addr_to_string(stream.local_addr());
let peer_addr = unix_socket_addr_to_string(stream.peer_addr());
let fut = async_h1::accept(stream, |mut req| async {
req.set_local_addr(local_addr.as_ref());
req.set_peer_addr(peer_addr.as_ref());
app.respond(req).await
});
if let Err(error) = fut.await {
log::error!("async-h1 error", { error: error.to_string() });
}
});
}
#[async_trait::async_trait]
impl<State: Clone + Send + Sync + 'static> Listener<State> for UnixListener {
async fn listen(&mut self, app: Server<State>) -> io::Result<()> {
self.connect().await?;
crate::log::info!("Server listening on {}", self);
let listener = self.listener()?;
let mut incoming = listener.incoming();
while let Some(stream) = incoming.next().await {
match stream {
Err(ref e) if is_transient_error(e) => continue,
Err(error) => {
let delay = std::time::Duration::from_millis(500);
crate::log::error!("Error: {}. Pausing for {:?}.", error, delay);
task::sleep(delay).await;
continue;
}
Ok(stream) => {
handle_unix(app.clone(), stream);
}
};
}
Ok(())
}
}
impl Display for UnixListener {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::FromListener(l) | Self::FromPath(_, Some(l)) => write!(
f,
"{}",
unix_socket_addr_to_string(l.local_addr())
.as_deref()
.unwrap_or("http+unix://[unknown]")
),
Self::FromPath(path, None) => {
write!(f, "http+unix://{}", path.to_str().unwrap_or("[unknown]"))
}
}
}
}
|
fn main() {
let vec = Vec::new();
work_on_bytes(&vec);
let arr = [0; 10];
work_on_bytes(&arr);
let slice = &[1, 2, 3];
work_on_bytes(slice);
}
fn work_on_bytes(slice: &[u8]) {
} |
//! Buffer usage, creation-info and wrappers.
mod usage;
pub use {
self::usage::{Usage, *},
gfx_hal::buffer::*,
};
use crate::{
escape::{Escape, KeepAlive, Terminal},
memory::{Block, MappedRange, MemoryBlock},
};
/// Buffer info.
#[derive(Clone, Copy, Debug)]
pub struct Info {
/// Buffer size.
pub size: u64,
/// Buffer usage flags.
pub usage: gfx_hal::buffer::Usage,
}
/// Generic buffer object wrapper.
#[derive(Debug)]
pub struct Buffer<B: gfx_hal::Backend> {
escape: Escape<(B::Buffer, MemoryBlock<B>)>,
info: Info,
}
impl<B> Buffer<B>
where
B: gfx_hal::Backend,
{
/// Wrap a buffer.
///
/// # Safety
///
/// `info` must match information about raw buffer.
/// `block` if provided must be the one bound to the raw buffer.
/// `terminal` will receive buffer and memory block upon drop, it must free buffer and memory properly.
///
pub unsafe fn new(
info: Info,
raw: B::Buffer,
block: MemoryBlock<B>,
terminal: &Terminal<(B::Buffer, MemoryBlock<B>)>,
) -> Self {
Buffer {
escape: terminal.escape((raw, block)),
info,
}
}
/// This will return `None` and would be equivalent to dropping
/// if there are `KeepAlive` created from this `Buffer.
pub fn unescape(self) -> Option<(B::Buffer, MemoryBlock<B>)> {
Escape::unescape(self.escape)
}
/// Creates [`KeepAlive`] handler to extend buffer lifetime.
///
/// [`KeepAlive`]: struct.KeepAlive.html
pub fn keep_alive(&self) -> KeepAlive {
Escape::keep_alive(&self.escape)
}
/// Check if this buffer could is bound to CPU visible memory and therefore mappable.
/// If this function returns `false` `map` will always return `InvalidAccess`.
///
/// [`map`]: #method.map
/// [`InvalidAccess`]: https://docs.rs/gfx-hal/0.1/gfx_hal/mapping/enum.Error.html#InvalidAccess
pub fn visible(&self) -> bool {
self.escape
.1
.properties()
.contains(gfx_hal::memory::Properties::CPU_VISIBLE)
}
/// Map range of the buffer to the CPU accessible memory.
pub fn map<'a>(
&'a mut self,
device: &impl gfx_hal::Device<B>,
range: std::ops::Range<u64>,
) -> Result<MappedRange<'a, B>, gfx_hal::mapping::Error> {
self.escape.1.map(device, range)
}
// /// Map range of the buffer to the CPU accessible memory.
// pub fn persistent_map(&mut self, range: std::ops::Range<u64>) -> Result<MappedRange<'a, B>, gfx_hal::mapping::Error> {
// self.escape.1.map(device, range)
// }
/// Get raw buffer handle.
///
/// # Safety
///
/// Raw buffer handler should not be used to violate this object valid usage.
pub fn raw(&self) -> &B::Buffer {
&self.escape.0
}
/// Get buffer info.
pub fn info(&self) -> &Info {
&self.info
}
/// Get buffer info.
pub fn size(&self) -> u64 {
self.info.size
}
}
|
use crate::domain;
use near_sdk::{
json_types::U64,
serde::{Deserialize, Serialize},
};
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(crate = "near_sdk::serde")]
pub struct Gas(pub U64);
impl From<domain::Gas> for Gas {
fn from(value: domain::Gas) -> Self {
value.0.into()
}
}
impl From<u64> for Gas {
fn from(value: u64) -> Self {
Self(value.into())
}
}
|
#![no_std]
extern crate wfe_executor;
extern crate nrf51;
extern crate nrf51_hal;
extern crate nrf51_blinker;
use wfe_executor::Executor;
use nrf51_hal::{timer::Timer, gpio::GpioExt};
pub fn main() {
let core = nrf51::CorePeripherals::take().unwrap();
let peripherals = nrf51::Peripherals::take().unwrap();
let gpio = peripherals.GPIO.split();
let timer = Timer::new(peripherals.TIMER0);
let led = gpio.pin21.into_open_drain_output();
let button = gpio.pin15.into_pull_up_input();
let future = nrf51_blinker::main(timer, led, button);
Executor::new(core).run_stable(future);
}
|
#![allow(dead_code)]
extern crate cgmath;
extern crate embree;
extern crate support;
use cgmath::{Vector3, Vector4};
use embree::{Device, Geometry, IntersectContext, QuadMesh, Ray, RayHit, Scene, TriangleMesh};
use support::Camera;
fn make_cube<'a>(device: &'a Device) -> Geometry<'a> {
let mut mesh = TriangleMesh::unanimated(device, 12, 8);
{
let mut verts = mesh.vertex_buffer.map();
let mut tris = mesh.index_buffer.map();
verts[0] = Vector4::new(-1.0, -1.0, -1.0, 0.0);
verts[1] = Vector4::new(-1.0, -1.0, 1.0, 0.0);
verts[2] = Vector4::new(-1.0, 1.0, -1.0, 0.0);
verts[3] = Vector4::new(-1.0, 1.0, 1.0, 0.0);
verts[4] = Vector4::new(1.0, -1.0, -1.0, 0.0);
verts[5] = Vector4::new(1.0, -1.0, 1.0, 0.0);
verts[6] = Vector4::new(1.0, 1.0, -1.0, 0.0);
verts[7] = Vector4::new(1.0, 1.0, 1.0, 0.0);
// left side
tris[0] = Vector3::new(0, 2, 1);
tris[1] = Vector3::new(1, 2, 3);
// right side
tris[2] = Vector3::new(4, 5, 6);
tris[3] = Vector3::new(5, 7, 6);
// bottom side
tris[4] = Vector3::new(0, 1, 4);
tris[5] = Vector3::new(1, 5, 4);
// top side
tris[6] = Vector3::new(2, 6, 3);
tris[7] = Vector3::new(3, 6, 7);
// front side
tris[8] = Vector3::new(0, 4, 2);
tris[9] = Vector3::new(2, 4, 6);
// back side
tris[10] = Vector3::new(1, 3, 5);
tris[11] = Vector3::new(3, 7, 5);
}
let mut mesh = Geometry::Triangle(mesh);
mesh.commit();
mesh
}
fn make_ground_plane<'a>(device: &'a Device) -> Geometry<'a> {
let mut mesh = QuadMesh::unanimated(device, 1, 4);
{
let mut verts = mesh.vertex_buffer.map();
let mut quads = mesh.index_buffer.map();
verts[0] = Vector4::new(-10.0, -2.0, -10.0, 0.0);
verts[1] = Vector4::new(-10.0, -2.0, 10.0, 0.0);
verts[2] = Vector4::new(10.0, -2.0, 10.0, 0.0);
verts[3] = Vector4::new(10.0, -2.0, -10.0, 0.0);
quads[0] = Vector4::new(0, 1, 2, 3);
}
let mut mesh = Geometry::Quad(mesh);
mesh.commit();
mesh
}
fn main() {
let mut display = support::Display::new(512, 512, "triangle geometry");
let device = Device::new();
let cube = make_cube(&device);
let ground = make_ground_plane(&device);
// TODO: Support for Embree3's new vertex attributes
let face_colors = vec![
Vector3::new(1.0, 0.0, 0.0),
Vector3::new(1.0, 0.0, 0.0),
Vector3::new(0.0, 1.0, 0.0),
Vector3::new(0.0, 1.0, 0.0),
Vector3::new(1.0, 0.0, 1.0),
Vector3::new(1.0, 0.0, 1.0),
Vector3::new(1.0, 1.0, 1.0),
Vector3::new(1.0, 1.0, 1.0),
Vector3::new(0.0, 0.0, 1.0),
Vector3::new(0.0, 0.0, 1.0),
Vector3::new(1.0, 1.0, 0.0),
Vector3::new(1.0, 1.0, 0.0),
];
let mut scene = Scene::new(&device);
scene.attach_geometry(cube);
let ground_id = scene.attach_geometry(ground);
let rtscene = scene.commit();
let mut intersection_ctx = IntersectContext::coherent();
display.run(|image, camera_pose, _| {
for p in image.iter_mut() {
*p = 0;
}
let img_dims = image.dimensions();
let camera = Camera::look_dir(
camera_pose.pos,
camera_pose.dir,
camera_pose.up,
75.0,
img_dims,
);
// Render the scene
for j in 0..img_dims.1 {
for i in 0..img_dims.0 {
let dir = camera.ray_dir((i as f32 + 0.5, j as f32 + 0.5));
let ray = Ray::new(camera.pos, dir);
let mut ray_hit = RayHit::new(ray);
rtscene.intersect(&mut intersection_ctx, &mut ray_hit);
if ray_hit.hit.hit() {
let mut p = image.get_pixel_mut(i, j);
let color = if ray_hit.hit.geomID == ground_id {
Vector3::new(0.6, 0.6, 0.6)
} else {
face_colors[ray_hit.hit.primID as usize]
};
p[0] = (color.x * 255.0) as u8;
p[1] = (color.y * 255.0) as u8;
p[2] = (color.z * 255.0) as u8;
}
}
}
});
}
|
use std::io::Read;
fn main() {
let mut buf = String::new();
// 標準入力から全部bufに読み込む
std::io::stdin().read_to_string(&mut buf).unwrap();
// 行ごとのiterが取れる
let mut iter = buf.split_whitespace();
let problem_counts: usize = iter.next().unwrap().parse().unwrap();
let target_score: usize = iter.next().unwrap().parse().unwrap();
let bornases: Vec<(usize, usize, usize)> = (0..problem_counts)
.enumerate()
.map(|(i, _)| {
(
(i + 1) * 100,
iter.next().unwrap().parse::<usize>().unwrap(),
iter.next().unwrap().parse::<usize>().unwrap(),
)
})
.map(|x| (x.0, x.1, x.0 * x.1 + x.2))
.collect();
#[derive(Clone, Debug)]
struct Pattern {
attempts: usize,
score: usize,
another_list: Vec<(usize, usize)>,
}
// 各行を選ぶ選ばないパターンを作る
let mut patterns = Vec::new();
// 2の3乗の組み合わせを作成
for i in 0..2usize.pow(problem_counts as u32) {
let mut row = Pattern {
attempts: 0,
score: 0,
another_list: vec![(
bornases[problem_counts - 1].0,
bornases[problem_counts - 1].1,
)],
};
// ビット演算する際の最大桁が1桁目に来るとこで
// シフトできれば良いので、number.len()-1までloop
let anothers: Vec<(usize, usize)> = (0..problem_counts)
.filter(|j| ((i >> j) & 1) != 1)
.map(|j| (bornases[j].0, bornases[j].1))
.collect();
for j in 0..problem_counts {
// j桁右シフトして最初のbitが1かチェック
if ((i >> j) & 1) == 1 {
row = Pattern {
attempts: row.attempts + bornases[j].1,
score: row.score + bornases[j].2,
another_list: anothers.clone(),
};
}
}
patterns.push(row);
}
let mut result = 10000000;
for pattern in &patterns {
let mut tmp_count = 0;
if pattern.score >= target_score {
tmp_count = pattern.attempts;
} else {
let mut current_score = pattern.score;
tmp_count = pattern.attempts;
'outer: for anothers in pattern.another_list.iter().rev() {
for _ in 0..anothers.1 {
if current_score < target_score {
tmp_count += 1;
current_score += anothers.0;
} else {
break 'outer;
}
}
}
if current_score < target_score {
continue;
}
}
if result > tmp_count && tmp_count != 0 {
result = tmp_count;
}
}
println!("{}", result);
}
|
use actix::prelude::*;
use serde::Serialize;
// use chrono::prelude::*;
// use std::time::Duration;
#[derive(Message)]
pub struct StatusUpdate {
pub status: ControllerState
}
// #[derive(Message)]
pub enum WorkerCommand {
Create,
Render,
Halt,
Destroy
}
impl Message for WorkerCommand {
// type Result = String;
type Result = Result<String, String>;
}
#[derive(Message)]
pub struct Connect {
pub addr: Recipient<StatusUpdate>,
}
#[derive(Message)]
pub struct CreateWorker {
}
#[derive(Debug, Clone, Serialize)]
pub struct ControllerState {
pub jobs: Vec<Job>
}
#[derive(Debug, Clone, Serialize)]
pub struct Job {
}
#[derive(Debug, Clone, Serialize)]
struct JobStatus {
frame_start: u32,
frame_end: u32,
render_times: Vec<u32>,
// time_start: Option<DateTime<Local>>,
// time_end: Option<DateTime<Local>>
}
|
#[macro_use]
extern crate nom;
use nom::{IResult, digit};
use std::collections::BTreeSet;
use std::io::{self, Read};
use std::str;
use std::str::FromStr;
#[derive(Debug)]
enum Dir {
Left,
Right
}
#[derive(Debug)]
struct Step {
dir: Dir,
dist: u16
}
named!(dir<Dir>, alt_complete!(value!(Dir::Left, char!('L')) | value!(Dir::Right, char!('R'))));
named!(step<Step>,
chain!(
d: dir ~
s: map_res!(map_res!(digit, str::from_utf8), FromStr::from_str),
|| {Step{dir: d, dist: s}}
)
);
named!(input<Vec<Step> >,
separated_nonempty_list!(
tag!(", "),
step
)
);
#[derive(PartialEq, Eq, Debug)]
enum Compass {
N,E,S,W
}
impl Compass {
fn rotate(&self, way: &Dir) -> Compass {
match *self {
Compass::N => match *way {
Dir::Left => Compass::W,
Dir::Right => Compass::E
},
Compass::E => match *way {
Dir::Left => Compass::N,
Dir::Right => Compass::S
},
Compass::S => match *way {
Dir::Left => Compass::E,
Dir::Right => Compass::W
},
Compass::W => match *way {
Dir::Left => Compass::S,
Dir::Right => Compass::N
}
}
}
fn turn(&mut self, way: &Dir) {
*self = self.rotate(way);
}
fn step_by(&self, coord: &mut (i16, i16)) {
match *self {
Compass::N => coord.1 += 1,
Compass::E => coord.0 += 1,
Compass::S => coord.1 -= 1,
Compass::W => coord.0 -= 1
};
}
}
fn main() {
let mut i : Vec<u8> = Vec::new();
let _ = io::stdin().read_to_end(&mut i);
let moves : Vec<Step> = match input(i.as_slice()) {
IResult::Done(_, r) => r,
_ => panic!()
};
let mut dir = Compass::N;
let mut loc = (0i16, 0i16);
let mut visited = BTreeSet::new();
let mut found = false;
for Step{dir: d, dist: s} in moves {
dir.turn(&d);
for _ in 0..s {
dir.step_by(&mut loc);
if !found {
if visited.contains(&loc) {
println!("Repeated visit to {}, {}, {}", loc.0, loc.1, loc.0.abs() + loc.1.abs());
found = true;
}
visited.insert(loc);
}
}
}
println!("Ended up at {}, {}, {}", loc.0, loc.1, loc.0.abs() + loc.1.abs());
}
|
#[macro_use]
extern crate lazy_static;
use regex::Regex;
use std::collections::HashMap;
fn as_fuddy(content: &mut String, reg: &Regex, replace: &str) {
let result = reg.replace_all(content, replace).to_string();
content.clear();
content.push_str(&result);
}
fn get_expressions() -> HashMap<&'static str, &'static str> {
[
(r#"(r|l)"#, "w"),
(r#"qu"#, "qw"),
(r#"th(\s)"#, "f$1"),
(r"th", "d"),
(r#"n\."#, "n, uh-hah-ha-ha."),
(r"(R|L)", "W"),
(r"(Qu|QW)", "QW"),
(r"TH(\s)", "F$1"),
(r"Th", "D"),
(r"N\.", "N, uh-hah-hah-hah"),
]
.iter()
.cloned()
.collect()
}
pub fn get_fudd(input: &str) -> String {
let mut result = input.to_string();
lazy_static! {
static ref EXPRESSIONS: Vec<(&'static str, &'static str)> = get_expressions()
.into_iter()
.map(|(k, v)| (k, v))
.collect::<Vec<(&str, &str)>>();
static ref REGEXS: Vec<Regex> = EXPRESSIONS
.iter()
.map(|(k, _)| (Regex::new(k).unwrap()))
.collect::<Vec<Regex>>();
};
for (i, (_, v)) in EXPRESSIONS.iter().enumerate() {
as_fuddy(&mut result, ®EXS[i], v)
}
result
}
#[cfg(test)]
mod tests {
use crate::get_fudd;
#[test]
fn given_rabbits_then_expect_wabbits() {
let result = get_fudd("rabbits");
assert_eq!(result, "wabbits");
}
#[test]
fn given_quiet_then_expect_qwiet() {
let result = get_fudd("quiet");
assert_eq!(result, "qwiet");
}
#[test]
fn given_thats_then_expect_dats() {
let result = get_fudd("thats");
assert_eq!(result, "dats");
}
#[test]
fn given_two_lines_expect_dialect_applied() {
let two_lines = "Shh. Be very, very quiet. I'm hunting rabbits.
(laughs) Oh boy, rabbit tracks.";
let result = get_fudd(&two_lines);
assert_eq!(
result,
"Shh. Be vewy, vewy qwiet. I'm hunting wabbits.\n(waughs) Oh boy, wabbit twacks."
);
}
}
|
use crate::schema::atendimentos;
use chrono::{NaiveDateTime, NaiveTime};
#[derive(Serialize, Deserialize, Queryable)]
pub struct Atendimentos {
pub id: i32,
pub id_professor: i32,
pub dia: String,
pub hora_inicio: NaiveTime,
pub hora_fim: NaiveTime,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
}
#[derive(Deserialize, Insertable)]
#[table_name = "atendimentos"]
pub struct InsertableAtendimento {
pub id_professor: i32,
pub dia: String,
pub hora_inicio: NaiveTime,
pub hora_fim: NaiveTime,
}
/*
atendimentos (id) {
id -> Integer,
id_professor -> Integer,
dia -> Varchar,
hora_inicio -> Time,
hora_fim -> Time,
created_at -> Datetime,
updated_at -> Datetime,
}
*/
|
use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
use clippy_utils::is_lint_allowed;
use clippy_utils::source::{indent_of, reindent_multiline, snippet};
use rustc_errors::Applicability;
use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use rustc_hir::{Block, BlockCheckMode, Expr, ExprKind, HirId, Local, UnsafeSource};
use rustc_lexer::TokenKind;
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_middle::lint::in_external_macro;
use rustc_middle::ty::TyCtxt;
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::{BytePos, Span};
use std::borrow::Cow;
declare_clippy_lint! {
/// ### What it does
/// Checks for `unsafe` blocks without a `// Safety: ` comment
/// explaining why the unsafe operations performed inside
/// the block are safe.
///
/// ### Why is this bad?
/// Undocumented unsafe blocks can make it difficult to
/// read and maintain code, as well as uncover unsoundness
/// and bugs.
///
/// ### Example
/// ```rust
/// use std::ptr::NonNull;
/// let a = &mut 42;
///
/// let ptr = unsafe { NonNull::new_unchecked(a) };
/// ```
/// Use instead:
/// ```rust
/// use std::ptr::NonNull;
/// let a = &mut 42;
///
/// // Safety: references are guaranteed to be non-null.
/// let ptr = unsafe { NonNull::new_unchecked(a) };
/// ```
#[clippy::version = "1.58.0"]
pub UNDOCUMENTED_UNSAFE_BLOCKS,
restriction,
"creating an unsafe block without explaining why it is safe"
}
impl_lint_pass!(UndocumentedUnsafeBlocks => [UNDOCUMENTED_UNSAFE_BLOCKS]);
#[derive(Default)]
pub struct UndocumentedUnsafeBlocks {
pub local_level: u32,
pub local_span: Option<Span>,
// The local was already checked for an overall safety comment
// There is no need to continue checking the blocks in the local
pub local_checked: bool,
// Since we can only check the blocks from expanded macros
// We have to omit the suggestion due to the actual definition
// Not being available to us
pub macro_expansion: bool,
}
impl LateLintPass<'_> for UndocumentedUnsafeBlocks {
fn check_block(&mut self, cx: &LateContext<'_>, block: &'_ Block<'_>) {
if_chain! {
if !self.local_checked;
if !is_lint_allowed(cx, UNDOCUMENTED_UNSAFE_BLOCKS, block.hir_id);
if !in_external_macro(cx.tcx.sess, block.span);
if let BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) = block.rules;
if let Some(enclosing_scope_hir_id) = cx.tcx.hir().get_enclosing_scope(block.hir_id);
if self.block_has_safety_comment(cx.tcx, enclosing_scope_hir_id, block.span) == Some(false);
then {
let mut span = block.span;
if let Some(local_span) = self.local_span {
span = local_span;
let result = self.block_has_safety_comment(cx.tcx, enclosing_scope_hir_id, span);
if result.unwrap_or(true) {
self.local_checked = true;
return;
}
}
self.lint(cx, span);
}
}
}
fn check_local(&mut self, cx: &LateContext<'_>, local: &'_ Local<'_>) {
if_chain! {
if !is_lint_allowed(cx, UNDOCUMENTED_UNSAFE_BLOCKS, local.hir_id);
if !in_external_macro(cx.tcx.sess, local.span);
if let Some(init) = local.init;
then {
self.visit_expr(init);
if self.local_level > 0 {
self.local_span = Some(local.span);
}
}
}
}
fn check_block_post(&mut self, _: &LateContext<'_>, _: &'_ Block<'_>) {
self.local_level = self.local_level.saturating_sub(1);
if self.local_level == 0 {
self.local_checked = false;
self.local_span = None;
}
}
}
impl<'hir> Visitor<'hir> for UndocumentedUnsafeBlocks {
type Map = Map<'hir>;
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::None
}
fn visit_expr(&mut self, ex: &'v Expr<'v>) {
match ex.kind {
ExprKind::Block(_, _) => self.local_level = self.local_level.saturating_add(1),
_ => walk_expr(self, ex),
}
}
}
impl UndocumentedUnsafeBlocks {
fn block_has_safety_comment(&mut self, tcx: TyCtxt<'_>, enclosing_hir_id: HirId, block_span: Span) -> Option<bool> {
let map = tcx.hir();
let source_map = tcx.sess.source_map();
let enclosing_scope_span = map.opt_span(enclosing_hir_id)?;
let between_span = if block_span.from_expansion() {
self.macro_expansion = true;
enclosing_scope_span.with_hi(block_span.hi())
} else {
self.macro_expansion = false;
enclosing_scope_span.to(block_span)
};
let file_name = source_map.span_to_filename(between_span);
let source_file = source_map.get_source_file(&file_name)?;
let lex_start = (between_span.lo().0 - source_file.start_pos.0 + 1) as usize;
let lex_end = (between_span.hi().0 - source_file.start_pos.0) as usize;
let src_str = source_file.src.as_ref()?[lex_start..lex_end].to_string();
let source_start_pos = source_file.start_pos.0 as usize + lex_start;
let mut pos = 0;
let mut comment = false;
for token in rustc_lexer::tokenize(&src_str) {
match token.kind {
TokenKind::LineComment { doc_style: None }
| TokenKind::BlockComment {
doc_style: None,
terminated: true,
} => {
let comment_str = src_str[pos + 2..pos + token.len].to_ascii_uppercase();
if comment_str.contains("SAFETY:") {
comment = true;
}
},
// We need to add all whitespace to `pos` before checking the comment's line number
TokenKind::Whitespace => {},
_ => {
if comment {
// Get the line number of the "comment" (really wherever the trailing whitespace ended)
let comment_line_num = source_file
.lookup_file_pos(BytePos((source_start_pos + pos).try_into().unwrap()))
.0;
// Find the block/local's line number
let block_line_num = tcx.sess.source_map().lookup_char_pos(block_span.lo()).line;
// Check the comment is immediately followed by the block/local
if block_line_num == comment_line_num + 1 || block_line_num == comment_line_num {
return Some(true);
}
comment = false;
}
},
}
pos += token.len;
}
Some(false)
}
fn lint(&self, cx: &LateContext<'_>, mut span: Span) {
let source_map = cx.tcx.sess.source_map();
if source_map.is_multiline(span) {
span = source_map.span_until_char(span, '\n');
}
if self.macro_expansion {
span_lint_and_help(
cx,
UNDOCUMENTED_UNSAFE_BLOCKS,
span,
"unsafe block in macro expansion missing a safety comment",
None,
"consider adding a safety comment in the macro definition",
);
} else {
let block_indent = indent_of(cx, span);
let suggestion = format!("// Safety: ...\n{}", snippet(cx, span, ".."));
span_lint_and_sugg(
cx,
UNDOCUMENTED_UNSAFE_BLOCKS,
span,
"unsafe block missing a safety comment",
"consider adding a safety comment",
reindent_multiline(Cow::Borrowed(&suggestion), true, block_indent).to_string(),
Applicability::HasPlaceholders,
);
}
}
}
|
mod args;
mod dependencies;
mod irust;
mod utils;
use crate::irust::IRust;
use crate::{
args::{handle_args, ArgsResult},
irust::options::Options,
};
use crossterm::{style::Stylize, tty::IsTty};
use dependencies::{check_required_deps, warn_about_opt_deps};
use irust_repl::CompileMode;
use std::process::exit;
fn main() {
let mut options = Options::new().unwrap_or_default();
// Handle args
let args: Vec<String> = std::env::args().skip(1).collect();
let args_result = if args.is_empty() {
ArgsResult::Proceed
} else {
handle_args(&args, &mut options)
};
// Exit if there is nothing more todo
if matches!(args_result, ArgsResult::Exit) {
exit(0)
}
// If no argument are provided, check stdin for some oneshot usage
if args.is_empty() {
let mut stdin = std::io::stdin();
if !stdin.is_tty() {
// Something was piped to stdin
// The users wants a oneshot evaluation
use irust_repl::{EvalConfig, EvalResult, Repl, DEFAULT_EVALUATOR};
use std::io::Read;
let mut repl = Repl::default();
match (|| -> irust::Result<EvalResult> {
let mut input = String::new();
stdin.read_to_string(&mut input)?;
let result = repl.eval_with_configuration(EvalConfig {
input,
interactive_function: None,
color: true,
evaluator: &*DEFAULT_EVALUATOR,
compile_mode: CompileMode::Debug,
})?;
Ok(result)
})() {
Ok(result) => {
if result.status.success() {
println!("{}", result.output);
} else {
println!(
"{}",
irust::format_err(&result.output, false, &repl.cargo.name)
);
}
exit(0)
}
Err(e) => {
eprintln!("failed to evaluate input, error: {e}");
exit(1)
}
}
}
}
// Check required dependencies and exit if they're not present
if !check_required_deps() {
exit(1);
}
// Create main IRust interface
let mut irust = if matches!(args_result, ArgsResult::ProceedWithDefaultConfig) {
let mut irust = IRust::new(Options::default());
irust.dont_save_options();
irust
} else {
// Check optional dependencies and warn if they're not present
warn_about_opt_deps(&mut options);
IRust::new(options)
};
// If a script path was provided try to load it
if let ArgsResult::ProceedWithScriptPath(script) = args_result {
// Ignore if it fails
let _ = irust.load_inner(script);
}
// Start IRust
let err = if let Err(e) = irust.run() {
Some(e)
} else {
None
};
// Now IRust has been dropped we can safely print to stderr
if let Some(err) = err {
eprintln!("{}", format!("\r\nIRust exited with error: {err}").red());
}
}
|
use gli;
pub trait Generator: gli::Generate {
type Object: gli::IntoObject<Self::Object>;
fn gen_one(&self) -> Self::Object {
debug!("gen, size = one");
let id = <Self as gli::Generate>::gl_gen(1)[0];
debug!("[{}]: generated", id);
<Self::Object as gli::IntoObject<Self::Object>>::new_object(id)
}
fn gen(&self, size: usize) -> Vec<Self::Object> {
debug!("gen, size = {}", size);
let ids = <Self as gli::Generate>::gl_gen(size);
debug!(
"[{}]: generated",
ids.iter()
.map(|id| id.to_string())
.collect::<Vec<String>>()
.connect(", ")
);
ids
.into_iter()
.map(|id| <Self::Object as gli::IntoObject<Self::Object>>::new_object(id) )
.collect()
}
}
|
use crate::group::*;
use crate::key::PublicKey;
use crate::keypackage::{self as kp, KeyPackage, MLS10_128_DHKEMP256_AES128GCM_SHA256_P256};
use crate::message::*;
use crate::utils::{decode_option, encode_option, encode_vec_u32, read_vec_u32};
use rustls::internal::msgs::codec::{self, Codec, Reader};
#[derive(Debug, Clone)]
/// spec: draft-ietf-mls-protocol.md#tree-hashes
pub struct ParentNode {
pub public_key: PublicKey,
// 0..2^32-1
pub unmerged_leaves: Vec<u32>,
// 0..255
pub parent_hash: Vec<u8>,
}
impl Codec for ParentNode {
fn encode(&self, bytes: &mut Vec<u8>) {
self.public_key.encode(bytes);
encode_vec_u32(bytes, &self.unmerged_leaves);
codec::encode_vec_u8(bytes, &self.parent_hash);
}
fn read(r: &mut Reader) -> Option<Self> {
let public_key = PublicKey::read(r)?;
let unmerged_leaves = read_vec_u32(r)?;
let parent_hash = codec::read_vec_u8(r)?;
Some(Self {
public_key,
unmerged_leaves,
parent_hash,
})
}
}
/// spec: draft-ietf-mls-protocol.md#tree-hashes
#[derive(Clone)]
pub enum Node {
Leaf(Option<KeyPackage>),
Parent(Option<ParentNode>),
}
impl Node {
pub fn is_leaf(&self) -> bool {
matches!(self, Node::Leaf(_))
}
pub fn is_empty_leaf(&self) -> bool {
matches!(self, Node::Leaf(None))
}
}
#[derive(Debug)]
/// spec: draft-ietf-mls-protocol.md#tree-hashes
pub struct ParentNodeHashInput {
pub node_index: u32,
pub parent_node: Option<ParentNode>,
pub left_hash: Vec<u8>,
pub right_hash: Vec<u8>,
}
impl Codec for ParentNodeHashInput {
fn encode(&self, bytes: &mut Vec<u8>) {
self.node_index.encode(bytes);
encode_option(bytes, &self.parent_node);
codec::encode_vec_u8(bytes, &self.left_hash);
codec::encode_vec_u8(bytes, &self.right_hash);
}
fn read(r: &mut Reader) -> Option<Self> {
let node_index = u32::read(r)?;
let parent_node: Option<ParentNode> = decode_option(r)?;
let left_hash = codec::read_vec_u8(r)?;
let right_hash = codec::read_vec_u8(r)?;
Some(Self {
node_index,
parent_node,
left_hash,
right_hash,
})
}
}
#[derive(Debug)]
/// spec: draft-ietf-mls-protocol.md#tree-hashes
pub struct LeafNodeHashInput {
pub node_index: u32,
pub key_package: Option<KeyPackage>,
}
impl Codec for LeafNodeHashInput {
fn encode(&self, bytes: &mut Vec<u8>) {
self.node_index.encode(bytes);
encode_option(bytes, &self.key_package);
}
fn read(r: &mut Reader) -> Option<Self> {
let node_index = u32::read(r)?;
let key_package: Option<KeyPackage> = decode_option(r)?;
Some(Self {
node_index,
key_package,
})
}
}
/// spec: draft-ietf-mls-protocol.md#tree-math
/// TODO: https://github.com/mlswg/mls-protocol/pull/327/files
#[derive(Clone)]
pub struct Tree {
/// all tree nodes stored in a vector
pub nodes: Vec<Node>,
/// the used ciphersuite (for hashing etc.)
/// TODO: unify with keypackage one
pub cs: CipherSuite,
/// position of the participant in the tree
/// TODO: leaf vs node position?
pub my_pos: usize,
}
/// The level of a node in the tree. Leaves are level 0, their
/// parents are level 1, etc. If a node's children are at different
/// level, then its level is the max level of its children plus one.
#[inline]
fn level(x: usize) -> usize {
if (x & 0x01) == 0 {
return 0;
}
let mut k = 0;
while ((x >> k) & 0x01) == 1 {
k += 1;
}
k
}
/// The number of nodes needed to represent a tree with n leaves
#[inline]
fn node_width(n: usize) -> usize {
2 * (n - 1) + 1
}
/// The left child of an intermediate node. Note that because the
/// tree is left-balanced, there is no dependency on the size of the
/// tree. The child of a leaf node is itself.
#[inline]
fn left(x: usize) -> usize {
let k = level(x);
if k == 0 {
return x;
}
x ^ (0x01 << (k - 1))
}
/// The right child of an intermediate node. Depends on the size of
/// the tree because the straightforward calculation can take you
/// beyond the edge of the tree. The child of a leaf node is itself.
#[inline]
fn right(x: usize, n: usize) -> usize {
let k = level(x);
if k == 0 {
return x;
}
let mut r = x ^ (0x03 << (k - 1));
while r >= node_width(n) {
r = left(r);
}
r
}
/// The index of the root node of a tree with n leaves
#[inline]
fn root(n: usize) -> usize {
let w = node_width(n);
(1usize << log2(w)) - 1
}
/// The largest power of 2 less than n. Equivalent to:
/// int(math.floor(math.log(x, 2)))
#[inline]
fn log2(x: usize) -> usize {
if x == 0 {
return 0;
}
let mut k = 0;
while (x >> k) > 0 {
k += 1
}
k - 1
}
/// The immediate parent of a node. May be beyond the right edge of
/// the tree.
#[inline]
fn parent_step(x: usize) -> usize {
let k = level(x);
let b = (x >> (k + 1)) & 0x01;
(x | (1 << k)) ^ (b << (k + 1))
}
/// The parent of a node. As with the right child calculation, have
/// to walk back until the parent is within the range of the tree.
#[inline]
fn parent(x: usize, n: usize) -> usize {
if x == root(n) {
return x;
}
let mut p = parent_step(x);
while p >= node_width(n) {
p = parent_step(p)
}
p
}
/// The direct path of a node, ordered from the root
/// down, including the root
#[inline]
fn direct_path(node_pos: usize, n: usize) -> Vec<usize> {
let mut d = Vec::new();
let mut p = parent(node_pos, n);
let r = root(n);
while p != r {
d.push(p);
p = parent(p, n);
}
if node_pos != r {
d.push(r);
}
d
}
impl Tree {
fn get_free_leaf_or_extend(&mut self) -> usize {
match self.nodes.iter().position(|n| n.is_empty_leaf()) {
Some(i) => i,
None => {
self.nodes.push(Node::Parent(None));
self.nodes.push(Node::Leaf(None));
self.nodes.len() - 1
}
}
}
pub fn update(
&mut self,
add_proposals: &[MLSPlaintext],
update_proposals: &[MLSPlaintext],
remove_proposals: &[MLSPlaintext],
) {
for _update in update_proposals.iter() {
// FIXME
}
for _remove in remove_proposals.iter() {
// FIXME
}
for add in add_proposals.iter() {
// position to add
// "If necessary, extend the tree to the right until it has at least index + 1 leaves"
let position = self.get_free_leaf_or_extend();
let leafs = self.leaf_len();
let dirpath = direct_path(position, leafs);
for d in dirpath.iter() {
let node = &mut self.nodes[*d];
if let Node::Parent(Some(ref mut np)) = node {
// "For each non-blank intermediate node along the
// path from the leaf at position index to the root,
// add index to the unmerged_leaves list for the node."
let du32 = *d as u32;
if !np.unmerged_leaves.contains(&du32) {
np.unmerged_leaves.push(du32);
}
}
}
// "Set the leaf node in the tree at position index to a new node containing the public key
// from the KeyPackage in the Add, as well as the credential under which the KeyPackage was signed"
let leaf_node = Node::Leaf(add.get_add_keypackage());
self.nodes[position] = leaf_node;
}
}
fn node_hash(&self, index: usize) -> Vec<u8> {
let node = &self.nodes[index];
match node {
Node::Leaf(kp) => {
let mut inp = Vec::new();
LeafNodeHashInput {
node_index: index as u32,
key_package: kp.clone(),
}
.encode(&mut inp);
self.cs.hash(&inp)
}
Node::Parent(pn) => {
let left_index = left(index);
let left_hash = self.node_hash(left_index);
let right_index = right(index, self.nodes.len());
let right_hash = self.node_hash(right_index);
let mut inp = Vec::new();
ParentNodeHashInput {
node_index: index as u32,
parent_node: pn.clone(),
left_hash,
right_hash,
}
.encode(&mut inp);
self.cs.hash(&inp)
}
}
}
fn leaf_len(&self) -> usize {
self.nodes.iter().filter(|n| n.is_leaf()).count()
}
pub fn compute_tree_hash(&self) -> Vec<u8> {
let root_index = root(self.leaf_len());
self.node_hash(root_index)
}
pub fn init(creator_kp: KeyPackage) -> Result<Self, kp::Error> {
let cs = match creator_kp.payload.cipher_suite {
MLS10_128_DHKEMP256_AES128GCM_SHA256_P256 => {
Ok(CipherSuite::MLS10_128_DHKEMP256_AES128GCM_SHA256_P256)
}
_ => Err(kp::Error::UnsupportedCipherSuite(
creator_kp.payload.cipher_suite,
)),
}?;
Ok(Self {
nodes: vec![Node::Leaf(Some(creator_kp))],
cs,
my_pos: 0,
})
}
}
#[cfg(test)]
mod test {
#[test]
fn test_tree_math() {
use super::{direct_path, left, level, log2, parent, right, root};
// Precomputed answers for the tree on eleven elements
// adapted from https://github.com/cisco/go-mls/blob/master/tree-math_test.go
let a_root = vec![
0x00, 0x01, 0x03, 0x03, 0x07, 0x07, 0x07, 0x07, 0x0f, 0x0f, 0x0f,
];
let a_log2 = vec![
0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04,
];
let a_level = vec![
0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x01,
0x00, 0x04, 0x00, 0x01, 0x00, 0x02, 0x00,
];
let a_left = vec![
0x00, 0x00, 0x02, 0x01, 0x04, 0x04, 0x06, 0x03, 0x08, 0x08, 0x0a, 0x09, 0x0c, 0x0c,
0x0e, 0x07, 0x10, 0x10, 0x12, 0x11, 0x14,
];
let a_right = vec![
0x00, 0x02, 0x02, 0x05, 0x04, 0x06, 0x06, 0x0b, 0x08, 0x0a, 0x0a, 0x0d, 0x0c, 0x0e,
0x0e, 0x13, 0x10, 0x12, 0x12, 0x14, 0x14,
];
let a_parent = vec![
0x01, 0x03, 0x01, 0x07, 0x05, 0x03, 0x05, 0x0f, 0x09, 0x0b, 0x09, 0x07, 0x0d, 0x0b,
0x0d, 0x0f, 0x11, 0x13, 0x11, 0x0f, 0x13,
];
let a_dirpath = [
vec![0x01, 0x03, 0x07, 0x0f],
vec![0x03, 0x07, 0x0f],
vec![0x01, 0x03, 0x07, 0x0f],
vec![0x07, 0x0f],
vec![0x05, 0x03, 0x07, 0x0f],
vec![0x03, 0x07, 0x0f],
vec![0x05, 0x03, 0x07, 0x0f],
vec![0x0f],
vec![0x09, 0x0b, 0x07, 0x0f],
vec![0x0b, 0x07, 0x0f],
vec![0x09, 0x0b, 0x07, 0x0f],
vec![0x07, 0x0f],
vec![0x0d, 0x0b, 0x07, 0x0f],
vec![0x0b, 0x07, 0x0f],
vec![0x0d, 0x0b, 0x07, 0x0f],
vec![],
vec![0x11, 0x13, 0x0f],
vec![0x13, 0x0f],
vec![0x11, 0x13, 0x0f],
vec![0x0f],
vec![0x13, 0x0f],
];
let a_n = 0x0b;
for n in 1..a_n {
assert_eq!(root(n), a_root[n - 1])
}
for i in 0x00..0x14 {
assert_eq!(a_log2[i], log2(i));
assert_eq!(a_level[i], level(i));
assert_eq!(a_left[i], left(i));
assert_eq!(a_right[i], right(i, a_n));
assert_eq!(a_parent[i], parent(i, a_n));
assert_eq!(a_dirpath[i], direct_path(i, a_n));
}
}
}
|
use super::io::*;
#[test]
fn can_inject_answer_to_prompt_into_test_io() {
let question = "some question".to_string();
let io = TestIo::new("answer".to_string());
assert_eq!("answer", io.prompt(question).as_slice());
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::Range;
use common_arrow::arrow::buffer::Buffer;
use common_exception::ErrorCode;
use common_exception::Result;
use enum_as_inner::EnumAsInner;
use ethnum::i256;
use itertools::Itertools;
use num_traits::ToPrimitive;
use serde::Deserialize;
use serde::Serialize;
use super::SimpleDomain;
use crate::types::ArgType;
use crate::types::DataType;
use crate::types::GenericMap;
use crate::types::ValueType;
use crate::utils::arrow::buffer_into_mut;
use crate::Column;
use crate::ColumnBuilder;
use crate::Domain;
use crate::Scalar;
use crate::ScalarRef;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecimalType<T: Decimal>(PhantomData<T>);
pub type Decimal128Type = DecimalType<i128>;
pub type Decimal256Type = DecimalType<i256>;
impl<Num: Decimal> ValueType for DecimalType<Num> {
type Scalar = Num;
type ScalarRef<'a> = Num;
type Column = Buffer<Num>;
type Domain = SimpleDomain<Num>;
type ColumnIterator<'a> = std::iter::Cloned<std::slice::Iter<'a, Num>>;
type ColumnBuilder = Vec<Num>;
fn upcast_gat<'short, 'long: 'short>(long: Self::ScalarRef<'long>) -> Self::ScalarRef<'short> {
long
}
fn to_owned_scalar<'a>(scalar: Self::ScalarRef<'a>) -> Self::Scalar {
scalar
}
fn to_scalar_ref<'a>(scalar: &'a Self::Scalar) -> Self::ScalarRef<'a> {
*scalar
}
fn try_downcast_scalar<'a>(scalar: &'a ScalarRef) -> Option<Self::ScalarRef<'a>> {
Num::try_downcast_scalar(scalar.as_decimal()?)
}
fn try_downcast_column<'a>(col: &'a Column) -> Option<Self::Column> {
let down_col = Num::try_downcast_column(col);
if let Some(col) = down_col {
Some(col.0)
} else {
None
}
}
fn try_downcast_domain(domain: &Domain) -> Option<Self::Domain> {
Num::try_downcast_domain(domain.as_decimal()?)
}
fn try_downcast_builder<'a>(
builder: &'a mut ColumnBuilder,
) -> Option<&'a mut Self::ColumnBuilder> {
Num::try_downcast_builder(builder)
}
fn upcast_scalar(scalar: Self::Scalar) -> Scalar {
Num::upcast_scalar(scalar, Num::default_decimal_size())
}
fn upcast_column(col: Self::Column) -> Column {
Num::upcast_column(col, Num::default_decimal_size())
}
fn upcast_domain(domain: Self::Domain) -> Domain {
Num::upcast_domain(domain, Num::default_decimal_size())
}
fn column_len<'a>(col: &'a Self::Column) -> usize {
col.len()
}
fn index_column<'a>(col: &'a Self::Column, index: usize) -> Option<Self::ScalarRef<'a>> {
col.get(index).cloned()
}
unsafe fn index_column_unchecked<'a>(
col: &'a Self::Column,
index: usize,
) -> Self::ScalarRef<'a> {
*col.get_unchecked(index)
}
fn slice_column<'a>(col: &'a Self::Column, range: Range<usize>) -> Self::Column {
col.clone().sliced(range.start, range.end - range.start)
}
fn iter_column<'a>(col: &'a Self::Column) -> Self::ColumnIterator<'a> {
col.iter().cloned()
}
fn column_to_builder(col: Self::Column) -> Self::ColumnBuilder {
buffer_into_mut(col)
}
fn builder_len(builder: &Self::ColumnBuilder) -> usize {
builder.len()
}
fn push_item(builder: &mut Self::ColumnBuilder, item: Self::ScalarRef<'_>) {
builder.push(item)
}
fn push_default(builder: &mut Self::ColumnBuilder) {
builder.push(Num::default())
}
fn append_column(builder: &mut Self::ColumnBuilder, other: &Self::Column) {
builder.extend_from_slice(other);
}
fn build_column(builder: Self::ColumnBuilder) -> Self::Column {
builder.into()
}
fn build_scalar(builder: Self::ColumnBuilder) -> Self::Scalar {
assert_eq!(builder.len(), 1);
builder[0]
}
}
impl<Num: Decimal> ArgType for DecimalType<Num> {
fn data_type() -> DataType {
Num::data_type()
}
fn full_domain() -> Self::Domain {
SimpleDomain {
min: Num::MIN,
max: Num::MAX,
}
}
fn create_builder(capacity: usize, _generics: &GenericMap) -> Self::ColumnBuilder {
Vec::with_capacity(capacity)
}
fn column_from_vec(vec: Vec<Self::Scalar>, _generics: &GenericMap) -> Self::Column {
vec.into()
}
fn column_from_iter(iter: impl Iterator<Item = Self::Scalar>, _: &GenericMap) -> Self::Column {
iter.collect()
}
fn column_from_ref_iter<'a>(
iter: impl Iterator<Item = Self::ScalarRef<'a>>,
_: &GenericMap,
) -> Self::Column {
iter.collect()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, EnumAsInner)]
pub enum DecimalDataType {
Decimal128(DecimalSize),
Decimal256(DecimalSize),
}
#[derive(Clone, Copy, PartialEq, Eq, EnumAsInner, Serialize, Deserialize)]
pub enum DecimalScalar {
Decimal128(i128, DecimalSize),
Decimal256(i256, DecimalSize),
}
impl DecimalScalar {
pub fn to_float64(&self) -> f64 {
match self {
DecimalScalar::Decimal128(v, size) => i128::to_float64(*v, size.scale),
DecimalScalar::Decimal256(v, size) => i256::to_float64(*v, size.scale),
}
}
}
#[derive(Clone, PartialEq, EnumAsInner)]
pub enum DecimalColumn {
Decimal128(Buffer<i128>, DecimalSize),
Decimal256(Buffer<i256>, DecimalSize),
}
#[derive(Debug, Clone, PartialEq, Eq, EnumAsInner)]
pub enum DecimalColumnBuilder {
Decimal128(Vec<i128>, DecimalSize),
Decimal256(Vec<i256>, DecimalSize),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumAsInner)]
pub enum DecimalDomain {
Decimal128(SimpleDomain<i128>, DecimalSize),
Decimal256(SimpleDomain<i256>, DecimalSize),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct DecimalSize {
pub precision: u8,
pub scale: u8,
}
pub trait Decimal:
Sized
+ Default
+ Debug
+ std::fmt::Display
+ Copy
+ Clone
+ PartialEq
+ Eq
+ PartialOrd
+ Ord
+ Sync
+ Send
+ 'static
{
fn zero() -> Self;
fn one() -> Self;
fn minus_one() -> Self;
// 10**scale
fn e(n: u32) -> Self;
fn mem_size() -> usize;
fn checked_add(self, rhs: Self) -> Option<Self>;
fn checked_sub(self, rhs: Self) -> Option<Self>;
fn checked_div(self, rhs: Self) -> Option<Self>;
fn checked_mul(self, rhs: Self) -> Option<Self>;
fn max_of_max_precision() -> Self;
fn min_for_precision(precision: u8) -> Self;
fn max_for_precision(precision: u8) -> Self;
fn default_decimal_size() -> DecimalSize;
fn from_float(value: f64) -> Self;
fn from_u64(value: u64) -> Self;
fn from_i64(value: i64) -> Self;
fn de_binary(bytes: &mut &[u8]) -> Self;
fn to_float64(self, scale: u8) -> f64;
fn try_downcast_column(column: &Column) -> Option<(Buffer<Self>, DecimalSize)>;
fn try_downcast_builder<'a>(builder: &'a mut ColumnBuilder) -> Option<&'a mut Vec<Self>>;
fn try_downcast_scalar(scalar: &DecimalScalar) -> Option<Self>;
fn try_downcast_domain(domain: &DecimalDomain) -> Option<SimpleDomain<Self>>;
fn upcast_scalar(scalar: Self, size: DecimalSize) -> Scalar;
fn upcast_column(col: Buffer<Self>, size: DecimalSize) -> Column;
fn upcast_domain(domain: SimpleDomain<Self>, size: DecimalSize) -> Domain;
fn data_type() -> DataType;
const MIN: Self;
const MAX: Self;
fn to_column_from_buffer(value: Buffer<Self>, size: DecimalSize) -> DecimalColumn;
fn to_column(value: Vec<Self>, size: DecimalSize) -> DecimalColumn {
Self::to_column_from_buffer(value.into(), size)
}
fn to_scalar(self, size: DecimalSize) -> DecimalScalar;
fn with_size(&self, size: DecimalSize) -> Option<Self> {
let multiplier = Self::e(size.scale as u32);
let min_for_precision = Self::min_for_precision(size.precision);
let max_for_precision = Self::max_for_precision(size.precision);
self.checked_mul(multiplier).and_then(|v| {
if v > max_for_precision || v < min_for_precision {
None
} else {
Some(v)
}
})
}
}
impl Decimal for i128 {
fn zero() -> Self {
0_i128
}
fn one() -> Self {
1_i128
}
fn minus_one() -> Self {
-1_i128
}
fn e(n: u32) -> Self {
10_i128.pow(n)
}
fn mem_size() -> usize {
16
}
fn checked_add(self, rhs: Self) -> Option<Self> {
self.checked_add(rhs)
}
fn checked_sub(self, rhs: Self) -> Option<Self> {
self.checked_sub(rhs)
}
fn checked_div(self, rhs: Self) -> Option<Self> {
self.checked_div(rhs)
}
fn checked_mul(self, rhs: Self) -> Option<Self> {
self.checked_mul(rhs)
}
fn max_of_max_precision() -> Self {
Self::max_for_precision(MAX_DECIMAL128_PRECISION)
}
fn min_for_precision(to_precision: u8) -> Self {
9_i128
.saturating_pow(1 + to_precision as u32)
.saturating_neg()
}
fn max_for_precision(to_precision: u8) -> Self {
9_i128.saturating_pow(1 + to_precision as u32)
}
fn default_decimal_size() -> DecimalSize {
DecimalSize {
precision: MAX_DECIMAL128_PRECISION,
scale: 0,
}
}
fn to_column_from_buffer(value: Buffer<Self>, size: DecimalSize) -> DecimalColumn {
DecimalColumn::Decimal128(value, size)
}
fn from_float(value: f64) -> Self {
value.to_i128().unwrap()
}
fn from_u64(value: u64) -> Self {
value.to_i128().unwrap()
}
fn from_i64(value: i64) -> Self {
value.to_i128().unwrap()
}
fn de_binary(bytes: &mut &[u8]) -> Self {
let bs: [u8; std::mem::size_of::<Self>()] =
bytes[0..std::mem::size_of::<Self>()].try_into().unwrap();
*bytes = &bytes[std::mem::size_of::<Self>()..];
i128::from_le_bytes(bs)
}
fn to_float64(self, scale: u8) -> f64 {
let div = 10_f64.powi(scale as i32);
self as f64 / div
}
fn to_scalar(self, size: DecimalSize) -> DecimalScalar {
DecimalScalar::Decimal128(self, size)
}
fn try_downcast_column(column: &Column) -> Option<(Buffer<Self>, DecimalSize)> {
let column = column.as_decimal()?;
match column {
DecimalColumn::Decimal128(c, size) => Some((c.clone(), *size)),
DecimalColumn::Decimal256(_, _) => None,
}
}
fn try_downcast_builder<'a>(builder: &'a mut ColumnBuilder) -> Option<&'a mut Vec<Self>> {
match builder {
ColumnBuilder::Decimal(DecimalColumnBuilder::Decimal128(s, _)) => Some(s),
_ => None,
}
}
fn try_downcast_scalar<'a>(scalar: &DecimalScalar) -> Option<Self> {
match scalar {
DecimalScalar::Decimal128(val, _) => Some(*val),
_ => None,
}
}
fn try_downcast_domain(domain: &DecimalDomain) -> Option<SimpleDomain<Self>> {
match domain {
DecimalDomain::Decimal128(val, _) => Some(*val),
_ => None,
}
}
// will mock DecimalSize need modify when use it
fn upcast_scalar(scalar: Self, size: DecimalSize) -> Scalar {
Scalar::Decimal(DecimalScalar::Decimal128(scalar, size))
}
fn upcast_column(col: Buffer<Self>, size: DecimalSize) -> Column {
Column::Decimal(DecimalColumn::Decimal128(col, size))
}
fn upcast_domain(domain: SimpleDomain<Self>, size: DecimalSize) -> Domain {
Domain::Decimal(DecimalDomain::Decimal128(domain, size))
}
fn data_type() -> DataType {
DataType::Decimal(DecimalDataType::Decimal128(DecimalSize {
precision: MAX_DECIMAL128_PRECISION,
scale: 0,
}))
}
const MIN: i128 = -99999999999999999999999999999999999999i128;
const MAX: i128 = 99999999999999999999999999999999999999i128;
}
impl Decimal for i256 {
fn zero() -> Self {
i256::ZERO
}
fn one() -> Self {
i256::ONE
}
fn minus_one() -> Self {
i256::MINUS_ONE
}
fn e(n: u32) -> Self {
(i256::ONE * 10).pow(n)
}
fn mem_size() -> usize {
32
}
fn checked_add(self, rhs: Self) -> Option<Self> {
self.checked_add(rhs)
}
fn checked_sub(self, rhs: Self) -> Option<Self> {
self.checked_sub(rhs)
}
fn checked_div(self, rhs: Self) -> Option<Self> {
self.checked_div(rhs)
}
fn checked_mul(self, rhs: Self) -> Option<Self> {
self.checked_mul(rhs)
}
fn max_of_max_precision() -> Self {
Self::max_for_precision(MAX_DECIMAL256_PRECISION)
}
fn min_for_precision(to_precision: u8) -> Self {
(i256::ONE * 9)
.saturating_pow(1 + to_precision as u32)
.saturating_neg()
}
fn max_for_precision(to_precision: u8) -> Self {
(i256::ONE * 9).saturating_pow(1 + to_precision as u32)
}
fn default_decimal_size() -> DecimalSize {
DecimalSize {
precision: MAX_DECIMAL256_PRECISION,
scale: 0,
}
}
fn from_float(value: f64) -> Self {
i256::from(value.to_i128().unwrap())
}
fn from_u64(value: u64) -> Self {
i256::from(value.to_i128().unwrap())
}
fn from_i64(value: i64) -> Self {
i256::from(value.to_i128().unwrap())
}
fn de_binary(bytes: &mut &[u8]) -> Self {
let bs: [u8; std::mem::size_of::<Self>()] =
bytes[0..std::mem::size_of::<Self>()].try_into().unwrap();
*bytes = &bytes[std::mem::size_of::<Self>()..];
i256::from_le_bytes(bs)
}
fn to_float64(self, scale: u8) -> f64 {
let div = 10_f64.powi(scale as i32);
self.as_f64() / div
}
fn to_scalar(self, size: DecimalSize) -> DecimalScalar {
DecimalScalar::Decimal256(self, size)
}
fn try_downcast_column(column: &Column) -> Option<(Buffer<Self>, DecimalSize)> {
let column = column.as_decimal()?;
match column {
DecimalColumn::Decimal256(c, size) => Some((c.clone(), *size)),
_ => None,
}
}
fn try_downcast_builder<'a>(builder: &'a mut ColumnBuilder) -> Option<&'a mut Vec<Self>> {
match builder {
ColumnBuilder::Decimal(DecimalColumnBuilder::Decimal256(s, _)) => Some(s),
_ => None,
}
}
fn try_downcast_scalar<'a>(scalar: &DecimalScalar) -> Option<Self> {
match scalar {
DecimalScalar::Decimal256(val, _) => Some(*val),
_ => None,
}
}
fn try_downcast_domain(domain: &DecimalDomain) -> Option<SimpleDomain<Self>> {
match domain {
DecimalDomain::Decimal256(val, _) => Some(*val),
_ => None,
}
}
fn upcast_scalar(scalar: Self, size: DecimalSize) -> Scalar {
Scalar::Decimal(DecimalScalar::Decimal256(scalar, size))
}
fn upcast_column(col: Buffer<Self>, size: DecimalSize) -> Column {
Column::Decimal(DecimalColumn::Decimal256(col, size))
}
fn upcast_domain(domain: SimpleDomain<Self>, size: DecimalSize) -> Domain {
Domain::Decimal(DecimalDomain::Decimal256(domain, size))
}
fn data_type() -> DataType {
DataType::Decimal(DecimalDataType::Decimal256(DecimalSize {
precision: MAX_DECIMAL256_PRECISION,
scale: 0,
}))
}
const MIN: i256 = ethnum::int!(
"-9999999999999999999999999999999999999999999999999999999999999999999999999999"
);
const MAX: i256 = ethnum::int!(
"9999999999999999999999999999999999999999999999999999999999999999999999999999"
);
fn to_column_from_buffer(value: Buffer<Self>, size: DecimalSize) -> DecimalColumn {
DecimalColumn::Decimal256(value, size)
}
}
pub static MAX_DECIMAL128_PRECISION: u8 = 38;
pub static MAX_DECIMAL256_PRECISION: u8 = 76;
impl DecimalDataType {
pub fn from_size(size: DecimalSize) -> Result<DecimalDataType> {
if size.precision < 1 || size.precision > MAX_DECIMAL256_PRECISION {
return Err(ErrorCode::Overflow(format!(
"Decimal precision must be between 1 and {}",
MAX_DECIMAL256_PRECISION
)));
}
if size.scale > size.precision {
return Err(ErrorCode::Overflow(format!(
"Decimal scale must be between 0 and precision {}",
size.precision
)));
}
if size.precision <= MAX_DECIMAL128_PRECISION {
Ok(DecimalDataType::Decimal128(size))
} else {
Ok(DecimalDataType::Decimal256(size))
}
}
pub fn default_scalar(&self) -> DecimalScalar {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalDataType::DECIMAL_TYPE(size) => DecimalScalar::DECIMAL_TYPE(0.into(), *size),
})
}
pub fn size(&self) -> DecimalSize {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalDataType::DECIMAL_TYPE(size) => *size,
})
}
pub fn scale(&self) -> u8 {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalDataType::DECIMAL_TYPE(size) => size.scale,
})
}
pub fn precision(&self) -> u8 {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalDataType::DECIMAL_TYPE(size) => size.precision,
})
}
pub fn leading_digits(&self) -> u8 {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalDataType::DECIMAL_TYPE(size) => size.precision - size.scale,
})
}
pub fn max_precision(&self) -> u8 {
match self {
DecimalDataType::Decimal128(_) => MAX_DECIMAL128_PRECISION,
DecimalDataType::Decimal256(_) => MAX_DECIMAL256_PRECISION,
}
}
pub fn max_result_precision(&self, other: &Self) -> u8 {
if matches!(other, DecimalDataType::Decimal128(_)) {
return self.max_precision();
}
other.max_precision()
}
pub fn binary_result_type(
a: &Self,
b: &Self,
is_multiply: bool,
is_divide: bool,
is_plus_minus: bool,
) -> Result<Self> {
let mut scale = a.scale().max(b.scale());
let mut precision = a.max_result_precision(b);
let multiply_precision = a.precision() + b.precision();
let divide_precision = a.precision() + b.scale();
if is_multiply {
scale = a.scale() + b.scale();
precision = precision.min(multiply_precision);
} else if is_divide {
scale = a.scale();
precision = precision.min(divide_precision);
} else if is_plus_minus {
scale = std::cmp::max(a.scale(), b.scale());
// for addition/subtraction, we add 1 to the width to ensure we don't overflow
let plus_min_precision = a.leading_digits().max(b.leading_digits()) + scale + 1;
precision = precision.min(plus_min_precision);
}
Self::from_size(DecimalSize { precision, scale })
}
// Decimal X Number or Nunmber X Decimal
pub fn binary_upgrade_to_max_precision(&self) -> Result<DecimalDataType> {
let scale = self.scale();
let precision = self.max_precision();
Self::from_size(DecimalSize { precision, scale })
}
}
impl DecimalScalar {
pub fn domain(&self) -> DecimalDomain {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalScalar::DECIMAL_TYPE(num, size) => DecimalDomain::DECIMAL_TYPE(
SimpleDomain {
min: *num,
max: *num,
},
*size
),
})
}
}
impl DecimalColumn {
pub fn len(&self) -> usize {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalColumn::DECIMAL_TYPE(col, _) => col.len(),
})
}
pub fn index(&self, index: usize) -> Option<DecimalScalar> {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalColumn::DECIMAL_TYPE(col, size) =>
Some(DecimalScalar::DECIMAL_TYPE(col.get(index).cloned()?, *size)),
})
}
/// # Safety
///
/// Calling this method with an out-of-bounds index is *[undefined behavior]*
pub unsafe fn index_unchecked(&self, index: usize) -> DecimalScalar {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalColumn::DECIMAL_TYPE(col, size) =>
DecimalScalar::DECIMAL_TYPE(*col.get_unchecked(index), *size),
})
}
pub fn slice(&self, range: Range<usize>) -> Self {
assert!(
range.end <= self.len(),
"range {:?} out of len {}",
range,
self.len()
);
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalColumn::DECIMAL_TYPE(col, size) => {
DecimalColumn::DECIMAL_TYPE(
col.clone().sliced(range.start, range.end - range.start),
*size,
)
}
})
}
pub fn domain(&self) -> DecimalDomain {
assert!(self.len() > 0);
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalColumn::DECIMAL_TYPE(col, size) => {
let (min, max) = col.iter().minmax().into_option().unwrap();
DecimalDomain::DECIMAL_TYPE(
SimpleDomain {
min: *min,
max: *max,
},
*size,
)
}
})
}
}
impl DecimalColumnBuilder {
pub fn from_column(col: DecimalColumn) -> Self {
crate::with_decimal_type!(|DECIMAL_TYPE| match col {
DecimalColumn::DECIMAL_TYPE(col, size) =>
DecimalColumnBuilder::DECIMAL_TYPE(buffer_into_mut(col), size),
})
}
pub fn repeat(scalar: DecimalScalar, n: usize) -> DecimalColumnBuilder {
crate::with_decimal_type!(|DECIMAL_TYPE| match scalar {
DecimalScalar::DECIMAL_TYPE(num, size) =>
DecimalColumnBuilder::DECIMAL_TYPE(vec![num; n], size),
})
}
pub fn len(&self) -> usize {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalColumnBuilder::DECIMAL_TYPE(col, _) => col.len(),
})
}
pub fn with_capacity(ty: &DecimalDataType, capacity: usize) -> Self {
crate::with_decimal_type!(|DECIMAL_TYPE| match ty {
DecimalDataType::DECIMAL_TYPE(size) =>
DecimalColumnBuilder::DECIMAL_TYPE(Vec::with_capacity(capacity), *size),
})
}
pub fn push(&mut self, item: DecimalScalar) {
crate::with_decimal_type!(|DECIMAL_TYPE| match (self, item) {
(
DecimalColumnBuilder::DECIMAL_TYPE(builder, builder_size),
DecimalScalar::DECIMAL_TYPE(value, value_size),
) => {
debug_assert_eq!(*builder_size, value_size);
builder.push(value)
}
(builder, scalar) => unreachable!("unable to push {scalar:?} to {builder:?}"),
})
}
pub fn push_default(&mut self) {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalColumnBuilder::DECIMAL_TYPE(builder, _) => builder.push(0.into()),
})
}
pub fn append_column(&mut self, other: &DecimalColumn) {
crate::with_decimal_type!(|DECIMAL_TYPE| match (self, other) {
(
DecimalColumnBuilder::DECIMAL_TYPE(builder, builder_size),
DecimalColumn::DECIMAL_TYPE(other, other_size),
) => {
debug_assert_eq!(builder_size, other_size);
builder.extend_from_slice(other);
}
(this, other) => unreachable!("unable append {other:?} onto {this:?}"),
})
}
pub fn build(self) -> DecimalColumn {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalColumnBuilder::DECIMAL_TYPE(builder, size) =>
DecimalColumn::DECIMAL_TYPE(builder.into(), size),
})
}
pub fn build_scalar(self) -> DecimalScalar {
assert_eq!(self.len(), 1);
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalColumnBuilder::DECIMAL_TYPE(builder, size) =>
DecimalScalar::DECIMAL_TYPE(builder[0], size),
})
}
pub fn pop(&mut self) -> Option<DecimalScalar> {
crate::with_decimal_type!(|DECIMAL_TYPE| match self {
DecimalColumnBuilder::DECIMAL_TYPE(builder, size) => {
builder
.pop()
.map(|num| DecimalScalar::DECIMAL_TYPE(num, *size))
}
})
}
}
impl PartialOrd for DecimalScalar {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
crate::with_decimal_type!(|DECIMAL_TYPE| match (self, other) {
(
DecimalScalar::DECIMAL_TYPE(lhs, lhs_size),
DecimalScalar::DECIMAL_TYPE(rhs, rhs_size),
) => {
if lhs_size == rhs_size {
lhs.partial_cmp(rhs)
} else {
None
}
}
_ => None,
})
}
}
impl PartialOrd for DecimalColumn {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
crate::with_decimal_type!(|DECIMAL_TYPE| match (self, other) {
(
DecimalColumn::DECIMAL_TYPE(lhs, lhs_size),
DecimalColumn::DECIMAL_TYPE(rhs, rhs_size),
) => {
if lhs_size == rhs_size {
lhs.iter().partial_cmp(rhs.iter())
} else {
None
}
}
_ => None,
})
}
}
#[macro_export]
macro_rules! with_decimal_type {
( | $t:tt | $($tail:tt)* ) => {
match_template::match_template! {
$t = [Decimal128, Decimal256],
$($tail)*
}
}
}
#[macro_export]
macro_rules! with_decimal_mapped_type {
(| $t:tt | $($tail:tt)*) => {
match_template::match_template! {
$t = [
Decimal128 => i128, Decimal256 => i256
],
$($tail)*
}
}
}
|
#[derive(Debug)]
pub struct Error {
inner: Option<Box<dyn std::error::Error>>,
desc: Option<&'static str>,
}
impl Error {
pub fn from_err(inner: Box<dyn std::error::Error>) -> Error {
Error { inner: Some(inner), desc: None }
}
pub fn from_str(s: &'static str) -> Error {
Error { inner: None, desc: Some(s) }
}
pub fn wrap<E: std::error::Error + 'static>(inner: E, desc: &'static str) -> Error {
Error {
inner: Some(Box::new(inner)),
desc: Some(desc),
}
}
}
impl<T: std::error::Error + 'static> std::convert::From<T> for Error {
fn from(e: T) -> Error {
Error::from_err(Box::new(e))
}
}
|
const DRAM_BASE: u64 = 0x80000000;
pub struct Memory {
data: Vec<u8>
}
impl Memory {
pub fn new() -> Self {
Memory {
data: vec![]
}
}
pub fn init(&mut self, capacity: u64) {
for _i in 0..capacity {
self.data.push(0);
}
}
pub fn read_byte(&self, address: u64) -> u8 {
if address < DRAM_BASE {
panic!("Wrong DRAM memory address {:X}", address);
}
self.data[(address - DRAM_BASE) as usize]
}
pub fn read_bytes(&self, address: u64, width: u64) -> u64 {
let mut data = 0 as u64;
for i in 0..width {
data |= (self.read_byte(address.wrapping_add(i)) as u64) << (i * 8);
}
data
}
pub fn write_byte(&mut self, address: u64, value: u8) {
if address < DRAM_BASE {
panic!("Wrong DRAM memory address {:X}", address);
}
self.data[(address - DRAM_BASE) as usize] = value;
}
pub fn write_bytes(&mut self, address: u64, value: u64, width: u64) {
for i in 0..width {
self.write_byte(address.wrapping_add(i), (value >> (i * 8)) as u8);
}
}
pub fn validate_address(&self, address: u64) -> bool {
if address < DRAM_BASE {
return false;
}
return ((address - DRAM_BASE) as usize) < self.data.len()
}
} |
use {Async, Future, IntoFuture, Poll};
use stream::Stream;
/// A stream combinator which executes a unit closure over each item on a
/// stream.
///
/// This structure is returned by the `Stream::for_each` method.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct ForEach<S, F, U> where U: IntoFuture {
stream: S,
f: F,
fut: Option<U::Future>,
}
pub fn new<S, F, U>(s: S, f: F) -> ForEach<S, F, U>
where S: Stream,
F: FnMut(S::Item) -> U,
U: IntoFuture<Item = (), Error = S::Error>,
{
ForEach {
stream: s,
f: f,
fut: None,
}
}
impl<S, F, U> Future for ForEach<S, F, U>
where S: Stream,
F: FnMut(S::Item) -> U,
U: IntoFuture<Item= (), Error = S::Error>,
{
type Item = ();
type Error = S::Error;
fn poll(&mut self) -> Poll<(), S::Error> {
loop {
if let Some(mut fut) = self.fut.take() {
if fut.poll()?.is_not_ready() {
self.fut = Some(fut);
return Ok(Async::NotReady);
}
}
match try_ready!(self.stream.poll()) {
Some(e) => self.fut = Some((self.f)(e).into_future()),
None => return Ok(Async::Ready(())),
}
}
}
}
|
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
fn main() {
let args: Vec<String> = env::args().collect();
let filename = &args[1];
let file = File::open(filename).expect("Could not read file");
let lines: Vec<String> = BufReader::new(file)
.lines()
.map(|line| line.expect("Line could not be read"))
.filter(|line| line.len() > 0)
.collect();
let input = lines
.iter()
.map(|line| {
let line = general_split(line, "@");
let i = general_split(line[0], "#")[1]
.parse::<usize>()
.expect("Not a number");
let relevent = general_split(line[1], ":");
let (x, y) = pair_split(relevent[0], ",");
let (w, h) = pair_split(relevent[1], "x");
(i, (x, y), (w, h))
}).collect();
println!("{}", part_one(&input));
println!("{}", part_two(&input));
}
fn part_one(lines: &Vec<(usize, (usize, usize), (usize, usize))>) -> usize {
let mut cloth = [[0; 1000]; 1000];
for (_, (x, y), (w, h)) in lines {
for col in (x + 1)..=(x + w) {
for row in (y + 1)..=(y + h) {
cloth[row][col] += 1;
}
}
}
return cloth.iter().fold(0, |sum, row| {
sum + row.iter().filter(|val| *val > &1).count()
});
}
fn general_split<'a>(string: &'a str, pivot: &str) -> Vec<&'a str> {
return string.split(pivot).map(|s| s.trim()).collect::<Vec<&str>>();
}
fn pair_split<'a>(string: &'a str, pivot: &str) -> (usize, usize) {
let ints = string
.split(pivot)
.map(|s| s.trim())
.map(|s| s.parse::<usize>().expect("Not a number"))
.collect::<Vec<usize>>();
return (ints[0], ints[1]);
}
fn part_two(lines: &Vec<(usize, (usize, usize), (usize, usize))>) -> usize {
let mut cloth = vec![vec![None; 1000]; 1000];
let mut valid = HashMap::new();
for (i, (x, y), (w, h)) in lines {
valid.insert(i, true);
for col in (x + 1)..=(x + w) {
for row in (y + 1)..=(y + h) {
match cloth[row][col] {
Some(o) => {
valid.insert(o, false);
valid.insert(i, false);
}
None => cloth[row][col] = Some(i),
}
}
}
}
return valid
.iter()
.filter(|(_, b)| **b)
.map(|(i, _)| **i)
.collect::<Vec<usize>>()[0];
}
|
use fontsource::BuiltinFont;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::{BufRead, BufReader, Result};
/// Relevant data that can be loaded from an AFM (Adobe Font Metrics) file. A
/// FontMetrics object is specific to a given encoding.
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub struct FontMetrics {
widths: BTreeMap<u8, u16>,
}
impl FontMetrics {
/// Create a FontMetrics by reading an .afm file.
pub fn parse(source: File) -> Result<FontMetrics> {
let source = BufReader::new(source);
let mut result = FontMetrics {
widths: BTreeMap::new(),
};
for line in source.lines() {
let line = line.expect("Could not read file.");
let words: Vec<&str> = line.split_whitespace().collect();
if words[0] == "C" && words[3] == "WX" {
if let (Ok(c), Ok(w)) =
(words[1].parse::<u8>(), words[4].parse::<u16>())
{
result.widths.insert(c, w);
}
}
}
Ok(result)
}
/// Create a FontMetrics from a slice of (char, width) pairs.
fn from_slice(data: &[(u8, u16)]) -> Self {
let mut widths = BTreeMap::new();
for &(c, w) in data {
widths.insert(c, w);
}
FontMetrics { widths }
}
/// Get the width of a specific character. The character is given in the
/// encoding of the FontMetrics object.
pub fn get_width(&self, char: u8) -> Option<u16> {
self.widths.get(&char).cloned()
}
}
include!(concat!(env!("OUT_DIR"), "/metrics_data.rs"));
|
// Copyright (c) 2014 Guillaume Pinot <texitoi(a)texitoi.eu>
//
// This work is free. You can redistribute it and/or modify it under
// the terms of the Do What The Fuck You Want To Public License,
// Version 2, as published by Sam Hocevar. See the COPYING file for
// more details.
#[macro_use] extern crate mdo;
fn main() {
// exporting the monadic functions for the Iterator monad (similar
// to list comprehension)
use mdo::iter::{bind, ret, mzero};
// getting the list of (x, y, z) such that
// - 1 <= x <= y < z < 11
// - x^2 + y^2 == z^2
let l = bind(1i32..11, move |z|
bind(1..z, move |x|
bind(x..z, move |y|
bind(if x * x + y * y == z * z { ret(()) }
else { mzero() },
move |_|
ret((x, y, z))
)))).collect::<Vec<_>>();
println!("{:?}", l);
// the same thing, using the mdo! macro
let l = mdo! {
z =<< 1i32..11;
x =<< 1..z;
y =<< x..z;
when x * x + y * y == z * z;
ret ret((x, y, z))
}.collect::<Vec<_>>();
println!("{:?}", l);
}
|
use projecteuler::helper;
use projecteuler::modulo;
fn main() {
helper::check_bench(|| {
solve();
});
assert_eq!(solve(), 8739992577);
dbg!(solve());
}
fn solve() -> usize {
let m = 10_000_000_000;
let exp = 7830457;
let mut t = modulo::modulo_power(2u128, exp, m);
t *= 28433;
t += 1;
(t % m) as usize
}
|
#![cfg(test)]
extern crate sudoku_solver;
use sudoku_solver::board;
use sudoku_solver::solver;
use sudoku_solver::board_serialize;
#[test]
fn display_empty_board() {
let a_board = sudoku_solver::board::new_empty();
a_board.display();
}
#[test]
fn test_solution () {
let mut a_board = Box::new(board::new_with_entries(
[[ 4,5,3, 9,2,7, 1,8,6],
[ 6,8,0, 4,3,5, 7,9,2],
[ 7,9,2, 6,8,0, 3,4,5],
[ 5,1,4, 7,9,3, 6,2,8],
[ 3,2,6, 5,0,0, 4,0,9],
[ 8,0,9, 2,6,4, 5,1,3],
[ 9,3,7, 8,4,6, 2,5,1],
[ 1,4,8, 3,5,2, 9,0,7],
[ 0,6,5, 1,7,9, 8,3,4]]));
let sol_board = board::new_with_entries(
[[ 4,5,3, 9,2,7, 1,8,6],
[ 6,8,1, 4,3,5, 7,9,2],
[ 7,9,2, 6,8,1, 3,4,5],
[ 5,1,4, 7,9,3, 6,2,8],
[ 3,2,6, 5,1,8, 4,7,9],
[ 8,7,9, 2,6,4, 5,1,3],
[ 9,3,7, 8,4,6, 2,5,1],
[ 1,4,8, 3,5,2, 9,6,7],
[ 2,6,5, 1,7,9, 8,3,4]]);
solver::solve_with_backtracing(&mut a_board);
assert!(*a_board == sol_board);
}
#[test]
fn test_deserialize_and_solve() {
let mut a_board = Box::new(board_serialize::deserialize("52...6.........7.13...........4..8..6......5...........418.........3..2...87....."));
solver::solve_with_backtracing(&mut a_board);
a_board.display();
println!("{:?}", a_board.is_valid_solution());
assert!(false);
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::MSTCTL {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `MSTCONTINUE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MSTCONTINUER {
#[doc = "No effect."]
NO_EFFECT_,
#[doc = "Continue. Informs the Master function to continue to the next operation. This must done after writing transmit data, reading received data, or any other housekeeping related to the next bus operation."]
CONTINUE_INFORMS_TH,
}
impl MSTCONTINUER {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
MSTCONTINUER::NO_EFFECT_ => false,
MSTCONTINUER::CONTINUE_INFORMS_TH => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> MSTCONTINUER {
match value {
false => MSTCONTINUER::NO_EFFECT_,
true => MSTCONTINUER::CONTINUE_INFORMS_TH,
}
}
#[doc = "Checks if the value of the field is `NO_EFFECT_`"]
#[inline]
pub fn is_no_effect_(&self) -> bool {
*self == MSTCONTINUER::NO_EFFECT_
}
#[doc = "Checks if the value of the field is `CONTINUE_INFORMS_TH`"]
#[inline]
pub fn is_continue_informs_th(&self) -> bool {
*self == MSTCONTINUER::CONTINUE_INFORMS_TH
}
}
#[doc = "Possible values of the field `MSTSTART`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MSTSTARTR {
#[doc = "No effect."]
NO_EFFECT_,
#[doc = "Start. A Start will be generated on the I2C bus at the next allowed time."]
START_A_START_WILL_,
}
impl MSTSTARTR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
MSTSTARTR::NO_EFFECT_ => false,
MSTSTARTR::START_A_START_WILL_ => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> MSTSTARTR {
match value {
false => MSTSTARTR::NO_EFFECT_,
true => MSTSTARTR::START_A_START_WILL_,
}
}
#[doc = "Checks if the value of the field is `NO_EFFECT_`"]
#[inline]
pub fn is_no_effect_(&self) -> bool {
*self == MSTSTARTR::NO_EFFECT_
}
#[doc = "Checks if the value of the field is `START_A_START_WILL_`"]
#[inline]
pub fn is_start_a_start_will_(&self) -> bool {
*self == MSTSTARTR::START_A_START_WILL_
}
}
#[doc = "Possible values of the field `MSTSTOP`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MSTSTOPR {
#[doc = "No effect."]
NO_EFFECT_,
#[doc = "Stop. A Stop will be generated on the I2C bus at the next allowed time, preceded by a Nack to the slave if the master is receiving data from the slave (Master Receiver mode)."]
STOP_A_STOP_WILL_BE,
}
impl MSTSTOPR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
MSTSTOPR::NO_EFFECT_ => false,
MSTSTOPR::STOP_A_STOP_WILL_BE => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> MSTSTOPR {
match value {
false => MSTSTOPR::NO_EFFECT_,
true => MSTSTOPR::STOP_A_STOP_WILL_BE,
}
}
#[doc = "Checks if the value of the field is `NO_EFFECT_`"]
#[inline]
pub fn is_no_effect_(&self) -> bool {
*self == MSTSTOPR::NO_EFFECT_
}
#[doc = "Checks if the value of the field is `STOP_A_STOP_WILL_BE`"]
#[inline]
pub fn is_stop_a_stop_will_be(&self) -> bool {
*self == MSTSTOPR::STOP_A_STOP_WILL_BE
}
}
#[doc = "Values that can be written to the field `MSTCONTINUE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MSTCONTINUEW {
#[doc = "No effect."]
NO_EFFECT_,
#[doc = "Continue. Informs the Master function to continue to the next operation. This must done after writing transmit data, reading received data, or any other housekeeping related to the next bus operation."]
CONTINUE_INFORMS_TH,
}
impl MSTCONTINUEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
MSTCONTINUEW::NO_EFFECT_ => false,
MSTCONTINUEW::CONTINUE_INFORMS_TH => true,
}
}
}
#[doc = r" Proxy"]
pub struct _MSTCONTINUEW<'a> {
w: &'a mut W,
}
impl<'a> _MSTCONTINUEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: MSTCONTINUEW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "No effect."]
#[inline]
pub fn no_effect_(self) -> &'a mut W {
self.variant(MSTCONTINUEW::NO_EFFECT_)
}
#[doc = "Continue. Informs the Master function to continue to the next operation. This must done after writing transmit data, reading received data, or any other housekeeping related to the next bus operation."]
#[inline]
pub fn continue_informs_th(self) -> &'a mut W {
self.variant(MSTCONTINUEW::CONTINUE_INFORMS_TH)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `MSTSTART`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MSTSTARTW {
#[doc = "No effect."]
NO_EFFECT_,
#[doc = "Start. A Start will be generated on the I2C bus at the next allowed time."]
START_A_START_WILL_,
}
impl MSTSTARTW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
MSTSTARTW::NO_EFFECT_ => false,
MSTSTARTW::START_A_START_WILL_ => true,
}
}
}
#[doc = r" Proxy"]
pub struct _MSTSTARTW<'a> {
w: &'a mut W,
}
impl<'a> _MSTSTARTW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: MSTSTARTW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "No effect."]
#[inline]
pub fn no_effect_(self) -> &'a mut W {
self.variant(MSTSTARTW::NO_EFFECT_)
}
#[doc = "Start. A Start will be generated on the I2C bus at the next allowed time."]
#[inline]
pub fn start_a_start_will_(self) -> &'a mut W {
self.variant(MSTSTARTW::START_A_START_WILL_)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `MSTSTOP`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MSTSTOPW {
#[doc = "No effect."]
NO_EFFECT_,
#[doc = "Stop. A Stop will be generated on the I2C bus at the next allowed time, preceded by a Nack to the slave if the master is receiving data from the slave (Master Receiver mode)."]
STOP_A_STOP_WILL_BE,
}
impl MSTSTOPW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
MSTSTOPW::NO_EFFECT_ => false,
MSTSTOPW::STOP_A_STOP_WILL_BE => true,
}
}
}
#[doc = r" Proxy"]
pub struct _MSTSTOPW<'a> {
w: &'a mut W,
}
impl<'a> _MSTSTOPW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: MSTSTOPW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "No effect."]
#[inline]
pub fn no_effect_(self) -> &'a mut W {
self.variant(MSTSTOPW::NO_EFFECT_)
}
#[doc = "Stop. A Stop will be generated on the I2C bus at the next allowed time, preceded by a Nack to the slave if the master is receiving data from the slave (Master Receiver mode)."]
#[inline]
pub fn stop_a_stop_will_be(self) -> &'a mut W {
self.variant(MSTSTOPW::STOP_A_STOP_WILL_BE)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Master Continue. This bit is write-only."]
#[inline]
pub fn mstcontinue(&self) -> MSTCONTINUER {
MSTCONTINUER::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 1 - Master Start control. This bit is write-only."]
#[inline]
pub fn mststart(&self) -> MSTSTARTR {
MSTSTARTR::_from({
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 2 - Master Stop control. This bit is write-only."]
#[inline]
pub fn mststop(&self) -> MSTSTOPR {
MSTSTOPR::_from({
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Master Continue. This bit is write-only."]
#[inline]
pub fn mstcontinue(&mut self) -> _MSTCONTINUEW {
_MSTCONTINUEW { w: self }
}
#[doc = "Bit 1 - Master Start control. This bit is write-only."]
#[inline]
pub fn mststart(&mut self) -> _MSTSTARTW {
_MSTSTARTW { w: self }
}
#[doc = "Bit 2 - Master Stop control. This bit is write-only."]
#[inline]
pub fn mststop(&mut self) -> _MSTSTOPW {
_MSTSTOPW { w: self }
}
}
|
extern crate num;
use std::io::prelude::*;
use std::fs::File;
use num::complex::*;
fn main() {
let mut f = File::open("input.txt").unwrap();
let mut s = String::new();
f.read_to_string(&mut s).unwrap();
let left = Complex::new(0, 1);
let right = Complex::new(0, -1);
let result = s.split(",").map(|s| s.trim())
.fold(
(Complex::new(0, 0), Complex::new(0, 1)),
|(pos, dir), instr| {
let (turn, dist) = match instr.split_at(1) {
(hd, tl) =>
(match hd {
"L" => left,
"R" => right,
_ => panic!()
},
tl.parse::<i32>().unwrap()),
};
(pos + (dir * turn).scale(dist), dir * turn)
}
);
println!("result: {}", result.0.re.abs() + result.0.im.abs());
}
|
#[doc = "Reader of register AF2"]
pub type R = crate::R<u32, super::AF2>;
#[doc = "Writer for register AF2"]
pub type W = crate::W<u32, super::AF2>;
#[doc = "Register AF2 `reset()`'s with value 0"]
impl crate::ResetValue for super::AF2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `OCRSEL`"]
pub type OCRSEL_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OCRSEL`"]
pub struct OCRSEL_W<'a> {
w: &'a mut W,
}
impl<'a> OCRSEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 16)) | (((value as u32) & 0x07) << 16);
self.w
}
}
#[doc = "Reader of field `BK2CMP4P`"]
pub type BK2CMP4P_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BK2CMP4P`"]
pub struct BK2CMP4P_W<'a> {
w: &'a mut W,
}
impl<'a> BK2CMP4P_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 `BK2CMP3P`"]
pub type BK2CMP3P_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BK2CMP3P`"]
pub struct BK2CMP3P_W<'a> {
w: &'a mut W,
}
impl<'a> BK2CMP3P_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 `BK2CMP2P`"]
pub type BK2CMP2P_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BK2CMP2P`"]
pub struct BK2CMP2P_W<'a> {
w: &'a mut W,
}
impl<'a> BK2CMP2P_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 `BK2CMP1P`"]
pub type BK2CMP1P_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BK2CMP1P`"]
pub struct BK2CMP1P_W<'a> {
w: &'a mut W,
}
impl<'a> BK2CMP1P_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 `BK2INP`"]
pub type BK2INP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BK2INP`"]
pub struct BK2INP_W<'a> {
w: &'a mut W,
}
impl<'a> BK2INP_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 `BK2CMP7E`"]
pub type BK2CMP7E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BK2CMP7E`"]
pub struct BK2CMP7E_W<'a> {
w: &'a mut W,
}
impl<'a> BK2CMP7E_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 `BK2CMP6E`"]
pub type BK2CMP6E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BK2CMP6E`"]
pub struct BK2CMP6E_W<'a> {
w: &'a mut W,
}
impl<'a> BK2CMP6E_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 `BK2CMP5E`"]
pub type BK2CMP5E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BK2CMP5E`"]
pub struct BK2CMP5E_W<'a> {
w: &'a mut W,
}
impl<'a> BK2CMP5E_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 `BK2CMP4E`"]
pub type BK2CMP4E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BK2CMP4E`"]
pub struct BK2CMP4E_W<'a> {
w: &'a mut W,
}
impl<'a> BK2CMP4E_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 `BK2CMP3E`"]
pub type BK2CMP3E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BK2CMP3E`"]
pub struct BK2CMP3E_W<'a> {
w: &'a mut W,
}
impl<'a> BK2CMP3E_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 `BK2CMP2E`"]
pub type BK2CMP2E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BK2CMP2E`"]
pub struct BK2CMP2E_W<'a> {
w: &'a mut W,
}
impl<'a> BK2CMP2E_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 `BK2CMP1E`"]
pub type BK2CMP1E_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BK2CMP1E`"]
pub struct BK2CMP1E_W<'a> {
w: &'a mut W,
}
impl<'a> BK2CMP1E_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 `BKINE`"]
pub type BKINE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BKINE`"]
pub struct BKINE_W<'a> {
w: &'a mut W,
}
impl<'a> BKINE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bits 16:18 - OCREF_CLR source selection"]
#[inline(always)]
pub fn ocrsel(&self) -> OCRSEL_R {
OCRSEL_R::new(((self.bits >> 16) & 0x07) as u8)
}
#[doc = "Bit 13 - BRK2 COMP4 input polarity"]
#[inline(always)]
pub fn bk2cmp4p(&self) -> BK2CMP4P_R {
BK2CMP4P_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 12 - BRK2 COMP3 input polarity"]
#[inline(always)]
pub fn bk2cmp3p(&self) -> BK2CMP3P_R {
BK2CMP3P_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 11 - BRK2 COMP2 input polarity"]
#[inline(always)]
pub fn bk2cmp2p(&self) -> BK2CMP2P_R {
BK2CMP2P_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 10 - BRK2 COMP1 input polarity"]
#[inline(always)]
pub fn bk2cmp1p(&self) -> BK2CMP1P_R {
BK2CMP1P_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 9 - BRK2 BKIN input polarity"]
#[inline(always)]
pub fn bk2inp(&self) -> BK2INP_R {
BK2INP_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 7 - BRK2 COMP7 enable"]
#[inline(always)]
pub fn bk2cmp7e(&self) -> BK2CMP7E_R {
BK2CMP7E_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 6 - BRK2 COMP6 enable"]
#[inline(always)]
pub fn bk2cmp6e(&self) -> BK2CMP6E_R {
BK2CMP6E_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 5 - BRK2 COMP5 enable"]
#[inline(always)]
pub fn bk2cmp5e(&self) -> BK2CMP5E_R {
BK2CMP5E_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4 - BRK2 COMP4 enable"]
#[inline(always)]
pub fn bk2cmp4e(&self) -> BK2CMP4E_R {
BK2CMP4E_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 3 - BRK2 COMP3 enable"]
#[inline(always)]
pub fn bk2cmp3e(&self) -> BK2CMP3E_R {
BK2CMP3E_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 2 - BRK2 COMP2 enable"]
#[inline(always)]
pub fn bk2cmp2e(&self) -> BK2CMP2E_R {
BK2CMP2E_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1 - BRK2 COMP1 enable"]
#[inline(always)]
pub fn bk2cmp1e(&self) -> BK2CMP1E_R {
BK2CMP1E_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - BRK BKIN input enable"]
#[inline(always)]
pub fn bkine(&self) -> BKINE_R {
BKINE_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 16:18 - OCREF_CLR source selection"]
#[inline(always)]
pub fn ocrsel(&mut self) -> OCRSEL_W {
OCRSEL_W { w: self }
}
#[doc = "Bit 13 - BRK2 COMP4 input polarity"]
#[inline(always)]
pub fn bk2cmp4p(&mut self) -> BK2CMP4P_W {
BK2CMP4P_W { w: self }
}
#[doc = "Bit 12 - BRK2 COMP3 input polarity"]
#[inline(always)]
pub fn bk2cmp3p(&mut self) -> BK2CMP3P_W {
BK2CMP3P_W { w: self }
}
#[doc = "Bit 11 - BRK2 COMP2 input polarity"]
#[inline(always)]
pub fn bk2cmp2p(&mut self) -> BK2CMP2P_W {
BK2CMP2P_W { w: self }
}
#[doc = "Bit 10 - BRK2 COMP1 input polarity"]
#[inline(always)]
pub fn bk2cmp1p(&mut self) -> BK2CMP1P_W {
BK2CMP1P_W { w: self }
}
#[doc = "Bit 9 - BRK2 BKIN input polarity"]
#[inline(always)]
pub fn bk2inp(&mut self) -> BK2INP_W {
BK2INP_W { w: self }
}
#[doc = "Bit 7 - BRK2 COMP7 enable"]
#[inline(always)]
pub fn bk2cmp7e(&mut self) -> BK2CMP7E_W {
BK2CMP7E_W { w: self }
}
#[doc = "Bit 6 - BRK2 COMP6 enable"]
#[inline(always)]
pub fn bk2cmp6e(&mut self) -> BK2CMP6E_W {
BK2CMP6E_W { w: self }
}
#[doc = "Bit 5 - BRK2 COMP5 enable"]
#[inline(always)]
pub fn bk2cmp5e(&mut self) -> BK2CMP5E_W {
BK2CMP5E_W { w: self }
}
#[doc = "Bit 4 - BRK2 COMP4 enable"]
#[inline(always)]
pub fn bk2cmp4e(&mut self) -> BK2CMP4E_W {
BK2CMP4E_W { w: self }
}
#[doc = "Bit 3 - BRK2 COMP3 enable"]
#[inline(always)]
pub fn bk2cmp3e(&mut self) -> BK2CMP3E_W {
BK2CMP3E_W { w: self }
}
#[doc = "Bit 2 - BRK2 COMP2 enable"]
#[inline(always)]
pub fn bk2cmp2e(&mut self) -> BK2CMP2E_W {
BK2CMP2E_W { w: self }
}
#[doc = "Bit 1 - BRK2 COMP1 enable"]
#[inline(always)]
pub fn bk2cmp1e(&mut self) -> BK2CMP1E_W {
BK2CMP1E_W { w: self }
}
#[doc = "Bit 0 - BRK BKIN input enable"]
#[inline(always)]
pub fn bkine(&mut self) -> BKINE_W {
BKINE_W { w: self }
}
}
|
use crate::probe::{Pin, PinConfig, PinMode, Probe};
use std::thread::sleep;
use std::time::Duration;
mod probe;
fn main() {
let mut pins = PinConfig::new();
pins.pin_mode(Pin::D12, PinMode::Digital);
pins.pin_mode(Pin::D4, PinMode::Digital);
pins.pin_mode(Pin::D6, PinMode::Digital);
pins.pin_mode(Pin::D8, PinMode::Digital);
pins.pin_mode(Pin::D10, PinMode::Digital);
pins.pin_mode(Pin::A0, PinMode::Digital);
pins.pin_mode(Pin::A1, PinMode::Analog);
pins.pin_mode(Pin::A2, PinMode::Analog);
pins.pin_mode(Pin::A3, PinMode::Analog);
pins.pin_mode(Pin::A4, PinMode::Analog);
let probe = Probe::new("/dev/ttyACM0");
probe.reset();
probe.configure_pins(pins);
println!("{}", probe.dump_pins());
probe.start_capture();
sleep(Duration::from_secs(5));
let result = probe.stop_capture();
println!("{}", result.len())
} |
//! Varisat is a [CDCL][cdcl] based SAT solver written in rust. Given a boolean formula in
//! [conjunctive normal form][cnf], it either finds a variable assignment that makes the formula
//! true or finds a proof that this is impossible.
//!
//! In addition to this API documentation, Varisat comes with a [user manual].
//!
//! [cdcl]: https://en.wikipedia.org/wiki/Conflict-Driven_Clause_Learning
//! [cnf]: https://en.wikipedia.org/wiki/Conjunctive_normal_form
//! [user manual]: https://jix.github.io/varisat/manual/0.2.1/
pub mod config;
pub mod solver;
mod analyze_conflict;
mod assumptions;
mod binary;
mod cdcl;
mod clause;
mod context;
mod decision;
mod glue;
mod load;
mod model;
mod proof;
mod prop;
mod schedule;
mod state;
mod tmp;
mod unit_simplify;
mod variables;
pub use solver::{ProofFormat, Solver};
pub use varisat_formula::{cnf, lit, CnfFormula, ExtendFormula, Lit, Var};
pub mod dimacs {
//! DIMCAS CNF parser and writer.
pub use varisat_dimacs::*;
}
pub mod checker {
//! Proof checker for Varisat proofs.
pub use varisat_checker::{
CheckedProofStep, Checker, CheckerData, CheckerError, ProofProcessor,
ProofTranscriptProcessor, ProofTranscriptStep,
};
}
|
/// Compute the value of the counter can take depending on the values the increments can take.
pub fn compute_counter({{>choice.arg_defs ../this}}
ir_instance: &ir::Function,
store: &DomainStore,
diff: &DomainDiff)
-> {{~#if half}} HalfRange {{else}} Range {{/if}}
{
let mut counter_val = {{~#if half~}}
HalfRange::new_eq(&(), {{base}}, &());
{{~else~}}
Range::new_eq(&(), {{base}}, &());
{{~/if~}}
{{#>loop_nest nest}}
{{body}}
{{/loop_nest}}
counter_val
}
|
use std::error::Error as StdError;
use std::fmt;
use std::io;
use std::result::Result as StdResult;
use serde;
pub type Result<T> = StdResult<T, Error>;
#[derive(Debug)]
pub enum Error {
IoError(io::Error),
Serde(String),
NBTError(nbt::Error),
UnsupportedType(&'static str),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Error::IoError(ref e) => e.fmt(f),
&Error::Serde(ref msg) => write!(f, "{}", msg),
Error::UnsupportedType(ref t) => write!(f,"unsupported type {}", t),
// Static messages should suffice for the remaining errors.
other => write!(f, "{}", other.description()),
}
}
}
impl StdError for Error {
fn description(&self) -> &str {
match *self {
Error::IoError(ref e) => e.description(),
Error::Serde(ref msg) => &msg[..],
Error::NBTError(ref e) => e.description(),
Error::UnsupportedType(_) => "unsupported type",
}
}
fn cause(&self) -> Option<&StdError> {
match *self {
Error::IoError(ref e) => e.source(),
Error::NBTError(ref e) => Some(e),
_ => None,
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Error {
Error::IoError(e)
}
}
impl serde::ser::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Error {
Error::Serde(msg.to_string())
}
}
impl serde::de::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Error {
Error::Serde(msg.to_string())
}
}
|
use paho_mqtt as mqtt;
use std::time::Duration;
const BROKER_URI: &str = "tcp://localhost:1883";
const TOPIC: &str = "sample";
const QOS: i32 = 1;
fn main() {
let client = mqtt::AsyncClient::new(BROKER_URI).unwrap();
let con_opts = mqtt::ConnectOptionsBuilder::new()
//.mqtt_version(5) // ERROR: Wrong MQTT version
.connect_timeout(Duration::from_secs(5))
.finalize();
println!("{:?}", con_opts);
let con = client.connect(con_opts)
.wait()
.unwrap();
println!("{:?}", con);
let msg = mqtt::Message::new(TOPIC, "test123", QOS);
let t = client.publish(msg);
if let Err(e) = t.wait() {
println!("ERROR: {:?}", e);
}
client.disconnect(mqtt::DisconnectOptions::new())
.wait()
.unwrap();
}
|
use errors::*;
use libsodacon::net::endpoint::Endpoint;
use rmp_serde;
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct DiscoveryReq {
pub discover: HashMap<Vec<u8>, Vec<Endpoint>>,
}
impl DiscoveryReq {
pub fn new(discover: HashMap<Vec<u8>, Vec<Endpoint>>) -> Self {
DiscoveryReq { discover }
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct DiscoveryRes {
pub discover: HashMap<Vec<u8>, Vec<Endpoint>>,
}
impl DiscoveryRes {
pub fn new(discover: HashMap<Vec<u8>, Vec<Endpoint>>) -> Self {
DiscoveryRes { discover }
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct UserMessage {
pub data: Vec<u8>,
}
impl UserMessage {
pub fn new(data: Vec<u8>) -> Self {
UserMessage { data }
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum Message {
DiscoveryReq(Box<DiscoveryReq>),
DiscoveryRes(Box<DiscoveryRes>),
UserMessage(Box<UserMessage>),
}
pub fn compile(message: &Message) -> Result<Vec<u8>> {
Ok(rmp_serde::to_vec(message)?)
}
pub fn parse(message: &[u8]) -> Result<Message> {
Ok(rmp_serde::from_slice(message)?)
}
|
use self::TokenType::*;
///
/// The type of a token.
///
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub enum TokenType {
EndOfFile,
Identifier,
Whitespace,
NewLine,
// LITERALS:
__LiteralBegin,
IntegerLiteral,
DecimalLiteral,
BooleanLiteral,
__LiteralEnd,
// KEYWORDS:
__KeywordBegin,
IfKeyword,
WhileKeyword,
StructKeyword,
// -- Type keywords:
IntKeyword,
FloatKeyword,
BoolKeyword,
__KeywordEnd,
// OPERATORS
__OperatorBegin,
Plus, // +
Minus, // -
Asterisk, // *
ForwardSlash, // /
EqualsOperator, // ==
__OperatorEnd,
// SYMBOLS:
Quote, // "
Tick, // '
Arrow, // ->
OpenParen,
CloseParen,
Comma,
Semicolon,
EqualsSign, // =
Colon,
OpenBrace,
CloseBrace,
Pipe, // |
Ampersand, // &
OpenLineComment,
OpenMultilineComment,
CloseMultilineComment,
UnknownSymbol,
}
impl TokenType {
///
/// Checks to see if this type is a literal type.
///
pub fn is_literal(self) -> bool {
self > __LiteralBegin && self < __LiteralEnd
}
///
/// Checks to see if this type is a keyword type.
///
pub fn is_keyword(self) -> bool {
self > __KeywordBegin && self < __KeywordEnd
}
///
/// Checks to see if this type is an operator type.
///
pub fn is_operator(self) -> bool {
self > __OperatorBegin && self < __OperatorEnd
}
}
|
// 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.
// Tests that two closures cannot simultaneously have mutable
// access to the variable, whether that mutable access be used
// for direct assignment or for taking mutable ref. Issue #6801.
#![feature(on_unimplemented)]
#[rustc_on_unimplemented(
message="the message"
label="the label"
)]
trait T {}
//~^^^ ERROR expected one of `)` or `,`, found `label`
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::aggregate_approx_count_distinct::aggregate_approx_count_distinct_function_desc;
use super::aggregate_arg_min_max::aggregate_arg_max_function_desc;
use super::aggregate_arg_min_max::aggregate_arg_min_function_desc;
use super::aggregate_avg::aggregate_avg_function_desc;
use super::aggregate_combinator_distinct::aggregate_combinator_distinct_desc;
use super::aggregate_combinator_distinct::aggregate_combinator_uniq_desc;
use super::aggregate_covariance::aggregate_covariance_population_desc;
use super::aggregate_covariance::aggregate_covariance_sample_desc;
use super::aggregate_min_max_any::aggregate_any_function_desc;
use super::aggregate_min_max_any::aggregate_max_function_desc;
use super::aggregate_min_max_any::aggregate_min_function_desc;
use super::aggregate_stddev::aggregate_stddev_pop_function_desc;
use super::aggregate_stddev::aggregate_stddev_samp_function_desc;
use super::aggregate_window_funnel::aggregate_window_funnel_function_desc;
use super::AggregateCountFunction;
use super::AggregateFunctionFactory;
use super::AggregateIfCombinator;
use crate::aggregates::aggregate_list::aggregate_list_function_desc;
use crate::aggregates::aggregate_quantile_cont::aggregate_median_function_desc;
use crate::aggregates::aggregate_quantile_cont::aggregate_quantile_function_desc;
use crate::aggregates::aggregate_retention::aggregate_retention_function_desc;
use crate::aggregates::aggregate_sum::aggregate_sum_function_desc;
pub struct Aggregators;
impl Aggregators {
pub fn register(factory: &mut AggregateFunctionFactory) {
// DatabendQuery always uses lowercase function names to get functions.
factory.register("sum", aggregate_sum_function_desc());
factory.register("count", AggregateCountFunction::desc());
factory.register("avg", aggregate_avg_function_desc());
factory.register("uniq", aggregate_combinator_uniq_desc());
factory.register("min", aggregate_min_function_desc());
factory.register("max", aggregate_max_function_desc());
factory.register("any", aggregate_any_function_desc());
factory.register("arg_min", aggregate_arg_min_function_desc());
factory.register("arg_max", aggregate_arg_max_function_desc());
factory.register("covar_samp", aggregate_covariance_sample_desc());
factory.register("covar_pop", aggregate_covariance_population_desc());
factory.register("stddev_samp", aggregate_stddev_samp_function_desc());
factory.register("stddev_pop", aggregate_stddev_pop_function_desc());
factory.register("stddev", aggregate_stddev_pop_function_desc());
factory.register("std", aggregate_stddev_pop_function_desc());
factory.register("quantile_cont", aggregate_quantile_function_desc());
factory.register("median", aggregate_median_function_desc());
factory.register("window_funnel", aggregate_window_funnel_function_desc());
factory.register(
"approx_count_distinct",
aggregate_approx_count_distinct_function_desc(),
);
factory.register("retention", aggregate_retention_function_desc());
factory.register("list", aggregate_list_function_desc());
}
pub fn register_combinator(factory: &mut AggregateFunctionFactory) {
factory.register_combinator("_if", AggregateIfCombinator::combinator_desc());
factory.register_combinator("_distinct", aggregate_combinator_distinct_desc());
}
}
|
pub mod label;
pub mod text;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.