text stringlengths 8 4.13M |
|---|
use bytes::Buf;
use hyper::{header, Body, Request, Response, StatusCode};
use serde::{Deserialize, Serialize};
use super::error::ApiError;
pub async fn json_request<T: for<'de> Deserialize<'de>>(
request: &mut Request<Body>,
) -> Result<T, ApiError> {
let whole_body = hyper::body::aggregate(request.body_mut())
.await
.map_err(ApiError::from_err)?;
Ok(serde_json::from_reader(whole_body.reader())
.map_err(|err| ApiError::BadRequest(format!("Failed to parse json request {}", err)))?)
}
pub fn json_response<T: Serialize>(
status: StatusCode,
data: T,
) -> Result<Response<Body>, ApiError> {
let json = serde_json::to_string(&data).map_err(ApiError::from_err)?;
let response = Response::builder()
.status(status)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(json))
.map_err(ApiError::from_err)?;
Ok(response)
}
|
use syntax::{ast, codemap, parse};
use syntax::ptr::P;
use syntax::ext::base;
use super::Generator;
#[macro_use] mod macro_ext;
mod parser;
mod generator;
#[derive(Clone)]
pub struct ModelState {
pub mod_name: ast::Ident,
pub model: P<ast::Item>,
pub primary_key: Option<Vec<String>>,
pub before_create: Vec<String>,
pub before_save: Vec<String>,
}
pub fn model<'cx>(cx: &'cx mut base::ExtCtxt, sp: codemap::Span,
name: ast::Ident, tokens: Vec<ast::TokenTree>) -> Box<base::MacResult + 'cx> {
// Parse a full ModelState from the input, emitting errors if used incorrectly.
let state: ModelState = super::Parser::parse(&mut parse::tts_to_parser(cx.parse_sess(), tokens, cx.cfg()), (sp, &mut*cx, Some(name)));
state.generate(sp, cx, ())
}
|
//! stdlib implementation for Redox, following http://pubs.opengroup.org/onlinepubs/7908799/xsh/stdlib.h.html
#![no_std]
#![feature(core_intrinsics)]
#![feature(global_allocator)]
extern crate ctype;
extern crate errno;
extern crate platform;
extern crate ralloc;
use core::{ptr, str};
use errno::*;
use platform::types::*;
#[global_allocator]
static ALLOCATOR: ralloc::Allocator = ralloc::Allocator;
pub const EXIT_FAILURE: c_int = 1;
pub const EXIT_SUCCESS: c_int = 0;
static mut ATEXIT_FUNCS: [Option<extern "C" fn()>; 32] = [None; 32];
#[no_mangle]
pub extern "C" fn a64l(s: *const c_char) -> c_long {
unimplemented!();
}
#[no_mangle]
pub unsafe extern "C" fn abort() {
use core::intrinsics;
intrinsics::abort();
}
#[no_mangle]
pub extern "C" fn abs(i: c_int) -> c_int {
if i < 0 {
-i
} else {
i
}
}
#[no_mangle]
pub unsafe extern "C" fn atexit(func: Option<extern "C" fn()>) -> c_int {
for i in 0..ATEXIT_FUNCS.len() {
if ATEXIT_FUNCS[i] == None {
ATEXIT_FUNCS[i] = func;
return 0;
}
}
1
}
#[no_mangle]
pub unsafe extern "C" fn atof(s: *const c_char) -> c_double {
strtod(s, ptr::null_mut())
}
macro_rules! dec_num_from_ascii {
($s: expr, $t: ty) => {
unsafe {
let mut s = $s;
// Iterate past whitespace
while ctype::isspace(*s as c_int) != 0 {
s = s.offset(1);
}
// Find out if there is a - sign
let neg_sign = match *s {
0x2d => {
s = s.offset(1);
true
}
// '+' increment s and continue parsing
0x2b => {
s = s.offset(1);
false
}
_ => false,
};
let mut n: $t = 0;
while ctype::isdigit(*s as c_int) != 0 {
n = 10 * n - (*s as $t - 0x30);
s = s.offset(1);
}
if neg_sign {
n
} else {
-n
}
}
};
}
#[no_mangle]
pub extern "C" fn atoi(s: *const c_char) -> c_int {
dec_num_from_ascii!(s, c_int)
}
#[no_mangle]
pub extern "C" fn atol(s: *const c_char) -> c_long {
dec_num_from_ascii!(s, c_long)
}
#[no_mangle]
pub extern "C" fn bsearch(
key: *const c_void,
base: *const c_void,
nel: size_t,
width: size_t,
compar: Option<extern "C" fn(*const c_void, *const c_void) -> c_int>,
) -> *mut c_void {
unimplemented!();
}
#[no_mangle]
pub unsafe extern "C" fn calloc(nelem: size_t, elsize: size_t) -> *mut c_void {
use core::intrinsics;
let size = nelem * elsize;
let ptr = malloc(size);
if !ptr.is_null() {
intrinsics::write_bytes(ptr as *mut u8, 0, size);
}
ptr
}
#[repr(C)]
pub struct div_t {
quot: c_int,
rem: c_int,
}
#[no_mangle]
pub extern "C" fn div(numer: c_int, denom: c_int) -> div_t {
div_t {
quot: numer / denom,
rem: numer % denom,
}
}
#[no_mangle]
pub extern "C" fn drand48() -> c_double {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn ecvt(
value: c_double,
ndigit: c_int,
decpt: *mut c_int,
sign: *mut c_int,
) -> *mut c_char {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn erand(xsubi: [c_ushort; 3]) -> c_double {
unimplemented!();
}
#[no_mangle]
pub unsafe extern "C" fn exit(status: c_int) {
for i in (0..ATEXIT_FUNCS.len()).rev() {
if let Some(func) = ATEXIT_FUNCS[i] {
(func)();
}
}
platform::exit(status);
}
#[no_mangle]
pub extern "C" fn fcvt(
value: c_double,
ndigit: c_int,
decpt: *mut c_int,
sign: *mut c_int,
) -> *mut c_char {
unimplemented!();
}
#[no_mangle]
pub unsafe extern "C" fn free(ptr: *mut c_void) {
let ptr = (ptr as *mut u8).offset(-16);
let size = *(ptr as *mut u64);
let _align = *(ptr as *mut u64).offset(1);
ralloc::free(ptr, size as usize);
}
#[no_mangle]
pub extern "C" fn gcvt(value: c_double, ndigit: c_int, buf: *mut c_char) -> *mut c_char {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn getenv(name: *const c_char) -> *mut c_char {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn getsubopt(
optionp: *mut *mut c_char,
tokens: *const *mut c_char,
valuep: *mut *mut c_char,
) -> c_int {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn grantpt(fildes: c_int) -> c_int {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn initstate(seec: c_uint, state: *mut c_char, size: size_t) -> *mut c_char {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn jrand48(xsubi: [c_ushort; 3]) -> c_long {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn l64a(value: c_long) -> *mut c_char {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn labs(i: c_long) -> c_long {
if i < 0 {
-i
} else {
i
}
}
#[no_mangle]
pub extern "C" fn lcong48(param: [c_ushort; 7]) {
unimplemented!();
}
#[repr(C)]
pub struct ldiv_t {
quot: c_long,
rem: c_long,
}
#[no_mangle]
pub extern "C" fn ldiv(numer: c_long, denom: c_long) -> ldiv_t {
ldiv_t {
quot: numer / denom,
rem: numer % denom,
}
}
#[no_mangle]
pub extern "C" fn lrand48() -> c_long {
unimplemented!();
}
#[no_mangle]
pub unsafe extern "C" fn malloc(size: size_t) -> *mut c_void {
let align = 8;
let ptr = ralloc::alloc(size + 16, align);
if !ptr.is_null() {
*(ptr as *mut u64) = (size + 16) as u64;
*(ptr as *mut u64).offset(1) = align as u64;
ptr.offset(16) as *mut c_void
} else {
ptr as *mut c_void
}
}
#[no_mangle]
pub extern "C" fn mblen(s: *const c_char, n: size_t) -> c_int {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn mbstowcs(pwcs: *mut wchar_t, s: *const c_char, n: size_t) -> size_t {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn mbtowc(pwc: *mut wchar_t, s: *const c_char, n: size_t) -> c_int {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn mktemp(template: *mut c_char) -> *mut c_char {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn mkstemp(template: *mut c_char) -> c_int {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn mrand48() -> c_long {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn nrand48(xsubi: [c_ushort; 3]) -> c_long {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn ptsname(fildes: c_int) -> *mut c_char {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn putenv(s: *mut c_char) -> c_int {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn qsort(
base: *mut c_void,
nel: size_t,
width: size_t,
compar: Option<extern "C" fn(*const c_void, *const c_void) -> c_int>,
) {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn rand() -> c_int {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn rand_r(seed: *mut c_uint) -> c_int {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn random() -> c_long {
unimplemented!();
}
#[no_mangle]
pub unsafe extern "C" fn realloc(ptr: *mut c_void, size: size_t) -> *mut c_void {
let old_ptr = (ptr as *mut u8).offset(-16);
let old_size = *(old_ptr as *mut u64);
let align = *(old_ptr as *mut u64).offset(1);
let ptr = ralloc::realloc(old_ptr, old_size as usize, size + 16, align as usize);
if !ptr.is_null() {
*(ptr as *mut u64) = (size + 16) as u64;
*(ptr as *mut u64).offset(1) = align;
ptr.offset(16) as *mut c_void
} else {
ptr as *mut c_void
}
}
#[no_mangle]
pub extern "C" fn realpath(file_name: *const c_char, resolved_name: *mut c_char) -> *mut c_char {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn seed48(seed16v: [c_ushort; 3]) -> c_ushort {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn setkey(key: *const c_char) {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn setstate(state: *const c_char) -> *mut c_char {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn srand(seed: c_uint) {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn srand48(seed: c_long) {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn srandom(seed: c_uint) {
unimplemented!();
}
#[no_mangle]
pub unsafe extern "C" fn strtod(s: *const c_char, endptr: *mut *mut c_char) -> c_double {
//TODO: endptr
use core::str::FromStr;
let s_str = str::from_utf8_unchecked(platform::c_str(s));
match f64::from_str(s_str) {
Ok(ok) => ok as c_double,
Err(_err) => {
platform::errno = EINVAL;
0.0
}
}
}
#[no_mangle]
pub extern "C" fn strtol(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_long {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn strtoul(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_ulong {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn system(command: *const c_char) -> c_int {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn ttyslot() -> c_int {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn unlockpt(fildes: c_int) -> c_int {
unimplemented!();
}
#[no_mangle]
pub unsafe extern "C" fn valloc(size: size_t) -> *mut c_void {
let align = 4096;
let ptr = ralloc::alloc(size + 16, align);
if !ptr.is_null() {
*(ptr as *mut u64) = (size + 16) as u64;
*(ptr as *mut u64).offset(1) = align as u64;
ptr.offset(16) as *mut c_void
} else {
ptr as *mut c_void
}
}
#[no_mangle]
pub extern "C" fn wcstombs(s: *mut c_char, pwcs: *const wchar_t, n: size_t) -> size_t {
unimplemented!();
}
#[no_mangle]
pub extern "C" fn wctomb(s: *mut c_char, wchar: wchar_t) -> c_int {
unimplemented!();
}
/*
#[no_mangle]
pub extern "C" fn func(args) -> c_int {
unimplemented!();
}
*/
|
use std::path::BytesContainer;
use http::headers::content_type::MediaType;
use self::mimegen::get_generated_content_type;
mod mimegen;
pub fn get_content_type(path: &Path) -> Option<MediaType> {
let path_str = path.container_as_str().unwrap();
let ext_pos = regex!(".[a-z0-9]+$").find(path_str);
let mut ext;
match ext_pos {
Some((start, _)) => {
ext = path_str.as_slice().slice_from(start);
},
None => return None
}
get_generated_content_type(ext)
}
|
pub type IDirectMusic = *mut ::core::ffi::c_void;
pub type IDirectMusic8 = *mut ::core::ffi::c_void;
pub type IDirectMusicBuffer = *mut ::core::ffi::c_void;
pub type IDirectMusicCollection = *mut ::core::ffi::c_void;
pub type IDirectMusicDownload = *mut ::core::ffi::c_void;
pub type IDirectMusicDownloadedInstrument = *mut ::core::ffi::c_void;
pub type IDirectMusicInstrument = *mut ::core::ffi::c_void;
pub type IDirectMusicPort = *mut ::core::ffi::c_void;
pub type IDirectMusicPortDownload = *mut ::core::ffi::c_void;
pub type IDirectMusicSynth = *mut ::core::ffi::c_void;
pub type IDirectMusicSynth8 = *mut ::core::ffi::c_void;
pub type IDirectMusicSynthSink = *mut ::core::ffi::c_void;
pub type IDirectMusicThru = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CLSID_DirectMusic: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x636b9f10_0c7d_11d1_95b2_0020afdc7421);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CLSID_DirectMusicCollection: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x480ff4b0_28b2_11d1_bef7_00c04fbf8fef);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CLSID_DirectMusicSynth: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x58c2b4d0_46e7_11d1_89ac_00a0c9054129);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CLSID_DirectMusicSynthSink: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xaec17ce3_a514_11d1_afa6_00aa0024d8b6);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CLSID_DirectSoundPrivate: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x11ab3ec0_25ec_11d1_a4d8_00c04fc28aca);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_ATTENUATION: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_CENTER: u32 = 18u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_CHORUS: u32 = 128u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG1_ATTACKTIME: u32 = 518u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG1_DECAYTIME: u32 = 519u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG1_DELAYTIME: u32 = 523u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG1_HOLDTIME: u32 = 524u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG1_RELEASETIME: u32 = 521u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG1_SHUTDOWNTIME: u32 = 525u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG1_SUSTAINLEVEL: u32 = 522u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG2_ATTACKTIME: u32 = 778u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG2_DECAYTIME: u32 = 779u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG2_DELAYTIME: u32 = 783u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG2_HOLDTIME: u32 = 784u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG2_RELEASETIME: u32 = 781u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_EG2_SUSTAINLEVEL: u32 = 782u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_FILTER_CUTOFF: u32 = 1280u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_FILTER_Q: u32 = 1281u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_GAIN: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_KEYNUMBER: u32 = 5u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_LEFT: u32 = 16u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_LEFTREAR: u32 = 19u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_LFE_CHANNEL: u32 = 21u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_LFO_FREQUENCY: u32 = 260u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_LFO_STARTDELAY: u32 = 261u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_NONE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_PAN: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_PITCH: u32 = 3u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_REVERB: u32 = 129u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_RIGHT: u32 = 17u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_RIGHTREAR: u32 = 20u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_VIB_FREQUENCY: u32 = 276u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_DST_VIB_STARTDELAY: u32 = 277u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_CC1: u32 = 129u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_CC10: u32 = 138u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_CC11: u32 = 139u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_CC7: u32 = 135u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_CC91: u32 = 219u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_CC93: u32 = 221u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_CHANNELPRESSURE: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_EG1: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_EG2: u32 = 5u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_KEYNUMBER: u32 = 3u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_KEYONVELOCITY: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_LFO: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_MONOPRESSURE: u32 = 10u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_NONE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_PITCHWHEEL: u32 = 6u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_POLYPRESSURE: u32 = 7u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_SRC_VIBRATO: u32 = 9u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_TRN_CONCAVE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_TRN_CONVEX: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_TRN_NONE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const CONN_TRN_SWITCH: u32 = 3u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN10_VOICE_PRIORITY_OFFSET: u32 = 15u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN11_VOICE_PRIORITY_OFFSET: u32 = 5u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN12_VOICE_PRIORITY_OFFSET: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN13_VOICE_PRIORITY_OFFSET: u32 = 3u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN14_VOICE_PRIORITY_OFFSET: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN15_VOICE_PRIORITY_OFFSET: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN16_VOICE_PRIORITY_OFFSET: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN1_VOICE_PRIORITY_OFFSET: u32 = 14u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN2_VOICE_PRIORITY_OFFSET: u32 = 13u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN3_VOICE_PRIORITY_OFFSET: u32 = 12u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN4_VOICE_PRIORITY_OFFSET: u32 = 11u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN5_VOICE_PRIORITY_OFFSET: u32 = 10u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN6_VOICE_PRIORITY_OFFSET: u32 = 9u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN7_VOICE_PRIORITY_OFFSET: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN8_VOICE_PRIORITY_OFFSET: u32 = 7u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CHAN9_VOICE_PRIORITY_OFFSET: u32 = 6u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_CRITICAL_VOICE_PRIORITY: u32 = 4026531840u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_HIGH_VOICE_PRIORITY: u32 = 3221225472u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_LOW_VOICE_PRIORITY: u32 = 1073741824u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_PERSIST_VOICE_PRIORITY: u32 = 268435456u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DAUD_STANDARD_VOICE_PRIORITY: u32 = 2147483648u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLSID_GMInHardware: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x178f2f24_c364_11d1_a760_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLSID_GSInHardware: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x178f2f25_c364_11d1_a760_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLSID_ManufacturersID: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xb03e1181_8095_11d2_a1ef_00600833dbd8);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLSID_ProductID: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xb03e1182_8095_11d2_a1ef_00600833dbd8);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLSID_SampleMemorySize: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x178f2f28_c364_11d1_a760_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLSID_SamplePlaybackRate: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x2a91f713_a4bf_11d2_bbdf_00600833dbd8);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLSID_SupportsDLS1: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x178f2f27_c364_11d1_a760_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLSID_SupportsDLS2: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xf14599e5_4689_11d2_afa6_00aa0024d8b6);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLSID_XGInHardware: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x178f2f26_c364_11d1_a760_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_ADD: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_AND: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_CONST: u32 = 16u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_DIVIDE: u32 = 7u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_EQ: u32 = 14u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_GE: u32 = 13u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_GT: u32 = 12u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_LE: u32 = 11u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_LOGICAL_AND: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_LOGICAL_OR: u32 = 9u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_LT: u32 = 10u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_MULTIPLY: u32 = 6u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_NOT: u32 = 15u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_OR: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_QUERY: u32 = 17u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_QUERYSUPPORTED: u32 = 18u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_SUBTRACT: u32 = 5u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DLS_CDL_XOR: u32 = 3u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_CLOCKF_GLOBAL: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_DEFAULT_SIZE_OFFSETTABLE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_DOWNLOADINFO_INSTRUMENT: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_DOWNLOADINFO_INSTRUMENT2: u32 = 3u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_DOWNLOADINFO_ONESHOTWAVE: u32 = 6u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_DOWNLOADINFO_STREAMINGWAVE: u32 = 5u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_DOWNLOADINFO_WAVE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_DOWNLOADINFO_WAVEARTICULATION: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_EFFECT_CHORUS: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_EFFECT_DELAY: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_EFFECT_NONE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_EFFECT_REVERB: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_EVENT_STRUCTURED: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_INSTRUMENT_GM_INSTRUMENT: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_MAX_DESCRIPTION: u32 = 128u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_MAX_DRIVER: u32 = 128u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_MIN_DATA_SIZE: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_AUDIOPATH: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_DIRECTSOUND: u32 = 128u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_DLS: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_DLS2: u32 = 512u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_EXTERNAL: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_GMINHARDWARE: u32 = 16u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_GSINHARDWARE: u32 = 32u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_INPUTCLASS: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_MEMORYSIZEFIXED: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_OUTPUTCLASS: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_SHAREABLE: u32 = 256u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_SOFTWARESYNTH: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_SYSTEMMEMORY: u32 = 2147483647u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_WAVE: u32 = 2048u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PC_XGINHARDWARE: u32 = 64u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PORTPARAMS_AUDIOCHANNELS: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PORTPARAMS_CHANNELGROUPS: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PORTPARAMS_EFFECTS: u32 = 32u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PORTPARAMS_FEATURES: u32 = 128u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PORTPARAMS_SAMPLERATE: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PORTPARAMS_SHARE: u32 = 64u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PORTPARAMS_VOICES: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PORT_FEATURE_AUDIOPATH: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PORT_FEATURE_STREAMING: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PORT_KERNEL_MODE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PORT_USER_MODE_SYNTH: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_PORT_WINMM_DRIVER: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_SYNTHSTATS_CPU_PER_VOICE: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_SYNTHSTATS_FREE_MEMORY: u32 = 32u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_SYNTHSTATS_LOST_NOTES: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_SYNTHSTATS_PEAK_VOLUME: u32 = 16u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_SYNTHSTATS_SYSTEMMEMORY: u32 = 2147483647u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_SYNTHSTATS_TOTAL_CPU: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_SYNTHSTATS_VOICES: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_VOLUME_MAX: u32 = 2000u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_VOLUME_MIN: i32 = -20000i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_BACK_CENTER: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_BACK_LEFT: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_BACK_RIGHT: u32 = 5u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_CHORUS_SEND: u32 = 65u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_DYNAMIC_0: u32 = 512u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_FIRST_SPKR_LOC: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_FRONT_CENTER: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_FRONT_LEFT: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_FRONT_LEFT_OF_CENTER: u32 = 6u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_FRONT_RIGHT: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_FRONT_RIGHT_OF_CENTER: u32 = 7u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_LAST_SPKR_LOC: u32 = 17u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_LEFT: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_LOW_FREQUENCY: u32 = 3u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_NULL: u32 = 4294967295u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_REVERB_SEND: u32 = 64u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_RIGHT: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_SIDE_LEFT: u32 = 9u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_SIDE_RIGHT: u32 = 10u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_TOP_BACK_CENTER: u32 = 16u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_TOP_BACK_LEFT: u32 = 15u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_TOP_BACK_RIGHT: u32 = 17u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_TOP_CENTER: u32 = 11u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_TOP_FRONT_CENTER: u32 = 13u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_TOP_FRONT_LEFT: u32 = 12u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSBUSID_TOP_FRONT_RIGHT: u32 = 14u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSPROPSETID_DirectSoundDevice: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x84624f82_25ec_11d1_a4d8_00c04fc28aca);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_AUDIOMODE: u32 = 3840u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_AUDIOQU: u32 = 117440512u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_AUDIOSMP: u32 = 939524096u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_CAP_AUD12Bits: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_CAP_AUD16Bits: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_DVSD_NTSC_FRAMESIZE: i32 = 120000i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_DVSD_PAL_FRAMESIZE: i32 = 144000i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_HD: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_NTSC: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_NTSCPAL: u32 = 2097152u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_PAL: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_SD: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_SL: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_SMCHN: u32 = 57344u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DV_STYPE: u32 = 2031616u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const F_INSTRUMENT_DRUMS: u32 = 2147483648u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const F_RGN_OPTION_SELFNONEXCLUSIVE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const F_WAVELINK_MULTICHANNEL: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const F_WAVELINK_PHASE_MASTER: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const F_WSMP_NO_COMPRESSION: i32 = 2i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const F_WSMP_NO_TRUNCATION: i32 = 1i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_DLS1: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x178f2f27_c364_11d1_a760_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_DLS2: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xf14599e5_4689_11d2_afa6_00aa0024d8b6);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_Effects: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xcda8d611_684a_11d2_871e_00600893b1bd);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_GM_Hardware: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x178f2f24_c364_11d1_a760_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_GS_Capable: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x6496aba2_61b0_11d2_afa6_00aa0024d8b6);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_GS_Hardware: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x178f2f25_c364_11d1_a760_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_INSTRUMENT2: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x865fd372_9f67_11d2_872a_00600893b1bd);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_LegacyCaps: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xcfa7cdc2_00a1_11d2_aad5_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_MemorySize: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x178f2f28_c364_11d1_a760_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_SampleMemorySize: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x178f2f28_c364_11d1_a760_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_SamplePlaybackRate: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x2a91f713_a4bf_11d2_bbdf_00600833dbd8);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_SetSynthSink: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x0a3a5ba5_37b6_11d2_b9f9_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_SinkUsesDSound: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xbe208857_8952_11d2_ba1c_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_SynthSink_DSOUND: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x0aa97844_c877_11d1_870c_00600893b1bd);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_SynthSink_WAVE: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x0aa97845_c877_11d1_870c_00600893b1bd);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_Volume: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xfedfae25_e46e_11d1_aace_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_WavesReverb: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x04cb5622_32e5_11d2_afa6_00aa0024d8b6);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_WriteLatency: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x268a0fa0_60f2_11d2_afa6_00aa0024d8b6);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_WritePeriod: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x268a0fa1_60f2_11d2_afa6_00aa0024d8b6);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_XG_Capable: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x6496aba1_61b0_11d2_afa6_00aa0024d8b6);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const GUID_DMUS_PROP_XG_Hardware: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x178f2f26_c364_11d1_a760_0000f875ac12);
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const POOL_CUE_NULL: i32 = -1i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const REFRESH_F_LASTBUFFER: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const REGSTR_PATH_SOFTWARESYNTHS: ::windows_sys::core::PCSTR = ::windows_sys::s!("Software\\Microsoft\\DirectMusic\\SoftwareSynths");
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const SIZE_DVINFO: u32 = 32u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const WAVELINK_CHANNEL_LEFT: i32 = 1i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const WAVELINK_CHANNEL_RIGHT: i32 = 2i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const WLOOP_TYPE_FORWARD: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const WLOOP_TYPE_RELEASE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub type DIRECTSOUNDDEVICE_DATAFLOW = i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DIRECTSOUNDDEVICE_DATAFLOW_RENDER: DIRECTSOUNDDEVICE_DATAFLOW = 0i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE: DIRECTSOUNDDEVICE_DATAFLOW = 1i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub type DIRECTSOUNDDEVICE_TYPE = i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DIRECTSOUNDDEVICE_TYPE_EMULATED: DIRECTSOUNDDEVICE_TYPE = 0i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DIRECTSOUNDDEVICE_TYPE_VXD: DIRECTSOUNDDEVICE_TYPE = 1i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DIRECTSOUNDDEVICE_TYPE_WDM: DIRECTSOUNDDEVICE_TYPE = 2i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub type DMUS_CLOCKTYPE = i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_CLOCK_SYSTEM: DMUS_CLOCKTYPE = 0i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DMUS_CLOCK_WAVE: DMUS_CLOCKTYPE = 1i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub type DSPROPERTY_DIRECTSOUNDDEVICE = i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_A: DSPROPERTY_DIRECTSOUNDDEVICE = 1i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_1: DSPROPERTY_DIRECTSOUNDDEVICE = 2i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_1: DSPROPERTY_DIRECTSOUNDDEVICE = 3i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_W: DSPROPERTY_DIRECTSOUNDDEVICE = 4i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_A: DSPROPERTY_DIRECTSOUNDDEVICE = 5i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W: DSPROPERTY_DIRECTSOUNDDEVICE = 6i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_A: DSPROPERTY_DIRECTSOUNDDEVICE = 7i32;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub const DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W: DSPROPERTY_DIRECTSOUNDDEVICE = 8i32;
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct CONNECTION {
pub usSource: u16,
pub usControl: u16,
pub usDestination: u16,
pub usTransform: u16,
pub lScale: i32,
}
impl ::core::marker::Copy for CONNECTION {}
impl ::core::clone::Clone for CONNECTION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct CONNECTIONLIST {
pub cbSize: u32,
pub cConnections: u32,
}
impl ::core::marker::Copy for CONNECTIONLIST {}
impl ::core::clone::Clone for CONNECTIONLIST {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DLSHEADER {
pub cInstruments: u32,
}
impl ::core::marker::Copy for DLSHEADER {}
impl ::core::clone::Clone for DLSHEADER {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DLSID {
pub ulData1: u32,
pub usData2: u16,
pub usData3: u16,
pub abData4: [u8; 8],
}
impl ::core::marker::Copy for DLSID {}
impl ::core::clone::Clone for DLSID {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DLSVERSION {
pub dwVersionMS: u32,
pub dwVersionLS: u32,
}
impl ::core::marker::Copy for DLSVERSION {}
impl ::core::clone::Clone for DLSVERSION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_ARTICPARAMS {
pub LFO: DMUS_LFOPARAMS,
pub VolEG: DMUS_VEGPARAMS,
pub PitchEG: DMUS_PEGPARAMS,
pub Misc: DMUS_MSCPARAMS,
}
impl ::core::marker::Copy for DMUS_ARTICPARAMS {}
impl ::core::clone::Clone for DMUS_ARTICPARAMS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_ARTICULATION {
pub ulArt1Idx: u32,
pub ulFirstExtCkIdx: u32,
}
impl ::core::marker::Copy for DMUS_ARTICULATION {}
impl ::core::clone::Clone for DMUS_ARTICULATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_ARTICULATION2 {
pub ulArtIdx: u32,
pub ulFirstExtCkIdx: u32,
pub ulNextArtIdx: u32,
}
impl ::core::marker::Copy for DMUS_ARTICULATION2 {}
impl ::core::clone::Clone for DMUS_ARTICULATION2 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_BUFFERDESC {
pub dwSize: u32,
pub dwFlags: u32,
pub guidBufferFormat: ::windows_sys::core::GUID,
pub cbBuffer: u32,
}
impl ::core::marker::Copy for DMUS_BUFFERDESC {}
impl ::core::clone::Clone for DMUS_BUFFERDESC {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_CLOCKINFO7 {
pub dwSize: u32,
pub ctType: DMUS_CLOCKTYPE,
pub guidClock: ::windows_sys::core::GUID,
pub wszDescription: [u16; 128],
}
impl ::core::marker::Copy for DMUS_CLOCKINFO7 {}
impl ::core::clone::Clone for DMUS_CLOCKINFO7 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_CLOCKINFO8 {
pub dwSize: u32,
pub ctType: DMUS_CLOCKTYPE,
pub guidClock: ::windows_sys::core::GUID,
pub wszDescription: [u16; 128],
pub dwFlags: u32,
}
impl ::core::marker::Copy for DMUS_CLOCKINFO8 {}
impl ::core::clone::Clone for DMUS_CLOCKINFO8 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_COPYRIGHT {
pub cbSize: u32,
pub byCopyright: [u8; 4],
}
impl ::core::marker::Copy for DMUS_COPYRIGHT {}
impl ::core::clone::Clone for DMUS_COPYRIGHT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_DOWNLOADINFO {
pub dwDLType: u32,
pub dwDLId: u32,
pub dwNumOffsetTableEntries: u32,
pub cbSize: u32,
}
impl ::core::marker::Copy for DMUS_DOWNLOADINFO {}
impl ::core::clone::Clone for DMUS_DOWNLOADINFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C, packed(4))]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_EVENTHEADER {
pub cbEvent: u32,
pub dwChannelGroup: u32,
pub rtDelta: i64,
pub dwFlags: u32,
}
impl ::core::marker::Copy for DMUS_EVENTHEADER {}
impl ::core::clone::Clone for DMUS_EVENTHEADER {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_EXTENSIONCHUNK {
pub cbSize: u32,
pub ulNextExtCkIdx: u32,
pub ExtCkID: u32,
pub byExtCk: [u8; 4],
}
impl ::core::marker::Copy for DMUS_EXTENSIONCHUNK {}
impl ::core::clone::Clone for DMUS_EXTENSIONCHUNK {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_INSTRUMENT {
pub ulPatch: u32,
pub ulFirstRegionIdx: u32,
pub ulGlobalArtIdx: u32,
pub ulFirstExtCkIdx: u32,
pub ulCopyrightIdx: u32,
pub ulFlags: u32,
}
impl ::core::marker::Copy for DMUS_INSTRUMENT {}
impl ::core::clone::Clone for DMUS_INSTRUMENT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_LFOPARAMS {
pub pcFrequency: i32,
pub tcDelay: i32,
pub gcVolumeScale: i32,
pub pcPitchScale: i32,
pub gcMWToVolume: i32,
pub pcMWToPitch: i32,
}
impl ::core::marker::Copy for DMUS_LFOPARAMS {}
impl ::core::clone::Clone for DMUS_LFOPARAMS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_MSCPARAMS {
pub ptDefaultPan: i32,
}
impl ::core::marker::Copy for DMUS_MSCPARAMS {}
impl ::core::clone::Clone for DMUS_MSCPARAMS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_NOTERANGE {
pub dwLowNote: u32,
pub dwHighNote: u32,
}
impl ::core::marker::Copy for DMUS_NOTERANGE {}
impl ::core::clone::Clone for DMUS_NOTERANGE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_OFFSETTABLE {
pub ulOffsetTable: [u32; 1],
}
impl ::core::marker::Copy for DMUS_OFFSETTABLE {}
impl ::core::clone::Clone for DMUS_OFFSETTABLE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_PEGPARAMS {
pub tcAttack: i32,
pub tcDecay: i32,
pub ptSustain: i32,
pub tcRelease: i32,
pub tcVel2Attack: i32,
pub tcKey2Decay: i32,
pub pcRange: i32,
}
impl ::core::marker::Copy for DMUS_PEGPARAMS {}
impl ::core::clone::Clone for DMUS_PEGPARAMS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_PORTCAPS {
pub dwSize: u32,
pub dwFlags: u32,
pub guidPort: ::windows_sys::core::GUID,
pub dwClass: u32,
pub dwType: u32,
pub dwMemorySize: u32,
pub dwMaxChannelGroups: u32,
pub dwMaxVoices: u32,
pub dwMaxAudioChannels: u32,
pub dwEffectFlags: u32,
pub wszDescription: [u16; 128],
}
impl ::core::marker::Copy for DMUS_PORTCAPS {}
impl ::core::clone::Clone for DMUS_PORTCAPS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct DMUS_PORTPARAMS7 {
pub dwSize: u32,
pub dwValidParams: u32,
pub dwVoices: u32,
pub dwChannelGroups: u32,
pub dwAudioChannels: u32,
pub dwSampleRate: u32,
pub dwEffectFlags: u32,
pub fShare: super::super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for DMUS_PORTPARAMS7 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for DMUS_PORTPARAMS7 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct DMUS_PORTPARAMS8 {
pub dwSize: u32,
pub dwValidParams: u32,
pub dwVoices: u32,
pub dwChannelGroups: u32,
pub dwAudioChannels: u32,
pub dwSampleRate: u32,
pub dwEffectFlags: u32,
pub fShare: super::super::super::Foundation::BOOL,
pub dwFeatures: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for DMUS_PORTPARAMS8 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for DMUS_PORTPARAMS8 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_REGION {
pub RangeKey: RGNRANGE,
pub RangeVelocity: RGNRANGE,
pub fusOptions: u16,
pub usKeyGroup: u16,
pub ulRegionArtIdx: u32,
pub ulNextRegionIdx: u32,
pub ulFirstExtCkIdx: u32,
pub WaveLink: WAVELINK,
pub WSMP: WSMPL,
pub WLOOP: [WLOOP; 1],
}
impl ::core::marker::Copy for DMUS_REGION {}
impl ::core::clone::Clone for DMUS_REGION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_SYNTHSTATS {
pub dwSize: u32,
pub dwValidStats: u32,
pub dwVoices: u32,
pub dwTotalCPU: u32,
pub dwCPUPerVoice: u32,
pub dwLostNotes: u32,
pub dwFreeMemory: u32,
pub lPeakVolume: i32,
}
impl ::core::marker::Copy for DMUS_SYNTHSTATS {}
impl ::core::clone::Clone for DMUS_SYNTHSTATS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_SYNTHSTATS8 {
pub dwSize: u32,
pub dwValidStats: u32,
pub dwVoices: u32,
pub dwTotalCPU: u32,
pub dwCPUPerVoice: u32,
pub dwLostNotes: u32,
pub dwFreeMemory: u32,
pub lPeakVolume: i32,
pub dwSynthMemUse: u32,
}
impl ::core::marker::Copy for DMUS_SYNTHSTATS8 {}
impl ::core::clone::Clone for DMUS_SYNTHSTATS8 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_VEGPARAMS {
pub tcAttack: i32,
pub tcDecay: i32,
pub ptSustain: i32,
pub tcRelease: i32,
pub tcVel2Attack: i32,
pub tcKey2Decay: i32,
}
impl ::core::marker::Copy for DMUS_VEGPARAMS {}
impl ::core::clone::Clone for DMUS_VEGPARAMS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct DMUS_VOICE_STATE {
pub bExists: super::super::super::Foundation::BOOL,
pub spPosition: u64,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for DMUS_VOICE_STATE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for DMUS_VOICE_STATE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_WAVE {
pub ulFirstExtCkIdx: u32,
pub ulCopyrightIdx: u32,
pub ulWaveDataIdx: u32,
pub WaveformatEx: super::WAVEFORMATEX,
}
impl ::core::marker::Copy for DMUS_WAVE {}
impl ::core::clone::Clone for DMUS_WAVE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_WAVEARTDL {
pub ulDownloadIdIdx: u32,
pub ulBus: u32,
pub ulBuffers: u32,
pub ulMasterDLId: u32,
pub usOptions: u16,
}
impl ::core::marker::Copy for DMUS_WAVEARTDL {}
impl ::core::clone::Clone for DMUS_WAVEARTDL {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_WAVEDATA {
pub cbSize: u32,
pub byData: [u8; 4],
}
impl ::core::marker::Copy for DMUS_WAVEDATA {}
impl ::core::clone::Clone for DMUS_WAVEDATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_WAVEDL {
pub cbWaveData: u32,
}
impl ::core::marker::Copy for DMUS_WAVEDL {}
impl ::core::clone::Clone for DMUS_WAVEDL {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DMUS_WAVES_REVERB_PARAMS {
pub fInGain: f32,
pub fReverbMix: f32,
pub fReverbTime: f32,
pub fHighFreqRTRatio: f32,
}
impl ::core::marker::Copy for DMUS_WAVES_REVERB_PARAMS {}
impl ::core::clone::Clone for DMUS_WAVES_REVERB_PARAMS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_1_DATA {
pub DeviceId: ::windows_sys::core::GUID,
pub DescriptionA: [super::super::super::Foundation::CHAR; 256],
pub DescriptionW: [u16; 256],
pub ModuleA: [super::super::super::Foundation::CHAR; 260],
pub ModuleW: [u16; 260],
pub Type: DIRECTSOUNDDEVICE_TYPE,
pub DataFlow: DIRECTSOUNDDEVICE_DATAFLOW,
pub WaveDeviceId: u32,
pub Devnode: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_1_DATA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_1_DATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_A_DATA {
pub Type: DIRECTSOUNDDEVICE_TYPE,
pub DataFlow: DIRECTSOUNDDEVICE_DATAFLOW,
pub DeviceId: ::windows_sys::core::GUID,
pub Description: ::windows_sys::core::PSTR,
pub Module: ::windows_sys::core::PSTR,
pub Interface: ::windows_sys::core::PSTR,
pub WaveDeviceId: u32,
}
impl ::core::marker::Copy for DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_A_DATA {}
impl ::core::clone::Clone for DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_A_DATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA {
pub Type: DIRECTSOUNDDEVICE_TYPE,
pub DataFlow: DIRECTSOUNDDEVICE_DATAFLOW,
pub DeviceId: ::windows_sys::core::GUID,
pub Description: ::windows_sys::core::PWSTR,
pub Module: ::windows_sys::core::PWSTR,
pub Interface: ::windows_sys::core::PWSTR,
pub WaveDeviceId: u32,
}
impl ::core::marker::Copy for DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA {}
impl ::core::clone::Clone for DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_1_DATA {
pub Callback: LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK1,
pub Context: *mut ::core::ffi::c_void,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_1_DATA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_1_DATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_A_DATA {
pub Callback: LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKA,
pub Context: *mut ::core::ffi::c_void,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_A_DATA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_A_DATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W_DATA {
pub Callback: LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKW,
pub Context: *mut ::core::ffi::c_void,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W_DATA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W_DATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_A_DATA {
pub DeviceName: ::windows_sys::core::PSTR,
pub DataFlow: DIRECTSOUNDDEVICE_DATAFLOW,
pub DeviceId: ::windows_sys::core::GUID,
}
impl ::core::marker::Copy for DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_A_DATA {}
impl ::core::clone::Clone for DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_A_DATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_W_DATA {
pub DeviceName: ::windows_sys::core::PWSTR,
pub DataFlow: DIRECTSOUNDDEVICE_DATAFLOW,
pub DeviceId: ::windows_sys::core::GUID,
}
impl ::core::marker::Copy for DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_W_DATA {}
impl ::core::clone::Clone for DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_W_DATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct DVAudInfo {
pub bAudStyle: [u8; 2],
pub bAudQu: [u8; 2],
pub bNumAudPin: u8,
pub wAvgSamplesPerPinPerFrm: [u16; 2],
pub wBlkMode: u16,
pub wDIFMode: u16,
pub wBlkDiv: u16,
}
impl ::core::marker::Copy for DVAudInfo {}
impl ::core::clone::Clone for DVAudInfo {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct INSTHEADER {
pub cRegions: u32,
pub Locale: MIDILOCALE,
}
impl ::core::marker::Copy for INSTHEADER {}
impl ::core::clone::Clone for INSTHEADER {
fn clone(&self) -> Self {
*self
}
}
#[repr(C, packed(1))]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct MDEVICECAPSEX {
pub cbSize: u32,
pub pCaps: *mut ::core::ffi::c_void,
}
impl ::core::marker::Copy for MDEVICECAPSEX {}
impl ::core::clone::Clone for MDEVICECAPSEX {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct MIDILOCALE {
pub ulBank: u32,
pub ulInstrument: u32,
}
impl ::core::marker::Copy for MIDILOCALE {}
impl ::core::clone::Clone for MIDILOCALE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C, packed(1))]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`, `\"Win32_Media_Multimedia\"`*"]
#[cfg(feature = "Win32_Media_Multimedia")]
pub struct MIDIOPENDESC {
pub hMidi: super::HMIDI,
pub dwCallback: usize,
pub dwInstance: usize,
pub dnDevNode: usize,
pub cIds: u32,
pub rgIds: [super::super::Multimedia::MIDIOPENSTRMID; 1],
}
#[cfg(feature = "Win32_Media_Multimedia")]
impl ::core::marker::Copy for MIDIOPENDESC {}
#[cfg(feature = "Win32_Media_Multimedia")]
impl ::core::clone::Clone for MIDIOPENDESC {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct POOLCUE {
pub ulOffset: u32,
}
impl ::core::marker::Copy for POOLCUE {}
impl ::core::clone::Clone for POOLCUE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct POOLTABLE {
pub cbSize: u32,
pub cCues: u32,
}
impl ::core::marker::Copy for POOLTABLE {}
impl ::core::clone::Clone for POOLTABLE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct RGNHEADER {
pub RangeKey: RGNRANGE,
pub RangeVelocity: RGNRANGE,
pub fusOptions: u16,
pub usKeyGroup: u16,
}
impl ::core::marker::Copy for RGNHEADER {}
impl ::core::clone::Clone for RGNHEADER {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct RGNRANGE {
pub usLow: u16,
pub usHigh: u16,
}
impl ::core::marker::Copy for RGNRANGE {}
impl ::core::clone::Clone for RGNRANGE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct WAVELINK {
pub fusOptions: u16,
pub usPhaseGroup: u16,
pub ulChannel: u32,
pub ulTableIndex: u32,
}
impl ::core::marker::Copy for WAVELINK {}
impl ::core::clone::Clone for WAVELINK {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct WLOOP {
pub cbSize: u32,
pub ulType: u32,
pub ulStart: u32,
pub ulLength: u32,
}
impl ::core::marker::Copy for WLOOP {}
impl ::core::clone::Clone for WLOOP {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`*"]
pub struct WSMPL {
pub cbSize: u32,
pub usUnityNote: u16,
pub sFineTune: i16,
pub lAttenuation: i32,
pub fulOptions: u32,
pub cSampleLoops: u32,
}
impl ::core::marker::Copy for WSMPL {}
impl ::core::clone::Clone for WSMPL {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK1 = ::core::option::Option<unsafe extern "system" fn(param0: *mut DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_1_DATA, param1: *mut ::core::ffi::c_void) -> super::super::super::Foundation::BOOL>;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKA = ::core::option::Option<unsafe extern "system" fn(param0: *mut DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_A_DATA, param1: *mut ::core::ffi::c_void) -> super::super::super::Foundation::BOOL>;
#[doc = "*Required features: `\"Win32_Media_Audio_DirectMusic\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type LPFNDIRECTSOUNDDEVICEENUMERATECALLBACKW = ::core::option::Option<unsafe extern "system" fn(param0: *mut DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA, param1: *mut ::core::ffi::c_void) -> super::super::super::Foundation::BOOL>;
|
use crate::color;
use pancurses::{Window, COLOR_PAIR};
use rand::{thread_rng, Rng};
pub struct Food<'a> {
pub x: i32,
pub y: i32,
form: char,
color: i16,
window: &'a Window,
}
impl<'a> Food<'a> {
pub fn new(window: &'a Window, form: char, color: i16) -> Self {
Self {
x: thread_rng().gen_range(window.get_beg_x()..=window.get_max_x()),
y: thread_rng().gen_range(window.get_beg_y()..=window.get_max_y()),
form,
color,
window,
}
}
pub fn rand_move(&mut self) {
self.x = thread_rng().gen_range(self.window.get_beg_x()..=self.window.get_max_x());
self.y = thread_rng().gen_range(self.window.get_beg_y()..=self.window.get_max_y());
}
pub fn spawn(&self) {
let color = match self.color {
9 => color::rand_color(),
_ => self.color as u32,
};
self.window.attron(COLOR_PAIR(color));
self.window.mvaddch(self.y, self.x, self.form);
self.window.attroff(COLOR_PAIR(color));
}
}
|
use std::cell::RefCell;
use std::collections::HashMap;
use crate::array::*;
use crate::shader::Vertex;
use gfx;
#[derive(Copy, Clone)]
pub struct BlockState {
pub value: u16,
}
pub const EMPTY_BLOCK: BlockState = BlockState { value: 0 };
#[derive(Copy, Clone)]
pub struct BiomeId {
pub value: u8,
}
#[derive(Copy, Clone)]
pub struct LightLevel {
pub value: u8,
}
impl LightLevel {
pub fn block_light(self) -> u8 {
self.value & 0xf
}
pub fn sky_light(self) -> u8 {
self.value >> 4
}
}
pub const SIZE: usize = 16;
/// A chunk of SIZE x SIZE x SIZE blocks, in YZX order.
#[derive(Copy, Clone)]
pub struct Chunk {
pub blocks: [[[BlockState; SIZE]; SIZE]; SIZE],
pub light_levels: [[[LightLevel; SIZE]; SIZE]; SIZE],
}
// TODO: Change to const pointer.
pub const EMPTY_CHUNK: &Chunk = &Chunk {
blocks: [[[EMPTY_BLOCK; SIZE]; SIZE]; SIZE],
light_levels: [[[LightLevel { value: 0xf0 }; SIZE]; SIZE]; SIZE],
};
pub struct ChunkColumn<R: gfx::Resources> {
pub chunks: Vec<Chunk>,
pub buffers: [RefCell<Option<gfx::handle::Buffer<R, Vertex>>>; SIZE],
pub biomes: [[BiomeId; SIZE]; SIZE],
}
pub struct ChunkManager<R: gfx::Resources> {
chunk_columns: HashMap<(i32, i32), ChunkColumn<R>>,
}
impl<R: gfx::Resources> ChunkManager<R> {
pub fn new() -> ChunkManager<R> {
ChunkManager {
chunk_columns: HashMap::new(),
}
}
pub fn add_chunk_column(&mut self, x: i32, z: i32, c: ChunkColumn<R>) {
self.chunk_columns.insert((x, z), c);
}
pub fn each_chunk_and_neighbors<'a, F>(&'a self, mut f: F)
where
F: FnMut(
/*coords:*/ [i32; 3],
/*buffer:*/ &'a RefCell<Option<gfx::handle::Buffer<R, Vertex>>>,
/*chunks:*/ [[[&'a Chunk; 3]; 3]; 3],
/*biomes:*/ [[Option<&'a [[BiomeId; SIZE]; SIZE]>; 3]; 3],
),
{
for &(x, z) in self.chunk_columns.keys() {
let columns =
[-1, 0, 1].map(|dz| [-1, 0, 1].map(|dx| self.chunk_columns.get(&(x + dx, z + dz))));
let central = columns[1][1].unwrap();
for y in 0..central.chunks.len() {
let chunks = [-1, 0, 1].map(|dy| {
let y = y as i32 + dy;
columns.map(|cz| {
cz.map(|cx| {
cx.and_then(|c| c.chunks[..].get(y as usize))
.unwrap_or(EMPTY_CHUNK)
})
})
});
f(
[x, y as i32, z],
¢ral.buffers[y],
chunks,
columns.map(|cz| cz.map(|cx| cx.map(|c| &c.biomes))),
)
}
}
}
pub fn each_chunk<F>(&self, mut f: F)
where
F: FnMut(
/*x:*/ i32,
/*y:*/ i32,
/*z:*/ i32,
/*c:*/ &Chunk,
/*b:*/ &RefCell<Option<gfx::handle::Buffer<R, Vertex>>>,
),
{
for (&(x, z), c) in self.chunk_columns.iter() {
for (y, (c, b)) in c.chunks.iter().zip(c.buffers.iter()).enumerate() {
f(x, y as i32, z, c, b)
}
}
}
}
|
extern crate actix;
extern crate actix_broker;
use std::time::Duration;
use actix::{clock::sleep, prelude::*};
use actix_broker::{Broker, BrokerSubscribe, SystemBroker};
#[derive(Clone, Message)]
#[rtype(result = "()")]
struct TestMessage;
#[derive(Default)]
struct TestActor {
count: u8,
}
impl Actor for TestActor {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
self.subscribe_async::<SystemBroker, TestMessage>(ctx);
}
}
impl Handler<TestMessage> for TestActor {
type Result = AtomicResponse<Self, ()>;
fn handle(&mut self, _msg: TestMessage, _ctx: &mut Self::Context) -> Self::Result {
let first = self.count == 0;
let task = async move {
if first {
sleep(Duration::from_millis(500)).await;
}
}
.into_actor(self)
.map(|_, act, _ctx| {
act.count += 1;
if act.count == 51 {
System::current().stop();
}
})
.boxed_local();
AtomicResponse::new(task)
}
}
#[test]
fn it_issues_async_on_full_mailbox() {
let sys = System::new();
sys.block_on(async {
let addr = TestActor::default().start();
sleep(Duration::from_millis(100)).await;
addr.try_send(TestMessage)
.expect("Unable to send base message");
for _ in 0..50 {
Broker::<SystemBroker>::issue_async(TestMessage);
}
});
sys.run().unwrap();
}
|
use futures::{stream, StreamExt};
use tokio::task::JoinError;
use web3::{
transports,
types::{BlockId, BlockNumber, Transaction, TransactionReceipt, H160, H256, U256},
Transport, Web3 as Web3Generic,
};
type Web3 = Web3Generic<transports::Http>;
pub struct TxInfo {
pub hash: H256,
pub from: H160,
pub to: Option<H160>,
pub gas_limit: U256,
}
// retrieve tx gas using `eth_getTransactionReceipt`
pub async fn gas_used(web3: &Web3, tx_hash: &str) -> Result<Option<U256>, web3::Error> {
let tx_hash = tx_hash
.trim_start_matches("0x")
.parse()
.expect("Unable to parse tx-hash");
let gas = web3
.eth()
.transaction_receipt(tx_hash)
.await?
.and_then(|tx| tx.gas_used);
Ok(gas)
}
// retrieve block tx gases using `eth_getTransactionReceipt`
pub async fn gas_used_parallel(
web3: &Web3,
hashes: impl Iterator<Item = String>,
) -> Result<Vec<U256>, JoinError> {
// create async tasks, one for each tx hash
let tasks = hashes.map(|tx| {
// clone so that we can move into async block
// this should not be expensive
let web3 = web3.clone();
tokio::spawn(async move {
match gas_used(&web3, &tx[..]).await {
Err(e) => panic!("Failed to retrieve gas for {}: {}", tx, e),
Ok(None) => panic!("Failed to retrieve gas for {}: None", tx),
Ok(Some(g)) => g,
}
})
});
stream::iter(tasks)
.buffered(4) // execute in parallel in batches of 4
.collect::<Vec<_>>()
.await // wait for all requests to complete
.into_iter()
.collect() // convert Vec<Result<_>> to Result<Vec<_>>
}
pub async fn block_receipts_parity(
web3: &Web3,
block: u64,
) -> web3::Result<Vec<TransactionReceipt>> {
// convert block number to hex
let block = format!("0x{:x}", block).into();
// call RPC
let raw = web3
.transport()
.execute("parity_getBlockReceipts", vec![block])
.await?;
// parse response
Ok(serde_json::from_value::<Vec<TransactionReceipt>>(raw)?)
}
// retrieve block tx gases using `parity_getBlockReceipts`
// this should be faster than `gas_parallel`
pub async fn gas_parity(web3: &Web3, block: u64) -> web3::Result<Vec<U256>> {
let gas = block_receipts_parity(web3, block)
.await?
.into_iter()
.map(|r| r.gas_used.expect("Receipt should contain `gas_used`"))
.collect();
Ok(gas)
}
pub fn gas_parity_parallel<'a>(
web3: &'a Web3,
blocks: impl Iterator<Item = u64> + 'a,
) -> impl stream::Stream<Item = Vec<U256>> + 'a {
// create async tasks, one for each tx hash
let tasks = blocks.map(move |b| {
// clone so that we can move into async block
// this should not be expensive
let web3 = web3.clone();
tokio::spawn(async move {
match gas_parity(&web3, b).await {
Err(e) => panic!("Failed to retrieve gas for {}: {}", b, e),
Ok(g) => g,
}
})
});
stream::iter(tasks)
.buffered(4) // execute in parallel in batches of 4
.map(|x| x.expect("RPC should succeed"))
}
// TODO
pub async fn block_txs(web3: &Web3, num: u64) -> Result<Option<Vec<Transaction>>, web3::Error> {
let block = BlockId::Number(BlockNumber::Number(num.into()));
let raw = web3
.eth()
.block_with_txs(block)
.await?
.map(|b| b.transactions);
Ok(raw)
}
// TODO
pub async fn tx_infos(web3: &Web3, num: u64) -> Result<Option<Vec<TxInfo>>, web3::Error> {
let infos = block_txs(web3, num).await?.map(|txs| {
txs.iter()
.map(|tx| TxInfo {
hash: tx.hash,
from: tx.from.expect("tx.from is not empty"),
to: tx.to,
gas_limit: tx.gas,
})
.collect::<Vec<_>>()
});
Ok(infos)
}
pub fn tx_infos_parallel<'a>(
web3: &'a Web3,
blocks: impl Iterator<Item = u64> + 'a,
) -> impl stream::Stream<Item = Vec<TxInfo>> + 'a {
// create async tasks, one for each tx hash
let tasks = blocks.map(move |b| {
// clone so that we can move into async block
// this should not be expensive
let web3 = web3.clone();
tokio::spawn(async move {
match tx_infos(&web3, b).await {
Err(e) => panic!("Failed to retrieve transactions for {}: {}", b, e),
Ok(None) => panic!("Block {} not found", b),
Ok(Some(receivers)) => receivers,
}
})
});
stream::iter(tasks)
.buffered(4) // execute in parallel in batches of 4
.map(|x| x.expect("RPC should succeed"))
}
#[rustfmt::skip]
#[cfg(test)]
mod tests {
use super::*;
const BLOCK1: u64 = 5232800;
const BLOCK2: u64 = 5232802;
// const NODE_URL: &str = "https://mainnet.infura.io/v3/c15ab95c12d441d19702cb4a0d1313e7";
const NODE_URL: &str = "http://localhost:8545";
fn web3() -> Result<web3::Web3<transports::Http>, web3::Error> {
let transport = web3::transports::Http::new(NODE_URL)?;
Ok(web3::Web3::new(transport))
}
// eth_getTransactionReceipt
#[tokio::test]
async fn test_gas_used() {
let web3 = web3().expect("can instantiate web3");
let gas_used = gas_used(&web3, "0xdb9a7dda261eb09fe3d1c3d4cdd00fe93693fa4a932ed6cfa51a5b6696f71c92")
.await
.expect("query succeeds")
.expect("receipt exists");
assert_eq!(gas_used, U256::from(52_249));
}
// eth_getTransactionReceipt
#[tokio::test]
async fn test_gas_used_parallel() {
let web3 = web3().expect("can instantiate web3");
let hashes = vec![
"0xdb9a7dda261eb09fe3d1c3d4cdd00fe93693fa4a932ed6cfa51a5b6696f71c92".to_string(),
"0xc68501cb5b3eda0fe845c30864a5657c9cf71d492c78f24b92e3d12986ae705b".to_string(),
"0x92376a0a83608f630e4ef678de54f437d3fd41cd0165e8799ca782e42eb308cc".to_string(),
];
let gas_used = gas_used_parallel(&web3, hashes.into_iter())
.await
.expect("queries succeed");
assert_eq!(gas_used.len(), 3);
assert_eq!(gas_used[0], U256::from(52_249));
assert_eq!(gas_used[1], U256::from(21_000));
assert_eq!(gas_used[2], U256::from(898_344));
}
// parity_getBlockReceipts
#[tokio::test]
async fn test_block_receipts_parity() {
let web3 = web3().expect("can instantiate web3");
let receipts = block_receipts_parity(&web3, BLOCK1).await.expect("query succeeds");
assert_eq!(receipts.len(), 88);
assert_eq!(receipts[0].transaction_hash, "c68501cb5b3eda0fe845c30864a5657c9cf71d492c78f24b92e3d12986ae705b".parse().unwrap());
assert_eq!(receipts[0].gas_used, Some(U256::from(21_000)));
assert_eq!(receipts[1].transaction_hash, "f9f3be29b6c70e3032a57e141c8374cc7cfb2b4006a640d680411af024b06179".parse().unwrap());
assert_eq!(receipts[1].gas_used, Some(U256::from(21_000)));
// ...
assert_eq!(receipts[87].transaction_hash, "76da1628c18e0096ed0a24d37adf110ee39fea04c8bed36dfa7065c016f5d4d3".parse().unwrap());
assert_eq!(receipts[87].gas_used, Some(U256::from(24_130)));
}
// parity_getBlockReceipts
#[tokio::test]
async fn test_gas_parity() {
let web3 = web3().expect("can instantiate web3");
let gas_used = gas_parity(&web3, BLOCK1).await.expect("query succeeds");
assert_eq!(gas_used.len(), 88);
assert_eq!(gas_used[0], U256::from(21_000));
assert_eq!(gas_used[1], U256::from(21_000));
// ...
assert_eq!(gas_used[87], U256::from(24_130));
}
// parity_getBlockReceipts
#[tokio::test]
async fn test_gas_parity_parallel() {
let web3 = web3().expect("can instantiate web3");
let blocks = vec![BLOCK1, BLOCK2];
let mut stream = gas_parity_parallel(&web3, blocks.into_iter());
match stream.next().await {
None => assert!(false),
Some(gas_used) => assert_eq!(gas_used.len(), 88),
}
match stream.next().await {
None => assert!(false),
Some(gas_used) => assert_eq!(gas_used.len(), 47),
}
assert!(stream.next().await.is_none());
}
// eth_getBlockByNumber
#[tokio::test]
async fn test_block_txs() {
let web3 = web3().expect("can instantiate web3");
let txs = block_txs(&web3, BLOCK1)
.await
.expect("query succeeds")
.expect("block exists");
assert_eq!(txs.len(), 88);
assert_eq!(txs[0].hash, "c68501cb5b3eda0fe845c30864a5657c9cf71d492c78f24b92e3d12986ae705b".parse().unwrap());
assert_eq!(txs[0].to, Some("9ff305d9f7692a9b45e4f9bce8be4e98992eddde".parse().unwrap()));
assert_eq!(txs[0].gas, U256::from(21_000));
assert_eq!(txs[1].hash, "f9f3be29b6c70e3032a57e141c8374cc7cfb2b4006a640d680411af024b06179".parse().unwrap());
assert_eq!(txs[1].to, Some("179631c363eef2cfec04f2354476f7b407ed031d".parse().unwrap()));
assert_eq!(txs[1].gas, U256::from(150_000));
// ...
assert_eq!(txs[87].hash, "76da1628c18e0096ed0a24d37adf110ee39fea04c8bed36dfa7065c016f5d4d3".parse().unwrap());
assert_eq!(txs[87].to, Some("d2f81cd7a20d60c0d558496c7169a20968389b40".parse().unwrap()));
assert_eq!(txs[87].gas, U256::from(36_195));
}
// eth_getBlockByNumber
#[tokio::test]
async fn test_tx_infos() {
let web3 = web3().expect("can instantiate web3");
let infos = tx_infos(&web3, BLOCK1)
.await
.expect("query succeeds")
.expect("block exists");
assert_eq!(infos.len(), 88);
assert_eq!(infos[0].hash, "c68501cb5b3eda0fe845c30864a5657c9cf71d492c78f24b92e3d12986ae705b".parse().unwrap());
assert_eq!(infos[0].to, Some("9ff305d9f7692a9b45e4f9bce8be4e98992eddde".parse().unwrap()));
assert_eq!(infos[0].gas_limit, U256::from(21_000));
assert_eq!(infos[1].hash, "f9f3be29b6c70e3032a57e141c8374cc7cfb2b4006a640d680411af024b06179".parse().unwrap());
assert_eq!(infos[1].to, Some("179631c363eef2cfec04f2354476f7b407ed031d".parse().unwrap()));
assert_eq!(infos[1].gas_limit, U256::from(150_000));
// ...
assert_eq!(infos[87].hash, "76da1628c18e0096ed0a24d37adf110ee39fea04c8bed36dfa7065c016f5d4d3".parse().unwrap());
assert_eq!(infos[87].to, Some("d2f81cd7a20d60c0d558496c7169a20968389b40".parse().unwrap()));
assert_eq!(infos[87].gas_limit, U256::from(36_195));
}
// eth_getBlockByNumber
#[tokio::test]
async fn test_tx_infos_parallel() {
let web3 = web3().expect("can instantiate web3");
let blocks = vec![BLOCK1, BLOCK2];
let mut stream = tx_infos_parallel(&web3, blocks.into_iter());
match stream.next().await {
None => assert!(false),
Some(infos) => assert_eq!(infos.len(), 88),
}
match stream.next().await {
None => assert!(false),
Some(infos) => assert_eq!(infos.len(), 47),
}
assert!(stream.next().await.is_none());
}
}
|
//! Generic encoding and decoding.
//!
//! This module contains the generic `Codec` trait and a protobuf codec
//! based on prost.
mod decode;
mod encode;
#[cfg(feature = "prost")]
mod prost;
#[cfg(test)]
mod tests;
pub use self::decode::Streaming;
pub(crate) use self::encode::{encode_client, encode_server};
#[cfg(feature = "prost")]
#[cfg_attr(docsrs, doc(cfg(feature = "prost")))]
pub use self::prost::ProstCodec;
pub use tokio_util::codec::{Decoder, Encoder};
use crate::Status;
/// Trait that knows how to encode and decode gRPC messages.
pub trait Codec: Default {
/// The encodable message.
type Encode: Send + 'static;
/// The decodable message.
type Decode: Send + 'static;
/// The encoder that can encode a message.
type Encoder: Encoder<Item = Self::Encode, Error = Status> + Send + Sync + 'static;
/// The encoder that can decode a message.
type Decoder: Decoder<Item = Self::Decode, Error = Status> + Send + Sync + 'static;
/// Fetch the encoder.
fn encoder(&mut self) -> Self::Encoder;
/// Fetch the decoder.
fn decoder(&mut self) -> Self::Decoder;
}
|
use directories::{ProjectDirs, UserDirs};
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use crate::Errors;
fn project_dir() -> Result<ProjectDirs, Errors> {
ProjectDirs::from("info", "Fuzen", "Melody").ok_or(Errors::FailedToGetAppDirectory)
}
#[derive(Debug)]
pub struct Settings {
pub volume: f32,
pub music: PathBuf,
pub prioritize_cwd: bool,
}
impl Settings {
pub fn new() -> Result<Settings, Errors> {
let project_dir = project_dir()?;
let mut config_file = project_dir.config_dir().to_owned();
let _ = ::std::fs::create_dir_all(&config_file).is_ok(); // Result doesnt matter
config_file.push("Config.melody");
log::info!("Config is located at: {:?}", config_file);
let mut settings = if !config_file.exists() {
Self::create_default(config_file)?
} else {
let file = ::std::fs::File::open(config_file).map_err(|_| Errors::FailedToGetConfig)?;
let mut volume: f32 = 0.25;
let mut prioritize_cwd: bool = false;
let mut music: Option<PathBuf> = None;
for line in BufReader::new(file).lines().flatten() {
if line.starts_with("volume=") {
if let Some(v) = line.get(7..) {
if let Ok(v) = v.parse() {
volume = v;
}
}
} else if line.starts_with("music=") {
if let Some(v) = line.get(6..) {
let p = PathBuf::from(v);
if p.exists() {
music = Some(p)
}
}
} else if line.starts_with("prioritize_cwd") {
if let Some(v) = line.get(15..) {
if let Ok(v) = v.parse() {
prioritize_cwd = v;
}
}
}
}
let music = match music {
Some(m) => m,
None => {
let user_dir = UserDirs::new().ok_or(Errors::FailedToGetUserDir)?;
user_dir
.audio_dir()
.ok_or(Errors::FailedToGetAudioDir)?
.to_owned()
}
};
Self {
volume,
prioritize_cwd,
music,
}
};
if let Ok(v) = ::std::env::var("MELODY_VOLUME") {
if let Ok(v) = v.parse() {
settings.volume = v;
}
}
if let Ok(v) = ::std::env::var("MELODY_MUSIC") {
let p = PathBuf::from(v);
if p.exists() {
settings.music = p;
}
}
if let Ok(v) = ::std::env::var("MELODY_PRIORITIZE_CWD") {
if let Ok(v) = v.parse() {
settings.prioritize_cwd = v;
}
}
Ok(settings)
}
fn create_default(config_file: PathBuf) -> Result<Self, Errors> {
let user_dir = UserDirs::new().ok_or(Errors::FailedToGetUserDir)?;
let audio_dir = user_dir
.audio_dir()
.ok_or(Errors::FailedToGetAudioDir)?
.to_owned();
let mut f = ::std::fs::File::create(config_file).map_err(|_| Errors::FailedToGetConfig)?;
let file_txt = format!(
"volume={}\nmusic={}\nprioritize_cwd={}",
0.25,
audio_dir.to_str().ok_or(Errors::FailedToGetAudioDir)?,
false
);
f.write_all(file_txt.as_bytes())
.map_err(|_| Errors::FailedToGetConfig)?;
Ok(Settings {
volume: 0.25,
music: audio_dir,
prioritize_cwd: false,
})
}
}
|
#![feature(try_trait)]
#![feature(map_into_keys_values)]
#![feature(hash_drain_filter)]
#![feature(hash_set_entry)]
#![feature(min_const_generics)]
mod utils;
//mod day1;
//mod day2;
//mod day3;
//mod day4;
//mod day5;
//mod day6;
//mod day7;
//mod day8;
//mod day9;
//mod day10;
//mod day11;
//mod day12;
//mod day13;
//mod day14;
//mod day15;
//mod day16;
//mod day17;
//mod day18;
//mod day19;
//mod day20;
//mod day21;
//mod day22;
//mod day23;
//mod day24;
mod day25;
/**
* Helpful links:
*
* Need to convert raw input to something easier to copy-paste?
* https://convert.town/replace-new-lines-with-commas
*/
fn main() {
//day1::day1();
//day2::day2();
//day3::day3();
//day4::day4();
//day5::day5();
//day6::day6();
//day7::day7();
//day8::day8();
//day9::day9();
//day10::day10();
//day11::day11();
//day12::day12();
//day13::day13();
//day14::day14();
//day15::day15();
//day16::day16();
//day17::day17();
//day18::day18();
//day19::day19();
//day20::day20();
//day21::day21();
//day22::day22();
//day23::day23();
//day24::day24();
day25::day25();
} |
use super::downcast::downcast_pf;
use super::error::RuntimeErr;
use super::pine_ref::PineRef;
use super::ref_data::RefData;
use super::series::Series;
use super::traits::{
Arithmetic, Category, Comparator, ComplexType, DataType, Negative, PineClass, PineFrom,
PineStaticType, PineType, SecondType, SimpleType,
};
// pine int type
pub type Int = Option<i64>;
impl Negative<Int> for Int {
fn negative(self) -> Int {
match self {
Some(i) => Some(-i),
None => None,
}
}
}
impl Arithmetic for Int {
fn add(self, other: Self) -> Self {
match (self, other) {
(Some(i1), Some(i2)) => Some(i1 + i2),
_ => None,
}
}
fn minus(self, other: Self) -> Self {
match (self, other) {
(Some(i1), Some(i2)) => Some(i1 - i2),
_ => None,
}
}
fn mul(self, other: Self) -> Self {
match (self, other) {
(Some(i1), Some(i2)) => Some(i1 * i2),
_ => None,
}
}
fn div(self, other: Self) -> Self {
match (self, other) {
(Some(i1), Some(i2)) => Some(i1 / i2),
_ => None,
}
}
fn rem(self, other: Self) -> Self {
match (self, other) {
(Some(i1), Some(i2)) => Some(i1 % i2),
_ => None,
}
}
}
impl PineStaticType for Int {
fn static_type() -> (DataType, SecondType) {
(DataType::Int, SecondType::Simple)
}
}
impl<'a> PineType<'a> for Int {
fn get_type(&self) -> (DataType, SecondType) {
<Self as PineStaticType>::static_type()
}
fn copy(&self) -> PineRef<'a> {
PineRef::Box(Box::new(self.clone()))
}
}
impl<'a> PineFrom<'a, Int> for Int {
// NA -> Int Float -> Int
fn explicity_from(t: PineRef<'a>) -> Result<RefData<Int>, RuntimeErr> {
match t.get_type() {
(DataType::Int, SecondType::Simple) => Ok(downcast_pf::<Int>(t).unwrap()),
(DataType::Int, SecondType::Series) => {
let s = downcast_pf::<Series<Int>>(t).unwrap();
Ok(RefData::new_box(s.get_current()))
}
(DataType::NA, SecondType::Simple) => {
let i: Int = None;
Ok(RefData::new_box(i))
}
(DataType::Float, SecondType::Simple) => {
let f: RefData<Float> = downcast_pf::<Float>(t).unwrap();
let i: Int = match *f {
Some(f) => Some(f as i64),
None => None,
};
Ok(RefData::new_box(i))
}
(DataType::Float, SecondType::Series) => {
let s = downcast_pf::<Series<Float>>(t).unwrap();
let i: Int = match s.get_current() {
Some(f) => Some(f as i64),
None => None,
};
Ok(RefData::new_box(i))
}
_ => Err(RuntimeErr::UnknownRuntimeErr),
}
}
// NA -> Int
fn implicity_from(t: PineRef<'a>) -> Result<RefData<Int>, RuntimeErr> {
match t.get_type() {
(DataType::Int, SecondType::Simple) => Ok(downcast_pf::<Int>(t).unwrap()),
(DataType::Int, SecondType::Series) => {
let s = downcast_pf::<Series<Int>>(t).unwrap();
Ok(RefData::new_box(s.get_current()))
}
(DataType::NA, _) => {
let i: Int = None;
Ok(RefData::new_box(i))
}
_ => Err(RuntimeErr::UnknownRuntimeErr),
}
}
}
impl<'a> SimpleType for Int {}
// pine float type
pub type Float = Option<f64>;
impl Negative<Float> for Float {
fn negative(self) -> Float {
match self {
Some(i) => Some(-i),
None => None,
}
}
}
impl Arithmetic for Float {
fn add(self, other: Self) -> Self {
match (self, other) {
(Some(i1), Some(i2)) => Some(i1 + i2),
_ => None,
}
}
fn minus(self, other: Self) -> Self {
match (self, other) {
(Some(i1), Some(i2)) => Some(i1 - i2),
_ => None,
}
}
fn mul(self, other: Self) -> Self {
match (self, other) {
(Some(i1), Some(i2)) => Some(i1 * i2),
_ => None,
}
}
fn div(self, other: Self) -> Self {
match (self, other) {
(Some(i1), Some(i2)) => {
let v = i1 / i2;
if v.is_nan() {
None
} else {
Some(v)
}
}
_ => None,
}
}
fn rem(self, other: Self) -> Self {
match (self, other) {
(Some(i1), Some(i2)) => Some(i1 % i2),
_ => None,
}
}
}
impl Comparator for Float {
fn gt(self, other: Self) -> bool {
match (self, other) {
(Some(v1), Some(v2)) => v1 > v2,
_ => false,
}
}
fn ge(self, other: Self) -> bool {
match (self, other) {
(Some(v1), Some(v2)) => v1 >= v2,
_ => false,
}
}
fn lt(self, other: Self) -> bool {
match (self, other) {
(Some(v1), Some(v2)) => v1 < v2,
_ => false,
}
}
fn le(self, other: Self) -> bool {
match (self, other) {
(Some(v1), Some(v2)) => v1 <= v2,
_ => false,
}
}
}
impl PineStaticType for Float {
fn static_type() -> (DataType, SecondType) {
(DataType::Float, SecondType::Simple)
}
}
impl<'a> PineType<'a> for Float {
fn get_type(&self) -> (DataType, SecondType) {
<Self as PineStaticType>::static_type()
}
fn copy(&self) -> PineRef<'a> {
PineRef::Box(Box::new(self.clone()))
}
}
pub fn int2float<'a>(i: Int) -> Float {
match i {
Some(i) => Some(i as f64),
None => None,
}
}
pub fn float2int<'a>(i: Float) -> Int {
match i {
Some(i) => Some(i as i64),
None => None,
}
}
impl<'a> PineFrom<'a, Float> for Float {
fn explicity_from(t: PineRef<'a>) -> Result<RefData<Float>, RuntimeErr> {
Self::implicity_from(t)
}
// NA => Float Int => Float
fn implicity_from(t: PineRef<'a>) -> Result<RefData<Float>, RuntimeErr> {
match t.get_type() {
(DataType::Float, SecondType::Simple) => Ok(downcast_pf::<Float>(t).unwrap()),
(DataType::Float, SecondType::Series) => {
let s = downcast_pf::<Series<Float>>(t).unwrap();
Ok(RefData::new_box(s.get_current()))
}
(DataType::NA, _) => {
let i: Float = None;
Ok(RefData::new_box(i))
}
(DataType::Int, SecondType::Simple) => {
let i = downcast_pf::<Int>(t).unwrap();
Ok(RefData::new_box(int2float(*i)))
}
(DataType::Int, SecondType::Series) => {
let s = downcast_pf::<Series<Int>>(t).unwrap();
Ok(RefData::new_box(int2float(s.get_current())))
}
_ => Err(RuntimeErr::UnknownRuntimeErr),
}
}
}
impl<'a> SimpleType for Float {}
// pine bool type
pub type Bool = bool;
impl PineStaticType for Bool {
fn static_type() -> (DataType, SecondType) {
(DataType::Bool, SecondType::Simple)
}
}
impl<'a> PineType<'a> for Bool {
fn get_type(&self) -> (DataType, SecondType) {
<Self as PineStaticType>::static_type()
}
fn copy(&self) -> PineRef<'a> {
PineRef::Box(Box::new(self.clone()))
}
}
impl<'a> PineFrom<'a, Bool> for Bool {
fn explicity_from(t: PineRef<'a>) -> Result<RefData<Bool>, RuntimeErr> {
Self::implicity_from(t)
}
// NA => Bool Float => Bool Int => Bool
fn implicity_from(t: PineRef<'a>) -> Result<RefData<Bool>, RuntimeErr> {
match t.get_type() {
(DataType::Bool, SecondType::Simple) => Ok(downcast_pf::<Bool>(t).unwrap()),
(DataType::Bool, SecondType::Series) => {
let s = downcast_pf::<Series<Bool>>(t).unwrap();
Ok(RefData::new_box(s.get_current()))
}
(DataType::NA, _) => {
let i: Bool = false;
Ok(RefData::new_box(i))
}
(DataType::Float, SecondType::Simple) => {
let f: RefData<Float> = downcast_pf::<Float>(t).unwrap();
let b: Bool = match *f {
Some(_) => true,
None => false,
};
Ok(RefData::new_box(b))
}
(DataType::Float, SecondType::Series) => {
let f: RefData<Series<Float>> = downcast_pf::<Series<Float>>(t).unwrap();
let b: Bool = match f.get_current() {
Some(_) => true,
None => false,
};
Ok(RefData::new_box(b))
}
(DataType::Int, SecondType::Simple) => {
let f: RefData<Int> = downcast_pf::<Int>(t).unwrap();
let b: Bool = match *f {
Some(_) => true,
None => false,
};
Ok(RefData::new_box(b))
}
(DataType::Int, SecondType::Series) => {
let f: RefData<Series<Int>> = downcast_pf::<Series<Int>>(t).unwrap();
let b: Bool = match f.get_current() {
Some(_) => true,
None => false,
};
Ok(RefData::new_box(b))
}
_ => Err(RuntimeErr::UnknownRuntimeErr),
}
}
}
impl SimpleType for Bool {}
// pine color type
#[derive(Debug, PartialEq, Clone, Default)]
pub struct Color<'a>(pub &'a str);
impl<'a> PineStaticType for Color<'a> {
fn static_type() -> (DataType, SecondType) {
(DataType::Color, SecondType::Simple)
}
}
impl<'a> PineType<'a> for Color<'a> {
fn get_type(&self) -> (DataType, SecondType) {
<Self as PineStaticType>::static_type()
}
fn copy(&self) -> PineRef<'a> {
PineRef::Box(Box::new(self.clone()))
}
}
impl<'a> PineFrom<'a, Color<'a>> for Color<'a> {
fn implicity_from(t: PineRef<'a>) -> Result<RefData<Color>, RuntimeErr> {
match t.get_type() {
(DataType::Color, SecondType::Simple) => Ok(downcast_pf::<Color>(t).unwrap()),
(DataType::Color, SecondType::Series) => {
let f: RefData<Series<Color>> = downcast_pf::<Series<Color>>(t).unwrap();
Ok(RefData::new_box(f.get_current()))
}
(DataType::NA, _) => Ok(RefData::new_box(Color(""))),
_ => Err(RuntimeErr::UnknownRuntimeErr),
}
}
}
impl<'a> SimpleType for Color<'a> {}
// pine na type
#[derive(Debug, PartialEq, Clone, Default)]
pub struct NA;
impl PineStaticType for NA {
fn static_type() -> (DataType, SecondType) {
(DataType::NA, SecondType::Simple)
}
}
impl<'a> PineType<'a> for NA {
fn get_type(&self) -> (DataType, SecondType) {
<Self as PineStaticType>::static_type()
}
fn copy(&self) -> PineRef<'a> {
PineRef::Box(Box::new(self.clone()))
}
}
impl<'a> PineFrom<'a, NA> for NA {
fn implicity_from(t: PineRef<'a>) -> Result<RefData<NA>, RuntimeErr> {
match t.get_type() {
(DataType::NA, _) => Ok(RefData::new_box(NA)),
_ => Err(RuntimeErr::UnknownRuntimeErr),
}
}
}
impl SimpleType for NA {}
// pine type that represent variable name
#[derive(Debug, PartialEq, Clone)]
pub struct PineVar<'a>(pub &'a str);
impl<'a> PineStaticType for PineVar<'a> {
fn static_type() -> (DataType, SecondType) {
(DataType::PineVar, SecondType::Simple)
}
}
impl<'a> PineType<'a> for PineVar<'a> {
fn get_type(&self) -> (DataType, SecondType) {
<Self as PineStaticType>::static_type()
}
fn copy(&self) -> PineRef<'a> {
PineRef::Box(Box::new(self.clone()))
}
}
impl<'a> PineFrom<'a, PineVar<'a>> for PineVar<'a> {}
impl<'a> SimpleType for PineVar<'a> {}
// pine tuple type
#[derive(PartialEq, Debug)]
pub struct Tuple<'a>(pub Vec<PineRef<'a>>);
impl<'a> Clone for Tuple<'a> {
fn clone(&self) -> Self {
Tuple(self.0.iter().map(|v| v.copy_inner()).collect())
}
}
impl<'a> PineStaticType for Tuple<'a> {
fn static_type() -> (DataType, SecondType) {
(DataType::Tuple, SecondType::Simple)
}
}
impl<'a> PineType<'a> for Tuple<'a> {
fn get_type(&self) -> (DataType, SecondType) {
<Self as PineStaticType>::static_type()
}
fn copy(&self) -> PineRef<'a> {
let new_vec = self.0.iter().map(|it| it.copy_inner()).collect();
PineRef::Box(Box::new(Tuple(new_vec)))
}
}
impl<'a> PineFrom<'a, Tuple<'a>> for Tuple<'a> {
fn implicity_from(t: PineRef<'a>) -> Result<RefData<Tuple<'a>>, RuntimeErr> {
match t.get_type() {
(DataType::Tuple, _) => Ok(downcast_pf::<Tuple>(t).unwrap()),
_ => Err(RuntimeErr::UnknownRuntimeErr),
}
}
}
impl<'a> SimpleType for Tuple<'a> {}
impl PineStaticType for String {
fn static_type() -> (DataType, SecondType) {
(DataType::String, SecondType::Simple)
}
}
// pine string type
impl<'a> PineType<'a> for String {
fn get_type(&self) -> (DataType, SecondType) {
<Self as PineStaticType>::static_type()
}
fn category(&self) -> Category {
Category::Complex
}
fn copy(&self) -> PineRef<'a> {
PineRef::new_rc(self.clone())
}
}
impl<'a> PineFrom<'a, String> for String {
fn implicity_from(_t: PineRef<'a>) -> Result<RefData<String>, RuntimeErr> {
match _t.get_type() {
(DataType::String, SecondType::Simple) => Ok(downcast_pf::<String>(_t)?),
(DataType::String, SecondType::Series) => {
let f: RefData<Series<String>> = downcast_pf::<Series<String>>(_t).unwrap();
Ok(RefData::new_rc(f.get_current()))
}
(DataType::NA, _) => Ok(RefData::new_rc(String::from(""))),
_ => Err(RuntimeErr::NotSupportOperator),
}
}
}
impl ComplexType for String {}
#[cfg(test)]
mod tests {
use super::super::primitive::Int;
use super::*;
#[test]
fn int_test() {
assert_eq!(
<Int as PineStaticType>::static_type(),
(DataType::Int, SecondType::Simple)
);
assert_eq!(
<Int as PineType>::get_type(&Int::default()),
(DataType::Int, SecondType::Simple)
);
assert!(Int::implicity_from(PineRef::new_box(NA)).is_ok());
assert!(Int::implicity_from(PineRef::new(Series::from(NA))).is_ok());
assert_eq!(
Int::implicity_from(PineRef::new_box(Some(1))),
Ok(RefData::new(Some(1)))
);
assert_eq!(
Int::implicity_from(PineRef::new(Series::from(Some(1)))),
Ok(RefData::new(Some(1)))
);
assert!(Int::explicity_from(PineRef::new_box(NA)).is_ok());
assert_eq!(
Int::explicity_from(PineRef::new_box(Some(1))),
Ok(RefData::new(Some(1)))
);
assert_eq!(
Int::explicity_from(PineRef::new(Series::from(Some(1)))),
Ok(RefData::new(Some(1)))
);
assert_eq!(
Int::explicity_from(PineRef::new_box(Some(1f64))),
Ok(RefData::new(Some(1)))
);
assert_eq!(
Int::explicity_from(PineRef::new(Series::from(Some(1f64)))),
Ok(RefData::new(Some(1)))
);
}
#[test]
fn float_test() {
assert_eq!(
<Float as PineStaticType>::static_type(),
(DataType::Float, SecondType::Simple)
);
assert_eq!(
<Float as PineType>::get_type(&Default::default()),
(DataType::Float, SecondType::Simple)
);
assert_eq!(
Float::implicity_from(PineRef::new_box(NA)),
Ok(RefData::new(None))
);
assert_eq!(
Float::implicity_from(PineRef::new(Series::from(NA))),
Ok(RefData::new(None))
);
assert_eq!(
Float::implicity_from(PineRef::new_box(Some(3f64))),
Ok(RefData::new(Some(3f64)))
);
assert_eq!(
Float::implicity_from(PineRef::new(Series::from(Some(3f64)))),
Ok(RefData::new(Some(3f64)))
);
assert_eq!(
Float::implicity_from(PineRef::new_box(Some(3i64))),
Ok(RefData::new(Some(3f64)))
);
assert_eq!(
Float::implicity_from(PineRef::new(Series::from(Some(3i64)))),
Ok(RefData::new_box(Some(3f64)))
);
assert_eq!(
Float::explicity_from(PineRef::new_box(NA)),
Ok(RefData::new(None))
);
assert_eq!(
Float::explicity_from(PineRef::new(Series::from(NA))),
Ok(RefData::new(None))
);
assert_eq!(
Float::explicity_from(PineRef::new_box(Some(3f64))),
Ok(RefData::new(Some(3f64)))
);
assert_eq!(
Float::explicity_from(PineRef::new(Series::from(Some(3f64)))),
Ok(RefData::new(Some(3f64)))
);
assert_eq!(
Float::explicity_from(PineRef::new_box(Some(3i64))),
Ok(RefData::new(Some(3f64)))
);
assert_eq!(
Float::explicity_from(PineRef::new(Series::from(Some(3i64)))),
Ok(RefData::new_box(Some(3f64)))
);
}
fn from_bool<'a, D>(val: D) -> Result<RefData<Bool>, RuntimeErr>
where
D: PineType<'a> + 'a,
{
Bool::implicity_from(PineRef::new(val))
}
fn ex_from_bool<'a, D>(val: D) -> Result<RefData<Bool>, RuntimeErr>
where
D: PineType<'a> + 'a,
{
Bool::explicity_from(PineRef::new(val))
}
#[test]
fn bool_test() {
assert_eq!(
<Bool as PineStaticType>::static_type(),
(DataType::Bool, SecondType::Simple)
);
assert_eq!(
<Bool as PineType>::get_type(&Bool::default()),
(DataType::Bool, SecondType::Simple)
);
assert_eq!(from_bool(true), Ok(RefData::new_box(true)));
assert_eq!(from_bool(false), Ok(RefData::new_box(false)));
assert_eq!(from_bool(Series::from(true)), Ok(RefData::new_box(true)));
assert_eq!(from_bool(NA), Ok(RefData::new_box(false)));
assert_eq!(from_bool(Series::from(NA)), Ok(RefData::new_box(false)));
assert_eq!(from_bool(Some(3i64)), Ok(RefData::new_box(true)));
assert_eq!(from_bool(None as Int), Ok(RefData::new_box(false)));
assert_eq!(
from_bool(Series::from(Some(3i64))),
Ok(RefData::new_box(true))
);
assert_eq!(from_bool(Some(3f64)), Ok(RefData::new_box(true)));
assert_eq!(from_bool(None as Float), Ok(RefData::new_box(false)));
assert_eq!(
from_bool(Series::from(Some(3f64))),
Ok(RefData::new_box(true))
);
assert_eq!(ex_from_bool(true), Ok(RefData::new_box(true)));
assert_eq!(ex_from_bool(false), Ok(RefData::new_box(false)));
assert_eq!(ex_from_bool(Series::from(true)), Ok(RefData::new_box(true)));
assert_eq!(ex_from_bool(NA), Ok(RefData::new_box(false)));
assert_eq!(ex_from_bool(Series::from(NA)), Ok(RefData::new_box(false)));
assert_eq!(ex_from_bool(Some(3i64)), Ok(RefData::new_box(true)));
assert_eq!(ex_from_bool(None as Int), Ok(RefData::new_box(false)));
assert_eq!(
ex_from_bool(Series::from(Some(3i64))),
Ok(RefData::new_box(true))
);
assert_eq!(ex_from_bool(Some(3f64)), Ok(RefData::new_box(true)));
assert_eq!(ex_from_bool(None as Float), Ok(RefData::new_box(false)));
assert_eq!(
ex_from_bool(Series::from(Some(3f64))),
Ok(RefData::new_box(true))
);
}
#[test]
fn color_test() {
assert_eq!(Color::static_type(), (DataType::Color, SecondType::Simple));
assert_eq!(
Color::get_type(&Color("")),
(DataType::Color, SecondType::Simple)
);
}
}
|
#[macro_use] extern crate random_number;
extern crate chrono;
extern crate ctrlc;
extern crate redis;
#[macro_use] extern crate colour;
pub mod exchange;
pub mod parser;
pub mod account;
pub mod buffer;
pub mod database;
pub use crate::exchange::{Exchange, Market, Request};
pub use crate::account::{Users};
pub use crate::buffer::{BufferCollection, UpdateCategories};
use std::env;
use std::process;
use std::io::{self, prelude::*};
use postgres::{Client, NoTls};
use std::thread;
use std::sync::mpsc;
use std::time::Instant;
// Helps us determine what each thread will work on.
pub enum Category {
InsertNew,
UpdateKnown,
InsertPending,
DeletePending,
UpdateTotal,
UpdateMarketStats,
InsertNewTrades
}
// Helps manage the workload.
pub struct WorkerThreads<T> {
pub threads: Vec<thread::JoinHandle<T>>, // Holds thread handles
pub senders: Vec<mpsc::Sender<(UpdateCategories, Category)>>, // Each thread receives only 1 category, all others are empty.
pub receivers: Vec<mpsc::Receiver<bool>> // When a thread is finished flushing it's category, it writes `true` to the channel.
}
fn main() {
let mut exchange = Exchange::new(); // Our central exchange, everything happens here.
let mut users = Users::new(); // All our users are stored here.
let mut buffers = BufferCollection::new(200000, 200000); // In-memory buffers that will batch write to DB.
let mut client = Client::connect("host=localhost user=postgres dbname=rustx", NoTls)
.expect("Failed to connect to Database. Please ensure it is up and running.");
let redis_client = redis::Client::open("redis://127.0.0.1/").expect("Failed to open redis");
let mut redis_conn = redis_client.get_connection().expect("Failed to connect to redis");
dark_green!("Connected to database.\n");
let start = Instant::now();
let user_count = Instant::now();
// Reads total # users
users.direct_update_total(&mut client);
let user_count = user_count.elapsed().as_millis();
/* TODO: Should we store the top N buys and sells in each market, rather than all?
* This would decrease the amount of RAM, and increases the computation speed.
* I think this needs to wait for a move to Redis, as we currently read users
* pending orders into their accounts by pulling this data
* - (see fetch_account_pending_orders).
**/
println!("Initializing exchange...");
dark_green!("\tTime elapsed to get user count: {} ms\n", user_count);
let market_time = Instant::now();
database::populate_exchange_markets(&mut exchange, &mut client); // Fill the pending orders of the markets
let market_time = market_time.elapsed().as_millis();
dark_green!("\tTime elapsed to populate markets: {} ms\n", market_time);
let stats_time = Instant::now();
database::populate_market_statistics(&mut exchange, &mut client); // Fill the statistics for each market
let stats_time = stats_time.elapsed().as_millis();
dark_green!("\tTime elapsed to populate market stats: {} ms\n", stats_time);
let x_stats_time = Instant::now();
database::populate_exchange_statistics(&mut exchange, &mut client); // Fill the statistics for the exchange
let x_stats_time = x_stats_time.elapsed().as_millis();
dark_green!("\tTime elapsed to populate exchange stats: {} ms\n", x_stats_time);
let has_trades_time = Instant::now();
database::populate_has_trades(&mut exchange, &mut client); // Fill the has_trades map for the exchange
let has_trades_time = has_trades_time.elapsed().as_millis();
dark_green!("\tTime elapsed to populate has_trades: {} ms\n", has_trades_time);
let end = start.elapsed().as_millis();
dark_green!("\nTotal Setup Time elapsed : {} ms\n", end);
let argument = match parser::command_args(env::args()) {
Ok(arg) => arg,
Err(e) => {
eprintln!("{}", e);
process::exit(1);
}
};
// Set sigINT/sigTERM handlers
// TODO: If we want the sigINT handler thread to be capable of flushing the buffers, we'll need
// to share the buffers with it. To do this, we will have to wrap the buffers inside a mutex
// and wrap the mutex in an Arc.
//
// This might not be too technically difficult, but I'm not sure I like the behaviour:
// - It implies that we can shut the exchange while an order is being processed, potentially
// resulting in inconsistent state.
// - To solve this, we would have to have some other shared var that says the state is
// consistent, and since we're shutting down no more orders can be placed.
ctrlc::set_handler(|| {
println!("Please use the EXIT command, still figuring out how to do a controlled shutdown...");
}).expect("Error setting Ctrl-C handler");
let (tx, rx) = mpsc::channel();
buffers.set_transmitter(tx);
/* This thread's job is to read categorized buffer data and write it to the database.
*
* It behaves in the following way:
* 1. Set up worker threads and additional channels
* loop {
* 2. Read the categories, if we got None, we must shutdown immediately.
* 3. If we got Some(data), send each component to the appropriate worker thread
* to be written to the database.
* }
*
**/
let handler = thread::spawn(move || {
let mut workers = WorkerThreads {
threads: Vec::new(),
senders: Vec::new(),
receivers: Vec::new()
};
// These are our worker threads. The buffer handling thread
// will write each category to its respective worker thread to be
// written to the database.
for _ in 0..7 {
// Set up the transmitter x receiver channel for sending data to worker,
// then set up response channel to get `true` message of completion.
let (transmitter, receiver) = mpsc::channel();
let (response_tx, response_rx) = mpsc::channel();
workers.senders.push(transmitter);
workers.receivers.push(response_rx);
let mut conn = Client::connect("host=localhost user=postgres dbname=rustx", NoTls)
.expect("Failed to connect to Database. Please ensure it is up and running.");
workers.threads.push(thread::spawn(move || {
loop {
let (data, category_type): (UpdateCategories, Category) = match receiver.recv() {
Ok((data, category_type)) => (data, category_type),
Err(_) => {
return;
}
};
// Perform the database write here depending on the type of category.
match category_type {
Category::InsertNew => BufferCollection::launch_insert_orders(&data.insert_orders, &mut conn),
Category::UpdateKnown => BufferCollection::launch_update_orders(&data.update_orders, &mut conn),
Category::InsertPending => BufferCollection::launch_insert_pending_orders(&data.insert_pending, &mut conn),
Category::DeletePending => BufferCollection::launch_delete_pending_orders(&data.delete_pending, &mut conn),
Category::UpdateTotal => BufferCollection::launch_exchange_stats_update(data.total_orders, &mut conn),
Category::UpdateMarketStats => BufferCollection::launch_update_market(&data.update_markets, &mut conn),
Category::InsertNewTrades => BufferCollection::launch_insert_trades(&data.insert_trades, &mut conn)
}
// Return the successful response message
response_tx.send(true).unwrap();
}
}));
}
// This is the main loop for the Buffer handling thread.
// We read the categories from the main thread, then send them
// to the worker threads. On shutdown, we clean everything up.
loop {
let categories: UpdateCategories = match rx.recv() {
Ok(option) => match option {
Some(data) => data,
// We write None to channel on shutdown.
// Better way would be to close Sender, but I'm having trouble with that...
None => {
dark_blue!("[Buffer Thread]: received shutdown request.\n");
drop(rx);
dark_blue!("[Buffer Thread]: waiting on worker threads to complete...\n");
for tx in workers.senders {
drop(tx);
}
for handle in workers.threads {
handle.join().unwrap();
}
return;
}
},
Err(_) => {
return;
}
};
dark_blue!("[BUFFER THREAD]: Initiating database writes.\n");
BufferCollection::launch_batch_db_updates(&categories, &mut workers);
dark_blue!("[BUFFER THREAD]: Writes successfully flushed.\n");
}
});
// Read from file mode
if !argument.interactive {
for line in argument.reader.unwrap().lines() {
match line {
Ok(input) => {
let raw = input.clone();
let request: Request = match parser::tokenize_input(input) {
Ok(req) => req,
Err(_) => {
println!("WARNING: [{}] is not a valid request.", raw);
continue;
}
};
println!("Servicing Request: {}", raw);
// Our input has been validated. We can now attempt to service the request.
// If we got an exit request, exit the loop and treat it like EOF.
if let Request::ExitReq = request {
break;
}
// Our input has been validated. We can now attempt to service the request.
parser::service_request(request, &mut exchange, &mut users, &mut buffers, &mut client, &mut redis_conn);
},
Err(_) => return
}
// Make sure our buffer states are accurate.
buffers.update_buffer_states();
// If order buffer was drained, we can reset our cached values modified field.
if buffers.transmit_buffer_data(&exchange) {
users.reset_users_modified();
// Set all market stats modified to false
for (_key, entry) in exchange.statistics.iter_mut() {
entry.modified = false;
}
}
}
let exit = Request::ExitReq;
parser::service_request(exit, &mut exchange, &mut users, &mut buffers, &mut client, &mut redis_conn);
} else {
// User interface version
dark_yellow!("
_ __ __ __ ____ __ _ __
| | / /__ / /________ ____ ___ ___ / /_____ / __ \\__ _______/ /| |/ /
| | /| / / _ \\/ / ___/ __ \\/ __ `__ \\/ _ \\ / __/ __ \\ / /_/ / / / / ___/ __/ /
| |/ |/ / __/ / /__/ /_/ / / / / / / __/ / /_/ /_/ / / _, _/ /_/ (__ ) /_/ |
|__/|__/\\___/_/\\___/\\____/_/ /_/ /_/\\___/ \\__/\\____/ /_/ |_|\\__,_/____/\\__/_/|_|\n");
print_instructions();
loop {
dark_yellow!("\n---What would you like to do?---\n");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let request: Request = match parser::tokenize_input(input) {
Ok(req) => req,
Err(_) => continue
};
// If we got an exit request, service it and exit loop.
if let Request::ExitReq = request {
parser::service_request(request, &mut exchange, &mut users, &mut buffers, &mut client, &mut redis_conn);
break;
}
// Our input has been validated. We can now attempt to service the request.
parser::service_request(request, &mut exchange, &mut users, &mut buffers, &mut client, &mut redis_conn);
// Make sure our buffer states are accurate.
buffers.update_buffer_states();
// If order buffer was drained, we can reset our cached values modified field.
if buffers.transmit_buffer_data(&exchange) {
users.reset_users_modified();
// Set all market stats modified to false
for (_key, entry) in exchange.statistics.iter_mut() {
entry.modified = false;
}
}
}
}
// Wait for the buffer thread to complete.
handler.join().unwrap();
println!("\nShutdown sequence complete. Goodbye!");
}
pub fn print_instructions() {
let buy_price = 167.34;
let buy_amount = 24;
let sell_price = 999.85;
let sell_amount = 12;
let user = "example";
let pass = "pass";
println!("Usage:");
println!("\tOrders: ACTION(buy/sell) SYMBOL(ticker) QUANTITY PRICE USERNAME PASSWORD");
println!("\t\tEx: buy GME {} {} {} {}\t<---- Sends a buy order for {} shares of GME at ${} a share. Order is placed by {} with password {}.", buy_amount, buy_price, user, pass, buy_amount, buy_price, user, pass);
println!("\t\tEx: sell GME {} {} {} {}\t<---- Sends a sell order for {} shares of GME at ${} a share. Order is placed by {} with password {}.\n", sell_amount, sell_price, user, pass, sell_amount, sell_price, user, pass);
println!("\tCancel Request: cancel SYMBOL ORDER_ID USERNAME PASSWORD");
println!("\t\tEx: cancel AAPL 4 admin pass\t\t<---- Cancels the order with ID 4 in the AAPL market, provided user (admin) placed it.\n");
println!("\tInfo Requests: ACTION SYMBOL(ticker)");
println!("\t\tEx: price GME\t\t<---- gives latest price an order was filled at.");
println!("\t\tEx: show GME\t\t<---- shows statistics for the GME market.");
println!("\t\tEx: history GME\t\t<---- shows past orders that were filled in the GME market.\n");
println!("\tSimulation Requests: simulate NUM_USERS NUM_MARKETS NUM_ORDERS");
println!("\t\tEx: simulate 300 500 10000\t<---- Simulates 10000 random buy/sell orders in 500 markets, with 300 random users.\n");
println!("\tAccount Requests: account create/show USERNAME PASSWORD");
println!("\t\tEx: account create bigMoney notHashed\n\n");
println!("\tTo perform a graceful shutdown and update the database, type EXIT.\n");
println!("\tYou can see these instructions at any point by typing help.");
}
|
use std::path::{PathBuf, Path};
use std::io::prelude::*;
use std::io::Error;
use std::fs::File;
use std::fs;
use rustc_serialize::json::Json;
use semver::Version;
use semver::VersionReq;
fn match_current_node(package_version: String, installed_versions: Vec<String>) -> Option<String> {
let installed_semver = installed_versions.iter().map(|v| Version::parse(&v).unwrap());
let version_requirement = VersionReq::parse(&package_version).unwrap();
for installed in installed_semver {
if version_requirement.matches(&installed) {
return Some(installed.to_string())
}
}
None
}
fn match_legacy_node(package_version: String, installed_versions: Vec<String>) -> Option<String> {
let installed_vers = installed_versions.iter().map(|v| Version::parse(&v).unwrap());
let version_requirement = match Version::parse(&package_version) {
Ok(v) => v,
Err(_) => return None
};
for installed in installed_vers {
if version_requirement == installed {
return Some(installed.to_string())
}
}
None
}
pub struct Selector {
package_path: PathBuf
}
impl Selector {
pub fn new(cwd: &Path) -> Selector {
let package_file = cwd.join("package.json");
Selector { package_path: package_file }
}
pub fn has_package_json(&self) -> bool {
match fs::metadata(&self.package_path){
Ok(metadata) => metadata.is_file(),
Err(_) => false
}
}
pub fn specified_version(&self) -> Result<String, String> {
let package_file = match self.read_package_json() {
Ok(file) => file,
Err(_) => return Err("No package.json found".to_string())
};
match self.find_engine_key(&package_file) {
Some(version) => Ok(version.replace("\"", "")),
None => Err("No node engine specified".to_string())
}
}
pub fn match_version(&self, package_version: String, installed_versions: Vec<String>) -> Option<String> {
let version = Version::parse(&package_version).unwrap();
if version.major == 0 {
match_legacy_node(package_version, installed_versions)
}
else {
match_current_node(package_version, installed_versions)
}
}
fn find_engine_key(&self, json_file: &String) -> Option<String> {
let json = Json::from_str(&json_file).unwrap();
match json.find_path(&["engines", "node"]) {
Some(key) => Some(key.to_string()),
None => None
}
}
fn read_package_json(&self) -> Result<String, Error> {
let mut f = try!(File::open(&self.package_path));
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(err) => Err(err)
}
}
}
|
use proptest::{prelude::*, *};
use rand::{distributions::Bernoulli, seq::SliceRandom};
use crate::{cnf::CnfFormula, lit::Lit};
/// Generate small hard unsat instances.
///
/// Implementation of http://www.cs.qub.ac.uk/~i.spence/sgen/ but with random partitions
pub fn sgen_unsat_formula(
blocks: impl Strategy<Value = usize>,
) -> impl Strategy<Value = CnfFormula> {
blocks.prop_flat_map(|blocks| {
collection::vec(bool::ANY, blocks * 4 + 1).prop_perturb(|polarity, mut rng| {
let mut clauses: Vec<Vec<Lit>> = vec![];
let mut lits = polarity
.into_iter()
.enumerate()
.map(|(index, polarity)| Lit::from_index(index, polarity))
.collect::<Vec<_>>();
for &invert in [false, true].iter() {
lits.shuffle(&mut rng);
for block in lits.chunks_exact(4) {
for a in 0..4 {
for b in 0..a {
for c in 0..b {
let mut clause =
vec![block[a] ^ invert, block[b] ^ invert, block[c] ^ invert];
clause.shuffle(&mut rng);
clauses.push(clause);
}
}
}
}
let &lit_a = lits.last().unwrap();
for b in 0..4 {
for c in 0..b {
let mut clause = vec![lit_a ^ invert, lits[b] ^ invert, lits[c] ^ invert];
clause.shuffle(&mut rng);
clauses.push(clause);
}
}
}
clauses.shuffle(&mut rng);
CnfFormula::from(clauses)
})
})
}
/// Generate a sat instance.
///
/// This generates a random full assignment and then only generates clauses compatible with that
/// assignment.
pub fn sat_formula(
vars: impl Strategy<Value = usize>,
clause_count: impl Strategy<Value = usize>,
density: impl Strategy<Value = f64>,
polarity_dist: impl Strategy<Value = f64>,
) -> impl Strategy<Value = CnfFormula> {
(vars, clause_count, density, polarity_dist).prop_flat_map(
|(vars, clause_count, density, polarity_dist)| {
let density = Bernoulli::new(density).unwrap();
let polarity_dist = Bernoulli::new(polarity_dist).unwrap();
collection::vec(bool::ANY, vars).prop_perturb(move |polarity, mut rng| {
let mut clauses: Vec<Vec<Lit>> = vec![];
let lits = polarity
.into_iter()
.enumerate()
.map(|(index, polarity)| Lit::from_index(index, polarity))
.collect::<Vec<_>>();
for _ in 0..clause_count {
let &fixed_lit = lits.choose(&mut rng).unwrap();
let mut clause = vec![fixed_lit];
for &lit in lits.iter() {
if lit != fixed_lit && rng.sample(density) {
clause.push(lit ^ rng.sample(polarity_dist));
}
}
clause.shuffle(&mut rng);
clauses.push(clause);
}
clauses.shuffle(&mut rng);
CnfFormula::from(clauses)
})
},
)
}
/// Generates a conditional pigeon hole principle formula.
pub fn conditional_pigeon_hole(
columns: impl Strategy<Value = usize>,
extra_rows: impl Strategy<Value = usize>,
) -> impl Strategy<Value = (Vec<Lit>, usize, CnfFormula)> {
(columns, extra_rows).prop_flat_map(|(columns, extra_rows)| {
let rows = columns + extra_rows;
let vars = (columns + 1) * rows;
collection::vec(bool::ANY, vars).prop_perturb(move |polarity, mut rng| {
let mut clauses: Vec<Vec<Lit>> = vec![];
let lits = polarity
.into_iter()
.enumerate()
.map(|(index, polarity)| Lit::from_index(index, polarity))
.collect::<Vec<_>>();
for i in 1..columns + 1 {
for j in 0..rows {
for k in 0..j {
let mut clause = [lits[i * rows + j], lits[i * rows + k]];
clause.shuffle(&mut rng);
clauses.push(clause[..].to_owned());
}
}
}
for j in 0..rows {
let mut clause: Vec<_> = (0..columns + 1).map(|i| !lits[i * rows + j]).collect();
clause.shuffle(&mut rng);
clauses.push(clause[..].to_owned());
}
clauses.shuffle(&mut rng);
(lits[0..rows].to_owned(), columns, CnfFormula::from(clauses))
})
})
}
|
#![allow(warnings)]
use rodio::Sink;
use std::fs::File;
use std::io::BufReader;
fn main() {
let (_stream, handle) = rodio::OutputStream::try_default().unwrap();
// load the music
let music = File::open("assets/music/spacelifeNo14.ogg").unwrap();
let source = rodio::Decoder::new(BufReader::new(music)).unwrap();
let sink = rodio::Sink::try_new(&handle).unwrap();
println!("{}", sink.empty());
sink.append(source);
println!("{}", sink.empty());
loop {}
}
|
//! This module represents the logoff request and response.
//! The SMB2 LOGOFF Request packet is sent by the client to request termination of a particular session.
//! This request is composed of an SMB2 header, followed by this request structure.
//! The SMB2 LOGOFF Response packet is sent by the server to confirm that an SMB2 LOGOFF Request was completed successfully.
//! This response is composed of an SMB2 header, followed by this request structure.
/// logoff request size of 4 bytes
const STRUCTURE_SIZE: &[u8; 2] = b"\x04\x00";
/// A struct that represents a logoff request and response.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LogOff {
/// StructureSize (2 bytes): The client/server MUST set this field to 4,
/// indicating the size of the request structure not including the header.
structure_size: Vec<u8>,
/// Reserved (2 bytes): This field MUST NOT be used and MUST be reserved.
/// The client/server MUST set this to 0, and the server/client MUST ignore it on receipt.
reserved: Vec<u8>,
}
impl LogOff {
/// Creates a new Logoff instance.
pub fn default() -> Self {
LogOff {
structure_size: STRUCTURE_SIZE.to_vec(),
reserved: b"\x00\x00".to_vec(),
}
}
}
#[cfg(test)]
mod tests {
use super::LogOff;
#[test]
fn new_logoff() {
let logoff = LogOff::default();
assert_eq!(logoff.structure_size, b"\x04\x00".to_vec());
assert_eq!(logoff.reserved, b"\x00\x00".to_vec())
}
}
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use super::universal_regions::UniversalRegions;
use rustc::hir::def_id::DefId;
use rustc::infer::InferCtxt;
use rustc::infer::NLLRegionVariableOrigin;
use rustc::infer::RegionVariableOrigin;
use rustc::infer::SubregionOrigin;
use rustc::infer::region_constraints::VarOrigins;
use rustc::mir::{ClosureOutlivesRequirement, ClosureRegionRequirements, Location, Mir};
use rustc::ty::{self, RegionVid};
use rustc_data_structures::indexed_vec::IndexVec;
use rustc_data_structures::fx::FxHashSet;
use std::fmt;
use std::rc::Rc;
use syntax_pos::Span;
mod annotation;
mod dump_mir;
mod graphviz;
mod values;
use self::values::{RegionValueElements, RegionValues};
pub struct RegionInferenceContext<'tcx> {
/// Contains the definition for every region variable. Region
/// variables are identified by their index (`RegionVid`). The
/// definition contains information about where the region came
/// from as well as its final inferred value.
definitions: IndexVec<RegionVid, RegionDefinition<'tcx>>,
/// Maps from points/universal-regions to a `RegionElementIndex`.
elements: Rc<RegionValueElements>,
/// The liveness constraints added to each region. For most
/// regions, these start out empty and steadily grow, though for
/// each universally quantified region R they start out containing
/// the entire CFG and `end(R)`.
liveness_constraints: RegionValues,
/// The final inferred values of the inference variables; `None`
/// until `solve` is invoked.
inferred_values: Option<RegionValues>,
/// The constraints we have accumulated and used during solving.
constraints: Vec<Constraint>,
/// Information about the universally quantified regions in scope
/// on this function and their (known) relations to one another.
universal_regions: UniversalRegions<'tcx>,
}
struct RegionDefinition<'tcx> {
/// Why we created this variable. Mostly these will be
/// `RegionVariableOrigin::NLL`, but some variables get created
/// elsewhere in the code with other causes (e.g., instantiation
/// late-bound-regions).
origin: RegionVariableOrigin,
/// True if this is a universally quantified region. This means a
/// lifetime parameter that appears in the function signature (or,
/// in the case of a closure, in the closure environment, which of
/// course is also in the function signature).
is_universal: bool,
/// If this is 'static or an early-bound region, then this is
/// `Some(X)` where `X` is the name of the region.
external_name: Option<ty::Region<'tcx>>,
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Constraint {
// NB. The ordering here is not significant for correctness, but
// it is for convenience. Before we dump the constraints in the
// debugging logs, we sort them, and we'd like the "super region"
// to be first, etc. (In particular, span should remain last.)
/// The region SUP must outlive SUB...
sup: RegionVid,
/// Region that must be outlived.
sub: RegionVid,
/// At this location.
point: Location,
/// Where did this constraint arise?
span: Span,
}
impl<'tcx> RegionInferenceContext<'tcx> {
/// Creates a new region inference context with a total of
/// `num_region_variables` valid inference variables; the first N
/// of those will be constant regions representing the free
/// regions defined in `universal_regions`.
pub fn new(
var_origins: VarOrigins,
universal_regions: UniversalRegions<'tcx>,
mir: &Mir<'tcx>,
) -> Self {
let num_region_variables = var_origins.len();
let num_universal_regions = universal_regions.len();
let elements = &Rc::new(RegionValueElements::new(mir, num_universal_regions));
// Create a RegionDefinition for each inference variable.
let definitions = var_origins
.into_iter()
.map(|origin| RegionDefinition::new(origin))
.collect();
let mut result = Self {
definitions,
elements: elements.clone(),
liveness_constraints: RegionValues::new(elements, num_region_variables),
inferred_values: None,
constraints: Vec::new(),
universal_regions,
};
result.init_universal_regions();
result
}
/// Initializes the region variables for each universally
/// quantified region (lifetime parameter). The first N variables
/// always correspond to the regions appearing in the function
/// signature (both named and anonymous) and where clauses. This
/// function iterates over those regions and initializes them with
/// minimum values.
///
/// For example:
///
/// fn foo<'a, 'b>(..) where 'a: 'b
///
/// would initialize two variables like so:
///
/// R0 = { CFG, R0 } // 'a
/// R1 = { CFG, R0, R1 } // 'b
///
/// Here, R0 represents `'a`, and it contains (a) the entire CFG
/// and (b) any universally quantified regions that it outlives,
/// which in this case is just itself. R1 (`'b`) in contrast also
/// outlives `'a` and hence contains R0 and R1.
fn init_universal_regions(&mut self) {
// Update the names (if any)
for (external_name, variable) in self.universal_regions.named_universal_regions() {
self.definitions[variable].external_name = Some(external_name);
}
// For each universally quantified region X:
for variable in self.universal_regions.universal_regions() {
// These should be free-region variables.
assert!(match self.definitions[variable].origin {
RegionVariableOrigin::NLL(NLLRegionVariableOrigin::FreeRegion) => true,
_ => false,
});
self.definitions[variable].is_universal = true;
// Add all nodes in the CFG to liveness constraints
for point_index in self.elements.all_point_indices() {
self.liveness_constraints.add(variable, point_index);
}
// Add `end(X)` into the set for X.
self.liveness_constraints.add(variable, variable);
}
}
/// Returns an iterator over all the region indices.
pub fn regions(&self) -> impl Iterator<Item = RegionVid> {
self.definitions.indices()
}
/// Given a universal region in scope on the MIR, returns the
/// corresponding index.
///
/// (Panics if `r` is not a registered universal region.)
pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
self.universal_regions.to_region_vid(r)
}
/// Returns true if the region `r` contains the point `p`.
///
/// Panics if called before `solve()` executes,
pub fn region_contains_point(&self, r: RegionVid, p: Location) -> bool {
let inferred_values = self.inferred_values
.as_ref()
.expect("region values not yet inferred");
inferred_values.contains(r, p)
}
/// Returns access to the value of `r` for debugging purposes.
pub(super) fn region_value_str(&self, r: RegionVid) -> String {
let inferred_values = self.inferred_values
.as_ref()
.expect("region values not yet inferred");
inferred_values.region_value_str(r)
}
/// Indicates that the region variable `v` is live at the point `point`.
///
/// Returns `true` if this constraint is new and `false` is the
/// constraint was already present.
pub(super) fn add_live_point(&mut self, v: RegionVid, point: Location) -> bool {
debug!("add_live_point({:?}, {:?})", v, point);
assert!(self.inferred_values.is_none(), "values already inferred");
debug!("add_live_point: @{:?}", point);
let element = self.elements.index(point);
if self.liveness_constraints.add(v, element) {
true
} else {
false
}
}
/// Indicates that the region variable `sup` must outlive `sub` is live at the point `point`.
pub(super) fn add_outlives(
&mut self,
span: Span,
sup: RegionVid,
sub: RegionVid,
point: Location,
) {
debug!("add_outlives({:?}: {:?} @ {:?}", sup, sub, point);
assert!(self.inferred_values.is_none(), "values already inferred");
self.constraints.push(Constraint {
span,
sup,
sub,
point,
});
}
/// Perform region inference.
pub(super) fn solve(
&mut self,
infcx: &InferCtxt<'_, '_, 'tcx>,
mir: &Mir<'tcx>,
mir_def_id: DefId,
) -> Option<ClosureRegionRequirements> {
assert!(self.inferred_values.is_none(), "values already inferred");
let tcx = infcx.tcx;
// Find the minimal regions that can solve the constraints. This is infallible.
self.propagate_constraints(mir);
// Now, see whether any of the constraints were too strong. In
// particular, we want to check for a case where a universally
// quantified region exceeded its bounds. Consider:
//
// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
//
// In this case, returning `x` requires `&'a u32 <: &'b u32`
// and hence we establish (transitively) a constraint that
// `'a: 'b`. The `propagate_constraints` code above will
// therefore add `end('a)` into the region for `'b` -- but we
// have no evidence that `'a` outlives `'b`, so we want to report
// an error.
// The universal regions are always found in a prefix of the
// full list.
let universal_definitions = self.definitions
.iter_enumerated()
.take_while(|(_, fr_definition)| fr_definition.is_universal);
// Go through each of the universal regions `fr` and check that
// they did not grow too large, accumulating any requirements
// for our caller into the `outlives_requirements` vector.
let mut outlives_requirements = vec![];
for (fr, _) in universal_definitions {
self.check_universal_region(infcx, fr, &mut outlives_requirements);
}
// If this is not a closure, then there is no caller to which we can
// "pass the buck". So if there are any outlives-requirements that were
// not satisfied, we just have to report a hard error here.
if !tcx.is_closure(mir_def_id) {
for outlives_requirement in outlives_requirements {
self.report_error(
infcx,
outlives_requirement.free_region,
outlives_requirement.outlived_free_region,
outlives_requirement.blame_span,
);
}
return None;
}
let num_external_vids = self.universal_regions.num_global_and_external_regions();
Some(ClosureRegionRequirements {
num_external_vids,
outlives_requirements,
})
}
/// Check the final value for the free region `fr` to see if it
/// grew too large. In particular, examine what `end(X)` points
/// wound up in `fr`'s final value; for each `end(X)` where `X !=
/// fr`, we want to check that `fr: X`. If not, that's either an
/// error, or something we have to propagate to our creator.
///
/// Things that are to be propagated are accumulated into the
/// `outlives_requirements` vector.
fn check_universal_region(
&self,
infcx: &InferCtxt<'_, '_, 'tcx>,
longer_fr: RegionVid,
outlives_requirements: &mut Vec<ClosureOutlivesRequirement>,
) {
let inferred_values = self.inferred_values.as_ref().unwrap();
debug!("check_universal_region(fr={:?})", longer_fr);
// Find every region `o` such that `fr: o`
// (because `fr` includes `end(o)`).
for shorter_fr in inferred_values.universal_regions_outlived_by(longer_fr) {
// If it is known that `fr: o`, carry on.
if self.universal_regions.outlives(longer_fr, shorter_fr) {
continue;
}
debug!(
"check_universal_region: fr={:?} does not outlive shorter_fr={:?}",
longer_fr,
shorter_fr,
);
let blame_span = self.blame_span(longer_fr, shorter_fr);
// Shrink `fr` until we find a non-local region (if we do).
// We'll call that `fr-` -- it's ever so slightly smaller than `fr`.
if let Some(fr_minus) = self.universal_regions.non_local_lower_bound(longer_fr) {
debug!("check_universal_region: fr_minus={:?}", fr_minus);
// Grow `shorter_fr` until we find a non-local
// regon. (We always will.) We'll call that
// `shorter_fr+` -- it's ever so slightly larger than
// `fr`.
let shorter_fr_plus = self.universal_regions.non_local_upper_bound(shorter_fr);
debug!(
"check_universal_region: shorter_fr_plus={:?}",
shorter_fr_plus
);
// Push the constraint `fr-: shorter_fr+`
outlives_requirements.push(ClosureOutlivesRequirement {
free_region: fr_minus,
outlived_free_region: shorter_fr_plus,
blame_span: blame_span,
});
return;
}
// If we could not shrink `fr` to something smaller that
// the external users care about, then we can't pass the
// buck; just report an error.
self.report_error(infcx, longer_fr, shorter_fr, blame_span);
}
}
fn report_error(
&self,
infcx: &InferCtxt<'_, '_, 'tcx>,
fr: RegionVid,
outlived_fr: RegionVid,
blame_span: Span,
) {
// Obviously uncool error reporting.
let fr_string = match self.definitions[fr].external_name {
Some(r) => format!("free region `{}`", r),
None => format!("free region `{:?}`", fr),
};
let outlived_fr_string = match self.definitions[outlived_fr].external_name {
Some(r) => format!("free region `{}`", r),
None => format!("free region `{:?}`", outlived_fr),
};
infcx.tcx.sess.span_err(
blame_span,
&format!("{} does not outlive {}", fr_string, outlived_fr_string,),
);
}
/// Propagate the region constraints: this will grow the values
/// for each region variable until all the constraints are
/// satisfied. Note that some values may grow **too** large to be
/// feasible, but we check this later.
fn propagate_constraints(&mut self, mir: &Mir<'tcx>) {
let mut changed = true;
debug!("propagate_constraints()");
debug!("propagate_constraints: constraints={:#?}", {
let mut constraints: Vec<_> = self.constraints.iter().collect();
constraints.sort();
constraints
});
// The initial values for each region are derived from the liveness
// constraints we have accumulated.
let mut inferred_values = self.liveness_constraints.clone();
while changed {
changed = false;
debug!("propagate_constraints: --------------------");
for constraint in &self.constraints {
debug!("propagate_constraints: constraint={:?}", constraint);
// Grow the value as needed to accommodate the
// outlives constraint.
if self.copy(
&mut inferred_values,
mir,
constraint.sub,
constraint.sup,
constraint.point,
) {
debug!("propagate_constraints: sub={:?}", constraint.sub);
debug!("propagate_constraints: sup={:?}", constraint.sup);
changed = true;
}
}
debug!("\n");
}
self.inferred_values = Some(inferred_values);
}
fn copy(
&self,
inferred_values: &mut RegionValues,
mir: &Mir<'tcx>,
from_region: RegionVid,
to_region: RegionVid,
constraint_point: Location,
) -> bool {
let mut changed = false;
let mut stack = vec![];
let mut visited = FxHashSet();
stack.push(constraint_point);
while let Some(p) = stack.pop() {
let point_index = self.elements.index(p);
if !inferred_values.contains(from_region, point_index) {
debug!(" not in from-region");
continue;
}
if !visited.insert(p) {
debug!(" already visited");
continue;
}
let new = inferred_values.add(to_region, point_index);
changed |= new;
let block_data = &mir[p.block];
let successor_points = if p.statement_index < block_data.statements.len() {
vec![
Location {
statement_index: p.statement_index + 1,
..p
},
]
} else {
block_data
.terminator()
.successors()
.iter()
.map(|&basic_block| {
Location {
statement_index: 0,
block: basic_block,
}
})
.collect::<Vec<_>>()
};
if successor_points.is_empty() {
// If we reach the END point in the graph, then copy
// over any skolemized end points in the `from_region`
// and make sure they are included in the `to_region`.
changed |=
inferred_values.add_universal_regions_outlived_by(from_region, to_region);
} else {
stack.extend(successor_points);
}
}
changed
}
/// Tries to finds a good span to blame for the fact that `fr1`
/// contains `fr2`.
fn blame_span(&self, fr1: RegionVid, fr2: RegionVid) -> Span {
// Find everything that influenced final value of `fr`.
let influenced_fr1 = self.dependencies(fr1);
// Try to find some outlives constraint `'X: fr2` where `'X`
// influenced `fr1`. Blame that.
//
// NB, this is a pretty bad choice most of the time. In
// particular, the connection between `'X` and `fr1` may not
// be obvious to the user -- not to mention the naive notion
// of dependencies, which doesn't account for the locations of
// contraints at all. But it will do for now.
for constraint in &self.constraints {
if constraint.sub == fr2 && influenced_fr1[constraint.sup] {
return constraint.span;
}
}
bug!(
"could not find any constraint to blame for {:?}: {:?}",
fr1,
fr2
);
}
/// Finds all regions whose values `'a` may depend on in some way.
/// Basically if there exists a constraint `'a: 'b @ P`, then `'b`
/// and `dependencies('b)` will be in the final set.
///
/// Used during error reporting, extremely naive and inefficient.
fn dependencies(&self, r0: RegionVid) -> IndexVec<RegionVid, bool> {
let mut result_set = IndexVec::from_elem(false, &self.definitions);
let mut changed = true;
result_set[r0] = true;
while changed {
changed = false;
for constraint in &self.constraints {
if result_set[constraint.sup] {
if !result_set[constraint.sub] {
result_set[constraint.sub] = true;
changed = true;
}
}
}
}
result_set
}
}
impl<'tcx> RegionDefinition<'tcx> {
fn new(origin: RegionVariableOrigin) -> Self {
// Create a new region definition. Note that, for free
// regions, these fields get updated later in
// `init_universal_regions`.
Self {
origin,
is_universal: false,
external_name: None,
}
}
}
impl fmt::Debug for Constraint {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(
formatter,
"({:?}: {:?} @ {:?}) due to {:?}",
self.sup,
self.sub,
self.point,
self.span
)
}
}
pub trait ClosureRegionRequirementsExt {
fn apply_requirements<'tcx>(
&self,
infcx: &InferCtxt<'_, '_, 'tcx>,
location: Location,
closure_def_id: DefId,
closure_substs: ty::ClosureSubsts<'tcx>,
);
}
impl ClosureRegionRequirementsExt for ClosureRegionRequirements {
/// Given an instance T of the closure type, this method
/// instantiates the "extra" requirements that we computed for the
/// closure into the inference context. This has the effect of
/// adding new subregion obligations to existing variables.
///
/// As described on `ClosureRegionRequirements`, the extra
/// requirements are expressed in terms of regionvids that index
/// into the free regions that appear on the closure type. So, to
/// do this, we first copy those regions out from the type T into
/// a vector. Then we can just index into that vector to extract
/// out the corresponding region from T and apply the
/// requirements.
fn apply_requirements<'tcx>(
&self,
infcx: &InferCtxt<'_, '_, 'tcx>,
location: Location,
closure_def_id: DefId,
closure_substs: ty::ClosureSubsts<'tcx>,
) {
let tcx = infcx.tcx;
debug!(
"apply_requirements(location={:?}, closure_def_id={:?}, closure_substs={:?})",
location,
closure_def_id,
closure_substs
);
// Get Tu.
let user_closure_ty = tcx.mk_closure(closure_def_id, closure_substs);
debug!("apply_requirements: user_closure_ty={:?}", user_closure_ty);
// Extract the values of the free regions in `user_closure_ty`
// into a vector. These are the regions that we will be
// relating to one another.
let closure_mapping =
UniversalRegions::closure_mapping(infcx, user_closure_ty, self.num_external_vids);
debug!("apply_requirements: closure_mapping={:?}", closure_mapping);
// Create the predicates.
for outlives_requirement in &self.outlives_requirements {
let region = closure_mapping[outlives_requirement.free_region];
let outlived_region = closure_mapping[outlives_requirement.outlived_free_region];
debug!(
"apply_requirements: region={:?} outlived_region={:?} outlives_requirements={:?}",
region,
outlived_region,
outlives_requirement
);
// FIXME, this origin is not entirely suitable.
let origin = SubregionOrigin::CallRcvr(outlives_requirement.blame_span);
infcx.sub_regions(origin, outlived_region, region);
}
}
}
|
pub type IChannelCredentials = *mut ::core::ffi::c_void;
|
#![allow(dead_code)]
use circuit_desc::circuit_desc_gen::*;
use circuit_desc::gate_desc::*;
#[derive(Clone, Debug)]
pub struct CircuitState<C: CircuitDesc> {
pub new_wire_label: usize,
pub new_input_wire_label: usize,
pub new_output_wire_label: usize,
pub circuit: C,
}
impl <C: CircuitDesc> CircuitState<C>
{
pub fn new(num_parties: usize, this_party: usize,
send_sockets: Vec<String>, recv_sockets: Vec<String>) -> Self
{
let circuit = C::new(num_parties, this_party, send_sockets,
recv_sockets);
// 0 and 1 are for public bool
CircuitState { new_wire_label: 2, new_input_wire_label: 2,
new_output_wire_label: 0, circuit: circuit }
}
pub fn get_new_wire_label(&mut self) -> WireLabel {
let w = WireLabel(self.new_wire_label);
self.new_wire_label += 1;
w
}
pub fn get_new_input_wire_label(&mut self) -> InputWireLabel {
let w = InputWireLabel(self.new_input_wire_label);
self.new_input_wire_label += 1;
w
}
pub fn get_new_output_wire_label(&mut self) -> OutputWireLabel {
let w = OutputWireLabel(self.new_output_wire_label);
self.new_output_wire_label += 1;
w
}
}
|
#[macro_use] extern crate quicli;
extern crate reqwest;
use quicli::prelude::*;
use std::process::Command;
use reqwest::header::{Authorization, Basic, ContentType};
use std::env;
/// Generates git branch names based on JIRA Issues
#[derive(Debug, StructOpt)]
struct Cli {
/// Jira issue number
issue: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Error {
error_messages: Vec<String>
}
#[derive(Deserialize)]
struct Success {
fields: Fields
}
#[derive(Deserialize)]
struct Fields {
issuetype: IssueType,
summary: String
}
#[derive(Deserialize)]
struct IssueType {
name: String
}
main!(|args: Cli| {
let git_host = Command::new("git")
.arg("config")
.arg("git.jira.host")
.output()
.expect("failed to execute process");
let jira_url = format!("https://{}/rest/api/2/issue/{}?fields=summary,issuetype", String::from_utf8_lossy(&git_host.stdout).trim(), args.issue);
let credentials = Basic {
username: read_env_var("JIRA_USERNAME"),
password: Some(read_env_var("JIRA_PASSWORD")),
};
let http_client = reqwest::Client::new();
let mut resp = http_client.get(&jira_url).header(Authorization(credentials)).header(ContentType::json()).send()?;
if resp.status().is_success() {
let success: Success = resp.json()?;
let issue_type = str::replace(&success.fields.issuetype.name.to_lowercase(), " ", "_");
let issue_summary = str::replace(&success.fields.summary.to_lowercase(), " ", "_");
let branch_name = format!("{}/{}-{}", issue_type, args.issue, issue_summary);
Command::new("git")
.arg("checkout")
.arg("-b")
.arg(&branch_name)
.output()
.expect("failed to execute process");
println!("Success: {:?}", branch_name);
} else {
let err: Error = resp.json()?;
println!("Error: {:?}", err.error_messages);
}
});
fn read_env_var(env_var: &str) -> String {
return match env::var(env_var) {
Ok(r) => r,
Err(e) => {
eprintln!("Couldn't read {} ({})", env_var, e);
::std::process::exit(1);
}
};
}
|
pub mod addr;
pub mod socket;
pub mod epoll;
pub mod tcp;
pub mod buff;
extern crate libc as c;
pub use self::socket::Socket as Socket;
pub use self::epoll::Selector as Selector;
pub use self::tcp::TcpStream as TcpStream;
pub use self::tcp::TcpListener as TcpListener;
pub use self::buff::Buff as Buff;
pub enum EventType
{
Read,
Write,
ReadWrite
}
pub type Events = self::epoll::Events;
pub type RawFd = c::c_int;
#[derive(Copy,Clone,Debug)]
pub struct Token(u64);
impl Token {
pub fn new(id: u64) -> Self {
Token(id)
}
pub fn id(&self) -> u64 {
self.0
}
}
impl std::hash::Hash for Token {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl std::cmp::PartialEq for Token {
fn eq(&self, other: &Token) -> bool {
return self.0 == other.0
}
}
impl std::cmp::Eq for Token {}
trait IsMinusOne {
fn is_minus_one(&self) -> bool;
}
impl IsMinusOne for i32 {
fn is_minus_one(&self) -> bool { *self == -1 }
}
impl IsMinusOne for isize {
fn is_minus_one(&self) -> bool { *self == -1 }
}
fn cvt<T: IsMinusOne>(t: T) -> std::io::Result<T> {
if t.is_minus_one() {
Err(std::io::Error::last_os_error())
} else {
Ok(t)
}
}
fn to_void_result(res: c::c_int) -> std::io::Result<()> {
cvt(res)
.map( |_| {} )
}
fn to_result<T: IsMinusOne>(res: T) -> std::io::Result<T> {
cvt(res)
}
|
#[doc = "Reader of register USTAT"]
pub type R = crate::R<u32, super::USTAT>;
#[doc = "Writer for register USTAT"]
pub type W = crate::W<u32, super::USTAT>;
#[doc = "Register USTAT `reset()`'s with value 0"]
impl crate::ResetValue for super::USTAT {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `UV0`"]
pub type UV0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `UV0`"]
pub struct UV0_W<'a> {
w: &'a mut W,
}
impl<'a> UV0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `UV1`"]
pub type UV1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `UV1`"]
pub struct UV1_W<'a> {
w: &'a mut W,
}
impl<'a> UV1_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 `UV2`"]
pub type UV2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `UV2`"]
pub struct UV2_W<'a> {
w: &'a mut W,
}
impl<'a> UV2_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 `UV3`"]
pub type UV3_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `UV3`"]
pub struct UV3_W<'a> {
w: &'a mut W,
}
impl<'a> UV3_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
}
}
impl R {
#[doc = "Bit 0 - SS0 FIFO Underflow"]
#[inline(always)]
pub fn uv0(&self) -> UV0_R {
UV0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - SS1 FIFO Underflow"]
#[inline(always)]
pub fn uv1(&self) -> UV1_R {
UV1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - SS2 FIFO Underflow"]
#[inline(always)]
pub fn uv2(&self) -> UV2_R {
UV2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - SS3 FIFO Underflow"]
#[inline(always)]
pub fn uv3(&self) -> UV3_R {
UV3_R::new(((self.bits >> 3) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - SS0 FIFO Underflow"]
#[inline(always)]
pub fn uv0(&mut self) -> UV0_W {
UV0_W { w: self }
}
#[doc = "Bit 1 - SS1 FIFO Underflow"]
#[inline(always)]
pub fn uv1(&mut self) -> UV1_W {
UV1_W { w: self }
}
#[doc = "Bit 2 - SS2 FIFO Underflow"]
#[inline(always)]
pub fn uv2(&mut self) -> UV2_W {
UV2_W { w: self }
}
#[doc = "Bit 3 - SS3 FIFO Underflow"]
#[inline(always)]
pub fn uv3(&mut self) -> UV3_W {
UV3_W { w: self }
}
}
|
use crate::{
helper::Helper,
types::{ElGamalParams, ModuloOperations},
};
use num_bigint::BigUint;
#[derive(Clone, Eq, PartialEq, Debug, Hash)]
pub struct KeyGenerationProof {
pub challenge: BigUint,
pub response: BigUint,
}
impl KeyGenerationProof {
/// GenKeyPairProof Algorithm 8.7 (CHVoteSpec 3.2)
///
/// Generates a proof of knowledge of a secret key (sk) that belongs to a public key (pk = g^sk) using the Schnorr protocol. It is a proof of knowledge of a discrete logarithm of x = log_g(g^x).
///
/// Step by Step:
/// 1. generate a "second" key pair (a,b) = (random value from Z_q, g^a mod p)
/// 2. compute challenge
/// 3. compute d = a + c*sk
pub fn generate(
params: &ElGamalParams,
sk: &BigUint,
pk_share: &BigUint,
r: &BigUint,
id: &[u8],
) -> KeyGenerationProof {
// system parameters
let g = ¶ms.g;
let q = ¶ms.q();
let p = ¶ms.p;
// the public key
let h = pk_share;
// the private key
let x = sk;
// the commitment
let a = r;
let b = &g.modpow(r, p);
// compute challenge -> hash public values (hash(unique_id, h, b) mod q)
let mut c = Helper::hash_key_gen_proof_inputs(id, "keygen", h, b);
c %= q;
// compute the response: d = a + c*sk mod q
let d = a.modadd(&c.modmul(x, q), q);
KeyGenerationProof {
challenge: c,
response: d,
}
}
/// CheckKeyPairProof Algorithm 8.8 (CHVoteSpec 3.2)
///
/// Verifies a proof of knowledge of a secret key (sk) that belongs to a public key (pk = g^sk) using the Schnorr protocol. It is a proof of knowledge of a discrete logarithm of x = log_g(g^x).
///
/// Step by Step:
/// 1. recompute b = g^d/h^c
/// 2. recompute the challenge c
/// 3. verify that the challenge is correct
/// 4. verify that: g^d == b * h^c
pub fn verify(
params: &ElGamalParams,
pk_share: &BigUint,
proof: &KeyGenerationProof,
id: &[u8],
) -> bool {
// system parameters
let g = ¶ms.g;
let q = ¶ms.q();
let p = ¶ms.p;
// the public key
let h = pk_share;
// the proof
let c = &proof.challenge;
let d = &proof.response;
// recompute b
let g_pow_d = g.modpow(d, p);
let h_pow_c = h.modpow(c, p);
let b = g_pow_d
.moddiv(&h_pow_c, p)
.expect("cannot compute mod_inverse in mod_div!");
// recompute the hash
let mut c_ = Helper::hash_key_gen_proof_inputs(id, "keygen", h, &b);
c_ %= q;
// verify that the challenges are the same
let v1 = *c == c_;
// verify that the responses are the same
let v2 = g_pow_d == b.modmul(&h_pow_c, p);
v1 && v2
}
}
#[cfg(test)]
mod tests {
use crate::{helper::Helper, proofs::keygen::KeyGenerationProof, random::Random};
use num_bigint::BigUint;
#[test]
fn it_should_create_keygen_proof_tiny() {
let sealer_id = "Bob".as_bytes();
let (params, sk, pk) = Helper::setup_tiny_system();
let r = BigUint::parse_bytes(b"B", 16).unwrap();
let proof = KeyGenerationProof::generate(¶ms, &sk.x, &pk.h, &r, sealer_id);
assert_eq!(proof.challenge, BigUint::from(15u32));
assert_eq!(proof.response, BigUint::from(13u32));
}
#[test]
fn it_should_verify_keygen_proof() {
let sealer_id = "Charlie".as_bytes();
let (params, sk, pk) = Helper::setup_sm_system();
let r = Random::get_random_less_than(¶ms.q());
let proof = KeyGenerationProof::generate(¶ms, &sk.x, &pk.h, &r, sealer_id);
// verify the proof
let is_correct = KeyGenerationProof::verify(¶ms, &pk.h, &proof, sealer_id);
assert!(is_correct);
}
}
|
use std::fmt;
use std::result;
use ff::FF;
use sbox;
use util;
#[derive(Debug, PartialEq)]
pub struct State {
state: [[u8; 4]; 4]
}
impl State {
pub fn from_slice(slice: &[u8]) -> State {
let mut state = [[0; 4]; 4];
for c in 0..4 {
for r in 0..4 {
state[r][c] = slice[c*4 + r];
}
}
State{state}
}
pub fn sub_bytes(&self) -> State {
let mut ret = [[0;4]; 4];
for i in 0..4 {
for j in 0..4 {
ret[i][j] = sbox::sub_byte(self.state[i][j]);
}
}
State{ state: ret }
}
pub fn inv_sub_bytes(&self) -> State {
let mut ret = [[0;4]; 4];
for i in 0..4 {
for j in 0..4 {
ret[i][j] = sbox::inv_sub_byte(self.state[i][j]);
}
}
State{ state: ret }
}
pub fn shift_rows(&self) -> State {
State{state: [
State::shift_row(&self.state[0], 0),
State::shift_row(&self.state[1], 1),
State::shift_row(&self.state[2], 2),
State::shift_row(&self.state[3], 3),
]}
}
pub fn inv_shift_rows(&self) -> State {
State{state: [
State::inv_shift_row(&self.state[0], 0),
State::inv_shift_row(&self.state[1], 1),
State::inv_shift_row(&self.state[2], 2),
State::inv_shift_row(&self.state[3], 3),
]}
}
fn shift_row(row: &[u8; 4], amount: usize) -> [u8; 4] {
if amount == 0 { return *row; }
let mut ret = [0; 4];
for i in 0..4 {
ret[i] = row[(i+amount) % 4];
}
ret
}
fn inv_shift_row(row: &[u8; 4], amount: usize) -> [u8; 4] {
if amount == 0 { return *row; }
let mut ret = [0; 4];
for i in 0..4 {
ret[i] = row[(i+4-amount) % 4];
}
ret
}
pub fn mix_columns(&self) -> State {
let mut ret = self.state.clone();
for i in 0..4 {
let col = State::mix_column(&mut ret, i);
for j in 0..4 {
ret[j][i] = col[j];
}
}
State{state: ret}
}
fn mix_column(arr: &[[u8;4]; 4], col: usize) -> [u8; 4] {
let mut ret = [0; 4];
for i in 0..4 {
ret[i] = (
FF::new(arr[(i+0)%4][col]) * FF::new(0x02)
+ FF::new(arr[(i+1)%4][col]) * FF::new(0x03)
+ FF::new(arr[(i+2)%4][col])
+ FF::new(arr[(i+3)%4][col])
).value();
}
ret
}
pub fn inv_mix_columns(&self) -> State {
let mut ret = self.state.clone();
for i in 0..4 {
let col = State::inv_mix_column(&mut ret, i);
for j in 0..4 {
ret[j][i] = col[j];
}
}
State{state: ret}
}
fn inv_mix_column(arr: &[[u8;4]; 4], col: usize) -> [u8; 4] {
let mut ret = [0; 4];
for i in 0..4 {
ret[i] = (
FF::new(arr[(i+0)%4][col]) * FF::new(0x0e)
+ FF::new(arr[(i+1)%4][col]) * FF::new(0x0b)
+ FF::new(arr[(i+2)%4][col]) * FF::new(0x0d)
+ FF::new(arr[(i+3)%4][col]) * FF::new(0x09)
).value();
}
ret
}
pub fn add_round_key(&self, slice: &[u32]) -> State {
let mut ret = [[0;4]; 4];
for c in 0..4 {
let word = util::bytes_to_word((self.state[0][c],self.state[1][c],self.state[2][c],self.state[3][c]));
let res = word ^ slice[c];
let bytes = util::word_to_bytes(res);
ret[0][c] = bytes.0;
ret[1][c] = bytes.1;
ret[2][c] = bytes.2;
ret[3][c] = bytes.3;
}
State{state: ret}
}
pub fn to_byte_array(self) -> [u8; 16] {
let mut ret = [0; 16];
for c in 0..4 {
for r in 0..4 {
ret[c*4 + r] = self.state[r][c];
}
}
ret
}
fn to_u128(&self) -> u128 {
let mut res = 0;
for c in 0..4 {
for r in 0..4 {
res <<= 8;
res |= self.state[r][c] as u128;
}
}
res
}
}
impl fmt::Display for State {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> result::Result<(), fmt::Error> {
write!(formatter, "{:0>32x}", self.to_u128())
}
}
#[cfg(test)]
mod tests {
use state::*;
static TEST_STATE: State = State{ state: [
[0x19,0xa0,0x9a,0xe9],
[0x3d,0xf4,0xc6,0xf8],
[0xe3,0xe2,0x8d,0x48],
[0xbe,0x2b,0x2a,0x08]
]};
// The test cases I've been given for shift_rows, mix_columns
// and add_round_key are each based on the output of the previous
// function, so the later tests are dependent on the previous
// functions being correctly implemented. It's not exactly a
// "unit test" per-se, but it's fine
#[test]
fn test_sub_bytes() {
assert_eq!(TEST_STATE.sub_bytes(), State{ state: [
[0xd4,0xe0,0xb8,0x1e],
[0x27,0xbf,0xb4,0x41],
[0x11,0x98,0x5d,0x52],
[0xae,0xf1,0xe5,0x30]
]});
}
#[test]
fn test_shift_rows() {
assert_eq!(TEST_STATE.sub_bytes().shift_rows(), State{ state: [
[0xd4, 0xe0, 0xb8, 0x1e],
[0xbf, 0xb4, 0x41, 0x27],
[0x5d, 0x52, 0x11, 0x98],
[0x30, 0xae, 0xf1, 0xe5]
]});
assert_eq!(State::from_slice(&[
0x63,0xca,0xb7,0x04,
0x09,0x53,0xd0,0x51,
0xcd,0x60,0xe0,0xe7,
0xba,0x70,0xe1,0x8c
]).shift_rows(), State::from_slice(&[
0x63,0x53,0xe0,0x8c,
0x09,0x60,0xe1,0x04,
0xcd,0x70,0xb7,0x51,
0xba,0xca,0xd0,0xe7
]));
}
#[test]
fn test_inv_shift_rows() {
assert_eq!(State::from_slice(&[
0x63,0x53,0xe0,0x8c,
0x09,0x60,0xe1,0x04,
0xcd,0x70,0xb7,0x51,
0xba,0xca,0xd0,0xe7
]).inv_shift_rows(), State::from_slice(&[
0x63,0xca,0xb7,0x04,
0x09,0x53,0xd0,0x51,
0xcd,0x60,0xe0,0xe7,
0xba,0x70,0xe1,0x8c
]));
}
#[test]
fn test_shift_row() {
assert_eq!([1, 2, 3, 4], State::shift_row(&([1,2,3,4] as [u8; 4]), 0));
assert_eq!([2, 3, 4, 1], State::shift_row(&([1,2,3,4] as [u8; 4]), 1));
assert_eq!([3, 4, 1, 2], State::shift_row(&([1,2,3,4] as [u8; 4]), 2));
assert_eq!([4, 1, 2, 3], State::shift_row(&([1,2,3,4] as [u8; 4]), 3));
}
#[test]
fn test_inv_shift_row() {
assert_eq!([1,2,3,4], State::inv_shift_row(&([1, 2, 3, 4] as [u8; 4]), 0));
assert_eq!([1,2,3,4], State::inv_shift_row(&([2, 3, 4, 1] as [u8; 4]), 1));
assert_eq!([1,2,3,4], State::inv_shift_row(&([3, 4, 1, 2] as [u8; 4]), 2));
assert_eq!([1,2,3,4], State::inv_shift_row(&([4, 1, 2, 3] as [u8; 4]), 3));
}
#[test]
fn test_mix_columns() {
assert_eq!(TEST_STATE.sub_bytes().shift_rows().mix_columns(), State{ state: [
[0x04, 0xe0, 0x48, 0x28],
[0x66, 0xcb, 0xf8, 0x06],
[0x81, 0x19, 0xd3, 0x26],
[0xe5, 0x9a, 0x7a, 0x4c]
]});
}
#[test]
fn test_inv_mix_columns() {
assert_eq!(State::from_slice(&[
0x62, 0x7b, 0xce, 0xb9,
0x99, 0x9d, 0x5a, 0xaa,
0xc9, 0x45, 0xec, 0xf4,
0x23, 0xf5, 0x6d, 0xa5
]).inv_mix_columns(), State::from_slice(&[
0xe5, 0x1c, 0x95, 0x02,
0xa5, 0xc1, 0x95, 0x05,
0x06, 0xa6, 0x10, 0x24,
0x59, 0x6b, 0x2b, 0x07
]));
}
#[test]
fn test_add_round_key() {
assert_eq!(State{state: [
[0x04, 0xe0, 0x48, 0x28],
[0x66, 0xcb, 0xf8, 0x06],
[0x81, 0x19, 0xd3, 0x26],
[0xe5, 0x9a, 0x7a, 0x4c]
]}.add_round_key(&[0xa0fafe17, 0x88542cb1, 0x23a33939, 0x2a6c7605]), State{ state: [
[0xa4, 0x68, 0x6b, 0x02],
[0x9c, 0x9f, 0x5b, 0x6a],
[0x7f, 0x35, 0xea, 0x50],
[0xf2, 0x2b, 0x43, 0x49]
]});
assert_eq!(State::from_slice(&[
0x00,0x11,0x22,0x33,
0x44,0x55,0x66,0x77,
0x88,0x99,0xaa,0xbb,
0xcc,0xdd,0xee,0xff
]).add_round_key(&[
0x00010203,0x04050607,0x08090a0b,0x0c0d0e0f
]), State::from_slice(&[
0x00,0x10,0x20,0x30,
0x40,0x50,0x60,0x70,
0x80,0x90,0xa0,0xb0,
0xc0,0xd0,0xe0,0xf0
]));
}
#[test]
fn test_to_u128() {
assert_eq!(0x193de3bea0f4e22b9ac68d2ae9f84808, TEST_STATE.to_u128());
}
} |
use std::fmt::Display;
use data_types::{CompactionLevel, ParquetFile};
use crate::{
components::{
divide_initial::multiple_branches::order_files, files_split::FilesSplit,
split_or_compact::SplitOrCompact,
},
file_classification::{
CompactReason, FileClassification, FilesForProgress, FilesToSplitOrCompact,
},
partition_info::PartitionInfo,
RoundInfo,
};
use super::FileClassifier;
/// Use [`FilesSplit`] to build a [`FileClassification`].
///
/// Uses the target_level from the `round_info` in the following data flow:
///
/// ```text
/// (files+target_level)-+.......................................
/// | :
/// | :
/// | +................................+
/// | : :
/// | : :
/// V V :
/// [target level split (FT)] :
/// | | :
/// | | :
/// | +------------+ :
/// | | :
/// | | :
/// | +............|...................+
/// | : | :
/// V V | :
/// [non overlap split (FO)] | :
/// | | | :
/// | | | :
/// | +------------+------+ :
/// | | :
/// | | :
/// | +................................+
/// | : | :
/// V V | :
/// [upgrade split (FU)] | :
/// | | | :
/// | | | :
/// | V | :
/// | (files upgrade) | :
/// | | :
/// | +................................+
/// | | |
/// V V |
/// [split or compact (FSC)] |
/// | | |
/// | +-------------------+
/// | |
/// V V
/// (files compact or split) (files keep)
/// ```
#[derive(Debug)]
pub struct SplitBasedFileClassifier<FT, FO, FU, FSC>
where
FT: FilesSplit,
FO: FilesSplit,
FU: FilesSplit,
FSC: SplitOrCompact,
{
target_level_split: FT,
non_overlap_split: FO,
upgrade_split: FU,
split_or_compact: FSC,
}
impl<FT, FO, FU, FSC> SplitBasedFileClassifier<FT, FO, FU, FSC>
where
FT: FilesSplit,
FO: FilesSplit,
FU: FilesSplit,
FSC: SplitOrCompact,
{
pub fn new(
target_level_split: FT,
non_overlap_split: FO,
upgrade_split: FU,
split_or_compact: FSC,
) -> Self {
Self {
target_level_split,
non_overlap_split,
upgrade_split,
split_or_compact,
}
}
}
impl<FT, FO, FU, FSC> Display for SplitBasedFileClassifier<FT, FO, FU, FSC>
where
FT: FilesSplit,
FO: FilesSplit,
FU: FilesSplit,
FSC: SplitOrCompact,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"split_based(target_level_split={}, non_overlap_split={}, upgrade_split={})",
self.target_level_split, self.non_overlap_split, self.upgrade_split,
)
}
}
impl<FT, FO, FU, FSC> FileClassifier for SplitBasedFileClassifier<FT, FO, FU, FSC>
where
FT: FilesSplit,
FO: FilesSplit,
FU: FilesSplit,
FSC: SplitOrCompact,
{
fn classify(
&self,
partition_info: &PartitionInfo,
round_info: &RoundInfo,
files: Vec<ParquetFile>,
) -> FileClassification {
let files_to_compact = files;
let target_level = round_info.target_level();
if round_info.is_many_small_files() {
return file_classification_for_many_files(
round_info.max_total_file_size_to_group().unwrap(),
round_info.max_num_files_to_group().unwrap(),
files_to_compact,
target_level,
);
}
if round_info.is_simulated_leading_edge() {
match round_info {
RoundInfo::SimulatedLeadingEdge { .. } => {
// file division already done in round_info_source
return FileClassification {
target_level: round_info.target_level(),
files_to_make_progress_on: FilesForProgress {
upgrade: vec![],
split_or_compact: FilesToSplitOrCompact::Compact(
files_to_compact,
CompactReason::TotalSizeLessThanMaxCompactSize,
),
},
files_to_keep: vec![],
};
}
_ => unreachable!(),
}
}
// Split files into files_to_compact, files_to_upgrade, and files_to_keep
//
// Since output of one compaction is used as input of next compaction, all files that are not
// compacted or upgraded are still kept to consider in next round of compaction
// Split actual files to compact from its higher-target-level files
// The higher-target-level files are kept for next round of compaction
let (files_to_compact, mut files_to_keep) = self
.target_level_split
.apply(files_to_compact, target_level);
// To have efficient compaction performance, we do not need to compact eligible non-overlapped files
// Find eligible non-overlapped files and keep for next round of compaction
let (files_to_compact, non_overlapping_files) =
self.non_overlap_split.apply(files_to_compact, target_level);
files_to_keep.extend(non_overlapping_files);
// To have efficient compaction performance, we only need to upgrade (catalog update only) eligible files
let (files_to_compact, files_to_upgrade) =
self.upgrade_split.apply(files_to_compact, target_level);
// See if we need to split start-level files due to over compaction size limit
let (files_to_split_or_compact, other_files) =
self.split_or_compact
.apply(partition_info, files_to_compact, target_level);
files_to_keep.extend(other_files);
let files_to_make_progress_on = FilesForProgress {
upgrade: files_to_upgrade,
split_or_compact: files_to_split_or_compact,
};
FileClassification {
target_level,
files_to_make_progress_on,
files_to_keep,
}
}
}
// ManySmallFiles assumes the L0 files are tiny and aims to do L0-> L0 compaction to reduce the number of tiny files.
fn file_classification_for_many_files(
max_total_file_size_to_group: usize,
max_num_files_to_group: usize,
files: Vec<ParquetFile>,
target_level: CompactionLevel,
) -> FileClassification {
// Verify all input files are in the target_level
let err_msg = format!(
"All files to compact must be in {target_level} level, but found files in other levels",
);
assert!(
files.iter().all(|f| f.compaction_level == target_level),
"{err_msg}"
);
let mut files_to_compact = vec![];
let mut files_to_keep: Vec<ParquetFile> = vec![];
// Enforce max_num_files_to_group
if files.len() > max_num_files_to_group {
let ordered_files = order_files(files, target_level.prev());
ordered_files
.chunks(max_num_files_to_group)
.for_each(|chunk| {
let this_chunk_bytes: usize =
chunk.iter().map(|f| f.file_size_bytes as usize).sum();
if this_chunk_bytes > max_total_file_size_to_group {
// This chunk of files are plenty big and don't fit the ManySmallFiles characteristics.
// If we let ManySmallFiles handle them, it may get stuck with unproductive compactions.
// So set them aside for later (when we're not in ManySmallFiles mode).
files_to_keep.append(chunk.to_vec().as_mut());
} else if files_to_compact.is_empty() {
files_to_compact = chunk.to_vec();
} else {
// We've already got a batch of files to compact, these can wait.
files_to_keep.append(chunk.to_vec().as_mut());
}
});
} else {
files_to_compact = files;
}
let files_to_make_progress_on = FilesForProgress {
upgrade: vec![],
split_or_compact: FilesToSplitOrCompact::Compact(
files_to_compact,
CompactReason::ManySmallFiles,
),
};
FileClassification {
target_level,
files_to_make_progress_on,
files_to_keep,
}
}
|
use amethyst::assets::{AssetStorage, Loader};
use amethyst::core::transform::Transform;
use amethyst::ecs::prelude::{Entity};
use amethyst::prelude::*;
use amethyst::ui::{Anchor, TtfFormat, UiText, UiTransform};
use amethyst::renderer::{
Camera, PngFormat, Projection, SpriteSheet,
SpriteSheetFormat, SpriteSheetHandle, Texture, TextureMetadata,
};
use crate::components;
pub const ARENA_HEIGHT: f32 = 100.0;
pub const ARENA_WIDTH: f32 = 100.0;
pub const PADDLE_HEIGHT: f32 = 16.0;
pub const PADDLE_WIDTH: f32 = 4.0;
pub const BALL_VELOCITY_X: f32 = 10.0;
pub const BALL_VELOCITY_Y: f32 = 7.0;
pub const BALL_RADIUS: f32 = 2.0;
fn initialise_camera(world: &mut World) {
let mut transform = Transform::default();
transform.set_z(1.0);
world
.create_entity()
.with(Camera::from(Projection::orthographic(
0.0,
ARENA_WIDTH,
0.0,
ARENA_HEIGHT,
)))
.with(transform)
.build();
}
fn load_sprite_sheet(world: &mut World) -> SpriteSheetHandle {
// Load the sprite sheet necessary to render the graphics.
// The texture is the pixel data
// `texture_handle` is a cloneable reference to the texture
let texture_handle = {
let loader = world.read_resource::<Loader>();
let texture_storage = world.read_resource::<AssetStorage<Texture>>();
loader.load(
"resources/texture/pong_spritesheet.png",
PngFormat,
TextureMetadata::srgb_scale(),
(),
&texture_storage,
)
};
let loader = world.read_resource::<Loader>();
let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();
let handle = loader.load(
"resources/texture/pong_spritesheet.ron", // Here we load the associated ron file
SpriteSheetFormat,
texture_handle, // We pass it the handle of the texture we want it to use
(),
&sprite_sheet_store,
);
return handle;
}
/// ScoreBoard contains the actual score data
#[derive(Default)]
pub struct ScoreBoard {
pub score_left: i32,
pub score_right: i32,
}
/// ScoreText contains the ui text components that display the score
pub struct ScoreText {
pub p1_score: Entity,
pub p2_score: Entity,
}
fn initialise_scoreboard(world: &mut World) {
let font = world.read_resource::<Loader>().load(
"resources/font/square.ttf",
TtfFormat,
Default::default(),
(),
&world.read_resource(),
);
let p1_transform = UiTransform::new(
"P1".to_string(), Anchor::TopMiddle,
-50., -50., 1., 200., 50., 0,
);
let p2_transform = UiTransform::new(
"P2".to_string(), Anchor::TopMiddle,
50., -50., 1., 200., 50., 0,
);
let p1_score = world
.create_entity()
.with(p1_transform)
.with(UiText::new(
font.clone(),
"0".to_string(),
[1., 1., 1., 1.],
50.,
)).build();
let p2_score = world
.create_entity()
.with(p2_transform)
.with(UiText::new(
font.clone(),
"0".to_string(),
[1., 1., 1., 1.],
50.,
)).build();
world.add_resource(ScoreText { p1_score, p2_score });
}
pub struct Hexagame{}
impl SimpleState for Hexagame {
fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) {
let world = data.world;
let sprite_sheet_handle = load_sprite_sheet(world);
world.register::<components::Ball>(); // <- add this line temporarily
components::initialise_ball(world, sprite_sheet_handle.clone()); // <- add this line
components::initialise_paddles(world, sprite_sheet_handle);
initialise_camera(world);
initialise_scoreboard(world);
}
}
|
use std::{sync::Arc, io::Read};
use sourcerenderer_core::{Vec2, Platform, graphics::*, platform::IO};
use crate::{renderer::{renderer_resources::HistoryResourceEntry, render_path::RenderPassParameters}, ui::UIDrawData};
pub struct UIPass<P: Platform> {
device: Arc<<P::GraphicsBackend as Backend>::Device>,
pipeline: Arc<<P::GraphicsBackend as Backend>::GraphicsPipeline>,
}
impl<P: Platform> UIPass<P> {
pub fn new(device: &Arc<<P::GraphicsBackend as Backend>::Device>) -> Self {
let vs = {
let mut file = <P::IO as IO>::open_asset("shaders/dear_imgui.vert.spv").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
device.create_shader(ShaderType::VertexShader, &bytes, Some("DearImguiVS"))
};
let ps = {
let mut file = <P::IO as IO>::open_asset("shaders/dear_imgui.frag.spv").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
device.create_shader(ShaderType::FragmentShader, &bytes, Some("DearImguiPS"))
};
let pipeline = device.create_graphics_pipeline(&GraphicsPipelineInfo {
vs: &vs,
fs: Some(&ps),
vertex_layout: VertexLayoutInfo {
shader_inputs: &[
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 0,
semantic_name_d3d: "aPos".to_string(),
semantic_index_d3d: 0,
offset: 0,
format: Format::RG32Float,
},
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 1,
semantic_name_d3d: "aUV".to_string(),
semantic_index_d3d: 0,
offset: 8,
format: Format::RG32Float,
},
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 2,
semantic_name_d3d: "aColor".to_string(),
semantic_index_d3d: 0,
offset: 16,
format: Format::RGBA8UNorm,
},
],
input_assembler: &[
InputAssemblerElement {
binding: 0,
input_rate: InputRate::PerVertex,
stride: 20,
},
],
},
rasterizer: RasterizerInfo {
fill_mode: FillMode::Fill,
cull_mode: CullMode::None,
front_face: FrontFace::CounterClockwise,
sample_count: SampleCount::Samples1,
},
depth_stencil: DepthStencilInfo::default(),
blend: BlendInfo {
attachments: &[
AttachmentBlendInfo {
blend_enabled: true,
src_color_blend_factor: BlendFactor::SrcAlpha,
dst_color_blend_factor: BlendFactor::OneMinusSrcAlpha,
color_blend_op: BlendOp::Add,
src_alpha_blend_factor: BlendFactor::One,
dst_alpha_blend_factor: BlendFactor::OneMinusSrcAlpha,
alpha_blend_op: BlendOp::Add,
write_mask: ColorComponents::all(),
}
],
..Default::default()
},
primitive_type: PrimitiveType::Triangles,
}, &RenderPassInfo {
attachments: &[
AttachmentInfo {
format: Format::RGBA8UNorm,
samples: SampleCount::Samples1,
}
],
subpasses: &[
SubpassInfo {
input_attachments: &[],
output_color_attachments: &[
OutputAttachmentRef { index: 0, resolve_attachment_index: None }
],
depth_stencil_attachment: None,
}
]
}, 0, Some("DearImgui"));
Self {
device: device.clone(),
pipeline,
}
}
pub fn execute(
&mut self,
command_buffer: &mut <P::GraphicsBackend as Backend>::CommandBuffer,
pass_params: &RenderPassParameters<'_, P>,
output_texture_name: &str,
draw: &UIDrawData<P::GraphicsBackend>
) {
let rtv = pass_params.resources.access_view(
command_buffer,
output_texture_name,
BarrierSync::RENDER_TARGET,
BarrierAccess::RENDER_TARGET_WRITE | BarrierAccess::RENDER_TARGET_WRITE,
TextureLayout::RenderTarget,
false,
&TextureViewInfo::default(),
HistoryResourceEntry::Current
);
command_buffer.flush_barriers();
command_buffer.set_pipeline(PipelineBinding::Graphics(&self.pipeline));
if draw.viewport.extent.x <= 0f32 || draw.viewport.extent.y <= 0f32 {
return;
}
#[repr(C)]
#[derive(Debug, Clone)]
struct ImguiPushConstants {
scale: Vec2,
translate: Vec2
}
command_buffer.upload_dynamic_data_inline(&[ImguiPushConstants {
scale: draw.scale,
translate: draw.translate,
}], ShaderType::VertexShader);
command_buffer.set_viewports(&[draw.viewport.clone()]);
command_buffer.begin_render_pass(&RenderPassBeginInfo {
attachments: &[
RenderPassAttachment {
view: RenderPassAttachmentView::RenderTarget(&rtv),
load_op: LoadOp::Load,
store_op: StoreOp::Store,
}
],
subpasses: &[
SubpassInfo {
input_attachments: &[],
output_color_attachments: &[
OutputAttachmentRef { index: 0, resolve_attachment_index: None }
],
depth_stencil_attachment: None,
}
],
}, RenderpassRecordingMode::Commands);
for list in &draw.draw_lists {
command_buffer.set_index_buffer(&list.index_buffer, 0, if std::mem::size_of::<imgui::DrawIdx>() == 2 { IndexFormat::U16 } else { IndexFormat::U32 });
command_buffer.set_vertex_buffer(&list.vertex_buffer, 0);
for draw in &list.draws {
command_buffer.set_scissors(&[
draw.scissor.clone()
]);
if let Some(texture) = &draw.texture {
command_buffer.bind_sampling_view_and_sampler(BindingFrequency::VeryFrequent, 0, texture, pass_params.resources.linear_sampler());
} else {
command_buffer.bind_sampling_view_and_sampler(BindingFrequency::VeryFrequent, 0, pass_params.zero_textures.zero_texture_view, pass_params.resources.linear_sampler());
}
command_buffer.finish_binding();
command_buffer.draw_indexed(1, 0, draw.index_count, draw.first_index, draw.vertex_offset as i32);
}
}
command_buffer.end_render_pass();
}
}
|
use deadpool::{
managed::{BuildError, PoolConfig},
Runtime,
};
use crate::{Manager, Pool};
/// Configuration object. By enabling the `config` feature you can
/// read the configuration using the [`config`](https://crates.io/crates/config)
/// crate.
///
/// ## Example environment
/// ```env
/// SQLITE__PATH=db.sqlite3
/// SQLITE__POOL__MAX_SIZE=16
/// SQLITE__POOL__TIMEOUTS__WAIT__SECS=5
/// SQLITE__POOL__TIMEOUTS__WAIT__NANOS=0
/// ```
///
/// ## Example usage
/// ```rust,ignore
/// struct Config {
/// sqlite: deadpool_postgres::Config,
/// }
/// impl Config {
/// pub fn from_env() -> Result<Self, ConfigError> {
/// let mut cfg = config::Config::new();
/// cfg.merge(config::Environment::new().separator("__")).unwrap();
/// cfg.try_into().unwrap()
/// }
/// }
/// ```
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
pub struct Config {
/// Path to database file
pub path: String,
/// Pool configuration
pub pool: Option<PoolConfig>,
}
impl Config {
/// Create new config instance
pub fn new(path: &str) -> Self {
Self {
path: path.to_owned(),
pool: None,
}
}
/// Create pool using the current configuration
pub fn create_pool(&self, runtime: Runtime) -> Result<Pool, BuildError<rusqlite::Error>> {
let manager = Manager::from_config(&self, runtime.clone());
Pool::builder(manager)
.config(self.get_pool_config())
.runtime(runtime)
.build()
}
/// Get `deadpool::PoolConfig` which can be used to construct a
/// `deadpool::managed::Pool` instance.
pub fn get_pool_config(&self) -> PoolConfig {
self.pool.clone().unwrap_or_default()
}
}
|
use crate::smb2::requests::tree_connect::TreeConnect;
/// Serializes a tree connect request from the corresponding struct.
pub fn serialize_tree_connect_request_body(request: &TreeConnect) -> Vec<u8> {
let mut serialized_request: Vec<u8> = Vec::new();
serialized_request.append(&mut request.structure_size.clone());
serialized_request.append(&mut request.flags.clone());
serialized_request.append(&mut request.path_offset.clone());
serialized_request.append(&mut request.path_length.clone());
serialized_request.append(&mut request.buffer.clone());
serialized_request
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_serialize_tree_connect_request_body() {
let mut tree_connect = TreeConnect::default();
tree_connect.flags = vec![0; 2];
tree_connect.path_offset = b"\x48\x00".to_vec();
tree_connect.path_length = b"\x2a\x00".to_vec();
tree_connect.buffer = b"\x5c\x00\x5c\x00\x31\x00\x39\x00\x32\x00\x2e\x00\x31\x00\x36\x00\
\x38\x00\x2e\x00\x30\x00\x2e\x00\x31\x00\x37\x00\x31\x00\x5c\x00\
\x73\x00\x68\x00\x61\x00\x72\x00\x65\x00"
.to_vec();
let expected_byte_array = b"\x09\x00\x00\x00\x48\x00\x2a\x00\x5c\x00\x5c\x00\x31\x00\x39\x00\
\x32\x00\x2e\x00\x31\x00\x36\x00\x38\x00\x2e\x00\x30\x00\x2e\x00\
\x31\x00\x37\x00\x31\x00\x5c\x00\x73\x00\x68\x00\x61\x00\x72\x00\
\x65\x00".to_vec();
assert_eq!(
expected_byte_array,
serialize_tree_connect_request_body(&tree_connect)
);
}
}
|
use crate::{
config::Config,
steamworks_util::{
OneShotRecvError,
UgcQueryBuilder,
},
};
use conrod_core::{
widget,
widget_ids,
Borderable,
Colorable,
Labelable,
Positionable,
Sizeable,
Widget,
};
use parking_lot::Mutex;
use std::{
borrow::Cow,
error::Error as StdError,
path::PathBuf,
sync::Arc,
};
use tokio::runtime::Runtime as TokioRuntime;
widget_ids! {
pub struct Ids {
title,
game_button,
levelbuilder_button,
cover_image,
syncing_label,
}
}
pub fn gui(ui: &mut conrod_core::UiCell, ids: &Ids, app: &mut App) {
let button_width = 200.0;
let button_height = 50.0;
let cover_image_side = 200.0;
widget::Text::new("Skeleton Sprint Launcher")
.color(conrod_core::color::WHITE)
.font_size(42)
.mid_top_of(ui.window)
.set(ids.title, ui);
widget::Image::new(app.cover_image)
.w_h(cover_image_side, cover_image_side)
.down_from(ids.title, 10.0)
// .up_from(ids.game_button, 0.0)
.align_middle_x_of(ui.window)
.set(ids.cover_image, ui);
for () in widget::Button::new()
.label("Launch Game")
.middle_of(ui.window)
.w_h(button_width, button_height)
.set(ids.game_button, ui)
{
if !app.steam_workshop_sync_state.lock().is_syncing() {
let game_path = app.config.get_game_path();
crate::util::open_program(&*game_path.to_string_lossy());
}
}
for () in widget::Button::new()
.label("Launch Levelbuilder")
.down_from(ids.game_button, 10.0)
.w_h(button_width, button_height)
.set(ids.levelbuilder_button, ui)
{
let levelbuilder_path = app.config.get_levelbuilder_path().clone();
crate::util::open_program(&*levelbuilder_path.to_string_lossy());
}
{
let steam_workshop_sync_state = app.steam_workshop_sync_state.lock();
let sync_label: Cow<'_, str> = match &*steam_workshop_sync_state {
SteamWorkshopSyncState::Starting => "Syncing...".into(),
SteamWorkshopSyncState::InProgress(current, total) => {
format!("Syncing({}/{})...", current, total).into()
}
SteamWorkshopSyncState::Done => "Sync Complete".into(),
SteamWorkshopSyncState::Failed(_) => "Sync Failed!".into(),
};
widget::TitleBar::new(&sync_label, ui.window)
.color(conrod_core::Color::Rgba(1.0, 1.0, 1.0, 1.0))
.bottom_left_with_margin_on(ui.window, 0.0)
.w_h(200.0, 30.0)
.border(0.0)
.set(ids.syncing_label, ui);
}
}
#[derive(Debug)]
pub enum AppError {
Io(std::io::Error),
Steam(steamworks::SteamError),
SteamWorkshopQuery(crate::steamworks_util::WorkshopQueryError),
InvalidSyncDir,
}
impl From<std::io::Error> for AppError {
fn from(e: std::io::Error) -> AppError {
AppError::Io(e)
}
}
impl From<steamworks::SteamError> for AppError {
fn from(e: steamworks::SteamError) -> AppError {
AppError::Steam(e)
}
}
impl From<crate::steamworks_util::WorkshopQueryError> for AppError {
fn from(e: crate::steamworks_util::WorkshopQueryError) -> AppError {
AppError::SteamWorkshopQuery(e)
}
}
impl std::fmt::Display for AppError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(e) => e.fmt(f),
Self::Steam(e) => e.fmt(f),
Self::SteamWorkshopQuery(e) => e.fmt(f),
Self::InvalidSyncDir => write!(f, "The sync dir is invalid"),
}
}
}
#[derive(Debug)]
pub enum SteamWorkshopSyncError {
Recieve(OneShotRecvError),
Steam(steamworks::SteamError),
Io(std::io::Error),
MissingItemInfo,
}
impl From<OneShotRecvError> for SteamWorkshopSyncError {
fn from(e: OneShotRecvError) -> Self {
Self::Recieve(e)
}
}
impl From<steamworks::SteamError> for SteamWorkshopSyncError {
fn from(e: steamworks::SteamError) -> Self {
Self::Steam(e)
}
}
impl From<std::io::Error> for SteamWorkshopSyncError {
fn from(e: std::io::Error) -> Self {
Self::Io(e)
}
}
impl std::fmt::Display for SteamWorkshopSyncError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Recieve(e) => e.fmt(f),
Self::Steam(e) => e.fmt(f),
Self::Io(e) => e.fmt(f),
Self::MissingItemInfo => write!(f, "Missing workshop item info"),
}
}
}
impl StdError for SteamWorkshopSyncError {}
#[derive(Debug)]
pub enum SteamWorkshopSyncState {
Starting,
InProgress(usize, usize),
Done,
Failed(SteamWorkshopSyncError),
}
impl SteamWorkshopSyncState {
pub fn begin_sync(&mut self, len: usize) {
*self = Self::InProgress(0, len);
}
pub fn add_synced(&mut self, synced: usize) {
if let Self::InProgress(old_synced, total) = self {
*old_synced += synced;
if *old_synced >= *total {
*self = Self::Done;
}
}
}
pub fn set_fail(&mut self, e: SteamWorkshopSyncError) {
*self = Self::Failed(e);
}
pub fn is_syncing(&self) -> bool {
matches!(self, Self::Starting | Self::InProgress(_, _))
}
}
pub struct App {
pub config: Config,
cover_image: conrod_core::image::Id,
pub tokio_rt: TokioRuntime,
pub steam_client: steamworks::Client,
steam_single_client: steamworks::SingleClient,
steam_workshop_sync_state: Arc<Mutex<SteamWorkshopSyncState>>,
}
impl App {
pub fn new(config: Config, cover_image: conrod_core::image::Id) -> Result<Self, AppError> {
let tokio_rt = TokioRuntime::new()?;
// For now, lets make steamworks necessary.
let (steam_client, steam_single_client) = steamworks::Client::init()?;
let ugc_query_future = UgcQueryBuilder::new(&steam_client)
.user_list(steamworks::UserList::Subscribed)
.send(|res| res.map(|res| res.iter().collect::<Vec<_>>()))?;
let sync_dir = config.get_workshop_sync_path().clone();
if !sync_dir.exists() {
std::fs::create_dir_all(&sync_dir)?;
}
if !sync_dir.is_dir() {
return Err(AppError::InvalidSyncDir);
}
let steam_workshop_sync_state = Arc::new(Mutex::new(SteamWorkshopSyncState::Starting));
let steam_workshop_sync_state_clone = steam_workshop_sync_state.clone();
let steam_client_clone = steam_client.clone();
tokio_rt.spawn(async move {
if let Err(e) = sync_steam_workshop(
steam_client_clone,
ugc_query_future.await,
steam_workshop_sync_state_clone.clone(),
sync_dir,
)
.await
{
eprintln!("Sync Failed: {}", e);
steam_workshop_sync_state_clone.lock().set_fail(e);
}
});
Ok(App {
config,
cover_image,
tokio_rt,
steam_client,
steam_single_client,
steam_workshop_sync_state,
})
}
pub fn update(&mut self) {
self.steam_single_client.run_callbacks();
}
}
async fn sync_steam_workshop(
steam_client: steamworks::Client,
workshop_data: Result<
Result<Vec<steamworks::QueryResult>, steamworks::SteamError>,
OneShotRecvError,
>,
steam_workshop_sync_state: Arc<Mutex<SteamWorkshopSyncState>>,
mut sync_dir: PathBuf,
) -> Result<(), SteamWorkshopSyncError> {
let workshop_data = workshop_data??;
steam_workshop_sync_state
.lock()
.begin_sync(workshop_data.len());
for workshop_item in workshop_data.iter() {
let item_info = steam_client
.ugc()
.item_install_info(workshop_item.published_file_id)
.ok_or(SteamWorkshopSyncError::MissingItemInfo)?;
sync_dir.push(&workshop_item.title);
sync_dir.set_extension("txt");
tokio::fs::copy(&item_info.folder, &sync_dir).await?;
sync_dir.pop();
steam_workshop_sync_state.lock().add_synced(1);
}
Ok(())
}
|
use crate::errors::*;
use crate::version::Version;
use bytes::*;
use std::cell::RefCell;
use std::mem;
use std::rc::Rc;
pub const MARKER: u8 = 0xC1;
#[derive(Debug, PartialEq, Clone)]
pub struct BoltFloat {
pub value: f64,
}
impl BoltFloat {
pub fn new(value: f64) -> BoltFloat {
BoltFloat { value }
}
pub fn can_parse(_: Version, input: Rc<RefCell<Bytes>>) -> bool {
input.borrow()[0] == MARKER
}
}
impl BoltFloat {
pub fn parse(_: Version, input: Rc<RefCell<Bytes>>) -> Result<BoltFloat> {
let mut input = input.borrow_mut();
let _marker = input.get_u8();
let value = input.get_f64();
Ok(BoltFloat::new(value))
}
pub fn into_bytes(self, _: Version) -> Result<Bytes> {
let mut bytes = BytesMut::with_capacity(mem::size_of::<u8>() + mem::size_of::<f64>());
bytes.put_u8(MARKER);
bytes.put_f64(self.value);
Ok(bytes.freeze())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_serialize_float() {
let b: Bytes = BoltFloat::new(1.23).into_bytes(Version::V4_1).unwrap();
assert_eq!(
&b[..],
&[0xC1, 0x3F, 0xF3, 0xAE, 0x14, 0x7A, 0xE1, 0x47, 0xAE]
);
let b: Bytes = BoltFloat::new(-1.23).into_bytes(Version::V4_1).unwrap();
assert_eq!(
&b[..],
&[0xC1, 0xBF, 0xF3, 0xAE, 0x14, 0x7A, 0xE1, 0x47, 0xAE,]
);
}
#[test]
fn should_deserialize_float() {
let input = Rc::new(RefCell::new(Bytes::from_static(&[
0xC1, 0x3F, 0xF3, 0xAE, 0x14, 0x7A, 0xE1, 0x47, 0xAE,
])));
let bolt_float: BoltFloat = BoltFloat::parse(Version::V4_1, input).unwrap();
assert_eq!(bolt_float.value, 1.23);
let input = Rc::new(RefCell::new(Bytes::from_static(&[
0xC1, 0xBF, 0xF3, 0xAE, 0x14, 0x7A, 0xE1, 0x47, 0xAE,
])));
let bolt_float: BoltFloat = BoltFloat::parse(Version::V4_1, input).unwrap();
assert_eq!(bolt_float.value, -1.23);
}
}
|
use std::collections::HashSet;
use console::style;
use reqwest::header::AUTHORIZATION;
use reqwest::StatusCode;
use serde_json::json;
use super::cli;
use super::issue;
use issue::Issue;
const API_ENDPOINT: &str = "https://api.github.com";
pub struct Request {
client: reqwest::Client,
url: String,
remote_url: String,
auth_header: String,
}
impl Request {
pub fn new(token: String, remote: String) -> Request {
//! Creates a new request object that encapsulates the http client,
//! url formatted with the API endpoint and user's remote repo,
//! and auth header containing the user's token.
Request {
client: reqwest::Client::new(),
url: format!("{}/repos/{}/issues", API_ENDPOINT, remote)
.to_string(),
remote_url: format!("https://github.com/{}", remote).to_string(),
auth_header: format!("token {}", token).to_string(),
}
}
pub fn open_issue(&self, issue: &Issue) -> Option<usize> {
//! Makes a POST request to create a new issue with
//! the inputted params (title and description).
//!
//! Panics if the response is not 201 Created or the request fails.
//! Returns a number which represents the issue number from GitHub.
let mut response = self
.client
.post(&self.url)
.header(AUTHORIZATION, self.auth_header.clone())
.json(&issue.to_json())
.send()
.expect("Failed to create issue");
if !Self::is_successful_response(response.status()) {
return None;
}
match response.json::<issue::Response>() {
Ok(json) => Some(json.get_number()),
Err(_) => None,
}
}
pub fn get_issues(&self, is_dry_run: bool) -> Option<HashSet<String>> {
//! Makes a GET request to retrieve all issues (open and closed)
//! with a todo label in the remote repository.
//!
//! Returns a hashset of the issue titles. Returns early if the response
//! is not 200 OK or the request fails.
if is_dry_run {
return Some(HashSet::new());
}
println!(
"Fetching all issues with {} label from {}",
style(issue::LABEL).cyan(),
style(&self.remote_url).italic()
);
let params = json!({
"labels": issue::LABEL,
"state": "all",
});
let mut response = self
.client
.get(&self.url)
.header(AUTHORIZATION, self.auth_header.clone())
.query(¶ms)
.send()
.expect("Failed to get issues");
if !Self::is_successful_response(response.status()) {
return None;
}
let mut issues = HashSet::new();
if let Ok(json_array) = response.json::<Vec<issue::Response>>() {
for result in json_array {
issues.insert(result.get_title());
}
}
match issues.len() {
0 => println!(
"No previously opened issues found in the remote repo."
),
n => println!(
"Found {} previously opened {} in the remote repo.",
style(n).bold(),
cli::handle_plural(&n, "issue")
),
};
Some(issues)
}
fn is_successful_response(status: StatusCode) -> bool {
//! Asserts that the status code returned is either
//! 200 OK or 201 CREATED.
//!
//! Otherwise, outputs a detailed description about the error.
match status {
StatusCode::OK | StatusCode::CREATED => return true,
StatusCode::UNAUTHORIZED => cli::print_error(
"Unathorized request. \
Make sure your access token is valid and \
you have pull access to the repository.",
),
StatusCode::GONE => {
cli::print_error("Issues are disabled in this repository.");
}
StatusCode::FORBIDDEN => cli::print_error(
"You have reached the GitHub API rate limit. \
Please try again later.",
),
StatusCode::NOT_FOUND => cli::print_error(
"Remote repository not found. \
If your repository is private check that \
your access token has the correct permissions.",
),
StatusCode::UNPROCESSABLE_ENTITY => {
cli::print_error("Unable to process request.");
}
s => cli::print_error(
&format!("Received unexpected status code {}", s).to_string(),
),
};
false
}
}
|
use std::collections::{VecDeque, HashMap};
use redcode::types::*;
use redcode::traits;
pub type SimulationResult<T> = Result<T, SimulationError>;
pub type LoadResult<T> = Result<T, LoadError>;
/// Errors that can occur during simulation
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SimulationError
{
/// Core was already halted
Halted,
}
/// Errors that can occur during loading
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum LoadError
{
/// Validation error: program has invalid length
InvalidLength,
/// Validation error: invalid distance between programs
InvalidDistance,
/// Load cannot be called with no programs
EmptyLoad
}
/// Events that can happen during a running simulation
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SimulationEvent
{
/// Game ended in a tie
MaxCyclesReached,
/// Process split inner contains address of new pc
Split,
/// A process terminated
Terminated,
/// The Mars halted
Halted,
/// A process jumped address
Jumped,
/// Skipped happens in all `Skip if ...` instructions
Skipped,
/// Nothing happened
Stepped,
}
/// Core wars runtime
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mars<T>
where T: traits::Instruction
{
/// Mars memory
pub(super) memory: Vec<T>,
/// Instruction register
pub(super) ir: T,
/// Current Pid executing on the Mars
pub(super) pid: Pid,
/// Current program counter
pub(super) pc: Address,
/// Current numbered cycle core is executing
pub(super) cycle: usize,
/// Program counter for each process currently loaded into memory
pub(super) process_queue: VecDeque<(Pid, VecDeque<Address>)>,
/// Private storage space for warriors
pub(super) pspace: HashMap<Pin, Vec<Value>>,
/// Has the core finished executing
pub(super) halted: bool,
// Load constraints
/// Maximum length of programs when loading
pub(super) max_length: usize,
/// Minimum distance between programs when batch loading
pub(super) min_distance: usize,
// Mars information (const)
/// Mars version
pub(super) version: usize,
/// Size of P-space
pub(super) pspace_size: usize,
// Runtime constraints
/// Maximum of processes that can be on the process queue at any time
pub(super) max_processes: usize,
/// Maximum number of cycles that can pass before a tie is declared
pub(super) max_cycles: usize,
}
impl<T> Mars<T>
where T: traits::Instruction
{
/// Step forward one cycle
pub fn step(&mut self) -> SimulationResult<SimulationEvent>
{
if self.halted() { // can't step after the core is halted
return Err(SimulationError::Halted);
}
else if self.cycle() >= self.max_cycles() {
self.halted = true;
return Ok(SimulationEvent::MaxCyclesReached)
}
let pc = self.pc();
// Fetch instruction
self.ir = self.fetch(pc);
let (a_mode, b_mode) = (self.ir.a_mode(), self.ir.b_mode());
// PostIncrement phase
let predecrement = a_mode == AddressingMode::AIndirectPreDecrement ||
a_mode == AddressingMode::BIndirectPreDecrement ||
b_mode == AddressingMode::AIndirectPreDecrement ||
b_mode == AddressingMode::BIndirectPreDecrement;
// Preincrement phase
if predecrement {
// fetch direct target
let a_addr = self.calc_addr_offset(pc, self.ir.a());
let b_addr = self.calc_addr_offset(pc, self.ir.b());
let mut a = self.fetch(a_addr);
let mut b = self.fetch(b_addr);
let (a_a, a_b) = (a.a(), a.b());
let (b_a, b_b) = (b.a(), b.b());
// FIXME: combine these into a single match statement
match a_mode {
AddressingMode::AIndirectPreDecrement => { a.set_a(a_a + 1); }
AddressingMode::BIndirectPreDecrement => { a.set_b(a_b + 1); }
_ => {}
};
match b_mode {
AddressingMode::AIndirectPreDecrement => { b.set_a(b_a + 1); }
AddressingMode::BIndirectPreDecrement => { b.set_b(b_b + 1); }
_ => {}
};
self.store(a_addr, a);
self.store(b_addr, b);
}
// Execute instruction(updating the program counter and requeing it
// are handled in this phase)
let exec_event = self.execute();
// PostIncrement phase
let postincrement = a_mode == AddressingMode::AIndirectPostIncrement ||
a_mode == AddressingMode::BIndirectPostIncrement ||
b_mode == AddressingMode::AIndirectPostIncrement ||
b_mode == AddressingMode::BIndirectPostIncrement;
if postincrement {
// fetch direct target
let a_addr = self.calc_addr_offset(pc, self.ir.a());
let b_addr = self.calc_addr_offset(pc, self.ir.b());
let mut a = self.fetch(a_addr);
let mut b = self.fetch(b_addr);
let (a_a, a_b) = (a.a(), a.b());
let (b_a, b_b) = (b.a(), b.b());
// FIXME: combine these into a single match statement
match a_mode {
AddressingMode::AIndirectPreDecrement => { a.set_a(a_a + 1); }
AddressingMode::BIndirectPreDecrement => { a.set_b(a_b + 1); }
_ => {}
};
match b_mode {
AddressingMode::AIndirectPreDecrement => { b.set_a(b_a + 1); }
AddressingMode::BIndirectPreDecrement => { b.set_b(b_b + 1); }
_ => {}
};
// store result
self.store(a_addr, a);
self.store(b_addr, b);
}
// check if there are any more process queues running on the core
let (pid, q) = self.process_queue.pop_front().unwrap();
if !q.is_empty() {
self.process_queue.push_back((pid, q));
}
// If no there are no processes left
if self.process_queue.is_empty() {
Ok(self.halt())
} else {
// Fetch new queue
let &mut(curr_pid, ref mut curr_q) = self.process_queue.front_mut().unwrap();
self.pid = curr_pid;
self.pc = curr_q.pop_front().unwrap();
self.cycle += 1;
Ok(exec_event)
}
}
/// Has the core finished its execution. This can mean either a tie has
/// occurred or a warrior has emerged victoriors
pub fn halted(&self) -> bool
{
self.halted
}
/// Halt the Mars
#[inline]
fn halt(&mut self) -> SimulationEvent
{
self.halted = true;
SimulationEvent::Halted
}
/// Reset the Mars's memory and the process queue
pub fn reset(&mut self)
{
// reset memory
for e in self.memory.iter_mut() {
*e = Default::default();
}
self.process_queue.clear();
self.cycle = 0;
self.ir = Default::default();
self.halted = true;
}
/// Reset the Mar's memory, process queue, AND P-space
pub fn reset_hard(&mut self)
{
self.pspace.clear();
self.reset();
}
/// Load mutliple programs into the Mars, checking their spacing and their
/// length
/// # Arguments
/// * `programs`: programs and load information loaded in a tuple, cannot
/// be empty
/// # Return
/// `Ok(())` if the load was successful, otherwise an error with the
/// corresponding `SimulationError`
pub fn load_batch(&mut self, programs: Vec<(Address, Option<Pin>, &Vec<T>)>)
-> LoadResult<()>
{
// TODO: validate margin
// TODO: correct addresses that are out of bounds by modulo-ing them
if programs.is_empty() {
return Err(LoadError::EmptyLoad);
}
let valid_margin = true; // TODO
if valid_margin {
// load each program
for &(dest, maybe_pin, ref prog) in programs.iter() {
let pin = maybe_pin.unwrap_or(self.process_count() as Pid);
let cycle_memory_iter = (0..self.size())
.cycle()
.skip(dest as usize)
.take(prog.len())
.enumerate();
// copy program into memory
for (i, j) in cycle_memory_iter {
self.memory[j] = prog[i].clone();
}
self.pspace.insert(pin, vec![0; self.pspace_size]);
let mut q = VecDeque::new();
q.push_front(dest);
self.process_queue.push_front((pin, q));
}
self.halted = false;
let &mut (curr_pid, ref mut curr_q) = self.process_queue.front_mut()
.unwrap();
self.pc = curr_q.pop_front().unwrap();
self.pid = curr_pid;
Ok(())
} else {
Err(LoadError::InvalidDistance)
}
}
/// Get `Pid` currently executing on the core
///
/// # Panics
/// * Panics is the process queue is empty
#[inline]
pub fn pc(&self) -> Address
{
self.pc
}
/// Get the program counters for all processes
pub fn pcs(&self) -> Vec<Address>
{
let mut pcs = vec![self.pc()];
for &(_, ref q) in &self.process_queue {
pcs.extend(q.iter().cloned());
}
pcs
}
/// Current cycle core is executing
#[inline]
pub fn cycle(&self) -> usize
{
self.cycle
}
/// Get the current `Pid` executing
#[inline]
pub fn pid(&self) -> Pid
{
self.pid
}
/// Get all `Pid`s that are currently active in the order they will be
/// executing
pub fn pids(&self) -> Vec<Pid>
{
let mut pids = vec![self.pid()];
pids.extend(self.process_queue.iter().map(|&(pid, _)| pid));
pids
}
/// Size of memory
pub fn size(&self) -> usize
{
self.memory.len()
}
/// Size of private storage space
#[inline]
pub fn pspace_size(&self) -> usize
{
self.pspace_size
}
/// Version of core multiplied by `100`
#[inline]
pub fn version(&self) -> usize
{
self.version
}
/// Maximum number of processes that can be in the core queue
#[inline]
pub fn max_processes(&self) -> usize
{
self.max_processes
}
/// Maximum number of cycles before a tie is declared
#[inline]
pub fn max_cycles(&self) -> usize
{
self.max_cycles
}
/// Maximum number of instructions allowed in a program
#[inline]
pub fn max_length(&self) -> usize
{
self.max_length
}
/// Minimum distance allowed between programs
pub fn min_distance(&self) -> usize
{
self.min_distance
}
/// Get immutable reference to memory
pub fn memory(&self) -> &Vec<T>
{
&self.memory
}
/// Get an immutable reference to private storage
pub fn pspace(&self) -> &HashMap<Pin, Vec<Value>>
{
&self.pspace
}
/// Get the number of processes currently running
pub fn process_count(&self) -> usize
{
self.process_queue.iter().map(|&(_, ref q)| q.len()).sum()
}
/// Fetch reference to current queue
pub fn current_queue(&self) -> Option<&VecDeque<Address>>
{
if let Some(&(_, ref q)) = self.process_queue.front() {
Some(q)
} else {
None
}
}
/// Fetch mutable reference to current queue
fn current_queue_mut(&mut self) -> Option<&mut VecDeque<Address>>
{
if let Some(&mut (_, ref mut q)) = self.process_queue.front_mut() {
Some(q)
} else {
None
}
}
/// Execute the instrcution in the `Instruction` register
#[inline]
fn execute(&mut self) -> SimulationEvent
{
match self.ir.op() {
OpCode::Dat => self.exec_dat(),
OpCode::Mov => self.exec_mov(),
OpCode::Add => self.exec_add(),
OpCode::Sub => self.exec_sub(),
OpCode::Mul => self.exec_mul(),
OpCode::Div => self.exec_div(),
OpCode::Mod => self.exec_mod(),
OpCode::Jmp => self.exec_jmp(),
OpCode::Jmz => self.exec_jmz(),
OpCode::Jmn => self.exec_jmn(),
OpCode::Djn => self.exec_djn(),
OpCode::Spl => self.exec_spl(),
OpCode::Seq => self.exec_seq(),
OpCode::Sne => self.exec_sne(),
OpCode::Slt => self.exec_slt(),
OpCode::Ldp => self.exec_ldp(),
OpCode::Stp => self.exec_stp(),
OpCode::Nop => self.exec_nop(),
}
}
////////////////////////////////////////////////////////////////////////////
// Address resolution functions
////////////////////////////////////////////////////////////////////////////
/// Calculate the address after adding an offset
///
/// # Arguments
/// * `base`: base address
/// * `offset`: distance from base to calculate
#[inline]
fn calc_addr_offset(&self, base: Address, offset: Value) -> Address
{
if offset < 0 {
(base.wrapping_sub(-offset as Address) % self.size() as Address)
} else {
(base.wrapping_add(offset as Address) % self.size() as Address)
}
}
/// Get the effective of address of the current `Instruction`. This takes
/// into account the addressing mode of the field used
///
/// # Arguments
/// * `use_a_field`: should the A field be used for calculation, or B
#[inline]
fn effective_addr(&self, use_a_field: bool) -> Address
{
use self::AddressingMode::*;
// fetch the addressing mode and offset
let (mode, offset) = if use_a_field {
(self.ir.a_mode(), self.ir.a())
} else {
(self.ir.b_mode(), self.ir.b())
};
let pc = self.pc();
let direct = self.fetch(self.calc_addr_offset(pc, offset));
match mode {
Immediate => pc,
Direct => self.calc_addr_offset(pc, offset),
AIndirect
| AIndirectPreDecrement
| AIndirectPostIncrement =>
self.calc_addr_offset(pc, direct.a() + offset),
BIndirect
| BIndirectPreDecrement
| BIndirectPostIncrement =>
self.calc_addr_offset(pc, direct.b() + offset),
}
}
/// Get the effective of address of the current `Instruction`'s A Field
///
/// An alias for `Mars::effective_addr(true)`
fn effective_addr_a(&self) -> Address
{
self.effective_addr(true)
}
/// Get the effective of address of the current `Instruction`'s A Field
///
/// An alias for `Mars::effective_addr(false)`
fn effective_addr_b(&self) -> Address
{
self.effective_addr(false)
}
////////////////////////////////////////////////////////////////////////////
// Program counter utility functions
////////////////////////////////////////////////////////////////////////////
/// Move the program counter forward
fn step_pc(&mut self) -> SimulationEvent
{
let pc = self.pc();
self.pc = (pc + 1) % self.size() as Address;
SimulationEvent::Stepped
}
/// Move the program counter forward twice
fn skip_pc(&mut self) -> SimulationEvent
{
let pc = self.pc();
self.pc = (pc + 2) % self.size() as Address;
SimulationEvent::Skipped
}
/// Jump the program counter by an offset
///
/// # Arguments
/// * `offset`: amount to jump
fn jump_pc(&mut self, offset: Value) -> SimulationEvent
{
let pc = self.pc();
self.pc = self.calc_addr_offset(pc, offset);
SimulationEvent::Jumped
}
/// Move the program counter forward by one and then queue the program
/// counter onto the current queue
fn step_and_queue_pc(&mut self) -> SimulationEvent
{
self.step_pc();
let pc = self.pc();
self.current_queue_mut().unwrap().push_back(pc);
SimulationEvent::Stepped
}
/// Move the program counter forward twice and then queue the program
/// counter onto the current queue
fn skip_and_queue_pc(&mut self) -> SimulationEvent
{
self.skip_pc();
let pc = self.pc();
self.current_queue_mut().unwrap().push_back(pc);
SimulationEvent::Skipped
}
/// Jump the program counter by an offset and then queue the program
/// count onto the current queue
///
/// # Arguments
/// * `offset`: amount to jump by
fn jump_and_queue_pc(&mut self, offset: Value) -> SimulationEvent
{
self.jump_pc(offset);
// remove old pc
let pc = self.pc();
self.current_queue_mut().unwrap().push_back(pc);
SimulationEvent::Jumped
}
////////////////////////////////////////////////////////////////////////////
// Storage and retrieval functions
////////////////////////////////////////////////////////////////////////////
/// Store an `Instruction` in memory
///
/// # Arguments
/// * `addr`: address to store
/// * `instr`: instruction to store
fn store(&mut self, addr: Address, instr: T)
{
let mem_size = self.size();
self.memory[addr as usize % mem_size] = instr;
}
/// Store an instruction in a specified pspace
///
/// # Arguments
/// * `pin`: programs pin, used as a lookup key
/// * `addr`: address in the pspace to store
/// * `instr`: instruction to store
fn store_pspace(&mut self, pin: Pin, addr: Address, value: Value)
{
if let Some(pspace) = self.pspace.get_mut(&pin) {
let pspace_size = pspace.len();
pspace[addr as usize % pspace_size] = value;
} else {
// TODO: create pspace for pin
unimplemented!();
}
}
/// Store an `Instruction` into the memory location pointed at by the A
/// field of the instruction loaded into the instruction register
///
/// # Arguments
/// * `instr`: `Instruction` to store
fn store_effective_a(&mut self, instr: T)
{
let eff_addr = self.effective_addr_a();
self.store(eff_addr, instr)
}
/// Store an `Instruction` into the memory location pointed at by the B
/// field of the instruction loaded into the instruction register
///
/// # Arguments
/// * `instr`: `Instruction` to store
fn store_effective_b(&mut self, instr: T)
{
let eff_addr = self.effective_addr_b();
self.store(eff_addr, instr)
}
/// Fetch copy of instruction in memory
///
/// # Arguments
/// * `addr`: adress to fetch
fn fetch(&self, addr: Address) -> T
{
self.memory[addr as usize % self.size()].clone()
}
/// Fetch an instruction from a programs private storage
///
/// # Arguments
/// * `pin`: pin of program, used as lookup key
/// * `addr`: address of pspace to access
fn fetch_pspace(&self, pin: Pin, addr: Address) -> Value
{
if let Some(pspace) = self.pspace.get(&pin) {
pspace[addr as usize % pspace.len()]
} else {
// TODO: create new pspace
unimplemented!();
}
}
/// Fetch copy of instruction pointed at by the A field of the instruction
/// loaded into the instruction register
fn fetch_effective_a(&self) -> T
{
self.fetch(self.effective_addr_a())
}
/// Fetch copy of instruction pointed at by the B field of the instruction
/// loaded into the instruction register
fn fetch_effective_b(&self) -> T
{
self.fetch(self.effective_addr_b())
}
////////////////////////////////////////////////////////////////////////////
// Instruction execution functions
////////////////////////////////////////////////////////////////////////////
/// Execute `dat` instruction
///
/// Supported Modifiers: None
#[inline]
fn exec_dat(&mut self) -> SimulationEvent
{
let _ = self.current_queue_mut().unwrap().pop_front();
SimulationEvent::Terminated
}
/// Execute `mov` instruction
///
/// Supported Modifiers: `A` `B` `AB` `BA` `X` `F` `I`
#[inline]
fn exec_mov(&mut self) -> SimulationEvent
{
let a = self.fetch_effective_a();
let mut b = self.fetch_effective_b();
let (a_a, a_b) = (a.a(), a.b());
match self.ir.modifier() {
Modifier::A => {b.set_a(a_a);},
Modifier::B => {b.set_b(a_b);},
Modifier::AB => {b.set_a(a_b);},
Modifier::BA => {b.set_b(a_a);},
Modifier::F =>
{
b.set_a(a_a);
b.set_b(a_b);
},
Modifier::X =>
{
b.set_a(a_b);
b.set_b(a_a);
},
Modifier::I => b = a
}
self.store_effective_b(b);
self.step_and_queue_pc()
}
/// Execute `add` instruction
///
/// Supported Modifiers: `A` `B` `AB` `BA` `X` `F`
#[inline]
fn exec_add(&mut self) -> SimulationEvent
{
// TODO: math needs to be done modulo core size
let a = self.fetch_effective_a();
let mut b = self.fetch_effective_b();
let (a_a, a_b) = (a.a(), a.b());
let (b_a, b_b) = (b.a(), b.b());
match self.ir.modifier() {
Modifier::A => { b.set_a((b_a + a_a) % self.size() as Value); }
Modifier::B => { b.set_b((b_b + a_b) % self.size() as Value); }
Modifier::BA => { b.set_a((b_a + a_b) % self.size() as Value); }
Modifier::AB => { b.set_b((b_b + a_a) % self.size() as Value); }
Modifier::F
| Modifier::I =>
{
b.set_a((b_a + a_a) % self.size() as Value);
b.set_b((b_b + a_b) % self.size() as Value);
}
Modifier::X =>
{
b.set_b((b_b + a_a) % self.size() as Value);
b.set_a((b_a + a_b) % self.size() as Value);
}
}
self.store_effective_b(b);
self.step_and_queue_pc()
}
/// Execute `sub` instruction
///
/// Supported Modifiers: `A` `B` `AB` `BA` `X` `F`
#[inline]
fn exec_sub(&mut self) -> SimulationEvent
{
// TODO: math needs to be done modulo core size
let a = self.fetch_effective_a();
let mut b = self.fetch_effective_b();
let (a_a, a_b) = (a.a(), a.b());
let (b_a, b_b) = (b.a(), b.b());
match self.ir.modifier() {
Modifier::A => { b.set_a((b_a - a_a) % self.size() as Value); }
Modifier::B => { b.set_b((b_b - a_b) % self.size() as Value); }
Modifier::BA => { b.set_a((b_a - a_b) % self.size() as Value); }
Modifier::AB => { b.set_b((b_b - a_a) % self.size() as Value); }
Modifier::F
| Modifier::I =>
{
b.set_a((b_a - a_a) % self.size() as Value);
b.set_b((b_b - a_b) % self.size() as Value);
}
Modifier::X =>
{
b.set_b((b_b - a_a) % self.size() as Value);
b.set_a((b_a - a_b) % self.size() as Value);
}
}
self.store_effective_b(b);
self.step_and_queue_pc()
}
/// Execute `mul` instruction
///
/// Supported Modifiers: `A` `B` `AB` `BA` `X` `F`
#[inline]
fn exec_mul(&mut self) -> SimulationEvent
{
// TODO: math needs to be done modulo core size
let a = self.fetch_effective_a();
let mut b = self.fetch_effective_b();
let (a_a, a_b) = (a.a(), a.b());
let (b_a, b_b) = (b.a(), b.b());
match self.ir.modifier() {
Modifier::A => { b.set_a((b_a * a_a) % self.size() as Value); }
Modifier::B => { b.set_b((b_b * a_b) % self.size() as Value); }
Modifier::BA => { b.set_a((b_a * a_b) % self.size() as Value); }
Modifier::AB => { b.set_b((b_b * a_a) % self.size() as Value); }
Modifier::F
| Modifier::I =>
{
b.set_a((b_a * a_a) % self.size() as Value);
b.set_b((b_b * a_b) % self.size() as Value);
}
Modifier::X =>
{
b.set_b((b_b * a_a) % self.size() as Value);
b.set_a((b_a * a_b) % self.size() as Value);
}
}
self.store_effective_b(b);
self.step_and_queue_pc()
}
/// Execute `div` instruction
///
/// Supported Modifiers: `A` `B` `AB` `BA` `X` `F`
#[inline]
fn exec_div(&mut self) -> SimulationEvent
{
// TODO: math needs to be done modulo core size
// TODO: division by zero needs to kill the process
let a = self.fetch_effective_a();
let mut b = self.fetch_effective_b();
let (a_a, a_b) = (a.a(), a.b());
let (b_a, b_b) = (b.a(), b.b());
match self.ir.modifier() {
Modifier::A => { b.set_a((b_a / a_a) % self.size() as Value); }
Modifier::B => { b.set_b((b_b / a_b) % self.size() as Value); }
Modifier::BA => { b.set_a((b_a / a_b) % self.size() as Value); }
Modifier::AB => { b.set_b((b_b / a_a) % self.size() as Value); }
Modifier::F
| Modifier::I =>
{
b.set_a((b_a / a_a) % self.size() as Value);
b.set_b((b_b / a_b) % self.size() as Value);
}
Modifier::X =>
{
b.set_b((b_b / a_a) % self.size() as Value);
b.set_a((b_a / a_b) % self.size() as Value);
}
};
self.store_effective_b(b);
self.step_and_queue_pc()
}
/// Execute `mod` instruction
///
/// Supported Modifiers: `A` `B` `AB` `BA` `X` `F`
#[inline]
fn exec_mod(&mut self) -> SimulationEvent
{
// TODO: math needs to be done modulo core size
// TODO: division by zero needs to kill the process
let a = self.fetch_effective_a();
let mut b = self.fetch_effective_b();
let (a_a, a_b) = (a.a(), a.b());
let (b_a, b_b) = (b.a(), b.b());
match self.ir.modifier() {
Modifier::A => { b.set_a((b_a % a_a) % self.size() as Value); }
Modifier::B => { b.set_b((b_b % a_b) % self.size() as Value); }
Modifier::BA => { b.set_a((b_a % a_b) % self.size() as Value); }
Modifier::AB => { b.set_b((b_b % a_a) % self.size() as Value); }
Modifier::F
| Modifier::I =>
{
b.set_a((b_a % a_a) % self.size() as Value);
b.set_b((b_b % a_b) % self.size() as Value);
}
Modifier::X =>
{
b.set_b((b_b % a_a) % self.size() as Value);
b.set_a((b_a % a_b) % self.size() as Value);
}
};
self.store_effective_b(b);
self.step_and_queue_pc()
}
/// Execute `jmp` instruction
///
/// Supported Modifiers: `B`
#[inline]
fn exec_jmp(&mut self) -> SimulationEvent
{
match self.ir.a_mode() {
AddressingMode::Immediate
| AddressingMode::Direct =>
{
let offset = self.ir.a();
self.jump_and_queue_pc(offset);
}
// TODO
_ => unimplemented!()
};
SimulationEvent::Jumped
}
/// Execute `jmz` instruction
///
/// Supported Modifiers: `B`
#[inline]
fn exec_jmz(&mut self) -> SimulationEvent
{
let b = self.fetch_effective_b();
let offset = self.ir.a(); // TODO: needs to calculate jump offset
let jump = match self.ir.modifier() {
Modifier::A
| Modifier::BA => b.a() == 0,
Modifier::B
| Modifier::AB => b.b() == 0,
Modifier::F
| Modifier::I
| Modifier::X => b.a() == 0 && b.b() == 0,
};
if jump {
self.jump_and_queue_pc(offset)
} else {
self.step_and_queue_pc()
}
}
/// Execute `jmn` instruction
///
/// Supported Modifiers: `B`
#[inline]
fn exec_jmn(&mut self) -> SimulationEvent
{
let b = self.fetch_effective_b();
let offset = self.ir.a(); // TODO: needs to calculate jump offset
let jump = match self.ir.modifier() {
Modifier::A
| Modifier::BA => b.a() != 0,
Modifier::B
| Modifier::AB => b.b() != 0,
Modifier::F
| Modifier::I
| Modifier::X => b.a() != 0 && b.b() != 0,
};
if jump {
self.jump_and_queue_pc(offset)
} else {
self.step_and_queue_pc()
}
}
/// Execute `djn` instruction
///
/// Supported Modifiers: `B`
#[inline]
fn exec_djn(&mut self) -> SimulationEvent
{
// predecrement the instruction before checking if its not zero
let mut b = self.fetch_effective_b();
let (b_a, b_b) = (b.a(), b.b());
match self.ir.modifier() {
Modifier::A
| Modifier::BA => { b.set_a(b_a - 1); },
Modifier::B
| Modifier::AB => { b.set_b(b_b - 1); },
Modifier::F
| Modifier::I
| Modifier::X =>
{
b.set_a(b_a - 1);
b.set_b(b_b - 1);
}
};
self.store_effective_b(b);
self.exec_jmn()
}
/// Execute `spl` instruction
///
/// Supported Modifiers: `B`
#[inline]
fn exec_spl(&mut self) -> SimulationEvent
{
if self.process_count() < self.max_processes(){
let target = self.effective_addr_a();
self.current_queue_mut().unwrap().push_back(target);
self.step_and_queue_pc();
SimulationEvent::Split
} else {
self.step_and_queue_pc()
}
}
/// Execute `seq` instruction
///
/// Supported Modifiers: `A` `B` `AB` `BA` `X` `F` `I`
#[inline]
fn exec_seq(&mut self) -> SimulationEvent
{
let a = self.fetch_effective_a();
let b = self.fetch_effective_b();
let skip = match self.ir.modifier() {
Modifier::A => a.a() == b.b(),
Modifier::B => a.b() == b.b(),
Modifier::BA => a.a() == b.b(),
Modifier::AB => a.b() == b.a(),
Modifier::X => a.b() == b.a() &&
a.a() == b.b(),
Modifier::F
| Modifier::I => a.a() == b.a() &&
a.b() == b.b(),
};
if skip { self.skip_and_queue_pc() } else { self.step_and_queue_pc() }
}
/// Execute `sne` instruction
///
/// Supported Modifiers: `A` `B` `AB` `BA` `X` `F` `I`
#[inline]
fn exec_sne(&mut self) -> SimulationEvent
{
let a = self.fetch_effective_a();
let b = self.fetch_effective_b();
let skip = match self.ir.modifier() {
Modifier::A => a.a() != b.b(),
Modifier::B => a.b() != b.b(),
Modifier::BA => a.a() != b.b(),
Modifier::AB => a.b() != b.a(),
Modifier::X => a.b() != b.a() &&
a.a() != b.b(),
Modifier::F
| Modifier::I => a.a() != b.a() &&
a.b() != b.b(),
};
if skip { self.skip_and_queue_pc() } else { self.step_and_queue_pc() }
}
/// Execute `slt` instruction
///
/// Supported Modifiers: `A` `B` `AB` `BA` `X` `F` `I`
#[inline]
fn exec_slt(&mut self) -> SimulationEvent
{
let a = self.fetch_effective_a();
let b = self.fetch_effective_b();
let skip = match self.ir.modifier() {
Modifier::A => a.a() < b.b(),
Modifier::B => a.b() < b.b(),
Modifier::BA => a.a() < b.b(),
Modifier::AB => a.b() < b.a(),
Modifier::X => a.b() < b.a() &&
a.a() < b.b(),
Modifier::F
| Modifier::I => a.a() < b.a() &&
a.b() < b.b(),
};
if skip { self.skip_and_queue_pc() } else { self.step_and_queue_pc() }
}
/// Execute `ldp` instruction
///
/// Supported Modifiers: `A` `B` `AB` `BA` `X` `F` `I`
#[inline]
fn exec_ldp(&mut self) -> SimulationEvent
{
match self.ir.modifier() {
_ => unimplemented!()
}
}
/// Execute `stp` instruction
///
/// Supported Modifiers: `A` `B` `AB` `BA` `X` `F` `I`
#[inline]
fn exec_stp(&mut self) -> SimulationEvent
{
match self.ir.modifier() {
_ => unimplemented!()
}
}
/// Execute 'nop' instruction
#[inline]
fn exec_nop(&mut self) -> SimulationEvent
{
self.step_and_queue_pc()
}
}
#[cfg(test)]
mod test
{
use simulation::MarsBuilder;
use redcode::traits::Instruction;
use redcode::Instruction as InstructionStruct;
use super::*;
fn mov_test_program(modifier: Modifier) -> Vec<InstructionStruct>
{
vec![
InstructionStruct::new(
OpCode::Mov,
modifier,
1,
AddressingMode::Direct,
2,
AddressingMode::Direct
),
InstructionStruct::new(
OpCode::Dat,
Modifier::I,
1,
AddressingMode::Direct,
2,
AddressingMode::Direct
),
InstructionStruct::new(
OpCode::Mov,
Modifier::I,
3,
AddressingMode::Direct,
4,
AddressingMode::Direct
)
]
}
#[test]
fn test_load_batch_fails_empty_vector()
{
let mut mars: Mars<InstructionStruct> = MarsBuilder::new().build();
assert_eq!(
Err(LoadError::EmptyLoad),
mars.load_batch(vec![])
);
}
#[test]
#[ignore]
fn test_load_batch_load_fails_invalid_distance()
{
let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
.min_distance(10)
.build();
let useless_program = vec![Default::default(); 1];
// intentionally load the programs with invalid spacings
let result = mars.load_batch(vec![
(0, None, &useless_program),
(1, None, &useless_program),
]);
assert_eq!(Err(LoadError::InvalidDistance), result);
}
#[test]
fn test_batch_load_succeeds()
{
let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
.min_distance(10)
.max_length(10)
.build();
let useless_program = vec![Default::default(); 10];
// intentionally load the programs with invalid spacings
let result = mars.load_batch(vec![
(0, None, &useless_program),
(21, None, &useless_program),
]);
assert_eq!(Ok(()), result);
}
#[test]
fn test_step_errors_when_halted()
{
let mut mars: Mars<InstructionStruct> = MarsBuilder::new().build();
let result = mars.step();
assert_eq!(Err(SimulationError::Halted), result);
}
#[test]
pub fn test_dat()
{
let mut mars: Mars<InstructionStruct> = MarsBuilder::new().build_and_load(vec![
(0, None, &vec![Default::default(); 1])
])
.unwrap();
let result = mars.step();
assert_eq!(Ok(SimulationEvent::Halted), result);
assert_eq!(true, mars.halted());
}
#[test]
fn test_mov_i_mode()
{
let prog = mov_test_program(Modifier::I);
let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
.build_and_load(vec![
(0, None, &prog)
])
.unwrap();
let init_pc = mars.pc();
assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
assert_eq!(prog[1], mars.memory()[2]);
assert_eq!(init_pc + 1, mars.pc());
}
#[test]
fn test_mov_a_mode()
{
let prog = mov_test_program(Modifier::A);
let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
.build_and_load(vec![
(0, None, &prog)
])
.unwrap();
let init_pc = mars.pc();
assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
assert_eq!(prog[1].a(), mars.memory()[2].a());
assert_eq!(prog[1].a_mode(), mars.memory()[2].a_mode());
assert_eq!(init_pc + 1, mars.pc());
}
#[test]
fn test_mov_b_mode()
{
let prog = mov_test_program(Modifier::B);
let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
.build_and_load(vec![
(0, None, &prog)
])
.unwrap();
let init_pc = mars.pc();
assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
assert_eq!(prog[1].b(), mars.memory()[2].b());
assert_eq!(prog[1].b_mode(), mars.memory()[2].b_mode());
assert_eq!(init_pc + 1, mars.pc());
}
#[test]
fn test_mov_ab_mode()
{
let prog = mov_test_program(Modifier::AB);
let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
.build_and_load(vec![
(0, None, &prog)
])
.unwrap();
let init_pc = mars.pc();
assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
assert_eq!(prog[1].b(), mars.memory()[2].a());
assert_eq!(prog[1].b_mode(), mars.memory()[2].a_mode());
assert_eq!(init_pc + 1, mars.pc());
}
#[test]
fn test_mov_ba_mode()
{
let prog = mov_test_program(Modifier::BA);
let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
.build_and_load(vec![
(0, None, &prog)
])
.unwrap();
let init_pc = mars.pc();
assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
assert_eq!(prog[1].a(), mars.memory()[2].b());
assert_eq!(prog[1].a_mode(), mars.memory()[2].b_mode());
assert_eq!(init_pc + 1, mars.pc());
}
#[test]
fn test_mov_x_mode()
{
let prog = mov_test_program(Modifier::X);
let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
.build_and_load(vec![
(0, None, &prog)
])
.unwrap();
let init_pc = mars.pc();
assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
assert_eq!(prog[1].a(), mars.memory()[2].b());
assert_eq!(prog[1].a_mode(), mars.memory()[2].b_mode());
assert_eq!(prog[1].b(), mars.memory()[2].a());
assert_eq!(prog[1].b_mode(), mars.memory()[2].a_mode());
assert_eq!(init_pc + 1, mars.pc());
}
#[test]
fn test_mov_f_mode()
{
let prog = mov_test_program(Modifier::F);
let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
.build_and_load(vec![
(0, None, &prog)
])
.unwrap();
let init_pc = mars.pc();
assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
assert_eq!(prog[1].a(), mars.memory()[2].a());
assert_eq!(prog[1].a_mode(), mars.memory()[2].a_mode());
assert_eq!(prog[1].b(), mars.memory()[2].b());
assert_eq!(prog[1].b_mode(), mars.memory()[2].b_mode());
assert_eq!(init_pc + 1, mars.pc());
}
#[test]
fn test_seq_i_mode()
{
let prog = vec![
InstructionStruct::new(
OpCode::Seq,
Modifier::I,
0,
AddressingMode::Direct,
1,
AddressingMode::Direct
),
InstructionStruct::new(
OpCode::Seq,
Modifier::I,
0,
AddressingMode::Direct,
1,
AddressingMode::Direct
),
InstructionStruct::new(
OpCode::Seq,
Modifier::I,
0,
AddressingMode::Direct,
1,
AddressingMode::Direct
),
InstructionStruct::new(
OpCode::Seq,
Modifier::I,
0,
AddressingMode::Direct,
0,
AddressingMode::Direct
),
];
let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
.max_processes(10)
.build_and_load(vec![(0, None, &prog)])
.unwrap();
let init_pc = mars.pc();
assert_eq!(Ok(SimulationEvent::Skipped), mars.step());
assert_eq!(init_pc + 2, mars.pc());
assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
assert_eq!(init_pc + 3, mars.pc());
}
#[test]
fn test_spl_cant_create_more_than_max_processes()
{
// splitter program, infinitely creates imps
let prog = vec![
InstructionStruct::new(
OpCode::Spl,
Modifier::I,
2,
AddressingMode::Direct,
1,
AddressingMode::Direct,
),
InstructionStruct::new(
OpCode::Jmp,
Modifier::I,
-1,
AddressingMode::Direct,
1,
AddressingMode::Direct,
),
InstructionStruct::new(
OpCode::Mov,
Modifier::I,
0,
AddressingMode::Direct,
1,
AddressingMode::Direct,
),
];
let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
.max_processes(10)
.build_and_load(vec![(0, None, &prog)])
.unwrap();
assert_eq!(Ok(SimulationEvent::Split), mars.step());
// run the simulation until it halts because cycles have been exauste
while !mars.halted() {
let _ = mars.step();
}
assert_eq!(10, mars.process_count());
}
}
|
use day03;
fn main() {
let input: Vec<&str> = include_str!("../../input/2018/day3.txt").lines().collect();
println!("Part 1: {}", day03::part1(&input));
println!("Part 2: {}", day03::part2(&input));
}
|
// 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.
//! Defines an interface for request filters and some basic filters.
use fidl_fuchsia_ledger_cloud::{DeviceSetRequest, PageCloudRequest, PositionToken};
use std::cell::RefCell;
use std::collections::hash_map::{DefaultHasher, Entry, HashMap};
use std::hash::{Hash, Hasher};
use crate::types::*;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Status {
Ok,
NetworkError,
}
pub trait RequestFilter {
/// Decides whether to disconnect the PageCloudWatcher.
fn page_cloud_watcher_status(&self) -> Status;
/// Decides whether to disconnect the DeviceSetWatcher.
fn device_set_watcher_status(&self) -> Status;
/// Decides what to do with a DeviceSetRequest.
fn device_set_request_status(&self, req: &DeviceSetRequest) -> Status;
/// Decides what to do with a PageCloudRequest.
fn page_cloud_request_status(&self, req: &PageCloudRequest) -> Status;
}
/// Filter that always returns the same status for all requests.
pub struct Always(Status);
impl Always {
pub fn new(status: Status) -> Always {
Always(status)
}
}
impl RequestFilter for Always {
fn page_cloud_watcher_status(&self) -> Status {
self.0
}
fn device_set_watcher_status(&self) -> Status {
self.0
}
fn device_set_request_status(&self, _req: &DeviceSetRequest) -> Status {
self.0
}
fn page_cloud_request_status(&self, _req: &PageCloudRequest) -> Status {
self.0
}
}
/// Flaky network simulator: a given request on the PageCloud is
/// accepted after `required_retry_count` retries of this request. The
/// counter of a request is reset after it succeeds.
/// The behavior matches the INJECT_NETWORK_ERROR mode of the C++ fake
/// cloud provider: requests on the device set do not fail, and
/// watchers are not disconnected.
pub struct Flaky {
/// The number of errors to return for each request before a success.
required_retry_count: u64,
/// A map associating request signatures (obtained by hashing the
/// relevant part of the request) to the number of errors that
/// should still be returned for this request.
remaining_retries: RefCell<HashMap<u64, u64>>,
}
impl Flaky {
/// Creates a new `NetworkErrorInjector` injecting
/// `required_retry_count` errors for each request.
pub fn new(required_retry_count: u64) -> Flaky {
Flaky { required_retry_count, remaining_retries: RefCell::new(HashMap::new()) }
}
/// Returns a signature for a request, or `None` for requests that
/// should never fail.
fn signature(req: &PageCloudRequest) -> Option<u64> {
// We cannot Hash requests directly because they contain FIDL
// responders.
let mut hasher = DefaultHasher::new();
std::mem::discriminant(req).hash(&mut hasher);
match req {
PageCloudRequest::AddCommits { commits, .. } => {
if let Ok(commits) = Commit::deserialize_pack(&commits) {
for (commit, _diff) in commits.into_iter() {
commit.id.0.hash(&mut hasher);
}
}
}
PageCloudRequest::GetCommits { min_position_token, .. } => {
Self::hash_token(min_position_token, &mut hasher)
}
PageCloudRequest::AddObject { id, buffer: _, .. } => {
// Don't hash the buffer, it may be encrypted
// differently each time.
id.hash(&mut hasher);
}
PageCloudRequest::GetObject { id, .. } => id.hash(&mut hasher),
PageCloudRequest::GetDiff { commit_id, .. } => commit_id.hash(&mut hasher),
PageCloudRequest::SetWatcher { .. } => return None,
}
return Some(hasher.finish());
}
fn hash_token(token: &Option<Box<PositionToken>>, hasher: &mut DefaultHasher) {
if let Some(token) = token {
token.opaque_id.hash(hasher)
}
}
}
impl RequestFilter for Flaky {
fn page_cloud_watcher_status(&self) -> Status {
Status::Ok
}
fn device_set_watcher_status(&self) -> Status {
Status::Ok
}
fn device_set_request_status(&self, _req: &DeviceSetRequest) -> Status {
Status::Ok
}
fn page_cloud_request_status(&self, req: &PageCloudRequest) -> Status {
let sig = match Self::signature(req) {
None => return Status::Ok,
Some(sig) => sig,
};
let mut map = self.remaining_retries.borrow_mut();
match map.entry(sig) {
Entry::Occupied(mut entry) => {
if *entry.get() == 0 {
// It's worth removing the entries after requests
// are successful, as most requests will be retried
// until they succeed, and will not use more space
// in the map after succeeding.
entry.remove();
Status::Ok
} else {
entry.insert(entry.get() - 1);
Status::NetworkError
}
}
Entry::Vacant(entry) => {
entry.insert(self.required_retry_count - 1);
Status::NetworkError
}
}
}
}
|
use crate::{proto, Client, MakeClient, RateLimit};
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use tokio::sync::Semaphore;
use tracing::{debug, debug_span, trace};
use tracing_futures::Instrument;
#[derive(Clone)]
pub struct Runner {
clients: usize,
streams: usize,
rate_limit: RateLimit,
total_requests: Option<TotalRequestsLimit>,
}
#[derive(Clone)]
struct TotalRequestsLimit {
limit: usize,
issued: Arc<AtomicUsize>,
}
impl Runner {
pub fn new(
clients: usize,
streams: usize,
total_requests: usize,
rate_limit: RateLimit,
) -> Self {
assert!(clients > 0 && streams > 0);
let total_requests = if total_requests == 0 {
None
} else {
Some(TotalRequestsLimit {
limit: total_requests,
issued: Arc::new(0.into()),
})
};
Self {
clients,
streams,
rate_limit,
total_requests,
}
}
pub async fn run<C>(self, mut connect: C)
where
C: MakeClient + Clone + Send + 'static,
C::Client: Clone + Send + 'static,
{
let Self {
clients,
streams,
rate_limit,
total_requests,
} = self;
debug!(clients, streams, "Running");
let limit = rate_limit.spawn();
for c in 0..clients {
let client = connect.make_client().await;
for s in 0..streams {
let total_requests = total_requests.clone();
let limit = limit.clone();
let mut client = client.clone();
tokio::spawn(
async move {
loop {
if let Some(lim) = total_requests.as_ref() {
if lim.issued.fetch_add(1, Ordering::Release) >= lim.limit {
return;
}
}
let permit = limit.acquire().await;
trace!("Acquired permits");
// TODO generate request params (latency, size, error).
let spec = proto::ResponseSpec {
result: Some(proto::response_spec::Result::Success(
proto::response_spec::Success::default(),
)),
..Default::default()
};
let _ = client.get(spec).await;
drop(permit);
}
}
.instrument(debug_span!("runner", c, s)),
);
}
}
}
}
|
//! To run this code, clone the rusty_engine repository and run the command:
//!
//! cargo run --release --example layer
use rusty_engine::prelude::*;
fn main() {
let mut game = Game::new();
let mut layer = 0.0;
let preset_iterator = SpritePreset::variant_iter().peekable();
for (x, sprite_preset) in (-300..=600).step_by(30).zip(preset_iterator) {
let mut sprite = game.add_sprite(format!("{:?}", sprite_preset), sprite_preset);
sprite.translation = Vec2::new(x as f32, (-x) as f32);
sprite.layer = layer; // 0.0 is the bottom (back) layer. 999.0 is the top (front) layer.
layer += 1.0;
}
// We don't do anything after game setup, so our game logic can be an empty closure
game.run(());
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qtablewidget.h
// dst-file: /src/widgets/qtablewidget.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
use super::qtableview::*; // 773
// use super::qlist::*; // 775
use super::super::core::qstring::*; // 771
use super::super::core::qobjectdefs::*; // 771
// use super::qtablewidget::QTableWidgetItem; // 773
use super::super::core::qstringlist::*; // 771
use super::super::core::qrect::*; // 771
use super::qwidget::*; // 773
// use super::qtablewidget::QTableWidgetSelectionRange; // 773
use super::super::core::qpoint::*; // 771
use super::super::gui::qcolor::*; // 771
use super::super::core::qvariant::*; // 771
use super::super::core::qsize::*; // 771
use super::super::gui::qbrush::*; // 771
use super::super::gui::qfont::*; // 771
use super::super::gui::qicon::*; // 771
use super::super::core::qdatastream::*; // 771
// use super::qtablewidget::QTableWidget; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QTableWidgetSelectionRange_Class_Size() -> c_int;
// proto: void QTableWidgetSelectionRange::QTableWidgetSelectionRange(int top, int left, int bottom, int right);
fn C_ZN26QTableWidgetSelectionRangeC2Eiiii(arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int) -> u64;
// proto: int QTableWidgetSelectionRange::columnCount();
fn C_ZNK26QTableWidgetSelectionRange11columnCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QTableWidgetSelectionRange::rowCount();
fn C_ZNK26QTableWidgetSelectionRange8rowCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QTableWidgetSelectionRange::leftColumn();
fn C_ZNK26QTableWidgetSelectionRange10leftColumnEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QTableWidgetSelectionRange::~QTableWidgetSelectionRange();
fn C_ZN26QTableWidgetSelectionRangeD2Ev(qthis: u64 /* *mut c_void*/);
// proto: int QTableWidgetSelectionRange::topRow();
fn C_ZNK26QTableWidgetSelectionRange6topRowEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QTableWidgetSelectionRange::rightColumn();
fn C_ZNK26QTableWidgetSelectionRange11rightColumnEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QTableWidgetSelectionRange::QTableWidgetSelectionRange();
fn C_ZN26QTableWidgetSelectionRangeC2Ev() -> u64;
// proto: void QTableWidgetSelectionRange::QTableWidgetSelectionRange(const QTableWidgetSelectionRange & other);
fn C_ZN26QTableWidgetSelectionRangeC2ERKS_(arg0: *mut c_void) -> u64;
// proto: int QTableWidgetSelectionRange::bottomRow();
fn C_ZNK26QTableWidgetSelectionRange9bottomRowEv(qthis: u64 /* *mut c_void*/) -> c_int;
fn QTableWidget_Class_Size() -> c_int;
// proto: void QTableWidget::setColumnCount(int columns);
fn C_ZN12QTableWidget14setColumnCountEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QTableWidget::~QTableWidget();
fn C_ZN12QTableWidgetD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QList<QTableWidgetItem *> QTableWidget::selectedItems();
fn C_ZNK12QTableWidget13selectedItemsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QTableWidget::isSortingEnabled();
fn C_ZNK12QTableWidget16isSortingEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: const QMetaObject * QTableWidget::metaObject();
fn C_ZNK12QTableWidget10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QTableWidget::closePersistentEditor(QTableWidgetItem * item);
fn C_ZN12QTableWidget21closePersistentEditorEP16QTableWidgetItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QTableWidget::setHorizontalHeaderLabels(const QStringList & labels);
fn C_ZN12QTableWidget25setHorizontalHeaderLabelsERK11QStringList(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QTableWidget::setItemSelected(const QTableWidgetItem * item, bool select);
fn C_ZN12QTableWidget15setItemSelectedEPK16QTableWidgetItemb(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_char);
// proto: QTableWidgetItem * QTableWidget::takeItem(int row, int column);
fn C_ZN12QTableWidget8takeItemEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int) -> *mut c_void;
// proto: void QTableWidget::removeCellWidget(int row, int column);
fn C_ZN12QTableWidget16removeCellWidgetEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int);
// proto: void QTableWidget::setVerticalHeaderItem(int row, QTableWidgetItem * item);
fn C_ZN12QTableWidget21setVerticalHeaderItemEiP16QTableWidgetItem(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void);
// proto: QRect QTableWidget::visualItemRect(const QTableWidgetItem * item);
fn C_ZNK12QTableWidget14visualItemRectEPK16QTableWidgetItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: QTableWidgetItem * QTableWidget::currentItem();
fn C_ZNK12QTableWidget11currentItemEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QTableWidget::row(const QTableWidgetItem * item);
fn C_ZNK12QTableWidget3rowEPK16QTableWidgetItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_int;
// proto: void QTableWidget::removeRow(int row);
fn C_ZN12QTableWidget9removeRowEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QTableWidget::setItemPrototype(const QTableWidgetItem * item);
fn C_ZN12QTableWidget16setItemPrototypeEPK16QTableWidgetItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QTableWidget::QTableWidget(int rows, int columns, QWidget * parent);
fn C_ZN12QTableWidgetC2EiiP7QWidget(arg0: c_int, arg1: c_int, arg2: *mut c_void) -> u64;
// proto: int QTableWidget::visualRow(int logicalRow);
fn C_ZNK12QTableWidget9visualRowEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int;
// proto: void QTableWidget::setCellWidget(int row, int column, QWidget * widget);
fn C_ZN12QTableWidget13setCellWidgetEiiP7QWidget(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: *mut c_void);
// proto: void QTableWidget::openPersistentEditor(QTableWidgetItem * item);
fn C_ZN12QTableWidget20openPersistentEditorEP16QTableWidgetItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: int QTableWidget::columnCount();
fn C_ZNK12QTableWidget11columnCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QTableWidget::currentRow();
fn C_ZNK12QTableWidget10currentRowEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QTableWidget::setCurrentItem(QTableWidgetItem * item);
fn C_ZN12QTableWidget14setCurrentItemEP16QTableWidgetItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QWidget * QTableWidget::cellWidget(int row, int column);
fn C_ZNK12QTableWidget10cellWidgetEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int) -> *mut c_void;
// proto: void QTableWidget::setSortingEnabled(bool enable);
fn C_ZN12QTableWidget17setSortingEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QTableWidget::setItem(int row, int column, QTableWidgetItem * item);
fn C_ZN12QTableWidget7setItemEiiP16QTableWidgetItem(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: *mut c_void);
// proto: QTableWidgetItem * QTableWidget::horizontalHeaderItem(int column);
fn C_ZNK12QTableWidget20horizontalHeaderItemEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: void QTableWidget::editItem(QTableWidgetItem * item);
fn C_ZN12QTableWidget8editItemEP16QTableWidgetItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QList<QTableWidgetSelectionRange> QTableWidget::selectedRanges();
fn C_ZNK12QTableWidget14selectedRangesEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QTableWidget::currentColumn();
fn C_ZNK12QTableWidget13currentColumnEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QTableWidget::removeColumn(int column);
fn C_ZN12QTableWidget12removeColumnEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QTableWidget::setRangeSelected(const QTableWidgetSelectionRange & range, bool select);
fn C_ZN12QTableWidget16setRangeSelectedERK26QTableWidgetSelectionRangeb(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_char);
// proto: int QTableWidget::column(const QTableWidgetItem * item);
fn C_ZNK12QTableWidget6columnEPK16QTableWidgetItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_int;
// proto: bool QTableWidget::isItemSelected(const QTableWidgetItem * item);
fn C_ZNK12QTableWidget14isItemSelectedEPK16QTableWidgetItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
// proto: QTableWidgetItem * QTableWidget::takeVerticalHeaderItem(int row);
fn C_ZN12QTableWidget22takeVerticalHeaderItemEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: void QTableWidget::insertRow(int row);
fn C_ZN12QTableWidget9insertRowEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: int QTableWidget::rowCount();
fn C_ZNK12QTableWidget8rowCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: QTableWidgetItem * QTableWidget::item(int row, int column);
fn C_ZNK12QTableWidget4itemEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int) -> *mut c_void;
// proto: void QTableWidget::QTableWidget(QWidget * parent);
fn C_ZN12QTableWidgetC2EP7QWidget(arg0: *mut c_void) -> u64;
// proto: void QTableWidget::setVerticalHeaderLabels(const QStringList & labels);
fn C_ZN12QTableWidget23setVerticalHeaderLabelsERK11QStringList(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: const QTableWidgetItem * QTableWidget::itemPrototype();
fn C_ZNK12QTableWidget13itemPrototypeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QTableWidgetItem * QTableWidget::itemAt(const QPoint & p);
fn C_ZNK12QTableWidget6itemAtERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: void QTableWidget::clearContents();
fn C_ZN12QTableWidget13clearContentsEv(qthis: u64 /* *mut c_void*/);
// proto: QTableWidgetItem * QTableWidget::itemAt(int x, int y);
fn C_ZNK12QTableWidget6itemAtEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int) -> *mut c_void;
// proto: void QTableWidget::setCurrentCell(int row, int column);
fn C_ZN12QTableWidget14setCurrentCellEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int);
// proto: void QTableWidget::setRowCount(int rows);
fn C_ZN12QTableWidget11setRowCountEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QTableWidget::setHorizontalHeaderItem(int column, QTableWidgetItem * item);
fn C_ZN12QTableWidget23setHorizontalHeaderItemEiP16QTableWidgetItem(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void);
// proto: int QTableWidget::visualColumn(int logicalColumn);
fn C_ZNK12QTableWidget12visualColumnEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int;
// proto: QTableWidgetItem * QTableWidget::takeHorizontalHeaderItem(int column);
fn C_ZN12QTableWidget24takeHorizontalHeaderItemEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: QTableWidgetItem * QTableWidget::verticalHeaderItem(int row);
fn C_ZNK12QTableWidget18verticalHeaderItemEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: void QTableWidget::clear();
fn C_ZN12QTableWidget5clearEv(qthis: u64 /* *mut c_void*/);
// proto: void QTableWidget::insertColumn(int column);
fn C_ZN12QTableWidget12insertColumnEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
fn QTableWidgetItem_Class_Size() -> c_int;
// proto: QColor QTableWidgetItem::backgroundColor();
fn C_ZNK16QTableWidgetItem15backgroundColorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QVariant QTableWidgetItem::data(int role);
fn C_ZNK16QTableWidgetItem4dataEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: void QTableWidgetItem::setSelected(bool select);
fn C_ZN16QTableWidgetItem11setSelectedEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QTableWidgetItem::setStatusTip(const QString & statusTip);
fn C_ZN16QTableWidgetItem12setStatusTipERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QColor QTableWidgetItem::textColor();
fn C_ZNK16QTableWidgetItem9textColorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QTableWidgetItem::~QTableWidgetItem();
fn C_ZN16QTableWidgetItemD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QString QTableWidgetItem::text();
fn C_ZNK16QTableWidgetItem4textEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QTableWidgetItem::setSizeHint(const QSize & size);
fn C_ZN16QTableWidgetItem11setSizeHintERK5QSize(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QBrush QTableWidgetItem::foreground();
fn C_ZNK16QTableWidgetItem10foregroundEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QTableWidgetItem::type();
fn C_ZNK16QTableWidgetItem4typeEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QTableWidgetItem::column();
fn C_ZNK16QTableWidgetItem6columnEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QTableWidgetItem::setTextAlignment(int alignment);
fn C_ZN16QTableWidgetItem16setTextAlignmentEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: QFont QTableWidgetItem::font();
fn C_ZNK16QTableWidgetItem4fontEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QIcon QTableWidgetItem::icon();
fn C_ZNK16QTableWidgetItem4iconEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QTableWidgetItem::write(QDataStream & out);
fn C_ZNK16QTableWidgetItem5writeER11QDataStream(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QTableWidgetItem::QTableWidgetItem(const QTableWidgetItem & other);
fn C_ZN16QTableWidgetItemC2ERKS_(arg0: *mut c_void) -> u64;
// proto: QBrush QTableWidgetItem::background();
fn C_ZNK16QTableWidgetItem10backgroundEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QTableWidgetItem::setIcon(const QIcon & icon);
fn C_ZN16QTableWidgetItem7setIconERK5QIcon(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QTableWidgetItem::QTableWidgetItem(const QString & text, int type);
fn C_ZN16QTableWidgetItemC2ERK7QStringi(arg0: *mut c_void, arg1: c_int) -> u64;
// proto: QString QTableWidgetItem::statusTip();
fn C_ZNK16QTableWidgetItem9statusTipEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QTableWidgetItem * QTableWidgetItem::clone();
fn C_ZNK16QTableWidgetItem5cloneEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QTableWidgetItem::QTableWidgetItem(int type);
fn C_ZN16QTableWidgetItemC2Ei(arg0: c_int) -> u64;
// proto: void QTableWidgetItem::setWhatsThis(const QString & whatsThis);
fn C_ZN16QTableWidgetItem12setWhatsThisERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QSize QTableWidgetItem::sizeHint();
fn C_ZNK16QTableWidgetItem8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QTableWidgetItem::setForeground(const QBrush & brush);
fn C_ZN16QTableWidgetItem13setForegroundERK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: int QTableWidgetItem::row();
fn C_ZNK16QTableWidgetItem3rowEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QTableWidgetItem::setData(int role, const QVariant & value);
fn C_ZN16QTableWidgetItem7setDataEiRK8QVariant(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void);
// proto: QTableWidget * QTableWidgetItem::tableWidget();
fn C_ZNK16QTableWidgetItem11tableWidgetEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QTableWidgetItem::QTableWidgetItem(const QIcon & icon, const QString & text, int type);
fn C_ZN16QTableWidgetItemC2ERK5QIconRK7QStringi(arg0: *mut c_void, arg1: *mut c_void, arg2: c_int) -> u64;
// proto: int QTableWidgetItem::textAlignment();
fn C_ZNK16QTableWidgetItem13textAlignmentEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QTableWidgetItem::read(QDataStream & in);
fn C_ZN16QTableWidgetItem4readER11QDataStream(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QString QTableWidgetItem::toolTip();
fn C_ZNK16QTableWidgetItem7toolTipEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QTableWidgetItem::isSelected();
fn C_ZNK16QTableWidgetItem10isSelectedEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QTableWidgetItem::setBackgroundColor(const QColor & color);
fn C_ZN16QTableWidgetItem18setBackgroundColorERK6QColor(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QTableWidgetItem::setBackground(const QBrush & brush);
fn C_ZN16QTableWidgetItem13setBackgroundERK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QTableWidgetItem::setFont(const QFont & font);
fn C_ZN16QTableWidgetItem7setFontERK5QFont(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QTableWidgetItem::setTextColor(const QColor & color);
fn C_ZN16QTableWidgetItem12setTextColorERK6QColor(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QTableWidgetItem::setText(const QString & text);
fn C_ZN16QTableWidgetItem7setTextERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QString QTableWidgetItem::whatsThis();
fn C_ZNK16QTableWidgetItem9whatsThisEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QTableWidgetItem::setToolTip(const QString & toolTip);
fn C_ZN16QTableWidgetItem10setToolTipERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget13itemActivatedEP16QTableWidgetItem(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget20itemSelectionChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget11itemChangedEP16QTableWidgetItem(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget11itemPressedEP16QTableWidgetItem(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget18currentItemChangedEP16QTableWidgetItemS1_(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget18currentCellChangedEiiii(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget11itemEnteredEP16QTableWidgetItem(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget11cellEnteredEii(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget13cellActivatedEii(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget11itemClickedEP16QTableWidgetItem(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget11cellClickedEii(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget17itemDoubleClickedEP16QTableWidgetItem(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget17cellDoubleClickedEii(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget11cellChangedEii(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTableWidget_SlotProxy_connect__ZN12QTableWidget11cellPressedEii(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QTableWidgetSelectionRange)=16
#[derive(Default)]
pub struct QTableWidgetSelectionRange {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QTableWidget)=1
#[derive(Default)]
pub struct QTableWidget {
qbase: QTableView,
pub qclsinst: u64 /* *mut c_void*/,
pub _itemDoubleClicked: QTableWidget_itemDoubleClicked_signal,
pub _cellEntered: QTableWidget_cellEntered_signal,
pub _itemClicked: QTableWidget_itemClicked_signal,
pub _currentItemChanged: QTableWidget_currentItemChanged_signal,
pub _itemEntered: QTableWidget_itemEntered_signal,
pub _itemPressed: QTableWidget_itemPressed_signal,
pub _cellClicked: QTableWidget_cellClicked_signal,
pub _itemSelectionChanged: QTableWidget_itemSelectionChanged_signal,
pub _cellChanged: QTableWidget_cellChanged_signal,
pub _itemActivated: QTableWidget_itemActivated_signal,
pub _cellActivated: QTableWidget_cellActivated_signal,
pub _itemChanged: QTableWidget_itemChanged_signal,
pub _currentCellChanged: QTableWidget_currentCellChanged_signal,
pub _cellDoubleClicked: QTableWidget_cellDoubleClicked_signal,
pub _cellPressed: QTableWidget_cellPressed_signal,
}
// class sizeof(QTableWidgetItem)=1
#[derive(Default)]
pub struct QTableWidgetItem {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QTableWidgetSelectionRange {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QTableWidgetSelectionRange {
return QTableWidgetSelectionRange{qclsinst: qthis, ..Default::default()};
}
}
// proto: void QTableWidgetSelectionRange::QTableWidgetSelectionRange(int top, int left, int bottom, int right);
impl /*struct*/ QTableWidgetSelectionRange {
pub fn new<T: QTableWidgetSelectionRange_new>(value: T) -> QTableWidgetSelectionRange {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QTableWidgetSelectionRange_new {
fn new(self) -> QTableWidgetSelectionRange;
}
// proto: void QTableWidgetSelectionRange::QTableWidgetSelectionRange(int top, int left, int bottom, int right);
impl<'a> /*trait*/ QTableWidgetSelectionRange_new for (i32, i32, i32, i32) {
fn new(self) -> QTableWidgetSelectionRange {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN26QTableWidgetSelectionRangeC2Eiiii()};
let ctysz: c_int = unsafe{QTableWidgetSelectionRange_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let qthis: u64 = unsafe {C_ZN26QTableWidgetSelectionRangeC2Eiiii(arg0, arg1, arg2, arg3)};
let rsthis = QTableWidgetSelectionRange{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: int QTableWidgetSelectionRange::columnCount();
impl /*struct*/ QTableWidgetSelectionRange {
pub fn columnCount<RetType, T: QTableWidgetSelectionRange_columnCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.columnCount(self);
// return 1;
}
}
pub trait QTableWidgetSelectionRange_columnCount<RetType> {
fn columnCount(self , rsthis: & QTableWidgetSelectionRange) -> RetType;
}
// proto: int QTableWidgetSelectionRange::columnCount();
impl<'a> /*trait*/ QTableWidgetSelectionRange_columnCount<i32> for () {
fn columnCount(self , rsthis: & QTableWidgetSelectionRange) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK26QTableWidgetSelectionRange11columnCountEv()};
let mut ret = unsafe {C_ZNK26QTableWidgetSelectionRange11columnCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QTableWidgetSelectionRange::rowCount();
impl /*struct*/ QTableWidgetSelectionRange {
pub fn rowCount<RetType, T: QTableWidgetSelectionRange_rowCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.rowCount(self);
// return 1;
}
}
pub trait QTableWidgetSelectionRange_rowCount<RetType> {
fn rowCount(self , rsthis: & QTableWidgetSelectionRange) -> RetType;
}
// proto: int QTableWidgetSelectionRange::rowCount();
impl<'a> /*trait*/ QTableWidgetSelectionRange_rowCount<i32> for () {
fn rowCount(self , rsthis: & QTableWidgetSelectionRange) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK26QTableWidgetSelectionRange8rowCountEv()};
let mut ret = unsafe {C_ZNK26QTableWidgetSelectionRange8rowCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QTableWidgetSelectionRange::leftColumn();
impl /*struct*/ QTableWidgetSelectionRange {
pub fn leftColumn<RetType, T: QTableWidgetSelectionRange_leftColumn<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.leftColumn(self);
// return 1;
}
}
pub trait QTableWidgetSelectionRange_leftColumn<RetType> {
fn leftColumn(self , rsthis: & QTableWidgetSelectionRange) -> RetType;
}
// proto: int QTableWidgetSelectionRange::leftColumn();
impl<'a> /*trait*/ QTableWidgetSelectionRange_leftColumn<i32> for () {
fn leftColumn(self , rsthis: & QTableWidgetSelectionRange) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK26QTableWidgetSelectionRange10leftColumnEv()};
let mut ret = unsafe {C_ZNK26QTableWidgetSelectionRange10leftColumnEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTableWidgetSelectionRange::~QTableWidgetSelectionRange();
impl /*struct*/ QTableWidgetSelectionRange {
pub fn free<RetType, T: QTableWidgetSelectionRange_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QTableWidgetSelectionRange_free<RetType> {
fn free(self , rsthis: & QTableWidgetSelectionRange) -> RetType;
}
// proto: void QTableWidgetSelectionRange::~QTableWidgetSelectionRange();
impl<'a> /*trait*/ QTableWidgetSelectionRange_free<()> for () {
fn free(self , rsthis: & QTableWidgetSelectionRange) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN26QTableWidgetSelectionRangeD2Ev()};
unsafe {C_ZN26QTableWidgetSelectionRangeD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: int QTableWidgetSelectionRange::topRow();
impl /*struct*/ QTableWidgetSelectionRange {
pub fn topRow<RetType, T: QTableWidgetSelectionRange_topRow<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.topRow(self);
// return 1;
}
}
pub trait QTableWidgetSelectionRange_topRow<RetType> {
fn topRow(self , rsthis: & QTableWidgetSelectionRange) -> RetType;
}
// proto: int QTableWidgetSelectionRange::topRow();
impl<'a> /*trait*/ QTableWidgetSelectionRange_topRow<i32> for () {
fn topRow(self , rsthis: & QTableWidgetSelectionRange) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK26QTableWidgetSelectionRange6topRowEv()};
let mut ret = unsafe {C_ZNK26QTableWidgetSelectionRange6topRowEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QTableWidgetSelectionRange::rightColumn();
impl /*struct*/ QTableWidgetSelectionRange {
pub fn rightColumn<RetType, T: QTableWidgetSelectionRange_rightColumn<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.rightColumn(self);
// return 1;
}
}
pub trait QTableWidgetSelectionRange_rightColumn<RetType> {
fn rightColumn(self , rsthis: & QTableWidgetSelectionRange) -> RetType;
}
// proto: int QTableWidgetSelectionRange::rightColumn();
impl<'a> /*trait*/ QTableWidgetSelectionRange_rightColumn<i32> for () {
fn rightColumn(self , rsthis: & QTableWidgetSelectionRange) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK26QTableWidgetSelectionRange11rightColumnEv()};
let mut ret = unsafe {C_ZNK26QTableWidgetSelectionRange11rightColumnEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTableWidgetSelectionRange::QTableWidgetSelectionRange();
impl<'a> /*trait*/ QTableWidgetSelectionRange_new for () {
fn new(self) -> QTableWidgetSelectionRange {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN26QTableWidgetSelectionRangeC2Ev()};
let ctysz: c_int = unsafe{QTableWidgetSelectionRange_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN26QTableWidgetSelectionRangeC2Ev()};
let rsthis = QTableWidgetSelectionRange{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QTableWidgetSelectionRange::QTableWidgetSelectionRange(const QTableWidgetSelectionRange & other);
impl<'a> /*trait*/ QTableWidgetSelectionRange_new for (&'a QTableWidgetSelectionRange) {
fn new(self) -> QTableWidgetSelectionRange {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN26QTableWidgetSelectionRangeC2ERKS_()};
let ctysz: c_int = unsafe{QTableWidgetSelectionRange_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN26QTableWidgetSelectionRangeC2ERKS_(arg0)};
let rsthis = QTableWidgetSelectionRange{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: int QTableWidgetSelectionRange::bottomRow();
impl /*struct*/ QTableWidgetSelectionRange {
pub fn bottomRow<RetType, T: QTableWidgetSelectionRange_bottomRow<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.bottomRow(self);
// return 1;
}
}
pub trait QTableWidgetSelectionRange_bottomRow<RetType> {
fn bottomRow(self , rsthis: & QTableWidgetSelectionRange) -> RetType;
}
// proto: int QTableWidgetSelectionRange::bottomRow();
impl<'a> /*trait*/ QTableWidgetSelectionRange_bottomRow<i32> for () {
fn bottomRow(self , rsthis: & QTableWidgetSelectionRange) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK26QTableWidgetSelectionRange9bottomRowEv()};
let mut ret = unsafe {C_ZNK26QTableWidgetSelectionRange9bottomRowEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
impl /*struct*/ QTableWidget {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QTableWidget {
return QTableWidget{qbase: QTableView::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QTableWidget {
type Target = QTableView;
fn deref(&self) -> &QTableView {
return & self.qbase;
}
}
impl AsRef<QTableView> for QTableWidget {
fn as_ref(& self) -> & QTableView {
return & self.qbase;
}
}
// proto: void QTableWidget::setColumnCount(int columns);
impl /*struct*/ QTableWidget {
pub fn setColumnCount<RetType, T: QTableWidget_setColumnCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setColumnCount(self);
// return 1;
}
}
pub trait QTableWidget_setColumnCount<RetType> {
fn setColumnCount(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setColumnCount(int columns);
impl<'a> /*trait*/ QTableWidget_setColumnCount<()> for (i32) {
fn setColumnCount(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget14setColumnCountEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QTableWidget14setColumnCountEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidget::~QTableWidget();
impl /*struct*/ QTableWidget {
pub fn free<RetType, T: QTableWidget_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QTableWidget_free<RetType> {
fn free(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::~QTableWidget();
impl<'a> /*trait*/ QTableWidget_free<()> for () {
fn free(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidgetD2Ev()};
unsafe {C_ZN12QTableWidgetD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QList<QTableWidgetItem *> QTableWidget::selectedItems();
impl /*struct*/ QTableWidget {
pub fn selectedItems<RetType, T: QTableWidget_selectedItems<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.selectedItems(self);
// return 1;
}
}
pub trait QTableWidget_selectedItems<RetType> {
fn selectedItems(self , rsthis: & QTableWidget) -> RetType;
}
// proto: QList<QTableWidgetItem *> QTableWidget::selectedItems();
impl<'a> /*trait*/ QTableWidget_selectedItems<u64> for () {
fn selectedItems(self , rsthis: & QTableWidget) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget13selectedItemsEv()};
let mut ret = unsafe {C_ZNK12QTableWidget13selectedItemsEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: bool QTableWidget::isSortingEnabled();
impl /*struct*/ QTableWidget {
pub fn isSortingEnabled<RetType, T: QTableWidget_isSortingEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isSortingEnabled(self);
// return 1;
}
}
pub trait QTableWidget_isSortingEnabled<RetType> {
fn isSortingEnabled(self , rsthis: & QTableWidget) -> RetType;
}
// proto: bool QTableWidget::isSortingEnabled();
impl<'a> /*trait*/ QTableWidget_isSortingEnabled<i8> for () {
fn isSortingEnabled(self , rsthis: & QTableWidget) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget16isSortingEnabledEv()};
let mut ret = unsafe {C_ZNK12QTableWidget16isSortingEnabledEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: const QMetaObject * QTableWidget::metaObject();
impl /*struct*/ QTableWidget {
pub fn metaObject<RetType, T: QTableWidget_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QTableWidget_metaObject<RetType> {
fn metaObject(self , rsthis: & QTableWidget) -> RetType;
}
// proto: const QMetaObject * QTableWidget::metaObject();
impl<'a> /*trait*/ QTableWidget_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QTableWidget) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget10metaObjectEv()};
let mut ret = unsafe {C_ZNK12QTableWidget10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidget::closePersistentEditor(QTableWidgetItem * item);
impl /*struct*/ QTableWidget {
pub fn closePersistentEditor<RetType, T: QTableWidget_closePersistentEditor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.closePersistentEditor(self);
// return 1;
}
}
pub trait QTableWidget_closePersistentEditor<RetType> {
fn closePersistentEditor(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::closePersistentEditor(QTableWidgetItem * item);
impl<'a> /*trait*/ QTableWidget_closePersistentEditor<()> for (&'a QTableWidgetItem) {
fn closePersistentEditor(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget21closePersistentEditorEP16QTableWidgetItem()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QTableWidget21closePersistentEditorEP16QTableWidgetItem(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidget::setHorizontalHeaderLabels(const QStringList & labels);
impl /*struct*/ QTableWidget {
pub fn setHorizontalHeaderLabels<RetType, T: QTableWidget_setHorizontalHeaderLabels<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setHorizontalHeaderLabels(self);
// return 1;
}
}
pub trait QTableWidget_setHorizontalHeaderLabels<RetType> {
fn setHorizontalHeaderLabels(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setHorizontalHeaderLabels(const QStringList & labels);
impl<'a> /*trait*/ QTableWidget_setHorizontalHeaderLabels<()> for (&'a QStringList) {
fn setHorizontalHeaderLabels(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget25setHorizontalHeaderLabelsERK11QStringList()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QTableWidget25setHorizontalHeaderLabelsERK11QStringList(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidget::setItemSelected(const QTableWidgetItem * item, bool select);
impl /*struct*/ QTableWidget {
pub fn setItemSelected<RetType, T: QTableWidget_setItemSelected<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setItemSelected(self);
// return 1;
}
}
pub trait QTableWidget_setItemSelected<RetType> {
fn setItemSelected(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setItemSelected(const QTableWidgetItem * item, bool select);
impl<'a> /*trait*/ QTableWidget_setItemSelected<()> for (&'a QTableWidgetItem, i8) {
fn setItemSelected(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget15setItemSelectedEPK16QTableWidgetItemb()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_char;
unsafe {C_ZN12QTableWidget15setItemSelectedEPK16QTableWidgetItemb(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QTableWidgetItem * QTableWidget::takeItem(int row, int column);
impl /*struct*/ QTableWidget {
pub fn takeItem<RetType, T: QTableWidget_takeItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.takeItem(self);
// return 1;
}
}
pub trait QTableWidget_takeItem<RetType> {
fn takeItem(self , rsthis: & QTableWidget) -> RetType;
}
// proto: QTableWidgetItem * QTableWidget::takeItem(int row, int column);
impl<'a> /*trait*/ QTableWidget_takeItem<QTableWidgetItem> for (i32, i32) {
fn takeItem(self , rsthis: & QTableWidget) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget8takeItemEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let mut ret = unsafe {C_ZN12QTableWidget8takeItemEii(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QTableWidgetItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidget::removeCellWidget(int row, int column);
impl /*struct*/ QTableWidget {
pub fn removeCellWidget<RetType, T: QTableWidget_removeCellWidget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.removeCellWidget(self);
// return 1;
}
}
pub trait QTableWidget_removeCellWidget<RetType> {
fn removeCellWidget(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::removeCellWidget(int row, int column);
impl<'a> /*trait*/ QTableWidget_removeCellWidget<()> for (i32, i32) {
fn removeCellWidget(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget16removeCellWidgetEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
unsafe {C_ZN12QTableWidget16removeCellWidgetEii(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QTableWidget::setVerticalHeaderItem(int row, QTableWidgetItem * item);
impl /*struct*/ QTableWidget {
pub fn setVerticalHeaderItem<RetType, T: QTableWidget_setVerticalHeaderItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setVerticalHeaderItem(self);
// return 1;
}
}
pub trait QTableWidget_setVerticalHeaderItem<RetType> {
fn setVerticalHeaderItem(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setVerticalHeaderItem(int row, QTableWidgetItem * item);
impl<'a> /*trait*/ QTableWidget_setVerticalHeaderItem<()> for (i32, &'a QTableWidgetItem) {
fn setVerticalHeaderItem(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget21setVerticalHeaderItemEiP16QTableWidgetItem()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN12QTableWidget21setVerticalHeaderItemEiP16QTableWidgetItem(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QRect QTableWidget::visualItemRect(const QTableWidgetItem * item);
impl /*struct*/ QTableWidget {
pub fn visualItemRect<RetType, T: QTableWidget_visualItemRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.visualItemRect(self);
// return 1;
}
}
pub trait QTableWidget_visualItemRect<RetType> {
fn visualItemRect(self , rsthis: & QTableWidget) -> RetType;
}
// proto: QRect QTableWidget::visualItemRect(const QTableWidgetItem * item);
impl<'a> /*trait*/ QTableWidget_visualItemRect<QRect> for (&'a QTableWidgetItem) {
fn visualItemRect(self , rsthis: & QTableWidget) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget14visualItemRectEPK16QTableWidgetItem()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK12QTableWidget14visualItemRectEPK16QTableWidgetItem(rsthis.qclsinst, arg0)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QTableWidgetItem * QTableWidget::currentItem();
impl /*struct*/ QTableWidget {
pub fn currentItem<RetType, T: QTableWidget_currentItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.currentItem(self);
// return 1;
}
}
pub trait QTableWidget_currentItem<RetType> {
fn currentItem(self , rsthis: & QTableWidget) -> RetType;
}
// proto: QTableWidgetItem * QTableWidget::currentItem();
impl<'a> /*trait*/ QTableWidget_currentItem<QTableWidgetItem> for () {
fn currentItem(self , rsthis: & QTableWidget) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget11currentItemEv()};
let mut ret = unsafe {C_ZNK12QTableWidget11currentItemEv(rsthis.qclsinst)};
let mut ret1 = QTableWidgetItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QTableWidget::row(const QTableWidgetItem * item);
impl /*struct*/ QTableWidget {
pub fn row<RetType, T: QTableWidget_row<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.row(self);
// return 1;
}
}
pub trait QTableWidget_row<RetType> {
fn row(self , rsthis: & QTableWidget) -> RetType;
}
// proto: int QTableWidget::row(const QTableWidgetItem * item);
impl<'a> /*trait*/ QTableWidget_row<i32> for (&'a QTableWidgetItem) {
fn row(self , rsthis: & QTableWidget) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget3rowEPK16QTableWidgetItem()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK12QTableWidget3rowEPK16QTableWidgetItem(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTableWidget::removeRow(int row);
impl /*struct*/ QTableWidget {
pub fn removeRow<RetType, T: QTableWidget_removeRow<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.removeRow(self);
// return 1;
}
}
pub trait QTableWidget_removeRow<RetType> {
fn removeRow(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::removeRow(int row);
impl<'a> /*trait*/ QTableWidget_removeRow<()> for (i32) {
fn removeRow(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget9removeRowEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QTableWidget9removeRowEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidget::setItemPrototype(const QTableWidgetItem * item);
impl /*struct*/ QTableWidget {
pub fn setItemPrototype<RetType, T: QTableWidget_setItemPrototype<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setItemPrototype(self);
// return 1;
}
}
pub trait QTableWidget_setItemPrototype<RetType> {
fn setItemPrototype(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setItemPrototype(const QTableWidgetItem * item);
impl<'a> /*trait*/ QTableWidget_setItemPrototype<()> for (&'a QTableWidgetItem) {
fn setItemPrototype(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget16setItemPrototypeEPK16QTableWidgetItem()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QTableWidget16setItemPrototypeEPK16QTableWidgetItem(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidget::QTableWidget(int rows, int columns, QWidget * parent);
impl /*struct*/ QTableWidget {
pub fn new<T: QTableWidget_new>(value: T) -> QTableWidget {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QTableWidget_new {
fn new(self) -> QTableWidget;
}
// proto: void QTableWidget::QTableWidget(int rows, int columns, QWidget * parent);
impl<'a> /*trait*/ QTableWidget_new for (i32, i32, Option<&'a QWidget>) {
fn new(self) -> QTableWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidgetC2EiiP7QWidget()};
let ctysz: c_int = unsafe{QTableWidget_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = (if self.2.is_none() {0} else {self.2.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN12QTableWidgetC2EiiP7QWidget(arg0, arg1, arg2)};
let rsthis = QTableWidget{qbase: QTableView::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: int QTableWidget::visualRow(int logicalRow);
impl /*struct*/ QTableWidget {
pub fn visualRow<RetType, T: QTableWidget_visualRow<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.visualRow(self);
// return 1;
}
}
pub trait QTableWidget_visualRow<RetType> {
fn visualRow(self , rsthis: & QTableWidget) -> RetType;
}
// proto: int QTableWidget::visualRow(int logicalRow);
impl<'a> /*trait*/ QTableWidget_visualRow<i32> for (i32) {
fn visualRow(self , rsthis: & QTableWidget) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget9visualRowEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK12QTableWidget9visualRowEi(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTableWidget::setCellWidget(int row, int column, QWidget * widget);
impl /*struct*/ QTableWidget {
pub fn setCellWidget<RetType, T: QTableWidget_setCellWidget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCellWidget(self);
// return 1;
}
}
pub trait QTableWidget_setCellWidget<RetType> {
fn setCellWidget(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setCellWidget(int row, int column, QWidget * widget);
impl<'a> /*trait*/ QTableWidget_setCellWidget<()> for (i32, i32, &'a QWidget) {
fn setCellWidget(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget13setCellWidgetEiiP7QWidget()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {C_ZN12QTableWidget13setCellWidgetEiiP7QWidget(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QTableWidget::openPersistentEditor(QTableWidgetItem * item);
impl /*struct*/ QTableWidget {
pub fn openPersistentEditor<RetType, T: QTableWidget_openPersistentEditor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.openPersistentEditor(self);
// return 1;
}
}
pub trait QTableWidget_openPersistentEditor<RetType> {
fn openPersistentEditor(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::openPersistentEditor(QTableWidgetItem * item);
impl<'a> /*trait*/ QTableWidget_openPersistentEditor<()> for (&'a QTableWidgetItem) {
fn openPersistentEditor(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget20openPersistentEditorEP16QTableWidgetItem()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QTableWidget20openPersistentEditorEP16QTableWidgetItem(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QTableWidget::columnCount();
impl /*struct*/ QTableWidget {
pub fn columnCount<RetType, T: QTableWidget_columnCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.columnCount(self);
// return 1;
}
}
pub trait QTableWidget_columnCount<RetType> {
fn columnCount(self , rsthis: & QTableWidget) -> RetType;
}
// proto: int QTableWidget::columnCount();
impl<'a> /*trait*/ QTableWidget_columnCount<i32> for () {
fn columnCount(self , rsthis: & QTableWidget) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget11columnCountEv()};
let mut ret = unsafe {C_ZNK12QTableWidget11columnCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QTableWidget::currentRow();
impl /*struct*/ QTableWidget {
pub fn currentRow<RetType, T: QTableWidget_currentRow<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.currentRow(self);
// return 1;
}
}
pub trait QTableWidget_currentRow<RetType> {
fn currentRow(self , rsthis: & QTableWidget) -> RetType;
}
// proto: int QTableWidget::currentRow();
impl<'a> /*trait*/ QTableWidget_currentRow<i32> for () {
fn currentRow(self , rsthis: & QTableWidget) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget10currentRowEv()};
let mut ret = unsafe {C_ZNK12QTableWidget10currentRowEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTableWidget::setCurrentItem(QTableWidgetItem * item);
impl /*struct*/ QTableWidget {
pub fn setCurrentItem<RetType, T: QTableWidget_setCurrentItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCurrentItem(self);
// return 1;
}
}
pub trait QTableWidget_setCurrentItem<RetType> {
fn setCurrentItem(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setCurrentItem(QTableWidgetItem * item);
impl<'a> /*trait*/ QTableWidget_setCurrentItem<()> for (&'a QTableWidgetItem) {
fn setCurrentItem(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget14setCurrentItemEP16QTableWidgetItem()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QTableWidget14setCurrentItemEP16QTableWidgetItem(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QWidget * QTableWidget::cellWidget(int row, int column);
impl /*struct*/ QTableWidget {
pub fn cellWidget<RetType, T: QTableWidget_cellWidget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.cellWidget(self);
// return 1;
}
}
pub trait QTableWidget_cellWidget<RetType> {
fn cellWidget(self , rsthis: & QTableWidget) -> RetType;
}
// proto: QWidget * QTableWidget::cellWidget(int row, int column);
impl<'a> /*trait*/ QTableWidget_cellWidget<QWidget> for (i32, i32) {
fn cellWidget(self , rsthis: & QTableWidget) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget10cellWidgetEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let mut ret = unsafe {C_ZNK12QTableWidget10cellWidgetEii(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidget::setSortingEnabled(bool enable);
impl /*struct*/ QTableWidget {
pub fn setSortingEnabled<RetType, T: QTableWidget_setSortingEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setSortingEnabled(self);
// return 1;
}
}
pub trait QTableWidget_setSortingEnabled<RetType> {
fn setSortingEnabled(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setSortingEnabled(bool enable);
impl<'a> /*trait*/ QTableWidget_setSortingEnabled<()> for (i8) {
fn setSortingEnabled(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget17setSortingEnabledEb()};
let arg0 = self as c_char;
unsafe {C_ZN12QTableWidget17setSortingEnabledEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidget::setItem(int row, int column, QTableWidgetItem * item);
impl /*struct*/ QTableWidget {
pub fn setItem<RetType, T: QTableWidget_setItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setItem(self);
// return 1;
}
}
pub trait QTableWidget_setItem<RetType> {
fn setItem(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setItem(int row, int column, QTableWidgetItem * item);
impl<'a> /*trait*/ QTableWidget_setItem<()> for (i32, i32, &'a QTableWidgetItem) {
fn setItem(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget7setItemEiiP16QTableWidgetItem()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {C_ZN12QTableWidget7setItemEiiP16QTableWidgetItem(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: QTableWidgetItem * QTableWidget::horizontalHeaderItem(int column);
impl /*struct*/ QTableWidget {
pub fn horizontalHeaderItem<RetType, T: QTableWidget_horizontalHeaderItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.horizontalHeaderItem(self);
// return 1;
}
}
pub trait QTableWidget_horizontalHeaderItem<RetType> {
fn horizontalHeaderItem(self , rsthis: & QTableWidget) -> RetType;
}
// proto: QTableWidgetItem * QTableWidget::horizontalHeaderItem(int column);
impl<'a> /*trait*/ QTableWidget_horizontalHeaderItem<QTableWidgetItem> for (i32) {
fn horizontalHeaderItem(self , rsthis: & QTableWidget) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget20horizontalHeaderItemEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK12QTableWidget20horizontalHeaderItemEi(rsthis.qclsinst, arg0)};
let mut ret1 = QTableWidgetItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidget::editItem(QTableWidgetItem * item);
impl /*struct*/ QTableWidget {
pub fn editItem<RetType, T: QTableWidget_editItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.editItem(self);
// return 1;
}
}
pub trait QTableWidget_editItem<RetType> {
fn editItem(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::editItem(QTableWidgetItem * item);
impl<'a> /*trait*/ QTableWidget_editItem<()> for (&'a QTableWidgetItem) {
fn editItem(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget8editItemEP16QTableWidgetItem()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QTableWidget8editItemEP16QTableWidgetItem(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QList<QTableWidgetSelectionRange> QTableWidget::selectedRanges();
impl /*struct*/ QTableWidget {
pub fn selectedRanges<RetType, T: QTableWidget_selectedRanges<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.selectedRanges(self);
// return 1;
}
}
pub trait QTableWidget_selectedRanges<RetType> {
fn selectedRanges(self , rsthis: & QTableWidget) -> RetType;
}
// proto: QList<QTableWidgetSelectionRange> QTableWidget::selectedRanges();
impl<'a> /*trait*/ QTableWidget_selectedRanges<u64> for () {
fn selectedRanges(self , rsthis: & QTableWidget) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget14selectedRangesEv()};
let mut ret = unsafe {C_ZNK12QTableWidget14selectedRangesEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: int QTableWidget::currentColumn();
impl /*struct*/ QTableWidget {
pub fn currentColumn<RetType, T: QTableWidget_currentColumn<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.currentColumn(self);
// return 1;
}
}
pub trait QTableWidget_currentColumn<RetType> {
fn currentColumn(self , rsthis: & QTableWidget) -> RetType;
}
// proto: int QTableWidget::currentColumn();
impl<'a> /*trait*/ QTableWidget_currentColumn<i32> for () {
fn currentColumn(self , rsthis: & QTableWidget) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget13currentColumnEv()};
let mut ret = unsafe {C_ZNK12QTableWidget13currentColumnEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTableWidget::removeColumn(int column);
impl /*struct*/ QTableWidget {
pub fn removeColumn<RetType, T: QTableWidget_removeColumn<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.removeColumn(self);
// return 1;
}
}
pub trait QTableWidget_removeColumn<RetType> {
fn removeColumn(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::removeColumn(int column);
impl<'a> /*trait*/ QTableWidget_removeColumn<()> for (i32) {
fn removeColumn(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget12removeColumnEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QTableWidget12removeColumnEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidget::setRangeSelected(const QTableWidgetSelectionRange & range, bool select);
impl /*struct*/ QTableWidget {
pub fn setRangeSelected<RetType, T: QTableWidget_setRangeSelected<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setRangeSelected(self);
// return 1;
}
}
pub trait QTableWidget_setRangeSelected<RetType> {
fn setRangeSelected(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setRangeSelected(const QTableWidgetSelectionRange & range, bool select);
impl<'a> /*trait*/ QTableWidget_setRangeSelected<()> for (&'a QTableWidgetSelectionRange, i8) {
fn setRangeSelected(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget16setRangeSelectedERK26QTableWidgetSelectionRangeb()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_char;
unsafe {C_ZN12QTableWidget16setRangeSelectedERK26QTableWidgetSelectionRangeb(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: int QTableWidget::column(const QTableWidgetItem * item);
impl /*struct*/ QTableWidget {
pub fn column<RetType, T: QTableWidget_column<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.column(self);
// return 1;
}
}
pub trait QTableWidget_column<RetType> {
fn column(self , rsthis: & QTableWidget) -> RetType;
}
// proto: int QTableWidget::column(const QTableWidgetItem * item);
impl<'a> /*trait*/ QTableWidget_column<i32> for (&'a QTableWidgetItem) {
fn column(self , rsthis: & QTableWidget) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget6columnEPK16QTableWidgetItem()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK12QTableWidget6columnEPK16QTableWidgetItem(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: bool QTableWidget::isItemSelected(const QTableWidgetItem * item);
impl /*struct*/ QTableWidget {
pub fn isItemSelected<RetType, T: QTableWidget_isItemSelected<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isItemSelected(self);
// return 1;
}
}
pub trait QTableWidget_isItemSelected<RetType> {
fn isItemSelected(self , rsthis: & QTableWidget) -> RetType;
}
// proto: bool QTableWidget::isItemSelected(const QTableWidgetItem * item);
impl<'a> /*trait*/ QTableWidget_isItemSelected<i8> for (&'a QTableWidgetItem) {
fn isItemSelected(self , rsthis: & QTableWidget) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget14isItemSelectedEPK16QTableWidgetItem()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK12QTableWidget14isItemSelectedEPK16QTableWidgetItem(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: QTableWidgetItem * QTableWidget::takeVerticalHeaderItem(int row);
impl /*struct*/ QTableWidget {
pub fn takeVerticalHeaderItem<RetType, T: QTableWidget_takeVerticalHeaderItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.takeVerticalHeaderItem(self);
// return 1;
}
}
pub trait QTableWidget_takeVerticalHeaderItem<RetType> {
fn takeVerticalHeaderItem(self , rsthis: & QTableWidget) -> RetType;
}
// proto: QTableWidgetItem * QTableWidget::takeVerticalHeaderItem(int row);
impl<'a> /*trait*/ QTableWidget_takeVerticalHeaderItem<QTableWidgetItem> for (i32) {
fn takeVerticalHeaderItem(self , rsthis: & QTableWidget) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget22takeVerticalHeaderItemEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZN12QTableWidget22takeVerticalHeaderItemEi(rsthis.qclsinst, arg0)};
let mut ret1 = QTableWidgetItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidget::insertRow(int row);
impl /*struct*/ QTableWidget {
pub fn insertRow<RetType, T: QTableWidget_insertRow<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.insertRow(self);
// return 1;
}
}
pub trait QTableWidget_insertRow<RetType> {
fn insertRow(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::insertRow(int row);
impl<'a> /*trait*/ QTableWidget_insertRow<()> for (i32) {
fn insertRow(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget9insertRowEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QTableWidget9insertRowEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QTableWidget::rowCount();
impl /*struct*/ QTableWidget {
pub fn rowCount<RetType, T: QTableWidget_rowCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.rowCount(self);
// return 1;
}
}
pub trait QTableWidget_rowCount<RetType> {
fn rowCount(self , rsthis: & QTableWidget) -> RetType;
}
// proto: int QTableWidget::rowCount();
impl<'a> /*trait*/ QTableWidget_rowCount<i32> for () {
fn rowCount(self , rsthis: & QTableWidget) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget8rowCountEv()};
let mut ret = unsafe {C_ZNK12QTableWidget8rowCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: QTableWidgetItem * QTableWidget::item(int row, int column);
impl /*struct*/ QTableWidget {
pub fn item<RetType, T: QTableWidget_item<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.item(self);
// return 1;
}
}
pub trait QTableWidget_item<RetType> {
fn item(self , rsthis: & QTableWidget) -> RetType;
}
// proto: QTableWidgetItem * QTableWidget::item(int row, int column);
impl<'a> /*trait*/ QTableWidget_item<QTableWidgetItem> for (i32, i32) {
fn item(self , rsthis: & QTableWidget) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget4itemEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let mut ret = unsafe {C_ZNK12QTableWidget4itemEii(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QTableWidgetItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidget::QTableWidget(QWidget * parent);
impl<'a> /*trait*/ QTableWidget_new for (Option<&'a QWidget>) {
fn new(self) -> QTableWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidgetC2EP7QWidget()};
let ctysz: c_int = unsafe{QTableWidget_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN12QTableWidgetC2EP7QWidget(arg0)};
let rsthis = QTableWidget{qbase: QTableView::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QTableWidget::setVerticalHeaderLabels(const QStringList & labels);
impl /*struct*/ QTableWidget {
pub fn setVerticalHeaderLabels<RetType, T: QTableWidget_setVerticalHeaderLabels<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setVerticalHeaderLabels(self);
// return 1;
}
}
pub trait QTableWidget_setVerticalHeaderLabels<RetType> {
fn setVerticalHeaderLabels(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setVerticalHeaderLabels(const QStringList & labels);
impl<'a> /*trait*/ QTableWidget_setVerticalHeaderLabels<()> for (&'a QStringList) {
fn setVerticalHeaderLabels(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget23setVerticalHeaderLabelsERK11QStringList()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QTableWidget23setVerticalHeaderLabelsERK11QStringList(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: const QTableWidgetItem * QTableWidget::itemPrototype();
impl /*struct*/ QTableWidget {
pub fn itemPrototype<RetType, T: QTableWidget_itemPrototype<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.itemPrototype(self);
// return 1;
}
}
pub trait QTableWidget_itemPrototype<RetType> {
fn itemPrototype(self , rsthis: & QTableWidget) -> RetType;
}
// proto: const QTableWidgetItem * QTableWidget::itemPrototype();
impl<'a> /*trait*/ QTableWidget_itemPrototype<QTableWidgetItem> for () {
fn itemPrototype(self , rsthis: & QTableWidget) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget13itemPrototypeEv()};
let mut ret = unsafe {C_ZNK12QTableWidget13itemPrototypeEv(rsthis.qclsinst)};
let mut ret1 = QTableWidgetItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QTableWidgetItem * QTableWidget::itemAt(const QPoint & p);
impl /*struct*/ QTableWidget {
pub fn itemAt<RetType, T: QTableWidget_itemAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.itemAt(self);
// return 1;
}
}
pub trait QTableWidget_itemAt<RetType> {
fn itemAt(self , rsthis: & QTableWidget) -> RetType;
}
// proto: QTableWidgetItem * QTableWidget::itemAt(const QPoint & p);
impl<'a> /*trait*/ QTableWidget_itemAt<QTableWidgetItem> for (&'a QPoint) {
fn itemAt(self , rsthis: & QTableWidget) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget6itemAtERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK12QTableWidget6itemAtERK6QPoint(rsthis.qclsinst, arg0)};
let mut ret1 = QTableWidgetItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidget::clearContents();
impl /*struct*/ QTableWidget {
pub fn clearContents<RetType, T: QTableWidget_clearContents<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clearContents(self);
// return 1;
}
}
pub trait QTableWidget_clearContents<RetType> {
fn clearContents(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::clearContents();
impl<'a> /*trait*/ QTableWidget_clearContents<()> for () {
fn clearContents(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget13clearContentsEv()};
unsafe {C_ZN12QTableWidget13clearContentsEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QTableWidgetItem * QTableWidget::itemAt(int x, int y);
impl<'a> /*trait*/ QTableWidget_itemAt<QTableWidgetItem> for (i32, i32) {
fn itemAt(self , rsthis: & QTableWidget) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget6itemAtEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let mut ret = unsafe {C_ZNK12QTableWidget6itemAtEii(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QTableWidgetItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidget::setCurrentCell(int row, int column);
impl /*struct*/ QTableWidget {
pub fn setCurrentCell<RetType, T: QTableWidget_setCurrentCell<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCurrentCell(self);
// return 1;
}
}
pub trait QTableWidget_setCurrentCell<RetType> {
fn setCurrentCell(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setCurrentCell(int row, int column);
impl<'a> /*trait*/ QTableWidget_setCurrentCell<()> for (i32, i32) {
fn setCurrentCell(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget14setCurrentCellEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
unsafe {C_ZN12QTableWidget14setCurrentCellEii(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QTableWidget::setRowCount(int rows);
impl /*struct*/ QTableWidget {
pub fn setRowCount<RetType, T: QTableWidget_setRowCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setRowCount(self);
// return 1;
}
}
pub trait QTableWidget_setRowCount<RetType> {
fn setRowCount(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setRowCount(int rows);
impl<'a> /*trait*/ QTableWidget_setRowCount<()> for (i32) {
fn setRowCount(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget11setRowCountEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QTableWidget11setRowCountEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidget::setHorizontalHeaderItem(int column, QTableWidgetItem * item);
impl /*struct*/ QTableWidget {
pub fn setHorizontalHeaderItem<RetType, T: QTableWidget_setHorizontalHeaderItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setHorizontalHeaderItem(self);
// return 1;
}
}
pub trait QTableWidget_setHorizontalHeaderItem<RetType> {
fn setHorizontalHeaderItem(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::setHorizontalHeaderItem(int column, QTableWidgetItem * item);
impl<'a> /*trait*/ QTableWidget_setHorizontalHeaderItem<()> for (i32, &'a QTableWidgetItem) {
fn setHorizontalHeaderItem(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget23setHorizontalHeaderItemEiP16QTableWidgetItem()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN12QTableWidget23setHorizontalHeaderItemEiP16QTableWidgetItem(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: int QTableWidget::visualColumn(int logicalColumn);
impl /*struct*/ QTableWidget {
pub fn visualColumn<RetType, T: QTableWidget_visualColumn<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.visualColumn(self);
// return 1;
}
}
pub trait QTableWidget_visualColumn<RetType> {
fn visualColumn(self , rsthis: & QTableWidget) -> RetType;
}
// proto: int QTableWidget::visualColumn(int logicalColumn);
impl<'a> /*trait*/ QTableWidget_visualColumn<i32> for (i32) {
fn visualColumn(self , rsthis: & QTableWidget) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget12visualColumnEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK12QTableWidget12visualColumnEi(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: QTableWidgetItem * QTableWidget::takeHorizontalHeaderItem(int column);
impl /*struct*/ QTableWidget {
pub fn takeHorizontalHeaderItem<RetType, T: QTableWidget_takeHorizontalHeaderItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.takeHorizontalHeaderItem(self);
// return 1;
}
}
pub trait QTableWidget_takeHorizontalHeaderItem<RetType> {
fn takeHorizontalHeaderItem(self , rsthis: & QTableWidget) -> RetType;
}
// proto: QTableWidgetItem * QTableWidget::takeHorizontalHeaderItem(int column);
impl<'a> /*trait*/ QTableWidget_takeHorizontalHeaderItem<QTableWidgetItem> for (i32) {
fn takeHorizontalHeaderItem(self , rsthis: & QTableWidget) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget24takeHorizontalHeaderItemEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZN12QTableWidget24takeHorizontalHeaderItemEi(rsthis.qclsinst, arg0)};
let mut ret1 = QTableWidgetItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QTableWidgetItem * QTableWidget::verticalHeaderItem(int row);
impl /*struct*/ QTableWidget {
pub fn verticalHeaderItem<RetType, T: QTableWidget_verticalHeaderItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.verticalHeaderItem(self);
// return 1;
}
}
pub trait QTableWidget_verticalHeaderItem<RetType> {
fn verticalHeaderItem(self , rsthis: & QTableWidget) -> RetType;
}
// proto: QTableWidgetItem * QTableWidget::verticalHeaderItem(int row);
impl<'a> /*trait*/ QTableWidget_verticalHeaderItem<QTableWidgetItem> for (i32) {
fn verticalHeaderItem(self , rsthis: & QTableWidget) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QTableWidget18verticalHeaderItemEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK12QTableWidget18verticalHeaderItemEi(rsthis.qclsinst, arg0)};
let mut ret1 = QTableWidgetItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidget::clear();
impl /*struct*/ QTableWidget {
pub fn clear<RetType, T: QTableWidget_clear<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clear(self);
// return 1;
}
}
pub trait QTableWidget_clear<RetType> {
fn clear(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::clear();
impl<'a> /*trait*/ QTableWidget_clear<()> for () {
fn clear(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget5clearEv()};
unsafe {C_ZN12QTableWidget5clearEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QTableWidget::insertColumn(int column);
impl /*struct*/ QTableWidget {
pub fn insertColumn<RetType, T: QTableWidget_insertColumn<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.insertColumn(self);
// return 1;
}
}
pub trait QTableWidget_insertColumn<RetType> {
fn insertColumn(self , rsthis: & QTableWidget) -> RetType;
}
// proto: void QTableWidget::insertColumn(int column);
impl<'a> /*trait*/ QTableWidget_insertColumn<()> for (i32) {
fn insertColumn(self , rsthis: & QTableWidget) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QTableWidget12insertColumnEi()};
let arg0 = self as c_int;
unsafe {C_ZN12QTableWidget12insertColumnEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
impl /*struct*/ QTableWidgetItem {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QTableWidgetItem {
return QTableWidgetItem{qclsinst: qthis, ..Default::default()};
}
}
// proto: QColor QTableWidgetItem::backgroundColor();
impl /*struct*/ QTableWidgetItem {
pub fn backgroundColor<RetType, T: QTableWidgetItem_backgroundColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.backgroundColor(self);
// return 1;
}
}
pub trait QTableWidgetItem_backgroundColor<RetType> {
fn backgroundColor(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QColor QTableWidgetItem::backgroundColor();
impl<'a> /*trait*/ QTableWidgetItem_backgroundColor<QColor> for () {
fn backgroundColor(self , rsthis: & QTableWidgetItem) -> QColor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem15backgroundColorEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem15backgroundColorEv(rsthis.qclsinst)};
let mut ret1 = QColor::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QVariant QTableWidgetItem::data(int role);
impl /*struct*/ QTableWidgetItem {
pub fn data<RetType, T: QTableWidgetItem_data<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.data(self);
// return 1;
}
}
pub trait QTableWidgetItem_data<RetType> {
fn data(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QVariant QTableWidgetItem::data(int role);
impl<'a> /*trait*/ QTableWidgetItem_data<QVariant> for (i32) {
fn data(self , rsthis: & QTableWidgetItem) -> QVariant {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem4dataEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK16QTableWidgetItem4dataEi(rsthis.qclsinst, arg0)};
let mut ret1 = QVariant::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidgetItem::setSelected(bool select);
impl /*struct*/ QTableWidgetItem {
pub fn setSelected<RetType, T: QTableWidgetItem_setSelected<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setSelected(self);
// return 1;
}
}
pub trait QTableWidgetItem_setSelected<RetType> {
fn setSelected(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setSelected(bool select);
impl<'a> /*trait*/ QTableWidgetItem_setSelected<()> for (i8) {
fn setSelected(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem11setSelectedEb()};
let arg0 = self as c_char;
unsafe {C_ZN16QTableWidgetItem11setSelectedEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidgetItem::setStatusTip(const QString & statusTip);
impl /*struct*/ QTableWidgetItem {
pub fn setStatusTip<RetType, T: QTableWidgetItem_setStatusTip<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setStatusTip(self);
// return 1;
}
}
pub trait QTableWidgetItem_setStatusTip<RetType> {
fn setStatusTip(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setStatusTip(const QString & statusTip);
impl<'a> /*trait*/ QTableWidgetItem_setStatusTip<()> for (&'a QString) {
fn setStatusTip(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem12setStatusTipERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem12setStatusTipERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QColor QTableWidgetItem::textColor();
impl /*struct*/ QTableWidgetItem {
pub fn textColor<RetType, T: QTableWidgetItem_textColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.textColor(self);
// return 1;
}
}
pub trait QTableWidgetItem_textColor<RetType> {
fn textColor(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QColor QTableWidgetItem::textColor();
impl<'a> /*trait*/ QTableWidgetItem_textColor<QColor> for () {
fn textColor(self , rsthis: & QTableWidgetItem) -> QColor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem9textColorEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem9textColorEv(rsthis.qclsinst)};
let mut ret1 = QColor::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidgetItem::~QTableWidgetItem();
impl /*struct*/ QTableWidgetItem {
pub fn free<RetType, T: QTableWidgetItem_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QTableWidgetItem_free<RetType> {
fn free(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::~QTableWidgetItem();
impl<'a> /*trait*/ QTableWidgetItem_free<()> for () {
fn free(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItemD2Ev()};
unsafe {C_ZN16QTableWidgetItemD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QString QTableWidgetItem::text();
impl /*struct*/ QTableWidgetItem {
pub fn text<RetType, T: QTableWidgetItem_text<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.text(self);
// return 1;
}
}
pub trait QTableWidgetItem_text<RetType> {
fn text(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QString QTableWidgetItem::text();
impl<'a> /*trait*/ QTableWidgetItem_text<QString> for () {
fn text(self , rsthis: & QTableWidgetItem) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem4textEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem4textEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidgetItem::setSizeHint(const QSize & size);
impl /*struct*/ QTableWidgetItem {
pub fn setSizeHint<RetType, T: QTableWidgetItem_setSizeHint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setSizeHint(self);
// return 1;
}
}
pub trait QTableWidgetItem_setSizeHint<RetType> {
fn setSizeHint(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setSizeHint(const QSize & size);
impl<'a> /*trait*/ QTableWidgetItem_setSizeHint<()> for (&'a QSize) {
fn setSizeHint(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem11setSizeHintERK5QSize()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem11setSizeHintERK5QSize(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QBrush QTableWidgetItem::foreground();
impl /*struct*/ QTableWidgetItem {
pub fn foreground<RetType, T: QTableWidgetItem_foreground<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.foreground(self);
// return 1;
}
}
pub trait QTableWidgetItem_foreground<RetType> {
fn foreground(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QBrush QTableWidgetItem::foreground();
impl<'a> /*trait*/ QTableWidgetItem_foreground<QBrush> for () {
fn foreground(self , rsthis: & QTableWidgetItem) -> QBrush {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem10foregroundEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem10foregroundEv(rsthis.qclsinst)};
let mut ret1 = QBrush::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QTableWidgetItem::type();
impl /*struct*/ QTableWidgetItem {
pub fn type_<RetType, T: QTableWidgetItem_type_<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.type_(self);
// return 1;
}
}
pub trait QTableWidgetItem_type_<RetType> {
fn type_(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: int QTableWidgetItem::type();
impl<'a> /*trait*/ QTableWidgetItem_type_<i32> for () {
fn type_(self , rsthis: & QTableWidgetItem) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem4typeEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem4typeEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QTableWidgetItem::column();
impl /*struct*/ QTableWidgetItem {
pub fn column<RetType, T: QTableWidgetItem_column<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.column(self);
// return 1;
}
}
pub trait QTableWidgetItem_column<RetType> {
fn column(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: int QTableWidgetItem::column();
impl<'a> /*trait*/ QTableWidgetItem_column<i32> for () {
fn column(self , rsthis: & QTableWidgetItem) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem6columnEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem6columnEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTableWidgetItem::setTextAlignment(int alignment);
impl /*struct*/ QTableWidgetItem {
pub fn setTextAlignment<RetType, T: QTableWidgetItem_setTextAlignment<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTextAlignment(self);
// return 1;
}
}
pub trait QTableWidgetItem_setTextAlignment<RetType> {
fn setTextAlignment(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setTextAlignment(int alignment);
impl<'a> /*trait*/ QTableWidgetItem_setTextAlignment<()> for (i32) {
fn setTextAlignment(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem16setTextAlignmentEi()};
let arg0 = self as c_int;
unsafe {C_ZN16QTableWidgetItem16setTextAlignmentEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QFont QTableWidgetItem::font();
impl /*struct*/ QTableWidgetItem {
pub fn font<RetType, T: QTableWidgetItem_font<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.font(self);
// return 1;
}
}
pub trait QTableWidgetItem_font<RetType> {
fn font(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QFont QTableWidgetItem::font();
impl<'a> /*trait*/ QTableWidgetItem_font<QFont> for () {
fn font(self , rsthis: & QTableWidgetItem) -> QFont {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem4fontEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem4fontEv(rsthis.qclsinst)};
let mut ret1 = QFont::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QIcon QTableWidgetItem::icon();
impl /*struct*/ QTableWidgetItem {
pub fn icon<RetType, T: QTableWidgetItem_icon<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.icon(self);
// return 1;
}
}
pub trait QTableWidgetItem_icon<RetType> {
fn icon(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QIcon QTableWidgetItem::icon();
impl<'a> /*trait*/ QTableWidgetItem_icon<QIcon> for () {
fn icon(self , rsthis: & QTableWidgetItem) -> QIcon {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem4iconEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem4iconEv(rsthis.qclsinst)};
let mut ret1 = QIcon::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidgetItem::write(QDataStream & out);
impl /*struct*/ QTableWidgetItem {
pub fn write<RetType, T: QTableWidgetItem_write<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.write(self);
// return 1;
}
}
pub trait QTableWidgetItem_write<RetType> {
fn write(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::write(QDataStream & out);
impl<'a> /*trait*/ QTableWidgetItem_write<()> for (&'a QDataStream) {
fn write(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem5writeER11QDataStream()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZNK16QTableWidgetItem5writeER11QDataStream(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidgetItem::QTableWidgetItem(const QTableWidgetItem & other);
impl /*struct*/ QTableWidgetItem {
pub fn new<T: QTableWidgetItem_new>(value: T) -> QTableWidgetItem {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QTableWidgetItem_new {
fn new(self) -> QTableWidgetItem;
}
// proto: void QTableWidgetItem::QTableWidgetItem(const QTableWidgetItem & other);
impl<'a> /*trait*/ QTableWidgetItem_new for (&'a QTableWidgetItem) {
fn new(self) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItemC2ERKS_()};
let ctysz: c_int = unsafe{QTableWidgetItem_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN16QTableWidgetItemC2ERKS_(arg0)};
let rsthis = QTableWidgetItem{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QBrush QTableWidgetItem::background();
impl /*struct*/ QTableWidgetItem {
pub fn background<RetType, T: QTableWidgetItem_background<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.background(self);
// return 1;
}
}
pub trait QTableWidgetItem_background<RetType> {
fn background(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QBrush QTableWidgetItem::background();
impl<'a> /*trait*/ QTableWidgetItem_background<QBrush> for () {
fn background(self , rsthis: & QTableWidgetItem) -> QBrush {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem10backgroundEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem10backgroundEv(rsthis.qclsinst)};
let mut ret1 = QBrush::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidgetItem::setIcon(const QIcon & icon);
impl /*struct*/ QTableWidgetItem {
pub fn setIcon<RetType, T: QTableWidgetItem_setIcon<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setIcon(self);
// return 1;
}
}
pub trait QTableWidgetItem_setIcon<RetType> {
fn setIcon(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setIcon(const QIcon & icon);
impl<'a> /*trait*/ QTableWidgetItem_setIcon<()> for (&'a QIcon) {
fn setIcon(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem7setIconERK5QIcon()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem7setIconERK5QIcon(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidgetItem::QTableWidgetItem(const QString & text, int type);
impl<'a> /*trait*/ QTableWidgetItem_new for (&'a QString, Option<i32>) {
fn new(self) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItemC2ERK7QStringi()};
let ctysz: c_int = unsafe{QTableWidgetItem_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {0 as i32} else {self.1.unwrap()}) as c_int;
let qthis: u64 = unsafe {C_ZN16QTableWidgetItemC2ERK7QStringi(arg0, arg1)};
let rsthis = QTableWidgetItem{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QString QTableWidgetItem::statusTip();
impl /*struct*/ QTableWidgetItem {
pub fn statusTip<RetType, T: QTableWidgetItem_statusTip<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.statusTip(self);
// return 1;
}
}
pub trait QTableWidgetItem_statusTip<RetType> {
fn statusTip(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QString QTableWidgetItem::statusTip();
impl<'a> /*trait*/ QTableWidgetItem_statusTip<QString> for () {
fn statusTip(self , rsthis: & QTableWidgetItem) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem9statusTipEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem9statusTipEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QTableWidgetItem * QTableWidgetItem::clone();
impl /*struct*/ QTableWidgetItem {
pub fn clone<RetType, T: QTableWidgetItem_clone<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clone(self);
// return 1;
}
}
pub trait QTableWidgetItem_clone<RetType> {
fn clone(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QTableWidgetItem * QTableWidgetItem::clone();
impl<'a> /*trait*/ QTableWidgetItem_clone<QTableWidgetItem> for () {
fn clone(self , rsthis: & QTableWidgetItem) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem5cloneEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem5cloneEv(rsthis.qclsinst)};
let mut ret1 = QTableWidgetItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidgetItem::QTableWidgetItem(int type);
impl<'a> /*trait*/ QTableWidgetItem_new for (Option<i32>) {
fn new(self) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItemC2Ei()};
let ctysz: c_int = unsafe{QTableWidgetItem_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0 as i32} else {self.unwrap()}) as c_int;
let qthis: u64 = unsafe {C_ZN16QTableWidgetItemC2Ei(arg0)};
let rsthis = QTableWidgetItem{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QTableWidgetItem::setWhatsThis(const QString & whatsThis);
impl /*struct*/ QTableWidgetItem {
pub fn setWhatsThis<RetType, T: QTableWidgetItem_setWhatsThis<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setWhatsThis(self);
// return 1;
}
}
pub trait QTableWidgetItem_setWhatsThis<RetType> {
fn setWhatsThis(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setWhatsThis(const QString & whatsThis);
impl<'a> /*trait*/ QTableWidgetItem_setWhatsThis<()> for (&'a QString) {
fn setWhatsThis(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem12setWhatsThisERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem12setWhatsThisERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QSize QTableWidgetItem::sizeHint();
impl /*struct*/ QTableWidgetItem {
pub fn sizeHint<RetType, T: QTableWidgetItem_sizeHint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sizeHint(self);
// return 1;
}
}
pub trait QTableWidgetItem_sizeHint<RetType> {
fn sizeHint(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QSize QTableWidgetItem::sizeHint();
impl<'a> /*trait*/ QTableWidgetItem_sizeHint<QSize> for () {
fn sizeHint(self , rsthis: & QTableWidgetItem) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem8sizeHintEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem8sizeHintEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidgetItem::setForeground(const QBrush & brush);
impl /*struct*/ QTableWidgetItem {
pub fn setForeground<RetType, T: QTableWidgetItem_setForeground<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setForeground(self);
// return 1;
}
}
pub trait QTableWidgetItem_setForeground<RetType> {
fn setForeground(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setForeground(const QBrush & brush);
impl<'a> /*trait*/ QTableWidgetItem_setForeground<()> for (&'a QBrush) {
fn setForeground(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem13setForegroundERK6QBrush()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem13setForegroundERK6QBrush(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QTableWidgetItem::row();
impl /*struct*/ QTableWidgetItem {
pub fn row<RetType, T: QTableWidgetItem_row<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.row(self);
// return 1;
}
}
pub trait QTableWidgetItem_row<RetType> {
fn row(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: int QTableWidgetItem::row();
impl<'a> /*trait*/ QTableWidgetItem_row<i32> for () {
fn row(self , rsthis: & QTableWidgetItem) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem3rowEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem3rowEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTableWidgetItem::setData(int role, const QVariant & value);
impl /*struct*/ QTableWidgetItem {
pub fn setData<RetType, T: QTableWidgetItem_setData<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setData(self);
// return 1;
}
}
pub trait QTableWidgetItem_setData<RetType> {
fn setData(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setData(int role, const QVariant & value);
impl<'a> /*trait*/ QTableWidgetItem_setData<()> for (i32, &'a QVariant) {
fn setData(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem7setDataEiRK8QVariant()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem7setDataEiRK8QVariant(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QTableWidget * QTableWidgetItem::tableWidget();
impl /*struct*/ QTableWidgetItem {
pub fn tableWidget<RetType, T: QTableWidgetItem_tableWidget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.tableWidget(self);
// return 1;
}
}
pub trait QTableWidgetItem_tableWidget<RetType> {
fn tableWidget(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QTableWidget * QTableWidgetItem::tableWidget();
impl<'a> /*trait*/ QTableWidgetItem_tableWidget<QTableWidget> for () {
fn tableWidget(self , rsthis: & QTableWidgetItem) -> QTableWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem11tableWidgetEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem11tableWidgetEv(rsthis.qclsinst)};
let mut ret1 = QTableWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidgetItem::QTableWidgetItem(const QIcon & icon, const QString & text, int type);
impl<'a> /*trait*/ QTableWidgetItem_new for (&'a QIcon, &'a QString, Option<i32>) {
fn new(self) -> QTableWidgetItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItemC2ERK5QIconRK7QStringi()};
let ctysz: c_int = unsafe{QTableWidgetItem_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = (if self.2.is_none() {0 as i32} else {self.2.unwrap()}) as c_int;
let qthis: u64 = unsafe {C_ZN16QTableWidgetItemC2ERK5QIconRK7QStringi(arg0, arg1, arg2)};
let rsthis = QTableWidgetItem{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: int QTableWidgetItem::textAlignment();
impl /*struct*/ QTableWidgetItem {
pub fn textAlignment<RetType, T: QTableWidgetItem_textAlignment<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.textAlignment(self);
// return 1;
}
}
pub trait QTableWidgetItem_textAlignment<RetType> {
fn textAlignment(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: int QTableWidgetItem::textAlignment();
impl<'a> /*trait*/ QTableWidgetItem_textAlignment<i32> for () {
fn textAlignment(self , rsthis: & QTableWidgetItem) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem13textAlignmentEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem13textAlignmentEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTableWidgetItem::read(QDataStream & in);
impl /*struct*/ QTableWidgetItem {
pub fn read<RetType, T: QTableWidgetItem_read<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.read(self);
// return 1;
}
}
pub trait QTableWidgetItem_read<RetType> {
fn read(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::read(QDataStream & in);
impl<'a> /*trait*/ QTableWidgetItem_read<()> for (&'a QDataStream) {
fn read(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem4readER11QDataStream()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem4readER11QDataStream(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QString QTableWidgetItem::toolTip();
impl /*struct*/ QTableWidgetItem {
pub fn toolTip<RetType, T: QTableWidgetItem_toolTip<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toolTip(self);
// return 1;
}
}
pub trait QTableWidgetItem_toolTip<RetType> {
fn toolTip(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QString QTableWidgetItem::toolTip();
impl<'a> /*trait*/ QTableWidgetItem_toolTip<QString> for () {
fn toolTip(self , rsthis: & QTableWidgetItem) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem7toolTipEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem7toolTipEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QTableWidgetItem::isSelected();
impl /*struct*/ QTableWidgetItem {
pub fn isSelected<RetType, T: QTableWidgetItem_isSelected<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isSelected(self);
// return 1;
}
}
pub trait QTableWidgetItem_isSelected<RetType> {
fn isSelected(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: bool QTableWidgetItem::isSelected();
impl<'a> /*trait*/ QTableWidgetItem_isSelected<i8> for () {
fn isSelected(self , rsthis: & QTableWidgetItem) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem10isSelectedEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem10isSelectedEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QTableWidgetItem::setBackgroundColor(const QColor & color);
impl /*struct*/ QTableWidgetItem {
pub fn setBackgroundColor<RetType, T: QTableWidgetItem_setBackgroundColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBackgroundColor(self);
// return 1;
}
}
pub trait QTableWidgetItem_setBackgroundColor<RetType> {
fn setBackgroundColor(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setBackgroundColor(const QColor & color);
impl<'a> /*trait*/ QTableWidgetItem_setBackgroundColor<()> for (&'a QColor) {
fn setBackgroundColor(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem18setBackgroundColorERK6QColor()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem18setBackgroundColorERK6QColor(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidgetItem::setBackground(const QBrush & brush);
impl /*struct*/ QTableWidgetItem {
pub fn setBackground<RetType, T: QTableWidgetItem_setBackground<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBackground(self);
// return 1;
}
}
pub trait QTableWidgetItem_setBackground<RetType> {
fn setBackground(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setBackground(const QBrush & brush);
impl<'a> /*trait*/ QTableWidgetItem_setBackground<()> for (&'a QBrush) {
fn setBackground(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem13setBackgroundERK6QBrush()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem13setBackgroundERK6QBrush(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidgetItem::setFont(const QFont & font);
impl /*struct*/ QTableWidgetItem {
pub fn setFont<RetType, T: QTableWidgetItem_setFont<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setFont(self);
// return 1;
}
}
pub trait QTableWidgetItem_setFont<RetType> {
fn setFont(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setFont(const QFont & font);
impl<'a> /*trait*/ QTableWidgetItem_setFont<()> for (&'a QFont) {
fn setFont(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem7setFontERK5QFont()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem7setFontERK5QFont(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidgetItem::setTextColor(const QColor & color);
impl /*struct*/ QTableWidgetItem {
pub fn setTextColor<RetType, T: QTableWidgetItem_setTextColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTextColor(self);
// return 1;
}
}
pub trait QTableWidgetItem_setTextColor<RetType> {
fn setTextColor(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setTextColor(const QColor & color);
impl<'a> /*trait*/ QTableWidgetItem_setTextColor<()> for (&'a QColor) {
fn setTextColor(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem12setTextColorERK6QColor()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem12setTextColorERK6QColor(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTableWidgetItem::setText(const QString & text);
impl /*struct*/ QTableWidgetItem {
pub fn setText<RetType, T: QTableWidgetItem_setText<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setText(self);
// return 1;
}
}
pub trait QTableWidgetItem_setText<RetType> {
fn setText(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setText(const QString & text);
impl<'a> /*trait*/ QTableWidgetItem_setText<()> for (&'a QString) {
fn setText(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem7setTextERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem7setTextERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QString QTableWidgetItem::whatsThis();
impl /*struct*/ QTableWidgetItem {
pub fn whatsThis<RetType, T: QTableWidgetItem_whatsThis<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.whatsThis(self);
// return 1;
}
}
pub trait QTableWidgetItem_whatsThis<RetType> {
fn whatsThis(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: QString QTableWidgetItem::whatsThis();
impl<'a> /*trait*/ QTableWidgetItem_whatsThis<QString> for () {
fn whatsThis(self , rsthis: & QTableWidgetItem) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QTableWidgetItem9whatsThisEv()};
let mut ret = unsafe {C_ZNK16QTableWidgetItem9whatsThisEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTableWidgetItem::setToolTip(const QString & toolTip);
impl /*struct*/ QTableWidgetItem {
pub fn setToolTip<RetType, T: QTableWidgetItem_setToolTip<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setToolTip(self);
// return 1;
}
}
pub trait QTableWidgetItem_setToolTip<RetType> {
fn setToolTip(self , rsthis: & QTableWidgetItem) -> RetType;
}
// proto: void QTableWidgetItem::setToolTip(const QString & toolTip);
impl<'a> /*trait*/ QTableWidgetItem_setToolTip<()> for (&'a QString) {
fn setToolTip(self , rsthis: & QTableWidgetItem) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QTableWidgetItem10setToolTipERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN16QTableWidgetItem10setToolTipERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
#[derive(Default)] // for QTableWidget_itemDoubleClicked
pub struct QTableWidget_itemDoubleClicked_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn itemDoubleClicked(&self) -> QTableWidget_itemDoubleClicked_signal {
return QTableWidget_itemDoubleClicked_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_itemDoubleClicked_signal {
pub fn connect<T: QTableWidget_itemDoubleClicked_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_itemDoubleClicked_signal_connect {
fn connect(self, sigthis: QTableWidget_itemDoubleClicked_signal);
}
#[derive(Default)] // for QTableWidget_cellEntered
pub struct QTableWidget_cellEntered_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn cellEntered(&self) -> QTableWidget_cellEntered_signal {
return QTableWidget_cellEntered_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_cellEntered_signal {
pub fn connect<T: QTableWidget_cellEntered_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_cellEntered_signal_connect {
fn connect(self, sigthis: QTableWidget_cellEntered_signal);
}
#[derive(Default)] // for QTableWidget_itemClicked
pub struct QTableWidget_itemClicked_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn itemClicked(&self) -> QTableWidget_itemClicked_signal {
return QTableWidget_itemClicked_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_itemClicked_signal {
pub fn connect<T: QTableWidget_itemClicked_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_itemClicked_signal_connect {
fn connect(self, sigthis: QTableWidget_itemClicked_signal);
}
#[derive(Default)] // for QTableWidget_currentItemChanged
pub struct QTableWidget_currentItemChanged_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn currentItemChanged(&self) -> QTableWidget_currentItemChanged_signal {
return QTableWidget_currentItemChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_currentItemChanged_signal {
pub fn connect<T: QTableWidget_currentItemChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_currentItemChanged_signal_connect {
fn connect(self, sigthis: QTableWidget_currentItemChanged_signal);
}
#[derive(Default)] // for QTableWidget_itemEntered
pub struct QTableWidget_itemEntered_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn itemEntered(&self) -> QTableWidget_itemEntered_signal {
return QTableWidget_itemEntered_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_itemEntered_signal {
pub fn connect<T: QTableWidget_itemEntered_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_itemEntered_signal_connect {
fn connect(self, sigthis: QTableWidget_itemEntered_signal);
}
#[derive(Default)] // for QTableWidget_itemPressed
pub struct QTableWidget_itemPressed_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn itemPressed(&self) -> QTableWidget_itemPressed_signal {
return QTableWidget_itemPressed_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_itemPressed_signal {
pub fn connect<T: QTableWidget_itemPressed_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_itemPressed_signal_connect {
fn connect(self, sigthis: QTableWidget_itemPressed_signal);
}
#[derive(Default)] // for QTableWidget_cellClicked
pub struct QTableWidget_cellClicked_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn cellClicked(&self) -> QTableWidget_cellClicked_signal {
return QTableWidget_cellClicked_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_cellClicked_signal {
pub fn connect<T: QTableWidget_cellClicked_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_cellClicked_signal_connect {
fn connect(self, sigthis: QTableWidget_cellClicked_signal);
}
#[derive(Default)] // for QTableWidget_itemSelectionChanged
pub struct QTableWidget_itemSelectionChanged_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn itemSelectionChanged(&self) -> QTableWidget_itemSelectionChanged_signal {
return QTableWidget_itemSelectionChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_itemSelectionChanged_signal {
pub fn connect<T: QTableWidget_itemSelectionChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_itemSelectionChanged_signal_connect {
fn connect(self, sigthis: QTableWidget_itemSelectionChanged_signal);
}
#[derive(Default)] // for QTableWidget_cellChanged
pub struct QTableWidget_cellChanged_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn cellChanged(&self) -> QTableWidget_cellChanged_signal {
return QTableWidget_cellChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_cellChanged_signal {
pub fn connect<T: QTableWidget_cellChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_cellChanged_signal_connect {
fn connect(self, sigthis: QTableWidget_cellChanged_signal);
}
#[derive(Default)] // for QTableWidget_itemActivated
pub struct QTableWidget_itemActivated_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn itemActivated(&self) -> QTableWidget_itemActivated_signal {
return QTableWidget_itemActivated_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_itemActivated_signal {
pub fn connect<T: QTableWidget_itemActivated_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_itemActivated_signal_connect {
fn connect(self, sigthis: QTableWidget_itemActivated_signal);
}
#[derive(Default)] // for QTableWidget_cellActivated
pub struct QTableWidget_cellActivated_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn cellActivated(&self) -> QTableWidget_cellActivated_signal {
return QTableWidget_cellActivated_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_cellActivated_signal {
pub fn connect<T: QTableWidget_cellActivated_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_cellActivated_signal_connect {
fn connect(self, sigthis: QTableWidget_cellActivated_signal);
}
#[derive(Default)] // for QTableWidget_itemChanged
pub struct QTableWidget_itemChanged_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn itemChanged(&self) -> QTableWidget_itemChanged_signal {
return QTableWidget_itemChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_itemChanged_signal {
pub fn connect<T: QTableWidget_itemChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_itemChanged_signal_connect {
fn connect(self, sigthis: QTableWidget_itemChanged_signal);
}
#[derive(Default)] // for QTableWidget_currentCellChanged
pub struct QTableWidget_currentCellChanged_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn currentCellChanged(&self) -> QTableWidget_currentCellChanged_signal {
return QTableWidget_currentCellChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_currentCellChanged_signal {
pub fn connect<T: QTableWidget_currentCellChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_currentCellChanged_signal_connect {
fn connect(self, sigthis: QTableWidget_currentCellChanged_signal);
}
#[derive(Default)] // for QTableWidget_cellDoubleClicked
pub struct QTableWidget_cellDoubleClicked_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn cellDoubleClicked(&self) -> QTableWidget_cellDoubleClicked_signal {
return QTableWidget_cellDoubleClicked_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_cellDoubleClicked_signal {
pub fn connect<T: QTableWidget_cellDoubleClicked_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_cellDoubleClicked_signal_connect {
fn connect(self, sigthis: QTableWidget_cellDoubleClicked_signal);
}
#[derive(Default)] // for QTableWidget_cellPressed
pub struct QTableWidget_cellPressed_signal{poi:u64}
impl /* struct */ QTableWidget {
pub fn cellPressed(&self) -> QTableWidget_cellPressed_signal {
return QTableWidget_cellPressed_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTableWidget_cellPressed_signal {
pub fn connect<T: QTableWidget_cellPressed_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTableWidget_cellPressed_signal_connect {
fn connect(self, sigthis: QTableWidget_cellPressed_signal);
}
// itemActivated(class QTableWidgetItem *)
extern fn QTableWidget_itemActivated_signal_connect_cb_0(rsfptr:fn(QTableWidgetItem), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QTableWidget_itemActivated_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QTableWidgetItem)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QTableWidget_itemActivated_signal_connect for fn(QTableWidgetItem) {
fn connect(self, sigthis: QTableWidget_itemActivated_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemActivated_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget13itemActivatedEP16QTableWidgetItem(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_itemActivated_signal_connect for Box<Fn(QTableWidgetItem)> {
fn connect(self, sigthis: QTableWidget_itemActivated_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemActivated_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget13itemActivatedEP16QTableWidgetItem(arg0, arg1, arg2)};
}
}
// itemSelectionChanged()
extern fn QTableWidget_itemSelectionChanged_signal_connect_cb_1(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QTableWidget_itemSelectionChanged_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QTableWidget_itemSelectionChanged_signal_connect for fn() {
fn connect(self, sigthis: QTableWidget_itemSelectionChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemSelectionChanged_signal_connect_cb_1 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget20itemSelectionChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_itemSelectionChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QTableWidget_itemSelectionChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemSelectionChanged_signal_connect_cb_box_1 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget20itemSelectionChangedEv(arg0, arg1, arg2)};
}
}
// itemChanged(class QTableWidgetItem *)
extern fn QTableWidget_itemChanged_signal_connect_cb_2(rsfptr:fn(QTableWidgetItem), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QTableWidget_itemChanged_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn(QTableWidgetItem)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QTableWidget_itemChanged_signal_connect for fn(QTableWidgetItem) {
fn connect(self, sigthis: QTableWidget_itemChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemChanged_signal_connect_cb_2 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11itemChangedEP16QTableWidgetItem(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_itemChanged_signal_connect for Box<Fn(QTableWidgetItem)> {
fn connect(self, sigthis: QTableWidget_itemChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemChanged_signal_connect_cb_box_2 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11itemChangedEP16QTableWidgetItem(arg0, arg1, arg2)};
}
}
// itemPressed(class QTableWidgetItem *)
extern fn QTableWidget_itemPressed_signal_connect_cb_3(rsfptr:fn(QTableWidgetItem), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QTableWidget_itemPressed_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn(QTableWidgetItem)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QTableWidget_itemPressed_signal_connect for fn(QTableWidgetItem) {
fn connect(self, sigthis: QTableWidget_itemPressed_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemPressed_signal_connect_cb_3 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11itemPressedEP16QTableWidgetItem(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_itemPressed_signal_connect for Box<Fn(QTableWidgetItem)> {
fn connect(self, sigthis: QTableWidget_itemPressed_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemPressed_signal_connect_cb_box_3 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11itemPressedEP16QTableWidgetItem(arg0, arg1, arg2)};
}
}
// currentItemChanged(class QTableWidgetItem *, class QTableWidgetItem *)
extern fn QTableWidget_currentItemChanged_signal_connect_cb_4(rsfptr:fn(QTableWidgetItem, QTableWidgetItem), arg0: *mut c_void, arg1: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
let rsarg1 = QTableWidgetItem::inheritFrom(arg1 as u64);
rsfptr(rsarg0,rsarg1);
}
extern fn QTableWidget_currentItemChanged_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn(QTableWidgetItem, QTableWidgetItem)>, arg0: *mut c_void, arg1: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
let rsarg1 = QTableWidgetItem::inheritFrom(arg1 as u64);
// rsfptr(rsarg0,rsarg1);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1)};
}
impl /* trait */ QTableWidget_currentItemChanged_signal_connect for fn(QTableWidgetItem, QTableWidgetItem) {
fn connect(self, sigthis: QTableWidget_currentItemChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_currentItemChanged_signal_connect_cb_4 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget18currentItemChangedEP16QTableWidgetItemS1_(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_currentItemChanged_signal_connect for Box<Fn(QTableWidgetItem, QTableWidgetItem)> {
fn connect(self, sigthis: QTableWidget_currentItemChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_currentItemChanged_signal_connect_cb_box_4 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget18currentItemChangedEP16QTableWidgetItemS1_(arg0, arg1, arg2)};
}
}
// currentCellChanged(int, int, int, int)
extern fn QTableWidget_currentCellChanged_signal_connect_cb_5(rsfptr:fn(i32, i32, i32, i32), arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
let rsarg2 = arg2 as i32;
let rsarg3 = arg3 as i32;
rsfptr(rsarg0,rsarg1,rsarg2,rsarg3);
}
extern fn QTableWidget_currentCellChanged_signal_connect_cb_box_5(rsfptr_raw:*mut Box<Fn(i32, i32, i32, i32)>, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
let rsarg2 = arg2 as i32;
let rsarg3 = arg3 as i32;
// rsfptr(rsarg0,rsarg1,rsarg2,rsarg3);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1,rsarg2,rsarg3)};
}
impl /* trait */ QTableWidget_currentCellChanged_signal_connect for fn(i32, i32, i32, i32) {
fn connect(self, sigthis: QTableWidget_currentCellChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_currentCellChanged_signal_connect_cb_5 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget18currentCellChangedEiiii(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_currentCellChanged_signal_connect for Box<Fn(i32, i32, i32, i32)> {
fn connect(self, sigthis: QTableWidget_currentCellChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_currentCellChanged_signal_connect_cb_box_5 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget18currentCellChangedEiiii(arg0, arg1, arg2)};
}
}
// itemEntered(class QTableWidgetItem *)
extern fn QTableWidget_itemEntered_signal_connect_cb_6(rsfptr:fn(QTableWidgetItem), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QTableWidget_itemEntered_signal_connect_cb_box_6(rsfptr_raw:*mut Box<Fn(QTableWidgetItem)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QTableWidget_itemEntered_signal_connect for fn(QTableWidgetItem) {
fn connect(self, sigthis: QTableWidget_itemEntered_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemEntered_signal_connect_cb_6 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11itemEnteredEP16QTableWidgetItem(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_itemEntered_signal_connect for Box<Fn(QTableWidgetItem)> {
fn connect(self, sigthis: QTableWidget_itemEntered_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemEntered_signal_connect_cb_box_6 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11itemEnteredEP16QTableWidgetItem(arg0, arg1, arg2)};
}
}
// cellEntered(int, int)
extern fn QTableWidget_cellEntered_signal_connect_cb_7(rsfptr:fn(i32, i32), arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
rsfptr(rsarg0,rsarg1);
}
extern fn QTableWidget_cellEntered_signal_connect_cb_box_7(rsfptr_raw:*mut Box<Fn(i32, i32)>, arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
// rsfptr(rsarg0,rsarg1);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1)};
}
impl /* trait */ QTableWidget_cellEntered_signal_connect for fn(i32, i32) {
fn connect(self, sigthis: QTableWidget_cellEntered_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_cellEntered_signal_connect_cb_7 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11cellEnteredEii(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_cellEntered_signal_connect for Box<Fn(i32, i32)> {
fn connect(self, sigthis: QTableWidget_cellEntered_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_cellEntered_signal_connect_cb_box_7 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11cellEnteredEii(arg0, arg1, arg2)};
}
}
// cellActivated(int, int)
extern fn QTableWidget_cellActivated_signal_connect_cb_8(rsfptr:fn(i32, i32), arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
rsfptr(rsarg0,rsarg1);
}
extern fn QTableWidget_cellActivated_signal_connect_cb_box_8(rsfptr_raw:*mut Box<Fn(i32, i32)>, arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
// rsfptr(rsarg0,rsarg1);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1)};
}
impl /* trait */ QTableWidget_cellActivated_signal_connect for fn(i32, i32) {
fn connect(self, sigthis: QTableWidget_cellActivated_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_cellActivated_signal_connect_cb_8 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget13cellActivatedEii(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_cellActivated_signal_connect for Box<Fn(i32, i32)> {
fn connect(self, sigthis: QTableWidget_cellActivated_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_cellActivated_signal_connect_cb_box_8 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget13cellActivatedEii(arg0, arg1, arg2)};
}
}
// itemClicked(class QTableWidgetItem *)
extern fn QTableWidget_itemClicked_signal_connect_cb_9(rsfptr:fn(QTableWidgetItem), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QTableWidget_itemClicked_signal_connect_cb_box_9(rsfptr_raw:*mut Box<Fn(QTableWidgetItem)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QTableWidget_itemClicked_signal_connect for fn(QTableWidgetItem) {
fn connect(self, sigthis: QTableWidget_itemClicked_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemClicked_signal_connect_cb_9 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11itemClickedEP16QTableWidgetItem(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_itemClicked_signal_connect for Box<Fn(QTableWidgetItem)> {
fn connect(self, sigthis: QTableWidget_itemClicked_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemClicked_signal_connect_cb_box_9 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11itemClickedEP16QTableWidgetItem(arg0, arg1, arg2)};
}
}
// cellClicked(int, int)
extern fn QTableWidget_cellClicked_signal_connect_cb_10(rsfptr:fn(i32, i32), arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
rsfptr(rsarg0,rsarg1);
}
extern fn QTableWidget_cellClicked_signal_connect_cb_box_10(rsfptr_raw:*mut Box<Fn(i32, i32)>, arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
// rsfptr(rsarg0,rsarg1);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1)};
}
impl /* trait */ QTableWidget_cellClicked_signal_connect for fn(i32, i32) {
fn connect(self, sigthis: QTableWidget_cellClicked_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_cellClicked_signal_connect_cb_10 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11cellClickedEii(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_cellClicked_signal_connect for Box<Fn(i32, i32)> {
fn connect(self, sigthis: QTableWidget_cellClicked_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_cellClicked_signal_connect_cb_box_10 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11cellClickedEii(arg0, arg1, arg2)};
}
}
// itemDoubleClicked(class QTableWidgetItem *)
extern fn QTableWidget_itemDoubleClicked_signal_connect_cb_11(rsfptr:fn(QTableWidgetItem), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QTableWidget_itemDoubleClicked_signal_connect_cb_box_11(rsfptr_raw:*mut Box<Fn(QTableWidgetItem)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QTableWidgetItem::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QTableWidget_itemDoubleClicked_signal_connect for fn(QTableWidgetItem) {
fn connect(self, sigthis: QTableWidget_itemDoubleClicked_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemDoubleClicked_signal_connect_cb_11 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget17itemDoubleClickedEP16QTableWidgetItem(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_itemDoubleClicked_signal_connect for Box<Fn(QTableWidgetItem)> {
fn connect(self, sigthis: QTableWidget_itemDoubleClicked_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_itemDoubleClicked_signal_connect_cb_box_11 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget17itemDoubleClickedEP16QTableWidgetItem(arg0, arg1, arg2)};
}
}
// cellDoubleClicked(int, int)
extern fn QTableWidget_cellDoubleClicked_signal_connect_cb_12(rsfptr:fn(i32, i32), arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
rsfptr(rsarg0,rsarg1);
}
extern fn QTableWidget_cellDoubleClicked_signal_connect_cb_box_12(rsfptr_raw:*mut Box<Fn(i32, i32)>, arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
// rsfptr(rsarg0,rsarg1);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1)};
}
impl /* trait */ QTableWidget_cellDoubleClicked_signal_connect for fn(i32, i32) {
fn connect(self, sigthis: QTableWidget_cellDoubleClicked_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_cellDoubleClicked_signal_connect_cb_12 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget17cellDoubleClickedEii(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_cellDoubleClicked_signal_connect for Box<Fn(i32, i32)> {
fn connect(self, sigthis: QTableWidget_cellDoubleClicked_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_cellDoubleClicked_signal_connect_cb_box_12 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget17cellDoubleClickedEii(arg0, arg1, arg2)};
}
}
// cellChanged(int, int)
extern fn QTableWidget_cellChanged_signal_connect_cb_13(rsfptr:fn(i32, i32), arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
rsfptr(rsarg0,rsarg1);
}
extern fn QTableWidget_cellChanged_signal_connect_cb_box_13(rsfptr_raw:*mut Box<Fn(i32, i32)>, arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
// rsfptr(rsarg0,rsarg1);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1)};
}
impl /* trait */ QTableWidget_cellChanged_signal_connect for fn(i32, i32) {
fn connect(self, sigthis: QTableWidget_cellChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_cellChanged_signal_connect_cb_13 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11cellChangedEii(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_cellChanged_signal_connect for Box<Fn(i32, i32)> {
fn connect(self, sigthis: QTableWidget_cellChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_cellChanged_signal_connect_cb_box_13 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11cellChangedEii(arg0, arg1, arg2)};
}
}
// cellPressed(int, int)
extern fn QTableWidget_cellPressed_signal_connect_cb_14(rsfptr:fn(i32, i32), arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
rsfptr(rsarg0,rsarg1);
}
extern fn QTableWidget_cellPressed_signal_connect_cb_box_14(rsfptr_raw:*mut Box<Fn(i32, i32)>, arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
// rsfptr(rsarg0,rsarg1);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1)};
}
impl /* trait */ QTableWidget_cellPressed_signal_connect for fn(i32, i32) {
fn connect(self, sigthis: QTableWidget_cellPressed_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_cellPressed_signal_connect_cb_14 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11cellPressedEii(arg0, arg1, arg2)};
}
}
impl /* trait */ QTableWidget_cellPressed_signal_connect for Box<Fn(i32, i32)> {
fn connect(self, sigthis: QTableWidget_cellPressed_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTableWidget_cellPressed_signal_connect_cb_box_14 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTableWidget_SlotProxy_connect__ZN12QTableWidget11cellPressedEii(arg0, arg1, arg2)};
}
}
// <= body block end
|
use std::collections::VecDeque;
use input_i_scanner::InputIScanner;
use join::Join;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
let (h, w) = scan!((usize, usize));
let n = scan!(usize);
let a = scan!(u32; n);
let mut que = VecDeque::new();
for i in 0..n {
for _ in 0..a[i] {
que.push_back(i + 1);
}
}
let mut y = 0;
let mut x = 0;
let mut right = true;
let mut ans = vec![vec![0; w]; h];
while let Some(color) = que.pop_front() {
ans[y][x] = color;
if right {
if x + 1 < w {
x += 1;
} else {
y += 1;
right = false;
}
} else {
if x >= 1 {
x -= 1;
} else {
y += 1;
right = true;
}
}
}
for row in ans {
println!("{}", row.iter().join(" "));
}
}
|
use super::chal39::{RsaKeyPair, RsaPubKey};
use num::{BigUint, One, Zero};
/// input an RSA public key, the ciphertext, and the oracle
/// outpus the decryption
pub fn rsa_parity_oracle_attack(pk: &RsaPubKey, ct: &BigUint, oracle: &Oracle) -> BigUint {
// inclusive upper and lower bounds
let mut upper = &pk.n - BigUint::one();
let mut lower = BigUint::zero();
let two = BigUint::parse_bytes(b"2", 10).unwrap();
let mut multiplier = two.clone();
while upper > lower {
let mid = (&upper + &lower) / &two;
let rem = (&upper + &lower) % &two;
if oracle.parity_query(&(ct * pk.encrypt(&multiplier))) {
upper = mid;
} else if rem == BigUint::zero() {
lower = mid;
} else {
lower = mid + BigUint::one();
}
multiplier *= two.clone();
}
assert_eq!(upper, lower);
lower
}
// using a struct because parity oracle requires private keys which should be private field, yet
// oracle is a public function
/// An RSA parity oracle
pub struct Oracle {
key_pair: RsaKeyPair,
}
impl Oracle {
/// initialize the oracle with an RSA keypair (priKey specifically)
pub fn new(key_pair: &RsaKeyPair) -> Oracle {
Oracle {
key_pair: key_pair.clone(),
}
}
/// public facing parity query API
pub fn parity_query(&self, ct: &BigUint) -> bool {
self.key_pair.priKey.parity(&ct)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parity_oracle_attack() {
let key_pair = RsaKeyPair::new_1024_rsa();
let oracle = Oracle::new(&key_pair);
let msg = BigUint::parse_bytes(b"314159", 10).unwrap();
let ct = key_pair.pubKey.encrypt(&msg);
assert_eq!(rsa_parity_oracle_attack(&key_pair.pubKey, &ct, &oracle), msg);
}
}
|
use super::player::*;
use super::io::*;
use super::board::*;
#[test]
fn human_player_get_move_returns_zero_based_move_when_valid() {
// Typing in 1 to choose the first space
// is more natural than typing 0
let io = TestIo::new("3".to_string());
let human_player = HumanPlayer::new(io, 1);
let board = Board::new();
assert_eq!(human_player.get_move(board), 2);
}
#[test]
fn cpu_player_chooses_last_valid_move() {
let cpu_player = CpuPlayer::new(1);
let mut board = Board::new();
board.set_spaces(vec![0, 1, 5, 8], 1);
board.set_spaces(vec![2, 3, 4, 7], 2);
assert_eq!(cpu_player.get_move(board), 6);
}
#[test]
fn cpu_player_wins_immediately_if_possible() {
let cpu_player = CpuPlayer::new(2);
let mut board = Board::new();
board.set_spaces(vec![1, 3, 5], 1);
board.set_spaces(vec![0, 4], 2);
// 2 | 1 | 0
// ---+---+---
// 1 | 2 | 1
// ---+---+---
// 0 | 0 | 0
assert_eq!(cpu_player.get_move(board), 8);
}
|
use yew::prelude::*;
use yew_router::{route::Route, switch::Permissive};
mod pages;
use pages::{
about::About, home::Home, page_not_found::PageNotFound, job_page::JobPage,
};
mod switch;
use switch::{AppAnchor, AppRoute, AppRouter, PublicUrlSwitch};
mod models;
pub enum Msg {
ToggleNavbar,
}
pub struct Model {
link: ComponentLink<Self>,
navbar_active: bool,
}
const SUPPORTED_JOBS: &'static [&'static str] = &["pld"];
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
navbar_active: false,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::ToggleNavbar => {
self.navbar_active = !self.navbar_active;
true
}
}
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
html! {
<>
{ self.view_nav() }
<main>
<AppRouter
render=AppRouter::render(Self::switch)
redirect=AppRouter::redirect(|route: Route| {
AppRoute::PageNotFound(Permissive(Some(route.route))).into_public()
})
/>
</main>
<footer class="footer">
<div class="content has-text-centered">
{ "Powered by " }
<a href="https://yew.rs">{ "Yew" }</a>
</div>
</footer>
</>
}
}
}
impl Model {
fn view_nav(&self) -> Html {
let Self {
ref link,
navbar_active,
..
} = *self;
let active_class = if navbar_active { "is-active" } else { "" };
html! {
<nav class="navbar is-primary" role="navigation" aria-label="main navigation">
<div class="navbar-brand">
<a role="button"
class=classes!("navbar-burger", "burger", active_class)
aria-label="menu" aria-expanded="false"
onclick=link.callback(|_| Msg::ToggleNavbar)
>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</a>
</div>
<div class=classes!("navbar-menu", active_class)>
<div class="navbar-start">
<AppAnchor classes="navbar-item" route=AppRoute::Home>
{ "Home" }
</AppAnchor>
<AppAnchor classes="navbar-item" route=AppRoute::About>
{ "About" }
</AppAnchor>
</div>
</div>
</nav>
}
}
fn switch(switch: PublicUrlSwitch) -> Html {
match switch.route() {
AppRoute::About => {
html! { <About /> }
}
AppRoute::Home => {
html! { <Home /> }
}
AppRoute::JobPage(job_name) => {
// TODO: This cannot possibly be idiomatic Rust.
if SUPPORTED_JOBS.iter().any(|x| x.to_string() == job_name) {
return html! { <JobPage job_name = job_name /> };
}
// This should be a redirect, not just a not-found render.
html! { <PageNotFound route=job_name /> }
}
AppRoute::PageNotFound(Permissive(route)) => {
html! { <PageNotFound route=route /> }
}
}
}
}
fn main() {
yew::start_app::<Model>();
} |
use std::fs::File;
use std::io::prelude::*;
use curl::easy::Easy;
use hurl::http::libcurl;
use hurl::http::libcurl::client::ClientOptions;
use hurl::http::libcurl::core::*;
use server::Server;
macro_rules! t {
($e:expr) => {
match $e {
Ok(e) => e,
Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
}
};
}
pub mod server;
pub fn new_header(name: &str, value: &str) -> Header {
Header {
name: name.to_string(),
value: value.to_string(),
}
}
#[test]
fn get_easy() {
let s = Server::new();
s.receive(
"\
GET /hello HTTP/1.1\r\n\
Host: 127.0.0.1:$PORT\r\n\
Accept: */*\r\n\
\r\n",
);
s.send("HTTP/1.1 200 OK\r\n\r\nHello World!");
let mut data = Vec::new();
let mut handle = Easy::new();
handle.url(&s.url("/hello")).unwrap();
{
let mut transfer = handle.transfer();
transfer.write_function(|new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
}).unwrap();
transfer.perform().unwrap();
}
assert_eq!(data, b"Hello World!");
}
fn default_client() -> libcurl::client::Client {
let options = ClientOptions {
follow_location: false,
max_redirect: None,
cookie_file: None,
cookie_jar: None,
proxy: None,
verbose: false,
};
libcurl::client::Client::init(options)
}
fn default_get_request(url: String) -> Request {
Request {
method: Method::Get,
url,
headers: vec![],
querystring: vec![],
form: vec![],
multipart: vec![],
cookies: vec![],
body: vec![]
}
}
// region basic
#[test]
fn test_hello() {
let mut client = default_client();
let request = default_get_request("http://localhost:8000/hello".to_string());
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.version, Version::Http10);
assert_eq!(response.status, 200);
assert_eq!(response.body, b"Hello World!".to_vec());
assert_eq!(response.headers.len(), 4);
assert!(response.headers.contains(&Header { name: "Content-Length".to_string(), value: "12".to_string() }));
assert!(response.headers.contains(&Header { name: "Content-Type".to_string(), value: "text/html; charset=utf-8".to_string() }));
assert_eq!(response.get_header_values("Date".to_string()).len(), 1);
}
// endregion
// region http method
#[test]
fn test_put() {
let mut client = default_client();
let request = Request {
method: Method::Put,
url: "http://localhost:8000/put".to_string(),
headers: vec![],
querystring: vec![],
form: vec![],
multipart: vec![],
cookies: vec![],
body: vec![]
};
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert!(response.body.is_empty());
}
#[test]
fn test_patch() {
let mut client = default_client();
let request = Request {
method: Method::Patch,
url: "http://localhost:8000/patch/file.txt".to_string(),
headers: vec![
Header { name: "Host".to_string(), value: "www.example.com".to_string() },
Header { name: "Content-Type".to_string(), value: "application/example".to_string() },
Header { name: "If-Match".to_string(), value: "\"e0023aa4e\"".to_string() },
],
querystring: vec![],
form: vec![],
multipart: vec![],
cookies: vec![],
body: vec![]
};
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 204);
assert!(response.body.is_empty());
}
// endregion
// region headers
#[test]
fn test_custom_headers() {
let mut client = default_client();
let request = Request {
method: Method::Get,
url: "http://localhost:8000/custom-headers".to_string(),
headers: vec![
new_header("Fruit", "Raspberry"),
new_header("Fruit", "Apple"),
new_header("Fruit", "Banana"),
new_header("Fruit", "Grape"),
new_header("Color", "Green"),
],
querystring: vec![],
form: vec![],
multipart: vec![],
cookies: vec![],
body: vec![]
};
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert!(response.body.is_empty());
}
// endregion
// region querystrings
#[test]
fn test_querystring_params() {
let mut client = default_client();
let request = Request {
method: Method::Get,
url: "http://localhost:8000/querystring-params".to_string(),
headers: vec![],
querystring: vec![
Param { name: "param1".to_string(), value: "value1".to_string() },
Param { name: "param2".to_string(), value: "".to_string() },
Param { name: "param3".to_string(), value: "a=b".to_string() },
Param { name: "param4".to_string(), value: "1,2,3".to_string() }
],
form: vec![],
multipart: vec![],
cookies: vec![],
body: vec![]
};
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert!(response.body.is_empty());
}
// endregion
// region form params
#[test]
fn test_form_params() {
let mut client = default_client();
let request = Request {
method: Method::Post,
url: "http://localhost:8000/form-params".to_string(),
headers: vec![],
querystring: vec![],
form: vec![
Param { name: "param1".to_string(), value: "value1".to_string() },
Param { name: "param2".to_string(), value: "".to_string() },
Param { name: "param3".to_string(), value: "a=b".to_string() },
Param { name: "param4".to_string(), value: "a%3db".to_string() }
],
multipart: vec![],
cookies: vec![],
body: vec![]
};
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert!(response.body.is_empty());
// make sure you can reuse client for other request
let request = default_get_request("http://localhost:8000/hello".to_string());
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert_eq!(response.body, b"Hello World!".to_vec());
}
// endregion
// region redirect
#[test]
fn test_follow_location() {
let request = default_get_request("http://localhost:8000/redirect".to_string());
let mut client = default_client();
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 302);
assert_eq!(response.get_header_values("Location".to_string()).get(0).unwrap(),
"http://localhost:8000/redirected");
assert_eq!(client.redirect_count, 0);
let options = ClientOptions {
follow_location: true,
max_redirect: None,
cookie_file: None,
cookie_jar: None,
proxy: None,
verbose: false,
};
let mut client = libcurl::client::Client::init(options);
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert_eq!(response.get_header_values("Content-Length".to_string()).get(0).unwrap(), "0");
assert_eq!(client.redirect_count, 1);
// make sure that the redirect count is reset to 0
let request = default_get_request("http://localhost:8000/hello".to_string());
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert_eq!(response.body, b"Hello World!".to_vec());
assert_eq!(client.redirect_count, 0);
}
#[test]
fn test_max_redirect() {
let options = ClientOptions {
follow_location: true,
max_redirect: Some(10),
cookie_file: None,
cookie_jar: None,
proxy: None,
verbose: false,
};
let mut client = libcurl::client::Client::init(options);
let request = default_get_request("http://localhost:8000/redirect".to_string());
let response = client.execute(&request, 5).unwrap();
assert_eq!(response.status, 200);
assert_eq!(client.redirect_count, 6);
let error = client.execute(&request, 11).err().unwrap();
assert_eq!(error, HttpError::TooManyRedirect);
}
// endregion
// region multipart
#[test]
fn test_multipart_form_data() {
let mut client = default_client();
let request = Request {
method: Method::Post,
url: "http://localhost:8000/multipart-form-data".to_string(),
headers: vec![],
querystring: vec![],
form: vec![],
multipart: vec![
MultipartParam::Param(Param{
name: "key1".to_string(),
value: "value1".to_string()
}),
MultipartParam::FileParam(FileParam{
name: "upload1".to_string(),
filename: "hello.txt".to_string(),
data: b"Hello World!".to_vec(),
content_type: "text/plain".to_string()
}),
MultipartParam::FileParam(FileParam{
name: "upload2".to_string(),
filename: "hello.html".to_string(),
data: b"Hello <b>World</b>!".to_vec(),
content_type: "text/html".to_string()
}),
MultipartParam::FileParam(FileParam{
name: "upload3".to_string(),
filename: "hello.txt".to_string(),
data: b"Hello World!".to_vec(),
content_type: "text/html".to_string()
}),
],
cookies: vec![],
body: vec![]
};
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert!(response.body.is_empty());
}
// endregion
// region http body
#[test]
fn test_post_bytes() {
let mut client = default_client();
let request = Request {
method: Method::Post,
url: "http://localhost:8000/post-base64".to_string(),
headers: vec![],
querystring: vec![],
form: vec![],
multipart: vec![],
cookies: vec![],
body: b"Hello World!".to_vec(),
};
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert!(response.body.is_empty());
}
// endregion
// region error
#[test]
fn test_error_could_not_resolve_host() {
let mut client = default_client();
let request = default_get_request("http://unknown".to_string());
let error = client.execute(&request, 0).err().unwrap();
assert_eq!(error, HttpError::CouldNotResolveHost);
}
#[test]
fn test_error_fail_to_connect() {
let mut client = default_client();
let request = default_get_request("http://localhost:9999".to_string());
let error = client.execute(&request, 0).err().unwrap();
assert_eq!(error, HttpError::FailToConnect);
let options = ClientOptions {
follow_location: false,
max_redirect: None,
cookie_file: None,
cookie_jar: None,
proxy: Some("localhost:9999".to_string()),
verbose: true,
};
let mut client = libcurl::client::Client::init(options);
let request = default_get_request("http://localhost:8000/hello".to_string());
let error = client.execute(&request, 0).err().unwrap();
assert_eq!(error, HttpError::FailToConnect);
}
#[test]
fn test_error_could_not_resolve_proxy_name() {
let options = ClientOptions {
follow_location: false,
max_redirect: None,
cookie_file: None,
cookie_jar: None,
proxy: Some("unknown".to_string()),
verbose: false,
};
let mut client = libcurl::client::Client::init(options);
let request = default_get_request("http://localhost:8000/hello".to_string());
let error = client.execute(&request, 0).err().unwrap();
assert_eq!(error, HttpError::CouldNotResolveProxyName);
}
// endregion
// region cookie
#[test]
fn test_cookie() {
let mut client = default_client();
let request = Request {
method: Method::Get,
url: "http://localhost:8000/cookies/set-request-cookie1-valueA".to_string(),
headers: vec![],
querystring: vec![],
form: vec![],
multipart: vec![],
cookies: vec![
RequestCookie { name: "cookie1".to_string(), value: "valueA".to_string() }
],
body: vec![]
};
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert!(response.body.is_empty());
// For the time-being setting a cookie on a request
// update the cookie store as well
// The same cookie does not need to be set explicitly on further requests
let request = default_get_request("http://localhost:8000/cookies/set-request-cookie1-valueA".to_string());
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert!(response.body.is_empty());
}
#[test]
fn test_cookie_storage() {
let mut client = default_client();
let request = default_get_request("http://localhost:8000/cookies/set-session-cookie2-valueA".to_string());
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert!(response.body.is_empty());
let cookie_store = client.get_cookie_storage();
assert_eq!(cookie_store.get(0).unwrap().clone(), Cookie {
domain: "localhost".to_string(),
include_subdomain: "FALSE".to_string(),
path: "/".to_string(),
https: "FALSE".to_string(),
expires: "0".to_string(),
name: "cookie2".to_string(),
value: "valueA".to_string(),
});
let request = default_get_request("http://localhost:8000/cookies/assert-that-cookie2-is-valueA".to_string());
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert!(response.body.is_empty());
}
#[test]
fn test_cookie_file() {
let temp_file = "/tmp/cookies";
let mut file = File::create(temp_file).expect("can not create temp file!");
file.write_all(b"localhost\tFALSE\t/\tFALSE\t0\tcookie2\tvalueA\n").unwrap();
let options = ClientOptions {
follow_location: false,
max_redirect: None,
cookie_file: Some(temp_file.to_string()),
cookie_jar: None,
proxy: None,
verbose: false,
};
let mut client = libcurl::client::Client::init(options);
let request = default_get_request("http://localhost:8000/cookies/assert-that-cookie2-is-valueA".to_string());
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert!(response.body.is_empty());
}
// endregion
// region proxy
#[test]
fn test_proxy() {
// mitmproxy listening on port 8080
let options = ClientOptions {
follow_location: false,
max_redirect: None,
cookie_file: None,
cookie_jar: None,
proxy: Some("localhost:8080".to_string()),
verbose: false,
};
let mut client = libcurl::client::Client::init(options);
let request = default_get_request("http://localhost:8000/hello".to_string());
let response = client.execute(&request, 0).unwrap();
assert_eq!(response.status, 200);
assert_eq!(response.body, b"Hello World!".to_vec());
}
// endregion
|
extern crate glob;
use std::string::String;
use std::process::{Stdio, Command};
use std::fs::File;
use std::os::unix::io::FromRawFd;
use std::os::unix::io::AsRawFd;
pub struct RashCmd {
cmd: Command,
name: String,
args: Vec<String>,
stdin: Stdio,
stdout: Stdio,
stderr: Stdio,
pred: Option<u8>
}
impl RashCmd {
pub fn new(name: &String) -> RashCmd {
return RashCmd {
cmd: Command::new(name.clone()),
name: name.clone(),
args: Vec::new(),
stdin: Stdio::piped(),
stdout: Stdio::piped(),
stderr: Stdio::piped(),
pred: None
}
}
// pub fn pipe_to(&mut self, to: &mut RashCmd) -> &mut RashCmd {
// unsafe {
// to.stdin = Stdio::from_raw_fd(self.stdout.as_raw_fd());
// }
// return self
// }
pub fn redirect_to(&mut self, to: File) -> &mut RashCmd {
unsafe {
self.stdout = Stdio::from_raw_fd(to.as_raw_fd());
}
return self
}
pub fn args(&mut self, args: &[String]) -> &mut RashCmd {
for arg in args {
self.args.push(arg.clone());
}
return self
}
pub fn eval(&mut self) -> Result<(), String> {
// Executes a command, with arguments
self.cmd.spawn()
.expect("Failed to spawn")
.wait()
.expect("Failed to exec");
return Ok(())
}
}
// pub fn parse(tokens: Vec<&str>) -> RashCmd {
// // Takes a list of tokens, and turns it into predicated and piped RashCmds.
// // TODO: Implement
// }
pub fn tokenize(input: &str) -> Result<Vec<String>, String> {
// Parses a shell input, deglobs it, and returns a vector of strings
let mut tokens = Vec::new();
for word in input.split_whitespace() {
if word.contains("*") {
let mut globbed = false;
for glob in glob::glob(word).expect("Failed to parse wildcard") {
let path = glob.expect("Failed to parse glob").to_str().unwrap().to_string();
globbed = true;
tokens.push(String::from(path));
}
if !globbed {
return Err(format!("Failed to expand glob: {}", word));
}
} else {
tokens.push(String::from(word));
}
}
return Ok(tokens)
}
|
use std::ffi::c_void;
use std::fmt::{self, Display};
use super::*;
use crate::support::{self, MlirStringCallback};
use crate::Context;
extern "C" {
type MlirAffineMap;
}
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct AffineMap(*mut MlirAffineMap);
impl AffineMap {
/// Creates a zero-result affine map with no dimensions or symbols
pub fn get_empty(context: Context) -> Self {
unsafe { mlir_affine_map_empty_get(context) }
}
/// Creates a zero-result affine map with the given dimensions and symbols
pub fn get_zero_result(context: Context, dims: usize, symbols: usize) -> Self {
unsafe { mlir_affine_map_zero_result_get(context, dims, symbols) }
}
/// Creates an affine map with results defined by the given list of affine expressions.
/// The resulting map also has the requested number of input dimensions and symbols,
/// regardless of them being used in the results.
pub fn get(context: Context, dims: usize, symbols: usize, exprs: &[AffineExprBase]) -> Self {
unsafe { mlir_affine_map_get(context, dims, symbols, exprs.len(), exprs.as_ptr()) }
}
/// Creates a single constant result affine map
pub fn get_constant(context: Context, value: u64) -> Self {
unsafe { mlir_affine_map_constant_get(context, value) }
}
/// Creates an affine map with `dims` identity
pub fn get_multi_dim_identity(context: Context, dims: usize) -> Self {
unsafe { mlir_affine_map_multi_dim_identity_get(context, dims) }
}
/// Creates an identity affine map on the most minor dimensions.
/// This function will panic if the number of dimensions is greater or equal to the number of results
pub fn get_minor_identity(context: Context, dims: usize, results: usize) -> Self {
assert!(
dims < results,
"the number of dimensions must be less than the number of results"
);
unsafe { mlir_affine_map_minor_identity_get(context, dims, results) }
}
/// Creates an affine map with a permutation expression and its size.
///
/// The permutation expression is a non-empty vector of integers.
/// The elements of the permutation vector must be continuous from 0 and cannot be repeated,
/// i.e. `[1, 2, 0]` is a valid permutation, `[2, 0]` or `[1, 1, 2]` are not.
pub fn get_permutation(context: Context, permutation: Permutation) -> Self {
unsafe { mlir_affine_map_permutation_get(context, permutation.len(), permutation.as_ptr()) }
}
/// Returns true if this is an identity affine map
pub fn is_identity(self) -> bool {
unsafe { mlir_affine_map_is_identity(self) }
}
/// Returns true if this is a minor identity affine map
pub fn is_minor_identity(self) -> bool {
unsafe { mlir_affine_map_is_minor_identity(self) }
}
/// Returns true if this is an empty affine map
pub fn is_empty(self) -> bool {
unsafe { mlir_affine_map_is_empty(self) }
}
/// Returns true if this is a single-result constant affine map
pub fn is_single_constant(self) -> bool {
unsafe { mlir_affine_map_is_single_constant(self) }
}
/// Returns the constant result of this affine map.
///
/// NOTE: This function will panic if the underlying affine map is not constant
pub fn get_constant_result(self) -> u64 {
assert!(
self.is_single_constant(),
"cannot get constant result from non-constant affine map"
);
unsafe { mlir_affine_map_get_single_constant_result(self) }
}
/// Returns the number of dimensions
pub fn num_dimensions(self) -> usize {
unsafe { mlir_affine_map_get_num_dims(self) }
}
/// Returns the number of symbols
pub fn num_symbols(self) -> usize {
unsafe { mlir_affine_map_get_num_symbols(self) }
}
/// Returns the number of results
pub fn num_results(self) -> usize {
unsafe { mlir_affine_map_get_num_results(self) }
}
/// Returns the number of inputs (dimensions + symbols)
pub fn num_inputs(self) -> usize {
unsafe { mlir_affine_map_get_num_inputs(self) }
}
/// Returns the result at the given position
pub fn result(self, index: usize) -> AffineExprBase {
unsafe { mlir_affine_map_get_result(self, index) }
}
/// Returns true if this affine map represents a subset of a symbol-less permutation map
pub fn is_projected_permutation(self) -> bool {
unsafe { mlir_affine_map_is_projected_permutation(self) }
}
/// Returns true if this affine map represents a symbol-less permutation map
pub fn is_permutation(self) -> bool {
unsafe { mlir_affine_map_is_permutation(self) }
}
/// Returns a new affine map consisting of the given results
pub fn subset(self, results: &[usize]) -> Self {
unsafe { mlir_affine_map_get_sub_map(self, results.len(), results.as_ptr()) }
}
/// Returns a new affine map consisting of the most major `n` results
/// Returns a null affine map if `n` is zero
/// Returns the input map if `n` is >= the number of its results
pub fn get_major_subset(self, n: usize) -> Self {
unsafe { mlir_affine_map_get_major_sub_map(self, n) }
}
/// Returns a new affine map consisting of the most minor `n` results
/// Returns a null affine map if `n` is zero
/// Returns the input map if `n` is >= the number of its results
pub fn get_minor_subset(self, n: usize) -> Self {
unsafe { mlir_affine_map_get_minor_sub_map(self, n) }
}
/// Returns a new affine map resulting from applying the given affine expression to each of the
/// results and with the specified number of dimensions and symbols
pub fn replace(
self,
expression: AffineExprBase,
replacement: AffineExprBase,
dims: usize,
symbols: usize,
) -> Self {
unsafe { mlir_affine_map_replace(self, expression, replacement, dims, symbols) }
}
/// Returns the simplified affine map resulting from dropping the symbols that do
/// not appear in any of the individual maps in `maps`.
///
/// Asserts that all maps in `maps` are normalized to the same number of dimensions and symbols.
pub fn compress_unused_symbols(maps: &[Self]) -> Vec<Self> {
extern "C" fn populate_result(results: &mut Vec<AffineMap>, _index: usize, map: AffineMap) {
results.push(map)
}
let mut out = Vec::new();
unsafe {
mlir_affine_map_compress_unused_symbols(
maps.as_ptr(),
maps.len(),
&mut out,
populate_result,
)
}
out
}
pub fn context(self) -> Context {
unsafe { mlir_affine_map_get_context(self) }
}
pub fn is_null(&self) -> bool {
self.0.is_null()
}
pub fn dump(self) {
unsafe { mlir_affine_map_dump(self) }
}
}
impl Default for AffineMap {
fn default() -> Self {
Self(unsafe { std::mem::transmute::<*mut (), *mut MlirAffineMap>(::core::ptr::null_mut()) })
}
}
impl Display for AffineMap {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
unsafe {
mlir_affine_map_print(
*self,
support::write_to_formatter,
f as *mut _ as *mut c_void,
);
}
Ok(())
}
}
impl fmt::Pointer for AffineMap {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:p}", self.0)
}
}
impl Eq for AffineMap {}
impl PartialEq for AffineMap {
fn eq(&self, other: &Self) -> bool {
unsafe { mlir_affine_map_equal(*self, *other) }
}
}
extern "C" {
#[link_name = "mlirAffineMapGetContext"]
fn mlir_affine_map_get_context(map: AffineMap) -> Context;
#[link_name = "mlirAffineMapEqual"]
fn mlir_affine_map_equal(a: AffineMap, b: AffineMap) -> bool;
#[link_name = "mlirAffineMapPrint"]
fn mlir_affine_map_print(map: AffineMap, callback: MlirStringCallback, userdata: *const c_void);
#[link_name = "mlirAffineMapDump"]
fn mlir_affine_map_dump(map: AffineMap);
#[link_name = "mlirAffineMapEmptyGet"]
fn mlir_affine_map_empty_get(context: Context) -> AffineMap;
#[link_name = "mlirAffineMapZeroResultGet"]
fn mlir_affine_map_zero_result_get(context: Context, dims: usize, symbols: usize) -> AffineMap;
#[link_name = "mlirAffineMapGet"]
fn mlir_affine_map_get(
context: Context,
dims: usize,
symbols: usize,
num_exprs: usize,
exprs: *const AffineExprBase,
) -> AffineMap;
#[link_name = "mlirAffineMapMinorIdentityGet"]
fn mlir_affine_map_minor_identity_get(
context: Context,
dims: usize,
results: usize,
) -> AffineMap;
#[link_name = "mlirAffineMapConstantGet"]
fn mlir_affine_map_constant_get(context: Context, value: u64) -> AffineMap;
#[link_name = "mlirAffineMapMultiDimIdentityGet"]
fn mlir_affine_map_multi_dim_identity_get(context: Context, num_dims: usize) -> AffineMap;
#[link_name = "mlirAffineMapPermutationGet"]
fn mlir_affine_map_permutation_get(
context: Context,
num_permutations: usize,
permutations: *const u32,
) -> AffineMap;
#[link_name = "mlirAffineMapIsIdentity"]
fn mlir_affine_map_is_identity(map: AffineMap) -> bool;
#[link_name = "mlirAffineMapIsMinorIdentity"]
fn mlir_affine_map_is_minor_identity(map: AffineMap) -> bool;
#[link_name = "mlirAffineMapIsEmpty"]
fn mlir_affine_map_is_empty(map: AffineMap) -> bool;
#[link_name = "mlirAffineMapIsSingleConstant"]
fn mlir_affine_map_is_single_constant(map: AffineMap) -> bool;
#[link_name = "mlirAffineMapGetSingleConstantResult"]
fn mlir_affine_map_get_single_constant_result(map: AffineMap) -> u64;
#[link_name = "mlirAffineMapGetResult"]
fn mlir_affine_map_get_result(map: AffineMap, index: usize) -> AffineExprBase;
#[link_name = "mlirAffineMapGetNumDims"]
fn mlir_affine_map_get_num_dims(map: AffineMap) -> usize;
#[link_name = "mlirAffineMapGetNumSymbols"]
fn mlir_affine_map_get_num_symbols(map: AffineMap) -> usize;
#[link_name = "mlirAffineMapGetNumResults"]
fn mlir_affine_map_get_num_results(map: AffineMap) -> usize;
#[link_name = "mlirAffineMapGetNumInputs"]
fn mlir_affine_map_get_num_inputs(map: AffineMap) -> usize;
#[link_name = "mlirAffineMapIsProjectedPermutation"]
fn mlir_affine_map_is_projected_permutation(map: AffineMap) -> bool;
#[link_name = "mlirAffineMapIsPermutation"]
fn mlir_affine_map_is_permutation(map: AffineMap) -> bool;
#[link_name = "mlirAffineMapGetSubMap"]
fn mlir_affine_map_get_sub_map(
map: AffineMap,
num_results: usize,
results: *const usize,
) -> AffineMap;
#[link_name = "mlirAffineMapGetMajorSubMap"]
fn mlir_affine_map_get_major_sub_map(map: AffineMap, results: usize) -> AffineMap;
#[link_name = "mlirAffineMapGetMinorSubMap"]
fn mlir_affine_map_get_minor_sub_map(map: AffineMap, results: usize) -> AffineMap;
#[link_name = "mlirAffineMapReplace"]
fn mlir_affine_map_replace(
map: AffineMap,
expression: AffineExprBase,
replacement: AffineExprBase,
dims: usize,
symbols: usize,
) -> AffineMap;
#[allow(improper_ctypes)]
#[link_name = "mlirAffineMapCompressUnusedSymbols"]
fn mlir_affine_map_compress_unused_symbols(
maps: *const AffineMap,
num_maps: usize,
result: &mut Vec<AffineMap>,
callback: extern "C" fn(&mut Vec<AffineMap>, usize, AffineMap),
);
}
/// Represents an affine map permutation expression.
///
/// A permutation expression is a non-empty vector of integers which
/// contains a continuous set of integers starting at 0 with no duplicates.
pub struct Permutation(Vec<u32>);
impl Permutation {
/// Construct a new random permutation of the given size
///
/// NOTE: This function asserts that the size is greater than 0
pub fn new(size: usize) -> Self {
use rand::prelude::*;
assert!(size > 0, "permutations cannot be empty");
let size: u32 = size.try_into().unwrap();
let mut rng = rand::thread_rng();
let mut values: Vec<u32> = (0..size).collect();
values.shuffle(&mut rng);
Self(values)
}
/// Constructs a permutation directly from the given `Vec`.
///
/// # Safety
///
/// It is up to the caller to ensure the invariants of this data structure
/// are met, otherwise use of this is likely to assert somewhere in MLIR or
/// potentially result in miscompilations. It is recommended that you only
/// use this when reproducing a previously constructed permutation for tests
/// or development.
pub unsafe fn from_vec(elements: Vec<u32>) -> Self {
Self(elements)
}
/// Returns the size of this permutation
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns a raw pointer to the beginning of the underlying vector
pub fn as_ptr(&self) -> *const u32 {
self.0.as_ptr()
}
/// Returns the underlying vector as a slice
pub fn as_slice(&self) -> &[u32] {
self.0.as_slice()
}
}
|
use failure::Fallible;
use std::collections::HashMap;
use futures::stream::Stream;
use std::sync::{Arc, Mutex};
use core::fmt::Debug;
use futures::Future;
use futures::future::IntoFuture;
use failure::Error;
use futures_locks::Mutex as FuturesMutex;
/// Convenience type to wrap other types in a Future
pub type FutureIO<'a, T> = Box<dyn Future<Item = T, Error = Error> + Send + 'a>;
// /// Convenience type for the thread-safe storage of plugins
pub type PluginReference = Box<dyn Plugin<String> + Sync + Send>;
/// Trait which fronts InternalPlugin and ExternalPlugin, allowing their trait objects to live in the same collection
pub trait Plugin<T>
where
Self: Debug,
T: Sync + Send,
{
fn run(self: &Self, t: T) -> FutureIO<'static, T>;
}
/// Trait to be implemented by internal plugins with their native IO type
pub trait InternalPlugin
where
Self: Debug,
{
fn run_internal(self: &mut Self, input: String) -> FutureIO<String>;
}
/// Wrapper struct for a universal implementation of Plugin<PluginIO> for all InternalPlugin implementors
#[derive(Debug, Clone)]
pub struct InternalPluginWrapper<T>(Arc<FuturesMutex<T>>);
/// This implementation allows the process function to run ipmlementors of
/// InternalPlugin
impl<T> Plugin<String> for Arc<InternalPluginWrapper<T>>
where
Self: Sync + Send + Clone + 'static,
T: InternalPlugin,
T: Sync + Send + Clone + 'static,
{
fn run(self: &Self, plugin_io: String) -> FutureIO<'static, String> {
// Box::new(futures::future::ok(plugin_io))
Box::new(
self.0.clone().lock()
.map_err(|_| failure::err_msg("could not acquire the plugin mutex"))
.map(|mut guard| {
futures::future::ok::<String, Error>(plugin_io)
.and_then(|internal_io| guard.run_internal(internal_io))
.and_then(|internal_io| {
let plugin_io: Fallible<String> = Ok(internal_io.to_owned());
plugin_io
})
})
.flatten(),
)
}
}
#[derive(Debug, Clone)]
pub struct PluginProcessor
{
plugins: Arc<Vec<Arc<PluginReference>>>,
}
impl PluginProcessor {
/// Processes all given Plugins sequentially.
///
/// This function automatically converts between the different IO representations
/// if necessary.
pub fn process<'a: 'b, 'b>(
self: &'a Self,
initial_io: String,
) -> FutureIO<'b, String> {
let future_result = futures::stream::iter_ok(0..self.plugins.len())
.fold(
String::new(),
move |last_io, next_plugin_index| match self.plugins.clone().get(next_plugin_index).clone() {
Some(next_plugin) => next_plugin.clone().run(last_io),
None => Box::new(futures::future::err(failure::err_msg(format!(
"could not find plugin at index {}",
next_plugin_index
)))),
}
)
.into_future()
.and_then(|final_io| {
Ok(final_io)
});
Box::new(future_result)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, Clone)]
struct TestInternalPlugin {
counter: usize,
dict: HashMap<usize, bool>,
}
impl InternalPlugin for TestInternalPlugin {
fn run_internal(self: &mut Self, io: String) -> FutureIO<String> {
self.counter += 1;
self.dict.insert(self.counter, true);
Box::new(futures::future::ok(io))
}
}
impl Plugin<String> for TestInternalPlugin {
fn run(self: Box<Self>, io: String) -> FutureIO<'static, String> {
Box::new(futures::future::ok(io))
}
}
#[test]
fn process_plugins_with_state() {
let initial_io = String::new();
let plugins: Arc<Vec<PluginReference>> = Arc::new(vec![
Arc::new(InternalPluginWrapper(
Arc::new(FuturesMutex::new(
TestInternalPlugin {
counter: Default::default(),
dict: Default::default(),
},
))
)),
// Arc::new(FuturesMutex::new(Box::new(InternalPluginWrapper(
// TestInternalPlugin {
// counter: Default::default(),
// dict: Default::default(),
// },
// )))),
]);
let plugin_processor = PluginProcessor { plugins };
let runs: usize = 10;
for _ in 0..runs {
let initial_io = initial_io.clone();
let plugins_future: FutureIO<String> =
plugin_processor.clone().process(initial_io.clone());
let _ = tokio::runtime::Runtime::new()
.unwrap()
.block_on(plugins_future)
.expect("plugin processing failed");
}
// assert_eq!(runs, counter.load(Ordering::SeqCst));
// assert!(dict.read().unwrap().get(&runs).unwrap());
}
} |
#[doc = "Writer for register TIMBICR"]
pub type W = crate::W<u32, super::TIMBICR>;
#[doc = "Register TIMBICR `reset()`'s with value 0"]
impl crate::ResetValue for super::TIMBICR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Delayed Protection Flag Clear\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DLYPRTC_AW {
#[doc = "1: Clears associated flag in ISR register"]
CLEAR = 1,
}
impl From<DLYPRTC_AW> for bool {
#[inline(always)]
fn from(variant: DLYPRTC_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `DLYPRTC`"]
pub struct DLYPRTC_W<'a> {
w: &'a mut W,
}
impl<'a> DLYPRTC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DLYPRTC_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reset Interrupt flag Clear"]
pub type RSTC_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `RSTC`"]
pub struct RSTC_W<'a> {
w: &'a mut W,
}
impl<'a> RSTC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RSTC_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[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 = "Output 2 Reset flag Clear"]
pub type RSTX2C_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `RSTx2C`"]
pub struct RSTX2C_W<'a> {
w: &'a mut W,
}
impl<'a> RSTX2C_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RSTX2C_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[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 = "Output 2 Set flag Clear"]
pub type SET2XC_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `SET2xC`"]
pub struct SET2XC_W<'a> {
w: &'a mut W,
}
impl<'a> SET2XC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SET2XC_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[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 = "Output 1 Reset flag Clear"]
pub type RSTX1C_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `RSTx1C`"]
pub struct RSTX1C_W<'a> {
w: &'a mut W,
}
impl<'a> RSTX1C_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RSTX1C_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[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 = "Output 1 Set flag Clear"]
pub type SET1XC_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `SET1xC`"]
pub struct SET1XC_W<'a> {
w: &'a mut W,
}
impl<'a> SET1XC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SET1XC_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[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 = "Capture2 Interrupt flag Clear"]
pub type CPT2C_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `CPT2C`"]
pub struct CPT2C_W<'a> {
w: &'a mut W,
}
impl<'a> CPT2C_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CPT2C_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Capture1 Interrupt flag Clear"]
pub type CPT1C_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `CPT1C`"]
pub struct CPT1C_W<'a> {
w: &'a mut W,
}
impl<'a> CPT1C_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CPT1C_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[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 = "Update Interrupt flag Clear"]
pub type UPDC_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `UPDC`"]
pub struct UPDC_W<'a> {
w: &'a mut W,
}
impl<'a> UPDC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: UPDC_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[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 = "Repetition Interrupt flag Clear"]
pub type REPC_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `REPC`"]
pub struct REPC_W<'a> {
w: &'a mut W,
}
impl<'a> REPC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: REPC_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[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 = "Compare 4 Interrupt flag Clear"]
pub type CMP4C_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `CMP4C`"]
pub struct CMP4C_W<'a> {
w: &'a mut W,
}
impl<'a> CMP4C_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CMP4C_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[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 = "Compare 3 Interrupt flag Clear"]
pub type CMP3C_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `CMP3C`"]
pub struct CMP3C_W<'a> {
w: &'a mut W,
}
impl<'a> CMP3C_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CMP3C_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[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 = "Compare 2 Interrupt flag Clear"]
pub type CMP2C_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `CMP2C`"]
pub struct CMP2C_W<'a> {
w: &'a mut W,
}
impl<'a> CMP2C_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CMP2C_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[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 = "Compare 1 Interrupt flag Clear"]
pub type CMP1C_AW = DLYPRTC_AW;
#[doc = "Write proxy for field `CMP1C`"]
pub struct CMP1C_W<'a> {
w: &'a mut W,
}
impl<'a> CMP1C_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CMP1C_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears associated flag in ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(DLYPRTC_AW::CLEAR)
}
#[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 W {
#[doc = "Bit 14 - Delayed Protection Flag Clear"]
#[inline(always)]
pub fn dlyprtc(&mut self) -> DLYPRTC_W {
DLYPRTC_W { w: self }
}
#[doc = "Bit 13 - Reset Interrupt flag Clear"]
#[inline(always)]
pub fn rstc(&mut self) -> RSTC_W {
RSTC_W { w: self }
}
#[doc = "Bit 12 - Output 2 Reset flag Clear"]
#[inline(always)]
pub fn rstx2c(&mut self) -> RSTX2C_W {
RSTX2C_W { w: self }
}
#[doc = "Bit 11 - Output 2 Set flag Clear"]
#[inline(always)]
pub fn set2x_c(&mut self) -> SET2XC_W {
SET2XC_W { w: self }
}
#[doc = "Bit 10 - Output 1 Reset flag Clear"]
#[inline(always)]
pub fn rstx1c(&mut self) -> RSTX1C_W {
RSTX1C_W { w: self }
}
#[doc = "Bit 9 - Output 1 Set flag Clear"]
#[inline(always)]
pub fn set1x_c(&mut self) -> SET1XC_W {
SET1XC_W { w: self }
}
#[doc = "Bit 8 - Capture2 Interrupt flag Clear"]
#[inline(always)]
pub fn cpt2c(&mut self) -> CPT2C_W {
CPT2C_W { w: self }
}
#[doc = "Bit 7 - Capture1 Interrupt flag Clear"]
#[inline(always)]
pub fn cpt1c(&mut self) -> CPT1C_W {
CPT1C_W { w: self }
}
#[doc = "Bit 6 - Update Interrupt flag Clear"]
#[inline(always)]
pub fn updc(&mut self) -> UPDC_W {
UPDC_W { w: self }
}
#[doc = "Bit 4 - Repetition Interrupt flag Clear"]
#[inline(always)]
pub fn repc(&mut self) -> REPC_W {
REPC_W { w: self }
}
#[doc = "Bit 3 - Compare 4 Interrupt flag Clear"]
#[inline(always)]
pub fn cmp4c(&mut self) -> CMP4C_W {
CMP4C_W { w: self }
}
#[doc = "Bit 2 - Compare 3 Interrupt flag Clear"]
#[inline(always)]
pub fn cmp3c(&mut self) -> CMP3C_W {
CMP3C_W { w: self }
}
#[doc = "Bit 1 - Compare 2 Interrupt flag Clear"]
#[inline(always)]
pub fn cmp2c(&mut self) -> CMP2C_W {
CMP2C_W { w: self }
}
#[doc = "Bit 0 - Compare 1 Interrupt flag Clear"]
#[inline(always)]
pub fn cmp1c(&mut self) -> CMP1C_W {
CMP1C_W { w: self }
}
}
|
struct Counter {
count: u32
}
fn main() {
let mut counter = Counter { count: 0 };
for _ in 1..=3 {
std::thread::spawn(move || {
counter.count += 1
});
}
} |
use chrono::{Datelike, Duration, NaiveDate, Weekday};
use crate::{
database::{period::Period, task_data::TaskData},
time_frame::TimeFrame,
};
pub fn get_done_fraction(
task: &TaskData,
done_timestamps: &[NaiveDate],
time_frame: &TimeFrame,
) -> f64 {
match task.period {
Period::Week => get_done_fraction_weekly(
task.count,
done_timestamps,
&time_frame.start,
&time_frame.end,
),
Period::Month => get_done_fraction_monthly(
task.count,
done_timestamps,
&time_frame.start,
&time_frame.end,
),
Period::Day => todo!(),
Period::OneTime => get_done_fraction_onetime(
task.count,
done_timestamps,
&time_frame.start,
&time_frame.end,
),
}
}
fn get_done_fraction_weekly(
count: i32,
done_timestamps: &[NaiveDate],
start_date: &NaiveDate,
end_date: &NaiveDate,
) -> f64 {
let mut fractions = vec![];
let week_day_counts = get_week_day_counts(&start_date, &end_date);
let refs = Box::new(done_timestamps.iter().map(move |x| *x));
for (week_start, week_end, days_in_week) in week_day_counts.iter() {
let done_count = count_days_in_range(refs.clone(), week_start, week_end);
let done_count = done_count.min(count as usize) as f64;
let should_have_done_count = (count as f64 * (*days_in_week as f64 / 7.0)).floor() as f64;
if should_have_done_count == 0.0 {
fractions.push(1.0);
continue;
}
fractions.push(done_count / should_have_done_count);
}
average(&fractions).unwrap_or(1.0)
}
fn get_done_fraction_monthly(
count: i32,
done_timestamps: &[NaiveDate],
start_date: &NaiveDate,
end_date: &NaiveDate,
) -> f64 {
let mut fractions = vec![];
let month_day_counts = get_month_day_counts(&start_date, &end_date);
let refs = Box::new(done_timestamps.iter().map(move |x| *x));
for (month_start, month_end, days_in_month) in month_day_counts.iter() {
let done_count = count_days_in_range(refs.clone(), month_start, month_end);
let done_count = done_count.min(count as usize) as f64;
let total_days_in_month = (*month_end - *month_start).num_days() + 1;
let should_have_done_count =
(count as f64 * (*days_in_month as f64 / total_days_in_month as f64)).floor() as f64;
if should_have_done_count == 0.0 {
fractions.push(1.0);
continue;
}
fractions.push(done_count / should_have_done_count);
}
average(&fractions).unwrap_or(1.0)
}
fn get_done_fraction_onetime(
count: i32,
done_timestamps: &[NaiveDate],
start_date: &NaiveDate,
end_date: &NaiveDate,
) -> f64 {
let done_count = count_days_in_range(
Box::new(done_timestamps.iter().map(|date| date.clone())),
start_date,
end_date,
);
(done_count as f64 / count as f64).min(1.0)
}
fn average(numbers: &[f64]) -> Option<f64> {
match numbers.len() {
0 => None,
_ => Some(numbers.iter().sum::<f64>() / (numbers.len() as f64)),
}
}
fn get_week_day_counts(
start_date: &NaiveDate,
end_date: &NaiveDate,
) -> Vec<(NaiveDate, NaiveDate, usize)> {
let days_to_last_monday = start_date.weekday().number_from_monday() - 1;
let last_monday = *start_date - Duration::days(days_to_last_monday as i64);
last_monday
.iter_weeks()
.take_while(|date| date <= end_date)
.map(|date| {
(
date,
end_of_week(&date),
get_week_day_count(&date, start_date, end_date),
)
})
.collect()
}
fn end_of_week(monday_of_week: &NaiveDate) -> NaiveDate {
*monday_of_week + Duration::days(6)
}
fn end_of_month(day_in_month: &NaiveDate) -> NaiveDate {
let this_month = day_in_month.month();
day_in_month
.iter_days()
.take_while(|day| day.month() == this_month)
.last()
.unwrap()
}
fn get_week_day_count(
monday_of_week: &NaiveDate,
start_date: &NaiveDate,
end_date: &NaiveDate,
) -> usize {
assert_eq!(monday_of_week.weekday(), Weekday::Mon);
let sunday_of_week = end_of_week(monday_of_week);
count_days_in_range(
Box::new(
monday_of_week
.iter_days()
.take_while(move |day| *day <= sunday_of_week),
),
start_date,
end_date,
)
}
fn get_month_day_counts(
start_date: &NaiveDate,
end_date: &NaiveDate,
) -> Vec<(NaiveDate, NaiveDate, usize)> {
let days_to_last_first = start_date.day() - 1;
let last_first = *start_date - Duration::days(days_to_last_first as i64);
iter_months(&last_first)
.take_while(|date| date <= end_date)
.map(|date| {
(
date,
end_of_month(&date),
get_month_day_count(&date, start_date, end_date),
)
})
.collect()
}
fn iter_months(naive_date: &NaiveDate) -> Box<dyn Iterator<Item = NaiveDate>> {
Box::new(naive_date.iter_days().filter(|day| day.day() == 1))
}
fn get_month_day_count(
first_of_month: &NaiveDate,
start_date: &NaiveDate,
end_date: &NaiveDate,
) -> usize {
let last_of_month = first_of_month
.iter_days()
.take_while(|day| day.month() == first_of_month.month())
.last()
.unwrap();
count_days_in_range(
Box::new(
first_of_month
.iter_days()
.take_while(move |day| *day <= last_of_month),
),
start_date,
end_date,
)
}
fn count_days_in_range<'a>(
days: Box<dyn Iterator<Item = NaiveDate> + 'a>,
start_date: &NaiveDate,
end_date: &NaiveDate,
) -> usize {
days.filter(|day| start_date <= day && day <= &end_date)
.count()
}
#[cfg(test)]
mod tests {
use chrono::NaiveDate;
use crate::{
database::{period::Period, task_data::TaskData},
time_frame::TimeFrame,
};
use super::{get_done_fraction, get_month_day_count, get_week_day_count, get_week_day_counts};
#[test]
fn weekly() {
let timeframe = TimeFrame {
start: NaiveDate::from_ymd(1970, 01, 01),
end: NaiveDate::from_ymd(1970, 01, 10),
};
let task_data = TaskData {
name: "".into(),
count: 7,
period: Period::Week,
};
let timestamps = &[timeframe.start, timeframe.end];
let fraction = get_done_fraction(&task_data, timestamps, &timeframe);
assert_eq!(fraction, (1.0 / 4.0 + 1.0 / 6.0) / 2.0);
let timestamps = &[
NaiveDate::from_ymd(1970, 01, 01),
NaiveDate::from_ymd(1970, 01, 02),
NaiveDate::from_ymd(1970, 01, 03),
NaiveDate::from_ymd(1970, 01, 04),
];
let fraction = get_done_fraction(&task_data, timestamps, &timeframe);
assert_eq!(fraction, (4.0 / 4.0 + 0.0 / 6.0) / 2.0);
let timestamps = &[
NaiveDate::from_ymd(1970, 01, 01),
NaiveDate::from_ymd(1970, 01, 02),
NaiveDate::from_ymd(1970, 01, 03),
NaiveDate::from_ymd(1970, 01, 05),
];
let fraction = get_done_fraction(&task_data, timestamps, &timeframe);
assert_eq!(fraction, (3.0 / 4.0 + 1.0 / 6.0) / 2.0);
let timestamps = &[
NaiveDate::from_ymd(1970, 12, 01),
NaiveDate::from_ymd(1970, 12, 02),
NaiveDate::from_ymd(1970, 12, 03),
NaiveDate::from_ymd(1970, 12, 05),
];
let fraction = get_done_fraction(&task_data, timestamps, &timeframe);
assert_eq!(fraction, 0.0);
// Once per week with two broken weeks means it never has to be done
let timestamps = &[
NaiveDate::from_ymd(1970, 01, 01),
NaiveDate::from_ymd(1970, 01, 02),
NaiveDate::from_ymd(1970, 01, 03),
NaiveDate::from_ymd(1970, 01, 04),
];
let task_data = TaskData {
name: "".into(),
count: 1,
period: Period::Week,
};
let fraction = get_done_fraction(&task_data, timestamps, &timeframe);
assert_eq!(fraction, (1.0 + 1.0) / 2.0);
}
#[test]
fn monthly() {
let timeframe = TimeFrame {
start: NaiveDate::from_ymd(1970, 01, 01),
end: NaiveDate::from_ymd(1970, 04, 30),
};
let task_data = TaskData {
name: "".into(),
count: 1,
period: Period::Month,
};
let timestamps = &[
NaiveDate::from_ymd(1970, 01, 01),
NaiveDate::from_ymd(1970, 02, 01),
];
let fraction = get_done_fraction(&task_data, timestamps, &timeframe);
assert_eq!(fraction, (1.0 / 1.0 + 1.0 / 1.0 + 2.0 * 0.0 / 1.0) / 4.0);
let timestamps = &[
NaiveDate::from_ymd(1970, 01, 01),
NaiveDate::from_ymd(1970, 01, 02),
NaiveDate::from_ymd(1970, 01, 03),
NaiveDate::from_ymd(1970, 01, 04),
];
let fraction = get_done_fraction(&task_data, timestamps, &timeframe);
assert_eq!(fraction, (1.0 / 1.0 + 3.0 * 0.0 / 1.0) / 4.0);
}
#[test]
fn test_get_week_day_counts() {
let start_date = NaiveDate::from_ymd(1970, 01, 01);
let end_date = NaiveDate::from_ymd(1970, 01, 20);
let week_day_counts = get_week_day_counts(&start_date, &end_date);
let mut week_day_counts_iter = week_day_counts.iter();
assert_eq!(
week_day_counts_iter.next().unwrap(),
&(
NaiveDate::from_ymd(1969, 12, 29),
NaiveDate::from_ymd(1970, 01, 04),
4
)
);
assert_eq!(
week_day_counts_iter.next().unwrap(),
&(
NaiveDate::from_ymd(1970, 01, 05),
NaiveDate::from_ymd(1970, 01, 11),
7
)
);
assert_eq!(
week_day_counts_iter.next().unwrap(),
&(
NaiveDate::from_ymd(1970, 01, 12),
NaiveDate::from_ymd(1970, 01, 18),
7
)
);
assert_eq!(
week_day_counts_iter.next().unwrap(),
&(
NaiveDate::from_ymd(1970, 01, 19),
NaiveDate::from_ymd(1970, 01, 25),
2
)
);
}
#[test]
fn test_get_week_day_count() {
let date = NaiveDate::from_ymd(1970, 01, 19);
assert_eq!(
get_week_day_count(
&date,
&NaiveDate::from_ymd(1970, 01, 01),
&NaiveDate::from_ymd(1970, 01, 31)
),
7
);
assert_eq!(
get_week_day_count(
&date,
&NaiveDate::from_ymd(1970, 01, 15),
&NaiveDate::from_ymd(1970, 01, 21)
),
3
);
assert_eq!(
get_week_day_count(
&date,
&NaiveDate::from_ymd(1970, 01, 19),
&NaiveDate::from_ymd(1970, 01, 19)
),
1
);
}
#[test]
fn test_get_month_day_count() {
let date = NaiveDate::from_ymd(1970, 01, 01);
assert_eq!(
get_month_day_count(
&date,
&NaiveDate::from_ymd(1969, 12, 01),
&NaiveDate::from_ymd(1970, 01, 31)
),
31
);
assert_eq!(
get_month_day_count(
&date,
&NaiveDate::from_ymd(1970, 01, 01),
&NaiveDate::from_ymd(1970, 01, 15)
),
15
);
assert_eq!(
get_month_day_count(
&date,
&NaiveDate::from_ymd(1970, 01, 07),
&NaiveDate::from_ymd(1970, 01, 15)
),
9
);
}
#[test]
fn test_onetime() {
let timeframe = TimeFrame {
start: NaiveDate::from_ymd(1970, 01, 01),
end: NaiveDate::from_ymd(1970, 01, 30),
};
let task_data = TaskData {
name: "".into(),
count: 2,
period: Period::OneTime,
};
let timestamps = &[];
let fraction = get_done_fraction(&task_data, timestamps, &timeframe);
assert_eq!(fraction, 0.0);
let timestamps = &[
NaiveDate::from_ymd(1970, 01, 01),
NaiveDate::from_ymd(1970, 01, 02),
];
let fraction = get_done_fraction(&task_data, timestamps, &timeframe);
assert_eq!(fraction, 1.0);
let timestamps = &[
NaiveDate::from_ymd(1970, 01, 01),
NaiveDate::from_ymd(1970, 01, 02),
NaiveDate::from_ymd(1970, 01, 03), // Doing it more often doesnt increase the fraction beyond 1.0
];
let fraction = get_done_fraction(&task_data, timestamps, &timeframe);
assert_eq!(fraction, 1.0);
let timestamps = &[
NaiveDate::from_ymd(1970, 01, 01),
NaiveDate::from_ymd(1970, 02, 01), // Shouldn't count because outside of range
];
let fraction = get_done_fraction(&task_data, timestamps, &timeframe);
assert_eq!(fraction, 0.5);
}
}
|
#[doc = "Reader of register C1_APB1HENR"]
pub type R = crate::R<u32, super::C1_APB1HENR>;
#[doc = "Writer for register C1_APB1HENR"]
pub type W = crate::W<u32, super::C1_APB1HENR>;
#[doc = "Register C1_APB1HENR `reset()`'s with value 0"]
impl crate::ResetValue for super::C1_APB1HENR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Clock Recovery System peripheral clock enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CRSEN_A {
#[doc = "0: The selected clock is disabled"]
DISABLED = 0,
#[doc = "1: The selected clock is enabled"]
ENABLED = 1,
}
impl From<CRSEN_A> for bool {
#[inline(always)]
fn from(variant: CRSEN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `CRSEN`"]
pub type CRSEN_R = crate::R<bool, CRSEN_A>;
impl CRSEN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CRSEN_A {
match self.bits {
false => CRSEN_A::DISABLED,
true => CRSEN_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == CRSEN_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == CRSEN_A::ENABLED
}
}
#[doc = "Write proxy for field `CRSEN`"]
pub struct CRSEN_W<'a> {
w: &'a mut W,
}
impl<'a> CRSEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CRSEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(CRSEN_A::DISABLED)
}
#[doc = "The selected clock is enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(CRSEN_A::ENABLED)
}
#[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 = "SWPMI Peripheral Clocks Enable"]
pub type SWPEN_A = CRSEN_A;
#[doc = "Reader of field `SWPEN`"]
pub type SWPEN_R = crate::R<bool, CRSEN_A>;
#[doc = "Write proxy for field `SWPEN`"]
pub struct SWPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SWPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SWPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(CRSEN_A::DISABLED)
}
#[doc = "The selected clock is enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(CRSEN_A::ENABLED)
}
#[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 = "OPAMP peripheral clock enable"]
pub type OPAMPEN_A = CRSEN_A;
#[doc = "Reader of field `OPAMPEN`"]
pub type OPAMPEN_R = crate::R<bool, CRSEN_A>;
#[doc = "Write proxy for field `OPAMPEN`"]
pub struct OPAMPEN_W<'a> {
w: &'a mut W,
}
impl<'a> OPAMPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: OPAMPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(CRSEN_A::DISABLED)
}
#[doc = "The selected clock is enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(CRSEN_A::ENABLED)
}
#[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 = "MDIOS peripheral clock enable"]
pub type MDIOSEN_A = CRSEN_A;
#[doc = "Reader of field `MDIOSEN`"]
pub type MDIOSEN_R = crate::R<bool, CRSEN_A>;
#[doc = "Write proxy for field `MDIOSEN`"]
pub struct MDIOSEN_W<'a> {
w: &'a mut W,
}
impl<'a> MDIOSEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MDIOSEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(CRSEN_A::DISABLED)
}
#[doc = "The selected clock is enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(CRSEN_A::ENABLED)
}
#[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 = "FDCAN Peripheral Clocks Enable"]
pub type FDCANEN_A = CRSEN_A;
#[doc = "Reader of field `FDCANEN`"]
pub type FDCANEN_R = crate::R<bool, CRSEN_A>;
#[doc = "Write proxy for field `FDCANEN`"]
pub struct FDCANEN_W<'a> {
w: &'a mut W,
}
impl<'a> FDCANEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FDCANEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(CRSEN_A::DISABLED)
}
#[doc = "The selected clock is enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(CRSEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
impl R {
#[doc = "Bit 1 - Clock Recovery System peripheral clock enable"]
#[inline(always)]
pub fn crsen(&self) -> CRSEN_R {
CRSEN_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - SWPMI Peripheral Clocks Enable"]
#[inline(always)]
pub fn swpen(&self) -> SWPEN_R {
SWPEN_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 4 - OPAMP peripheral clock enable"]
#[inline(always)]
pub fn opampen(&self) -> OPAMPEN_R {
OPAMPEN_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - MDIOS peripheral clock enable"]
#[inline(always)]
pub fn mdiosen(&self) -> MDIOSEN_R {
MDIOSEN_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 8 - FDCAN Peripheral Clocks Enable"]
#[inline(always)]
pub fn fdcanen(&self) -> FDCANEN_R {
FDCANEN_R::new(((self.bits >> 8) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 1 - Clock Recovery System peripheral clock enable"]
#[inline(always)]
pub fn crsen(&mut self) -> CRSEN_W {
CRSEN_W { w: self }
}
#[doc = "Bit 2 - SWPMI Peripheral Clocks Enable"]
#[inline(always)]
pub fn swpen(&mut self) -> SWPEN_W {
SWPEN_W { w: self }
}
#[doc = "Bit 4 - OPAMP peripheral clock enable"]
#[inline(always)]
pub fn opampen(&mut self) -> OPAMPEN_W {
OPAMPEN_W { w: self }
}
#[doc = "Bit 5 - MDIOS peripheral clock enable"]
#[inline(always)]
pub fn mdiosen(&mut self) -> MDIOSEN_W {
MDIOSEN_W { w: self }
}
#[doc = "Bit 8 - FDCAN Peripheral Clocks Enable"]
#[inline(always)]
pub fn fdcanen(&mut self) -> FDCANEN_W {
FDCANEN_W { w: self }
}
}
|
use crate::{
engine::world::WorldCameraExt, engine::Engine, game::GameState, render::components::Cursor,
};
use cvar::{INode, IVisit};
pub use gfx2d::math::*;
use hecs::World;
mod cli;
mod entities;
mod render;
mod spawner;
pub use render::RenderState;
#[derive(Default)]
pub struct DebugState {
pub visible: bool,
pub initial_zoom: f32,
cli: cli::CliState,
spawner: spawner::SpawnerState,
entities: entities::EntitiesState,
pub render: RenderState,
}
impl IVisit for DebugState {
fn visit(&mut self, f: &mut dyn FnMut(&mut dyn INode)) {
f(&mut cvar::Property("visible", &mut self.visible, false));
f(&mut cvar::Property(
"initial_zoom",
&mut self.initial_zoom,
0.0,
));
f(&mut cvar::List("cli", &mut self.cli));
f(&mut cvar::List("spawner", &mut self.spawner));
f(&mut cvar::List("entities", &mut self.entities));
f(&mut cvar::List("render", &mut self.render));
}
}
pub fn build_ui(eng: &Engine<'_>, game: &mut GameState) {
let gravity = game.config.phys.gravity;
let debug = &mut game.config.debug;
if debug.visible {
let mouse = if let Some((_entity, cursor)) = game.world.query::<&Cursor>().iter().next() {
**cursor
} else {
Vec2::ZERO
};
let scale = game.config.phys.scale;
let (camera, camera_position) = game.world.get_camera_and_camera_position();
let (dx, dy, _w, _h) = camera.viewport(*camera_position);
let (x, y) = camera.mouse_to_world(*camera_position, mouse.x, mouse.y);
egui::Window::new("Debugger")
.title_bar(false)
.resizable(false)
.collapsible(false)
.show(eng.egui_ctx, |ui| {
ui.horizontal_wrapped(|ui| {
if ui.selectable_label(debug.cli.visible, "CLI").clicked() {
debug.cli.visible = !debug.cli.visible;
debug.cli.auto_focus = true;
debug.cli.auto_scroll = true;
}
toggle_state(ui, &mut debug.spawner.visible, "Spawn");
toggle_state(ui, &mut debug.entities.visible, "Entities");
toggle_state(ui, &mut debug.render.visible, "Render");
});
ui.separator();
ui.scope(|ui| {
ui.style_mut().override_text_style = Some(egui::TextStyle::Monospace);
ui.label(format!(
"{:4}FPS \u{B1}{}",
eng.fps, eng.overstep_percentage
));
ui.horizontal_wrapped(|ui| {
if ui.button("\u{2196}").clicked() {
eng.quad_ctx.set_cursor_grab(false);
}
ui.label(format!(
"{:4} {:3} [{:.3} {:.3}]",
eng.input.mouse_x, eng.input.mouse_y, mouse.x, mouse.y
));
});
ui.label(format!(
" \u{1F5FA} {:4.3} {:3.3} ({:.3},{:.3})",
x, y, dx, dy
));
});
});
debug.cli.build_ui(eng);
debug
.spawner
.build_ui(eng.egui_ctx, &mut game.world, x, y, scale, gravity);
debug.entities.build_ui(eng.egui_ctx, &mut game.world);
debug.render.build_ui(eng.egui_ctx);
}
}
fn toggle_state(ui: &mut egui::Ui, state: &mut bool, label: &str) {
if ui.selectable_label(*state, label).clicked() {
*state = !*state;
}
}
fn toggle_state_inv(ui: &mut egui::Ui, state: &mut bool, label: &str) {
if ui.selectable_label(!*state, label).clicked() {
*state = !*state;
}
}
|
use std::fmt::{Debug, Error, Formatter};
use libwebp_sys::*;
use crate::shared::{PixelLayout, WebPImage, WebPMemory};
/// A decoder for WebP images. It uses the default configuration of libwebp.
/// Currently, animated images are not supported.
pub struct Decoder<'a> {
data: &'a [u8],
}
impl<'a> Decoder<'a> {
/// Creates a new decoder from the given image data.
pub fn new(data: &'a [u8]) -> Self {
Self { data }
}
/// Decodes the image data. If the image contains a valid WebP image, a [WebPImage](../shared/struct.WebPImage.html) is returned.
pub fn decode(&self) -> Option<WebPImage> {
let features = BitstreamFeatures::new(self.data)?;
if features.has_animation() {
return None;
}
let width = features.width();
let height = features.height();
let pixel_count = width * height;
let image_ptr = unsafe {
let mut width = width as i32;
let mut height = height as i32;
if features.has_alpha() {
WebPDecodeRGBA(
self.data.as_ptr(),
self.data.len(),
&mut width as *mut _,
&mut height as *mut _,
)
} else {
WebPDecodeRGB(
self.data.as_ptr(),
self.data.len(),
&mut width as *mut _,
&mut height as *mut _,
)
}
};
if image_ptr.is_null() {
return None;
}
let image = if features.has_alpha() {
let len = 4 * pixel_count as usize;
WebPImage::new(WebPMemory(image_ptr, len), PixelLayout::Rgba, width, height)
} else {
let len = 3 * pixel_count as usize;
WebPImage::new(WebPMemory(image_ptr, len), PixelLayout::Rgb, width, height)
};
Some(image)
}
}
/// A wrapper around libwebp-sys::WebPBitstreamFeatures which allows to get information about the image.
pub struct BitstreamFeatures(WebPBitstreamFeatures);
impl BitstreamFeatures {
pub fn new(data: &[u8]) -> Option<Self> {
unsafe {
let mut features: WebPBitstreamFeatures = std::mem::zeroed();
let result = WebPGetFeatures(data.as_ptr(), data.len(), &mut features as *mut _);
if result == VP8StatusCode::VP8_STATUS_OK {
return Some(Self(features));
}
}
None
}
/// Returns the width of the image as described by the bitstream in pixels.
pub fn width(&self) -> u32 {
self.0.width as u32
}
/// Returns the height of the image as described by the bitstream in pixels.
pub fn height(&self) -> u32 {
self.0.height as u32
}
/// Returns true if the image as described by the bitstream has an alpha channel.
pub fn has_alpha(&self) -> bool {
self.0.has_alpha == 1
}
/// Returns true if the image as described by the bitstream is animated.
pub fn has_animation(&self) -> bool {
self.0.has_animation == 1
}
/// Returns the format of the image as described by image bitstream.
pub fn format(&self) -> Option<BitstreamFormat> {
match self.0.format {
0 => Some(BitstreamFormat::Undefined),
1 => Some(BitstreamFormat::Lossy),
2 => Some(BitstreamFormat::Lossless),
_ => None,
}
}
}
impl Debug for BitstreamFeatures {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
let mut debug_struct = f.debug_struct("BitstreamFeatures");
debug_struct
.field("width", &self.width())
.field("height", &self.height())
.field("has_alpha", &self.has_alpha())
.field("has_animation", &self.has_animation());
match self.format() {
Some(BitstreamFormat::Undefined) => debug_struct.field("format", &"Undefined"),
Some(BitstreamFormat::Lossy) => debug_struct.field("format", &"Lossy"),
Some(BitstreamFormat::Lossless) => debug_struct.field("format", &"Lossless"),
None => debug_struct.field("format", &"Error"),
};
debug_struct.finish()
}
}
#[derive(Debug)]
/// The format of the image bitstream which is either lossy, lossless or something else.
pub enum BitstreamFormat {
Undefined = 0,
Lossy = 1,
Lossless = 2,
}
|
use node::Node;
use traits::{Leaf, PathInfo, SubOrd};
use node::NodesPtr;
use self::actions::{NodeAction, LeafAction};
pub trait CursorNav: Sized {
type Leaf: Leaf;
type NodesPtr: NodesPtr<Self::Leaf>;
type PathInfo: PathInfo<<Self::Leaf as Leaf>::Info>;
fn _is_root(&self) -> bool;
fn _path_info(&self) -> Self::PathInfo;
fn _leaf(&self) -> Option<&Self::Leaf>;
fn _height(&self) -> Option<usize>;
fn _current(&self) -> Option<&Node<Self::Leaf, Self::NodesPtr>>;
fn _current_must(&self) -> &Node<Self::Leaf, Self::NodesPtr>;
fn _reset(&mut self);
fn _ascend(&mut self) -> Option<&Node<Self::Leaf, Self::NodesPtr>>;
fn _descend_first(&mut self) -> Option<&Node<Self::Leaf, Self::NodesPtr>>;
fn _descend_last(&mut self) -> Option<&Node<Self::Leaf, Self::NodesPtr>>;
fn _left_sibling(&mut self) -> Option<&Node<Self::Leaf, Self::NodesPtr>>;
fn _right_sibling(&mut self) -> Option<&Node<Self::Leaf, Self::NodesPtr>>;
fn first_leaf(&mut self) -> Option<&Self::Leaf> {
while self._descend_first().is_some() {}
self._leaf()
}
fn last_leaf(&mut self) -> Option<&Self::Leaf> {
while self._descend_last().is_some() {}
self._leaf()
}
fn next_node(&mut self) -> Option<&Node<Self::Leaf, Self::NodesPtr>> {
let height = self._height();
if self.right_maybe_ascend().is_some() {
let height = height.unwrap();
while self._current_must().height() > height {
let _res = self._descend_first();
debug_assert!(_res.is_some());
}
Some(&self._current_must())
} else {
None
}
}
fn prev_node(&mut self) -> Option<&Node<Self::Leaf, Self::NodesPtr>> {
let height = self._height();
if self.left_maybe_ascend().is_some() {
let height = height.unwrap();
while self._current_must().height() > height {
let _res = self._descend_last();
debug_assert!(_res.is_some());
}
Some(self._current_must())
} else {
None
}
}
fn next_leaf(&mut self) -> Option<&Self::Leaf> {
self.next_node().and_then(|n| n.leaf())
}
fn prev_leaf(&mut self) -> Option<&Self::Leaf> {
self.prev_node().and_then(|n| n.leaf())
}
fn left_maybe_ascend(&mut self) -> Option<&Node<Self::Leaf, Self::NodesPtr>> {
loop {
if self._left_sibling().is_some() {
return Some(self._current_must());
} else if self._ascend().is_none() {
return None;
}
}
}
fn right_maybe_ascend(&mut self) -> Option<&Node<Self::Leaf, Self::NodesPtr>> {
loop {
if self._right_sibling().is_some() {
return Some(self._current_must());
} else if self._ascend().is_none() {
return None;
}
}
}
fn action_till<A, F>(&mut self, predicate: F) -> bool
where A: actions::NodeAction,
F: Fn(Self::PathInfo, <Self::Leaf as Leaf>::Info) -> bool
{
while A::act_on(self).is_some() {
if predicate(self._path_info(), self._current_must().info()) {
return true;
}
}
return false;
}
fn jump_to<JAS, F>(&mut self, satisfies: F) -> Option<&Self::Leaf>
where JAS: actions::JumpActionSet,
F: Fn(Self::PathInfo, <Self::Leaf as Leaf>::Info) -> bool,
{
enum FindStatus {
HitRoot, // condition was false at root
HitTrue, // condition was true at its pibling
}
let mut status;
// ascend till a well-defined state
match self._current().map(|n| satisfies(self._path_info(), n.info())) {
Some(true) => {
if !self.action_till::<JAS::AscendToFalse, _>(|path_info, info| !satisfies(path_info, info)) {
// condition is satisfied at root
return JAS::TrueRootToLeaf::act_on(self); // must unwrap
}
status = FindStatus::HitTrue;
},
Some(false) => {
if self._is_root() {
status = FindStatus::HitRoot;
} else {
if self.action_till::<JAS::AscendToTrue, _>(|path_info, info| satisfies(path_info, info)) {
JAS::SiblingToFalse::act_on(self); // make condition false, must unwrap
status = FindStatus::HitTrue;
} else {
status = FindStatus::HitRoot;
}
}
},
None => return None,
}
debug_assert!(!satisfies(self._path_info(), self._current().unwrap().info()));
// descend till the last leaf that don't satisfy the condition
while self.action_till::<JAS::DescendToFalse, _>(|path_info, info| satisfies(path_info, info)) {
status = FindStatus::HitTrue;
if !self.action_till::<JAS::SiblingToFalse, _>(|path_info, info| !satisfies(path_info, info)) {
// there must be a sibling that don't satisfy the condition
unreachable!();
}
}
debug_assert!(self._leaf().is_some());
debug_assert!(!satisfies(self._path_info(), self._current().unwrap().info()));
match status {
FindStatus::HitRoot => None,
FindStatus::HitTrue => JAS::FalseLeafToTrue::act_on(self), // must unwrap
}
}
fn find_min<IS>(&mut self, info_sub: IS) -> Option<&Self::Leaf>
where IS: SubOrd<<Self::Leaf as Leaf>::Info>,
{
use std::cmp::Ordering;
let satisfies = |_path_info, info| -> bool {
match info_sub.sub_cmp(&info) {
Ordering::Less | Ordering::Equal => true,
Ordering::Greater => false,
}
};
self.jump_to::<actions::PrefixMin, _>(satisfies)
}
fn find_max<IS>(&mut self, info_sub: IS) -> Option<&Self::Leaf>
where IS: SubOrd<<Self::Leaf as Leaf>::Info>,
{
use std::cmp::Ordering;
let satisfies = |_path_info, info| -> bool {
match info_sub.sub_cmp(&info) {
Ordering::Greater | Ordering::Equal => true,
Ordering::Less => false,
}
};
self.jump_to::<actions::SuffixMax, _>(satisfies)
}
fn goto_min<PS: SubOrd<Self::PathInfo>>(&mut self, path_info_sub: PS) -> Option<&Self::Leaf> {
use std::cmp::Ordering;
let satisfies = |path_info, _info| -> bool {
match path_info_sub.sub_cmp(&path_info) {
Ordering::Less | Ordering::Equal => true,
Ordering::Greater => false,
}
};
self.jump_to::<actions::PrefixMin, _>(satisfies)
}
fn goto_max<PS: SubOrd<Self::PathInfo>>(&mut self, path_info_sub: PS) -> Option<&Self::Leaf> {
use std::cmp::Ordering;
let satisfies = |path_info: Self::PathInfo, info| -> bool {
match path_info_sub.sub_cmp(&path_info.extend(info)) {
Ordering::Greater | Ordering::Equal => true,
Ordering::Less => false,
}
};
self.jump_to::<actions::SuffixMax, _>(satisfies)
}
}
pub mod actions {
use super::{CursorNav, Node};
pub trait NodeAction {
fn act_on<C: CursorNav>(cursor: &mut C) -> Option<&Node<C::Leaf, C::NodesPtr>>;
}
pub trait LeafAction {
fn act_on<C: CursorNav>(cursor: &mut C) -> Option<&C::Leaf>;
}
pub enum LeftSibling {}
impl NodeAction for LeftSibling {
fn act_on<C: CursorNav>(cursor: &mut C) -> Option<&Node<C::Leaf, C::NodesPtr>> {
cursor._left_sibling()
}
}
pub enum RightSibling {}
impl NodeAction for RightSibling {
fn act_on<C: CursorNav>(cursor: &mut C) -> Option<&Node<C::Leaf, C::NodesPtr>> {
cursor._right_sibling()
}
}
pub enum LeftMaybeAscend {}
impl NodeAction for LeftMaybeAscend {
fn act_on<C: CursorNav>(cursor: &mut C) -> Option<&Node<C::Leaf, C::NodesPtr>> {
cursor.left_maybe_ascend()
}
}
pub enum RightMaybeAscend {}
impl NodeAction for RightMaybeAscend {
fn act_on<C: CursorNav>(cursor: &mut C) -> Option<&Node<C::Leaf, C::NodesPtr>> {
cursor.right_maybe_ascend()
}
}
pub enum DescendFirst {}
impl NodeAction for DescendFirst {
fn act_on<C: CursorNav>(cursor: &mut C) -> Option<&Node<C::Leaf, C::NodesPtr>> {
cursor._descend_first()
}
}
pub enum DescendLast {}
impl NodeAction for DescendLast {
fn act_on<C: CursorNav>(cursor: &mut C) -> Option<&Node<C::Leaf, C::NodesPtr>> {
cursor._descend_last()
}
}
pub enum NextLeaf {}
impl LeafAction for NextLeaf {
fn act_on<C: CursorNav>(cursor: &mut C) -> Option<&C::Leaf> {
cursor.next_leaf()
}
}
pub enum PrevLeaf {}
impl LeafAction for PrevLeaf {
fn act_on<C: CursorNav>(cursor: &mut C) -> Option<&C::Leaf> {
cursor.prev_leaf()
}
}
pub enum FirstLeaf {}
impl LeafAction for FirstLeaf {
fn act_on<C: CursorNav>(cursor: &mut C) -> Option<&C::Leaf> {
cursor.first_leaf()
}
}
pub enum LastLeaf {}
impl LeafAction for LastLeaf {
fn act_on<C: CursorNav>(cursor: &mut C) -> Option<&C::Leaf> {
cursor.last_leaf()
}
}
#[doc(hidden)]
pub trait JumpActionSet {
type AscendToTrue: NodeAction;
type AscendToFalse: NodeAction;
type TrueRootToLeaf: LeafAction;
type SiblingToFalse: NodeAction;
type DescendToFalse: NodeAction;
type FalseLeafToTrue: LeafAction;
}
#[doc(hidden)]
pub enum PrefixMin {}
impl JumpActionSet for PrefixMin {
type AscendToTrue = RightMaybeAscend;
type AscendToFalse = LeftMaybeAscend;
type TrueRootToLeaf = FirstLeaf;
type SiblingToFalse = LeftSibling;
type DescendToFalse = DescendLast;
type FalseLeafToTrue = NextLeaf;
}
#[doc(hidden)]
pub enum SuffixMax {}
impl JumpActionSet for SuffixMax {
type AscendToTrue = LeftMaybeAscend;
type AscendToFalse = RightMaybeAscend;
type TrueRootToLeaf = LastLeaf;
type SiblingToFalse = RightSibling;
type DescendToFalse = DescendFirst;
type FalseLeafToTrue = PrevLeaf;
}
}
|
#[cfg(feature="never")]
mod will_fail {
use std::cmp::max;
unsafe fn make_room<T>(v : &mut Vec<T>, req : usize) {
let new_size = max(req, v.len());
v.reserve(new_size);
v.set_len(new_size);
}
fn array_copy<T : Clone>(
src : &Vec<T>,
dest : &mut Vec<T>,
src_off : usize,
dest_off : usize,
len : usize) {
let iter =
src[src_off..src_off+len]
.iter().enumerate();
unsafe {
make_room(dest, dest_off + len);
for (i, x) in iter {
*dest.get_mut(dest_off + i) = x.clone();
}
}
}
fn test() {
let mut v = vec![1, 2, 3];
array_copy(&v, &mut v, 0, 1, 3);
}
}
|
use crate::{Coordinate, CoordinateType, Line, Point, Triangle};
use std::iter::FromIterator;
use std::ops::{Index, IndexMut};
/// An ordered collection of two or more [`Coordinate`s](struct.Coordinate.html), representing a
/// path between locations.
///
/// # Examples
///
/// Create a `LineString` by calling it directly:
///
/// ```
/// use geo_types::{Coordinate, LineString};
///
/// let line_string = LineString(vec![
/// Coordinate { x: 0., y: 0. },
/// Coordinate { x: 10., y: 0. },
/// ]);
/// ```
///
/// Converting a `Vec` of `Coordinate`-like things:
///
/// ```
/// use geo_types::LineString;
///
/// let line_string: LineString<f32> = vec![(0., 0.), (10., 0.)].into();
/// ```
///
/// ```
/// use geo_types::LineString;
///
/// let line_string: LineString<f64> = vec![[0., 0.], [10., 0.]].into();
/// ```
//
/// Or `collect`ing from a `Coordinate` iterator
///
/// ```
/// use geo_types::{Coordinate, LineString};
///
/// let mut coords_iter =
/// vec![Coordinate { x: 0., y: 0. }, Coordinate { x: 10., y: 0. }].into_iter();
///
/// let line_string: LineString<f32> = coords_iter.collect();
/// ```
///
/// You can iterate over the coordinates in the `LineString`:
///
/// ```
/// use geo_types::{Coordinate, LineString};
///
/// let line_string = LineString(vec![
/// Coordinate { x: 0., y: 0. },
/// Coordinate { x: 10., y: 0. },
/// ]);
///
/// for coord in line_string {
/// println!("Coordinate x = {}, y = {}", coord.x, coord.y);
/// }
/// ```
///
/// You can also iterate over the coordinates in the `LineString` as `Point`s:
///
/// ```
/// use geo_types::{Coordinate, LineString};
///
/// let line_string = LineString(vec![
/// Coordinate { x: 0., y: 0. },
/// Coordinate { x: 10., y: 0. },
/// ]);
///
/// for point in line_string.points_iter() {
/// println!("Point x = {}, y = {}", point.x(), point.y());
/// }
/// ```
#[derive(Eq, PartialEq, Clone, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct LineString<T>(pub Vec<Coordinate<T>>)
where
T: CoordinateType;
/// A `Point` iterator returned by the `points_iter` method
pub struct PointsIter<'a, T: CoordinateType + 'a>(::std::slice::Iter<'a, Coordinate<T>>);
impl<'a, T: CoordinateType> Iterator for PointsIter<'a, T> {
type Item = Point<T>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|c| Point(*c))
}
}
impl<'a, T: CoordinateType> DoubleEndedIterator for PointsIter<'a, T> {
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back().map(|c| Point(*c))
}
}
impl<T: CoordinateType> LineString<T> {
/// Return an iterator yielding the coordinates of a `LineString` as `Point`s
pub fn points_iter(&self) -> PointsIter<T> {
PointsIter(self.0.iter())
}
/// Return the coordinates of a `LineString` as a `Vec` of `Point`s
pub fn into_points(self) -> Vec<Point<T>> {
self.0.into_iter().map(Point).collect()
}
/// Return an iterator yielding one `Line` for each line segment
/// in the `LineString`.
///
/// # Examples
///
/// ```
/// use geo_types::{Coordinate, Line, LineString};
///
/// let mut coords = vec![(0., 0.), (5., 0.), (7., 9.)];
/// let line_string: LineString<f32> = coords.into_iter().collect();
///
/// let mut lines = line_string.lines();
/// assert_eq!(
/// Some(Line::new(
/// Coordinate { x: 0., y: 0. },
/// Coordinate { x: 5., y: 0. }
/// )),
/// lines.next()
/// );
/// assert_eq!(
/// Some(Line::new(
/// Coordinate { x: 5., y: 0. },
/// Coordinate { x: 7., y: 9. }
/// )),
/// lines.next()
/// );
/// assert!(lines.next().is_none());
/// ```
pub fn lines<'a>(&'a self) -> impl ExactSizeIterator + Iterator<Item = Line<T>> + 'a {
self.0.windows(2).map(|w| {
// slice::windows(N) is guaranteed to yield a slice with exactly N elements
unsafe { Line::new(*w.get_unchecked(0), *w.get_unchecked(1)) }
})
}
/// An iterator which yields the coordinates of a `LineString` as `Triangle`s
pub fn triangles<'a>(&'a self) -> impl ExactSizeIterator + Iterator<Item = Triangle<T>> + 'a {
self.0.windows(3).map(|w| {
// slice::windows(N) is guaranteed to yield a slice with exactly N elements
unsafe {
Triangle(
*w.get_unchecked(0),
*w.get_unchecked(1),
*w.get_unchecked(2),
)
}
})
}
/// Close the `LineString`. Specifically, if the `LineString` has is at least one coordinate,
/// and the value of the first coordinate does not equal the value of the last coordinate, then
/// a new coordinate is added to the end with the value of the first coordinate.
pub(crate) fn close(&mut self) {
if let (Some(first), Some(last)) = (self.0.first().copied(), self.0.last().copied()) {
if first != last {
self.0.push(first);
}
}
}
/// Return the number of coordinates in the `LineString`.
///
/// # Examples
///
/// ```
/// use geo_types::LineString;
///
/// let mut coords = vec![(0., 0.), (5., 0.), (7., 9.)];
/// let line_string: LineString<f32> = coords.into_iter().collect();
/// assert_eq!(3, line_string.num_coords());
/// ```
pub fn num_coords(&self) -> usize {
self.0.len()
}
}
/// Turn a `Vec` of `Point`-like objects into a `LineString`.
impl<T: CoordinateType, IC: Into<Coordinate<T>>> From<Vec<IC>> for LineString<T> {
fn from(v: Vec<IC>) -> Self {
LineString(v.into_iter().map(|c| c.into()).collect())
}
}
/// Turn an iterator of `Point`-like objects into a `LineString`.
impl<T: CoordinateType, IC: Into<Coordinate<T>>> FromIterator<IC> for LineString<T> {
fn from_iter<I: IntoIterator<Item = IC>>(iter: I) -> Self {
LineString(iter.into_iter().map(|c| c.into()).collect())
}
}
/// Iterate over all the [Coordinate](struct.Coordinates.html)s in this `LineString`.
impl<T: CoordinateType> IntoIterator for LineString<T> {
type Item = Coordinate<T>;
type IntoIter = ::std::vec::IntoIter<Coordinate<T>>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
/// Mutably iterate over all the [Coordinate](struct.Coordinates.html)s in this `LineString`.
impl<'a, T: CoordinateType> IntoIterator for &'a mut LineString<T> {
type Item = &'a mut Coordinate<T>;
type IntoIter = ::std::slice::IterMut<'a, Coordinate<T>>;
fn into_iter(self) -> ::std::slice::IterMut<'a, Coordinate<T>> {
self.0.iter_mut()
}
}
impl<T: CoordinateType> Index<usize> for LineString<T> {
type Output = Coordinate<T>;
fn index(&self, index: usize) -> &Coordinate<T> {
self.0.index(index)
}
}
impl<T: CoordinateType> IndexMut<usize> for LineString<T> {
fn index_mut(&mut self, index: usize) -> &mut Coordinate<T> {
self.0.index_mut(index)
}
}
#[cfg(feature = "rstar")]
impl<T> ::rstar::RTreeObject for LineString<T>
where
T: ::num_traits::Float + ::rstar::RTreeNum,
{
type Envelope = ::rstar::AABB<Point<T>>;
fn envelope(&self) -> Self::Envelope {
use num_traits::Bounded;
let bounding_rect = crate::private_utils::line_string_bounding_rect(self);
match bounding_rect {
None => ::rstar::AABB::from_corners(
Point::new(Bounded::min_value(), Bounded::min_value()),
Point::new(Bounded::max_value(), Bounded::max_value()),
),
Some(b) => ::rstar::AABB::from_corners(
Point::new(b.min().x, b.min().y),
Point::new(b.max().x, b.max().y),
),
}
}
}
#[cfg(feature = "rstar")]
impl<T> ::rstar::PointDistance for LineString<T>
where
T: ::num_traits::Float + ::rstar::RTreeNum,
{
fn distance_2(&self, point: &Point<T>) -> T {
let d = crate::private_utils::point_line_string_euclidean_distance(*point, self);
if d == T::zero() {
d
} else {
d.powi(2)
}
}
}
|
use crate::manager::{AccountStatus, OnChainIdentity};
use crate::primitives::{Account, AccountType, Fatal, Judgement, NetAccount};
#[cfg(test)]
use crate::tests::mocks::MatrixEventMock;
use crossbeam::channel::{unbounded, Receiver, Sender};
#[cfg(test)]
use matrix_sdk::identifiers::{RoomId, UserId};
use tokio::time::{self, Duration};
pub fn generate_comms(
sender: Sender<CommsMessage>,
account_ty: AccountType,
) -> (CommsMain, CommsVerifier) {
let (tx, recv) = unbounded();
(
CommsMain { sender: tx },
CommsVerifier {
sender: sender,
recv: recv,
address_ty: account_ty,
},
)
}
pub enum CommsMessage {
NewJudgementRequest(OnChainIdentity),
JudgeIdentity {
net_account: NetAccount,
judgement: Judgement,
},
LeaveRoom {
net_account: NetAccount,
},
AccountToVerify {
net_account: NetAccount,
account: Account,
},
NotifyStatusChange {
net_account: NetAccount,
},
MessageAcknowledged,
NotifyInvalidAccount {
net_account: NetAccount,
account: Account,
accounts: Vec<(AccountType, Account, AccountStatus)>,
},
ExistingDisplayNames {
accounts: Vec<(Account, NetAccount)>,
},
JudgementGivenAck {
net_account: NetAccount,
},
// Only used to manually trigger the event handler in tests, since the
// matrix sdk runs the EventEmitter in the background.
#[cfg(test)]
TriggerMatrixEmitter {
room_id: RoomId,
my_user_id: UserId,
event: MatrixEventMock,
},
}
#[derive(Debug, Clone)]
pub struct CommsMain {
sender: Sender<CommsMessage>,
}
impl CommsMain {
pub fn notify_account_verification(&self, net_account: NetAccount, account: Account) {
self.sender
.send(CommsMessage::AccountToVerify {
net_account: net_account,
account: account,
})
.fatal();
}
pub fn notify_identity_judgment(&self, net_account: NetAccount, judgment: Judgement) {
self.sender
.send(CommsMessage::JudgeIdentity {
net_account: net_account,
judgement: judgment,
})
.fatal();
}
pub fn leave_matrix_room(&self, net_account: NetAccount) {
self.sender
.send(CommsMessage::LeaveRoom {
net_account: net_account,
})
.fatal();
}
pub fn notify_invalid_accounts(
&self,
net_account: NetAccount,
account: Account,
accounts: Vec<(AccountType, Account, AccountStatus)>,
) {
self.sender
.send(CommsMessage::NotifyInvalidAccount {
net_account: net_account,
account: account,
accounts: accounts,
})
.fatal()
}
#[cfg(test)]
pub fn trigger_matrix_emitter(
&self,
room_id: RoomId,
my_user_id: UserId,
event: MatrixEventMock,
) {
self.sender
.send(CommsMessage::TriggerMatrixEmitter {
room_id: room_id,
my_user_id: my_user_id,
event: event,
})
.fatal()
}
}
#[derive(Debug, Clone)]
pub struct CommsVerifier {
sender: Sender<CommsMessage>,
recv: Receiver<CommsMessage>,
address_ty: AccountType,
}
impl CommsVerifier {
#[cfg(test)]
/// Create a CommsVerifier without any useful functionality. Only used as a
/// filler for certain tests.
pub fn new() -> Self {
let (tx, recv) = unbounded();
CommsVerifier {
sender: tx,
recv: recv,
address_ty: AccountType::Matrix,
}
}
pub async fn recv(&self) -> CommsMessage {
let mut interval = time::interval(Duration::from_millis(10));
loop {
if let Ok(msg) = self.recv.try_recv() {
return msg;
} else {
interval.tick().await;
}
}
}
pub fn try_recv(&self) -> Option<CommsMessage> {
self.recv.try_recv().ok()
}
pub fn notify_new_identity(&self, ident: OnChainIdentity) {
self.sender
.send(CommsMessage::NewJudgementRequest(ident))
.fatal();
}
pub fn notify_status_change(&self, net_account: NetAccount) {
self.sender
.send(CommsMessage::NotifyStatusChange {
net_account: net_account,
})
.fatal()
}
pub fn notify_ack(&self) {
self.sender.send(CommsMessage::MessageAcknowledged).fatal();
}
pub fn notify_judgement_given_ack(&self, net_account: NetAccount) {
self.sender
.send(CommsMessage::JudgementGivenAck {
net_account: net_account,
})
.fatal()
}
pub fn notify_existing_display_names(&self, accounts: Vec<(Account, NetAccount)>) {
self.sender
.send(CommsMessage::ExistingDisplayNames { accounts: accounts })
.fatal()
}
}
|
use crate::{
buffers::{Buffers, DefaultBuffers},
lexer::{Lexer, Token, TokenType},
words::{Atom, Word, WordsOrComments},
Callbacks, Comment, GCode, Line, Mnemonic, Nop,
};
use core::{iter::Peekable, marker::PhantomData};
/// Parse each [`GCode`] in some text, ignoring any errors that may occur or
/// [`Comment`]s that are found.
///
/// This function is probably what you are looking for if you just want to read
/// the [`GCode`] commands in a program. If more detailed information is needed,
/// have a look at [`full_parse_with_callbacks()`].
pub fn parse<'input>(src: &'input str) -> impl Iterator<Item = GCode> + 'input {
full_parse_with_callbacks(src, Nop).flat_map(|line| line.into_gcodes())
}
/// Parse each [`Line`] in some text, using the provided [`Callbacks`] when a
/// parse error occurs that we can recover from.
///
/// Unlike [`parse()`], this function will also give you access to any comments
/// and line numbers that are found, plus the location of the entire [`Line`]
/// in its source text.
pub fn full_parse_with_callbacks<'input, C: Callbacks + 'input>(
src: &'input str,
callbacks: C,
) -> impl Iterator<Item = Line<'input>> + 'input {
let tokens = Lexer::new(src);
let atoms = WordsOrComments::new(tokens);
Lines::new(atoms, callbacks)
}
/// A parser for parsing g-code programs.
#[derive(Debug)]
pub struct Parser<'input, C, B = DefaultBuffers> {
// Explicitly instantiate Lines so Parser's type parameters don't expose
// internal details
lines: Lines<'input, WordsOrComments<'input, Lexer<'input>>, C, B>,
}
impl<'input, C, B> Parser<'input, C, B> {
/// Create a new [`Parser`] from some source text and a set of
/// [`Callbacks`].
pub fn new(src: &'input str, callbacks: C) -> Self {
let tokens = Lexer::new(src);
let atoms = WordsOrComments::new(tokens);
let lines = Lines::new(atoms, callbacks);
Parser { lines }
}
}
impl<'input, B> From<&'input str> for Parser<'input, Nop, B> {
fn from(src: &'input str) -> Self { Parser::new(src, Nop) }
}
impl<'input, C: Callbacks, B: Buffers<'input>> Iterator
for Parser<'input, C, B>
{
type Item = Line<'input, B>;
fn next(&mut self) -> Option<Self::Item> { self.lines.next() }
}
#[derive(Debug)]
struct Lines<'input, I, C, B>
where
I: Iterator<Item = Atom<'input>>,
{
atoms: Peekable<I>,
callbacks: C,
last_gcode_type: Option<Word>,
_buffers: PhantomData<B>,
}
impl<'input, I, C, B> Lines<'input, I, C, B>
where
I: Iterator<Item = Atom<'input>>,
{
fn new(atoms: I, callbacks: C) -> Self {
Lines {
atoms: atoms.peekable(),
callbacks,
last_gcode_type: None,
_buffers: PhantomData,
}
}
}
impl<'input, I, C, B> Lines<'input, I, C, B>
where
I: Iterator<Item = Atom<'input>>,
C: Callbacks,
B: Buffers<'input>,
{
fn handle_line_number(
&mut self,
word: Word,
line: &mut Line<'input, B>,
has_temp_gcode: bool,
) {
if line.gcodes().is_empty()
&& line.line_number().is_none()
&& !has_temp_gcode
{
line.set_line_number(word);
} else {
self.callbacks.unexpected_line_number(word.value, word.span);
}
}
fn handle_arg(
&mut self,
word: Word,
line: &mut Line<'input, B>,
temp_gcode: &mut Option<GCode<B::Arguments>>,
) {
if let Some(mnemonic) = Mnemonic::for_letter(word.letter) {
// we need to start another gcode. push the one we were building
// onto the line so we can start working on the next one
self.last_gcode_type = Some(word);
if let Some(completed) = temp_gcode.take() {
if let Err(e) = line.push_gcode(completed) {
self.on_gcode_push_error(e.0);
}
}
*temp_gcode = Some(GCode::new_with_argument_buffer(
mnemonic,
word.value,
word.span,
B::Arguments::default(),
));
return;
}
// we've got an argument, try adding it to the gcode we're building
if let Some(temp) = temp_gcode {
if let Err(e) = temp.push_argument(word) {
self.on_arg_push_error(&temp, e.0);
}
return;
}
// we haven't already started building a gcode, maybe the author elided
// the command ("G90") and wants to use the one from the last line?
match self.last_gcode_type {
Some(ty) => {
let mut new_gcode = GCode::new_with_argument_buffer(
Mnemonic::for_letter(ty.letter).unwrap(),
ty.value,
ty.span,
B::Arguments::default(),
);
if let Err(e) = new_gcode.push_argument(word) {
self.on_arg_push_error(&new_gcode, e.0);
}
*temp_gcode = Some(new_gcode);
},
// oh well, you can't say we didn't try...
None => {
self.callbacks.argument_without_a_command(
word.letter,
word.value,
word.span,
);
},
}
}
fn handle_broken_word(&mut self, token: Token<'_>) {
if token.kind == TokenType::Letter {
self.callbacks
.letter_without_a_number(token.value, token.span);
} else {
self.callbacks
.number_without_a_letter(token.value, token.span);
}
}
fn on_arg_push_error(&mut self, gcode: &GCode<B::Arguments>, arg: Word) {
self.callbacks.gcode_argument_buffer_overflowed(
gcode.mnemonic(),
gcode.major_number(),
gcode.minor_number(),
arg,
);
}
fn on_comment_push_error(&mut self, comment: Comment<'_>) {
self.callbacks.comment_buffer_overflow(comment);
}
fn on_gcode_push_error(&mut self, gcode: GCode<B::Arguments>) {
self.callbacks.gcode_buffer_overflowed(
gcode.mnemonic(),
gcode.major_number(),
gcode.minor_number(),
gcode.arguments(),
gcode.span(),
);
}
fn next_line_number(&mut self) -> Option<usize> {
self.atoms.peek().map(|a| a.span().line)
}
}
impl<'input, I, C, B> Iterator for Lines<'input, I, C, B>
where
I: Iterator<Item = Atom<'input>> + 'input,
C: Callbacks,
B: Buffers<'input>,
{
type Item = Line<'input, B>;
fn next(&mut self) -> Option<Self::Item> {
let mut line = Line::default();
// we need a scratch space for the gcode we're in the middle of
// constructing
let mut temp_gcode = None;
while let Some(next_line) = self.next_line_number() {
if !line.is_empty() && next_line != line.span().line {
// we've started the next line
break;
}
match self.atoms.next().expect("unreachable") {
Atom::Unknown(token) => {
self.callbacks.unknown_content(token.value, token.span)
},
Atom::Comment(comment) => {
if let Err(e) = line.push_comment(comment) {
self.on_comment_push_error(e.0);
}
},
// line numbers are annoying, so handle them separately
Atom::Word(word) if word.letter.to_ascii_lowercase() == 'n' => {
self.handle_line_number(
word,
&mut line,
temp_gcode.is_some(),
);
},
Atom::Word(word) => {
self.handle_arg(word, &mut line, &mut temp_gcode)
},
Atom::BrokenWord(token) => self.handle_broken_word(token),
}
}
if let Some(gcode) = temp_gcode.take() {
if let Err(e) = line.push_gcode(gcode) {
self.on_gcode_push_error(e.0);
}
}
if line.is_empty() {
None
} else {
Some(line)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Span;
use arrayvec::ArrayVec;
use std::{prelude::v1::*, sync::Mutex};
#[derive(Debug)]
struct MockCallbacks<'a> {
unexpected_line_number: &'a Mutex<Vec<(f32, Span)>>,
}
impl<'a> Callbacks for MockCallbacks<'a> {
fn unexpected_line_number(&mut self, line_number: f32, span: Span) {
self.unexpected_line_number
.lock()
.unwrap()
.push((line_number, span));
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum BigBuffers {}
impl<'input> Buffers<'input> for BigBuffers {
type Arguments = ArrayVec<[Word; 16]>;
type Commands = ArrayVec<[GCode<Self::Arguments>; 16]>;
type Comments = ArrayVec<[Comment<'input>; 16]>;
}
fn parse(
src: &str,
) -> Lines<'_, impl Iterator<Item = Atom<'_>>, Nop, BigBuffers> {
let tokens = Lexer::new(src);
let atoms = WordsOrComments::new(tokens);
Lines::new(atoms, Nop)
}
#[test]
fn we_can_parse_a_comment() {
let src = "(this is a comment)";
let got: Vec<_> = parse(src).collect();
assert_eq!(got.len(), 1);
let line = &got[0];
assert_eq!(line.comments().len(), 1);
assert_eq!(line.gcodes().len(), 0);
assert_eq!(line.span(), Span::new(0, src.len(), 0));
}
#[test]
fn line_numbers() {
let src = "N42";
let got: Vec<_> = parse(src).collect();
assert_eq!(got.len(), 1);
let line = &got[0];
assert_eq!(line.comments().len(), 0);
assert_eq!(line.gcodes().len(), 0);
let span = Span::new(0, src.len(), 0);
assert_eq!(
line.line_number(),
Some(Word {
letter: 'N',
value: 42.0,
span
})
);
assert_eq!(line.span(), span);
}
#[test]
fn line_numbers_after_the_start_are_an_error() {
let src = "G90 N42";
let unexpected_line_number = Default::default();
let got: Vec<_> = full_parse_with_callbacks(
src,
MockCallbacks {
unexpected_line_number: &unexpected_line_number,
},
)
.collect();
assert_eq!(got.len(), 1);
assert!(got[0].line_number().is_none());
let unexpected_line_number = unexpected_line_number.lock().unwrap();
assert_eq!(unexpected_line_number.len(), 1);
assert_eq!(unexpected_line_number[0].0, 42.0);
}
#[test]
fn parse_g90() {
let src = "G90";
let got: Vec<_> = parse(src).collect();
assert_eq!(got.len(), 1);
let line = &got[0];
assert_eq!(line.gcodes().len(), 1);
let g90 = &line.gcodes()[0];
assert_eq!(g90.major_number(), 90);
assert_eq!(g90.minor_number(), 0);
assert_eq!(g90.arguments().len(), 0);
}
#[test]
fn parse_command_with_arguments() {
let src = "G01X5 Y-20";
let should_be =
GCode::new(Mnemonic::General, 1.0, Span::new(0, src.len(), 0))
.with_argument(Word {
letter: 'X',
value: 5.0,
span: Span::new(3, 5, 0),
})
.with_argument(Word {
letter: 'Y',
value: -20.0,
span: Span::new(6, 10, 0),
});
let got: Vec<_> = parse(src).collect();
assert_eq!(got.len(), 1);
let line = &got[0];
assert_eq!(line.gcodes().len(), 1);
let g01 = &line.gcodes()[0];
assert_eq!(g01, &should_be);
}
#[test]
fn multiple_commands_on_the_same_line() {
let src = "G01 X5 G90 (comment) G91 M10\nG01";
let got: Vec<_> = parse(src).collect();
assert_eq!(got.len(), 2);
assert_eq!(got[0].gcodes().len(), 4);
assert_eq!(got[0].comments().len(), 1);
assert_eq!(got[1].gcodes().len(), 1);
}
/// I wasn't sure if the `#[derive(Serialize)]` would work given we use
/// `B::Comments`, which would borrow from the original source.
#[test]
#[cfg(feature = "serde-1")]
fn you_can_actually_serialize_lines() {
let src = "G01 X5 G90 (comment) G91 M10\nG01\n";
let line = parse(src).next().unwrap();
fn assert_serializable<S: serde::Serialize>(_: &S) {}
fn assert_deserializable<'de, D: serde::Deserialize<'de>>() {}
assert_serializable(&line);
assert_deserializable::<Line<'_>>();
}
/// For some reason we were parsing the G90, then an empty G01 and the
/// actual G01.
#[test]
#[ignore]
fn funny_bug_in_crate_example() {
let src = "G90 \n G01 X50.0 Y-10";
let expected = vec![
GCode::new(Mnemonic::General, 90.0, Span::PLACEHOLDER),
GCode::new(Mnemonic::General, 1.0, Span::PLACEHOLDER)
.with_argument(Word::new('X', 50.0, Span::PLACEHOLDER))
.with_argument(Word::new('Y', -10.0, Span::PLACEHOLDER)),
];
let got: Vec<_> = crate::parse(src).collect();
assert_eq!(got, expected);
}
}
|
//! Quicksilver uses the `View` structure as an abstraction for both graphical and input projection.
//!
//! This means that a view can be thought of like a camera: it
//! determines what coordinates in draw calls appear where on screen, as well as the relationship
//! between the mouse location on the screen and the reported coordinates.
//!
//! Important to understanding `View` is understanding *world* versus *screen* coordinates.
//! *Screen* coordinates map the the window on the user's device. (0, 0) on the screen is the
//! top-left, and screen coordinates span to the pixel width and height of the window. *World*
//! coordinates are defined by the active view. By default, the world is a rectangle with the size
//! of the initial window.
//!
//! Here is a View in action (the camera example):
//! ```no_run
//! // Demonstrate adding a View to the draw-geometry example
//! // The camera can be controlled with the arrow keys
//! extern crate quicksilver;
//!
//! use quicksilver::{
//! Result,
//! geom::{Circle, Line, Rectangle, Shape, Transform, Triangle, Vector},
//! graphics::{Background::Col, Color, View},
//! input::{Key},
//! lifecycle::{Settings, State, Window, run},
//! };
//!
//! struct Camera {
//! view: Rectangle
//! }
//!
//! impl State for Camera {
//! // Initialize the struct
//! fn new() -> Result<Camera> {
//! Ok(Camera {
//! view: Rectangle::new_sized((800, 600))
//! })
//! }
//!
//! fn update(&mut self, window: &mut Window) -> Result<()> {
//! if window.keyboard()[Key::Left].is_down() {
//! self.view = self.view.translate((-4, 0));
//! }
//! if window.keyboard()[Key::Right].is_down() {
//! self.view = self.view.translate((4, 0));
//! }
//! if window.keyboard()[Key::Down].is_down() {
//! self.view = self.view.translate((0, 4));
//! }
//! if window.keyboard()[Key::Up].is_down() {
//! self.view = self.view.translate((0, -4));
//! }
//! window.set_view(View::new(self.view));
//! Ok(())
//! }
//!
//! fn draw(&mut self, window: &mut Window) -> Result<()> {
//! window.clear(Color::WHITE)?;
//! window.draw(&Rectangle::new((100, 100), (32, 32)), Col(Color::BLUE));
//! window.draw_ex(&Rectangle::new((400, 300), (32, 32)), Col(Color::BLUE), Transform::rotate(45), 10);
//! window.draw(&Circle::new((400, 300), 100), Col(Color::GREEN));
//! window.draw_ex(
//! &Line::new((50, 80),(600, 450)).with_thickness(2.0),
//! Col(Color::RED),
//! Transform::IDENTITY,
//! 5
//! );
//! window.draw_ex(
//! &Triangle::new((500, 50), (450, 100), (650, 150)),
//! Col(Color::RED),
//! Transform::rotate(45) * Transform::scale((0.5, 0.5)),
//! 0
//! );
//! Ok(())
//! }
//! }
//!
//! fn main() {
//! run::<Camera>("Camera", Vector::new(800, 600), Settings::default());
//! }
//! ```
|
use crate::{executor, sys};
impl sys::sGaugeDrawData {
/// Get the width of the target instrument texture.
pub fn width(&self) -> usize {
self.winWidth as usize
}
/// Get the height of the target instrument texture.
pub fn height(&self) -> usize {
self.winHeight as usize
}
/// Get the elapsed time since the last frame.
pub fn delta_time(&self) -> std::time::Duration {
std::time::Duration::from_secs_f64(self.dt)
}
}
use crate::sim_connect::{SimConnect, SimConnectRecv};
pub use msfs_derive::{gauge, standalone_module};
/// Used in Gauges to dispatch lifetime events, mouse events, and SimConnect events.
#[derive(Debug)]
pub enum MSFSEvent<'a> {
PostInstall,
PreInitialize,
PostInitialize,
PreUpdate,
PostUpdate,
PreDraw(&'a sys::sGaugeDrawData),
PostDraw(&'a sys::sGaugeDrawData),
PreKill,
Mouse { x: f32, y: f32, flags: u32 },
SimConnect(SimConnectRecv<'a>),
}
/// Gauge
pub struct Gauge {
executor: *mut GaugeExecutor,
rx: futures::channel::mpsc::Receiver<MSFSEvent<'static>>,
}
impl Gauge {
/// Send a request to the Microsoft Flight Simulator server to open up communications with a new client.
pub fn open_simconnect<'a>(
&self,
name: &str,
) -> Result<std::pin::Pin<Box<crate::sim_connect::SimConnect<'a>>>, Box<dyn std::error::Error>>
{
let executor = self.executor;
let sim = crate::sim_connect::SimConnect::open(name, move |_sim, recv| {
let executor = unsafe { &mut *executor };
let recv =
unsafe { std::mem::transmute::<SimConnectRecv<'_>, SimConnectRecv<'static>>(recv) };
executor
.executor
.send(Some(MSFSEvent::SimConnect(recv)))
.unwrap();
})?;
Ok(sim)
}
/// Create a NanoVG rendering context. See `Context` for more details.
#[cfg(any(target_arch = "wasm32", doc))]
pub fn create_nanovg(&self) -> Option<crate::nvg::Context> {
crate::nvg::Context::create(unsafe { (*self.executor).fs_ctx.unwrap() })
}
/// Consume the next event from MSFS.
pub fn next_event(&mut self) -> impl futures::Future<Output = Option<MSFSEvent<'_>>> + '_ {
use futures::stream::StreamExt;
async move { self.rx.next().await }
}
}
#[doc(hidden)]
pub struct GaugeExecutor {
pub fs_ctx: Option<sys::FsContext>,
pub executor: executor::Executor<Gauge, MSFSEvent<'static>>,
}
#[doc(hidden)]
impl GaugeExecutor {
pub fn handle_gauge(
&mut self,
ctx: sys::FsContext,
service_id: std::os::raw::c_int,
p_data: *mut std::ffi::c_void,
) -> bool {
match service_id as u32 {
sys::PANEL_SERVICE_PRE_INSTALL => {
let executor = self as *mut GaugeExecutor;
self.fs_ctx = Some(ctx);
self.executor
.start(Box::new(move |rx| Gauge { executor, rx }))
.is_ok()
}
sys::PANEL_SERVICE_POST_KILL => self.executor.send(None).is_ok(),
service_id => {
if let Some(data) = match service_id {
sys::PANEL_SERVICE_POST_INSTALL => Some(MSFSEvent::PostInstall),
sys::PANEL_SERVICE_PRE_INITIALIZE => Some(MSFSEvent::PreInitialize),
sys::PANEL_SERVICE_POST_INITIALIZE => Some(MSFSEvent::PostInitialize),
sys::PANEL_SERVICE_PRE_UPDATE => Some(MSFSEvent::PreUpdate),
sys::PANEL_SERVICE_POST_UPDATE => Some(MSFSEvent::PostUpdate),
sys::PANEL_SERVICE_PRE_DRAW => Some(MSFSEvent::PreDraw(unsafe {
&*(p_data as *const sys::sGaugeDrawData)
})),
sys::PANEL_SERVICE_POST_DRAW => Some(MSFSEvent::PostDraw(unsafe {
&*(p_data as *const sys::sGaugeDrawData)
})),
sys::PANEL_SERVICE_PRE_KILL => Some(MSFSEvent::PreKill),
_ => None,
} {
self.executor.send(Some(data)).is_ok()
} else {
true
}
}
}
}
pub fn handle_mouse(&mut self, x: f32, y: f32, flags: u32) {
self.executor
.send(Some(MSFSEvent::Mouse { x, y, flags }))
.unwrap();
}
}
pub struct StandaloneModule {
executor: *mut StandaloneModuleExecutor,
rx: futures::channel::mpsc::Receiver<SimConnectRecv<'static>>,
}
impl StandaloneModule {
/// Send a request to the Microsoft Flight Simulator server to open up communications with a new client.
pub fn open_simconnect<'a>(
&self,
name: &str,
) -> Result<std::pin::Pin<Box<SimConnect<'a>>>, Box<dyn std::error::Error>> {
let executor = self.executor;
let sim = SimConnect::open(name, move |_sim, recv| {
let executor = unsafe { &mut *executor };
let recv =
unsafe { std::mem::transmute::<SimConnectRecv<'_>, SimConnectRecv<'static>>(recv) };
executor.executor.send(Some(recv)).unwrap();
})?;
Ok(sim)
}
/// Consume the next event from MSFS.
pub fn next_event(&mut self) -> impl futures::Future<Output = Option<SimConnectRecv<'_>>> + '_ {
use futures::stream::StreamExt;
async move { self.rx.next().await }
}
}
#[doc(hidden)]
pub struct StandaloneModuleExecutor {
pub executor: executor::Executor<StandaloneModule, SimConnectRecv<'static>>,
}
#[doc(hidden)]
impl StandaloneModuleExecutor {
fn start(&mut self) -> Result<(), Box<dyn std::error::Error>> {
let executor = self as *mut StandaloneModuleExecutor;
self.executor
.start(Box::new(move |rx| StandaloneModule { executor, rx }))
}
pub fn handle_init(&mut self) {
self.start().unwrap();
}
fn end(&mut self) -> Result<(), Box<dyn std::error::Error>> {
self.executor.send(None)
}
pub fn handle_deinit(&mut self) {
self.end().unwrap();
}
}
|
pub trait MonteCarloStatsCollector {
fn accumulate_result(&mut self, result: f64);
fn running_stats(&self) -> Vec<Vec<f64>>;
}
pub struct MonteCarloMeanCollector {
running_sum: f64,
paths_done: usize
}
impl MonteCarloMeanCollector {
pub fn new() -> MonteCarloMeanCollector {
MonteCarloMeanCollector { running_sum: 0.0, paths_done: 0 }
}
}
impl MonteCarloStatsCollector for MonteCarloMeanCollector {
fn accumulate_result(&mut self, result: f64) {
self.running_sum += result;
self.paths_done += 1;
}
fn running_stats(&self) -> Vec<Vec<f64>> {
let mut results = vec![vec![0.0; 1]; 1];
results[0][0] = self.running_sum / self.paths_done as f64;
results
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mean_collector() {
let mut mc_mean = MonteCarloMeanCollector::new();
mc_mean.accumulate_result(2.0);
mc_mean.accumulate_result(2.0);
mc_mean.accumulate_result(2.0);
let stats = mc_mean.running_stats();
assert_eq!(stats[0][0], 2.0);
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - DMA interrupt status register"]
pub bdma_isr: BDMA_ISR,
#[doc = "0x04 - DMA interrupt flag clear register"]
pub bdma_ifcr: BDMA_IFCR,
#[doc = "0x08 - DMA channel x configuration register"]
pub bdma_ccr0: BDMA_CCR0,
#[doc = "0x0c - DMA channel x number of data register"]
pub bdma_cndtr0: BDMA_CNDTR0,
#[doc = "0x10 - This register must not be written when the channel is enabled."]
pub bdma_cpar0: BDMA_CPAR0,
#[doc = "0x14 - This register must not be written when the channel is enabled."]
pub bdma_cm0ar0: BDMA_CM0AR0,
#[doc = "0x18 - This register must not be written when the channel is enabled"]
pub bdma_cm1ar0: BDMA_CM1AR0,
#[doc = "0x1c - DMA channel x configuration register"]
pub bdma_ccr1: BDMA_CCR1,
#[doc = "0x20 - DMA channel x number of data register"]
pub bdma_cndtr1: BDMA_CNDTR1,
#[doc = "0x24 - This register must not be written when the channel is enabled."]
pub bdma_cpar1: BDMA_CPAR1,
#[doc = "0x28 - This register must not be written when the channel is enabled."]
pub bdma_cm0ar1: BDMA_CM0AR1,
#[doc = "0x2c - BDMA_CMAR1"]
pub bdma_cm1ar1: BDMA_CM1AR1,
#[doc = "0x30 - DMA channel x configuration register"]
pub bdma_ccr2: BDMA_CCR2,
#[doc = "0x34 - DMA channel x number of data register"]
pub bdma_cndtr2: BDMA_CNDTR2,
#[doc = "0x38 - This register must not be written when the channel is enabled."]
pub bdma_cpar2: BDMA_CPAR2,
#[doc = "0x3c - This register must not be written when the channel is enabled."]
pub bdma_cm0ar2: BDMA_CM0AR2,
#[doc = "0x40 - BDMA_CM1AR2"]
pub bdma_cm1ar2: BDMA_CM1AR2,
#[doc = "0x44 - DMA channel x configuration register"]
pub bdma_ccr3: BDMA_CCR3,
#[doc = "0x48 - DMA channel x number of data register"]
pub bdma_cndtr3: BDMA_CNDTR3,
#[doc = "0x4c - This register must not be written when the channel is enabled."]
pub bdma_cpar3: BDMA_CPAR3,
#[doc = "0x50 - This register must not be written when the channel is enabled."]
pub bdma_cm0ar3: BDMA_CM0AR3,
#[doc = "0x54 - BDMA_CMAR3"]
pub bdma_cm1ar3: BDMA_CM1AR3,
#[doc = "0x58 - DMA channel x configuration register"]
pub bdma_ccr4: BDMA_CCR4,
#[doc = "0x5c - DMA channel x number of data register"]
pub bdma_cndtr4: BDMA_CNDTR4,
#[doc = "0x60 - This register must not be written when the channel is enabled."]
pub bdma_cpar4: BDMA_CPAR4,
#[doc = "0x64 - This register must not be written when the channel is enabled."]
pub bdma_cm0ar4: BDMA_CM0AR4,
#[doc = "0x68 - BDMA_CM1AR4"]
pub bdma_cm1ar4: BDMA_CM1AR4,
#[doc = "0x6c - DMA channel x configuration register"]
pub bdma_ccr5: BDMA_CCR5,
#[doc = "0x70 - DMA channel x number of data register"]
pub bdma_cndtr5: BDMA_CNDTR5,
#[doc = "0x74 - This register must not be written when the channel is enabled."]
pub bdma_cpar5: BDMA_CPAR5,
#[doc = "0x78 - This register must not be written when the channel is enabled."]
pub bdma_cm0ar5: BDMA_CM0AR5,
#[doc = "0x7c - This register must not be written when the channel is enabled."]
pub bdma_cm1ar5: BDMA_CM1AR5,
#[doc = "0x80 - DMA channel x configuration register"]
pub bdma_ccr6: BDMA_CCR6,
#[doc = "0x84 - DMA channel x number of data register"]
pub bdma_cndtr6: BDMA_CNDTR6,
#[doc = "0x88 - This register must not be written when the channel is enabled."]
pub bdma_cpar6: BDMA_CPAR6,
#[doc = "0x8c - This register must not be written when the channel is enabled."]
pub bdma_cm0ar6: BDMA_CM0AR6,
#[doc = "0x90 - This register must not be written when the channel is enabled."]
pub bdma_cm1ar6: BDMA_CM1AR6,
#[doc = "0x94 - DMA channel x configuration register"]
pub bdma_ccr7: BDMA_CCR7,
#[doc = "0x98 - DMA channel x number of data register"]
pub bdma_cndtr7: BDMA_CNDTR7,
#[doc = "0x9c - This register must not be written when the channel is enabled."]
pub bdma_cpar7: BDMA_CPAR7,
#[doc = "0xa0 - This register must not be written when the channel is enabled."]
pub bdma_cm0ar7: BDMA_CM0AR7,
#[doc = "0xa4 - This register must not be written when the channel is enabled."]
pub bdma_cm1ar7: BDMA_CM1AR7,
}
#[doc = "DMA interrupt status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_isr](bdma_isr) module"]
pub type BDMA_ISR = crate::Reg<u32, _BDMA_ISR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_ISR;
#[doc = "`read()` method returns [bdma_isr::R](bdma_isr::R) reader structure"]
impl crate::Readable for BDMA_ISR {}
#[doc = "DMA interrupt status register"]
pub mod bdma_isr;
#[doc = "DMA interrupt flag clear register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_ifcr](bdma_ifcr) module"]
pub type BDMA_IFCR = crate::Reg<u32, _BDMA_IFCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_IFCR;
#[doc = "`write(|w| ..)` method takes [bdma_ifcr::W](bdma_ifcr::W) writer structure"]
impl crate::Writable for BDMA_IFCR {}
#[doc = "DMA interrupt flag clear register"]
pub mod bdma_ifcr;
#[doc = "DMA channel x configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_ccr0](bdma_ccr0) module"]
pub type BDMA_CCR0 = crate::Reg<u32, _BDMA_CCR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CCR0;
#[doc = "`read()` method returns [bdma_ccr0::R](bdma_ccr0::R) reader structure"]
impl crate::Readable for BDMA_CCR0 {}
#[doc = "`write(|w| ..)` method takes [bdma_ccr0::W](bdma_ccr0::W) writer structure"]
impl crate::Writable for BDMA_CCR0 {}
#[doc = "DMA channel x configuration register"]
pub mod bdma_ccr0;
#[doc = "DMA channel x number of data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cndtr0](bdma_cndtr0) module"]
pub type BDMA_CNDTR0 = crate::Reg<u32, _BDMA_CNDTR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CNDTR0;
#[doc = "`read()` method returns [bdma_cndtr0::R](bdma_cndtr0::R) reader structure"]
impl crate::Readable for BDMA_CNDTR0 {}
#[doc = "`write(|w| ..)` method takes [bdma_cndtr0::W](bdma_cndtr0::W) writer structure"]
impl crate::Writable for BDMA_CNDTR0 {}
#[doc = "DMA channel x number of data register"]
pub mod bdma_cndtr0;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cpar0](bdma_cpar0) module"]
pub type BDMA_CPAR0 = crate::Reg<u32, _BDMA_CPAR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CPAR0;
#[doc = "`read()` method returns [bdma_cpar0::R](bdma_cpar0::R) reader structure"]
impl crate::Readable for BDMA_CPAR0 {}
#[doc = "`write(|w| ..)` method takes [bdma_cpar0::W](bdma_cpar0::W) writer structure"]
impl crate::Writable for BDMA_CPAR0 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cpar0;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm0ar0](bdma_cm0ar0) module"]
pub type BDMA_CM0AR0 = crate::Reg<u32, _BDMA_CM0AR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM0AR0;
#[doc = "`read()` method returns [bdma_cm0ar0::R](bdma_cm0ar0::R) reader structure"]
impl crate::Readable for BDMA_CM0AR0 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm0ar0::W](bdma_cm0ar0::W) writer structure"]
impl crate::Writable for BDMA_CM0AR0 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cm0ar0;
#[doc = "DMA channel x configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_ccr1](bdma_ccr1) module"]
pub type BDMA_CCR1 = crate::Reg<u32, _BDMA_CCR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CCR1;
#[doc = "`read()` method returns [bdma_ccr1::R](bdma_ccr1::R) reader structure"]
impl crate::Readable for BDMA_CCR1 {}
#[doc = "`write(|w| ..)` method takes [bdma_ccr1::W](bdma_ccr1::W) writer structure"]
impl crate::Writable for BDMA_CCR1 {}
#[doc = "DMA channel x configuration register"]
pub mod bdma_ccr1;
#[doc = "DMA channel x number of data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cndtr1](bdma_cndtr1) module"]
pub type BDMA_CNDTR1 = crate::Reg<u32, _BDMA_CNDTR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CNDTR1;
#[doc = "`read()` method returns [bdma_cndtr1::R](bdma_cndtr1::R) reader structure"]
impl crate::Readable for BDMA_CNDTR1 {}
#[doc = "`write(|w| ..)` method takes [bdma_cndtr1::W](bdma_cndtr1::W) writer structure"]
impl crate::Writable for BDMA_CNDTR1 {}
#[doc = "DMA channel x number of data register"]
pub mod bdma_cndtr1;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cpar1](bdma_cpar1) module"]
pub type BDMA_CPAR1 = crate::Reg<u32, _BDMA_CPAR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CPAR1;
#[doc = "`read()` method returns [bdma_cpar1::R](bdma_cpar1::R) reader structure"]
impl crate::Readable for BDMA_CPAR1 {}
#[doc = "`write(|w| ..)` method takes [bdma_cpar1::W](bdma_cpar1::W) writer structure"]
impl crate::Writable for BDMA_CPAR1 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cpar1;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm0ar1](bdma_cm0ar1) module"]
pub type BDMA_CM0AR1 = crate::Reg<u32, _BDMA_CM0AR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM0AR1;
#[doc = "`read()` method returns [bdma_cm0ar1::R](bdma_cm0ar1::R) reader structure"]
impl crate::Readable for BDMA_CM0AR1 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm0ar1::W](bdma_cm0ar1::W) writer structure"]
impl crate::Writable for BDMA_CM0AR1 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cm0ar1;
#[doc = "DMA channel x configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_ccr2](bdma_ccr2) module"]
pub type BDMA_CCR2 = crate::Reg<u32, _BDMA_CCR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CCR2;
#[doc = "`read()` method returns [bdma_ccr2::R](bdma_ccr2::R) reader structure"]
impl crate::Readable for BDMA_CCR2 {}
#[doc = "`write(|w| ..)` method takes [bdma_ccr2::W](bdma_ccr2::W) writer structure"]
impl crate::Writable for BDMA_CCR2 {}
#[doc = "DMA channel x configuration register"]
pub mod bdma_ccr2;
#[doc = "DMA channel x number of data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cndtr2](bdma_cndtr2) module"]
pub type BDMA_CNDTR2 = crate::Reg<u32, _BDMA_CNDTR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CNDTR2;
#[doc = "`read()` method returns [bdma_cndtr2::R](bdma_cndtr2::R) reader structure"]
impl crate::Readable for BDMA_CNDTR2 {}
#[doc = "`write(|w| ..)` method takes [bdma_cndtr2::W](bdma_cndtr2::W) writer structure"]
impl crate::Writable for BDMA_CNDTR2 {}
#[doc = "DMA channel x number of data register"]
pub mod bdma_cndtr2;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cpar2](bdma_cpar2) module"]
pub type BDMA_CPAR2 = crate::Reg<u32, _BDMA_CPAR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CPAR2;
#[doc = "`read()` method returns [bdma_cpar2::R](bdma_cpar2::R) reader structure"]
impl crate::Readable for BDMA_CPAR2 {}
#[doc = "`write(|w| ..)` method takes [bdma_cpar2::W](bdma_cpar2::W) writer structure"]
impl crate::Writable for BDMA_CPAR2 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cpar2;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm0ar2](bdma_cm0ar2) module"]
pub type BDMA_CM0AR2 = crate::Reg<u32, _BDMA_CM0AR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM0AR2;
#[doc = "`read()` method returns [bdma_cm0ar2::R](bdma_cm0ar2::R) reader structure"]
impl crate::Readable for BDMA_CM0AR2 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm0ar2::W](bdma_cm0ar2::W) writer structure"]
impl crate::Writable for BDMA_CM0AR2 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cm0ar2;
#[doc = "DMA channel x configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_ccr3](bdma_ccr3) module"]
pub type BDMA_CCR3 = crate::Reg<u32, _BDMA_CCR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CCR3;
#[doc = "`read()` method returns [bdma_ccr3::R](bdma_ccr3::R) reader structure"]
impl crate::Readable for BDMA_CCR3 {}
#[doc = "`write(|w| ..)` method takes [bdma_ccr3::W](bdma_ccr3::W) writer structure"]
impl crate::Writable for BDMA_CCR3 {}
#[doc = "DMA channel x configuration register"]
pub mod bdma_ccr3;
#[doc = "DMA channel x number of data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cndtr3](bdma_cndtr3) module"]
pub type BDMA_CNDTR3 = crate::Reg<u32, _BDMA_CNDTR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CNDTR3;
#[doc = "`read()` method returns [bdma_cndtr3::R](bdma_cndtr3::R) reader structure"]
impl crate::Readable for BDMA_CNDTR3 {}
#[doc = "`write(|w| ..)` method takes [bdma_cndtr3::W](bdma_cndtr3::W) writer structure"]
impl crate::Writable for BDMA_CNDTR3 {}
#[doc = "DMA channel x number of data register"]
pub mod bdma_cndtr3;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cpar3](bdma_cpar3) module"]
pub type BDMA_CPAR3 = crate::Reg<u32, _BDMA_CPAR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CPAR3;
#[doc = "`read()` method returns [bdma_cpar3::R](bdma_cpar3::R) reader structure"]
impl crate::Readable for BDMA_CPAR3 {}
#[doc = "`write(|w| ..)` method takes [bdma_cpar3::W](bdma_cpar3::W) writer structure"]
impl crate::Writable for BDMA_CPAR3 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cpar3;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm0ar3](bdma_cm0ar3) module"]
pub type BDMA_CM0AR3 = crate::Reg<u32, _BDMA_CM0AR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM0AR3;
#[doc = "`read()` method returns [bdma_cm0ar3::R](bdma_cm0ar3::R) reader structure"]
impl crate::Readable for BDMA_CM0AR3 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm0ar3::W](bdma_cm0ar3::W) writer structure"]
impl crate::Writable for BDMA_CM0AR3 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cm0ar3;
#[doc = "DMA channel x configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_ccr4](bdma_ccr4) module"]
pub type BDMA_CCR4 = crate::Reg<u32, _BDMA_CCR4>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CCR4;
#[doc = "`read()` method returns [bdma_ccr4::R](bdma_ccr4::R) reader structure"]
impl crate::Readable for BDMA_CCR4 {}
#[doc = "`write(|w| ..)` method takes [bdma_ccr4::W](bdma_ccr4::W) writer structure"]
impl crate::Writable for BDMA_CCR4 {}
#[doc = "DMA channel x configuration register"]
pub mod bdma_ccr4;
#[doc = "DMA channel x number of data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cndtr4](bdma_cndtr4) module"]
pub type BDMA_CNDTR4 = crate::Reg<u32, _BDMA_CNDTR4>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CNDTR4;
#[doc = "`read()` method returns [bdma_cndtr4::R](bdma_cndtr4::R) reader structure"]
impl crate::Readable for BDMA_CNDTR4 {}
#[doc = "`write(|w| ..)` method takes [bdma_cndtr4::W](bdma_cndtr4::W) writer structure"]
impl crate::Writable for BDMA_CNDTR4 {}
#[doc = "DMA channel x number of data register"]
pub mod bdma_cndtr4;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cpar4](bdma_cpar4) module"]
pub type BDMA_CPAR4 = crate::Reg<u32, _BDMA_CPAR4>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CPAR4;
#[doc = "`read()` method returns [bdma_cpar4::R](bdma_cpar4::R) reader structure"]
impl crate::Readable for BDMA_CPAR4 {}
#[doc = "`write(|w| ..)` method takes [bdma_cpar4::W](bdma_cpar4::W) writer structure"]
impl crate::Writable for BDMA_CPAR4 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cpar4;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm0ar4](bdma_cm0ar4) module"]
pub type BDMA_CM0AR4 = crate::Reg<u32, _BDMA_CM0AR4>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM0AR4;
#[doc = "`read()` method returns [bdma_cm0ar4::R](bdma_cm0ar4::R) reader structure"]
impl crate::Readable for BDMA_CM0AR4 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm0ar4::W](bdma_cm0ar4::W) writer structure"]
impl crate::Writable for BDMA_CM0AR4 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cm0ar4;
#[doc = "DMA channel x configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_ccr5](bdma_ccr5) module"]
pub type BDMA_CCR5 = crate::Reg<u32, _BDMA_CCR5>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CCR5;
#[doc = "`read()` method returns [bdma_ccr5::R](bdma_ccr5::R) reader structure"]
impl crate::Readable for BDMA_CCR5 {}
#[doc = "`write(|w| ..)` method takes [bdma_ccr5::W](bdma_ccr5::W) writer structure"]
impl crate::Writable for BDMA_CCR5 {}
#[doc = "DMA channel x configuration register"]
pub mod bdma_ccr5;
#[doc = "DMA channel x number of data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cndtr5](bdma_cndtr5) module"]
pub type BDMA_CNDTR5 = crate::Reg<u32, _BDMA_CNDTR5>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CNDTR5;
#[doc = "`read()` method returns [bdma_cndtr5::R](bdma_cndtr5::R) reader structure"]
impl crate::Readable for BDMA_CNDTR5 {}
#[doc = "`write(|w| ..)` method takes [bdma_cndtr5::W](bdma_cndtr5::W) writer structure"]
impl crate::Writable for BDMA_CNDTR5 {}
#[doc = "DMA channel x number of data register"]
pub mod bdma_cndtr5;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cpar5](bdma_cpar5) module"]
pub type BDMA_CPAR5 = crate::Reg<u32, _BDMA_CPAR5>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CPAR5;
#[doc = "`read()` method returns [bdma_cpar5::R](bdma_cpar5::R) reader structure"]
impl crate::Readable for BDMA_CPAR5 {}
#[doc = "`write(|w| ..)` method takes [bdma_cpar5::W](bdma_cpar5::W) writer structure"]
impl crate::Writable for BDMA_CPAR5 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cpar5;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm0ar5](bdma_cm0ar5) module"]
pub type BDMA_CM0AR5 = crate::Reg<u32, _BDMA_CM0AR5>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM0AR5;
#[doc = "`read()` method returns [bdma_cm0ar5::R](bdma_cm0ar5::R) reader structure"]
impl crate::Readable for BDMA_CM0AR5 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm0ar5::W](bdma_cm0ar5::W) writer structure"]
impl crate::Writable for BDMA_CM0AR5 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cm0ar5;
#[doc = "DMA channel x configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_ccr6](bdma_ccr6) module"]
pub type BDMA_CCR6 = crate::Reg<u32, _BDMA_CCR6>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CCR6;
#[doc = "`read()` method returns [bdma_ccr6::R](bdma_ccr6::R) reader structure"]
impl crate::Readable for BDMA_CCR6 {}
#[doc = "`write(|w| ..)` method takes [bdma_ccr6::W](bdma_ccr6::W) writer structure"]
impl crate::Writable for BDMA_CCR6 {}
#[doc = "DMA channel x configuration register"]
pub mod bdma_ccr6;
#[doc = "DMA channel x number of data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cndtr6](bdma_cndtr6) module"]
pub type BDMA_CNDTR6 = crate::Reg<u32, _BDMA_CNDTR6>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CNDTR6;
#[doc = "`read()` method returns [bdma_cndtr6::R](bdma_cndtr6::R) reader structure"]
impl crate::Readable for BDMA_CNDTR6 {}
#[doc = "`write(|w| ..)` method takes [bdma_cndtr6::W](bdma_cndtr6::W) writer structure"]
impl crate::Writable for BDMA_CNDTR6 {}
#[doc = "DMA channel x number of data register"]
pub mod bdma_cndtr6;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cpar6](bdma_cpar6) module"]
pub type BDMA_CPAR6 = crate::Reg<u32, _BDMA_CPAR6>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CPAR6;
#[doc = "`read()` method returns [bdma_cpar6::R](bdma_cpar6::R) reader structure"]
impl crate::Readable for BDMA_CPAR6 {}
#[doc = "`write(|w| ..)` method takes [bdma_cpar6::W](bdma_cpar6::W) writer structure"]
impl crate::Writable for BDMA_CPAR6 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cpar6;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm0ar6](bdma_cm0ar6) module"]
pub type BDMA_CM0AR6 = crate::Reg<u32, _BDMA_CM0AR6>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM0AR6;
#[doc = "`read()` method returns [bdma_cm0ar6::R](bdma_cm0ar6::R) reader structure"]
impl crate::Readable for BDMA_CM0AR6 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm0ar6::W](bdma_cm0ar6::W) writer structure"]
impl crate::Writable for BDMA_CM0AR6 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cm0ar6;
#[doc = "DMA channel x configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_ccr7](bdma_ccr7) module"]
pub type BDMA_CCR7 = crate::Reg<u32, _BDMA_CCR7>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CCR7;
#[doc = "`read()` method returns [bdma_ccr7::R](bdma_ccr7::R) reader structure"]
impl crate::Readable for BDMA_CCR7 {}
#[doc = "`write(|w| ..)` method takes [bdma_ccr7::W](bdma_ccr7::W) writer structure"]
impl crate::Writable for BDMA_CCR7 {}
#[doc = "DMA channel x configuration register"]
pub mod bdma_ccr7;
#[doc = "DMA channel x number of data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cndtr7](bdma_cndtr7) module"]
pub type BDMA_CNDTR7 = crate::Reg<u32, _BDMA_CNDTR7>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CNDTR7;
#[doc = "`read()` method returns [bdma_cndtr7::R](bdma_cndtr7::R) reader structure"]
impl crate::Readable for BDMA_CNDTR7 {}
#[doc = "`write(|w| ..)` method takes [bdma_cndtr7::W](bdma_cndtr7::W) writer structure"]
impl crate::Writable for BDMA_CNDTR7 {}
#[doc = "DMA channel x number of data register"]
pub mod bdma_cndtr7;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cpar7](bdma_cpar7) module"]
pub type BDMA_CPAR7 = crate::Reg<u32, _BDMA_CPAR7>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CPAR7;
#[doc = "`read()` method returns [bdma_cpar7::R](bdma_cpar7::R) reader structure"]
impl crate::Readable for BDMA_CPAR7 {}
#[doc = "`write(|w| ..)` method takes [bdma_cpar7::W](bdma_cpar7::W) writer structure"]
impl crate::Writable for BDMA_CPAR7 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cpar7;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm0ar7](bdma_cm0ar7) module"]
pub type BDMA_CM0AR7 = crate::Reg<u32, _BDMA_CM0AR7>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM0AR7;
#[doc = "`read()` method returns [bdma_cm0ar7::R](bdma_cm0ar7::R) reader structure"]
impl crate::Readable for BDMA_CM0AR7 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm0ar7::W](bdma_cm0ar7::W) writer structure"]
impl crate::Writable for BDMA_CM0AR7 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cm0ar7;
#[doc = "This register must not be written when the channel is enabled\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm1ar0](bdma_cm1ar0) module"]
pub type BDMA_CM1AR0 = crate::Reg<u32, _BDMA_CM1AR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM1AR0;
#[doc = "`read()` method returns [bdma_cm1ar0::R](bdma_cm1ar0::R) reader structure"]
impl crate::Readable for BDMA_CM1AR0 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm1ar0::W](bdma_cm1ar0::W) writer structure"]
impl crate::Writable for BDMA_CM1AR0 {}
#[doc = "This register must not be written when the channel is enabled"]
pub mod bdma_cm1ar0;
#[doc = "BDMA_CMAR1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm1ar1](bdma_cm1ar1) module"]
pub type BDMA_CM1AR1 = crate::Reg<u32, _BDMA_CM1AR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM1AR1;
#[doc = "`read()` method returns [bdma_cm1ar1::R](bdma_cm1ar1::R) reader structure"]
impl crate::Readable for BDMA_CM1AR1 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm1ar1::W](bdma_cm1ar1::W) writer structure"]
impl crate::Writable for BDMA_CM1AR1 {}
#[doc = "BDMA_CMAR1"]
pub mod bdma_cm1ar1;
#[doc = "BDMA_CM1AR2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm1ar2](bdma_cm1ar2) module"]
pub type BDMA_CM1AR2 = crate::Reg<u32, _BDMA_CM1AR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM1AR2;
#[doc = "`read()` method returns [bdma_cm1ar2::R](bdma_cm1ar2::R) reader structure"]
impl crate::Readable for BDMA_CM1AR2 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm1ar2::W](bdma_cm1ar2::W) writer structure"]
impl crate::Writable for BDMA_CM1AR2 {}
#[doc = "BDMA_CM1AR2"]
pub mod bdma_cm1ar2;
#[doc = "BDMA_CMAR3\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm1ar3](bdma_cm1ar3) module"]
pub type BDMA_CM1AR3 = crate::Reg<u32, _BDMA_CM1AR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM1AR3;
#[doc = "`read()` method returns [bdma_cm1ar3::R](bdma_cm1ar3::R) reader structure"]
impl crate::Readable for BDMA_CM1AR3 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm1ar3::W](bdma_cm1ar3::W) writer structure"]
impl crate::Writable for BDMA_CM1AR3 {}
#[doc = "BDMA_CMAR3"]
pub mod bdma_cm1ar3;
#[doc = "BDMA_CM1AR4\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm1ar4](bdma_cm1ar4) module"]
pub type BDMA_CM1AR4 = crate::Reg<u32, _BDMA_CM1AR4>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM1AR4;
#[doc = "`read()` method returns [bdma_cm1ar4::R](bdma_cm1ar4::R) reader structure"]
impl crate::Readable for BDMA_CM1AR4 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm1ar4::W](bdma_cm1ar4::W) writer structure"]
impl crate::Writable for BDMA_CM1AR4 {}
#[doc = "BDMA_CM1AR4"]
pub mod bdma_cm1ar4;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm1ar5](bdma_cm1ar5) module"]
pub type BDMA_CM1AR5 = crate::Reg<u32, _BDMA_CM1AR5>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM1AR5;
#[doc = "`read()` method returns [bdma_cm1ar5::R](bdma_cm1ar5::R) reader structure"]
impl crate::Readable for BDMA_CM1AR5 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm1ar5::W](bdma_cm1ar5::W) writer structure"]
impl crate::Writable for BDMA_CM1AR5 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cm1ar5;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm1ar6](bdma_cm1ar6) module"]
pub type BDMA_CM1AR6 = crate::Reg<u32, _BDMA_CM1AR6>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM1AR6;
#[doc = "`read()` method returns [bdma_cm1ar6::R](bdma_cm1ar6::R) reader structure"]
impl crate::Readable for BDMA_CM1AR6 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm1ar6::W](bdma_cm1ar6::W) writer structure"]
impl crate::Writable for BDMA_CM1AR6 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cm1ar6;
#[doc = "This register must not be written when the channel is enabled.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bdma_cm1ar7](bdma_cm1ar7) module"]
pub type BDMA_CM1AR7 = crate::Reg<u32, _BDMA_CM1AR7>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BDMA_CM1AR7;
#[doc = "`read()` method returns [bdma_cm1ar7::R](bdma_cm1ar7::R) reader structure"]
impl crate::Readable for BDMA_CM1AR7 {}
#[doc = "`write(|w| ..)` method takes [bdma_cm1ar7::W](bdma_cm1ar7::W) writer structure"]
impl crate::Writable for BDMA_CM1AR7 {}
#[doc = "This register must not be written when the channel is enabled."]
pub mod bdma_cm1ar7;
|
#[derive(Debug, Clone)]
pub struct InputSeed {
pub is_favored:bool,
pub was_fuzzed:bool,
pub seed_vec:Vec<u8>,
}
impl InputSeed {
// pub fn emptyNew()-> InputSeed {
// InputSeed {
// is_favored:true,
// was_fuzzed:false,
// seed_vec:Vec::new(),
// }
// }
// pub fn new(is_favored:bool, was_fuzzed:bool, seed_vec:Vec<u8>)-> InputSeed {
// InputSeed {
// is_favored:is_favored,
// was_fuzzed:was_fuzzed,
// seed_vec:seed_vec,
// }
// }
pub fn new(seed_vec:Vec<u8>)-> InputSeed {
InputSeed {
is_favored:true,
was_fuzzed:false,
seed_vec:seed_vec,
}
}
// pub fn set_seed_vec(&mut self, seed_vec:Vec<u8>) {
// self.seed_vec = seed_vec;
// }
pub fn get_seed_vec(&self)->Vec<u8> {
self.seed_vec.clone()
}
} |
use crate::cpu::Cpu;
use crate::trap::Exception;
pub fn execute(_cpu: &mut Cpu, _inst: u64) -> Result<(), Exception> {
/*
let opcode = inst & 0x7f;
let rd = ((inst >> 7) & 0x1f) as usize;
let rs1 = ((inst >> 15) & 0x1f) as usize;
let rs2 = ((inst >> 20) & 0x1f) as usize;
let funct3 = (inst >> 12) & 0x7;
let funct7 = (inst >> 25) & 0x7f;
if opcode == 0x03 {
// imm[11:0] = inst[31:20]
let imm = ((inst as i32 as i64) >> 20) as u64;
let addr = cpu.regs[rs1].wrapping_add(imm);
match funct3 {
0x0 => {
// lb
let val = cpu.load(addr, 8)?;
cpu.regs[rd] = val as i8 as i64 as u64;
}
0x1 => {
// lh
let val = cpu.load(addr, 16)?;
cpu.regs[rd] = val as i16 as i64 as u64;
}
0x2 => {
// lw
let val = cpu.load(addr, 32)?;
cpu.regs[rd] = val as i32 as i64 as u64;
}
0x3 => {
// ld
let val = cpu.load(addr, 64)?;
cpu.regs[rd] = val;
}
0x4 => {
// lbu
let val = cpu.load(addr, 8)?;
cpu.regs[rd] = val;
}
0x5 => {
// lhu
let val = cpu.load(addr, 16)?;
cpu.regs[rd] = val;
}
0x6 => {
// lwu
let val = cpu.load(addr, 32)?;
cpu.regs[rd] = val;
}
_ => {
println!("not implemented: opcode {:#x} funct3 {:#x}", opcode, funct3);
return Err(Exception::IllegalInstruction);
}
}
}
if opcode == 0x0f {
// A fence instruction does nothing because this emulator executes an instruction
// sequentially on a single thread.
match funct3 {
0x0 => {} // fence
_ => {
println!("not implemented: opcode {:#x} funct3 {:#x}", opcode, funct3);
return Err(Exception::IllegalInstruction);
}
}
}
*/
Ok(())
}
|
#![feature(test)]
extern crate test;
use test::Bencher;
use coruscant_nbt::{from_slice, to_gzip_writer, to_vec, to_writer, Compression};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize)]
#[serde(rename = "wrap")]
struct Wrap {
#[serde(rename = "inner")]
inner: Inner,
}
#[derive(Serialize, Deserialize)]
struct Inner {
map: HashMap<String, f32>,
}
// 44 bytes (uncompressed) in total
fn value() -> Wrap {
let mut map = HashMap::new();
map.insert("123".to_owned(), 123.456);
map.insert("456".to_owned(), 789.012);
Wrap {
inner: Inner { map },
}
}
#[bench]
fn json_ser_simple(b: &mut Bencher) {
let value = value();
let mut vec = Vec::with_capacity(512);
b.iter(|| {
let _ = serde_json::to_writer(&mut vec, &value).unwrap();
vec.clear();
});
}
#[bench]
fn nbt_ser_simple(b: &mut Bencher) {
let value = value();
let mut vec = Vec::with_capacity(128);
b.iter(|| {
let _ = to_writer(&mut vec, &value).unwrap();
vec.clear();
});
}
#[bench]
fn nbt_ser_simple_gzip_none(b: &mut Bencher) {
let value = value();
let mut vec = Vec::with_capacity(128);
b.iter(|| {
let _ = to_gzip_writer(&mut vec, &value, Compression::none()).unwrap();
vec.clear();
});
}
#[bench]
fn nbt_ser_simple_gzip_fast(b: &mut Bencher) {
let value = value();
let mut vec = Vec::with_capacity(128);
b.iter(|| {
let _ = to_gzip_writer(&mut vec, &value, Compression::fast()).unwrap();
vec.clear();
});
}
#[bench]
fn nbt_ser_simple_gzip_best(b: &mut Bencher) {
let value = value();
let mut vec = Vec::with_capacity(128);
b.iter(|| {
let _ = to_gzip_writer(&mut vec, &value, Compression::best()).unwrap();
vec.clear();
});
}
#[bench]
fn json_de_simple(b: &mut Bencher) {
let value = value();
let vec = serde_json::to_vec(&value).unwrap();
b.iter(|| {
let _: Wrap = serde_json::from_slice(&vec).unwrap();
});
}
#[bench]
fn nbt_de_simple(b: &mut Bencher) {
let value = value();
let vec = to_vec(&value).unwrap();
b.iter(|| {
let _: Wrap = from_slice(&vec).unwrap();
});
}
#[derive(Serialize, Deserialize)]
struct TestStruct {
#[serde(rename = "byteTest")]
byte_test: i8,
#[serde(rename = "shortTest")]
short_test: i16,
#[serde(rename = "intTest")]
int_test: i32,
#[serde(rename = "longTest")]
long_test: i64,
#[serde(rename = "floatTest")]
float_test: f32,
#[serde(rename = "doubleTest")]
double_test: f64,
#[serde(rename = "stringTest")]
string_test: String,
#[serde(rename = "listTest (long)")]
list_long_test: [i64; 5],
#[serde(rename = "listTest (compound)")]
list_compound_test: Vec<NestedCompound>,
#[serde(
rename = "byteArrayTest (the first 1000 values of (n*n*255+n*7)%100, starting with n=0 (0, 62, 34, 16, 8, ...))"
)]
byte_array_test: Box<[i8]>,
#[serde(rename = "nested compound test")]
nested: Nested,
}
#[derive(Serialize, Deserialize)]
struct Nested {
egg: Food,
ham: Food,
}
#[derive(Serialize, Deserialize)]
struct Food {
name: String,
value: f32,
}
#[derive(Serialize, Deserialize)]
struct NestedCompound {
#[serde(rename = "created-on")]
created_on: i64,
name: String,
}
// 1537 bytes (uncompressed) in total
fn value_big() -> TestStruct {
let mut byte_array_test = Vec::new();
for i in 0i32..1000 {
let value = (i * i * 255 + i * 7) % 100;
byte_array_test.push(value as i8)
}
let byte_array_test = byte_array_test.into_boxed_slice();
TestStruct {
nested: Nested {
egg: Food {
name: "Eggbert".to_owned(),
value: 0.5,
},
ham: Food {
name: "Hampus".to_owned(),
value: 0.75,
},
},
byte_test: 127,
short_test: 32767,
int_test: 2147483647,
long_test: 9223372036854775807,
double_test: 0.49312871321823148,
float_test: 0.49823147058486938,
string_test: "HELLO WORLD THIS IS A TEST STRING!".to_owned(),
list_long_test: [11, 12, 13, 14, 15],
list_compound_test: vec![
NestedCompound {
created_on: 1264099775885,
name: "Compound tag #0".to_owned(),
},
NestedCompound {
created_on: 1264099775885,
name: "Compound tag #1".to_owned(),
},
],
byte_array_test,
}
}
#[bench]
fn json_ser_big(b: &mut Bencher) {
let value = value_big();
let mut vec = Vec::with_capacity(512);
b.iter(|| {
let _ = serde_json::to_writer(&mut vec, &value).unwrap();
vec.clear();
});
}
#[bench]
fn nbt_ser_big(b: &mut Bencher) {
let value = value_big();
let mut vec = Vec::with_capacity(512);
b.iter(|| {
let _ = to_writer(&mut vec, &value).unwrap();
vec.clear();
});
}
#[bench]
fn nbt_ser_big_gzip_none(b: &mut Bencher) {
let value = value_big();
let mut vec = Vec::with_capacity(512);
b.iter(|| {
let _ = to_gzip_writer(&mut vec, &value, Compression::none()).unwrap();
vec.clear();
});
}
#[bench]
fn nbt_ser_big_gzip_fast(b: &mut Bencher) {
let value = value_big();
let mut vec = Vec::with_capacity(512);
b.iter(|| {
let _ = to_gzip_writer(&mut vec, &value, Compression::fast()).unwrap();
vec.clear();
});
}
#[bench]
fn nbt_ser_big_gzip_best(b: &mut Bencher) {
let value = value_big();
let mut vec = Vec::with_capacity(512);
b.iter(|| {
let _ = to_gzip_writer(&mut vec, &value, Compression::best()).unwrap();
vec.clear();
});
}
#[bench]
fn json_de_big(b: &mut Bencher) {
let value = value_big();
let vec = serde_json::to_vec(&value).unwrap();
b.iter(|| {
let _: TestStruct = serde_json::from_slice(&vec).unwrap();
});
}
#[bench]
fn nbt_de_big(b: &mut Bencher) {
let value = value_big();
let vec = to_vec(&value).unwrap();
b.iter(|| {
let _: TestStruct = from_slice(&vec).unwrap();
});
}
|
//! A module containing the structure of the valgrind XML output.
//!
//! Only the memcheck tool is implemented in accordance to [this][link]
//! description].
//!
//! Note, that not all fields are implemented.
//!
//! [link]: https://github.com/fredericgermain/valgrind/blob/master/docs/internals/xml-output-protocol4.txt
#![allow(clippy::missing_docs_in_private_items)]
#[cfg(test)]
mod tests;
use serde::{de::Visitor, Deserialize, Deserializer};
use std::fmt::{self, Display, Formatter};
/// The output of a valgrind run.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
#[serde(rename = "valgrindoutput")]
pub struct Output {
#[serde(rename = "protocolversion")]
protocol_version: ProtocolVersion,
#[serde(rename = "protocoltool")]
tool: Tool,
#[serde(rename = "error")]
pub errors: Option<Vec<Error>>,
}
/// The version of the XML format.
///
/// Although there are also versions 1-3, there is only a variant for version 4,
/// so that all older formats will fail. The other `struct`s in this file assume
/// the newest protocol version.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize)]
enum ProtocolVersion {
#[serde(rename = "4")]
Version4,
// other formats are not supported
}
/// The check tool used by valgrind.
///
/// Although there are other tools available, there is only a variant for the
/// so-called `memcheck` tool, so that all other tools will fail. The other
/// `struct`s in this file assume the memcheck output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize)]
enum Tool {
#[serde(rename = "memcheck")]
MemCheck,
// other tools are not supported
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
pub struct Error {
#[serde(deserialize_with = "deserialize_hex")]
unique: u64,
pub kind: Kind,
#[serde(default)]
#[serde(rename = "xwhat")]
pub resources: Resources,
#[serde(rename = "stack")]
pub stack_trace: Stack,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize)]
pub enum Kind {
#[serde(rename = "Leak_DefinitelyLost")]
LeakDefinitelyLost,
#[serde(rename = "Leak_StillReachable")]
LeakStillReachable,
#[serde(rename = "Leak_IndirectlyLost")]
LeakIndirectlyLost,
#[serde(rename = "Leak_PossiblyLost")]
LeakPossiblyLost,
InvalidFree,
MismatchedFree,
InvalidRead,
InvalidWrite,
InvalidJump,
Overlap,
InvalidMemPool,
UninitCondition,
UninitValue,
SyscallParam,
ClientCheck,
}
impl Display for Kind {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::LeakDefinitelyLost => write!(f, "Leak (definitely lost)"),
Self::LeakStillReachable => write!(f, "Leak (still reachable)"),
Self::LeakIndirectlyLost => write!(f, "Leak (indirectly lost)"),
Self::LeakPossiblyLost => write!(f, "Leak (possibly lost)"),
Self::InvalidFree => write!(f, "invalid free"),
Self::MismatchedFree => write!(f, "mismatched free"),
Self::InvalidRead => write!(f, "invalid read"),
Self::InvalidWrite => write!(f, "invalid write"),
Self::InvalidJump => write!(f, "invalid jump"),
Self::Overlap => write!(f, "overlap"),
Self::InvalidMemPool => write!(f, "invalid memory pool"),
Self::UninitCondition => write!(f, "uninitialized condition"),
Self::UninitValue => write!(f, "uninitialized value"),
Self::SyscallParam => write!(f, "syscall parameter"),
Self::ClientCheck => write!(f, "client check"),
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Deserialize)]
pub struct Resources {
#[serde(rename = "leakedbytes")]
pub bytes: usize,
#[serde(rename = "leakedblocks")]
pub blocks: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
pub struct Stack {
#[serde(rename = "frame")]
pub frames: Vec<Frame>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
pub struct Frame {
#[serde(rename = "ip")]
#[serde(deserialize_with = "deserialize_hex")]
pub instruction_pointer: u64,
#[serde(rename = "obj")]
pub object: Option<String>,
#[serde(rename = "dir")]
pub directory: Option<String>,
#[serde(rename = "fn")]
pub function: Option<String>,
pub file: Option<String>,
pub line: Option<usize>,
}
impl Display for Frame {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str(self.function.as_ref().unwrap_or(&"unknown".into()))?;
if let Some(file) = &self.file {
f.write_str(" (")?;
f.write_str(file)?;
if let Some(line) = self.line {
write!(f, ":{}", line)?;
}
f.write_str(")")?;
}
Ok(())
}
}
fn deserialize_hex<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
deserializer.deserialize_str(HexVisitor)
}
/// A visitor for parsing a `u64` in the format `0xDEADBEEF`.
struct HexVisitor;
impl<'de> Visitor<'de> for HexVisitor {
type Value = u64;
fn expecting(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("hexadecimal number with leading '0x'")
}
fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> {
let value = value.to_ascii_lowercase();
let value = value
.strip_prefix("0x")
.ok_or_else(|| E::custom("'0x' prefix missing"))?;
Self::Value::from_str_radix(value, 16)
.map_err(|_| E::custom(format!("invalid hex number '{}'", value)))
}
}
|
use diesel::pg::PgConnection;
use diesel::r2d2::ConnectionManager;
use lazy_static::*;
use r2d2::{Pool, PooledConnection};
use crate::util::env_vars::{DB_MAX_POOL_SIZE, DB_URL};
lazy_static! {
static ref DB_CONNECTION_POOL: Pool<ConnectionManager<PgConnection>> = {
let manager = ConnectionManager::new(&*DB_URL);
let pool = Pool::builder()
.max_size(*DB_MAX_POOL_SIZE)
.build(manager)
.unwrap();
pool
};
}
pub fn establish_connection() -> PooledConnection<ConnectionManager<PgConnection>> {
DB_CONNECTION_POOL
.get()
.expect(&format!("Error connecting to {}", *DB_URL))
}
|
// When the logging feature is not used, these should effectively do nothing.
// However, if we simply ignore the arguments passed to the macro, we'll get
// a bunch of warnings about dead code, unused variables, etc. To get around
// this, we can bind all of the arguments in a local scope. However, simply
// binding the arguments will take ownership of them, which is not always
// desired, so we bind references to them instead. These bindings should
// be optimized away by the compiler.
#[macro_export]
macro_rules! log {
($($arg:expr),*) => ({
$(let _arg = &$arg;)*
#[cfg(feature = "log-cli")]
print!($($arg),*);
});
}
#[macro_export]
macro_rules! logln {
($($arg:expr),*) => ({
$(let _arg = &$arg;)*
#[cfg(feature = "log-cli")]
println!($($arg),*);
});
} |
#[doc = "Reader of register DINR15"]
pub type R = crate::R<u32, super::DINR15>;
#[doc = "Reader of field `DIN15`"]
pub type DIN15_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - Input data received from MDIO Master during write frames"]
#[inline(always)]
pub fn din15(&self) -> DIN15_R {
DIN15_R::new((self.bits & 0xffff) as u16)
}
}
|
mod game_world;
mod position;
mod region;
pub use game_world::*;
pub use position::*;
pub use region::*;
|
use crate::token::Token;
pub trait Node {
fn token_literal(&self) -> String;
}
#[derive(Debug)]
pub enum Statement {
Let(LetStatement),
Return(ReturnStatement),
Expression(ExpressionStatement),
}
impl Node for Statement {
fn token_literal(&self) -> String {
match self {
Statement::Let(statement) => statement.token_literal(),
Statement::Return(statement) => statement.token_literal(),
Statement::Expression(statement) => statement.token_literal(),
}
}
}
impl std::fmt::Display for Statement {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Statement::Let(statement) => write!(f, "{}", statement),
Statement::Return(statement) => write!(f, "{}", statement),
Statement::Expression(statement) => write!(f, "{}", statement),
}
}
}
#[derive(Debug)]
pub struct LetStatement {
pub token: Box<Token>,
pub identifier: Identifier,
pub expression: Box<Expression>,
}
impl LetStatement {
pub fn new(token: Box<Token>, identifier: Identifier, expression: Box<Expression>) -> Self {
Self {
token,
identifier,
expression,
}
}
}
impl Node for LetStatement {
fn token_literal(&self) -> String {
self.token.literal.clone()
}
}
impl std::fmt::Display for LetStatement {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{} {} = {};",
self.token_literal(),
self.identifier,
self.expression
)
}
}
#[derive(Debug)]
pub struct ReturnStatement {
pub token: Box<Token>,
pub return_value: Box<Expression>,
}
impl ReturnStatement {
pub fn new(token: Box<Token>, return_value: Box<Expression>) -> Self {
Self {
token,
return_value,
}
}
}
impl Node for ReturnStatement {
fn token_literal(&self) -> String {
self.token.literal.clone()
}
}
impl std::fmt::Display for ReturnStatement {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{} {};", self.token_literal(), self.return_value)
}
}
#[derive(Debug)]
pub struct ExpressionStatement {
pub expression: Box<Expression>,
}
impl ExpressionStatement {
pub fn new(expression: Box<Expression>) -> Self {
Self { expression }
}
}
impl Node for ExpressionStatement {
fn token_literal(&self) -> String {
self.expression.token_literal()
}
}
impl std::fmt::Display for ExpressionStatement {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.expression)
}
}
#[derive(Debug)]
pub enum Expression {
Identifier(Identifier),
Integer(IntegerLiteral),
Prefix(PrefixExpression),
Infix(InfixExpression),
Boolean(Boolean),
}
impl Node for Expression {
fn token_literal(&self) -> String {
match self {
Expression::Identifier(identifier) => identifier.token_literal(),
Expression::Integer(integer_literal) => integer_literal.token_literal(),
Expression::Prefix(prefix) => prefix.token_literal(),
Expression::Infix(infix) => infix.token_literal(),
Expression::Boolean(boolean) => boolean.token_literal(),
}
}
}
impl std::fmt::Display for Expression {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Expression::Identifier(identifier) => write!(f, "{}", identifier),
Expression::Integer(integer_literal) => write!(f, "{}", integer_literal),
Expression::Prefix(prefix) => write!(f, "{}", prefix),
Expression::Infix(infix) => write!(f, "{}", infix),
Expression::Boolean(boolean) => write!(f, "{}", boolean),
}
}
}
#[derive(Debug)]
pub struct Identifier {
pub token: Box<Token>,
pub value: String,
}
impl Identifier {
pub fn new(token: Box<Token>) -> Self {
let value = token.literal.clone();
Self { token, value }
}
}
impl Node for Identifier {
fn token_literal(&self) -> String {
self.token.literal.clone()
}
}
impl std::fmt::Display for Identifier {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.value)
}
}
#[derive(Debug)]
pub struct IntegerLiteral {
pub token: Box<Token>,
pub value: i64,
}
impl IntegerLiteral {
pub fn new(token: Box<Token>) -> Self {
let value = token
.literal
.parse::<i64>()
.unwrap_or_else(|e| panic!("could not parse {} as integer", e));
Self { token, value }
}
}
impl Node for IntegerLiteral {
fn token_literal(&self) -> String {
self.token.literal.clone()
}
}
impl std::fmt::Display for IntegerLiteral {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.value)
}
}
#[derive(Debug)]
pub struct PrefixExpression {
pub token: Box<Token>,
pub operator: String,
pub right: Box<Expression>,
}
impl PrefixExpression {
pub fn new(token: Box<Token>, right: Box<Expression>) -> Self {
let operator = token.literal.clone();
Self {
token,
operator,
right,
}
}
}
impl Node for PrefixExpression {
fn token_literal(&self) -> String {
self.token.literal.clone()
}
}
impl std::fmt::Display for PrefixExpression {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "({}{})", self.operator, self.right,)
}
}
#[derive(Debug)]
pub struct InfixExpression {
pub token: Box<Token>,
pub left: Box<Expression>,
pub operator: String,
pub right: Box<Expression>,
}
impl InfixExpression {
pub fn new(token: Box<Token>, left: Box<Expression>, right: Box<Expression>) -> Self {
let operator = token.literal.clone();
Self {
token,
left,
operator,
right,
}
}
}
impl Node for InfixExpression {
fn token_literal(&self) -> String {
self.token.literal.clone()
}
}
impl std::fmt::Display for InfixExpression {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "({} {} {})", self.left, self.operator, self.right)
}
}
#[derive(Debug)]
pub struct Boolean {
pub token: Box<Token>,
pub value: bool,
}
impl Boolean {
pub fn new(token: Box<Token>, value: bool) -> Self {
Self { token, value }
}
}
impl std::fmt::Display for Boolean {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.value)
}
}
impl Node for Boolean {
fn token_literal(&self) -> String {
self.token.literal.clone()
}
}
pub type Program = Vec<Statement>;
pub fn string(program: &[Statement]) -> String {
program
.iter()
.fold(String::new(), |string, ast| format!("{}{}", string, ast))
}
|
use std::io;
use num::BigUint;
use crate::{rsa, io as asdf};
use std::error::Error;
fn print_help() {
println!("Key generation: ");
println!("\t k -> Generate new key and store in memory");
println!("\t wk -> Write key stored in memory to file");
println!("\t rk -> Read key from disk. Must be present in current directory.");
println!("Encryption: ");
println!("\t e <message> -> Encrypt message using stored key, storing cipher in memory.");
println!("\t wc <filename> -> Write stored cipher to <filename>");
println!("\t pc -> Prints stored cipher to stdout. Warning: very long line");
println!("Decryption: ");
println!("\t d -> Decrypt cipher stored in memory, display result to stdout");
println!("\t df <filename> -> Read cipher from file and decrypt using stored key, display result to stdout");
println!("Misc: ");
println!("\t q -> Quit.");
println!("\t s -> Print status. Shows whether key/cipher is stored in memory");
println!("\t h -> Print this help menu again");
}
pub fn init_cli_interface() {
println!("Rust implementation of RSA-1024, written by Ariel Young and Nashir Janmohamed\n");
println!("Commands are as follows -- ");
print_help();
let mut stored_key: Option<((BigUint, BigUint), BigUint)> = None;
let mut stored_cipher: Option<Vec<BigUint>> = None;
'outer: loop {
println!();
let mut input = String::new();
io::stdin().read_line(&mut input).expect("> Unable to read input");
let mut parts: Vec<&str> = input.split_ascii_whitespace().collect();
match parts[0] {
"k" => {
println!("> Generating key...");
stored_key = Some(rsa::gen_key());
println!("> Finished!");
},
"wk" => match stored_key.clone() {
Some(key) => {asdf::write_json_to_disk(key); println!("> Done!");},
None => println!("> Error: No stored key")
},
"rk" => match asdf::read_key_from_disk() {
Ok(key) => {stored_key = Some(key); println!("> Done!");},
Err(e) => println!("> Error reading key from file: {}", e.to_string()),
},
"e" => {
if stored_key.is_none() {
println!("> Error: No stored key");
println!("> Either generate one, or read from file using 'rk <filename>'");
} else if parts.len() >= 2 {
println!("> Encrypting message...");
let key = stored_key.clone().unwrap();
let res = rsa::encrypt_str(&parts[1..].join(" "), key.0);
println!("> Finished!");
println!("> Result: {:?}", res);
stored_cipher = Some(res);
} else {
println!("> Error: invalid parameters to 'e'");
}
},
"wc" => {
if stored_cipher.is_none() {
println!("> Error: No cipher stored in memory. Please encrypt something.");
} else if parts.len() != 2 {
println!("> Usage: `wc [filename`");
} else {
print!("> Writing cipher to disk...");
asdf::write_cipher_to_disk(stored_cipher.clone().unwrap().as_ref(), parts[1]);
println!("Done!");
}
},
"pc" => match stored_cipher.clone() {
Some(t) => {
println!("> Stored cipher: {:?}", t);
print!("> Hex: ");
for b in &t { print!("{:x}", b); }
println!();
},
None => println!("> Error: No stored cipher"),
}
"d" => {
if stored_cipher.is_none() {
println!("> Error: No stored cipher.");
println!("> Either encrypt a message using 'e', or decrypt a cipher from file using 'df'");
} else if stored_key.is_none() {
println!("> Error: No stored key");
println!("> You probably want to read one from disk using 'rk'");
} else {
let key = stored_key.clone().unwrap();
println!("> Decryption result: {}", rsa::decrypt_str(&stored_cipher.clone().unwrap(),
key.1, (key.0).0));
}
},
"df" => {
if parts.len() != 2 {
println!("> Usage: `df <filename>");
} else if stored_key.is_none() {
println!("> Error: No stored key");
println!("> You probably want to read one from disk using 'rk'");
} else {
print!("> Reading cipher from disk...");
match asdf::read_cipher_from_disk(parts[1]) {
Ok(c) => {
println!("Done!");
let key = stored_key.clone().unwrap();
println!("> Decryption result: {}", rsa::decrypt_str(&c, key.1, (key.0).0));
},
Err(e) => println!("failed \n> Error reading cipher from disk"),
}
}
},
"s" => {
if stored_key.is_none() {
println!("> Key stored in memory: no");
} else {
println!("> Key stored in memory: yes");
}
if stored_cipher.is_none() {
println!("> Key stored in memory: no");
} else {
println!("> Key stored in memory: yes");
}
},
"h" => print_help(),
"q" => {
println!("> Exiting...");
return;
},
_ => println!("> Input not recognized, enter 'h' for help"),
}
}
} |
#[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::INTENCLR {
#[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 `STOPPED`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum STOPPEDR {
#[doc = "Interrupt disabled."]
DISABLED,
#[doc = "Interrupt enabled."]
ENABLED,
}
impl STOPPEDR {
#[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 {
STOPPEDR::DISABLED => false,
STOPPEDR::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> STOPPEDR {
match value {
false => STOPPEDR::DISABLED,
true => STOPPEDR::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == STOPPEDR::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == STOPPEDR::ENABLED
}
}
#[doc = "Possible values of the field `RXDREADY`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RXDREADYR {
#[doc = "Interrupt disabled."]
DISABLED,
#[doc = "Interrupt enabled."]
ENABLED,
}
impl RXDREADYR {
#[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 {
RXDREADYR::DISABLED => false,
RXDREADYR::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> RXDREADYR {
match value {
false => RXDREADYR::DISABLED,
true => RXDREADYR::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == RXDREADYR::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == RXDREADYR::ENABLED
}
}
#[doc = "Possible values of the field `TXDSENT`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TXDSENTR {
#[doc = "Interrupt disabled."]
DISABLED,
#[doc = "Interrupt enabled."]
ENABLED,
}
impl TXDSENTR {
#[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 {
TXDSENTR::DISABLED => false,
TXDSENTR::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TXDSENTR {
match value {
false => TXDSENTR::DISABLED,
true => TXDSENTR::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == TXDSENTR::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == TXDSENTR::ENABLED
}
}
#[doc = "Possible values of the field `ERROR`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ERRORR {
#[doc = "Interrupt disabled."]
DISABLED,
#[doc = "Interrupt enabled."]
ENABLED,
}
impl ERRORR {
#[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 {
ERRORR::DISABLED => false,
ERRORR::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> ERRORR {
match value {
false => ERRORR::DISABLED,
true => ERRORR::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == ERRORR::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == ERRORR::ENABLED
}
}
#[doc = "Possible values of the field `BB`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BBR {
#[doc = "Interrupt disabled."]
DISABLED,
#[doc = "Interrupt enabled."]
ENABLED,
}
impl BBR {
#[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 {
BBR::DISABLED => false,
BBR::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> BBR {
match value {
false => BBR::DISABLED,
true => BBR::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == BBR::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == BBR::ENABLED
}
}
#[doc = "Values that can be written to the field `STOPPED`"]
pub enum STOPPEDW {
#[doc = "Disable interrupt on write."]
CLEAR,
}
impl STOPPEDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
STOPPEDW::CLEAR => true,
}
}
}
#[doc = r" Proxy"]
pub struct _STOPPEDW<'a> {
w: &'a mut W,
}
impl<'a> _STOPPEDW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: STOPPEDW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable interrupt on write."]
#[inline]
pub fn clear(self) -> &'a mut W {
self.variant(STOPPEDW::CLEAR)
}
#[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 `RXDREADY`"]
pub enum RXDREADYW {
#[doc = "Disable interrupt on write."]
CLEAR,
}
impl RXDREADYW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
RXDREADYW::CLEAR => true,
}
}
}
#[doc = r" Proxy"]
pub struct _RXDREADYW<'a> {
w: &'a mut W,
}
impl<'a> _RXDREADYW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: RXDREADYW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable interrupt on write."]
#[inline]
pub fn clear(self) -> &'a mut W {
self.variant(RXDREADYW::CLEAR)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TXDSENT`"]
pub enum TXDSENTW {
#[doc = "Disable interrupt on write."]
CLEAR,
}
impl TXDSENTW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TXDSENTW::CLEAR => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TXDSENTW<'a> {
w: &'a mut W,
}
impl<'a> _TXDSENTW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TXDSENTW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable interrupt on write."]
#[inline]
pub fn clear(self) -> &'a mut W {
self.variant(TXDSENTW::CLEAR)
}
#[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 = 7;
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 `ERROR`"]
pub enum ERRORW {
#[doc = "Disable interrupt on write."]
CLEAR,
}
impl ERRORW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
ERRORW::CLEAR => true,
}
}
}
#[doc = r" Proxy"]
pub struct _ERRORW<'a> {
w: &'a mut W,
}
impl<'a> _ERRORW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: ERRORW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable interrupt on write."]
#[inline]
pub fn clear(self) -> &'a mut W {
self.variant(ERRORW::CLEAR)
}
#[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 = 9;
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 `BB`"]
pub enum BBW {
#[doc = "Disable interrupt on write."]
CLEAR,
}
impl BBW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
BBW::CLEAR => true,
}
}
}
#[doc = r" Proxy"]
pub struct _BBW<'a> {
w: &'a mut W,
}
impl<'a> _BBW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: BBW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable interrupt on write."]
#[inline]
pub fn clear(self) -> &'a mut W {
self.variant(BBW::CLEAR)
}
#[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 = 14;
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 1 - Disable interrupt on STOPPED event."]
#[inline]
pub fn stopped(&self) -> STOPPEDR {
STOPPEDR::_from({
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 2 - Disable interrupt on RXDREADY event."]
#[inline]
pub fn rxdready(&self) -> RXDREADYR {
RXDREADYR::_from({
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 7 - Disable interrupt on TXDSENT event."]
#[inline]
pub fn txdsent(&self) -> TXDSENTR {
TXDSENTR::_from({
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 9 - Disable interrupt on ERROR event."]
#[inline]
pub fn error(&self) -> ERRORR {
ERRORR::_from({
const MASK: bool = true;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 14 - Disable interrupt on BB event."]
#[inline]
pub fn bb(&self) -> BBR {
BBR::_from({
const MASK: bool = true;
const OFFSET: u8 = 14;
((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 1 - Disable interrupt on STOPPED event."]
#[inline]
pub fn stopped(&mut self) -> _STOPPEDW {
_STOPPEDW { w: self }
}
#[doc = "Bit 2 - Disable interrupt on RXDREADY event."]
#[inline]
pub fn rxdready(&mut self) -> _RXDREADYW {
_RXDREADYW { w: self }
}
#[doc = "Bit 7 - Disable interrupt on TXDSENT event."]
#[inline]
pub fn txdsent(&mut self) -> _TXDSENTW {
_TXDSENTW { w: self }
}
#[doc = "Bit 9 - Disable interrupt on ERROR event."]
#[inline]
pub fn error(&mut self) -> _ERRORW {
_ERRORW { w: self }
}
#[doc = "Bit 14 - Disable interrupt on BB event."]
#[inline]
pub fn bb(&mut self) -> _BBW {
_BBW { w: self }
}
}
|
#[doc = "Reader of register MPCBB2_VCTR2"]
pub type R = crate::R<u32, super::MPCBB2_VCTR2>;
#[doc = "Writer for register MPCBB2_VCTR2"]
pub type W = crate::W<u32, super::MPCBB2_VCTR2>;
#[doc = "Register MPCBB2_VCTR2 `reset()`'s with value 0xffff_ffff"]
impl crate::ResetValue for super::MPCBB2_VCTR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xffff_ffff
}
}
#[doc = "Reader of field `B64`"]
pub type B64_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B64`"]
pub struct B64_W<'a> {
w: &'a mut W,
}
impl<'a> B64_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `B65`"]
pub type B65_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B65`"]
pub struct B65_W<'a> {
w: &'a mut W,
}
impl<'a> B65_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 `B66`"]
pub type B66_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B66`"]
pub struct B66_W<'a> {
w: &'a mut W,
}
impl<'a> B66_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 `B67`"]
pub type B67_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B67`"]
pub struct B67_W<'a> {
w: &'a mut W,
}
impl<'a> B67_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 `B68`"]
pub type B68_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B68`"]
pub struct B68_W<'a> {
w: &'a mut W,
}
impl<'a> B68_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 `B69`"]
pub type B69_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B69`"]
pub struct B69_W<'a> {
w: &'a mut W,
}
impl<'a> B69_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 `B70`"]
pub type B70_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B70`"]
pub struct B70_W<'a> {
w: &'a mut W,
}
impl<'a> B70_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 `B71`"]
pub type B71_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B71`"]
pub struct B71_W<'a> {
w: &'a mut W,
}
impl<'a> B71_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 `B72`"]
pub type B72_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B72`"]
pub struct B72_W<'a> {
w: &'a mut W,
}
impl<'a> B72_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `B73`"]
pub type B73_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B73`"]
pub struct B73_W<'a> {
w: &'a mut W,
}
impl<'a> B73_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 `B74`"]
pub type B74_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B74`"]
pub struct B74_W<'a> {
w: &'a mut W,
}
impl<'a> B74_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 `B75`"]
pub type B75_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B75`"]
pub struct B75_W<'a> {
w: &'a mut W,
}
impl<'a> B75_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 `B76`"]
pub type B76_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B76`"]
pub struct B76_W<'a> {
w: &'a mut W,
}
impl<'a> B76_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 `B77`"]
pub type B77_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B77`"]
pub struct B77_W<'a> {
w: &'a mut W,
}
impl<'a> B77_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 `B78`"]
pub type B78_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B78`"]
pub struct B78_W<'a> {
w: &'a mut W,
}
impl<'a> B78_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `B79`"]
pub type B79_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B79`"]
pub struct B79_W<'a> {
w: &'a mut W,
}
impl<'a> B79_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `B80`"]
pub type B80_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B80`"]
pub struct B80_W<'a> {
w: &'a mut W,
}
impl<'a> B80_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `B81`"]
pub type B81_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B81`"]
pub struct B81_W<'a> {
w: &'a mut W,
}
impl<'a> B81_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `B82`"]
pub type B82_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B82`"]
pub struct B82_W<'a> {
w: &'a mut W,
}
impl<'a> B82_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `B83`"]
pub type B83_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B83`"]
pub struct B83_W<'a> {
w: &'a mut W,
}
impl<'a> B83_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Reader of field `B84`"]
pub type B84_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B84`"]
pub struct B84_W<'a> {
w: &'a mut W,
}
impl<'a> B84_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Reader of field `B85`"]
pub type B85_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B85`"]
pub struct B85_W<'a> {
w: &'a mut W,
}
impl<'a> B85_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Reader of field `B86`"]
pub type B86_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B86`"]
pub struct B86_W<'a> {
w: &'a mut W,
}
impl<'a> B86_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "Reader of field `B87`"]
pub type B87_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B87`"]
pub struct B87_W<'a> {
w: &'a mut W,
}
impl<'a> B87_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "Reader of field `B88`"]
pub type B88_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B88`"]
pub struct B88_W<'a> {
w: &'a mut W,
}
impl<'a> B88_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `B89`"]
pub type B89_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B89`"]
pub struct B89_W<'a> {
w: &'a mut W,
}
impl<'a> B89_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Reader of field `B90`"]
pub type B90_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B90`"]
pub struct B90_W<'a> {
w: &'a mut W,
}
impl<'a> B90_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Reader of field `B91`"]
pub type B91_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B91`"]
pub struct B91_W<'a> {
w: &'a mut W,
}
impl<'a> B91_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Reader of field `B92`"]
pub type B92_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B92`"]
pub struct B92_W<'a> {
w: &'a mut W,
}
impl<'a> B92_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Reader of field `B93`"]
pub type B93_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B93`"]
pub struct B93_W<'a> {
w: &'a mut W,
}
impl<'a> B93_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "Reader of field `B94`"]
pub type B94_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B94`"]
pub struct B94_W<'a> {
w: &'a mut W,
}
impl<'a> B94_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Reader of field `B95`"]
pub type B95_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `B95`"]
pub struct B95_W<'a> {
w: &'a mut W,
}
impl<'a> B95_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - B64"]
#[inline(always)]
pub fn b64(&self) -> B64_R {
B64_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - B65"]
#[inline(always)]
pub fn b65(&self) -> B65_R {
B65_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - B66"]
#[inline(always)]
pub fn b66(&self) -> B66_R {
B66_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - B67"]
#[inline(always)]
pub fn b67(&self) -> B67_R {
B67_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - B68"]
#[inline(always)]
pub fn b68(&self) -> B68_R {
B68_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - B69"]
#[inline(always)]
pub fn b69(&self) -> B69_R {
B69_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - B70"]
#[inline(always)]
pub fn b70(&self) -> B70_R {
B70_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - B71"]
#[inline(always)]
pub fn b71(&self) -> B71_R {
B71_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - B72"]
#[inline(always)]
pub fn b72(&self) -> B72_R {
B72_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - B73"]
#[inline(always)]
pub fn b73(&self) -> B73_R {
B73_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - B74"]
#[inline(always)]
pub fn b74(&self) -> B74_R {
B74_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - B75"]
#[inline(always)]
pub fn b75(&self) -> B75_R {
B75_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - B76"]
#[inline(always)]
pub fn b76(&self) -> B76_R {
B76_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - B77"]
#[inline(always)]
pub fn b77(&self) -> B77_R {
B77_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - B78"]
#[inline(always)]
pub fn b78(&self) -> B78_R {
B78_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - B79"]
#[inline(always)]
pub fn b79(&self) -> B79_R {
B79_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - B80"]
#[inline(always)]
pub fn b80(&self) -> B80_R {
B80_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - B81"]
#[inline(always)]
pub fn b81(&self) -> B81_R {
B81_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - B82"]
#[inline(always)]
pub fn b82(&self) -> B82_R {
B82_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - B83"]
#[inline(always)]
pub fn b83(&self) -> B83_R {
B83_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - B84"]
#[inline(always)]
pub fn b84(&self) -> B84_R {
B84_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - B85"]
#[inline(always)]
pub fn b85(&self) -> B85_R {
B85_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - B86"]
#[inline(always)]
pub fn b86(&self) -> B86_R {
B86_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - B87"]
#[inline(always)]
pub fn b87(&self) -> B87_R {
B87_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - B88"]
#[inline(always)]
pub fn b88(&self) -> B88_R {
B88_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - B89"]
#[inline(always)]
pub fn b89(&self) -> B89_R {
B89_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - B90"]
#[inline(always)]
pub fn b90(&self) -> B90_R {
B90_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - B91"]
#[inline(always)]
pub fn b91(&self) -> B91_R {
B91_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - B92"]
#[inline(always)]
pub fn b92(&self) -> B92_R {
B92_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - B93"]
#[inline(always)]
pub fn b93(&self) -> B93_R {
B93_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 30 - B94"]
#[inline(always)]
pub fn b94(&self) -> B94_R {
B94_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - B95"]
#[inline(always)]
pub fn b95(&self) -> B95_R {
B95_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - B64"]
#[inline(always)]
pub fn b64(&mut self) -> B64_W {
B64_W { w: self }
}
#[doc = "Bit 1 - B65"]
#[inline(always)]
pub fn b65(&mut self) -> B65_W {
B65_W { w: self }
}
#[doc = "Bit 2 - B66"]
#[inline(always)]
pub fn b66(&mut self) -> B66_W {
B66_W { w: self }
}
#[doc = "Bit 3 - B67"]
#[inline(always)]
pub fn b67(&mut self) -> B67_W {
B67_W { w: self }
}
#[doc = "Bit 4 - B68"]
#[inline(always)]
pub fn b68(&mut self) -> B68_W {
B68_W { w: self }
}
#[doc = "Bit 5 - B69"]
#[inline(always)]
pub fn b69(&mut self) -> B69_W {
B69_W { w: self }
}
#[doc = "Bit 6 - B70"]
#[inline(always)]
pub fn b70(&mut self) -> B70_W {
B70_W { w: self }
}
#[doc = "Bit 7 - B71"]
#[inline(always)]
pub fn b71(&mut self) -> B71_W {
B71_W { w: self }
}
#[doc = "Bit 8 - B72"]
#[inline(always)]
pub fn b72(&mut self) -> B72_W {
B72_W { w: self }
}
#[doc = "Bit 9 - B73"]
#[inline(always)]
pub fn b73(&mut self) -> B73_W {
B73_W { w: self }
}
#[doc = "Bit 10 - B74"]
#[inline(always)]
pub fn b74(&mut self) -> B74_W {
B74_W { w: self }
}
#[doc = "Bit 11 - B75"]
#[inline(always)]
pub fn b75(&mut self) -> B75_W {
B75_W { w: self }
}
#[doc = "Bit 12 - B76"]
#[inline(always)]
pub fn b76(&mut self) -> B76_W {
B76_W { w: self }
}
#[doc = "Bit 13 - B77"]
#[inline(always)]
pub fn b77(&mut self) -> B77_W {
B77_W { w: self }
}
#[doc = "Bit 14 - B78"]
#[inline(always)]
pub fn b78(&mut self) -> B78_W {
B78_W { w: self }
}
#[doc = "Bit 15 - B79"]
#[inline(always)]
pub fn b79(&mut self) -> B79_W {
B79_W { w: self }
}
#[doc = "Bit 16 - B80"]
#[inline(always)]
pub fn b80(&mut self) -> B80_W {
B80_W { w: self }
}
#[doc = "Bit 17 - B81"]
#[inline(always)]
pub fn b81(&mut self) -> B81_W {
B81_W { w: self }
}
#[doc = "Bit 18 - B82"]
#[inline(always)]
pub fn b82(&mut self) -> B82_W {
B82_W { w: self }
}
#[doc = "Bit 19 - B83"]
#[inline(always)]
pub fn b83(&mut self) -> B83_W {
B83_W { w: self }
}
#[doc = "Bit 20 - B84"]
#[inline(always)]
pub fn b84(&mut self) -> B84_W {
B84_W { w: self }
}
#[doc = "Bit 21 - B85"]
#[inline(always)]
pub fn b85(&mut self) -> B85_W {
B85_W { w: self }
}
#[doc = "Bit 22 - B86"]
#[inline(always)]
pub fn b86(&mut self) -> B86_W {
B86_W { w: self }
}
#[doc = "Bit 23 - B87"]
#[inline(always)]
pub fn b87(&mut self) -> B87_W {
B87_W { w: self }
}
#[doc = "Bit 24 - B88"]
#[inline(always)]
pub fn b88(&mut self) -> B88_W {
B88_W { w: self }
}
#[doc = "Bit 25 - B89"]
#[inline(always)]
pub fn b89(&mut self) -> B89_W {
B89_W { w: self }
}
#[doc = "Bit 26 - B90"]
#[inline(always)]
pub fn b90(&mut self) -> B90_W {
B90_W { w: self }
}
#[doc = "Bit 27 - B91"]
#[inline(always)]
pub fn b91(&mut self) -> B91_W {
B91_W { w: self }
}
#[doc = "Bit 28 - B92"]
#[inline(always)]
pub fn b92(&mut self) -> B92_W {
B92_W { w: self }
}
#[doc = "Bit 29 - B93"]
#[inline(always)]
pub fn b93(&mut self) -> B93_W {
B93_W { w: self }
}
#[doc = "Bit 30 - B94"]
#[inline(always)]
pub fn b94(&mut self) -> B94_W {
B94_W { w: self }
}
#[doc = "Bit 31 - B95"]
#[inline(always)]
pub fn b95(&mut self) -> B95_W {
B95_W { w: self }
}
}
|
//! Core runtime support for SQLx. **Semver-exempt**, not for general use.
#[cfg(not(any(
feature = "runtime-actix-native-tls",
feature = "runtime-async-std-native-tls",
feature = "runtime-tokio-native-tls",
feature = "runtime-actix-rustls",
feature = "runtime-async-std-rustls",
feature = "runtime-tokio-rustls",
)))]
compile_error!(
"one of the features ['runtime-actix-native-tls', 'runtime-async-std-native-tls', \
'runtime-tokio-native-tls', 'runtime-actix-rustls', 'runtime-async-std-rustls', \
'runtime-tokio-rustls'] must be enabled"
);
#[cfg(any(
all(feature = "_rt-actix", feature = "_rt-async-std"),
all(feature = "_rt-actix", feature = "_rt-tokio"),
all(feature = "_rt-async-std", feature = "_rt-tokio"),
all(feature = "_tls-native-tls", feature = "_tls-rustls"),
))]
compile_error!(
"only one of ['runtime-actix-native-tls', 'runtime-async-std-native-tls', \
'runtime-tokio-native-tls', 'runtime-actix-rustls', 'runtime-async-std-rustls', \
'runtime-tokio-rustls'] can be enabled"
);
#[cfg(feature = "_rt-async-std")]
mod rt_async_std;
#[cfg(any(feature = "_rt-tokio", feature = "_rt-actix"))]
mod rt_tokio;
#[cfg(all(feature = "_tls-native-tls"))]
pub use native_tls;
//
// Actix *OR* Tokio
//
#[cfg(all(any(feature = "_rt-tokio", feature = "_rt-actix"),))]
pub use rt_tokio::*;
#[cfg(all(
feature = "_rt-async-std",
not(any(feature = "_rt-tokio", feature = "_rt-actix"))
))]
pub use rt_async_std::*;
|
extern crate ndbx_core;
extern crate xml;
use std::fs::File;
use std::io::BufReader;
use xml::reader::{EventReader, XmlEvent};
fn indent(size: usize) -> String {
const INDENT: &'static str = " ";
(0..size)
.map(|_| INDENT)
.fold(String::with_capacity(size * INDENT.len()), |r, s| r + s)
}
// fn parse_ndbx(parser: &EventReader) -> Result<(), Err> {
// for e in parser {
// match e {
// Ok(XmlEvent::StartElement {name, ..}) => {
// if name.local_name != "ndbx" {
// return Err("Document does not start with <ndbx> tag.");
// }
// parse_
// }
// }
// }
// }
// }
// fn parse_doc(parser: &EventReader) -> Result<(), Err> {
// for e in parser {
// match e {
// Ok(XmlEvent::StartElement {name, ..}) => {
// if name.local_name != "ndbx" {
// return Err("Document does not start with <ndbx> tag.");
// }
// return parse_ndbx(parser);
// }
// Ok(XmlEvent::EndElement { name }) => {
// if name.local_name != "ndbx" {
// return Err("Document does not end with <ndbx> tag.");
// }
// return
// }
// }
// }
// }
// }
fn main() {
let file = File::open("examples/corevector.ndbx").unwrap();
let file = BufReader::new(file);
let parser = EventReader::new(file);
// parse_ndbx(e);
let mut depth = 0;
for e in parser {
match e {
Ok(XmlEvent::StartElement { name, .. }) => {
if name.local_name == "ndbx" {
println!("Start of ndbx doc");
}
println!("{}+{}", indent(depth), name);
depth += 1;
}
Ok(XmlEvent::EndElement { name }) => {
depth -= 1;
println!("{}-{}", indent(depth), name);
}
Err(e) => {
println!("Error: {}", e);
break;
}
_ => {}
}
}
}
|
// MinIO Rust Library for Amazon S3 Compatible Cloud Storage
// Copyright 2022 MinIO, Inc.
//
// 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 crate::s3::args::*;
use crate::s3::creds::Provider;
use crate::s3::error::{Error, ErrorResponse};
use crate::s3::http::{BaseUrl, Url};
use crate::s3::response::*;
use crate::s3::signer::{presign_v4, sign_v4_s3};
use crate::s3::sse::SseCustomerKey;
use crate::s3::types::{
Bucket, DeleteObject, Directive, Item, LifecycleConfig, NotificationConfig,
NotificationRecords, ObjectLockConfig, Part, ReplicationConfig, RetentionMode, SseConfig,
};
use crate::s3::utils::{
from_iso8601utc, get_default_text, get_option_text, get_text, md5sum_hash, merge, sha256_hash,
to_amz_date, to_iso8601utc, urldecode, utc_now, Multimap,
};
use async_recursion::async_recursion;
use bytes::{Buf, Bytes};
use dashmap::DashMap;
use hyper::http::Method;
use reqwest::header::HeaderMap;
use std::collections::{HashMap, VecDeque};
use std::fs::File;
use std::io::prelude::*;
use std::io::Read;
use xmltree::Element;
fn url_decode(
encoding_type: &Option<String>,
prefix: Option<String>,
) -> Result<Option<String>, Error> {
if let Some(v) = encoding_type.as_ref() {
if v == "url" {
if let Some(v) = prefix {
return Ok(Some(urldecode(&v)?.to_string()));
}
}
}
if let Some(v) = prefix.as_ref() {
return Ok(Some(v.to_string()));
}
return Ok(None);
}
fn add_common_list_objects_query_params(
query_params: &mut Multimap,
delimiter: Option<&str>,
encoding_type: Option<&str>,
max_keys: Option<u16>,
prefix: Option<&str>,
) {
query_params.insert(
String::from("delimiter"),
delimiter.unwrap_or("").to_string(),
);
query_params.insert(
String::from("max-keys"),
max_keys.unwrap_or(1000).to_string(),
);
query_params.insert(String::from("prefix"), prefix.unwrap_or("").to_string());
if let Some(v) = encoding_type {
query_params.insert(String::from("encoding-type"), v.to_string());
}
}
fn parse_common_list_objects_response(
root: &Element,
) -> Result<
(
String,
Option<String>,
Option<String>,
Option<String>,
bool,
Option<u16>,
),
Error,
> {
let encoding_type = get_option_text(&root, "EncodingType");
let prefix = url_decode(&encoding_type, Some(get_default_text(&root, "Prefix")))?;
Ok((
get_text(&root, "Name")?,
encoding_type,
prefix,
get_option_text(&root, "Delimiter"),
match get_option_text(&root, "IsTruncated") {
Some(v) => v.to_lowercase() == "true",
None => false,
},
match get_option_text(&root, "MaxKeys") {
Some(v) => Some(v.parse::<u16>()?),
None => None,
},
))
}
fn parse_list_objects_contents(
contents: &mut Vec<Item>,
root: &mut xmltree::Element,
tag: &str,
encoding_type: &Option<String>,
is_delete_marker: bool,
) -> Result<(), Error> {
loop {
let content = match root.take_child(tag) {
Some(v) => v,
None => break,
};
let etype = encoding_type.as_ref().map(|v| v.clone());
let key = url_decode(&etype, Some(get_text(&content, "Key")?))?.unwrap();
let last_modified = Some(from_iso8601utc(&get_text(&content, "LastModified")?)?);
let etag = get_option_text(&content, "ETag");
let v = get_default_text(&content, "Size");
let size = match v.is_empty() {
true => None,
false => Some(v.parse::<usize>()?),
};
let storage_class = get_option_text(&content, "StorageClass");
let is_latest = get_default_text(&content, "IsLatest").to_lowercase() == "true";
let version_id = get_option_text(&content, "VersionId");
let (owner_id, owner_name) = match content.get_child("Owner") {
Some(v) => (
get_option_text(&v, "ID"),
get_option_text(&v, "DisplayName"),
),
None => (None, None),
};
let user_metadata = match content.get_child("UserMetadata") {
Some(v) => {
let mut map: HashMap<String, String> = HashMap::new();
for xml_node in &v.children {
let u = xml_node
.as_element()
.ok_or(Error::XmlError(format!("unable to convert to element")))?;
map.insert(
u.name.to_string(),
u.get_text().unwrap_or_default().to_string(),
);
}
Some(map)
}
None => None,
};
contents.push(Item {
name: key,
last_modified: last_modified,
etag: etag,
owner_id: owner_id,
owner_name: owner_name,
size: size,
storage_class: storage_class,
is_latest: is_latest,
version_id: version_id,
user_metadata: user_metadata,
is_prefix: false,
is_delete_marker: is_delete_marker,
encoding_type: etype,
});
}
Ok(())
}
fn parse_list_objects_common_prefixes(
contents: &mut Vec<Item>,
root: &mut Element,
encoding_type: &Option<String>,
) -> Result<(), Error> {
loop {
let common_prefix = match root.take_child("CommonPrefixes") {
Some(v) => v,
None => break,
};
contents.push(Item {
name: url_decode(&encoding_type, Some(get_text(&common_prefix, "Prefix")?))?.unwrap(),
last_modified: None,
etag: None,
owner_id: None,
owner_name: None,
size: None,
storage_class: None,
is_latest: false,
version_id: None,
user_metadata: None,
is_prefix: true,
is_delete_marker: false,
encoding_type: encoding_type.as_ref().map(|v| v.clone()),
});
}
Ok(())
}
#[derive(Clone, Debug, Default)]
pub struct Client<'a> {
base_url: BaseUrl,
provider: Option<&'a (dyn Provider + Send + Sync)>,
pub ssl_cert_file: String,
pub ignore_cert_check: bool,
pub user_agent: String,
region_map: DashMap<String, String>,
debug: bool,
}
impl<'a> Client<'a> {
pub fn new(base_url: BaseUrl, provider: Option<&(dyn Provider + Send + Sync)>) -> Client {
Client {
base_url: base_url,
provider: provider,
ssl_cert_file: String::new(),
ignore_cert_check: false,
user_agent: String::new(),
region_map: DashMap::new(),
debug: false,
}
}
fn build_headers(
&self,
headers: &mut Multimap,
query_params: &Multimap,
region: &String,
url: &Url,
method: &Method,
data: &[u8],
) {
headers.insert(String::from("Host"), url.host_header_value());
headers.insert(
String::from("User-Agent"),
String::from("MinIO (Linux; x86_64) minio-rs/0.1.0"),
);
let mut md5sum = String::new();
let mut sha256 = String::new();
match *method {
Method::PUT | Method::POST => {
headers.insert(String::from("Content-Length"), data.len().to_string());
if !headers.contains_key("Content-Type") {
headers.insert(
String::from("Content-Type"),
String::from("application/octet-stream"),
);
}
if self.provider.is_some() {
sha256 = sha256_hash(data);
} else if !headers.contains_key("Content-MD5") {
md5sum = md5sum_hash(data);
}
}
_ => {
if self.provider.is_some() {
sha256 = String::from(
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
);
}
}
};
if !md5sum.is_empty() {
headers.insert(String::from("Content-MD5"), md5sum);
}
if !sha256.is_empty() {
headers.insert(String::from("x-amz-content-sha256"), sha256.clone());
}
let date = utc_now();
headers.insert(String::from("x-amz-date"), to_amz_date(date));
if let Some(p) = self.provider {
let creds = p.fetch();
if creds.session_token.is_some() {
headers.insert(
String::from("X-Amz-Security-Token"),
creds.session_token.unwrap(),
);
}
sign_v4_s3(
&method,
&url.path,
region,
headers,
query_params,
&creds.access_key,
&creds.secret_key,
&sha256,
date,
);
}
}
fn handle_redirect_response(
&self,
status_code: u16,
method: &Method,
header_map: &reqwest::header::HeaderMap,
bucket_name: Option<&str>,
retry: bool,
) -> Result<(String, String), Error> {
let (mut code, mut message) = match status_code {
301 => (
String::from("PermanentRedirect"),
String::from("Moved Permanently"),
),
307 => (String::from("Redirect"), String::from("Temporary redirect")),
400 => (String::from("BadRequest"), String::from("Bad request")),
_ => (String::new(), String::new()),
};
let region = match header_map.get("x-amz-bucket-region") {
Some(v) => v.to_str()?,
_ => "",
};
if !message.is_empty() && !region.is_empty() {
message.push_str("; use region ");
message.push_str(region);
}
if retry && !region.is_empty() && method == Method::HEAD {
if let Some(v) = bucket_name {
if self.region_map.contains_key(v) {
code = String::from("RetryHead");
message = String::new();
}
}
}
return Ok((code, message));
}
fn get_error_response(
&self,
body: &mut Bytes,
status_code: u16,
header_map: &reqwest::header::HeaderMap,
method: &Method,
resource: &str,
bucket_name: Option<&str>,
object_name: Option<&str>,
retry: bool,
) -> Error {
if body.len() > 0 {
return match header_map.get("Content-Type") {
Some(v) => match v.to_str() {
Ok(s) => match s.to_lowercase().contains("application/xml") {
true => match ErrorResponse::parse(body) {
Ok(v) => Error::S3Error(v),
Err(e) => e,
},
false => Error::InvalidResponse(status_code, s.to_string()),
},
Err(e) => return Error::StrError(e),
},
_ => Error::InvalidResponse(status_code, String::new()),
};
}
let (code, message) = match status_code {
301 | 307 | 400 => match self.handle_redirect_response(
status_code,
method,
header_map,
bucket_name,
retry,
) {
Ok(v) => v,
Err(e) => return e,
},
403 => (String::from("AccessDenied"), String::from("Access denied")),
404 => match object_name {
Some(_) => (
String::from("NoSuchKey"),
String::from("Object does not exist"),
),
_ => match bucket_name {
Some(_) => (
String::from("NoSuchBucket"),
String::from("Bucket does not exist"),
),
_ => (
String::from("ResourceNotFound"),
String::from("Request resource not found"),
),
},
},
405 => (
String::from("MethodNotAllowed"),
String::from("The specified method is not allowed against this resource"),
),
409 => match bucket_name {
Some(_) => (
String::from("NoSuchBucket"),
String::from("Bucket does not exist"),
),
_ => (
String::from("ResourceConflict"),
String::from("Request resource conflicts"),
),
},
501 => (
String::from("MethodNotAllowed"),
String::from("The specified method is not allowed against this resource"),
),
_ => return Error::ServerError(status_code),
};
let request_id = match header_map.get("x-amz-request-id") {
Some(v) => match v.to_str() {
Ok(s) => s.to_string(),
Err(e) => return Error::StrError(e),
},
_ => String::new(),
};
let host_id = match header_map.get("x-amz-id-2") {
Some(v) => match v.to_str() {
Ok(s) => s.to_string(),
Err(e) => return Error::StrError(e),
},
_ => String::new(),
};
Error::S3Error(ErrorResponse {
code: code,
message: message,
resource: resource.to_string(),
request_id: request_id,
host_id: host_id,
bucket_name: bucket_name.unwrap_or_default().to_string(),
object_name: object_name.unwrap_or_default().to_string(),
})
}
pub async fn do_execute(
&self,
method: Method,
region: &String,
headers: &mut Multimap,
query_params: &Multimap,
bucket_name: Option<&str>,
object_name: Option<&str>,
data: Option<&[u8]>,
retry: bool,
) -> Result<reqwest::Response, Error> {
let body = data.unwrap_or_default();
let url =
self.base_url
.build_url(&method, region, query_params, bucket_name, object_name)?;
self.build_headers(headers, query_params, region, &url, &method, body);
let mut builder = reqwest::Client::builder().no_gzip();
if self.ignore_cert_check {
builder = builder.danger_accept_invalid_certs(self.ignore_cert_check);
}
if !self.ssl_cert_file.is_empty() {
let mut buf = Vec::new();
File::open(self.ssl_cert_file.to_string())?.read_to_end(&mut buf)?;
let cert = reqwest::Certificate::from_pem(&buf)?;
builder = builder.add_root_certificate(cert);
}
let client = builder.build()?;
let mut req = client.request(method.clone(), url.to_string());
for (key, values) in headers.iter_all() {
for value in values {
req = req.header(key, value);
}
}
if method == Method::PUT || method == Method::POST {
req = req.body(body.to_vec());
}
let resp = req.send().await?;
if resp.status().is_success() {
return Ok(resp);
}
let status_code = resp.status().as_u16();
let header_map = resp.headers().clone();
let mut body = resp.bytes().await?;
let e = self.get_error_response(
&mut body,
status_code,
&header_map,
&method,
&url.path,
bucket_name,
object_name,
retry,
);
match e {
Error::S3Error(ref er) => {
if er.code == "NoSuchBucket" || er.code == "RetryHead" {
if let Some(v) = bucket_name {
self.region_map.remove(v);
}
}
}
_ => return Err(e),
};
return Err(e);
}
pub async fn execute(
&self,
method: Method,
region: &String,
headers: &mut Multimap,
query_params: &Multimap,
bucket_name: Option<&str>,
object_name: Option<&str>,
data: Option<&[u8]>,
) -> Result<reqwest::Response, Error> {
let res = self
.do_execute(
method.clone(),
region,
headers,
query_params,
bucket_name,
object_name,
data,
true,
)
.await;
match res {
Ok(r) => return Ok(r),
Err(e) => match e {
Error::S3Error(ref er) => {
if er.code != "RetryHead" {
return Err(e);
}
}
_ => return Err(e),
},
};
// Retry only once on RetryHead error.
self.do_execute(
method.clone(),
region,
headers,
query_params,
bucket_name,
object_name,
data,
false,
)
.await
}
pub async fn get_region(
&self,
bucket_name: &str,
region: Option<&str>,
) -> Result<String, Error> {
if !region.map_or(true, |v| v.is_empty()) {
if !self.base_url.region.is_empty() && self.base_url.region != *region.unwrap() {
return Err(Error::RegionMismatch(
self.base_url.region.clone(),
region.unwrap().to_string(),
));
}
return Ok(region.unwrap().to_string());
}
if !self.base_url.region.is_empty() {
return Ok(self.base_url.region.clone());
}
if bucket_name.is_empty() || self.provider.is_none() {
return Ok(String::from("us-east-1"));
}
if let Some(v) = self.region_map.get(bucket_name) {
return Ok((*v).to_string());
}
let mut headers = Multimap::new();
let mut query_params = Multimap::new();
query_params.insert(String::from("location"), String::new());
let resp = self
.execute(
Method::GET,
&String::from("us-east-1"),
&mut headers,
&query_params,
Some(bucket_name),
None,
None,
)
.await?;
let body = resp.bytes().await?;
let root = Element::parse(body.reader())?;
let mut location = root.get_text().unwrap_or_default().to_string();
if location.is_empty() {
location = String::from("us-east-1");
}
self.region_map
.insert(bucket_name.to_string(), location.clone());
Ok(location)
}
pub async fn abort_multipart_upload(
&self,
args: &AbortMultipartUploadArgs<'_>,
) -> Result<AbortMultipartUploadResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("uploadId"), args.upload_id.to_string());
let resp = self
.execute(
Method::DELETE,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
None,
)
.await?;
Ok(AbortMultipartUploadResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
upload_id: args.upload_id.to_string(),
})
}
pub async fn bucket_exists(&self, args: &BucketExistsArgs<'_>) -> Result<bool, Error> {
let region;
match self.get_region(&args.bucket, args.region).await {
Ok(r) => region = r,
Err(e) => match e {
Error::S3Error(ref er) => {
if er.code == "NoSuchBucket" {
return Ok(false);
}
return Err(e);
}
_ => return Err(e),
},
};
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = &Multimap::new();
if let Some(v) = &args.extra_query_params {
query_params = v;
}
match self
.execute(
Method::HEAD,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await
{
Ok(_) => Ok(true),
Err(e) => match e {
Error::S3Error(ref er) => {
if er.code == "NoSuchBucket" {
return Ok(false);
}
return Err(e);
}
_ => return Err(e),
},
}
}
pub async fn complete_multipart_upload(
&self,
args: &CompleteMultipartUploadArgs<'_>,
) -> Result<CompleteMultipartUploadResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut data = String::from("<CompleteMultipartUpload>");
for part in args.parts.iter() {
let s = format!(
"<Part><PartNumber>{}</PartNumber><ETag>{}</ETag></Part>",
part.number, part.etag
);
data.push_str(&s);
}
data.push_str("</CompleteMultipartUpload>");
let b = data.as_bytes();
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
headers.insert(
String::from("Content-Type"),
String::from("application/xml"),
);
headers.insert(String::from("Content-MD5"), md5sum_hash(b));
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("uploadId"), args.upload_id.to_string());
let resp = self
.execute(
Method::POST,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
Some(&b),
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let root = Element::parse(body.reader())?;
Ok(CompleteMultipartUploadResponse {
headers: header_map.clone(),
bucket_name: get_text(&root, "Bucket")?,
object_name: get_text(&root, "Key")?,
location: get_text(&root, "Location")?,
etag: get_text(&root, "ETag")?.trim_matches('"').to_string(),
version_id: match header_map.get("x-amz-version-id") {
Some(v) => Some(v.to_str()?.to_string()),
None => None,
},
})
}
async fn calculate_part_count(
&self,
sources: &'a mut Vec<ComposeSource<'_>>,
) -> Result<u16, Error> {
let mut object_size = 0_usize;
let mut i = 0;
let mut part_count = 0_u16;
let sources_len = sources.len();
for source in sources.iter_mut() {
if source.ssec.is_some() && !self.base_url.https {
return Err(Error::SseTlsRequired(Some(format!(
"source {}/{}{}: ",
source.bucket,
source.object,
source
.version_id
.as_ref()
.map_or(String::new(), |v| String::from("?versionId=") + v)
))));
}
i += 1;
let mut stat_args = StatObjectArgs::new(source.bucket, source.object)?;
stat_args.extra_headers = source.extra_headers;
stat_args.extra_query_params = source.extra_query_params;
stat_args.region = source.region;
stat_args.version_id = source.version_id;
stat_args.ssec = source.ssec;
stat_args.match_etag = source.match_etag;
stat_args.not_match_etag = source.not_match_etag;
stat_args.modified_since = source.modified_since;
stat_args.unmodified_since = source.unmodified_since;
let stat_resp = self.stat_object(&stat_args).await?;
source.build_headers(stat_resp.size, stat_resp.etag.clone())?;
let mut size = stat_resp.size;
if let Some(l) = source.length {
size = l;
} else if let Some(o) = source.offset {
size -= o;
}
if size < MIN_PART_SIZE && sources_len != 1 && i != sources_len {
return Err(Error::InvalidComposeSourcePartSize(
source.bucket.to_string(),
source.object.to_string(),
source.version_id.map(|v| v.to_string()),
size,
MIN_PART_SIZE,
));
}
object_size += size;
if object_size > MAX_OBJECT_SIZE {
return Err(Error::InvalidObjectSize(object_size));
}
if size > MAX_PART_SIZE {
let mut count = size / MAX_PART_SIZE;
let mut last_part_size = size - (count * MAX_PART_SIZE);
if last_part_size > 0 {
count += 1;
} else {
last_part_size = MAX_PART_SIZE;
}
if last_part_size < MIN_PART_SIZE && sources_len != 1 && i != sources_len {
return Err(Error::InvalidComposeSourceMultipart(
source.bucket.to_string(),
source.object.to_string(),
source.version_id.map(|v| v.to_string()),
size,
MIN_PART_SIZE,
));
}
part_count += count as u16;
} else {
part_count += 1;
}
if part_count > MAX_MULTIPART_COUNT {
return Err(Error::InvalidMultipartCount(MAX_MULTIPART_COUNT));
}
}
return Ok(part_count);
}
#[async_recursion(?Send)]
pub async fn do_compose_object(
&self,
args: &mut ComposeObjectArgs<'_>,
upload_id: &mut String,
) -> Result<ComposeObjectResponse, Error> {
let part_count = self.calculate_part_count(&mut args.sources).await?;
if part_count == 1 && args.sources[0].offset.is_none() && args.sources[0].length.is_none() {
let mut source =
ObjectConditionalReadArgs::new(args.sources[0].bucket, args.sources[0].object)?;
source.extra_headers = args.sources[0].extra_headers;
source.extra_query_params = args.sources[0].extra_query_params;
source.region = args.sources[0].region;
source.version_id = args.sources[0].version_id;
source.ssec = args.sources[0].ssec;
source.match_etag = args.sources[0].match_etag;
source.not_match_etag = args.sources[0].not_match_etag;
source.modified_since = args.sources[0].modified_since;
source.unmodified_since = args.sources[0].unmodified_since;
let mut coargs = CopyObjectArgs::new(args.bucket, args.object, source)?;
coargs.extra_headers = args.extra_headers;
coargs.extra_query_params = args.extra_query_params;
coargs.region = args.region;
coargs.headers = args.headers;
coargs.user_metadata = args.user_metadata;
coargs.sse = args.sse;
coargs.tags = args.tags;
coargs.retention = args.retention;
coargs.legal_hold = args.legal_hold;
return self.copy_object(&coargs).await;
}
let headers = args.get_headers();
let mut cmu_args = CreateMultipartUploadArgs::new(args.bucket, args.object)?;
cmu_args.extra_query_params = args.extra_query_params;
cmu_args.region = args.region;
cmu_args.headers = Some(&headers);
let resp = self.create_multipart_upload(&cmu_args).await?;
upload_id.push_str(&resp.upload_id);
let mut part_number = 0_u16;
let ssec_headers = match args.sse {
Some(v) => match v.as_any().downcast_ref::<SseCustomerKey>() {
Some(_) => v.headers(),
_ => Multimap::new(),
},
_ => Multimap::new(),
};
let mut parts: Vec<Part> = Vec::new();
for source in args.sources.iter() {
let mut size = source.get_object_size();
if let Some(l) = source.length {
size = l;
} else if let Some(o) = source.offset {
size -= o;
}
let mut offset = source.offset.unwrap_or_default();
let mut headers = source.get_headers();
merge(&mut headers, &ssec_headers);
if size <= MAX_PART_SIZE {
part_number += 1;
if let Some(l) = source.length {
headers.insert(
String::from("x-amz-copy-source-range"),
format!("bytes={}-{}", offset, offset + l - 1),
);
} else if source.offset.is_some() {
headers.insert(
String::from("x-amz-copy-source-range"),
format!("bytes={}-{}", offset, offset + size - 1),
);
}
let mut upc_args = UploadPartCopyArgs::new(
args.bucket,
args.object,
upload_id,
part_number,
headers,
)?;
upc_args.region = args.region;
let resp = self.upload_part_copy(&upc_args).await?;
parts.push(Part {
number: part_number,
etag: resp.etag,
});
} else {
while size > 0 {
part_number += 1;
let start_bytes = offset;
let mut end_bytes = start_bytes + MAX_PART_SIZE;
if size < MAX_PART_SIZE {
end_bytes = start_bytes + size;
}
let mut headers_copy = headers.clone();
headers_copy.insert(
String::from("x-amz-copy-source-range"),
format!("bytes={}-{}", start_bytes, end_bytes),
);
let mut upc_args = UploadPartCopyArgs::new(
args.bucket,
args.object,
upload_id,
part_number,
headers_copy,
)?;
upc_args.region = args.region;
let resp = self.upload_part_copy(&upc_args).await?;
parts.push(Part {
number: part_number,
etag: resp.etag,
});
offset = start_bytes;
size -= end_bytes - start_bytes;
}
}
}
let mut cmu_args =
CompleteMultipartUploadArgs::new(args.bucket, args.object, upload_id, &parts)?;
cmu_args.region = args.region;
return self.complete_multipart_upload(&cmu_args).await;
}
pub async fn compose_object(
&self,
args: &mut ComposeObjectArgs<'_>,
) -> Result<ComposeObjectResponse, Error> {
if let Some(v) = &args.sse {
if v.tls_required() && !self.base_url.https {
return Err(Error::SseTlsRequired(None));
}
}
let mut upload_id = String::new();
let res = self.do_compose_object(args, &mut upload_id).await;
if res.is_err() && !upload_id.is_empty() {
let amuargs = &AbortMultipartUploadArgs::new(&args.bucket, &args.object, &upload_id)?;
self.abort_multipart_upload(&amuargs).await?;
}
return res;
}
pub async fn copy_object(
&self,
args: &CopyObjectArgs<'_>,
) -> Result<CopyObjectResponse, Error> {
if let Some(v) = &args.sse {
if v.tls_required() && !self.base_url.https {
return Err(Error::SseTlsRequired(None));
}
}
if args.source.ssec.is_some() && !self.base_url.https {
return Err(Error::SseTlsRequired(None));
}
let stat_resp = self.stat_object(&args.source).await?;
if args.source.offset.is_some()
|| args.source.length.is_some()
|| stat_resp.size > MAX_PART_SIZE
{
if let Some(v) = &args.metadata_directive {
match v {
Directive::Copy => return Err(Error::InvalidCopyDirective(String::from("COPY metadata directive is not applicable to source object size greater than 5 GiB"))),
_ => todo!(), // Nothing to do.
}
}
if let Some(v) = &args.tagging_directive {
match v {
Directive::Copy => return Err(Error::InvalidCopyDirective(String::from("COPY tagging directive is not applicable to source object size greater than 5 GiB"))),
_ => todo!(), // Nothing to do.
}
}
let mut src = ComposeSource::new(args.source.bucket, args.source.object)?;
src.extra_headers = args.source.extra_headers;
src.extra_query_params = args.source.extra_query_params;
src.region = args.source.region;
src.ssec = args.source.ssec;
src.offset = args.source.offset;
src.length = args.source.length;
src.match_etag = args.source.match_etag;
src.not_match_etag = args.source.not_match_etag;
src.modified_since = args.source.modified_since;
src.unmodified_since = args.source.unmodified_since;
let mut sources: Vec<ComposeSource> = Vec::new();
sources.push(src);
let mut coargs = ComposeObjectArgs::new(args.bucket, args.object, &mut sources)?;
coargs.extra_headers = args.extra_headers;
coargs.extra_query_params = args.extra_query_params;
coargs.region = args.region;
coargs.headers = args.headers;
coargs.user_metadata = args.user_metadata;
coargs.sse = args.sse;
coargs.tags = args.tags;
coargs.retention = args.retention;
coargs.legal_hold = args.legal_hold;
return self.compose_object(&mut coargs).await;
}
let mut headers = args.get_headers();
if let Some(v) = &args.metadata_directive {
headers.insert(String::from("x-amz-metadata-directive"), v.to_string());
}
if let Some(v) = &args.tagging_directive {
headers.insert(String::from("x-amz-tagging-directive"), v.to_string());
}
merge(&mut headers, &args.source.get_copy_headers());
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
let region = self.get_region(&args.bucket, args.region).await?;
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let root = Element::parse(body.reader())?;
Ok(CopyObjectResponse {
headers: header_map.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
location: region.clone(),
etag: get_text(&root, "ETag")?.trim_matches('"').to_string(),
version_id: match header_map.get("x-amz-version-id") {
Some(v) => Some(v.to_str()?.to_string()),
None => None,
},
})
}
pub async fn create_multipart_upload(
&self,
args: &CreateMultipartUploadArgs<'_>,
) -> Result<CreateMultipartUploadResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
if !headers.contains_key("Content-Type") {
headers.insert(
String::from("Content-Type"),
String::from("application/octet-stream"),
);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("uploads"), String::new());
let resp = self
.execute(
Method::POST,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let root = Element::parse(body.reader())?;
Ok(CreateMultipartUploadResponse {
headers: header_map.clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
upload_id: get_text(&root, "UploadId")?,
})
}
pub async fn delete_bucket_encryption(
&self,
args: &DeleteBucketEncryptionArgs<'_>,
) -> Result<DeleteBucketEncryptionResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("encryption"), String::new());
match self
.execute(
Method::DELETE,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await
{
Ok(resp) => Ok(DeleteBucketEncryptionResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
}),
Err(e) => match e {
Error::S3Error(ref err) => {
if err.code == "ServerSideEncryptionConfigurationNotFoundError" {
return Ok(DeleteBucketEncryptionResponse {
headers: HeaderMap::new(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
});
}
return Err(e);
}
_ => return Err(e),
},
}
}
pub async fn disable_object_legal_hold(
&self,
args: &DisableObjectLegalHoldArgs<'_>,
) -> Result<DisableObjectLegalHoldResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.version_id {
query_params.insert(String::from("versionId"), v.to_string());
}
query_params.insert(String::from("legal-hold"), String::new());
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
Some(b"<LegalHold><Status>OFF</Status></LegalHold>"),
)
.await?;
Ok(DisableObjectLegalHoldResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: args.version_id.as_ref().map(|v| v.to_string()),
})
}
pub async fn delete_bucket_lifecycle(
&self,
args: &DeleteBucketLifecycleArgs<'_>,
) -> Result<DeleteBucketLifecycleResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("lifecycle"), String::new());
let resp = self
.execute(
Method::DELETE,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await?;
Ok(DeleteBucketLifecycleResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
})
}
pub async fn delete_bucket_notification(
&self,
args: &DeleteBucketNotificationArgs<'_>,
) -> Result<DeleteBucketNotificationResponse, Error> {
self.set_bucket_notification(&SetBucketNotificationArgs {
extra_headers: args.extra_headers,
extra_query_params: args.extra_query_params,
region: args.region,
bucket: args.bucket,
config: &NotificationConfig {
cloud_func_config_list: None,
queue_config_list: None,
topic_config_list: None,
},
})
.await
}
pub async fn delete_bucket_policy(
&self,
args: &DeleteBucketPolicyArgs<'_>,
) -> Result<DeleteBucketPolicyResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("policy"), String::new());
match self
.execute(
Method::DELETE,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await
{
Ok(resp) => Ok(DeleteBucketPolicyResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
}),
Err(e) => match e {
Error::S3Error(ref err) => {
if err.code == "NoSuchBucketPolicy" {
return Ok(DeleteBucketPolicyResponse {
headers: HeaderMap::new(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
});
}
return Err(e);
}
_ => return Err(e),
},
}
}
pub async fn delete_bucket_replication(
&self,
args: &DeleteBucketReplicationArgs<'_>,
) -> Result<DeleteBucketReplicationResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("replication"), String::new());
match self
.execute(
Method::DELETE,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await
{
Ok(resp) => Ok(DeleteBucketReplicationResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
}),
Err(e) => match e {
Error::S3Error(ref err) => {
if err.code == "ReplicationConfigurationNotFoundError" {
return Ok(DeleteBucketReplicationResponse {
headers: HeaderMap::new(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
});
}
return Err(e);
}
_ => return Err(e),
},
}
}
pub async fn delete_bucket_tags(
&self,
args: &DeleteBucketTagsArgs<'_>,
) -> Result<DeleteBucketTagsResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("tagging"), String::new());
let resp = self
.execute(
Method::DELETE,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await?;
Ok(DeleteBucketTagsResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
})
}
pub async fn delete_object_lock_config(
&self,
args: &DeleteObjectLockConfigArgs<'_>,
) -> Result<DeleteObjectLockConfigResponse, Error> {
self.set_object_lock_config(&SetObjectLockConfigArgs {
extra_headers: args.extra_headers,
extra_query_params: args.extra_query_params,
region: args.region,
bucket: args.bucket,
config: &ObjectLockConfig {
retention_mode: None,
retention_duration_days: None,
retention_duration_years: None,
},
})
.await
}
pub async fn delete_object_tags(
&self,
args: &DeleteObjectTagsArgs<'_>,
) -> Result<DeleteObjectTagsResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.version_id {
query_params.insert(String::from("versionId"), v.to_string());
}
query_params.insert(String::from("tagging"), String::new());
let resp = self
.execute(
Method::DELETE,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
None,
)
.await?;
Ok(DeleteObjectTagsResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: args.version_id.as_ref().map(|v| v.to_string()),
})
}
pub async fn download_object(
&self,
args: &DownloadObjectArgs<'_>,
) -> Result<DownloadObjectResponse, Error> {
let mut resp = self
.get_object(&GetObjectArgs {
extra_headers: args.extra_headers,
extra_query_params: args.extra_query_params,
region: args.region,
bucket: args.bucket,
object: args.object,
version_id: args.version_id,
ssec: args.ssec,
offset: None,
length: None,
match_etag: None,
not_match_etag: None,
modified_since: None,
unmodified_since: None,
})
.await?;
let mut file = match args.overwrite {
true => File::create(args.filename)?,
false => File::options()
.write(true)
.truncate(true)
.create_new(true)
.open(args.filename)?,
};
while let Some(v) = resp.chunk().await? {
file.write_all(&v)?;
}
file.sync_all()?;
Ok(DownloadObjectResponse {
headers: resp.headers().clone(),
region: args.region.map_or(String::new(), |v| String::from(v)),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: args.version_id.as_ref().map(|v| v.to_string()),
})
}
pub async fn enable_object_legal_hold(
&self,
args: &EnableObjectLegalHoldArgs<'_>,
) -> Result<EnableObjectLegalHoldResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.version_id {
query_params.insert(String::from("versionId"), v.to_string());
}
query_params.insert(String::from("legal-hold"), String::new());
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
Some(b"<LegalHold><Status>ON</Status></LegalHold>"),
)
.await?;
Ok(EnableObjectLegalHoldResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: args.version_id.as_ref().map(|v| v.to_string()),
})
}
pub async fn get_bucket_encryption(
&self,
args: &GetBucketEncryptionArgs<'_>,
) -> Result<GetBucketEncryptionResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("encryption"), String::new());
let resp = self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let mut root = Element::parse(body.reader())?;
let rule = root
.get_mut_child("Rule")
.ok_or(Error::XmlError(String::from("<Rule> tag not found")))?;
let sse_by_default = rule
.get_mut_child("ApplyServerSideEncryptionByDefault")
.ok_or(Error::XmlError(String::from(
"<ApplyServerSideEncryptionByDefault> tag not found",
)))?;
Ok(GetBucketEncryptionResponse {
headers: header_map.clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
config: SseConfig {
sse_algorithm: get_text(sse_by_default, "SSEAlgorithm")?,
kms_master_key_id: get_option_text(sse_by_default, "KMSMasterKeyID"),
},
})
}
pub async fn get_bucket_lifecycle(
&self,
args: &GetBucketLifecycleArgs<'_>,
) -> Result<GetBucketLifecycleResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("lifecycle"), String::new());
match self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await
{
Ok(resp) => {
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let root = Element::parse(body.reader())?;
return Ok(GetBucketLifecycleResponse {
headers: header_map.clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
config: LifecycleConfig::from_xml(&root)?,
});
}
Err(e) => match e {
Error::S3Error(ref err) => {
if err.code == "NoSuchLifecycleConfiguration" {
return Ok(GetBucketLifecycleResponse {
headers: HeaderMap::new(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
config: LifecycleConfig { rules: Vec::new() },
});
}
return Err(e);
}
_ => return Err(e),
},
}
}
pub async fn get_bucket_notification(
&self,
args: &GetBucketNotificationArgs<'_>,
) -> Result<GetBucketNotificationResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("notification"), String::new());
let resp = self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let mut root = Element::parse(body.reader())?;
return Ok(GetBucketNotificationResponse {
headers: header_map.clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
config: NotificationConfig::from_xml(&mut root)?,
});
}
pub async fn get_bucket_policy(
&self,
args: &GetBucketPolicyArgs<'_>,
) -> Result<GetBucketPolicyResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("policy"), String::new());
match self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await
{
Ok(resp) => {
return Ok(GetBucketPolicyResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
config: resp.text().await?,
})
}
Err(e) => match e {
Error::S3Error(ref err) => {
if err.code == "NoSuchBucketPolicy" {
return Ok(GetBucketPolicyResponse {
headers: HeaderMap::new(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
config: String::from("{}"),
});
}
return Err(e);
}
_ => return Err(e),
},
}
}
pub async fn get_bucket_replication(
&self,
args: &GetBucketReplicationArgs<'_>,
) -> Result<GetBucketReplicationResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("replication"), String::new());
let resp = self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let root = Element::parse(body.reader())?;
return Ok(GetBucketReplicationResponse {
headers: header_map.clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
config: ReplicationConfig::from_xml(&root)?,
});
}
pub async fn get_bucket_tags(
&self,
args: &GetBucketTagsArgs<'_>,
) -> Result<GetBucketTagsResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("tagging"), String::new());
match self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await
{
Ok(resp) => {
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let mut root = Element::parse(body.reader())?;
let element = root
.get_mut_child("TagSet")
.ok_or(Error::XmlError(format!("<TagSet> tag not found")))?;
let mut tags = std::collections::HashMap::new();
loop {
match element.take_child("Tag") {
Some(v) => tags.insert(get_text(&v, "Key")?, get_text(&v, "Value")?),
_ => break,
};
}
return Ok(GetBucketTagsResponse {
headers: header_map.clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
tags: tags,
});
}
Err(e) => match e {
Error::S3Error(ref err) => {
if err.code == "NoSuchTagSet" {
return Ok(GetBucketTagsResponse {
headers: HeaderMap::new(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
tags: HashMap::new(),
});
}
return Err(e);
}
_ => return Err(e),
},
}
}
pub async fn get_bucket_versioning(
&self,
args: &GetBucketVersioningArgs<'_>,
) -> Result<GetBucketVersioningResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("versioning"), String::new());
let resp = self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let root = Element::parse(body.reader())?;
return Ok(GetBucketVersioningResponse {
headers: header_map.clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
status: get_option_text(&root, "Status").map(|v| v == "Enabled"),
mfa_delete: get_option_text(&root, "MFADelete").map(|v| v == "Enabled"),
});
}
pub async fn get_object(&self, args: &GetObjectArgs<'_>) -> Result<reqwest::Response, Error> {
if args.ssec.is_some() && !self.base_url.https {
return Err(Error::SseTlsRequired(None));
}
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
merge(&mut headers, &args.get_headers());
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.version_id {
query_params.insert(String::from("versionId"), v.to_string());
}
self.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
None,
)
.await
}
pub async fn get_object_lock_config(
&self,
args: &GetObjectLockConfigArgs<'_>,
) -> Result<GetObjectLockConfigResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("object-lock"), String::new());
let resp = self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let root = Element::parse(body.reader())?;
return Ok(GetObjectLockConfigResponse {
headers: header_map.clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
config: ObjectLockConfig::from_xml(&root)?,
});
}
pub async fn get_object_retention(
&self,
args: &GetObjectRetentionArgs<'_>,
) -> Result<GetObjectRetentionResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.version_id {
query_params.insert(String::from("versionId"), v.to_string());
}
query_params.insert(String::from("retention"), String::new());
match self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
None,
)
.await
{
Ok(resp) => {
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let root = Element::parse(body.reader())?;
return Ok(GetObjectRetentionResponse {
headers: header_map.clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: args.version_id.as_ref().map(|v| v.to_string()),
retention_mode: match get_option_text(&root, "Mode") {
Some(v) => Some(RetentionMode::parse(&v)?),
_ => None,
},
retain_until_date: match get_option_text(&root, "RetainUntilDate") {
Some(v) => Some(from_iso8601utc(&v)?),
_ => None,
},
});
}
Err(e) => match e {
Error::S3Error(ref err) => {
if err.code == "NoSuchObjectLockConfiguration" {
return Ok(GetObjectRetentionResponse {
headers: HeaderMap::new(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: args.version_id.as_ref().map(|v| v.to_string()),
retention_mode: None,
retain_until_date: None,
});
}
return Err(e);
}
_ => return Err(e),
},
}
}
pub async fn get_object_tags(
&self,
args: &GetObjectTagsArgs<'_>,
) -> Result<GetObjectTagsResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.version_id {
query_params.insert(String::from("versionId"), v.to_string());
}
query_params.insert(String::from("tagging"), String::new());
let resp = self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let mut root = Element::parse(body.reader())?;
let element = root
.get_mut_child("TagSet")
.ok_or(Error::XmlError(format!("<TagSet> tag not found")))?;
let mut tags = std::collections::HashMap::new();
loop {
match element.take_child("Tag") {
Some(v) => tags.insert(get_text(&v, "Key")?, get_text(&v, "Value")?),
_ => break,
};
}
return Ok(GetObjectTagsResponse {
headers: header_map.clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: args.version_id.as_ref().map(|v| v.to_string()),
tags: tags,
});
}
pub async fn get_presigned_object_url(
&self,
args: &GetPresignedObjectUrlArgs<'_>,
) -> Result<GetPresignedObjectUrlResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.version_id {
query_params.insert(String::from("versionId"), v.to_string());
}
let mut url = self.base_url.build_url(
&args.method,
®ion,
&query_params,
Some(args.bucket),
Some(args.object),
)?;
if let Some(p) = self.provider {
let creds = p.fetch();
if let Some(t) = creds.session_token {
query_params.insert(String::from("X-Amz-Security-Token"), t);
}
let date = match args.request_time {
Some(v) => v,
_ => utc_now(),
};
presign_v4(
&args.method,
&url.host,
&url.path,
®ion,
&mut query_params,
&creds.access_key,
&creds.secret_key,
date,
args.expiry_seconds.unwrap_or(DEFAULT_EXPIRY_SECONDS),
);
url.query = query_params;
}
return Ok(GetPresignedObjectUrlResponse {
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: args.version_id.as_ref().map(|v| v.to_string()),
url: url.to_string(),
});
}
pub async fn get_presigned_post_form_data(
&self,
policy: &PostPolicy<'_>,
) -> Result<HashMap<String, String>, Error> {
if self.provider.is_none() {
return Err(Error::PostPolicyError(format!(
"anonymous access does not require presigned post form-data"
)));
}
let region = self.get_region(&policy.bucket, policy.region).await?;
let creds = self.provider.unwrap().fetch();
policy.form_data(
creds.access_key,
creds.secret_key,
creds.session_token,
region,
)
}
pub async fn is_object_legal_hold_enabled(
&self,
args: &IsObjectLegalHoldEnabledArgs<'_>,
) -> Result<IsObjectLegalHoldEnabledResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.version_id {
query_params.insert(String::from("versionId"), v.to_string());
}
query_params.insert(String::from("legal-hold"), String::new());
match self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
None,
)
.await
{
Ok(resp) => {
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let root = Element::parse(body.reader())?;
Ok(IsObjectLegalHoldEnabledResponse {
headers: header_map.clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: args.version_id.as_ref().map(|v| v.to_string()),
enabled: get_default_text(&root, "Status") == "ON",
})
}
Err(e) => match e {
Error::S3Error(ref err) => {
if err.code == "NoSuchObjectLockConfiguration" {
return Ok(IsObjectLegalHoldEnabledResponse {
headers: HeaderMap::new(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: args.version_id.as_ref().map(|v| v.to_string()),
enabled: false,
});
}
return Err(e);
}
_ => return Err(e),
},
}
}
pub async fn list_buckets(
&self,
args: &ListBucketsArgs<'_>,
) -> Result<ListBucketsResponse, Error> {
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = &Multimap::new();
if let Some(v) = &args.extra_query_params {
query_params = v;
}
let resp = self
.execute(
Method::GET,
&String::from("us-east-1"),
&mut headers,
&query_params,
None,
None,
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let mut root = Element::parse(body.reader())?;
let buckets = root
.get_mut_child("Buckets")
.ok_or(Error::XmlError(String::from("<Buckets> tag not found")))?;
let mut bucket_list: Vec<Bucket> = Vec::new();
loop {
let bucket = match buckets.take_child("Bucket") {
Some(b) => b,
None => break,
};
bucket_list.push(Bucket {
name: get_text(&bucket, "Name")?,
creation_date: from_iso8601utc(&get_text(&bucket, "CreationDate")?)?,
})
}
Ok(ListBucketsResponse {
headers: header_map.clone(),
buckets: bucket_list,
})
}
pub async fn listen_bucket_notification(
&self,
args: &ListenBucketNotificationArgs<'_>,
) -> Result<ListenBucketNotificationResponse, Error> {
if self.base_url.aws_host {
return Err(Error::UnsupportedApi(String::from(
"ListenBucketNotification",
)));
}
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.prefix {
query_params.insert(String::from("prefix"), v.to_string());
}
if let Some(v) = args.suffix {
query_params.insert(String::from("suffix"), v.to_string());
}
if let Some(v) = &args.events {
for e in v.iter() {
query_params.insert(String::from("events"), e.to_string());
}
} else {
query_params.insert(String::from("events"), String::from("s3:ObjectCreated:*"));
query_params.insert(String::from("events"), String::from("s3:ObjectRemoved:*"));
query_params.insert(String::from("events"), String::from("s3:ObjectAccessed:*"));
}
let mut resp = self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await?;
let header_map = resp.headers().clone();
let mut done = false;
let mut buf = VecDeque::<u8>::new();
while !done {
let chunk = match resp.chunk().await? {
Some(v) => v,
None => {
done = true;
Bytes::new()
}
};
buf.extend(chunk.iter().copied());
while !done {
match buf.iter().position(|&v| v == '\n' as u8) {
Some(i) => {
let mut data = vec![0_u8; i + 1];
for j in 0..=i {
data[j] = buf.pop_front().ok_or(Error::InsufficientData(i, j))?;
}
let mut line = String::from_utf8(data)?;
line = line.trim().to_string();
if !line.is_empty() {
let records: NotificationRecords = serde_json::from_str(&line)?;
done = !(args.event_fn)(records);
}
}
None => break,
};
}
}
Ok(ListenBucketNotificationResponse::new(
header_map,
®ion,
&args.bucket,
))
}
pub async fn list_objects_v1(
&self,
args: &ListObjectsV1Args<'_>,
) -> Result<ListObjectsV1Response, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
add_common_list_objects_query_params(
&mut query_params,
args.delimiter,
args.encoding_type,
args.max_keys,
args.prefix,
);
if let Some(v) = &args.marker {
query_params.insert(String::from("marker"), v.to_string());
}
let resp = self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let mut root = Element::parse(body.reader())?;
let (name, encoding_type, prefix, delimiter, is_truncated, max_keys) =
parse_common_list_objects_response(&root)?;
let marker = url_decode(&encoding_type, get_option_text(&root, "Marker"))?;
let mut next_marker = url_decode(&encoding_type, get_option_text(&root, "NextMarker"))?;
let mut contents: Vec<Item> = Vec::new();
parse_list_objects_contents(&mut contents, &mut root, "Contents", &encoding_type, false)?;
if is_truncated && next_marker.is_none() {
next_marker = match contents.last() {
Some(v) => Some(v.name.clone()),
None => None,
}
}
parse_list_objects_common_prefixes(&mut contents, &mut root, &encoding_type)?;
Ok(ListObjectsV1Response {
headers: header_map,
name: name,
encoding_type: encoding_type,
prefix: prefix,
delimiter: delimiter,
is_truncated: is_truncated,
max_keys: max_keys,
contents: contents,
marker: marker,
next_marker: next_marker,
})
}
pub async fn list_objects_v2(
&self,
args: &ListObjectsV2Args<'_>,
) -> Result<ListObjectsV2Response, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("list-type"), String::from("2"));
add_common_list_objects_query_params(
&mut query_params,
args.delimiter,
args.encoding_type,
args.max_keys,
args.prefix,
);
if let Some(v) = &args.continuation_token {
query_params.insert(String::from("continuation-token"), v.to_string());
}
if args.fetch_owner {
query_params.insert(String::from("fetch-owner"), String::from("true"));
}
if let Some(v) = &args.start_after {
query_params.insert(String::from("start-after"), v.to_string());
}
if args.include_user_metadata {
query_params.insert(String::from("metadata"), String::from("true"));
}
let resp = self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let mut root = Element::parse(body.reader())?;
let (name, encoding_type, prefix, delimiter, is_truncated, max_keys) =
parse_common_list_objects_response(&root)?;
let text = get_option_text(&root, "KeyCount");
let key_count = match text {
Some(v) => match v.is_empty() {
true => None,
false => Some(v.parse::<u16>()?),
},
None => None,
};
let start_after = url_decode(&encoding_type, get_option_text(&root, "StartAfter"))?;
let continuation_token = get_option_text(&root, "ContinuationToken");
let next_continuation_token = get_option_text(&root, "NextContinuationToken");
let mut contents: Vec<Item> = Vec::new();
parse_list_objects_contents(&mut contents, &mut root, "Contents", &encoding_type, false)?;
parse_list_objects_common_prefixes(&mut contents, &mut root, &encoding_type)?;
Ok(ListObjectsV2Response {
headers: header_map,
name: name,
encoding_type: encoding_type,
prefix: prefix,
delimiter: delimiter,
is_truncated: is_truncated,
max_keys: max_keys,
contents: contents,
key_count: key_count,
start_after: start_after,
continuation_token: continuation_token,
next_continuation_token: next_continuation_token,
})
}
pub async fn list_object_versions(
&self,
args: &ListObjectVersionsArgs<'_>,
) -> Result<ListObjectVersionsResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("versions"), String::new());
add_common_list_objects_query_params(
&mut query_params,
args.delimiter,
args.encoding_type,
args.max_keys,
args.prefix,
);
if let Some(v) = &args.key_marker {
query_params.insert(String::from("key-marker"), v.to_string());
}
if let Some(v) = &args.version_id_marker {
query_params.insert(String::from("version-id-marker"), v.to_string());
}
let resp = self
.execute(
Method::GET,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let mut root = Element::parse(body.reader())?;
let (name, encoding_type, prefix, delimiter, is_truncated, max_keys) =
parse_common_list_objects_response(&root)?;
let key_marker = url_decode(&encoding_type, get_option_text(&root, "KeyMarker"))?;
let next_key_marker = url_decode(&encoding_type, get_option_text(&root, "NextKeyMarker"))?;
let version_id_marker = get_option_text(&root, "VersionIdMarker");
let next_version_id_marker = get_option_text(&root, "NextVersionIdMarker");
let mut contents: Vec<Item> = Vec::new();
parse_list_objects_contents(&mut contents, &mut root, "Version", &encoding_type, false)?;
parse_list_objects_common_prefixes(&mut contents, &mut root, &encoding_type)?;
parse_list_objects_contents(
&mut contents,
&mut root,
"DeleteMarker",
&encoding_type,
true,
)?;
Ok(ListObjectVersionsResponse {
headers: header_map,
name: name,
encoding_type: encoding_type,
prefix: prefix,
delimiter: delimiter,
is_truncated: is_truncated,
max_keys: max_keys,
contents: contents,
key_marker: key_marker,
next_key_marker: next_key_marker,
version_id_marker: version_id_marker,
next_version_id_marker: next_version_id_marker,
})
}
pub async fn list_objects(&self, args: &ListObjectsArgs<'_>) -> Result<(), Error> {
let mut lov1_args = ListObjectsV1Args::new(&args.bucket)?;
lov1_args.extra_headers = args.extra_headers;
lov1_args.extra_query_params = args.extra_query_params;
lov1_args.region = args.region;
if args.recursive {
lov1_args.delimiter = None;
} else {
lov1_args.delimiter = Some(args.delimiter.unwrap_or("/"));
}
lov1_args.encoding_type = match args.use_url_encoding_type {
true => Some("url"),
false => None,
};
lov1_args.max_keys = args.max_keys;
lov1_args.prefix = args.prefix;
lov1_args.marker = args.marker.map(|x| x.to_string());
let mut lov2_args = ListObjectsV2Args::new(&args.bucket)?;
lov2_args.extra_headers = args.extra_headers;
lov2_args.extra_query_params = args.extra_query_params;
lov2_args.region = args.region;
if args.recursive {
lov2_args.delimiter = None;
} else {
lov2_args.delimiter = Some(args.delimiter.unwrap_or("/"));
}
lov2_args.encoding_type = match args.use_url_encoding_type {
true => Some("url"),
false => None,
};
lov2_args.max_keys = args.max_keys;
lov2_args.prefix = args.prefix;
lov2_args.start_after = args.start_after.map(|x| x.to_string());
lov2_args.continuation_token = args.continuation_token.map(|x| x.to_string());
lov2_args.fetch_owner = args.fetch_owner;
lov2_args.include_user_metadata = args.include_user_metadata;
let mut lov_args = ListObjectVersionsArgs::new(&args.bucket)?;
lov_args.extra_headers = args.extra_headers;
lov_args.extra_query_params = args.extra_query_params;
lov_args.region = args.region;
if args.recursive {
lov_args.delimiter = None;
} else {
lov_args.delimiter = Some(args.delimiter.unwrap_or("/"));
}
lov_args.encoding_type = match args.use_url_encoding_type {
true => Some("url"),
false => None,
};
lov_args.max_keys = args.max_keys;
lov_args.prefix = args.prefix;
lov_args.key_marker = args.key_marker.map(|x| x.to_string());
lov_args.version_id_marker = args.version_id_marker.map(|x| x.to_string());
let mut stop = false;
while !stop {
if args.include_versions {
let resp = self.list_object_versions(&lov_args).await?;
stop = !resp.is_truncated;
if resp.is_truncated {
lov_args.key_marker = resp.next_key_marker;
lov_args.version_id_marker = resp.next_version_id_marker;
}
stop = stop || !(args.result_fn)(resp.contents);
} else if args.use_api_v1 {
let resp = self.list_objects_v1(&lov1_args).await?;
stop = !resp.is_truncated;
if resp.is_truncated {
lov1_args.marker = resp.next_marker;
}
stop = stop || !(args.result_fn)(resp.contents);
} else {
let resp = self.list_objects_v2(&lov2_args).await?;
stop = !resp.is_truncated;
if resp.is_truncated {
lov2_args.start_after = resp.start_after;
lov2_args.continuation_token = resp.next_continuation_token;
}
stop = stop || !(args.result_fn)(resp.contents);
}
}
Ok(())
}
pub async fn make_bucket(
&self,
args: &MakeBucketArgs<'_>,
) -> Result<MakeBucketResponse, Error> {
let mut region = "us-east-1";
if let Some(r) = &args.region {
if !self.base_url.region.is_empty() {
if self.base_url.region != *r {
return Err(Error::RegionMismatch(
self.base_url.region.clone(),
r.to_string(),
));
}
region = r;
}
}
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
};
if args.object_lock {
headers.insert(
String::from("x-amz-bucket-object-lock-enabled"),
String::from("true"),
);
}
let mut query_params = &Multimap::new();
if let Some(v) = &args.extra_query_params {
query_params = v;
}
let data = match region {
"us-east-1" => String::new(),
_ => format!("<CreateBucketConfiguration><LocationConstraint>{}</LocationConstraint></CreateBucketConfiguration>", region),
};
let body = match data.is_empty() {
true => None,
false => Some(data.as_bytes()),
};
let resp = self
.execute(
Method::PUT,
®ion.to_string(),
&mut headers,
&query_params,
Some(&args.bucket),
None,
body,
)
.await?;
self.region_map
.insert(args.bucket.to_string(), region.to_string());
Ok(MakeBucketResponse {
headers: resp.headers().clone(),
region: region.to_string(),
bucket_name: args.bucket.to_string(),
})
}
fn read_part(
reader: &mut dyn std::io::Read,
buf: &mut [u8],
size: usize,
) -> Result<usize, Error> {
let mut bytes_read = 0_usize;
let mut i = 0_usize;
let mut stop = false;
while !stop {
let br = reader.read(&mut buf[i..size])?;
bytes_read += br;
stop = (br == 0) || (br == size - i);
i += br;
}
Ok(bytes_read)
}
async fn do_put_object(
&self,
args: &mut PutObjectArgs<'_>,
buf: &mut [u8],
upload_id: &mut String,
) -> Result<PutObjectResponse, Error> {
let mut headers = args.get_headers();
if !headers.contains_key("Content-Type") {
if args.content_type.is_empty() {
headers.insert(
String::from("Content-Type"),
String::from("application/octet-stream"),
);
} else {
headers.insert(String::from("Content-Type"), args.content_type.to_string());
}
}
let mut uploaded_size = 0_usize;
let mut part_number = 0_i16;
let mut stop = false;
let mut one_byte: Vec<u8> = Vec::new();
let mut parts: Vec<Part> = Vec::new();
let object_size = &args.object_size.unwrap();
let mut part_size = args.part_size;
let mut part_count = args.part_count;
while !stop {
part_number += 1;
let mut bytes_read = 0_usize;
if args.part_count > 0 {
if part_number == args.part_count {
part_size = object_size - uploaded_size;
stop = true;
}
bytes_read = Client::read_part(&mut args.stream, buf, part_size)?;
if bytes_read != part_size {
return Err(Error::InsufficientData(part_size, bytes_read));
}
} else {
let mut size = part_size + 1;
let mut newbuf = match one_byte.len() == 1 {
true => {
buf[0] = one_byte.pop().unwrap();
size -= 1;
bytes_read = 1;
&mut buf[1..]
}
false => buf,
};
let n = Client::read_part(&mut args.stream, &mut newbuf, size)?;
bytes_read += n;
// If bytes read is less than or equals to part size, then we have reached last part.
if bytes_read <= part_size {
part_count = part_number;
part_size = bytes_read;
stop = true;
} else {
one_byte.push(buf[part_size + 1]);
}
}
let data = &buf[0..part_size];
uploaded_size += part_size;
if part_count == 1_i16 {
let mut poaargs = PutObjectApiArgs::new(&args.bucket, &args.object, &data)?;
poaargs.extra_query_params = args.extra_query_params;
poaargs.region = args.region;
poaargs.headers = Some(&headers);
return self.put_object_api(&poaargs).await;
}
if upload_id.is_empty() {
let mut cmuargs = CreateMultipartUploadArgs::new(&args.bucket, &args.object)?;
cmuargs.extra_query_params = args.extra_query_params;
cmuargs.region = args.region;
cmuargs.headers = Some(&headers);
let resp = self.create_multipart_upload(&cmuargs).await?;
upload_id.push_str(&resp.upload_id);
}
let mut upargs = UploadPartArgs::new(
&args.bucket,
&args.object,
&upload_id,
part_number as u16,
&data,
)?;
upargs.region = args.region;
let ssec_headers = match args.sse {
Some(v) => match v.as_any().downcast_ref::<SseCustomerKey>() {
Some(_) => v.headers(),
_ => Multimap::new(),
},
_ => Multimap::new(),
};
upargs.headers = Some(&ssec_headers);
let resp = self.upload_part(&upargs).await?;
parts.push(Part {
number: part_number as u16,
etag: resp.etag.clone(),
});
}
let mut cmuargs =
CompleteMultipartUploadArgs::new(&args.bucket, &args.object, &upload_id, &parts)?;
cmuargs.region = args.region;
return self.complete_multipart_upload(&cmuargs).await;
}
pub async fn put_object(
&self,
args: &mut PutObjectArgs<'_>,
) -> Result<PutObjectResponse, Error> {
if let Some(v) = &args.sse {
if v.tls_required() && !self.base_url.https {
return Err(Error::SseTlsRequired(None));
}
}
let bufsize = match args.part_count > 0 {
true => args.part_size as usize,
false => (args.part_size as usize) + 1,
};
let mut buf = vec![0_u8; bufsize];
let mut upload_id = String::new();
let res = self.do_put_object(args, &mut buf, &mut upload_id).await;
std::mem::drop(buf);
if res.is_err() && !upload_id.is_empty() {
let amuargs = &AbortMultipartUploadArgs::new(&args.bucket, &args.object, &upload_id)?;
self.abort_multipart_upload(&amuargs).await?;
}
return res;
}
pub async fn put_object_api(
&self,
args: &PutObjectApiArgs<'_>,
) -> Result<PutObjectApiResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = args.get_headers();
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = &args.query_params {
merge(&mut query_params, v);
}
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
Some(&args.data),
)
.await?;
let header_map = resp.headers();
Ok(PutObjectBaseResponse {
headers: header_map.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
location: region.clone(),
etag: match header_map.get("etag") {
Some(v) => v.to_str()?.to_string().trim_matches('"').to_string(),
_ => String::new(),
},
version_id: match header_map.get("x-amz-version-id") {
Some(v) => Some(v.to_str()?.to_string()),
None => None,
},
})
}
pub async fn remove_bucket(
&self,
args: &RemoveBucketArgs<'_>,
) -> Result<RemoveBucketResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = &Multimap::new();
if let Some(v) = &args.extra_query_params {
query_params = v;
}
let resp = self
.execute(
Method::DELETE,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
None,
)
.await?;
self.region_map.remove(&args.bucket.to_string());
Ok(RemoveBucketResponse {
headers: resp.headers().clone(),
region: region.to_string(),
bucket_name: args.bucket.to_string(),
})
}
pub async fn remove_object(
&self,
args: &RemoveObjectArgs<'_>,
) -> Result<RemoveObjectResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.version_id {
query_params.insert(String::from("versionId"), v.to_string());
}
let resp = self
.execute(
Method::DELETE,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
None,
)
.await?;
Ok(RemoveObjectResponse {
headers: resp.headers().clone(),
region: region.to_string(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: match args.version_id {
Some(v) => Some(v.to_string()),
None => None,
},
})
}
pub async fn remove_objects_api(
&self,
args: &RemoveObjectsApiArgs<'_>,
) -> Result<RemoveObjectsApiResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut data = String::from("<Delete>");
if args.quiet {
data.push_str("<Quiet>true</Quiet>");
}
for object in args.objects.iter() {
data.push_str("<Object>");
data.push_str("<Key>");
data.push_str(&object.name);
data.push_str("</Key>");
if let Some(v) = object.version_id {
data.push_str("<VersionId>");
data.push_str(&v);
data.push_str("</VersionId>");
}
data.push_str("</Object>");
}
data.push_str("</Delete>");
let b = data.as_bytes();
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
if args.bypass_governance_mode {
headers.insert(
String::from("x-amz-bypass-governance-retention"),
String::from("true"),
);
}
headers.insert(
String::from("Content-Type"),
String::from("application/xml"),
);
headers.insert(String::from("Content-MD5"), md5sum_hash(b));
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("delete"), String::new());
let resp = self
.execute(
Method::POST,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
Some(&b),
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let mut root = Element::parse(body.reader())?;
let mut objects: Vec<DeletedObject> = Vec::new();
loop {
let deleted = match root.take_child("Deleted") {
Some(v) => v,
None => break,
};
objects.push(DeletedObject {
name: get_text(&deleted, "Key")?,
version_id: get_option_text(&deleted, "VersionId"),
delete_marker: get_text(&deleted, "DeleteMarker")?.to_lowercase() == "true",
delete_marker_version_id: get_option_text(&deleted, "DeleteMarkerVersionId"),
})
}
let mut errors: Vec<DeleteError> = Vec::new();
loop {
let error = match root.take_child("Error") {
Some(v) => v,
None => break,
};
errors.push(DeleteError {
code: get_text(&error, "Code")?,
message: get_text(&error, "Message")?,
object_name: get_text(&error, "Key")?,
version_id: get_option_text(&error, "VersionId"),
})
}
Ok(RemoveObjectsApiResponse {
headers: header_map.clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
objects: objects,
errors: errors,
})
}
pub async fn remove_objects(
&self,
args: &mut RemoveObjectsArgs<'_>,
) -> Result<RemoveObjectsResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
loop {
let mut objects: Vec<DeleteObject> = Vec::new();
for object in args.objects.take(1000) {
objects.push(*object);
}
if objects.len() == 0 {
break;
}
let mut roa_args = RemoveObjectsApiArgs::new(&args.bucket, &objects)?;
roa_args.extra_headers = args.extra_headers;
roa_args.extra_query_params = args.extra_query_params;
roa_args.region = args.region;
roa_args.bypass_governance_mode = args.bypass_governance_mode;
roa_args.quiet = true;
let resp = self.remove_objects_api(&roa_args).await?;
if resp.errors.len() > 0 {
return Ok(resp);
}
}
Ok(RemoveObjectsResponse {
headers: HeaderMap::new(),
region: region.to_string(),
bucket_name: args.bucket.to_string(),
objects: vec![],
errors: vec![],
})
}
pub async fn set_bucket_encryption(
&self,
args: &SetBucketEncryptionArgs<'_>,
) -> Result<SetBucketEncryptionResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("encryption"), String::new());
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
Some(args.config.to_xml().as_bytes()),
)
.await?;
Ok(SetBucketEncryptionResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
})
}
pub async fn set_bucket_lifecycle(
&self,
args: &SetBucketLifecycleArgs<'_>,
) -> Result<SetBucketLifecycleResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("lifecycle"), String::new());
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
Some(args.config.to_xml().as_bytes()),
)
.await?;
Ok(SetBucketLifecycleResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
})
}
pub async fn set_bucket_notification(
&self,
args: &SetBucketNotificationArgs<'_>,
) -> Result<SetBucketNotificationResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("notification"), String::new());
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
Some(args.config.to_xml().as_bytes()),
)
.await?;
Ok(SetBucketNotificationResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
})
}
pub async fn set_bucket_policy(
&self,
args: &SetBucketPolicyArgs<'_>,
) -> Result<SetBucketPolicyResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("policy"), String::new());
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
Some(args.config.as_bytes()),
)
.await?;
Ok(SetBucketPolicyResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
})
}
pub async fn set_bucket_replication(
&self,
args: &SetBucketReplicationArgs<'_>,
) -> Result<SetBucketReplicationResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("replication"), String::new());
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
Some(args.config.to_xml().as_bytes()),
)
.await?;
Ok(SetBucketReplicationResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
})
}
pub async fn set_bucket_tags(
&self,
args: &SetBucketTagsArgs<'_>,
) -> Result<SetBucketTagsResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("tagging"), String::new());
let mut data = String::from("<Tagging>");
if !args.tags.is_empty() {
data.push_str("<TagSet>");
for (key, value) in args.tags.iter() {
data.push_str("<Tag>");
data.push_str("<Key>");
data.push_str(&key);
data.push_str("</Key>");
data.push_str("<Value>");
data.push_str(&value);
data.push_str("</Value>");
data.push_str("</Tag>");
}
data.push_str("</TagSet>");
}
data.push_str("</Tagging>");
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
Some(data.as_bytes()),
)
.await?;
Ok(SetBucketTagsResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
})
}
pub async fn set_bucket_versioning(
&self,
args: &SetBucketVersioningArgs<'_>,
) -> Result<SetBucketVersioningResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("versioning"), String::new());
let mut data = String::from("<VersioningConfiguration>");
data.push_str("<Status>");
data.push_str(match args.status {
true => "Enabled",
false => "Suspended",
});
data.push_str("</Status>");
if let Some(v) = args.mfa_delete {
data.push_str("<MFADelete>");
data.push_str(match v {
true => "Enabled",
false => "Disabled",
});
data.push_str("</MFADelete>");
}
data.push_str("</VersioningConfiguration>");
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
Some(data.as_bytes()),
)
.await?;
Ok(SetBucketVersioningResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
})
}
pub async fn set_object_lock_config(
&self,
args: &SetObjectLockConfigArgs<'_>,
) -> Result<SetObjectLockConfigResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("object-lock"), String::new());
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
None,
Some(args.config.to_xml().as_bytes()),
)
.await?;
Ok(SetObjectLockConfigResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
})
}
pub async fn set_object_retention(
&self,
args: &SetObjectRetentionArgs<'_>,
) -> Result<SetObjectRetentionResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
if args.bypass_governance_mode {
headers.insert(
String::from("x-amz-bypass-governance-retention"),
String::from("true"),
);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.version_id {
query_params.insert(String::from("versionId"), v.to_string());
}
query_params.insert(String::from("retention"), String::new());
let mut data = String::from("<Retention>");
if let Some(v) = &args.retention_mode {
data.push_str("<Mode>");
data.push_str(&v.to_string());
data.push_str("</Mode>");
}
if let Some(v) = &args.retain_until_date {
data.push_str("<RetainUntilDate>");
data.push_str(&to_iso8601utc(*v));
data.push_str("</RetainUntilDate>");
}
data.push_str("</Retention>");
headers.insert(String::from("Content-MD5"), md5sum_hash(&data.as_bytes()));
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
Some(data.as_bytes()),
)
.await?;
Ok(SetObjectRetentionResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: args.version_id.as_ref().map(|v| v.to_string()),
})
}
pub async fn set_object_tags(
&self,
args: &SetObjectTagsArgs<'_>,
) -> Result<SetObjectTagsResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.version_id {
query_params.insert(String::from("versionId"), v.to_string());
}
query_params.insert(String::from("tagging"), String::new());
let mut data = String::from("<Tagging>");
if !args.tags.is_empty() {
data.push_str("<TagSet>");
for (key, value) in args.tags.iter() {
data.push_str("<Tag>");
data.push_str("<Key>");
data.push_str(&key);
data.push_str("</Key>");
data.push_str("<Value>");
data.push_str(&value);
data.push_str("</Value>");
data.push_str("</Tag>");
}
data.push_str("</TagSet>");
}
data.push_str("</Tagging>");
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
Some(data.as_bytes()),
)
.await?;
Ok(SetObjectTagsResponse {
headers: resp.headers().clone(),
region: region.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
version_id: args.version_id.as_ref().map(|v| v.to_string()),
})
}
pub async fn select_object_content(
&self,
args: &SelectObjectContentArgs<'_>,
) -> Result<SelectObjectContentResponse, Error> {
if args.ssec.is_some() && !self.base_url.https {
return Err(Error::SseTlsRequired(None));
}
let region = self.get_region(&args.bucket, args.region).await?;
let data = args.request.to_xml();
let b = data.as_bytes();
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
headers.insert(String::from("Content-MD5"), md5sum_hash(&b));
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("select"), String::new());
query_params.insert(String::from("select-type"), String::from("2"));
Ok(SelectObjectContentResponse::new(
self.execute(
Method::POST,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
Some(&b),
)
.await?,
®ion,
&args.bucket,
&args.object,
))
}
pub async fn stat_object(
&self,
args: &StatObjectArgs<'_>,
) -> Result<StatObjectResponse, Error> {
if args.ssec.is_some() && !self.base_url.https {
return Err(Error::SseTlsRequired(None));
}
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
merge(&mut headers, &args.get_headers());
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
if let Some(v) = args.version_id {
query_params.insert(String::from("versionId"), v.to_string());
}
let resp = self
.execute(
Method::HEAD,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
None,
)
.await?;
StatObjectResponse::new(&resp.headers(), ®ion, &args.bucket, &args.object)
}
pub async fn upload_object(
&self,
args: &UploadObjectArgs<'_>,
) -> Result<UploadObjectResponse, Error> {
let mut file = File::open(args.filename)?;
self.put_object(&mut PutObjectArgs {
extra_headers: args.extra_headers,
extra_query_params: args.extra_query_params,
region: args.region,
bucket: args.bucket,
object: args.object,
headers: args.headers,
user_metadata: args.user_metadata,
sse: args.sse,
tags: args.tags,
retention: args.retention,
legal_hold: args.legal_hold,
object_size: args.object_size,
part_size: args.part_size,
part_count: args.part_count,
content_type: args.content_type,
stream: &mut file,
})
.await
}
pub async fn upload_part(
&self,
args: &UploadPartArgs<'_>,
) -> Result<UploadPartResponse, Error> {
let mut query_params = Multimap::new();
query_params.insert(String::from("partNumber"), args.part_number.to_string());
query_params.insert(String::from("uploadId"), args.upload_id.to_string());
let mut poa_args = PutObjectApiArgs::new(&args.bucket, &args.object, &args.data)?;
poa_args.query_params = Some(&query_params);
poa_args.extra_headers = args.extra_headers;
poa_args.extra_query_params = args.extra_query_params;
poa_args.region = args.region;
poa_args.headers = args.headers;
poa_args.user_metadata = args.user_metadata;
poa_args.sse = args.sse;
poa_args.tags = args.tags;
poa_args.retention = args.retention;
poa_args.legal_hold = args.legal_hold;
self.put_object_api(&poa_args).await
}
pub async fn upload_part_copy(
&self,
args: &UploadPartCopyArgs<'_>,
) -> Result<UploadPartCopyResponse, Error> {
let region = self.get_region(&args.bucket, args.region).await?;
let mut headers = Multimap::new();
if let Some(v) = &args.extra_headers {
merge(&mut headers, v);
}
merge(&mut headers, &args.headers);
let mut query_params = Multimap::new();
if let Some(v) = &args.extra_query_params {
merge(&mut query_params, v);
}
query_params.insert(String::from("partNumber"), args.part_number.to_string());
query_params.insert(String::from("uploadId"), args.upload_id.to_string());
let resp = self
.execute(
Method::PUT,
®ion,
&mut headers,
&query_params,
Some(&args.bucket),
Some(&args.object),
None,
)
.await?;
let header_map = resp.headers().clone();
let body = resp.bytes().await?;
let root = Element::parse(body.reader())?;
Ok(PutObjectBaseResponse {
headers: header_map.clone(),
bucket_name: args.bucket.to_string(),
object_name: args.object.to_string(),
location: region.clone(),
etag: get_text(&root, "ETag")?.trim_matches('"').to_string(),
version_id: None,
})
}
}
|
pub enum Action {
List,
Clone,
Pull,
Checkout,
MirrorPull,
MirrorPush,
}
impl Action {
pub fn from(input: &str) -> Result<Action, &str> {
let action = match input {
"list" => Action::List,
"clone" => Action::Clone,
"pull" => Action::Pull,
"checkout" => Action::Checkout,
"mirror_pull" => Action::MirrorPull,
"mirror_push" => Action::MirrorPush,
_ => return Err(input)
};
Ok(action)
}
}
|
use crate::*;
use num_derive::FromPrimitive;
use num_traits::FromPrimitive;
#[derive(PartialEq, Eq, Hash, Clone, Debug, Serialize, Deserialize)]
pub struct ScoreId(HashSha256, PlayMode);
impl ScoreId {
pub fn new(sha256: HashSha256, mode: PlayMode) -> ScoreId {
ScoreId(sha256, mode)
}
pub fn sha256(&self) -> HashSha256 {
self.0.clone()
}
pub fn mode(&self) -> PlayMode {
self.1.clone()
}
}
#[derive(Eq, PartialEq, Hash, Clone, Debug, Serialize, Deserialize, Default)]
pub struct PlayMode(LnMode);
impl PlayMode {
pub fn to_int(&self) -> i32 {
self.0 as i32
}
}
impl From<i32> for PlayMode {
fn from(mode: i32) -> Self {
let lm = match FromPrimitive::from_i32(mode % 10) {
Some(lm) => lm,
None => LnMode::Long,
};
PlayMode(lm)
}
}
#[derive(Eq, PartialEq, Hash, Copy, Clone, Debug, Serialize, Deserialize, FromPrimitive)]
pub enum LnMode {
Long = 0,
Charge = 1,
HellCharge = 2,
}
impl Default for LnMode {
fn default() -> LnMode {
LnMode::Long
}
}
|
use std::mem::uninitialized;
/// Estimates the Shannon entropy of the given byte buffer, which must be less
/// than or equal to 65536 bytes long.
pub fn entropy_estimate(src: &[u8]) -> f64 {
assert!(src.len() < 65536);
let mut probabilities: [u16; 256] = unsafe { uninitialized() };
for n in 0..256 { probabilities[n] = 0 }
for byt in src {
probabilities[*byt as usize] += 1;
}
let float_len = src.len() as f64;
probabilities.iter()
.map(|&x| if x == 0 { 0.0 }
else {(x as f64 / float_len).log2() * x as f64})
.fold(0.0, |a,e| a - e)
}
#[cfg(test)]
mod tests {
use super::entropy_estimate;
#[test]
fn simple_entropies() {
assert_eq!(entropy_estimate(b"AAAAAAAAAAAAAAAAAAAA"), 0.0);
assert_eq!(entropy_estimate(b"ABAABBAAABBBAAAABBBB"), 20.0);
assert_eq!(entropy_estimate(b"ABCCBACCCCABABCCCABC"), 30.0);
}
}
|
use actix_web::actix::Addr;
use crate::filestore::{FileNode, FileStore};
use crate::model::db::Database;
use crate::model::{
member::Member,
project::{CreateProject, Project, ProjectById, ProjectMembers},
user::{User, UserById, UserProjects},
};
use futures::Future;
use juniper::Context;
use juniper::RootNode;
use juniper::{FieldError, FieldResult};
use std::path::Path;
use uuid::Uuid;
pub struct SchemaContext {
pub current_user: Option<User>,
pub db_addr: Addr<Database>,
}
impl Context for SchemaContext {}
pub type Schema = RootNode<'static, QueryRoot, MutationRoot>;
pub fn create_schema() -> Schema {
Schema::new(QueryRoot {}, MutationRoot {})
}
graphql_object!(User: SchemaContext |&self| {
description: "An User"
field id() -> String as "The unique id of the user" {
self.id.hyphenated().to_string()
}
field name() -> &str as "The user username" {
&self.username
}
field projects(&executor) -> FieldResult<Vec<Project>> {
match executor
.context()
.db_addr
.send(UserProjects{user: self.clone()})
.wait()
.unwrap() {
Ok(projects) => Ok(projects),
Err(_e) => Err(FieldError::new(
"Could not get Project",
graphql_value!({ "internal_error": ""})
)),
}
}
});
graphql_object!(Project: SchemaContext |&self| {
description: "A Project"
field id() -> String as "The unique id of the project" {
self.id.hyphenated().to_string()
}
field name() -> &str as "The project name" {
&self.name
}
field members(&executor) -> FieldResult<Vec<Member>> as "Project members" {
match executor
.context()
.db_addr
.send(ProjectMembers{project: self.clone()})
.wait()
.unwrap() {
Ok(members) => Ok(members),
Err(_e) => Err(FieldError::new(
"Could not get members for project",
graphql_value!({ "internal_error": ""})
)),
}
}
field files(&executor) -> Vec<FileNode> as "Project files" {
FileStore::dir(&FileStore::project_root(self.id))
}
});
graphql_object!(FileNode: SchemaContext |&self| {
description: ""
field name() -> String as "File name" {
self.name.clone()
}
field path() -> String as "File path" {
self.path.clone()
}
field extension() -> Option<String> as "File extension" {
self.extension.clone()
}
field children() -> Vec<FileNode> as "File extension" {
match self.children.clone() {
Some(c) => c,
None => vec![],
}
}
field isDir() -> bool as "Is a directory?" {
self.is_dir
}
});
#[derive(GraphQLEnum, Copy, Clone, Eq, PartialEq, Debug)]
pub enum Permission {
Read,
Write,
Owner,
}
graphql_object!(Member: SchemaContext |&self| {
description: "A Member"
field user(&executor) -> FieldResult<User> as "The user" {
match executor
.context()
.db_addr
.send(UserById{user_id: self.user_id.to_string()})
.wait()
.unwrap() {
Ok(project) => Ok(project),
Err(_e) => Err(FieldError::new(
"Could not get User",
graphql_value!({ "internal_error": ""})
)),
}
}
field project(&executor) -> FieldResult<Project> as "The project" {
match executor
.context()
.db_addr
.send(ProjectById{project_id: self.project_id.to_string()})
.wait()
.unwrap() {
Ok(project) => Ok(project),
Err(_e) => Err(FieldError::new(
"Could not get Project",
graphql_value!({ "internal_error": ""})
)),
}
}
field permission() -> Option<Permission> as "The project name" {
if self.permission == "READ" {
Some(Permission::Read)
} else if self.permission == "WRITE" {
Some(Permission::Write)
} else if self.permission == "OWNER" {
Some(Permission::Owner)
} else {
None
}
}
});
pub struct QueryRoot();
graphql_object!(QueryRoot: SchemaContext as "Query" |&self| {
description: "The root query object of the schema"
field current_user(&executor) -> FieldResult<User>
as ""
{
match executor.context().current_user.clone() {
Some(user) => Ok(user),
None => Err(FieldError::new(
"Not authenticated",
graphql_value!({ "internal_error": "Could not parse the current user from the authentication token" })
)),
}
}
field users(&executor) -> Vec<User>
as ""
{
vec![]
}
field projects(&executor) -> Vec<Project>
as ""
{
vec![]
}
field project(&executor, id: String) -> FieldResult<Project>
as ""
{
match executor
.context()
.db_addr
.send(ProjectById{project_id: id})
.wait()
.unwrap() {
Ok(project) => Ok(project),
Err(_e) => Err(FieldError::new(
"Could not get Project",
graphql_value!({ "internal_error": ""})
)),
}
}
field readFile(&executor, id: String, path: String) -> FieldResult<String>
as ""
{
let file = FileStore::project_root(Uuid::parse_str(&id).unwrap()).join(Path::new(&path));
match FileStore::read(&file) {
Ok(contents) => Ok(contents),
Err(_e) => Err(FieldError::new(
"Could not read file",
graphql_value!({ "internal_error": ""})
)),
}
}
field templates() -> FieldResult<Vec<String>>
as ""
{
Ok(vec!["default".to_string(), "shortestpath".to_string()])
}
});
pub struct MutationRoot;
graphql_object!(MutationRoot: SchemaContext as "Mutation" |&self| {
description: "The root mutation object of the schema"
field new_project(&executor, name: String, template: String) -> FieldResult<Project>
as "Create a new project"
{
let templates: Vec<String> = vec!["default".to_string(), "shortestpath".to_string()];
match executor.context().current_user.clone() {
Some(current_user) => {
if !templates.contains(&template) {
return Err(FieldError::new("", graphql_value!({"internal_error": ""})));
}
match executor
.context()
.db_addr
.send(CreateProject{name: name, user: current_user})
.wait()
.unwrap() {
Ok(project) => {
let project_root = FileStore::project_root(project.id);
match FileStore::create_all(&project_root) {
Ok(_) => (),
Err(_) => return Err(FieldError::new(
"Could not create Project dir",
graphql_value!({ "internal_error": ""})
)),
};
// TODO: select template
let template_root = FileStore::template_root(&template);
match FileStore::copy_recursive(&template_root, &project_root) {
Ok(_) => (),
Err(_) => return Err(FieldError::new(
"Could not copy template files",
graphql_value!({ "internal_error": ""})
)),
};
Ok(project)
},
Err(_e) => Err(FieldError::new(
"Could not create Project",
graphql_value!({ "internal_error": ""})
)),
}
},
None => Err(FieldError::new("Invalid credentials", graphql_value!({"internal_error": ""})))
}
}
field delete_project(&executor, pid: String) -> bool as "Deletes a project" {
false
}
});
|
use crate::{permute_comp, PoseidonState};
use stark_curve::FieldElement;
/// Hashes two elements using the Poseidon hash.
///
/// Equivalent to [`poseidon_hash`](https://github.com/starkware-libs/cairo-lang/blob/12ca9e91bbdc8a423c63280949c7e34382792067/src/starkware/cairo/common/builtin_poseidon/poseidon.cairo#L5).
pub fn poseidon_hash(x: FieldElement, y: FieldElement) -> FieldElement {
let mut state = [x, y, FieldElement::TWO];
permute_comp(&mut state);
state[0]
}
/// Hashes a number of messages using the Poseidon hash.
///
/// Equivalent to [`poseidon_hash_many`](https://github.com/starkware-libs/cairo-lang/blob/12ca9e91bbdc8a423c63280949c7e34382792067/src/starkware/cairo/common/builtin_poseidon/poseidon.cairo#L28).
pub fn poseidon_hash_many(msgs: &[FieldElement]) -> FieldElement {
let mut state = [FieldElement::ZERO, FieldElement::ZERO, FieldElement::ZERO];
let mut iter = msgs.chunks_exact(2);
for msg in iter.by_ref() {
state[0] += msg[0];
state[1] += msg[1];
permute_comp(&mut state);
}
let r = iter.remainder();
if r.len() == 1 {
state[0] += r[0];
}
state[r.len()] += FieldElement::ONE;
permute_comp(&mut state);
state[0]
}
/// The PoseidonHasher can build up a hash by appending to state
///
/// Its output is equivalent to calling [poseidon_hash_many] with the
/// field elements.
pub struct PoseidonHasher {
state: PoseidonState,
buffer: Option<FieldElement>,
}
impl PoseidonHasher {
/// Creates a new PoseidonHasher
pub fn new() -> PoseidonHasher {
PoseidonHasher {
state: [FieldElement::ZERO, FieldElement::ZERO, FieldElement::ZERO],
buffer: None,
}
}
/// Absorbs message into the hash
pub fn write(&mut self, msg: FieldElement) {
match self.buffer.take() {
Some(previous_message) => {
self.state[0] += previous_message;
self.state[1] += msg;
permute_comp(&mut self.state);
}
None => {
self.buffer = Some(msg);
}
}
}
/// Finish and return hash
pub fn finish(mut self) -> FieldElement {
// Apply padding
match self.buffer.take() {
Some(last_message) => {
self.state[0] += last_message;
self.state[1] += FieldElement::ONE;
}
None => {
self.state[0] += FieldElement::ONE;
}
}
permute_comp(&mut self.state);
self.state[0]
}
}
impl Default for PoseidonHasher {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::{poseidon_hash, poseidon_hash_many, PoseidonHasher};
use stark_curve::FieldElement;
use stark_hash::Felt;
#[test]
fn test_poseidon_hash() {
// The test vector is derived by running the Python implementation with random input.
let x =
Felt::from_hex_str("0x23a77118133287637ebdcd9e87a1613e443df789558867f5ba91faf7a024204")
.unwrap();
let y =
Felt::from_hex_str("0x259f432e6f4590b9a164106cf6a659eb4862b21fb97d43588561712e8e5216a")
.unwrap();
let expected_hash =
Felt::from_hex_str("0x4be9af45b942b4b0c9f04a15e37b7f34f8109873ef7ef20e9eef8a38a3011e1")
.unwrap();
assert_eq!(poseidon_hash(x.into(), y.into()), expected_hash.into());
}
#[test]
fn test_poseidon_hash_many_empty_input() {
// The test vector is derived by running the Python implementation with random input.
assert_eq!(
poseidon_hash_many(&[]),
Felt::from_hex_str("0x2272be0f580fd156823304800919530eaa97430e972d7213ee13f4fbf7a5dbc")
.unwrap()
.into()
);
}
#[test]
fn test_poseidon_hash_many_single_input() {
// The test vector is derived by running the Python implementation with random input.
assert_eq!(
poseidon_hash_many(&[Felt::from_hex_str(
"0x23a77118133287637ebdcd9e87a1613e443df789558867f5ba91faf7a024204"
)
.unwrap()
.into()]),
Felt::from_hex_str("0x7d1f569e0e898982de6515c20132703410abca88ee56100e02df737fc4bf10e")
.unwrap()
.into()
);
}
#[test]
fn test_poseidon_hash_many_two_inputs() {
// The test vector is derived by running the Python implementation with random input.
assert_eq!(
poseidon_hash_many(&[
Felt::from_hex_str(
"0x259f432e6f4590b9a164106cf6a659eb4862b21fb97d43588561712e8e5216a"
)
.unwrap()
.into(),
Felt::from_hex_str(
"0x5487ce1af19922ad9b8a714e61a441c12e0c8b2bad640fb19488dec4f65d4d9"
)
.unwrap()
.into(),
]),
Felt::from_hex_str("0x70869d36570fc0b364777c9322373fb7e15452d2282ebdb5b4f3212669f2e7")
.unwrap()
.into()
);
}
#[test]
fn test_sponge() {
let expected_result = FieldElement::from(
Felt::from_hex_str("07b8f30ac298ea12d170c0873f1fa631a18c00756c6e7d1fd273b9a239d0d413")
.unwrap(),
);
// Construct messages, the first few integers
let msgs = [
FieldElement::ZERO,
FieldElement::ONE,
FieldElement::TWO,
FieldElement::THREE,
];
// Construct hash from hasher
let mut hasher = PoseidonHasher::new();
for msg in msgs {
hasher.write(msg);
}
let hasher_result = hasher.finish();
// Construct hash from hash function
let hash_result = poseidon_hash_many(&msgs);
// Check they are equal
assert_eq!(hasher_result, hash_result);
assert_eq!(expected_result, hash_result);
}
}
|
use crate::core::{
attribute::TypedAttribute,
channel_list::{ChannelListRef, ChannelListRefMut},
cppstd::CppString,
error::Error,
preview_image::{PreviewImage, PreviewImageRef},
refptr::{OpaquePtr, Ref, RefMut},
tile_description::TileDescription,
Compression, LineOrder,
};
use openexr_sys as sys;
use imath_traits::{Bound2, Vec2};
type Result<T, E = Error> = std::result::Result<T, E>;
use std::alloc::{GlobalAlloc, Layout, System};
use std::ffi::{CStr, CString};
/// The `Header` represents the header in the OpenEXR file and is typically read
/// or written when the file is first opened.
///
/// There will be one header for each *part* of an OpenEXR file and it describes
/// the structure of the associated image.
///
/// The header must always contain the following required attributes, accessible
/// by convenience methods:
/// * [`display_window()`](Header::display_window) - "displayWindow" - the rectangle describing the viewable
/// portion of the image plane.
/// * [`data_window()`](Header::data_window) - "dataWindow" - the rectangle describing the portion of
/// the image plane that contains data.
/// * [`pixel_aspect_ratio()`](Header::pixel_aspect_ratio) - "pixelAspectRatio" - the ratio of a pixel's
/// width to height when the image is projected at the correct ratio
/// * [`channels()`](Header::channels) - "channels" - the description of
/// [`Channel`](crate::core::channel_list::Channel)s in the image.
/// * [`compression()`](Header::compression) - "compression" - which compression method is applied to
/// the pixel data when it is stored.
/// * [`line_order()`](Header::line_order) - "lineOrder" - the order in which scan lines are stored
/// in the file. Note this does not change the interpretation of "up", which is
/// always down in screen space, this is just an optimization hint for readers.
/// * [`screen_window_width()`](Header::screen_window_width) - "screenWindowWidth" - the width of the screen
/// window for the perspective projection that produced the image. If the image
/// wasn't produced by a perspective projection this should be set to 1.0.
/// * [`screen_window_center()`](Header::screen_window_center) - "screenWindowCenter" - the center of the screen
/// window for the perspective projection that produced the image. If the image
/// wasn't produced by a perspective projection this should be set to 1.0.
/// * "tiles" - required for tiled images only. [`TileDescription`]
/// describes the size, level mode and level rounding mode of the image.
/// * [`name()`](Header::name) - "name" - required for multi-part images only. The name of the
/// part, which must be unique between all parts in the image.
/// * [`image_type()`](Header::image_type) - "type" - required for deep images only, optional for
/// others. Can be either "scanlineimage", "tiledimage", "deepscanline", or
/// "deeptile"
/// * "maxSamplesPerPixel" - this attribute is
/// automatically added to deep files, being set when the file is written. This
/// represents the maximum number of samples contained by any pixel in the image
/// and is intended as an optimization hint for readers for pre-allocating storage.
///
#[repr(transparent)]
pub struct Header(pub(crate) Box<sys::Imf_Header_t>);
#[repr(transparent)]
pub struct HeaderSlice(pub(crate) Box<[sys::Imf_Header_t]>);
unsafe impl OpaquePtr for Header {
type SysPointee = sys::Imf_Header_t;
type Pointee = Header;
}
pub type HeaderRef<'a, P = Header> = Ref<'a, P>;
pub type HeaderRefMut<'a, P = Header> = RefMut<'a, P>;
impl Header {
/// Construct a new [`Header`] with the given attributes.
///
/// # Arguments
/// * `data_window` - The window which contains data. Typically will be the
/// same as the display window, but may be smaller to represent a crop region
/// or larger to represent overscan.
/// * `display_window` - The window which represents the size of the
/// displayable image. Typically will be [[0, width-1], [0, height-1]].
/// * `pixel_aspect_ratio` - The ratio of the pixel `width/height`, e.g. 2.0
/// for anamorphic.
/// * `screen_window_center` - The center of the screen window. Will be (0,0)
/// for images that were not generated by perspective projection.
/// * `screen_window_width` - The width of the screen window. Will be 1.0 for
/// images that were not generated by perspective projection
/// * `line_order` - The vertical order in which scanlines are stored. This
/// is a hint for readers and may not be respected.
/// * `compression` - The compression scheme to use to store all image data.
///
/// ## Errors
/// * [`Error::InvalidArgument`] - If the pixel aspect ratio is negative, or
/// if the width or height of the display window is less than 1.
///
pub fn new<B, V>(
data_window: B,
display_window: B,
pixel_aspect_ratio: f32,
screen_window_center: V,
screen_window_width: f32,
line_order: LineOrder,
compression: Compression,
) -> Result<Header>
where
B: Bound2<i32>,
V: Vec2<f32>,
{
unsafe {
// We use the system allocator here as Header is not movable, but
// is exposed as opaquebytes so that we can create arrays for it.
// That means that we need Header to wrap a Box<sys::Imf_Header_t>
// so that the C struct will never move.
// The only way to do this is with Box::from_raw
//
let header = System.alloc(Layout::new::<sys::Imf_Header_t>())
as *mut sys::Imf_Header_t;
sys::Imf_Header_ctor(
header,
data_window.as_ptr() as *const sys::Imath_Box2i_t,
display_window.as_ptr() as *const sys::Imath_Box2i_t,
pixel_aspect_ratio,
screen_window_center.as_ptr() as *const sys::Imath_V2f_t,
screen_window_width,
line_order.into(),
compression.into(),
)
.into_result()?;
Ok(Header(Box::from_raw(header)))
}
}
/// Construct a new [`Header`] with the given attributes.
///
/// # Arguments
/// * `width` - The width of the image, setting both data and display
/// windows
/// * `height` - The height of the image, setting both data and display
/// windows
/// displayable image. Typically will be [[0, width-1], [0, height-1]].
/// * `pixel_aspect_ratio` - The ratio of the pixel `width/height`, e.g. 2.0
/// for anamorphic.
/// * `screen_window_center` - The center of the screen window. Will be (0,0)
/// for images that were not generated by perspective projection.
/// * `screen_window_width` - The width of the screen window. Will be 1.0 for
/// images that were not generated by perspective projection
/// * `line_order` - The vertical order in which scanlines are stored. This
/// is a hint for readers and may not be respected.
/// * `compression` - The compression scheme to use to store all image data.
///
/// ## Errors
/// * [`Error::InvalidArgument`] - If the pixel aspect ratio is negative, or
/// if the width or height of the display window is less than 1.
///
pub fn with_dimensions<V>(
width: i32,
height: i32,
pixel_aspect_ratio: f32,
screen_window_center: V,
screen_window_width: f32,
line_order: LineOrder,
compression: Compression,
) -> Result<Header>
where
V: Vec2<f32>,
{
unsafe {
// We use the system allocator here as Header is not movable, but
// is exposed as opaquebytes so that we can create arrays for it.
// That means that we need Header to wrap a Box<sys::Imf_Header_t>
// so that the C struct will never move.
// The only way to do this is with Box::from_raw
//
let header = System.alloc(Layout::new::<sys::Imf_Header_t>())
as *mut sys::Imf_Header_t;
sys::Imf_Header_with_dimensions(
header,
width,
height,
pixel_aspect_ratio,
screen_window_center.as_ptr() as *const sys::Imath_V2f_t,
screen_window_width,
line_order.into(),
compression.into(),
)
.into_result()?;
Ok(Header(Box::from_raw(header)))
}
}
/// Construct a new [`HeaderSlice`], i.e. an array of `num` [`Header`]s,
/// suitable for passing to the constructor of e.g.
/// [`MultiPartOutputFile`](`crate::multi_part::multi_part_output_file::MultiPartOutputFile`).
///
/// All the resulting [`Header`]s are default-initialized so you should
/// manually iterate over and set their attributes after construction.
///
pub fn new_array(num: usize) -> HeaderSlice {
unsafe {
let ptr = System
.alloc(Layout::array::<sys::Imf_Header_t>(num).unwrap())
as *mut sys::Imf_Header_t;
// FIXME: is this safe? We're only using Vec as an intermediary
// but not sure...
let mut array =
Vec::from_raw_parts(ptr, num, num).into_boxed_slice();
for header in array.iter_mut() {
sys::Imf_Header_with_dimensions(
header,
64,
64,
1.0f32,
[0.0f32, 0.0f32].as_ptr() as *const sys::Imath_V2f_t,
1.0f32,
LineOrder::IncreasingY.into(),
Compression::Zip.into(),
);
}
HeaderSlice(array)
}
}
/// Shortcut to construct a new [`Header`] with just the dimensions and
/// everything else Default
///
pub fn from_dimensions(width: i32, height: i32) -> Header {
let mut header = Header::default();
header.set_dimensions(width, height);
header
}
/// Shortcut to construct a new [`Header`] with just the data and display
/// windows and everything else Default
///
pub fn from_windows<B: Bound2<i32>>(
data_window: B,
display_window: B,
) -> Header {
let mut header = Header::default();
*header.data_window_mut() = data_window;
*header.display_window_mut() = display_window;
header
}
/// Examines the header and returns an error if it finds something wrong
/// with the attributes (e.g. empty display window, negative pixel aspect
/// ratio etc.)
///
/// # Arguments
/// * `is_tiled` - This header should represent a tiled file
/// * `is_multi_part` - This header should represent a multi-part file
///
/// ## Errors
/// * [`Error::InvalidArgument`] - If any of the header attributes are invalid
///
pub fn sanity_check(
&self,
is_tiled: bool,
is_multi_part: bool,
) -> Result<()> {
unsafe {
sys::Imf_Header_sanityCheck(
self.0.as_ref(),
is_tiled,
is_multi_part,
)
.into_result()?;
}
Ok(())
}
/// [`Header::sanity_check()`] will throw an exception if the width or
/// height of the data window exceeds the maximum image width or height, or
/// if the size of a tile exceeds the maximum tile width or height.
///
/// At program startup the maximum image and tile width and height
/// are set to zero, meaning that width and height are unlimited.
///
/// Limiting image and tile width and height limits how much memory
/// will be allocated when a file is opened. This can help protect
/// applications from running out of memory while trying to read
/// a damaged image file.
///
pub fn set_max_image_size(max_width: i32, max_height: i32) {
unsafe {
sys::Imf_Header_setMaxImageSize(max_width, max_height)
.into_result()
.unwrap();
}
}
/// [`Header::sanity_check()`] will throw an exception if the width or
/// height of the data window exceeds the maximum image width or height, or
/// if the size of a tile exceeds the maximum tile width or height.
///
/// At program startup the maximum image and tile width and height
/// are set to zero, meaning that width and height are unlimited.
///
/// Limiting image and tile width and height limits how much memory
/// will be allocated when a file is opened. This can help protect
/// applications from running out of memory while trying to read
/// a damaged image file.
///
pub fn set_max_tile_size(max_width: i32, max_height: i32) {
unsafe {
sys::Imf_Header_setMaxTileSize(max_width, max_height)
.into_result()
.unwrap();
}
}
/// Check if the header reads nothing
///
/// FIXME: This should be a const method in C++ but it's not - patch OpenEXR?
///
pub fn reads_nothing(&mut self) -> bool {
let mut result = false;
unsafe {
sys::Imf_Header_readsNothing(self.0.as_mut(), &mut result)
.into_result()
.unwrap()
};
result
}
}
impl Default for Header {
/// Creates a default header
///
/// The resulting header has parameters:
/// * `width` = 64
/// * `height` = 64
/// * `pixel_aspect_ratio` = 1.0
/// * `screen_window_center` = [0.0, 0.0]
/// * `screen_window_width` = 1.0
/// * `line_order` = LineOrder::IncreasingY
/// * `compression` = Compression::Zip
///
fn default() -> Header {
Header::with_dimensions(
64,
64,
1.0f32,
[0.0f32, 0.0f32],
1.0f32,
LineOrder::IncreasingY,
Compression::Zip,
)
.unwrap()
}
}
impl Header {
//! # Standard attributes
//!
//! These methods can be used to get and set the required attributes of a
//! standard OpenEXR file. The attributes `name`, `type` and
//! `maxSamplesPerPixel` are only required for deep and multi-part images.
/// Get a reference to the display window.
///
/// The display window represents the rectangular region in pixel space that
/// we wish to display. This typically correlates to what we normally think
/// of as the "width" and "height" of the image, such that the display
/// window rectangle is defined as a min/max inclusive pair of points
/// (0, 0), (width-1, height-1).
///
/// The display window must be the same for all parts in a file.
///
/// Pixel space is a 2D coordinate system with X increasing from left to
/// right and Y increasing from top to bottom.
///
pub fn display_window<B>(&self) -> &B
where
B: Bound2<i32>,
{
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_Header_displayWindow_const(self.0.as_ref(), &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_Box2i_t as *const B)
}
}
/// Get a mutable reference to the display window.
///
/// The display window represents the rectangular region in pixel space that
/// we wish to display. This typically correlates to what we normally think
/// of as the "width" and "height" of the image, such that the display
/// window rectangle is defined as a min/max inclusive pair of points
/// (0, 0), (width-1, height-1).
///
/// The display window must be the same for all parts in a file.
///
/// Pixel space is a 2D coordinate system with X increasing from left to
/// right and Y increasing from top to bottom.
///
pub fn display_window_mut<B>(&mut self) -> &mut B
where
B: Bound2<i32>,
{
unsafe {
let mut ptr = std::ptr::null_mut();
sys::Imf_Header_displayWindow(self.0.as_mut(), &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_Box2i_t as *mut B)
}
}
/// Get a reference to the data window
///
/// The data window represents the rectangular region of the image for which
/// pixel data is defined in the file. Attempting to read or write data
/// outside of that region is an error. For a "normal" image, the data
/// window corresponds exactly to the display window, but for special cases
/// may be different. For example it is common to only render a small section
/// of the image ("crop region"), in which case the data window will be
/// smaller than the display window, or to to render extra pixels outside of
/// the display window ("overscan"), in which case the data window will be
/// larger than the display window.
///
pub fn data_window<B>(&self) -> &B
where
B: Bound2<i32>,
{
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_Header_dataWindow_const(self.0.as_ref(), &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_Box2i_t as *const B)
}
}
/// Get a mutable reference to the data window
///
/// The data window represents the rectangular region of the image for which
/// pixel data is defined in the file. Attempting to read or write data
/// outside of that region is an error. For a "normal" image, the data
/// window corresponds exactly to the display window, but for special cases
/// may be different. For example it is common to only render a small section
/// of the image ("crop region"), in which case the data window will be
/// smaller than the display window, or to to render extra pixels outside of
/// the display window ("overscan"), in which case the data window will be
/// larger than the display window.
///
pub fn data_window_mut<B>(&mut self) -> &mut B
where
B: Bound2<i32>,
{
unsafe {
let mut ptr = std::ptr::null_mut();
sys::Imf_Header_dataWindow(self.0.as_mut(), &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_Box2i_t as *mut B)
}
}
/// Set both display and data windows to [[0, 0], [width-1, height-1]]
///
pub fn set_dimensions(&mut self, width: i32, height: i32) {
*self.data_window_mut() = [0, 0, width - 1, height - 1];
*self.display_window_mut() = [0, 0, width - 1, height - 1];
}
/// Get the pixel aspect ratio
///
/// Given d_x, the difference between pixel locations (x, y) and (x+1, y),
/// and d_y, difference between pixel locations (x, y) and (x, y+1) on the
/// the display, the pixel aspect ratio is the ratio d_x / d_y when the image
/// is displayed dusch that the aspect ratio width/height is as intended.
///
/// The pixel aspect ratio must be the same for all parts in a file.
///
/// A normal image thus has a pixel aspect ratio of 1.0, while it is 2.0
/// for an anamorphic image.
///
pub fn pixel_aspect_ratio(&self) -> f32 {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_Header_pixelAspectRatio_const(self.0.as_ref(), &mut ptr)
.into_result()
.unwrap();
*ptr
}
}
/// Set the pixel aspect ratio
///
/// Given d_x, the difference between pixel locations (x, y) and (x+1, y),
/// and d_y, difference between pixel locations (x, y) and (x, y+1) on the
/// the display, the pixel aspect ratio is the ratio d_x / d_y when the image
/// is displayed dusch that the aspect ratio width/height is as intended.
///
/// The pixel aspect ratio must be the same for all parts in a file.
///
/// A normal image thus has a pixel aspect ratio of 1.0, while it is 2.0
/// for an anamorphic image.
///
pub fn set_pixel_aspect_ratio(&mut self, par: f32) {
unsafe {
let mut ptr = std::ptr::null_mut();
sys::Imf_Header_pixelAspectRatio(self.0.as_mut(), &mut ptr)
.into_result()
.unwrap();
*ptr = par;
}
}
/// Get a reference to the screen window center
///
/// The screen window represents the bounding rectangle of the image on the
/// `z=1` plane assuming the image was generated by perspective projection
/// with a width, `W`, and a center, `C`. The height of the window can be
/// derived from the center and the pixel aspect ratio.
///
/// Images that were not generated by perspective projection should have
/// their screen window width set to 1 and their center to (0,0).
///
pub fn screen_window_center<B>(&self) -> &B
where
B: Bound2<i32>,
{
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_Header_screenWindowCenter_const(self.0.as_ref(), &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_Box2i_t as *const B)
}
}
/// Get a mutable reference to the screen window center
///
/// The screen window represents the bounding rectangle of the image on the
/// `z=1` plane assuming the image was generated by perspective projection
/// with a width, `W`, and a center, `C`. The height of the window can be
/// derived from the center and the pixel aspect ratio.
///
/// Images that were not generated by perspective projection should have
/// their screen window width set to 1 and their center to (0,0).
///
pub fn screen_window_center_mut<B>(&mut self) -> &mut B
where
B: Bound2<i32>,
{
unsafe {
let mut ptr = std::ptr::null_mut();
sys::Imf_Header_screenWindowCenter(self.0.as_mut(), &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_Box2i_t as *mut B)
}
}
/// Get a reference to the screen window width
///
/// The screen window represents the bounding rectangle of the image on the
/// `z=1` plane assuming the image was generated by perspective projection
/// with a width, `W`, and a center, `C`. The height of the window can be
/// derived from the center and the pixel aspect ratio.
///
/// Images that were not generated by perspective projection should have
/// their screen window width set to 1 and their center to (0,0).
///
pub fn screen_window_width(&self) -> &f32 {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_Header_screenWindowWidth_const(self.0.as_ref(), &mut ptr)
.into_result()
.unwrap();
&*ptr
}
}
/// Get a mutable reference to the screen window width
///
/// The screen window represents the bounding rectangle of the image on the
/// `z=1` plane assuming the image was generated by perspective projection
/// with a width, `W`, and a center, `C`. The height of the window can be
/// derived from the center and the pixel aspect ratio.
///
/// Images that were not generated by perspective projection should have
/// their screen window width set to 1 and their center to (0,0).
///
pub fn screen_window_width_mut(&mut self) -> &f32 {
unsafe {
let mut ptr = std::ptr::null_mut();
sys::Imf_Header_screenWindowWidth(self.0.as_mut(), &mut ptr)
.into_result()
.unwrap();
&mut *ptr
}
}
/// Get a reference to the list of channels in the header
pub fn channels(&self) -> ChannelListRef {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_Header_channels_const(self.0.as_ref(), &mut ptr)
.into_result()
.unwrap();
ChannelListRef::new(ptr)
}
}
/// Get a mutable reference to the list of channels in the header
pub fn channels_mut(&mut self) -> ChannelListRefMut {
unsafe {
let mut ptr = std::ptr::null_mut();
sys::Imf_Header_channels(self.0.as_mut(), &mut ptr)
.into_result()
.unwrap();
ChannelListRefMut::new(ptr)
}
}
/// Get the line order from the header
///
/// Specifies the order in which rows of pixels are stored in the file,
/// either [`LineOrder::IncreasingY`], [`LineOrder::DecreasingY`] or
/// [`LineOrder::RandomY`] for tiled images.
///
/// This does not affect the pixel space coordinates, only the order in
/// which the data is stored.
///
pub fn line_order(&self) -> LineOrder {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_Header_lineOrder_const(self.0.as_ref(), &mut ptr)
.into_result()
.unwrap();
(*ptr).into()
}
}
/// Set the line order in the header
///
/// Specifies the order in which rows of pixels are stored in the file,
/// either [`LineOrder::IncreasingY`], [`LineOrder::DecreasingY`] or
/// [`LineOrder::RandomY`] for tiled images.
///
/// This does not affect the pixel space coordinates, only the order in
/// which the data is stored.
///
pub fn set_line_order(&mut self, lo: LineOrder) {
unsafe {
let mut ptr = std::ptr::null_mut();
sys::Imf_Header_lineOrder(self.0.as_mut(), &mut ptr)
.into_result()
.unwrap();
*ptr = lo.into();
};
}
/// Get the compression type from the header
///
/// Defines the compression scheme used to store all pixel data.
///
pub fn compression(&self) -> Compression {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_Header_compression_const(self.0.as_ref(), &mut ptr)
.into_result()
.unwrap();
(*ptr).into()
}
}
/// Set the compression type in the header
///
/// Defines the compression scheme used to store all pixel data.
///
pub fn set_compression(&mut self, cmp: Compression) {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_Header_compression(self.0.as_mut(), &mut ptr)
.into_result()
.unwrap();
*ptr = cmp.into();
}
}
}
impl Header {
//! # Required attributes for multi-part files
//!
//! These attributes are all mandatory for multi-part files and optional
//! for single-part files.
/// Get the name of this part from the header
///
/// Names must be unique, that is no two parts in the same file may share
/// the same name.
///
pub fn name(&self) -> Result<String> {
unsafe {
let mut s = std::ptr::null();
sys::Imf_Header_name_const(self.0.as_ref(), &mut s)
.into_result()
.map(|_| {
let mut cptr = std::ptr::null();
sys::std_string_c_str(s, &mut cptr).into_result().unwrap();
CStr::from_ptr(cptr).to_string_lossy().to_string()
})
.map_err(Error::from)
}
}
/// Set the name of this part in the header
///
/// Names must be unique, that is no two parts in the same file may share
/// the same name.
///
pub fn set_name(&mut self, name: &str) {
unsafe {
let s = CppString::new(name);
sys::Imf_Header_setName(self.0.as_mut(), s.0);
}
}
/// Does the file/part have a name?
pub fn has_name(&self) -> bool {
unsafe {
let mut v = false;
sys::Imf_Header_hasName(self.0.as_ref(), &mut v);
v
}
}
/// Get the image type of this part from the header
///
/// This must be one of:
/// * `scanlineimage` - Flat, scanline-based.
/// * `tiledimage` - Flat, tiled.
/// * `deepscanline` - Deep, scanline-based.
/// * `deeptile` - Deep, tiled.
///
pub fn image_type(&self) -> Result<ImageType> {
unsafe {
let mut s = std::ptr::null();
sys::Imf_Header_type_const(self.0.as_ref(), &mut s)
.into_result()
.map(|_| {
let mut cptr = std::ptr::null();
sys::std_string_c_str(s, &mut cptr);
match CStr::from_ptr(cptr).to_str().unwrap() {
"scanlineimage" => ImageType::Scanline,
"tiledimage" => ImageType::Tiled,
"deepscanline" => ImageType::DeepScanline,
"deeptile" => ImageType::DeepTiled,
_ => panic!("bad value for image type"),
}
})
.map_err(Error::from)
}
}
/// Set the image type of this part in the header
///
/// This must be one of:
/// * `scanlineimage` - Flat, scanline-based.
/// * `tiledimage` - Flat, tiled.
/// * `deepscanline` - Deep, scanline-based.
/// * `deeptile` - Deep, tiled.
///
pub fn set_image_type(&mut self, image_type: ImageType) {
unsafe {
let s = match image_type {
ImageType::Scanline => CppString::new("scanlineimage"),
ImageType::Tiled => CppString::new("tiledimage"),
ImageType::DeepScanline => CppString::new("deepscanline"),
ImageType::DeepTiled => CppString::new("deeptile"),
};
sys::Imf_Header_setType(self.0.as_mut(), s.0)
.into_result()
.expect("Unexpected exception from Imf_Header_setType");
}
}
/// Does the file/part have a type?
pub fn has_image_type(&self) -> bool {
unsafe {
let mut v = false;
sys::Imf_Header_hasType(self.0.as_ref(), &mut v);
v
}
}
/// Get the version of the file
///
pub fn version(&self) -> Result<i32> {
unsafe {
let mut v = std::ptr::null();
sys::Imf_Header_version_const(self.0.as_ref(), &mut v)
.into_result()
.map(|_| *v)
.map_err(Error::from)
}
}
/// Set the version of the file
///
pub fn set_version(&mut self, v: i32) {
unsafe {
sys::Imf_Header_setVersion(self.0.as_mut(), v);
}
}
/// Does the file have its version specified?
pub fn has_version(&self) -> bool {
unsafe {
let mut v = false;
sys::Imf_Header_hasVersion(self.0.as_ref(), &mut v);
v
}
}
}
impl Header {
//! # Chunk count
//!
//! Chunk count is set automatically when writing the file
/// Does the file have its chunk count specified?
pub fn has_chunk_count(&self) -> bool {
unsafe {
let mut v = false;
sys::Imf_Header_hasChunkCount(self.0.as_ref(), &mut v);
v
}
}
/// Get the chunk_count of the file
///
pub fn chunk_count(&self) -> Result<i32> {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_Header_chunkCount_const(self.0.as_ref(), &mut ptr)
.into_result()
.map(|_| *ptr)
.map_err(Error::from)
}
}
}
impl Header {
//! # Views
//!
//! View names must be unique, that is no two parts in the same file may share
//! the same view. Only supported for multi-part files, deprecated for
//! single-part files.
/// Get the view of this part from the header
///
pub fn view(&self) -> Result<String> {
unsafe {
let mut s = std::ptr::null();
sys::Imf_Header_view_const(self.0.as_ref(), &mut s)
.into_result()
.map(|_| {
let mut cptr = std::ptr::null();
sys::std_string_c_str(s, &mut cptr);
CStr::from_ptr(cptr).to_string_lossy().to_string()
})
.map_err(Error::from)
}
}
/// Set the view of this part in the header
///
pub fn set_view(&mut self, view: &str) {
unsafe {
let s = CppString::new(view);
sys::Imf_Header_setView(self.0.as_mut(), s.0);
}
}
/// Does the part have a view specified?
pub fn has_view(&self) -> bool {
unsafe {
let mut v = false;
sys::Imf_Header_hasView(self.0.as_ref(), &mut v);
v
}
}
}
impl Header {
//! # Tile Description
//!
//! The tile description is a
//! [`TileDescriptionAttribute`](crate::core::attribute::TileDescriptionAttribute) whose name is
//! `"tiles"`. It is mandatory for tiled files. The [`TileDescription`]
//! describes various properties of the tiles that make up the image file.
/// Get the tile description from the header
///
pub fn tile_description(&self) -> Result<TileDescription> {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_Header_tileDescription_const(self.0.as_ref(), &mut ptr)
.into_result()
.map(|_| (*ptr).clone().into())
.map_err(Error::from)
}
}
/// Set the tile description in the header
///
pub fn set_tile_description(&mut self, td: &TileDescription) {
unsafe {
let td = (*td).into();
sys::Imf_Header_setTileDescription(self.0.as_mut(), &td);
}
}
/// Does the part have a tile description?
///
pub fn has_tile_description(&self) -> bool {
unsafe {
let mut v = false;
sys::Imf_Header_hasTileDescription(self.0.as_ref(), &mut v);
v
}
}
}
impl Header {
//! # Preview Image
//!
//! The preview image ias a [`PreviewImageAttribute`](crate::core::attribute::PreviewImageAttribute) whose name is
//! `"preview"`.
//! This attribute is special -- while an image file is being written,
//! the pixels of the preview image can be changed repeatedly by calling
//! [`update_preview_image()`](crate::core::output_file::OutputFile::update_preview_image)
/// Get the preview image from the header
///
/// # Errors
/// * [`Error::InvalidType`] - If the preview image attribute is not of the expected type
/// * [`Error::Base`] - If any other error occurs
///
pub fn preview_image(&self) -> Result<PreviewImageRef> {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_Header_previewImage_const(self.0.as_ref(), &mut ptr)
.into_result()?;
Ok(PreviewImageRef::new(ptr))
}
}
/// Set the preview image in the header
///
/// # Errors
/// * [`Error::InvalidType`] - If the preview image attribute can not be assigned the expected type
/// * [`Error::Base`] - If any other error occurs
pub fn set_preview_image(&mut self, pi: &PreviewImage) -> Result<()> {
unsafe {
sys::Imf_Header_setPreviewImage(self.0.as_mut(), pi.0)
.into_result()?;
Ok(())
}
}
/// Does the part have a preview image?
///
pub fn has_preview_image(&self) -> bool {
unsafe {
let mut v = false;
sys::Imf_Header_hasPreviewImage(self.0.as_ref(), &mut v);
v
}
}
}
use paste::paste;
macro_rules! make_find_typed_attribute {
($tn:ident, $sfx:ident) => {
paste! {
use crate::core::attribute::{[<$tn AttributeRef>], [<$tn AttributeRefMut>]};
impl Header {
/// Get a reference to the typed Attribute with the given name
///
pub fn [<find_typed_attribute_ $sfx>](
&self,
name: &str,
) -> Option<[<$tn AttributeRef>]> {
let c_name = CString::new(name).expect("Invalid UTF-8 in name");
let mut attr_ptr = std::ptr::null();
unsafe {
sys::[<Imf_Header_findTypedAttribute_ $tn _const>](
self.0.as_ref(),
&mut attr_ptr,
c_name.as_ptr(),
)
};
if !attr_ptr.is_null() {
Some([<$tn AttributeRef>]::new(attr_ptr))
} else {
None
}
}
/// Get a mutable reference to the typed Attribute with the given name
///
pub fn [<find_typed_attribute_ $sfx _mut>](
&mut self,
name: &str,
) -> Option<[<$tn AttributeRefMut>]> {
let c_name = CString::new(name).expect("Invalid UTF-8 in name");
let mut attr_ptr = std::ptr::null_mut();
unsafe {
sys::[<Imf_Header_findTypedAttribute_ $tn>](
self.0.as_mut(),
&mut attr_ptr,
c_name.as_ptr(),
)
};
if !attr_ptr.is_null() {
Some([<$tn AttributeRefMut>]::new(attr_ptr))
} else {
None
}
}
}
}
}
}
impl Header {
//! # Modifying user attributes
/// Inserts the given metadata attribute with the given name
///
/// ## Errors
/// * [`Error::InvalidType`] - If the attribute to be inserted matches an
/// attribute that is already present but with a different type.
/// * [`Error::InvalidArgument`] - If the attribute name is the empty string
///
pub fn insert<A>(&mut self, name: &str, attribute: &A) -> Result<()>
where
A: TypedAttribute,
{
let c_name = CString::new(name).expect("Invalid UTF-8 in name");
unsafe {
sys::Imf_Header_insert(
self.0.as_mut(),
c_name.as_ptr(),
attribute.as_attribute_ptr(),
)
.into_result()?;
}
Ok(())
}
/// Erases the attribute with the given name.
///
/// If no attribute with `name` exists, the [`Header`] is unchanged.
///
pub fn erase(&mut self, name: &str) -> Result<()> {
let c_name = CString::new(name).expect("Invalid UTF-8 in name");
unsafe {
sys::Imf_Header_erase(self.0.as_mut(), c_name.as_ptr())
.into_result()?;
}
Ok(())
}
}
make_find_typed_attribute!(Int, int);
make_find_typed_attribute!(Float, float);
make_find_typed_attribute!(Double, double);
make_find_typed_attribute!(Chromaticities, chromaticities);
make_find_typed_attribute!(Compression, compression);
make_find_typed_attribute!(DeepImageState, deep_image_state);
make_find_typed_attribute!(Envmap, envmap);
make_find_typed_attribute!(ChannelList, channel_list);
make_find_typed_attribute!(CppVectorFloat, vector_float);
make_find_typed_attribute!(CppVectorString, vector_string);
make_find_typed_attribute!(CppString, string);
make_find_typed_attribute!(LineOrder, line_order);
make_find_typed_attribute!(V2i, v2i);
make_find_typed_attribute!(V2f, v2f);
make_find_typed_attribute!(V2d, v2d);
make_find_typed_attribute!(V3i, v3i);
make_find_typed_attribute!(V3f, v3f);
make_find_typed_attribute!(V3d, v3d);
make_find_typed_attribute!(Box2i, box2i);
make_find_typed_attribute!(Box2f, box2f);
make_find_typed_attribute!(M33f, m33f);
make_find_typed_attribute!(M33d, m33d);
make_find_typed_attribute!(M44f, m44f);
make_find_typed_attribute!(M44d, m44d);
impl Drop for Header {
fn drop(&mut self) {
unsafe {
sys::Imf_Header_dtor(self.0.as_mut());
}
}
}
impl HeaderSlice {
pub fn iter(&self) -> HeaderSliceIter {
HeaderSliceIter {
curr: 0,
len: self.0.len(),
header_slice: self,
}
}
pub fn iter_mut(&mut self) -> HeaderSliceIterMut {
HeaderSliceIterMut {
curr: 0,
len: self.0.len(),
header_slice: self,
}
}
}
pub struct HeaderSliceIter<'s> {
curr: usize,
len: usize,
header_slice: &'s HeaderSlice,
}
impl<'s> Iterator for HeaderSliceIter<'s> {
type Item = HeaderRef<'s>;
fn next(&mut self) -> Option<Self::Item> {
if self.curr == self.len {
None
} else {
let ptr = &((*self.header_slice.0)[self.curr])
as *const sys::Imf_Header_t;
self.curr += 1;
Some(HeaderRef::new(ptr))
}
}
}
pub struct HeaderSliceIterMut<'s> {
curr: usize,
len: usize,
header_slice: &'s mut HeaderSlice,
}
impl<'s> Iterator for HeaderSliceIterMut<'s> {
type Item = HeaderRefMut<'s>;
fn next(&mut self) -> Option<Self::Item> {
if self.curr == self.len {
None
} else {
let ptr = &mut ((*self.header_slice.0)[self.curr])
as *mut sys::Imf_Header_t;
self.curr += 1;
Some(HeaderRefMut::new(ptr))
}
}
}
/// Used to set (or inspect) the type of an image in the header
///
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ImageType {
Scanline,
Tiled,
DeepScanline,
DeepTiled,
}
#[cfg(test)]
#[test]
fn header_rtrip1() -> Result<()> {
use crate::tests::load_ferris;
use crate::{
core::{
attribute::{
CompressionAttribute, CppStringAttribute,
CppVectorFloatAttribute, CppVectorStringAttribute,
DeepImageStateAttribute, DoubleAttribute, EnvmapAttribute,
FloatAttribute, IntAttribute,
},
cppstd::{CppVectorFloat, CppVectorString},
Envmap,
},
deep::DeepImageState,
rgba::{
rgba::RgbaChannels,
rgba_file::{RgbaInputFile, RgbaOutputFile},
},
};
let (pixels, width, height) = load_ferris();
let mut header = Header::from_dimensions(width, height);
header.insert("at_int", &IntAttribute::from_value(17))?;
header.insert("at_float", &FloatAttribute::from_value(42.0))?;
header.insert("at_double", &DoubleAttribute::from_value(127.0))?;
header.insert(
"at_compression",
&CompressionAttribute::from_value(&Compression::Dwaa),
)?;
header.insert(
"at_deep_image_state",
&DeepImageStateAttribute::from_value(&DeepImageState::NonOverlapping),
)?;
header
.insert("at_envmap", &EnvmapAttribute::from_value(&Envmap::Latlong))?;
header.insert(
"at_vector_float",
&CppVectorFloatAttribute::from_value(&CppVectorFloat::from_slice(&[
1.0, 2.0, 3.0, 4.0,
])),
)?;
header.insert(
"at_vector_string",
&CppVectorStringAttribute::from_value(&CppVectorString::from_slice(&[
"a", "b", "c", "d",
])),
)?;
header
.insert("at_string", &CppStringAttribute::from_value("lorem ipsum"))?;
let mut file = RgbaOutputFile::new(
"header_rtrip1.exr",
&header,
RgbaChannels::WriteRgba,
1,
)?;
file.set_frame_buffer(&pixels, 1, width as usize)?;
file.write_pixels(height)?;
std::mem::drop(file);
let file = RgbaInputFile::new("header_rtrip1.exr", 4)?;
assert_eq!(
file.header()
.find_typed_attribute_int("at_int")
.unwrap()
.value(),
&17
);
assert_eq!(
file.header()
.find_typed_attribute_float("at_float")
.unwrap()
.value(),
&42.0
);
assert_eq!(
file.header()
.find_typed_attribute_double("at_double")
.unwrap()
.value(),
&127.0
);
assert_eq!(
file.header()
.find_typed_attribute_compression("at_compression")
.unwrap()
.value(),
Compression::Dwaa
);
assert_eq!(
file.header()
.find_typed_attribute_deep_image_state("at_deep_image_state")
.unwrap()
.value(),
DeepImageState::NonOverlapping,
);
assert_eq!(
file.header()
.find_typed_attribute_envmap("at_envmap")
.unwrap()
.value(),
Envmap::Latlong,
);
assert_eq!(
file.header()
.find_typed_attribute_vector_float("at_vector_float")
.unwrap()
.value()
.as_slice(),
&[1.0f32, 2.0, 3.0, 4.0],
);
assert_eq!(
file.header()
.find_typed_attribute_vector_string("at_vector_string")
.unwrap()
.value()
.to_vec(),
&["a", "b", "c", "d"],
);
assert_eq!(
file.header()
.find_typed_attribute_string("at_string")
.unwrap()
.value(),
"lorem ipsum",
);
assert!(file.header().version().is_err());
assert!(file.header().image_type().is_err());
assert!(file.header().preview_image().is_err());
assert!(file.header().name().is_err());
assert!(file.header().view().is_err());
Ok(())
}
|
#![allow(unused_assignments)]
use types::*;
macro_rules! syscall {
($id:expr, $name:ident) => {
#[inline(always)]
#[no_mangle]
pub unsafe extern fn $name() -> int_t {
let mut ret: int_t = $id;
asm!("syscall" :
"+{rax}"(ret) :
:
"rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" :
"volatile");
ret
}
};
($id:expr, $name:ident, $a:ty) => {
#[inline(always)]
#[no_mangle]
pub unsafe extern fn $name(a: $a) -> int_t {
let mut ret: int_t = $id;
asm!("syscall" :
"+{rax}"(ret) :
"{rdi}"(a) :
"rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" :
"volatile");
ret
}
};
($id:expr, $name:ident, $a:ty, $b:ty) => {
#[inline(always)]
#[no_mangle]
pub unsafe extern fn $name(a: $a, b: $b) -> int_t {
let mut ret: int_t = $id;
asm!("syscall" :
"+{rax}"(ret) :
"{rdi}"(a), "{rsi}"(b) :
"rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" :
"volatile");
ret
}
};
($id:expr, $name:ident, $a:ty, $b:ty, $c:ty) => {
#[inline(always)]
#[no_mangle]
pub unsafe extern fn $name(a: $a, b: $b, c: $c) -> int_t {
let mut ret: int_t = $id;
asm!("syscall" :
"+{rax}"(ret) :
"{rdi}"(a), "{rsi}"(b), "{rdx}"(c) :
"rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" :
"volatile");
ret
}
};
($id:expr, $name:ident, $a:ty, $b:ty, $c:ty, $d:ty) => {
#[inline(always)]
#[no_mangle]
pub unsafe extern fn $name(a: $a, b: $b, c: $c, d: $d) -> int_t {
let mut ret: int_t = $id;
asm!("syscall" :
"+{rax}"(ret) :
"{rdi}"(a), "{rsi}"(b), "{rdx}"(c), "{r10}"(d) :
"rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" :
"volatile");
ret
}
};
($id:expr, $name:ident, $a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {
#[inline(always)]
#[no_mangle]
pub unsafe extern fn $name(a: $a, b: $b, c: $c, d: $d, e: $e) -> int_t {
let mut ret: int_t = $id;
asm!("syscall" :
"+{rax}"(ret) :
"{rdi}"(a), "{rsi}"(b), "{rdx}"(c), "{r10}"(d) "{r8}"(e) :
"rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" :
"volatile");
ret
}
};
($id:expr, $name:ident, $a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {
#[inline(always)]
#[no_mangle]
pub unsafe extern fn $name(a: $a, b: $b, c: $c, d: $d, e: $e, f:$f) -> int_t {
let mut ret: int_t = $id;
asm!("syscall" :
"+{rax}"(ret) :
"{rdi}"(a), "{rsi}"(b), "{rdx}"(c), "{r10}"(d) "{r8}"(e), "{r9}"(f) :
"rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" :
"volatile");
ret
}
};
}
syscall!(000, sys_read, uint_t, *mut char_t, size_t);
syscall!(001, sys_write, uint_t, *const char_t, size_t);
syscall!(002, sys_open, *const char_t, int_t, int_t);
syscall!(003, sys_close, uint_t);
syscall!(004, sys_stat, *const char_t, *mut stat);
syscall!(005, sys_fstat, uint_t, *mut stat);
syscall!(006, sys_lstat, *const char_t, *mut stat);
syscall!(007, sys_poll, *mut pollfd, uint_t, long_t);
syscall!(008, sys_lseek, uint_t, off_t, uint_t);
syscall!(009, sys_mmap, ulong_t, ulong_t, ulong_t, ulong_t, ulong_t, ulong_t);
syscall!(010, sys_mprotect, ulong_t, size_t, ulong_t);
syscall!(011, sys_munmap, ulong_t, size_t);
syscall!(012, sys_brk, ulong_t);
syscall!(013, sys_rt_sigaction, int_t, *const sigaction, *mut sigaction, size_t);
syscall!(014, sys_rt_sigprocmask, int_t, *mut sigset_t, *mut sigset_t, size_t);
syscall!(015, sys_rt_sigreturn, ulong_t);
syscall!(016, sys_ioctl, uint_t, uint_t, ulong_t);
syscall!(017, sys_pread64, ulong_t, *mut char_t, size_t, loff_t);
syscall!(018, sys_pwrite64, uint_t, *const char_t, size_t, loff_t);
syscall!(019, sys_readv, ulong_t, *const iovec, ulong_t);
syscall!(020, sys_writev, ulong_t, *const iovec, ulong_t);
syscall!(021, sys_access, *const char_t, int_t);
syscall!(022, sys_pipe, *mut int_t);
syscall!(023, sys_select, int_t, *mut fd_set, *mut fd_set, *mut fd_set, *mut timeval);
syscall!(024, sys_sched_yield);
syscall!(025, sys_mremap, ulong_t, ulong_t, ulong_t, ulong_t, ulong_t);
syscall!(026, sys_msync, ulong_t, size_t, int_t);
syscall!(027, sys_mincore, ulong_t, size_t, *mut uchar_t);
syscall!(028, sys_madvise, ulong_t, size_t, int_t);
syscall!(029, sys_shmget, key_t, size_t, int_t);
syscall!(030, sys_shmat, int_t, *mut char_t, int_t);
syscall!(031, sys_shmctl, int_t, int_t, *mut shmid_ds);
syscall!(032, sys_dup, uint_t);
syscall!(033, sys_dup2, uint_t, uint_t);
syscall!(034, sys_pause);
syscall!(035, sys_nanosleep, *mut timespec, *mut timespec);
syscall!(036, sys_getitimer, int_t, *mut itimerval);
syscall!(037, sys_alarm, uint_t);
syscall!(038, sys_setitimer, int_t, *mut itimerval, *mut itimerval);
syscall!(039, sys_getpid);
syscall!(040, sys_sendfile, int_t, int_t, *mut off_t, size_t);
syscall!(041, sys_socket, int_t, int_t, int_t);
syscall!(042, sys_connect, int_t, *mut sockaddr, int_t);
syscall!(043, sys_accept, int_t, *mut sockaddr, *mut int_t);
syscall!(044, sys_sendto, int_t, *mut void_t, size_t, uint_t, *mut sockaddr, int_t);
syscall!(045, sys_recvfrom, int_t, *mut void_t, size_t, uint_t, *mut sockaddr, *mut int_t);
syscall!(046, sys_sendmsg, int_t, *mut msghdr, uint_t);
syscall!(047, sys_recvmsg, int_t, *mut msghdr, uint_t);
syscall!(048, sys_shutdown, int_t, int_t);
syscall!(049, sys_bind, int_t, *mut sockaddr, int_t);
syscall!(050, sys_listen, int_t, int_t);
syscall!(051, sys_getsockname, int_t, *mut sockaddr, *mut int_t);
syscall!(052, sys_getpeername, int_t, *mut sockaddr, *mut int_t);
syscall!(053, sys_socketpair, int_t, int_t, int_t, *mut int_t);
syscall!(054, sys_setsockopt, int_t, int_t, int_t, *mut char_t, int_t);
syscall!(055, sys_getsockopt, int_t, int_t, int_t, *mut char_t, *mut int_t);
syscall!(056, sys_clone, ulong_t, ulong_t, *mut void_t, *mut void_t);
syscall!(057, sys_fork);
syscall!(058, sys_vfork);
syscall!(059, sys_execve, *const char_t, *const *const char_t, *const *const char_t);
syscall!(060, sys_exit, int_t);
syscall!(061, sys_wait4, pid_t, *mut int_t, int_t, *mut rusage);
syscall!(062, sys_kill, pid_t, int_t);
syscall!(063, sys_uname, *mut old_utsname);
syscall!(064, sys_semget, key_t, int_t, int_t);
syscall!(065, sys_semop, int_t, *mut sembuf, uint_t);
// TODO syscall!(066, sys_semctl, int_t, int_t, int_t, union semun);
syscall!(067, sys_shmdt, *mut char_t);
syscall!(068, sys_msgget, key_t, int_t);
syscall!(069, sys_msgsnd, int_t, *mut msgbuf, size_t, int_t);
syscall!(070, sys_msgrcv, int_t, *mut msgbuf, size_t, long_t, int_t);
syscall!(071, sys_msgctl, int_t, int_t, *mut msqid_ds);
syscall!(072, sys_fcntl, uint_t, uint_t, ulong_t);
syscall!(073, sys_flock, uint_t, uint_t);
syscall!(074, sys_fsync, uint_t);
syscall!(075, sys_fdatasync, uint_t);
syscall!(076, sys_truncate, *const char_t, long_t);
syscall!(077, sys_ftruncate, uint_t, ulong_t);
syscall!(078, sys_getdents, uint_t, *mut linux_dirent, uint_t);
syscall!(079, sys_getcwd, *mut char_t, ulong_t);
syscall!(080, sys_chdir, *const char_t);
syscall!(081, sys_fchdir, uint_t);
syscall!(082, sys_rename, *const char_t, *const char_t);
syscall!(083, sys_mkdir, *const char_t, int_t);
syscall!(084, sys_rmdir, *const char_t);
syscall!(085, sys_creat, *const char_t, int_t);
syscall!(086, sys_link, *const char_t, *const char_t);
syscall!(087, sys_unlink, *const char_t);
syscall!(088, sys_symlink, *const char_t, *const char_t);
syscall!(089, sys_readlink, *const char_t, *mut char_t, int_t);
syscall!(090, sys_chmod, *const char_t, mode_t);
syscall!(091, sys_fchmod, uint_t, mode_t);
syscall!(092, sys_chown, *const char_t, uid_t, gid_t);
syscall!(093, sys_fchown, uint_t, uid_t, gid_t);
syscall!(094, sys_lchown, *const char_t, uid_t, gid_t);
syscall!(095, sys_umask, int_t);
syscall!(096, sys_gettimeofday, *mut timeval, *mut timezone);
syscall!(097, sys_getrlimit, uint_t, *mut rlimit);
syscall!(098, sys_getrusage, int_t, *mut rusage);
syscall!(099, sys_sysinfo, *mut sysinfo);
syscall!(100, sys_times, *mut sysinfo);
syscall!(101, sys_ptrace, long_t, long_t, ulong_t, ulong_t);
syscall!(102, sys_getuid);
syscall!(103, sys_syslog, int_t, *mut char_t, int_t);
syscall!(104, sys_getgid);
syscall!(105, sys_setuid, uid_t);
syscall!(106, sys_setgid, gid_t);
syscall!(107, sys_geteuid);
syscall!(108, sys_getegid);
syscall!(109, sys_setpgid, pid_t, pid_t);
syscall!(110, sys_getppid);
syscall!(111, sys_getpgrp);
syscall!(112, sys_setsid);
syscall!(113, sys_setreuid, uid_t, uid_t);
syscall!(114, sys_setregid, gid_t, gid_t);
syscall!(115, sys_getgroups, int_t, *mut gid_t);
syscall!(116, sys_setgroups, int_t, *mut gid_t);
syscall!(117, sys_setresuid, *mut uid_t, *mut uid_t, *mut uid_t);
syscall!(118, sys_getresuid, *mut uid_t, *mut uid_t, *mut uid_t);
syscall!(119, sys_setresgid, gid_t, gid_t, gid_t);
syscall!(120, sys_getresgid, *mut gid_t, *mut gid_t, *mut gid_t);
syscall!(121, sys_getpgid, pid_t);
syscall!(122, sys_setfsuid, uid_t);
syscall!(123, sys_setfsgid, gid_t);
syscall!(124, sys_getsid, pid_t);
syscall!(125, sys_capget, cap_user_header_t, cap_user_data_t);
syscall!(126, sys_capset, cap_user_header_t, *const cap_user_data_t);
syscall!(127, sys_rt_sigpending, *mut sigset_t, size_t);
// TODO syscall!(128, sys_rt_sigtimedwait, *sigset_t, *mut siginfo_t, *timespec, size_t);
// TODO syscall!(129, sys_rt_sigqueueinfo, pid_t, int_t, *mut siginfo_t);
syscall!(130, sys_rt_sigsuspend, *mut sigset_t, size_t);
syscall!(131, sys_sigaltstack, *const stack_t, *mut stack_t);
syscall!(132, sys_utime, *mut char_t, *mut utimbuf);
syscall!(133, sys_mknod, *const char_t, int_t, uint_t);
// syscall!(134, sys_uselib, NOT);
syscall!(135, sys_personality, uint_t);
syscall!(136, sys_ustat, uint_t, *mut ustat);
syscall!(137, sys_statfs, *const char_t, *mut statfs);
syscall!(138, sys_fstatfs, uint_t, *mut statfs);
syscall!(139, sys_sysfs, int_t, ulong_t, ulong_t);
syscall!(140, sys_getpriority, int_t, int_t);
syscall!(141, sys_setpriority, int_t, int_t, int_t);
syscall!(142, sys_sched_setparam, pid_t, *mut sched_param);
syscall!(143, sys_sched_getparam, pid_t, *mut sched_param);
syscall!(144, sys_sched_setscheduler, pid_t, int_t, *mut sched_param);
syscall!(145, sys_sched_getscheduler, pid_t);
syscall!(146, sys_sched_get_priority_max, int_t);
syscall!(147, sys_sched_get_priority_min, int_t);
syscall!(148, sys_sched_rr_get_int_terval, pid_t, *mut timespec);
syscall!(149, sys_mlock, ulong_t, size_t);
syscall!(150, sys_munlock, ulong_t, size_t);
syscall!(151, sys_mlockall, int_t);
syscall!(152, sys_munlockall);
syscall!(153, sys_vhangup);
syscall!(154, sys_modify_ldt, int_t, *mut void_t, ulong_t);
syscall!(155, sys_pivot_root, *const char_t, *const char_t);
syscall!(156, sys__sysctl, *mut __sysctl_args);
// This causes llvm to segfault syscall!(157, sys_prctl, int_t, ulong_t, ulong_t, ulong_t, ();, ulong_t)
// TODO syscall!(158, sys_arch_prctl, *mut task_struct, int_t, *mut ulong_t);
syscall!(159, sys_adjtimex, *mut timex);
syscall!(160, sys_setrlimit, uint_t, *mut rlimit);
syscall!(161, sys_chroot, *const char_t);
syscall!(162, sys_sync);
syscall!(163, sys_acct, *const char_t);
syscall!(164, sys_settimeofday, *mut timeval, *mut timezone);
syscall!(165, sys_mount, *mut char_t, *mut char_t, *mut char_t, ulong_t, *mut void_t);
syscall!(166, sys_umount2, *const char_t, int_t);
syscall!(167, sys_swapon, *const char_t, int_t);
syscall!(168, sys_swapoff, *const char_t);
syscall!(169, sys_reboot, int_t, int_t, uint_t, *mut void_t);
syscall!(170, sys_sethostname, *mut char_t, int_t);
syscall!(171, sys_setdomainname, *mut char_t, int_t);
syscall!(172, sys_iopl, uint_t, *mut pt_regs);
syscall!(173, sys_ioperm, ulong_t, ulong_t, int_t);
// syscall!(174, sys_create_module, REMOVED IN Linux 2.);
syscall!(175, sys_init_module, *mut void_t, ulong_t, *const char_t);
syscall!(176, sys_delete_module, *const char_t, uint_t);
// syscall!(177, sys_get_kernel_syms, REMOVED IN Linux 2.);
// syscall!(178, sys_query_module, REMOVED IN Linux 2.);
syscall!(179, sys_quotactl, uint_t, *const char_t, qid_t, *mut void_t);
// syscall!(180, sys_nfsservctl, NOT);
// syscall!(181, sys_getpmsg, NOT);
// syscall!(182, sys_putpmsg, NOT);
// syscall!(183, sys_afs_syscall, NOT);
// syscall!(184, sys_tuxcall, NOT);
// syscall!(185, sys_security, NOT);
syscall!(186, sys_gettid);
syscall!(187, sys_readahead, int_t, loff_t, size_t);
syscall!(188, sys_setxattr, *const char_t, *const char_t, *const void_t, size_t, int_t);
syscall!(189, sys_lsetxattr, *const char_t, *const char_t, *const void_t, size_t, int_t);
syscall!(190, sys_fsetxattr, int_t, *const char_t, *const void_t, size_t, int_t);
syscall!(191, sys_getxattr, *const char_t, *const char_t, *mut void_t, size_t);
syscall!(192, sys_lgetxattr, *const char_t, *const char_t, *mut void_t, size_t);
syscall!(193, sys_fgetxattr, int_t, *const char_t, *mut void_t, size_t);
syscall!(194, sys_listxattr, *const char_t, *mut char_t, size_t);
syscall!(195, sys_llistxattr, *const char_t, *mut char_t, size_t);
syscall!(196, sys_flistxattr, int_t, *mut char_t, size_t);
syscall!(197, sys_removexattr, *const char_t, *const char_t);
syscall!(198, sys_lremovexattr, *const char_t, *const char_t);
syscall!(199, sys_fremovexattr, int_t, *const char_t);
// TODO syscall!(200, sys_tkill, pid_t, ing);
syscall!(201, sys_time, *mut time_t);
syscall!(202, sys_futex, *mut u32, int_t, u32, *mut timespec, *mut u32, u32);
syscall!(203, sys_sched_setaffinity, pid_t, uint_t, *mut ulong_t);
syscall!(204, sys_sched_getaffinity, pid_t, uint_t, *mut ulong_t);
// syscall!(205, sys_set_thread_area, NOT IMPLEMENTED. Use);
syscall!(206, sys_io_setup, uint_t, *mut aio_context_t);
syscall!(207, sys_io_destroy, aio_context_t);
syscall!(208, sys_io_getevents, aio_context_t, long_t, long_t, *mut io_event);
syscall!(209, sys_io_submit, aio_context_t, long_t, *mut *mut iocb);
syscall!(210, sys_io_cancel, aio_context_t, *mut iocb, *mut *mut io_event);
// syscall!(211, sys_get_thread_area, NOT IMPLEMENTED. Use);
syscall!(212, sys_lookup_dcookie, u64, long_t, long_t);
syscall!(213, sys_epoll_create, int_t);
// syscall!(214, sys_epoll_ctl_old, NOT);
// syscall!(215, sys_epoll_wait_old, NOT);
syscall!(216, sys_remap_file_pages, ulong_t, ulong_t, ulong_t, ulong_t, ulong_t);
syscall!(217, sys_getdents64, uint_t, *mut linux_dirent64, uint_t);
syscall!(218, sys_set_tid_address, *mut int_t);
syscall!(219, sys_restart_syscall);
syscall!(220, sys_semtimedop, int_t, *mut sembuf, uint_t, *const timespec);
syscall!(221, sys_fadvise64, int_t, loff_t, size_t, int_t);
// TODO syscall!(222, sys_timer_create, *clockid_t, *mut sigevent, *mut timer_t);
syscall!(223, sys_timer_settime, timer_t, int_t, *const itimerspec, *mut itimerspec);
syscall!(224, sys_timer_gettime, timer_t, *mut itimerspec);
syscall!(225, sys_timer_getoverrun, timer_t);
syscall!(226, sys_timer_delete, timer_t);
syscall!(227, sys_clock_settime, *const clockid_t, *const timespec);
syscall!(228, sys_clock_gettime, *const clockid_t, *mut timespec);
syscall!(229, sys_clock_getres, *const clockid_t, *mut timespec);
syscall!(230, sys_clock_nanosleep, *const clockid_t, int_t, *const timespec, *mut timespec);
syscall!(231, sys_exit_group, int_t);
syscall!(232, sys_epoll_wait, int_t, *mut epoll_event, int_t, int_t);
syscall!(233, sys_epoll_ctl, int_t, int_t, int_t, *mut epoll_event);
syscall!(234, sys_tgkill, pid_t, pid_t, int_t);
syscall!(235, sys_utimes, *const char_t, *mut timeval); // WARNING *mut char_t
// syscall!(236, sys_vserver, NOT);
syscall!(237, sys_mbind, ulong_t, ulong_t, ulong_t, *mut ulong_t, ulong_t, uint_t);
syscall!(238, sys_set_mempolicy, int_t, *mut ulong_t, ulong_t);
syscall!(239, sys_get_mempolicy, *mut int_t, *mut ulong_t, ulong_t, ulong_t, ulong_t);
syscall!(240, sys_mq_open, *const char_t, int_t, mode_t, *mut mq_attr);
syscall!(241, sys_mq_unlink, *const char_t);
syscall!(242, sys_mq_timedsend, mqd_t, *const char_t, size_t, uint_t, *const timespec);
syscall!(243, sys_mq_timedreceive, mqd_t, *mut char_t, size_t, *mut uint_t, *const timespec);
// TODO syscall!(244, sys_mq_notify, mqd_t, *sigevent);
syscall!(245, sys_mq_getsetattr, mqd_t, *const mq_attr, *mut mq_attr);
syscall!(246, sys_kexec_load, ulong_t, ulong_t, *mut kexec_segment, ulong_t);
// TODO syscall!(247, sys_waitid, int_t, pid_t, *mut siginfo, int_t, *mut rusage);
syscall!(248, sys_add_key, *const char_t, *const char_t, *const void_t, size_t);
syscall!(249, sys_request_key, *const char_t, *const char_t, *const char_t, key_serial_t);
syscall!(250, sys_keyctl, int_t, ulong_t, ulong_t, ulong_t, ulong_t);
syscall!(251, sys_ioprio_set, int_t, int_t, int_t);
syscall!(252, sys_ioprio_get, int_t, int_t);
syscall!(253, sys_inotify_init);
syscall!(254, sys_inotify_add_watch, int_t, *const char_t, u32);
syscall!(255, sys_inotify_rm_watch, int_t, i32);
syscall!(256, sys_migrate_pages, pid_t, ulong_t, *const ulong_t, *const ulong_t);
syscall!(257, sys_openat, int_t, *const char_t, int_t, int_t);
syscall!(258, sys_mkdirat, int_t, *const char_t, int_t);
syscall!(259, sys_mknodat, int_t, *const char_t, int_t, uint_t);
syscall!(260, sys_fchownat, int_t, *const char_t, uid_t, gid_t, int_t);
syscall!(261, sys_futimesat, int_t, *const char_t, *mut timeval);
syscall!(262, sys_newfstatat, int_t, *const char_t, *mut stat, int_t);
syscall!(263, sys_unlinkat, int_t, *const char_t, int_t);
syscall!(264, sys_renameat, int_t, *const char_t, int_t, *const char_t);
syscall!(265, sys_linkat, int_t, *const char_t, int_t, *const char_t, int_t);
syscall!(266, sys_symlinkat, *const char_t, int_t, *const char_t);
syscall!(267, sys_readlinkat, int_t, *const char_t, *mut char_t, int_t);
syscall!(268, sys_fchmodat, int_t, *const char_t, mode_t);
syscall!(269, sys_faccessat, int_t, *const char_t, int_t);
syscall!(270, sys_pselect6, int_t, *mut fd_set, *mut fd_set, *mut fd_set, *mut timespec,
*mut void_t);
syscall!(271, sys_ppoll, *mut pollfd, uint_t, *mut timespec, *const sigset_t, size_t);
syscall!(272, sys_unshare, ulong_t);
syscall!(273, sys_set_robust_list, *mut robust_list_head, size_t);
syscall!(274, sys_get_robust_list, int_t, *mut *mut robust_list_head, *mut size_t);
syscall!(275, sys_splice, int_t, *mut loff_t, int_t, *mut loff_t, size_t, uint_t);
syscall!(276, sys_tee, int_t, int_t, size_t, uint_t);
syscall!(277, sys_sync_file_range, long_t, loff_t, loff_t, long_t);
syscall!(278, sys_vmsplice, int_t, *const iovec, ulong_t, uint_t);
syscall!(279, sys_move_pages, pid_t, ulong_t, *mut *const void_t, *const int_t, *mut int_t, int_t);
syscall!(280, sys_utimensat, int_t, *const char_t, *mut timespec, int_t);
syscall!(281, sys_epoll_pwait, int_t, *mut epoll_event, int_t, int_t, *const sigset_t, size_t);
syscall!(282, sys_signalfd, int_t, *mut sigset_t, size_t);
syscall!(283, sys_timerfd_create, int_t, int_t);
syscall!(284, sys_eventfd, uint_t);
syscall!(285, sys_fallocate, long_t, long_t, loff_t, loff_t);
syscall!(286, sys_timerfd_settime, int_t, int_t, *const itimerspec, *mut itimerspec);
syscall!(287, sys_timerfd_gettime, int_t, *mut itimerspec);
syscall!(288, sys_accept4, int_t, *mut sockaddr, *mut int_t, int_t);
syscall!(289, sys_signalfd4, int_t, *mut sigset_t, size_t, int_t);
syscall!(290, sys_eventfd2, uint_t, int_t);
syscall!(291, sys_epoll_create1, int_t);
syscall!(292, sys_dup3, uint_t, uint_t, int_t);
syscall!(293, sys_pipe2, *mut int_t, int_t);
syscall!(294, sys_inotify_init1, int_t);
syscall!(295, sys_preadv, ulong_t, *const iovec, ulong_t, ulong_t, ulong_t);
syscall!(296, sys_pwritev, ulong_t, *const iovec, ulong_t, ulong_t, ulong_t);
// TODO syscall!(297, sys_rt_tgsigqueueinfo, pid_t, pid_t, int_t, *mut siginfo_t);
// TODO syscall!(298, sys_perf_event_open, *mut perf_event_attr, pid_t, int_t, int_t, ulong_t);
syscall!(299, sys_recvmmsg, int_t, *mut msghdr, uint_t, uint_t, *mut timespec);
syscall!(300, sys_fanotify_init, uint_t, uint_t);
syscall!(301, sys_fanotify_mark, long_t, long_t, u64, long_t, long_t);
syscall!(302, sys_prlimit64, pid_t, uint_t, *const rlimit64, *mut rlimit64);
syscall!(303, sys_name_to_handle_at, int_t, *const char_t, *mut file_handle, *mut int_t, int_t);
syscall!(304, sys_open_by_handle_at, int_t, *const char_t, *mut file_handle, *mut int_t, int_t);
syscall!(305, sys_clock_adjtime, clockid_t, *mut timex);
syscall!(306, sys_syncfs, int_t);
syscall!(307, sys_sendmmsg, int_t, *mut mmsghdr, uint_t, uint_t);
syscall!(308, sys_setns, int_t, int_t);
syscall!(309, sys_getcpu, *mut uint_t, *mut uint_t, *mut getcpu_cache);
syscall!(310, sys_process_vm_readv, pid_t, *const iovec, ulong_t, *const iovec, ulong_t, ulong_t);
syscall!(311, sys_process_vm_writev, pid_t, *const iovec, ulong_t, *const iovec, ulong_t, ulong_t);
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qitemeditorfactory.h
// dst-file: /src/widgets/qitemeditorfactory.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
use super::super::core::qbytearray::*; // 771
use super::qwidget::*; // 773
// use super::qitemeditorfactory::QItemEditorCreatorBase; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QItemEditorCreatorBase_Class_Size() -> c_int;
// proto: QByteArray QItemEditorCreatorBase::valuePropertyName();
fn C_ZNK22QItemEditorCreatorBase17valuePropertyNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QWidget * QItemEditorCreatorBase::createWidget(QWidget * parent);
fn C_ZNK22QItemEditorCreatorBase12createWidgetEP7QWidget(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: void QItemEditorCreatorBase::~QItemEditorCreatorBase();
fn C_ZN22QItemEditorCreatorBaseD2Ev(qthis: u64 /* *mut c_void*/);
fn QItemEditorFactory_Class_Size() -> c_int;
// proto: void QItemEditorFactory::QItemEditorFactory();
fn C_ZN18QItemEditorFactoryC2Ev() -> u64;
// proto: QByteArray QItemEditorFactory::valuePropertyName(int userType);
fn C_ZNK18QItemEditorFactory17valuePropertyNameEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: static const QItemEditorFactory * QItemEditorFactory::defaultFactory();
fn C_ZN18QItemEditorFactory14defaultFactoryEv() -> *mut c_void;
// proto: void QItemEditorFactory::~QItemEditorFactory();
fn C_ZN18QItemEditorFactoryD2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QItemEditorFactory::registerEditor(int userType, QItemEditorCreatorBase * creator);
fn C_ZN18QItemEditorFactory14registerEditorEiP22QItemEditorCreatorBase(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void);
// proto: static void QItemEditorFactory::setDefaultFactory(QItemEditorFactory * factory);
fn C_ZN18QItemEditorFactory17setDefaultFactoryEPS_(arg0: *mut c_void);
// proto: QWidget * QItemEditorFactory::createEditor(int userType, QWidget * parent);
fn C_ZNK18QItemEditorFactory12createEditorEiP7QWidget(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void) -> *mut c_void;
} // <= ext block end
// body block begin =>
// class sizeof(QItemEditorCreatorBase)=8
#[derive(Default)]
pub struct QItemEditorCreatorBase {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QItemEditorFactory)=1
#[derive(Default)]
pub struct QItemEditorFactory {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QItemEditorCreatorBase {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QItemEditorCreatorBase {
return QItemEditorCreatorBase{qclsinst: qthis, ..Default::default()};
}
}
// proto: QByteArray QItemEditorCreatorBase::valuePropertyName();
impl /*struct*/ QItemEditorCreatorBase {
pub fn valuePropertyName<RetType, T: QItemEditorCreatorBase_valuePropertyName<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.valuePropertyName(self);
// return 1;
}
}
pub trait QItemEditorCreatorBase_valuePropertyName<RetType> {
fn valuePropertyName(self , rsthis: & QItemEditorCreatorBase) -> RetType;
}
// proto: QByteArray QItemEditorCreatorBase::valuePropertyName();
impl<'a> /*trait*/ QItemEditorCreatorBase_valuePropertyName<QByteArray> for () {
fn valuePropertyName(self , rsthis: & QItemEditorCreatorBase) -> QByteArray {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK22QItemEditorCreatorBase17valuePropertyNameEv()};
let mut ret = unsafe {C_ZNK22QItemEditorCreatorBase17valuePropertyNameEv(rsthis.qclsinst)};
let mut ret1 = QByteArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QWidget * QItemEditorCreatorBase::createWidget(QWidget * parent);
impl /*struct*/ QItemEditorCreatorBase {
pub fn createWidget<RetType, T: QItemEditorCreatorBase_createWidget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.createWidget(self);
// return 1;
}
}
pub trait QItemEditorCreatorBase_createWidget<RetType> {
fn createWidget(self , rsthis: & QItemEditorCreatorBase) -> RetType;
}
// proto: QWidget * QItemEditorCreatorBase::createWidget(QWidget * parent);
impl<'a> /*trait*/ QItemEditorCreatorBase_createWidget<QWidget> for (&'a QWidget) {
fn createWidget(self , rsthis: & QItemEditorCreatorBase) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK22QItemEditorCreatorBase12createWidgetEP7QWidget()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK22QItemEditorCreatorBase12createWidgetEP7QWidget(rsthis.qclsinst, arg0)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QItemEditorCreatorBase::~QItemEditorCreatorBase();
impl /*struct*/ QItemEditorCreatorBase {
pub fn free<RetType, T: QItemEditorCreatorBase_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QItemEditorCreatorBase_free<RetType> {
fn free(self , rsthis: & QItemEditorCreatorBase) -> RetType;
}
// proto: void QItemEditorCreatorBase::~QItemEditorCreatorBase();
impl<'a> /*trait*/ QItemEditorCreatorBase_free<()> for () {
fn free(self , rsthis: & QItemEditorCreatorBase) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN22QItemEditorCreatorBaseD2Ev()};
unsafe {C_ZN22QItemEditorCreatorBaseD2Ev(rsthis.qclsinst)};
// return 1;
}
}
impl /*struct*/ QItemEditorFactory {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QItemEditorFactory {
return QItemEditorFactory{qclsinst: qthis, ..Default::default()};
}
}
// proto: void QItemEditorFactory::QItemEditorFactory();
impl /*struct*/ QItemEditorFactory {
pub fn new<T: QItemEditorFactory_new>(value: T) -> QItemEditorFactory {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QItemEditorFactory_new {
fn new(self) -> QItemEditorFactory;
}
// proto: void QItemEditorFactory::QItemEditorFactory();
impl<'a> /*trait*/ QItemEditorFactory_new for () {
fn new(self) -> QItemEditorFactory {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QItemEditorFactoryC2Ev()};
let ctysz: c_int = unsafe{QItemEditorFactory_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN18QItemEditorFactoryC2Ev()};
let rsthis = QItemEditorFactory{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QByteArray QItemEditorFactory::valuePropertyName(int userType);
impl /*struct*/ QItemEditorFactory {
pub fn valuePropertyName<RetType, T: QItemEditorFactory_valuePropertyName<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.valuePropertyName(self);
// return 1;
}
}
pub trait QItemEditorFactory_valuePropertyName<RetType> {
fn valuePropertyName(self , rsthis: & QItemEditorFactory) -> RetType;
}
// proto: QByteArray QItemEditorFactory::valuePropertyName(int userType);
impl<'a> /*trait*/ QItemEditorFactory_valuePropertyName<QByteArray> for (i32) {
fn valuePropertyName(self , rsthis: & QItemEditorFactory) -> QByteArray {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QItemEditorFactory17valuePropertyNameEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK18QItemEditorFactory17valuePropertyNameEi(rsthis.qclsinst, arg0)};
let mut ret1 = QByteArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static const QItemEditorFactory * QItemEditorFactory::defaultFactory();
impl /*struct*/ QItemEditorFactory {
pub fn defaultFactory_s<RetType, T: QItemEditorFactory_defaultFactory_s<RetType>>( overload_args: T) -> RetType {
return overload_args.defaultFactory_s();
// return 1;
}
}
pub trait QItemEditorFactory_defaultFactory_s<RetType> {
fn defaultFactory_s(self ) -> RetType;
}
// proto: static const QItemEditorFactory * QItemEditorFactory::defaultFactory();
impl<'a> /*trait*/ QItemEditorFactory_defaultFactory_s<QItemEditorFactory> for () {
fn defaultFactory_s(self ) -> QItemEditorFactory {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QItemEditorFactory14defaultFactoryEv()};
let mut ret = unsafe {C_ZN18QItemEditorFactory14defaultFactoryEv()};
let mut ret1 = QItemEditorFactory::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QItemEditorFactory::~QItemEditorFactory();
impl /*struct*/ QItemEditorFactory {
pub fn free<RetType, T: QItemEditorFactory_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QItemEditorFactory_free<RetType> {
fn free(self , rsthis: & QItemEditorFactory) -> RetType;
}
// proto: void QItemEditorFactory::~QItemEditorFactory();
impl<'a> /*trait*/ QItemEditorFactory_free<()> for () {
fn free(self , rsthis: & QItemEditorFactory) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QItemEditorFactoryD2Ev()};
unsafe {C_ZN18QItemEditorFactoryD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QItemEditorFactory::registerEditor(int userType, QItemEditorCreatorBase * creator);
impl /*struct*/ QItemEditorFactory {
pub fn registerEditor<RetType, T: QItemEditorFactory_registerEditor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.registerEditor(self);
// return 1;
}
}
pub trait QItemEditorFactory_registerEditor<RetType> {
fn registerEditor(self , rsthis: & QItemEditorFactory) -> RetType;
}
// proto: void QItemEditorFactory::registerEditor(int userType, QItemEditorCreatorBase * creator);
impl<'a> /*trait*/ QItemEditorFactory_registerEditor<()> for (i32, &'a QItemEditorCreatorBase) {
fn registerEditor(self , rsthis: & QItemEditorFactory) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QItemEditorFactory14registerEditorEiP22QItemEditorCreatorBase()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN18QItemEditorFactory14registerEditorEiP22QItemEditorCreatorBase(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: static void QItemEditorFactory::setDefaultFactory(QItemEditorFactory * factory);
impl /*struct*/ QItemEditorFactory {
pub fn setDefaultFactory_s<RetType, T: QItemEditorFactory_setDefaultFactory_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setDefaultFactory_s();
// return 1;
}
}
pub trait QItemEditorFactory_setDefaultFactory_s<RetType> {
fn setDefaultFactory_s(self ) -> RetType;
}
// proto: static void QItemEditorFactory::setDefaultFactory(QItemEditorFactory * factory);
impl<'a> /*trait*/ QItemEditorFactory_setDefaultFactory_s<()> for (&'a QItemEditorFactory) {
fn setDefaultFactory_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QItemEditorFactory17setDefaultFactoryEPS_()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN18QItemEditorFactory17setDefaultFactoryEPS_(arg0)};
// return 1;
}
}
// proto: QWidget * QItemEditorFactory::createEditor(int userType, QWidget * parent);
impl /*struct*/ QItemEditorFactory {
pub fn createEditor<RetType, T: QItemEditorFactory_createEditor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.createEditor(self);
// return 1;
}
}
pub trait QItemEditorFactory_createEditor<RetType> {
fn createEditor(self , rsthis: & QItemEditorFactory) -> RetType;
}
// proto: QWidget * QItemEditorFactory::createEditor(int userType, QWidget * parent);
impl<'a> /*trait*/ QItemEditorFactory_createEditor<QWidget> for (i32, &'a QWidget) {
fn createEditor(self , rsthis: & QItemEditorFactory) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QItemEditorFactory12createEditorEiP7QWidget()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK18QItemEditorFactory12createEditorEiP7QWidget(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// <= body block end
|
use clippy_utils::diagnostics::span_lint;
use clippy_utils::trait_ref_of_method;
use rustc_hir as hir;
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::TypeFoldable;
use rustc_middle::ty::{Adt, Array, Ref, Slice, Tuple, Ty};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::symbol::sym;
use std::iter;
declare_clippy_lint! {
/// ### What it does
/// Checks for sets/maps with mutable key types.
///
/// ### Why is this bad?
/// All of `HashMap`, `HashSet`, `BTreeMap` and
/// `BtreeSet` rely on either the hash or the order of keys be unchanging,
/// so having types with interior mutability is a bad idea.
///
/// ### Known problems
///
/// #### False Positives
/// It's correct to use a struct that contains interior mutability as a key, when its
/// implementation of `Hash` or `Ord` doesn't access any of the interior mutable types.
/// However, this lint is unable to recognize this, so it will often cause false positives in
/// theses cases. The `bytes` crate is a great example of this.
///
/// #### False Negatives
/// For custom `struct`s/`enum`s, this lint is unable to check for interior mutability behind
/// indirection. For example, `struct BadKey<'a>(&'a Cell<usize>)` will be seen as immutable
/// and cause a false negative if its implementation of `Hash`/`Ord` accesses the `Cell`.
///
/// This lint does check a few cases for indirection. Firstly, using some standard library
/// types (`Option`, `Result`, `Box`, `Rc`, `Arc`, `Vec`, `VecDeque`, `BTreeMap` and
/// `BTreeSet`) directly as keys (e.g. in `HashMap<Box<Cell<usize>>, ()>`) **will** trigger the
/// lint, because the impls of `Hash`/`Ord` for these types directly call `Hash`/`Ord` on their
/// contained type.
///
/// Secondly, the implementations of `Hash` and `Ord` for raw pointers (`*const T` or `*mut T`)
/// apply only to the **address** of the contained value. Therefore, interior mutability
/// behind raw pointers (e.g. in `HashSet<*mut Cell<usize>>`) can't impact the value of `Hash`
/// or `Ord`, and therefore will not trigger this link. For more info, see issue
/// [#6745](https://github.com/rust-lang/rust-clippy/issues/6745).
///
/// ### Example
/// ```rust
/// use std::cmp::{PartialEq, Eq};
/// use std::collections::HashSet;
/// use std::hash::{Hash, Hasher};
/// use std::sync::atomic::AtomicUsize;
///# #[allow(unused)]
///
/// struct Bad(AtomicUsize);
/// impl PartialEq for Bad {
/// fn eq(&self, rhs: &Self) -> bool {
/// ..
/// ; unimplemented!();
/// }
/// }
///
/// impl Eq for Bad {}
///
/// impl Hash for Bad {
/// fn hash<H: Hasher>(&self, h: &mut H) {
/// ..
/// ; unimplemented!();
/// }
/// }
///
/// fn main() {
/// let _: HashSet<Bad> = HashSet::new();
/// }
/// ```
#[clippy::version = "1.42.0"]
pub MUTABLE_KEY_TYPE,
suspicious,
"Check for mutable `Map`/`Set` key type"
}
declare_lint_pass!(MutableKeyType => [ MUTABLE_KEY_TYPE ]);
impl<'tcx> LateLintPass<'tcx> for MutableKeyType {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
if let hir::ItemKind::Fn(ref sig, ..) = item.kind {
check_sig(cx, item.hir_id(), sig.decl);
}
}
fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'tcx>) {
if let hir::ImplItemKind::Fn(ref sig, ..) = item.kind {
if trait_ref_of_method(cx, item.hir_id()).is_none() {
check_sig(cx, item.hir_id(), sig.decl);
}
}
}
fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'tcx>) {
if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
check_sig(cx, item.hir_id(), sig.decl);
}
}
fn check_local(&mut self, cx: &LateContext<'_>, local: &hir::Local<'_>) {
if let hir::PatKind::Wild = local.pat.kind {
return;
}
check_ty(cx, local.span, cx.typeck_results().pat_ty(&*local.pat));
}
}
fn check_sig<'tcx>(cx: &LateContext<'tcx>, item_hir_id: hir::HirId, decl: &hir::FnDecl<'_>) {
let fn_def_id = cx.tcx.hir().local_def_id(item_hir_id);
let fn_sig = cx.tcx.fn_sig(fn_def_id);
for (hir_ty, ty) in iter::zip(decl.inputs, fn_sig.inputs().skip_binder()) {
check_ty(cx, hir_ty.span, ty);
}
check_ty(cx, decl.output.span(), cx.tcx.erase_late_bound_regions(fn_sig.output()));
}
// We want to lint 1. sets or maps with 2. not immutable key types and 3. no unerased
// generics (because the compiler cannot ensure immutability for unknown types).
fn check_ty<'tcx>(cx: &LateContext<'tcx>, span: Span, ty: Ty<'tcx>) {
let ty = ty.peel_refs();
if let Adt(def, substs) = ty.kind() {
let is_keyed_type = [sym::HashMap, sym::BTreeMap, sym::HashSet, sym::BTreeSet]
.iter()
.any(|diag_item| cx.tcx.is_diagnostic_item(*diag_item, def.did));
if is_keyed_type && is_interior_mutable_type(cx, substs.type_at(0), span) {
span_lint(cx, MUTABLE_KEY_TYPE, span, "mutable key type");
}
}
}
/// Determines if a type contains interior mutability which would affect its implementation of
/// [`Hash`] or [`Ord`].
fn is_interior_mutable_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span) -> bool {
match *ty.kind() {
Ref(_, inner_ty, mutbl) => mutbl == hir::Mutability::Mut || is_interior_mutable_type(cx, inner_ty, span),
Slice(inner_ty) => is_interior_mutable_type(cx, inner_ty, span),
Array(inner_ty, size) => {
size.try_eval_usize(cx.tcx, cx.param_env).map_or(true, |u| u != 0)
&& is_interior_mutable_type(cx, inner_ty, span)
},
Tuple(..) => ty.tuple_fields().any(|ty| is_interior_mutable_type(cx, ty, span)),
Adt(def, substs) => {
// Special case for collections in `std` who's impl of `Hash` or `Ord` delegates to
// that of their type parameters. Note: we don't include `HashSet` and `HashMap`
// because they have no impl for `Hash` or `Ord`.
let is_std_collection = [
sym::Option,
sym::Result,
sym::LinkedList,
sym::Vec,
sym::VecDeque,
sym::BTreeMap,
sym::BTreeSet,
sym::Rc,
sym::Arc,
]
.iter()
.any(|diag_item| cx.tcx.is_diagnostic_item(*diag_item, def.did));
let is_box = Some(def.did) == cx.tcx.lang_items().owned_box();
if is_std_collection || is_box {
// The type is mutable if any of its type parameters are
substs.types().any(|ty| is_interior_mutable_type(cx, ty, span))
} else {
!ty.has_escaping_bound_vars()
&& cx.tcx.layout_of(cx.param_env.and(ty)).is_ok()
&& !ty.is_freeze(cx.tcx.at(span), cx.param_env)
}
},
_ => false,
}
}
|
use core::f32;
use core::u32;
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn fmodf(x: f32, y: f32) -> f32 {
let mut uxi = x.to_bits();
let mut uyi = y.to_bits();
let mut ex = (uxi >> 23 & 0xff) as i32;
let mut ey = (uyi >> 23 & 0xff) as i32;
let sx = uxi & 0x80000000;
let mut i;
if uyi << 1 == 0 || y.is_nan() || ex == 0xff {
return (x * y) / (x * y);
}
if uxi << 1 <= uyi << 1 {
if uxi << 1 == uyi << 1 {
return 0.0 * x;
}
return x;
}
/* normalize x and y */
if ex == 0 {
i = uxi << 9;
while i >> 31 == 0 {
ex -= 1;
i <<= 1;
}
uxi <<= -ex + 1;
} else {
uxi &= u32::MAX >> 9;
uxi |= 1 << 23;
}
if ey == 0 {
i = uyi << 9;
while i >> 31 == 0 {
ey -= 1;
i <<= 1;
}
uyi <<= -ey + 1;
} else {
uyi &= u32::MAX >> 9;
uyi |= 1 << 23;
}
/* x mod y */
while ex > ey {
i = uxi.wrapping_sub(uyi);
if i >> 31 == 0 {
if i == 0 {
return 0.0 * x;
}
uxi = i;
}
uxi <<= 1;
ex -= 1;
}
i = uxi.wrapping_sub(uyi);
if i >> 31 == 0 {
if i == 0 {
return 0.0 * x;
}
uxi = i;
}
while uxi >> 23 == 0 {
uxi <<= 1;
ex -= 1;
}
/* scale result up */
if ex > 0 {
uxi -= 1 << 23;
uxi |= (ex as u32) << 23;
} else {
uxi >>= -ex + 1;
}
uxi |= sx;
f32::from_bits(uxi)
}
|
//! Audio file helpers
//!
//!
use std::f64;
pub fn audio_file_samples(path: &str) -> Vec<i16> {
let mut reader = hound::WavReader::open(path).unwrap();
let samples = reader.samples::<i16>();
let mut samples_vec: Vec<i16> = Vec::new();
let mut count = 0;
{
let sampels_vec2 = &mut samples_vec;
samples.for_each(|s| {
count += 1;
sampels_vec2.push(s.unwrap());
});
}
samples_vec
}
/**
* Cross Correlation Index
*
* Shoul return 1 when the 2 vectors contain the same items.
*
* See https://github.com/actonDev/wavelet-denoiser/blob/master/src/metric-cci.py
*/
pub fn cross_correlation_index(s1: &Vec<i16>, s2: &Vec<i16>) -> f64 {
if s1.len() != s2.len() {
return 0.0;
}
let s1_mean = mean(s1);
let s2_mean = mean(s2);
let mut sum_diff_sq_1 = 0.0;
let mut sum_diff_sq_2 = 0.0;
let mut sum_nominator: f64 = 0.0;
for it in s1.iter().zip(s2.iter()) {
let (x1, x2) = it;
// *bi = 2 * *ai;
let diff_s1 = (*x1 as f64) - s1_mean;
let diff_s2 = (*x2 as f64) - s2_mean;
sum_nominator += diff_s1 * diff_s2;
sum_diff_sq_1 += diff_s1.powi(2);
sum_diff_sq_2 += diff_s2.powi(2);
// sumDiffsBSquared += diffB * *2;
// counter += 1;
}
let cii: f64 = sum_nominator / (sum_diff_sq_1 * sum_diff_sq_2).sqrt() as f64;
return cii;
}
/**
* Root Mean Square Error
*/
pub fn rmse(s1: &Vec<i16>, s2: &Vec<i16>) -> f64 {
if s1.len() != s2.len() {
return f64::MAX;
}
let mut sum_sq: f64 = 0.0;
// let mut sum_mean_sq : f64 = 0.0;
for it in s1.iter().zip(s2.iter()) {
let (x1, x2) = it;
// note: without converting to i32 I was getting multiply overflow error
// sum_mea/n_sq += ((x1 - x2) as i32).pow(2) as f64 / s1.len() as f64;
sum_sq += ((x1 - x2) as i32).pow(2) as f64;
// println!("sum mean sq {}", sum_mean_sq);
}
// println!("sum_mean_sq res is {}", sum_mean_sq.sqrt());
// sum.sqrt()
let sum_sq_res = (sum_sq / s1.len() as f64).sqrt();
// println!("sum res {}", sum_sq_res);
sum_sq_res
// (sum / s1.len() as f64 ).sqrt()
// 4824.83864474248
}
pub fn mean(xs: &Vec<i16>) -> f64 {
let mut sum: f64 = 0.0;
for x in xs {
sum += *x as f64;
}
sum as f64 / xs.len() as f64
}
|
//
// Sysinfo
//
// Copyright (c) 2017 Guillaume Gomez
//
#![crate_type = "bin"]
#![allow(unused_must_use, non_upper_case_globals)]
extern crate sysinfo;
use sysinfo::{NetworkExt, Pid, ProcessExt, ProcessorExt, Signal, System, SystemExt};
use sysinfo::Signal::*;
use std::io::{self, BufRead, Write};
use std::str::FromStr;
const signals: [Signal; 31] = [Hangup, Interrupt, Quit, Illegal, Trap, Abort, Bus,
FloatingPointException, Kill, User1, Segv, User2, Pipe, Alarm,
Term, Stklft, Child, Continue, Stop, TSTP, TTIN, TTOU, Urgent,
XCPU, XFSZ, VirtualAlarm, Profiling, Winch, IO, Power, Sys];
fn print_help() {
writeln!(&mut io::stdout(), "== Help menu ==");
writeln!(&mut io::stdout(), "help : show this menu");
writeln!(&mut io::stdout(), "signals : show the available signals");
writeln!(&mut io::stdout(), "refresh : reloads all processes' information");
writeln!(&mut io::stdout(), "refresh [pid] : reloads corresponding process' information");
writeln!(&mut io::stdout(), "refresh_disks : reloads only disks' information");
writeln!(&mut io::stdout(), "show [pid | name] : show information of the given process \
corresponding to [pid | name]");
writeln!(&mut io::stdout(), "kill [pid] [signal]: send [signal] to the process with this \
[pid]. 0 < [signal] < 32");
writeln!(&mut io::stdout(), "proc : Displays proc state");
writeln!(&mut io::stdout(), "memory : Displays memory state");
writeln!(&mut io::stdout(), "temperature : Displays components' temperature");
writeln!(&mut io::stdout(), "disks : Displays disks' information");
writeln!(&mut io::stdout(), "network : Displays network' information");
writeln!(&mut io::stdout(), "all : Displays all process name and pid");
writeln!(&mut io::stdout(), "uptime : Displays system uptime");
writeln!(&mut io::stdout(), "quit : exit the program");
}
fn interpret_input(input: &str, sys: &mut System) -> bool {
match input.trim() {
"help" => print_help(),
"refresh_disks" => {
writeln!(&mut io::stdout(), "Refreshing disk list...");
sys.refresh_disk_list();
writeln!(&mut io::stdout(), "Done.");
}
"signals" => {
let mut nb = 1i32;
for sig in &signals {
writeln!(&mut io::stdout(), "{:2}:{:?}", nb, sig);
nb += 1;
}
}
"proc" => {
// Note: you should refresh a few times before using this, so that usage statistics can be ascertained
let procs = sys.get_processor_list();
writeln!(&mut io::stdout(), "total process usage: {}%", procs[0].get_cpu_usage());
for proc_ in procs.iter().skip(1) {
writeln!(&mut io::stdout(), "{:?}", proc_);
}
}
"memory" => {
writeln!(&mut io::stdout(), "total memory: {} kB", sys.get_total_memory());
writeln!(&mut io::stdout(), "used memory : {} kB", sys.get_used_memory());
writeln!(&mut io::stdout(), "total swap : {} kB", sys.get_total_swap());
writeln!(&mut io::stdout(), "used swap : {} kB", sys.get_used_swap());
}
"quit" | "exit" => return true,
"all" => {
for (pid, proc_) in sys.get_process_list() {
writeln!(&mut io::stdout(), "{}:{} status={:?}", pid, proc_.name(), proc_.status());
}
}
e if e.starts_with("show ") => {
let tmp : Vec<&str> = e.split(' ').collect();
if tmp.len() != 2 {
writeln!(&mut io::stdout(), "show command takes a pid or a name in parameter!");
writeln!(&mut io::stdout(), "example: show 1254");
} else if let Ok(pid) = Pid::from_str(tmp[1]) {
match sys.get_process(pid) {
Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
None => writeln!(&mut io::stdout(), "pid not found")
};
} else {
let proc_name = tmp[1];
for proc_ in sys.get_process_by_name(proc_name) {
writeln!(&mut io::stdout(), "==== {} ====", proc_.name());
writeln!(&mut io::stdout(), "{:?}", proc_);
}
}
}
"temperature" => {
for component in sys.get_components_list() {
writeln!(&mut io::stdout(), "{:?}", component);
}
}
"network" => {
writeln!(&mut io::stdout(), "input data : {} B", sys.get_network().get_income());
writeln!(&mut io::stdout(), "output data: {} B", sys.get_network().get_outcome());
}
"show" => {
writeln!(&mut io::stdout(), "'show' command expects a pid number or a process name");
}
e if e.starts_with("kill ") => {
let tmp : Vec<&str> = e.split(' ').collect();
if tmp.len() != 3 {
writeln!(&mut io::stdout(),
"kill command takes the pid and a signal number in parameter !");
writeln!(&mut io::stdout(), "example: kill 1254 9");
} else {
let pid = Pid::from_str(tmp[1]).unwrap();
let signal = i32::from_str(tmp[2]).unwrap();
if signal < 1 || signal > 31 {
writeln!(&mut io::stdout(),
"Signal must be between 0 and 32 ! See the signals list with the \
signals command");
} else {
match sys.get_process(pid) {
Some(p) => {
writeln!(&mut io::stdout(), "kill: {}",
p.kill(*signals.get(signal as usize - 1).unwrap()));
},
None => {
writeln!(&mut io::stdout(), "pid not found");
}
};
}
}
}
"disks" => {
for disk in sys.get_disks() {
writeln!(&mut io::stdout(), "{:?}", disk);
}
}
"uptime" => {
let mut uptime = sys.get_uptime();
let days = uptime / 86400;
uptime -= days * 86400;
let hours = uptime / 3600;
uptime -= hours * 3600;
let minutes = uptime / 60;
writeln!(&mut io::stdout(),
"{} days {} hours {} minutes",
days,
hours,
minutes);
}
x if x.starts_with("refresh") => {
if x == "refresh" {
writeln!(&mut io::stdout(), "Getting processes' information...");
sys.refresh_all();
writeln!(&mut io::stdout(), "Done.");
} else if x.starts_with("refresh ") {
writeln!(&mut io::stdout(), "Getting process' information...");
if let Some(pid) = x.split(' ').filter_map(|pid| pid.parse().ok()).take(1).next() {
if sys.refresh_process(pid) {
writeln!(&mut io::stdout(), "Process `{}` updated successfully", pid);
} else {
writeln!(&mut io::stdout(), "Process `{}` couldn't be updated...", pid);
}
} else {
writeln!(&mut io::stdout(), "Invalid [pid] received...");
}
} else {
writeln!(&mut io::stdout(),
"\"{}\": Unknown command. Enter 'help' if you want to get the commands' \
list.", x);
}
}
e => {
writeln!(&mut io::stdout(),
"\"{}\": Unknown command. Enter 'help' if you want to get the commands' \
list.", e);
}
}
false
}
fn main() {
println!("Getting processes' information...");
let mut t = System::new();
println!("Done.");
let t_stin = io::stdin();
let mut stin = t_stin.lock();
let mut done = false;
println!("To get the commands' list, enter 'help'.");
while !done {
let mut input = String::new();
write!(&mut io::stdout(), "> ");
io::stdout().flush();
stin.read_line(&mut input);
if (&input as &str).ends_with('\n') {
input.pop();
}
done = interpret_input(input.as_ref(), &mut t);
}
}
|
pub use VkStencilFaceFlags::*;
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VkStencilFaceFlags {
VK_STENCIL_FACE_FRONT_BIT = 0x00000001,
VK_STENCIL_FACE_BACK_BIT = 0x00000002,
VK_STENCIL_FRONT_AND_BACK = 0x3,
}
use crate::SetupVkFlags;
#[repr(C)]
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct VkStencilFaceFlagBits(u32);
SetupVkFlags!(VkStencilFaceFlags, VkStencilFaceFlagBits);
|
use std::{path::Path, process::Command, time::Duration};
use criterion::{criterion_group, criterion_main, BatchSize, BenchmarkGroup, Criterion};
use test_dir::{fs_fn, join_all, TestDir};
pub fn clone_repo<P: AsRef<Path>>(url: &str, path: P) {
let path = path.as_ref();
println!("git cloning path {}", path.display());
let status = Command::new("git")
.arg("clone")
.arg(url)
.arg(&path)
.status()
.expect("Failed to get status");
println!("Exit status {}", status);
}
fn bench_on_repo<M: criterion::measurement::Measurement>(
dir: &TestDir,
url: &str,
from: &str,
to: &str,
group: &mut BenchmarkGroup<'_, M>,
) {
join_all!(dir, from, to);
clone_repo(url, &from);
let setup = || {
if to.exists() {
more_fs::remove_dir_all(&to).unwrap();
}
};
group.bench_function(format!("single threaded more_fs {}", url), |b| {
b.iter_batched(
setup,
|_| more_fs::copy_dir_all(&from, &to).unwrap(),
BatchSize::PerIteration,
)
});
#[cfg(feature = "rayon")]
group.bench_function(format!("multi threaded more_fs {}", url), |b| {
b.iter_batched(
setup,
|_| more_fs::copy_dir_all_par(&from, &to).unwrap(),
BatchSize::PerIteration,
)
});
let mut fs_extra_copy_opt = fs_extra::dir::CopyOptions::new();
fs_extra_copy_opt.copy_inside = true;
group.bench_function(format!("single threaded fs_extra {}", url), |b| {
b.iter_batched(
setup,
|_| fs_extra::dir::copy(&from, &to, &fs_extra_copy_opt).unwrap(),
BatchSize::PerIteration,
)
});
}
fs_fn! {
fn copy_benchmark(c: &mut Criterion)(dir) {
let mut group = c.benchmark_group("recursive copy functions");
bench_on_repo(&dir,
"https://github.com/rust-lang/rust.git",
"rust_from",
"rust_to",
&mut group
);
bench_on_repo(&dir,
"https://github.com/sharkdp/fd.git",
"fd_from",
"fd_to",
&mut group
);
bench_on_repo(&dir,
"https://github.com/oberblastmeister/more-fs.git",
"more_fs_from",
"more_fs_to",
&mut group
);
group.finish();
}
}
criterion_group! {
name = benches;
config = Criterion::default()
.sample_size(30)
.measurement_time(Duration::from_secs(10));
targets = copy_benchmark
}
criterion_main!(benches);
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - DFSDM channel configuration 0 register 1"]
pub dfsdm_chcfg0r1: DFSDM_CHCFG0R1,
#[doc = "0x04 - DFSDM channel configuration 0 register 2"]
pub dfsdm_chcfg0r2: DFSDM_CHCFG0R2,
#[doc = "0x08 - DFSDM analog watchdog and short-circuit detector register"]
pub dfsdm_awscd0r: DFSDM_AWSCD0R,
#[doc = "0x0c - DFSDM channel watchdog filter data register"]
pub dfsdm_chwdat0r: DFSDM_CHWDAT0R,
#[doc = "0x10 - DFSDM channel data input register"]
pub dfsdm_chdatin0r: DFSDM_CHDATIN0R,
_reserved5: [u8; 12usize],
#[doc = "0x20 - DFSDM channel configuration 1 register 1"]
pub dfsdm_chcfg1r1: DFSDM_CHCFG1R1,
#[doc = "0x24 - DFSDM channel configuration 1 register 2"]
pub dfsdm_chcfg1r2: DFSDM_CHCFG1R2,
#[doc = "0x28 - DFSDM analog watchdog and short-circuit detector register"]
pub dfsdm_awscd1r: DFSDM_AWSCD1R,
#[doc = "0x2c - DFSDM channel watchdog filter data register"]
pub dfsdm_chwdat1r: DFSDM_CHWDAT1R,
#[doc = "0x30 - DFSDM channel data input register"]
pub dfsdm_chdatin1r: DFSDM_CHDATIN1R,
_reserved10: [u8; 12usize],
#[doc = "0x40 - DFSDM channel configuration 2 register 1"]
pub dfsdm_chcfg2r1: DFSDM_CHCFG2R1,
#[doc = "0x44 - DFSDM channel configuration 2 register 2"]
pub dfsdm_chcfg2r2: DFSDM_CHCFG2R2,
#[doc = "0x48 - DFSDM analog watchdog and short-circuit detector register"]
pub dfsdm_awscd2r: DFSDM_AWSCD2R,
#[doc = "0x4c - DFSDM channel watchdog filter data register"]
pub dfsdm_chwdat2r: DFSDM_CHWDAT2R,
#[doc = "0x50 - DFSDM channel data input register"]
pub dfsdm_chdatin2r: DFSDM_CHDATIN2R,
_reserved15: [u8; 12usize],
#[doc = "0x60 - DFSDM channel configuration 3 register 1"]
pub dfsdm_chcfg3r1: DFSDM_CHCFG3R1,
#[doc = "0x64 - DFSDM channel configuration 3 register 2"]
pub dfsdm_chcfg3r2: DFSDM_CHCFG3R2,
#[doc = "0x68 - DFSDM analog watchdog and short-circuit detector register"]
pub dfsdm_awscd3r: DFSDM_AWSCD3R,
#[doc = "0x6c - DFSDM channel watchdog filter data register"]
pub dfsdm_chwdat3r: DFSDM_CHWDAT3R,
#[doc = "0x70 - DFSDM channel data input register"]
pub dfsdm_chdatin3r: DFSDM_CHDATIN3R,
_reserved20: [u8; 12usize],
#[doc = "0x80 - DFSDM channel configuration 4 register 1"]
pub dfsdm_chcfg4r1: DFSDM_CHCFG4R1,
#[doc = "0x84 - DFSDM channel configuration 4 register 2"]
pub dfsdm_chcfg4r2: DFSDM_CHCFG4R2,
#[doc = "0x88 - DFSDM analog watchdog and short-circuit detector register"]
pub dfsdm_awscd4r: DFSDM_AWSCD4R,
#[doc = "0x8c - DFSDM channel watchdog filter data register"]
pub dfsdm_chwdat4r: DFSDM_CHWDAT4R,
#[doc = "0x90 - DFSDM channel data input register"]
pub dfsdm_chdatin4r: DFSDM_CHDATIN4R,
_reserved25: [u8; 12usize],
#[doc = "0xa0 - DFSDM channel configuration 5 register 1"]
pub dfsdm_chcfg5r1: DFSDM_CHCFG5R1,
#[doc = "0xa4 - DFSDM channel configuration 5 register 2"]
pub dfsdm_chcfg5r2: DFSDM_CHCFG5R2,
#[doc = "0xa8 - DFSDM analog watchdog and short-circuit detector register"]
pub dfsdm_awscd5r: DFSDM_AWSCD5R,
#[doc = "0xac - DFSDM channel watchdog filter data register"]
pub dfsdm_chwdat5r: DFSDM_CHWDAT5R,
#[doc = "0xb0 - DFSDM channel data input register"]
pub dfsdm_chdatin5r: DFSDM_CHDATIN5R,
_reserved30: [u8; 12usize],
#[doc = "0xc0 - DFSDM channel configuration 6 register 1"]
pub dfsdm_chcfg6r1: DFSDM_CHCFG6R1,
#[doc = "0xc4 - DFSDM channel configuration 6 register 2"]
pub dfsdm_chcfg6r2: DFSDM_CHCFG6R2,
#[doc = "0xc8 - DFSDM analog watchdog and short-circuit detector register"]
pub dfsdm_awscd6r: DFSDM_AWSCD6R,
#[doc = "0xcc - DFSDM channel watchdog filter data register"]
pub dfsdm_chwdat6r: DFSDM_CHWDAT6R,
#[doc = "0xd0 - DFSDM channel data input register"]
pub dfsdm_chdatin6r: DFSDM_CHDATIN6R,
_reserved35: [u8; 12usize],
#[doc = "0xe0 - DFSDM channel configuration 7 register 1"]
pub dfsdm_chcfg7r1: DFSDM_CHCFG7R1,
#[doc = "0xe4 - DFSDM channel configuration 7 register 2"]
pub dfsdm_chcfg7r2: DFSDM_CHCFG7R2,
#[doc = "0xe8 - DFSDM analog watchdog and short-circuit detector register"]
pub dfsdm_awscd7r: DFSDM_AWSCD7R,
#[doc = "0xec - DFSDM channel watchdog filter data register"]
pub dfsdm_chwdat7r: DFSDM_CHWDAT7R,
#[doc = "0xf0 - DFSDM channel data input register"]
pub dfsdm_chdatin7r: DFSDM_CHDATIN7R,
_reserved40: [u8; 12usize],
#[doc = "0x100 - DFSDM control register 1"]
pub dfsdm0_cr1: DFSDM0_CR1,
#[doc = "0x104 - DFSDM control register 2"]
pub dfsdm0_cr2: DFSDM0_CR2,
#[doc = "0x108 - DFSDM interrupt and status register"]
pub dfsdm0_isr: DFSDM0_ISR,
#[doc = "0x10c - DFSDM interrupt flag clear register"]
pub dfsdm0_icr: DFSDM0_ICR,
#[doc = "0x110 - DFSDM injected channel group selection register"]
pub dfsdm0_jchgr: DFSDM0_JCHGR,
#[doc = "0x114 - DFSDM filter control register"]
pub dfsdm0_fcr: DFSDM0_FCR,
#[doc = "0x118 - DFSDM data register for injected group"]
pub dfsdm0_jdatar: DFSDM0_JDATAR,
#[doc = "0x11c - DFSDM data register for the regular channel"]
pub dfsdm0_rdatar: DFSDM0_RDATAR,
#[doc = "0x120 - DFSDM analog watchdog high threshold register"]
pub dfsdm0_awhtr: DFSDM0_AWHTR,
#[doc = "0x124 - DFSDM analog watchdog low threshold register"]
pub dfsdm0_awltr: DFSDM0_AWLTR,
#[doc = "0x128 - DFSDM analog watchdog status register"]
pub dfsdm0_awsr: DFSDM0_AWSR,
#[doc = "0x12c - DFSDM analog watchdog clear flag register"]
pub dfsdm0_awcfr: DFSDM0_AWCFR,
#[doc = "0x130 - DFSDM Extremes detector maximum register"]
pub dfsdm0_exmax: DFSDM0_EXMAX,
#[doc = "0x134 - DFSDM Extremes detector minimum register"]
pub dfsdm0_exmin: DFSDM0_EXMIN,
#[doc = "0x138 - DFSDM conversion timer register"]
pub dfsdm0_cnvtimr: DFSDM0_CNVTIMR,
_reserved55: [u8; 68usize],
#[doc = "0x180 - DFSDM control register 1"]
pub dfsdm1_cr1: DFSDM1_CR1,
#[doc = "0x184 - DFSDM control register 2"]
pub dfsdm1_cr2: DFSDM1_CR2,
#[doc = "0x188 - DFSDM interrupt and status register"]
pub dfsdm1_isr: DFSDM1_ISR,
#[doc = "0x18c - DFSDM interrupt flag clear register"]
pub dfsdm1_icr: DFSDM1_ICR,
#[doc = "0x190 - DFSDM injected channel group selection register"]
pub dfsdm1_jchgr: DFSDM1_JCHGR,
#[doc = "0x194 - DFSDM filter control register"]
pub dfsdm1_fcr: DFSDM1_FCR,
_reserved_61_dfsdm1: [u8; 4usize],
_reserved62: [u8; 4usize],
#[doc = "0x1a0 - DFSDM analog watchdog high threshold register"]
pub dfsdm1_awhtr: DFSDM1_AWHTR,
#[doc = "0x1a4 - DFSDM analog watchdog low threshold register"]
pub dfsdm1_awltr: DFSDM1_AWLTR,
#[doc = "0x1a8 - DFSDM analog watchdog status register"]
pub dfsdm1_awsr: DFSDM1_AWSR,
#[doc = "0x1ac - DFSDM analog watchdog clear flag register"]
pub dfsdm1_awcfr: DFSDM1_AWCFR,
#[doc = "0x1b0 - DFSDM Extremes detector maximum register"]
pub dfsdm1_exmax: DFSDM1_EXMAX,
#[doc = "0x1b4 - DFSDM Extremes detector minimum register"]
pub dfsdm1_exmin: DFSDM1_EXMIN,
#[doc = "0x1b8 - DFSDM conversion timer register"]
pub dfsdm1_cnvtimr: DFSDM1_CNVTIMR,
_reserved69: [u8; 68usize],
#[doc = "0x200 - DFSDM control register 1"]
pub dfsdm2_cr1: DFSDM2_CR1,
#[doc = "0x204 - DFSDM control register 2"]
pub dfsdm2_cr2: DFSDM2_CR2,
#[doc = "0x208 - DFSDM interrupt and status register"]
pub dfsdm2_isr: DFSDM2_ISR,
#[doc = "0x20c - DFSDM interrupt flag clear register"]
pub dfsdm2_icr: DFSDM2_ICR,
#[doc = "0x210 - DFSDM injected channel group selection register"]
pub dfsdm2_jchgr: DFSDM2_JCHGR,
#[doc = "0x214 - DFSDM filter control register"]
pub dfsdm2_fcr: DFSDM2_FCR,
_reserved_75_dfsdm2: [u8; 4usize],
_reserved76: [u8; 4usize],
#[doc = "0x220 - DFSDM analog watchdog high threshold register"]
pub dfsdm2_awhtr: DFSDM2_AWHTR,
#[doc = "0x224 - DFSDM analog watchdog low threshold register"]
pub dfsdm2_awltr: DFSDM2_AWLTR,
#[doc = "0x228 - DFSDM analog watchdog status register"]
pub dfsdm2_awsr: DFSDM2_AWSR,
#[doc = "0x22c - DFSDM analog watchdog clear flag register"]
pub dfsdm2_awcfr: DFSDM2_AWCFR,
#[doc = "0x230 - DFSDM Extremes detector maximum register"]
pub dfsdm2_exmax: DFSDM2_EXMAX,
#[doc = "0x234 - DFSDM Extremes detector minimum register"]
pub dfsdm2_exmin: DFSDM2_EXMIN,
#[doc = "0x238 - DFSDM conversion timer register"]
pub dfsdm2_cnvtimr: DFSDM2_CNVTIMR,
_reserved83: [u8; 100usize],
#[doc = "0x2a0 - DFSDM analog watchdog high threshold register"]
pub dfsdm3_awhtr: DFSDM3_AWHTR,
#[doc = "0x2a4 - DFSDM analog watchdog low threshold register"]
pub dfsdm3_awltr: DFSDM3_AWLTR,
#[doc = "0x2a8 - DFSDM analog watchdog status register"]
pub dfsdm3_awsr: DFSDM3_AWSR,
#[doc = "0x2ac - DFSDM analog watchdog clear flag register"]
pub dfsdm3_awcfr: DFSDM3_AWCFR,
#[doc = "0x2b0 - DFSDM Extremes detector maximum register"]
pub dfsdm3_exmax: DFSDM3_EXMAX,
#[doc = "0x2b4 - DFSDM Extremes detector minimum register"]
pub dfsdm3_exmin: DFSDM3_EXMIN,
#[doc = "0x2b8 - DFSDM conversion timer register"]
pub dfsdm3_cnvtimr: DFSDM3_CNVTIMR,
_reserved90: [u8; 84usize],
#[doc = "0x310 - DFSDM injected channel group selection register"]
pub dfsdm3_jchgr: DFSDM3_JCHGR,
#[doc = "0x314 - DFSDM filter control register"]
pub dfsdm3_fcr: DFSDM3_FCR,
_reserved_92_dfsdm3: [u8; 4usize],
_reserved93: [u8; 100usize],
#[doc = "0x380 - DFSDM control register 1"]
pub dfsdm3_cr1: DFSDM3_CR1,
#[doc = "0x384 - DFSDM control register 2"]
pub dfsdm3_cr2: DFSDM3_CR2,
#[doc = "0x388 - DFSDM interrupt and status register"]
pub dfsdm3_isr: DFSDM3_ISR,
#[doc = "0x38c - DFSDM interrupt flag clear register"]
pub dfsdm3_icr: DFSDM3_ICR,
}
impl RegisterBlock {
#[doc = "0x198 - DFSDM data register for the regular channel"]
#[inline(always)]
pub fn dfsdm1_rdatar(&self) -> &DFSDM1_RDATAR {
unsafe { &*(((self as *const Self) as *const u8).add(408usize) as *const DFSDM1_RDATAR) }
}
#[doc = "0x198 - DFSDM data register for the regular channel"]
#[inline(always)]
pub fn dfsdm1_rdatar_mut(&self) -> &mut DFSDM1_RDATAR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(408usize) as *mut DFSDM1_RDATAR) }
}
#[doc = "0x198 - DFSDM data register for injected group"]
#[inline(always)]
pub fn dfsdm1_jdatar(&self) -> &DFSDM1_JDATAR {
unsafe { &*(((self as *const Self) as *const u8).add(408usize) as *const DFSDM1_JDATAR) }
}
#[doc = "0x198 - DFSDM data register for injected group"]
#[inline(always)]
pub fn dfsdm1_jdatar_mut(&self) -> &mut DFSDM1_JDATAR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(408usize) as *mut DFSDM1_JDATAR) }
}
#[doc = "0x218 - DFSDM data register for the regular channel"]
#[inline(always)]
pub fn dfsdm2_rdatar(&self) -> &DFSDM2_RDATAR {
unsafe { &*(((self as *const Self) as *const u8).add(536usize) as *const DFSDM2_RDATAR) }
}
#[doc = "0x218 - DFSDM data register for the regular channel"]
#[inline(always)]
pub fn dfsdm2_rdatar_mut(&self) -> &mut DFSDM2_RDATAR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(536usize) as *mut DFSDM2_RDATAR) }
}
#[doc = "0x218 - DFSDM data register for injected group"]
#[inline(always)]
pub fn dfsdm2_jdatar(&self) -> &DFSDM2_JDATAR {
unsafe { &*(((self as *const Self) as *const u8).add(536usize) as *const DFSDM2_JDATAR) }
}
#[doc = "0x218 - DFSDM data register for injected group"]
#[inline(always)]
pub fn dfsdm2_jdatar_mut(&self) -> &mut DFSDM2_JDATAR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(536usize) as *mut DFSDM2_JDATAR) }
}
#[doc = "0x318 - DFSDM data register for the regular channel"]
#[inline(always)]
pub fn dfsdm3_rdatar(&self) -> &DFSDM3_RDATAR {
unsafe { &*(((self as *const Self) as *const u8).add(792usize) as *const DFSDM3_RDATAR) }
}
#[doc = "0x318 - DFSDM data register for the regular channel"]
#[inline(always)]
pub fn dfsdm3_rdatar_mut(&self) -> &mut DFSDM3_RDATAR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(792usize) as *mut DFSDM3_RDATAR) }
}
#[doc = "0x318 - DFSDM data register for injected group"]
#[inline(always)]
pub fn dfsdm3_jdatar(&self) -> &DFSDM3_JDATAR {
unsafe { &*(((self as *const Self) as *const u8).add(792usize) as *const DFSDM3_JDATAR) }
}
#[doc = "0x318 - DFSDM data register for injected group"]
#[inline(always)]
pub fn dfsdm3_jdatar_mut(&self) -> &mut DFSDM3_JDATAR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(792usize) as *mut DFSDM3_JDATAR) }
}
}
#[doc = "DFSDM channel configuration 0 register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg0r1](dfsdm_chcfg0r1) module"]
pub type DFSDM_CHCFG0R1 = crate::Reg<u32, _DFSDM_CHCFG0R1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG0R1;
#[doc = "`read()` method returns [dfsdm_chcfg0r1::R](dfsdm_chcfg0r1::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG0R1 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg0r1::W](dfsdm_chcfg0r1::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG0R1 {}
#[doc = "DFSDM channel configuration 0 register 1"]
pub mod dfsdm_chcfg0r1;
#[doc = "DFSDM channel configuration 1 register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg1r1](dfsdm_chcfg1r1) module"]
pub type DFSDM_CHCFG1R1 = crate::Reg<u32, _DFSDM_CHCFG1R1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG1R1;
#[doc = "`read()` method returns [dfsdm_chcfg1r1::R](dfsdm_chcfg1r1::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG1R1 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg1r1::W](dfsdm_chcfg1r1::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG1R1 {}
#[doc = "DFSDM channel configuration 1 register 1"]
pub mod dfsdm_chcfg1r1;
#[doc = "DFSDM channel configuration 2 register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg2r1](dfsdm_chcfg2r1) module"]
pub type DFSDM_CHCFG2R1 = crate::Reg<u32, _DFSDM_CHCFG2R1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG2R1;
#[doc = "`read()` method returns [dfsdm_chcfg2r1::R](dfsdm_chcfg2r1::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG2R1 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg2r1::W](dfsdm_chcfg2r1::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG2R1 {}
#[doc = "DFSDM channel configuration 2 register 1"]
pub mod dfsdm_chcfg2r1;
#[doc = "DFSDM channel configuration 3 register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg3r1](dfsdm_chcfg3r1) module"]
pub type DFSDM_CHCFG3R1 = crate::Reg<u32, _DFSDM_CHCFG3R1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG3R1;
#[doc = "`read()` method returns [dfsdm_chcfg3r1::R](dfsdm_chcfg3r1::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG3R1 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg3r1::W](dfsdm_chcfg3r1::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG3R1 {}
#[doc = "DFSDM channel configuration 3 register 1"]
pub mod dfsdm_chcfg3r1;
#[doc = "DFSDM channel configuration 4 register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg4r1](dfsdm_chcfg4r1) module"]
pub type DFSDM_CHCFG4R1 = crate::Reg<u32, _DFSDM_CHCFG4R1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG4R1;
#[doc = "`read()` method returns [dfsdm_chcfg4r1::R](dfsdm_chcfg4r1::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG4R1 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg4r1::W](dfsdm_chcfg4r1::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG4R1 {}
#[doc = "DFSDM channel configuration 4 register 1"]
pub mod dfsdm_chcfg4r1;
#[doc = "DFSDM channel configuration 5 register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg5r1](dfsdm_chcfg5r1) module"]
pub type DFSDM_CHCFG5R1 = crate::Reg<u32, _DFSDM_CHCFG5R1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG5R1;
#[doc = "`read()` method returns [dfsdm_chcfg5r1::R](dfsdm_chcfg5r1::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG5R1 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg5r1::W](dfsdm_chcfg5r1::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG5R1 {}
#[doc = "DFSDM channel configuration 5 register 1"]
pub mod dfsdm_chcfg5r1;
#[doc = "DFSDM channel configuration 6 register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg6r1](dfsdm_chcfg6r1) module"]
pub type DFSDM_CHCFG6R1 = crate::Reg<u32, _DFSDM_CHCFG6R1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG6R1;
#[doc = "`read()` method returns [dfsdm_chcfg6r1::R](dfsdm_chcfg6r1::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG6R1 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg6r1::W](dfsdm_chcfg6r1::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG6R1 {}
#[doc = "DFSDM channel configuration 6 register 1"]
pub mod dfsdm_chcfg6r1;
#[doc = "DFSDM channel configuration 7 register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg7r1](dfsdm_chcfg7r1) module"]
pub type DFSDM_CHCFG7R1 = crate::Reg<u32, _DFSDM_CHCFG7R1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG7R1;
#[doc = "`read()` method returns [dfsdm_chcfg7r1::R](dfsdm_chcfg7r1::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG7R1 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg7r1::W](dfsdm_chcfg7r1::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG7R1 {}
#[doc = "DFSDM channel configuration 7 register 1"]
pub mod dfsdm_chcfg7r1;
#[doc = "DFSDM channel configuration 0 register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg0r2](dfsdm_chcfg0r2) module"]
pub type DFSDM_CHCFG0R2 = crate::Reg<u32, _DFSDM_CHCFG0R2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG0R2;
#[doc = "`read()` method returns [dfsdm_chcfg0r2::R](dfsdm_chcfg0r2::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG0R2 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg0r2::W](dfsdm_chcfg0r2::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG0R2 {}
#[doc = "DFSDM channel configuration 0 register 2"]
pub mod dfsdm_chcfg0r2;
#[doc = "DFSDM channel configuration 1 register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg1r2](dfsdm_chcfg1r2) module"]
pub type DFSDM_CHCFG1R2 = crate::Reg<u32, _DFSDM_CHCFG1R2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG1R2;
#[doc = "`read()` method returns [dfsdm_chcfg1r2::R](dfsdm_chcfg1r2::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG1R2 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg1r2::W](dfsdm_chcfg1r2::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG1R2 {}
#[doc = "DFSDM channel configuration 1 register 2"]
pub mod dfsdm_chcfg1r2;
#[doc = "DFSDM channel configuration 2 register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg2r2](dfsdm_chcfg2r2) module"]
pub type DFSDM_CHCFG2R2 = crate::Reg<u32, _DFSDM_CHCFG2R2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG2R2;
#[doc = "`read()` method returns [dfsdm_chcfg2r2::R](dfsdm_chcfg2r2::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG2R2 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg2r2::W](dfsdm_chcfg2r2::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG2R2 {}
#[doc = "DFSDM channel configuration 2 register 2"]
pub mod dfsdm_chcfg2r2;
#[doc = "DFSDM channel configuration 3 register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg3r2](dfsdm_chcfg3r2) module"]
pub type DFSDM_CHCFG3R2 = crate::Reg<u32, _DFSDM_CHCFG3R2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG3R2;
#[doc = "`read()` method returns [dfsdm_chcfg3r2::R](dfsdm_chcfg3r2::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG3R2 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg3r2::W](dfsdm_chcfg3r2::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG3R2 {}
#[doc = "DFSDM channel configuration 3 register 2"]
pub mod dfsdm_chcfg3r2;
#[doc = "DFSDM channel configuration 4 register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg4r2](dfsdm_chcfg4r2) module"]
pub type DFSDM_CHCFG4R2 = crate::Reg<u32, _DFSDM_CHCFG4R2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG4R2;
#[doc = "`read()` method returns [dfsdm_chcfg4r2::R](dfsdm_chcfg4r2::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG4R2 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg4r2::W](dfsdm_chcfg4r2::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG4R2 {}
#[doc = "DFSDM channel configuration 4 register 2"]
pub mod dfsdm_chcfg4r2;
#[doc = "DFSDM channel configuration 5 register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg5r2](dfsdm_chcfg5r2) module"]
pub type DFSDM_CHCFG5R2 = crate::Reg<u32, _DFSDM_CHCFG5R2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG5R2;
#[doc = "`read()` method returns [dfsdm_chcfg5r2::R](dfsdm_chcfg5r2::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG5R2 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg5r2::W](dfsdm_chcfg5r2::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG5R2 {}
#[doc = "DFSDM channel configuration 5 register 2"]
pub mod dfsdm_chcfg5r2;
#[doc = "DFSDM channel configuration 6 register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg6r2](dfsdm_chcfg6r2) module"]
pub type DFSDM_CHCFG6R2 = crate::Reg<u32, _DFSDM_CHCFG6R2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG6R2;
#[doc = "`read()` method returns [dfsdm_chcfg6r2::R](dfsdm_chcfg6r2::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG6R2 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg6r2::W](dfsdm_chcfg6r2::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG6R2 {}
#[doc = "DFSDM channel configuration 6 register 2"]
pub mod dfsdm_chcfg6r2;
#[doc = "DFSDM channel configuration 7 register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chcfg7r2](dfsdm_chcfg7r2) module"]
pub type DFSDM_CHCFG7R2 = crate::Reg<u32, _DFSDM_CHCFG7R2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHCFG7R2;
#[doc = "`read()` method returns [dfsdm_chcfg7r2::R](dfsdm_chcfg7r2::R) reader structure"]
impl crate::Readable for DFSDM_CHCFG7R2 {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chcfg7r2::W](dfsdm_chcfg7r2::W) writer structure"]
impl crate::Writable for DFSDM_CHCFG7R2 {}
#[doc = "DFSDM channel configuration 7 register 2"]
pub mod dfsdm_chcfg7r2;
#[doc = "DFSDM analog watchdog and short-circuit detector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_awscd0r](dfsdm_awscd0r) module"]
pub type DFSDM_AWSCD0R = crate::Reg<u32, _DFSDM_AWSCD0R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_AWSCD0R;
#[doc = "`read()` method returns [dfsdm_awscd0r::R](dfsdm_awscd0r::R) reader structure"]
impl crate::Readable for DFSDM_AWSCD0R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_awscd0r::W](dfsdm_awscd0r::W) writer structure"]
impl crate::Writable for DFSDM_AWSCD0R {}
#[doc = "DFSDM analog watchdog and short-circuit detector register"]
pub mod dfsdm_awscd0r;
#[doc = "DFSDM analog watchdog and short-circuit detector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_awscd1r](dfsdm_awscd1r) module"]
pub type DFSDM_AWSCD1R = crate::Reg<u32, _DFSDM_AWSCD1R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_AWSCD1R;
#[doc = "`read()` method returns [dfsdm_awscd1r::R](dfsdm_awscd1r::R) reader structure"]
impl crate::Readable for DFSDM_AWSCD1R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_awscd1r::W](dfsdm_awscd1r::W) writer structure"]
impl crate::Writable for DFSDM_AWSCD1R {}
#[doc = "DFSDM analog watchdog and short-circuit detector register"]
pub mod dfsdm_awscd1r;
#[doc = "DFSDM analog watchdog and short-circuit detector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_awscd2r](dfsdm_awscd2r) module"]
pub type DFSDM_AWSCD2R = crate::Reg<u32, _DFSDM_AWSCD2R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_AWSCD2R;
#[doc = "`read()` method returns [dfsdm_awscd2r::R](dfsdm_awscd2r::R) reader structure"]
impl crate::Readable for DFSDM_AWSCD2R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_awscd2r::W](dfsdm_awscd2r::W) writer structure"]
impl crate::Writable for DFSDM_AWSCD2R {}
#[doc = "DFSDM analog watchdog and short-circuit detector register"]
pub mod dfsdm_awscd2r;
#[doc = "DFSDM analog watchdog and short-circuit detector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_awscd3r](dfsdm_awscd3r) module"]
pub type DFSDM_AWSCD3R = crate::Reg<u32, _DFSDM_AWSCD3R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_AWSCD3R;
#[doc = "`read()` method returns [dfsdm_awscd3r::R](dfsdm_awscd3r::R) reader structure"]
impl crate::Readable for DFSDM_AWSCD3R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_awscd3r::W](dfsdm_awscd3r::W) writer structure"]
impl crate::Writable for DFSDM_AWSCD3R {}
#[doc = "DFSDM analog watchdog and short-circuit detector register"]
pub mod dfsdm_awscd3r;
#[doc = "DFSDM analog watchdog and short-circuit detector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_awscd4r](dfsdm_awscd4r) module"]
pub type DFSDM_AWSCD4R = crate::Reg<u32, _DFSDM_AWSCD4R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_AWSCD4R;
#[doc = "`read()` method returns [dfsdm_awscd4r::R](dfsdm_awscd4r::R) reader structure"]
impl crate::Readable for DFSDM_AWSCD4R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_awscd4r::W](dfsdm_awscd4r::W) writer structure"]
impl crate::Writable for DFSDM_AWSCD4R {}
#[doc = "DFSDM analog watchdog and short-circuit detector register"]
pub mod dfsdm_awscd4r;
#[doc = "DFSDM analog watchdog and short-circuit detector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_awscd5r](dfsdm_awscd5r) module"]
pub type DFSDM_AWSCD5R = crate::Reg<u32, _DFSDM_AWSCD5R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_AWSCD5R;
#[doc = "`read()` method returns [dfsdm_awscd5r::R](dfsdm_awscd5r::R) reader structure"]
impl crate::Readable for DFSDM_AWSCD5R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_awscd5r::W](dfsdm_awscd5r::W) writer structure"]
impl crate::Writable for DFSDM_AWSCD5R {}
#[doc = "DFSDM analog watchdog and short-circuit detector register"]
pub mod dfsdm_awscd5r;
#[doc = "DFSDM analog watchdog and short-circuit detector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_awscd6r](dfsdm_awscd6r) module"]
pub type DFSDM_AWSCD6R = crate::Reg<u32, _DFSDM_AWSCD6R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_AWSCD6R;
#[doc = "`read()` method returns [dfsdm_awscd6r::R](dfsdm_awscd6r::R) reader structure"]
impl crate::Readable for DFSDM_AWSCD6R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_awscd6r::W](dfsdm_awscd6r::W) writer structure"]
impl crate::Writable for DFSDM_AWSCD6R {}
#[doc = "DFSDM analog watchdog and short-circuit detector register"]
pub mod dfsdm_awscd6r;
#[doc = "DFSDM analog watchdog and short-circuit detector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_awscd7r](dfsdm_awscd7r) module"]
pub type DFSDM_AWSCD7R = crate::Reg<u32, _DFSDM_AWSCD7R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_AWSCD7R;
#[doc = "`read()` method returns [dfsdm_awscd7r::R](dfsdm_awscd7r::R) reader structure"]
impl crate::Readable for DFSDM_AWSCD7R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_awscd7r::W](dfsdm_awscd7r::W) writer structure"]
impl crate::Writable for DFSDM_AWSCD7R {}
#[doc = "DFSDM analog watchdog and short-circuit detector register"]
pub mod dfsdm_awscd7r;
#[doc = "DFSDM channel watchdog filter data register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chwdat0r](dfsdm_chwdat0r) module"]
pub type DFSDM_CHWDAT0R = crate::Reg<u32, _DFSDM_CHWDAT0R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHWDAT0R;
#[doc = "`read()` method returns [dfsdm_chwdat0r::R](dfsdm_chwdat0r::R) reader structure"]
impl crate::Readable for DFSDM_CHWDAT0R {}
#[doc = "DFSDM channel watchdog filter data register"]
pub mod dfsdm_chwdat0r;
#[doc = "DFSDM channel watchdog filter data register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chwdat1r](dfsdm_chwdat1r) module"]
pub type DFSDM_CHWDAT1R = crate::Reg<u32, _DFSDM_CHWDAT1R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHWDAT1R;
#[doc = "`read()` method returns [dfsdm_chwdat1r::R](dfsdm_chwdat1r::R) reader structure"]
impl crate::Readable for DFSDM_CHWDAT1R {}
#[doc = "DFSDM channel watchdog filter data register"]
pub mod dfsdm_chwdat1r;
#[doc = "DFSDM channel watchdog filter data register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chwdat2r](dfsdm_chwdat2r) module"]
pub type DFSDM_CHWDAT2R = crate::Reg<u32, _DFSDM_CHWDAT2R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHWDAT2R;
#[doc = "`read()` method returns [dfsdm_chwdat2r::R](dfsdm_chwdat2r::R) reader structure"]
impl crate::Readable for DFSDM_CHWDAT2R {}
#[doc = "DFSDM channel watchdog filter data register"]
pub mod dfsdm_chwdat2r;
#[doc = "DFSDM channel watchdog filter data register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chwdat3r](dfsdm_chwdat3r) module"]
pub type DFSDM_CHWDAT3R = crate::Reg<u32, _DFSDM_CHWDAT3R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHWDAT3R;
#[doc = "`read()` method returns [dfsdm_chwdat3r::R](dfsdm_chwdat3r::R) reader structure"]
impl crate::Readable for DFSDM_CHWDAT3R {}
#[doc = "DFSDM channel watchdog filter data register"]
pub mod dfsdm_chwdat3r;
#[doc = "DFSDM channel watchdog filter data register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chwdat4r](dfsdm_chwdat4r) module"]
pub type DFSDM_CHWDAT4R = crate::Reg<u32, _DFSDM_CHWDAT4R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHWDAT4R;
#[doc = "`read()` method returns [dfsdm_chwdat4r::R](dfsdm_chwdat4r::R) reader structure"]
impl crate::Readable for DFSDM_CHWDAT4R {}
#[doc = "DFSDM channel watchdog filter data register"]
pub mod dfsdm_chwdat4r;
#[doc = "DFSDM channel watchdog filter data register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chwdat5r](dfsdm_chwdat5r) module"]
pub type DFSDM_CHWDAT5R = crate::Reg<u32, _DFSDM_CHWDAT5R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHWDAT5R;
#[doc = "`read()` method returns [dfsdm_chwdat5r::R](dfsdm_chwdat5r::R) reader structure"]
impl crate::Readable for DFSDM_CHWDAT5R {}
#[doc = "DFSDM channel watchdog filter data register"]
pub mod dfsdm_chwdat5r;
#[doc = "DFSDM channel watchdog filter data register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chwdat6r](dfsdm_chwdat6r) module"]
pub type DFSDM_CHWDAT6R = crate::Reg<u32, _DFSDM_CHWDAT6R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHWDAT6R;
#[doc = "`read()` method returns [dfsdm_chwdat6r::R](dfsdm_chwdat6r::R) reader structure"]
impl crate::Readable for DFSDM_CHWDAT6R {}
#[doc = "DFSDM channel watchdog filter data register"]
pub mod dfsdm_chwdat6r;
#[doc = "DFSDM channel watchdog filter data register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chwdat7r](dfsdm_chwdat7r) module"]
pub type DFSDM_CHWDAT7R = crate::Reg<u32, _DFSDM_CHWDAT7R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHWDAT7R;
#[doc = "`read()` method returns [dfsdm_chwdat7r::R](dfsdm_chwdat7r::R) reader structure"]
impl crate::Readable for DFSDM_CHWDAT7R {}
#[doc = "DFSDM channel watchdog filter data register"]
pub mod dfsdm_chwdat7r;
#[doc = "DFSDM channel data input register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chdatin0r](dfsdm_chdatin0r) module"]
pub type DFSDM_CHDATIN0R = crate::Reg<u32, _DFSDM_CHDATIN0R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHDATIN0R;
#[doc = "`read()` method returns [dfsdm_chdatin0r::R](dfsdm_chdatin0r::R) reader structure"]
impl crate::Readable for DFSDM_CHDATIN0R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chdatin0r::W](dfsdm_chdatin0r::W) writer structure"]
impl crate::Writable for DFSDM_CHDATIN0R {}
#[doc = "DFSDM channel data input register"]
pub mod dfsdm_chdatin0r;
#[doc = "DFSDM channel data input register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chdatin1r](dfsdm_chdatin1r) module"]
pub type DFSDM_CHDATIN1R = crate::Reg<u32, _DFSDM_CHDATIN1R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHDATIN1R;
#[doc = "`read()` method returns [dfsdm_chdatin1r::R](dfsdm_chdatin1r::R) reader structure"]
impl crate::Readable for DFSDM_CHDATIN1R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chdatin1r::W](dfsdm_chdatin1r::W) writer structure"]
impl crate::Writable for DFSDM_CHDATIN1R {}
#[doc = "DFSDM channel data input register"]
pub mod dfsdm_chdatin1r;
#[doc = "DFSDM channel data input register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chdatin2r](dfsdm_chdatin2r) module"]
pub type DFSDM_CHDATIN2R = crate::Reg<u32, _DFSDM_CHDATIN2R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHDATIN2R;
#[doc = "`read()` method returns [dfsdm_chdatin2r::R](dfsdm_chdatin2r::R) reader structure"]
impl crate::Readable for DFSDM_CHDATIN2R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chdatin2r::W](dfsdm_chdatin2r::W) writer structure"]
impl crate::Writable for DFSDM_CHDATIN2R {}
#[doc = "DFSDM channel data input register"]
pub mod dfsdm_chdatin2r;
#[doc = "DFSDM channel data input register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chdatin3r](dfsdm_chdatin3r) module"]
pub type DFSDM_CHDATIN3R = crate::Reg<u32, _DFSDM_CHDATIN3R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHDATIN3R;
#[doc = "`read()` method returns [dfsdm_chdatin3r::R](dfsdm_chdatin3r::R) reader structure"]
impl crate::Readable for DFSDM_CHDATIN3R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chdatin3r::W](dfsdm_chdatin3r::W) writer structure"]
impl crate::Writable for DFSDM_CHDATIN3R {}
#[doc = "DFSDM channel data input register"]
pub mod dfsdm_chdatin3r;
#[doc = "DFSDM channel data input register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chdatin4r](dfsdm_chdatin4r) module"]
pub type DFSDM_CHDATIN4R = crate::Reg<u32, _DFSDM_CHDATIN4R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHDATIN4R;
#[doc = "`read()` method returns [dfsdm_chdatin4r::R](dfsdm_chdatin4r::R) reader structure"]
impl crate::Readable for DFSDM_CHDATIN4R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chdatin4r::W](dfsdm_chdatin4r::W) writer structure"]
impl crate::Writable for DFSDM_CHDATIN4R {}
#[doc = "DFSDM channel data input register"]
pub mod dfsdm_chdatin4r;
#[doc = "DFSDM channel data input register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chdatin5r](dfsdm_chdatin5r) module"]
pub type DFSDM_CHDATIN5R = crate::Reg<u32, _DFSDM_CHDATIN5R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHDATIN5R;
#[doc = "`read()` method returns [dfsdm_chdatin5r::R](dfsdm_chdatin5r::R) reader structure"]
impl crate::Readable for DFSDM_CHDATIN5R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chdatin5r::W](dfsdm_chdatin5r::W) writer structure"]
impl crate::Writable for DFSDM_CHDATIN5R {}
#[doc = "DFSDM channel data input register"]
pub mod dfsdm_chdatin5r;
#[doc = "DFSDM channel data input register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chdatin6r](dfsdm_chdatin6r) module"]
pub type DFSDM_CHDATIN6R = crate::Reg<u32, _DFSDM_CHDATIN6R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHDATIN6R;
#[doc = "`read()` method returns [dfsdm_chdatin6r::R](dfsdm_chdatin6r::R) reader structure"]
impl crate::Readable for DFSDM_CHDATIN6R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chdatin6r::W](dfsdm_chdatin6r::W) writer structure"]
impl crate::Writable for DFSDM_CHDATIN6R {}
#[doc = "DFSDM channel data input register"]
pub mod dfsdm_chdatin6r;
#[doc = "DFSDM channel data input register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_chdatin7r](dfsdm_chdatin7r) module"]
pub type DFSDM_CHDATIN7R = crate::Reg<u32, _DFSDM_CHDATIN7R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM_CHDATIN7R;
#[doc = "`read()` method returns [dfsdm_chdatin7r::R](dfsdm_chdatin7r::R) reader structure"]
impl crate::Readable for DFSDM_CHDATIN7R {}
#[doc = "`write(|w| ..)` method takes [dfsdm_chdatin7r::W](dfsdm_chdatin7r::W) writer structure"]
impl crate::Writable for DFSDM_CHDATIN7R {}
#[doc = "DFSDM channel data input register"]
pub mod dfsdm_chdatin7r;
#[doc = "DFSDM control register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_cr1](dfsdm0_cr1) module"]
pub type DFSDM0_CR1 = crate::Reg<u32, _DFSDM0_CR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_CR1;
#[doc = "`read()` method returns [dfsdm0_cr1::R](dfsdm0_cr1::R) reader structure"]
impl crate::Readable for DFSDM0_CR1 {}
#[doc = "`write(|w| ..)` method takes [dfsdm0_cr1::W](dfsdm0_cr1::W) writer structure"]
impl crate::Writable for DFSDM0_CR1 {}
#[doc = "DFSDM control register 1"]
pub mod dfsdm0_cr1;
#[doc = "DFSDM control register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_cr1](dfsdm1_cr1) module"]
pub type DFSDM1_CR1 = crate::Reg<u32, _DFSDM1_CR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_CR1;
#[doc = "`read()` method returns [dfsdm1_cr1::R](dfsdm1_cr1::R) reader structure"]
impl crate::Readable for DFSDM1_CR1 {}
#[doc = "`write(|w| ..)` method takes [dfsdm1_cr1::W](dfsdm1_cr1::W) writer structure"]
impl crate::Writable for DFSDM1_CR1 {}
#[doc = "DFSDM control register 1"]
pub mod dfsdm1_cr1;
#[doc = "DFSDM control register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_cr1](dfsdm2_cr1) module"]
pub type DFSDM2_CR1 = crate::Reg<u32, _DFSDM2_CR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_CR1;
#[doc = "`read()` method returns [dfsdm2_cr1::R](dfsdm2_cr1::R) reader structure"]
impl crate::Readable for DFSDM2_CR1 {}
#[doc = "`write(|w| ..)` method takes [dfsdm2_cr1::W](dfsdm2_cr1::W) writer structure"]
impl crate::Writable for DFSDM2_CR1 {}
#[doc = "DFSDM control register 1"]
pub mod dfsdm2_cr1;
#[doc = "DFSDM control register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_cr1](dfsdm3_cr1) module"]
pub type DFSDM3_CR1 = crate::Reg<u32, _DFSDM3_CR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_CR1;
#[doc = "`read()` method returns [dfsdm3_cr1::R](dfsdm3_cr1::R) reader structure"]
impl crate::Readable for DFSDM3_CR1 {}
#[doc = "`write(|w| ..)` method takes [dfsdm3_cr1::W](dfsdm3_cr1::W) writer structure"]
impl crate::Writable for DFSDM3_CR1 {}
#[doc = "DFSDM control register 1"]
pub mod dfsdm3_cr1;
#[doc = "DFSDM control register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_cr2](dfsdm0_cr2) module"]
pub type DFSDM0_CR2 = crate::Reg<u32, _DFSDM0_CR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_CR2;
#[doc = "`read()` method returns [dfsdm0_cr2::R](dfsdm0_cr2::R) reader structure"]
impl crate::Readable for DFSDM0_CR2 {}
#[doc = "`write(|w| ..)` method takes [dfsdm0_cr2::W](dfsdm0_cr2::W) writer structure"]
impl crate::Writable for DFSDM0_CR2 {}
#[doc = "DFSDM control register 2"]
pub mod dfsdm0_cr2;
#[doc = "DFSDM control register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_cr2](dfsdm1_cr2) module"]
pub type DFSDM1_CR2 = crate::Reg<u32, _DFSDM1_CR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_CR2;
#[doc = "`read()` method returns [dfsdm1_cr2::R](dfsdm1_cr2::R) reader structure"]
impl crate::Readable for DFSDM1_CR2 {}
#[doc = "`write(|w| ..)` method takes [dfsdm1_cr2::W](dfsdm1_cr2::W) writer structure"]
impl crate::Writable for DFSDM1_CR2 {}
#[doc = "DFSDM control register 2"]
pub mod dfsdm1_cr2;
#[doc = "DFSDM control register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_cr2](dfsdm2_cr2) module"]
pub type DFSDM2_CR2 = crate::Reg<u32, _DFSDM2_CR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_CR2;
#[doc = "`read()` method returns [dfsdm2_cr2::R](dfsdm2_cr2::R) reader structure"]
impl crate::Readable for DFSDM2_CR2 {}
#[doc = "`write(|w| ..)` method takes [dfsdm2_cr2::W](dfsdm2_cr2::W) writer structure"]
impl crate::Writable for DFSDM2_CR2 {}
#[doc = "DFSDM control register 2"]
pub mod dfsdm2_cr2;
#[doc = "DFSDM control register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_cr2](dfsdm3_cr2) module"]
pub type DFSDM3_CR2 = crate::Reg<u32, _DFSDM3_CR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_CR2;
#[doc = "`read()` method returns [dfsdm3_cr2::R](dfsdm3_cr2::R) reader structure"]
impl crate::Readable for DFSDM3_CR2 {}
#[doc = "`write(|w| ..)` method takes [dfsdm3_cr2::W](dfsdm3_cr2::W) writer structure"]
impl crate::Writable for DFSDM3_CR2 {}
#[doc = "DFSDM control register 2"]
pub mod dfsdm3_cr2;
#[doc = "DFSDM interrupt and status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_isr](dfsdm0_isr) module"]
pub type DFSDM0_ISR = crate::Reg<u32, _DFSDM0_ISR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_ISR;
#[doc = "`read()` method returns [dfsdm0_isr::R](dfsdm0_isr::R) reader structure"]
impl crate::Readable for DFSDM0_ISR {}
#[doc = "DFSDM interrupt and status register"]
pub mod dfsdm0_isr;
#[doc = "DFSDM interrupt and status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_isr](dfsdm1_isr) module"]
pub type DFSDM1_ISR = crate::Reg<u32, _DFSDM1_ISR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_ISR;
#[doc = "`read()` method returns [dfsdm1_isr::R](dfsdm1_isr::R) reader structure"]
impl crate::Readable for DFSDM1_ISR {}
#[doc = "DFSDM interrupt and status register"]
pub mod dfsdm1_isr;
#[doc = "DFSDM interrupt and status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_isr](dfsdm2_isr) module"]
pub type DFSDM2_ISR = crate::Reg<u32, _DFSDM2_ISR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_ISR;
#[doc = "`read()` method returns [dfsdm2_isr::R](dfsdm2_isr::R) reader structure"]
impl crate::Readable for DFSDM2_ISR {}
#[doc = "DFSDM interrupt and status register"]
pub mod dfsdm2_isr;
#[doc = "DFSDM interrupt and status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_isr](dfsdm3_isr) module"]
pub type DFSDM3_ISR = crate::Reg<u32, _DFSDM3_ISR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_ISR;
#[doc = "`read()` method returns [dfsdm3_isr::R](dfsdm3_isr::R) reader structure"]
impl crate::Readable for DFSDM3_ISR {}
#[doc = "DFSDM interrupt and status register"]
pub mod dfsdm3_isr;
#[doc = "DFSDM interrupt flag clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_icr](dfsdm0_icr) module"]
pub type DFSDM0_ICR = crate::Reg<u32, _DFSDM0_ICR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_ICR;
#[doc = "`read()` method returns [dfsdm0_icr::R](dfsdm0_icr::R) reader structure"]
impl crate::Readable for DFSDM0_ICR {}
#[doc = "`write(|w| ..)` method takes [dfsdm0_icr::W](dfsdm0_icr::W) writer structure"]
impl crate::Writable for DFSDM0_ICR {}
#[doc = "DFSDM interrupt flag clear register"]
pub mod dfsdm0_icr;
#[doc = "DFSDM interrupt flag clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_icr](dfsdm1_icr) module"]
pub type DFSDM1_ICR = crate::Reg<u32, _DFSDM1_ICR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_ICR;
#[doc = "`read()` method returns [dfsdm1_icr::R](dfsdm1_icr::R) reader structure"]
impl crate::Readable for DFSDM1_ICR {}
#[doc = "`write(|w| ..)` method takes [dfsdm1_icr::W](dfsdm1_icr::W) writer structure"]
impl crate::Writable for DFSDM1_ICR {}
#[doc = "DFSDM interrupt flag clear register"]
pub mod dfsdm1_icr;
#[doc = "DFSDM interrupt flag clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_icr](dfsdm2_icr) module"]
pub type DFSDM2_ICR = crate::Reg<u32, _DFSDM2_ICR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_ICR;
#[doc = "`read()` method returns [dfsdm2_icr::R](dfsdm2_icr::R) reader structure"]
impl crate::Readable for DFSDM2_ICR {}
#[doc = "`write(|w| ..)` method takes [dfsdm2_icr::W](dfsdm2_icr::W) writer structure"]
impl crate::Writable for DFSDM2_ICR {}
#[doc = "DFSDM interrupt flag clear register"]
pub mod dfsdm2_icr;
#[doc = "DFSDM interrupt flag clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_icr](dfsdm3_icr) module"]
pub type DFSDM3_ICR = crate::Reg<u32, _DFSDM3_ICR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_ICR;
#[doc = "`read()` method returns [dfsdm3_icr::R](dfsdm3_icr::R) reader structure"]
impl crate::Readable for DFSDM3_ICR {}
#[doc = "`write(|w| ..)` method takes [dfsdm3_icr::W](dfsdm3_icr::W) writer structure"]
impl crate::Writable for DFSDM3_ICR {}
#[doc = "DFSDM interrupt flag clear register"]
pub mod dfsdm3_icr;
#[doc = "DFSDM injected channel group selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_jchgr](dfsdm0_jchgr) module"]
pub type DFSDM0_JCHGR = crate::Reg<u32, _DFSDM0_JCHGR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_JCHGR;
#[doc = "`read()` method returns [dfsdm0_jchgr::R](dfsdm0_jchgr::R) reader structure"]
impl crate::Readable for DFSDM0_JCHGR {}
#[doc = "`write(|w| ..)` method takes [dfsdm0_jchgr::W](dfsdm0_jchgr::W) writer structure"]
impl crate::Writable for DFSDM0_JCHGR {}
#[doc = "DFSDM injected channel group selection register"]
pub mod dfsdm0_jchgr;
#[doc = "DFSDM injected channel group selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_jchgr](dfsdm1_jchgr) module"]
pub type DFSDM1_JCHGR = crate::Reg<u32, _DFSDM1_JCHGR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_JCHGR;
#[doc = "`read()` method returns [dfsdm1_jchgr::R](dfsdm1_jchgr::R) reader structure"]
impl crate::Readable for DFSDM1_JCHGR {}
#[doc = "`write(|w| ..)` method takes [dfsdm1_jchgr::W](dfsdm1_jchgr::W) writer structure"]
impl crate::Writable for DFSDM1_JCHGR {}
#[doc = "DFSDM injected channel group selection register"]
pub mod dfsdm1_jchgr;
#[doc = "DFSDM injected channel group selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_jchgr](dfsdm2_jchgr) module"]
pub type DFSDM2_JCHGR = crate::Reg<u32, _DFSDM2_JCHGR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_JCHGR;
#[doc = "`read()` method returns [dfsdm2_jchgr::R](dfsdm2_jchgr::R) reader structure"]
impl crate::Readable for DFSDM2_JCHGR {}
#[doc = "`write(|w| ..)` method takes [dfsdm2_jchgr::W](dfsdm2_jchgr::W) writer structure"]
impl crate::Writable for DFSDM2_JCHGR {}
#[doc = "DFSDM injected channel group selection register"]
pub mod dfsdm2_jchgr;
#[doc = "DFSDM injected channel group selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_jchgr](dfsdm3_jchgr) module"]
pub type DFSDM3_JCHGR = crate::Reg<u32, _DFSDM3_JCHGR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_JCHGR;
#[doc = "`read()` method returns [dfsdm3_jchgr::R](dfsdm3_jchgr::R) reader structure"]
impl crate::Readable for DFSDM3_JCHGR {}
#[doc = "`write(|w| ..)` method takes [dfsdm3_jchgr::W](dfsdm3_jchgr::W) writer structure"]
impl crate::Writable for DFSDM3_JCHGR {}
#[doc = "DFSDM injected channel group selection register"]
pub mod dfsdm3_jchgr;
#[doc = "DFSDM filter control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_fcr](dfsdm0_fcr) module"]
pub type DFSDM0_FCR = crate::Reg<u32, _DFSDM0_FCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_FCR;
#[doc = "`read()` method returns [dfsdm0_fcr::R](dfsdm0_fcr::R) reader structure"]
impl crate::Readable for DFSDM0_FCR {}
#[doc = "`write(|w| ..)` method takes [dfsdm0_fcr::W](dfsdm0_fcr::W) writer structure"]
impl crate::Writable for DFSDM0_FCR {}
#[doc = "DFSDM filter control register"]
pub mod dfsdm0_fcr;
#[doc = "DFSDM filter control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_fcr](dfsdm1_fcr) module"]
pub type DFSDM1_FCR = crate::Reg<u32, _DFSDM1_FCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_FCR;
#[doc = "`read()` method returns [dfsdm1_fcr::R](dfsdm1_fcr::R) reader structure"]
impl crate::Readable for DFSDM1_FCR {}
#[doc = "`write(|w| ..)` method takes [dfsdm1_fcr::W](dfsdm1_fcr::W) writer structure"]
impl crate::Writable for DFSDM1_FCR {}
#[doc = "DFSDM filter control register"]
pub mod dfsdm1_fcr;
#[doc = "DFSDM filter control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_fcr](dfsdm2_fcr) module"]
pub type DFSDM2_FCR = crate::Reg<u32, _DFSDM2_FCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_FCR;
#[doc = "`read()` method returns [dfsdm2_fcr::R](dfsdm2_fcr::R) reader structure"]
impl crate::Readable for DFSDM2_FCR {}
#[doc = "`write(|w| ..)` method takes [dfsdm2_fcr::W](dfsdm2_fcr::W) writer structure"]
impl crate::Writable for DFSDM2_FCR {}
#[doc = "DFSDM filter control register"]
pub mod dfsdm2_fcr;
#[doc = "DFSDM filter control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_fcr](dfsdm3_fcr) module"]
pub type DFSDM3_FCR = crate::Reg<u32, _DFSDM3_FCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_FCR;
#[doc = "`read()` method returns [dfsdm3_fcr::R](dfsdm3_fcr::R) reader structure"]
impl crate::Readable for DFSDM3_FCR {}
#[doc = "`write(|w| ..)` method takes [dfsdm3_fcr::W](dfsdm3_fcr::W) writer structure"]
impl crate::Writable for DFSDM3_FCR {}
#[doc = "DFSDM filter control register"]
pub mod dfsdm3_fcr;
#[doc = "DFSDM data register for injected group\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_jdatar](dfsdm0_jdatar) module"]
pub type DFSDM0_JDATAR = crate::Reg<u32, _DFSDM0_JDATAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_JDATAR;
#[doc = "`read()` method returns [dfsdm0_jdatar::R](dfsdm0_jdatar::R) reader structure"]
impl crate::Readable for DFSDM0_JDATAR {}
#[doc = "DFSDM data register for injected group"]
pub mod dfsdm0_jdatar;
#[doc = "DFSDM data register for injected group\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_jdatar](dfsdm1_jdatar) module"]
pub type DFSDM1_JDATAR = crate::Reg<u32, _DFSDM1_JDATAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_JDATAR;
#[doc = "`read()` method returns [dfsdm1_jdatar::R](dfsdm1_jdatar::R) reader structure"]
impl crate::Readable for DFSDM1_JDATAR {}
#[doc = "DFSDM data register for injected group"]
pub mod dfsdm1_jdatar;
#[doc = "DFSDM data register for injected group\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_jdatar](dfsdm2_jdatar) module"]
pub type DFSDM2_JDATAR = crate::Reg<u32, _DFSDM2_JDATAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_JDATAR;
#[doc = "`read()` method returns [dfsdm2_jdatar::R](dfsdm2_jdatar::R) reader structure"]
impl crate::Readable for DFSDM2_JDATAR {}
#[doc = "DFSDM data register for injected group"]
pub mod dfsdm2_jdatar;
#[doc = "DFSDM data register for injected group\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_jdatar](dfsdm3_jdatar) module"]
pub type DFSDM3_JDATAR = crate::Reg<u32, _DFSDM3_JDATAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_JDATAR;
#[doc = "`read()` method returns [dfsdm3_jdatar::R](dfsdm3_jdatar::R) reader structure"]
impl crate::Readable for DFSDM3_JDATAR {}
#[doc = "DFSDM data register for injected group"]
pub mod dfsdm3_jdatar;
#[doc = "DFSDM data register for the regular channel\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_rdatar](dfsdm0_rdatar) module"]
pub type DFSDM0_RDATAR = crate::Reg<u32, _DFSDM0_RDATAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_RDATAR;
#[doc = "`read()` method returns [dfsdm0_rdatar::R](dfsdm0_rdatar::R) reader structure"]
impl crate::Readable for DFSDM0_RDATAR {}
#[doc = "DFSDM data register for the regular channel"]
pub mod dfsdm0_rdatar;
#[doc = "DFSDM data register for the regular channel\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_rdatar](dfsdm1_rdatar) module"]
pub type DFSDM1_RDATAR = crate::Reg<u32, _DFSDM1_RDATAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_RDATAR;
#[doc = "`read()` method returns [dfsdm1_rdatar::R](dfsdm1_rdatar::R) reader structure"]
impl crate::Readable for DFSDM1_RDATAR {}
#[doc = "DFSDM data register for the regular channel"]
pub mod dfsdm1_rdatar;
#[doc = "DFSDM data register for the regular channel\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_rdatar](dfsdm2_rdatar) module"]
pub type DFSDM2_RDATAR = crate::Reg<u32, _DFSDM2_RDATAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_RDATAR;
#[doc = "`read()` method returns [dfsdm2_rdatar::R](dfsdm2_rdatar::R) reader structure"]
impl crate::Readable for DFSDM2_RDATAR {}
#[doc = "DFSDM data register for the regular channel"]
pub mod dfsdm2_rdatar;
#[doc = "DFSDM data register for the regular channel\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_rdatar](dfsdm3_rdatar) module"]
pub type DFSDM3_RDATAR = crate::Reg<u32, _DFSDM3_RDATAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_RDATAR;
#[doc = "`read()` method returns [dfsdm3_rdatar::R](dfsdm3_rdatar::R) reader structure"]
impl crate::Readable for DFSDM3_RDATAR {}
#[doc = "DFSDM data register for the regular channel"]
pub mod dfsdm3_rdatar;
#[doc = "DFSDM analog watchdog high threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_awhtr](dfsdm0_awhtr) module"]
pub type DFSDM0_AWHTR = crate::Reg<u32, _DFSDM0_AWHTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_AWHTR;
#[doc = "`read()` method returns [dfsdm0_awhtr::R](dfsdm0_awhtr::R) reader structure"]
impl crate::Readable for DFSDM0_AWHTR {}
#[doc = "`write(|w| ..)` method takes [dfsdm0_awhtr::W](dfsdm0_awhtr::W) writer structure"]
impl crate::Writable for DFSDM0_AWHTR {}
#[doc = "DFSDM analog watchdog high threshold register"]
pub mod dfsdm0_awhtr;
#[doc = "DFSDM analog watchdog high threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_awhtr](dfsdm1_awhtr) module"]
pub type DFSDM1_AWHTR = crate::Reg<u32, _DFSDM1_AWHTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_AWHTR;
#[doc = "`read()` method returns [dfsdm1_awhtr::R](dfsdm1_awhtr::R) reader structure"]
impl crate::Readable for DFSDM1_AWHTR {}
#[doc = "`write(|w| ..)` method takes [dfsdm1_awhtr::W](dfsdm1_awhtr::W) writer structure"]
impl crate::Writable for DFSDM1_AWHTR {}
#[doc = "DFSDM analog watchdog high threshold register"]
pub mod dfsdm1_awhtr;
#[doc = "DFSDM analog watchdog high threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_awhtr](dfsdm2_awhtr) module"]
pub type DFSDM2_AWHTR = crate::Reg<u32, _DFSDM2_AWHTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_AWHTR;
#[doc = "`read()` method returns [dfsdm2_awhtr::R](dfsdm2_awhtr::R) reader structure"]
impl crate::Readable for DFSDM2_AWHTR {}
#[doc = "`write(|w| ..)` method takes [dfsdm2_awhtr::W](dfsdm2_awhtr::W) writer structure"]
impl crate::Writable for DFSDM2_AWHTR {}
#[doc = "DFSDM analog watchdog high threshold register"]
pub mod dfsdm2_awhtr;
#[doc = "DFSDM analog watchdog high threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_awhtr](dfsdm3_awhtr) module"]
pub type DFSDM3_AWHTR = crate::Reg<u32, _DFSDM3_AWHTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_AWHTR;
#[doc = "`read()` method returns [dfsdm3_awhtr::R](dfsdm3_awhtr::R) reader structure"]
impl crate::Readable for DFSDM3_AWHTR {}
#[doc = "`write(|w| ..)` method takes [dfsdm3_awhtr::W](dfsdm3_awhtr::W) writer structure"]
impl crate::Writable for DFSDM3_AWHTR {}
#[doc = "DFSDM analog watchdog high threshold register"]
pub mod dfsdm3_awhtr;
#[doc = "DFSDM analog watchdog low threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_awltr](dfsdm0_awltr) module"]
pub type DFSDM0_AWLTR = crate::Reg<u32, _DFSDM0_AWLTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_AWLTR;
#[doc = "`read()` method returns [dfsdm0_awltr::R](dfsdm0_awltr::R) reader structure"]
impl crate::Readable for DFSDM0_AWLTR {}
#[doc = "`write(|w| ..)` method takes [dfsdm0_awltr::W](dfsdm0_awltr::W) writer structure"]
impl crate::Writable for DFSDM0_AWLTR {}
#[doc = "DFSDM analog watchdog low threshold register"]
pub mod dfsdm0_awltr;
#[doc = "DFSDM analog watchdog low threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_awltr](dfsdm1_awltr) module"]
pub type DFSDM1_AWLTR = crate::Reg<u32, _DFSDM1_AWLTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_AWLTR;
#[doc = "`read()` method returns [dfsdm1_awltr::R](dfsdm1_awltr::R) reader structure"]
impl crate::Readable for DFSDM1_AWLTR {}
#[doc = "`write(|w| ..)` method takes [dfsdm1_awltr::W](dfsdm1_awltr::W) writer structure"]
impl crate::Writable for DFSDM1_AWLTR {}
#[doc = "DFSDM analog watchdog low threshold register"]
pub mod dfsdm1_awltr;
#[doc = "DFSDM analog watchdog low threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_awltr](dfsdm2_awltr) module"]
pub type DFSDM2_AWLTR = crate::Reg<u32, _DFSDM2_AWLTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_AWLTR;
#[doc = "`read()` method returns [dfsdm2_awltr::R](dfsdm2_awltr::R) reader structure"]
impl crate::Readable for DFSDM2_AWLTR {}
#[doc = "`write(|w| ..)` method takes [dfsdm2_awltr::W](dfsdm2_awltr::W) writer structure"]
impl crate::Writable for DFSDM2_AWLTR {}
#[doc = "DFSDM analog watchdog low threshold register"]
pub mod dfsdm2_awltr;
#[doc = "DFSDM analog watchdog low threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_awltr](dfsdm3_awltr) module"]
pub type DFSDM3_AWLTR = crate::Reg<u32, _DFSDM3_AWLTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_AWLTR;
#[doc = "`read()` method returns [dfsdm3_awltr::R](dfsdm3_awltr::R) reader structure"]
impl crate::Readable for DFSDM3_AWLTR {}
#[doc = "`write(|w| ..)` method takes [dfsdm3_awltr::W](dfsdm3_awltr::W) writer structure"]
impl crate::Writable for DFSDM3_AWLTR {}
#[doc = "DFSDM analog watchdog low threshold register"]
pub mod dfsdm3_awltr;
#[doc = "DFSDM analog watchdog status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_awsr](dfsdm0_awsr) module"]
pub type DFSDM0_AWSR = crate::Reg<u32, _DFSDM0_AWSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_AWSR;
#[doc = "`read()` method returns [dfsdm0_awsr::R](dfsdm0_awsr::R) reader structure"]
impl crate::Readable for DFSDM0_AWSR {}
#[doc = "DFSDM analog watchdog status register"]
pub mod dfsdm0_awsr;
#[doc = "DFSDM analog watchdog status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_awsr](dfsdm1_awsr) module"]
pub type DFSDM1_AWSR = crate::Reg<u32, _DFSDM1_AWSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_AWSR;
#[doc = "`read()` method returns [dfsdm1_awsr::R](dfsdm1_awsr::R) reader structure"]
impl crate::Readable for DFSDM1_AWSR {}
#[doc = "DFSDM analog watchdog status register"]
pub mod dfsdm1_awsr;
#[doc = "DFSDM analog watchdog status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_awsr](dfsdm2_awsr) module"]
pub type DFSDM2_AWSR = crate::Reg<u32, _DFSDM2_AWSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_AWSR;
#[doc = "`read()` method returns [dfsdm2_awsr::R](dfsdm2_awsr::R) reader structure"]
impl crate::Readable for DFSDM2_AWSR {}
#[doc = "DFSDM analog watchdog status register"]
pub mod dfsdm2_awsr;
#[doc = "DFSDM analog watchdog status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_awsr](dfsdm3_awsr) module"]
pub type DFSDM3_AWSR = crate::Reg<u32, _DFSDM3_AWSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_AWSR;
#[doc = "`read()` method returns [dfsdm3_awsr::R](dfsdm3_awsr::R) reader structure"]
impl crate::Readable for DFSDM3_AWSR {}
#[doc = "DFSDM analog watchdog status register"]
pub mod dfsdm3_awsr;
#[doc = "DFSDM analog watchdog clear flag register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_awcfr](dfsdm0_awcfr) module"]
pub type DFSDM0_AWCFR = crate::Reg<u32, _DFSDM0_AWCFR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_AWCFR;
#[doc = "`read()` method returns [dfsdm0_awcfr::R](dfsdm0_awcfr::R) reader structure"]
impl crate::Readable for DFSDM0_AWCFR {}
#[doc = "`write(|w| ..)` method takes [dfsdm0_awcfr::W](dfsdm0_awcfr::W) writer structure"]
impl crate::Writable for DFSDM0_AWCFR {}
#[doc = "DFSDM analog watchdog clear flag register"]
pub mod dfsdm0_awcfr;
#[doc = "DFSDM analog watchdog clear flag register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_awcfr](dfsdm1_awcfr) module"]
pub type DFSDM1_AWCFR = crate::Reg<u32, _DFSDM1_AWCFR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_AWCFR;
#[doc = "`read()` method returns [dfsdm1_awcfr::R](dfsdm1_awcfr::R) reader structure"]
impl crate::Readable for DFSDM1_AWCFR {}
#[doc = "`write(|w| ..)` method takes [dfsdm1_awcfr::W](dfsdm1_awcfr::W) writer structure"]
impl crate::Writable for DFSDM1_AWCFR {}
#[doc = "DFSDM analog watchdog clear flag register"]
pub mod dfsdm1_awcfr;
#[doc = "DFSDM analog watchdog clear flag register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_awcfr](dfsdm2_awcfr) module"]
pub type DFSDM2_AWCFR = crate::Reg<u32, _DFSDM2_AWCFR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_AWCFR;
#[doc = "`read()` method returns [dfsdm2_awcfr::R](dfsdm2_awcfr::R) reader structure"]
impl crate::Readable for DFSDM2_AWCFR {}
#[doc = "`write(|w| ..)` method takes [dfsdm2_awcfr::W](dfsdm2_awcfr::W) writer structure"]
impl crate::Writable for DFSDM2_AWCFR {}
#[doc = "DFSDM analog watchdog clear flag register"]
pub mod dfsdm2_awcfr;
#[doc = "DFSDM analog watchdog clear flag register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_awcfr](dfsdm3_awcfr) module"]
pub type DFSDM3_AWCFR = crate::Reg<u32, _DFSDM3_AWCFR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_AWCFR;
#[doc = "`read()` method returns [dfsdm3_awcfr::R](dfsdm3_awcfr::R) reader structure"]
impl crate::Readable for DFSDM3_AWCFR {}
#[doc = "`write(|w| ..)` method takes [dfsdm3_awcfr::W](dfsdm3_awcfr::W) writer structure"]
impl crate::Writable for DFSDM3_AWCFR {}
#[doc = "DFSDM analog watchdog clear flag register"]
pub mod dfsdm3_awcfr;
#[doc = "DFSDM Extremes detector maximum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_exmax](dfsdm0_exmax) module"]
pub type DFSDM0_EXMAX = crate::Reg<u32, _DFSDM0_EXMAX>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_EXMAX;
#[doc = "`read()` method returns [dfsdm0_exmax::R](dfsdm0_exmax::R) reader structure"]
impl crate::Readable for DFSDM0_EXMAX {}
#[doc = "DFSDM Extremes detector maximum register"]
pub mod dfsdm0_exmax;
#[doc = "DFSDM Extremes detector maximum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_exmax](dfsdm1_exmax) module"]
pub type DFSDM1_EXMAX = crate::Reg<u32, _DFSDM1_EXMAX>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_EXMAX;
#[doc = "`read()` method returns [dfsdm1_exmax::R](dfsdm1_exmax::R) reader structure"]
impl crate::Readable for DFSDM1_EXMAX {}
#[doc = "DFSDM Extremes detector maximum register"]
pub mod dfsdm1_exmax;
#[doc = "DFSDM Extremes detector maximum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_exmax](dfsdm2_exmax) module"]
pub type DFSDM2_EXMAX = crate::Reg<u32, _DFSDM2_EXMAX>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_EXMAX;
#[doc = "`read()` method returns [dfsdm2_exmax::R](dfsdm2_exmax::R) reader structure"]
impl crate::Readable for DFSDM2_EXMAX {}
#[doc = "DFSDM Extremes detector maximum register"]
pub mod dfsdm2_exmax;
#[doc = "DFSDM Extremes detector maximum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_exmax](dfsdm3_exmax) module"]
pub type DFSDM3_EXMAX = crate::Reg<u32, _DFSDM3_EXMAX>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_EXMAX;
#[doc = "`read()` method returns [dfsdm3_exmax::R](dfsdm3_exmax::R) reader structure"]
impl crate::Readable for DFSDM3_EXMAX {}
#[doc = "DFSDM Extremes detector maximum register"]
pub mod dfsdm3_exmax;
#[doc = "DFSDM Extremes detector minimum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_exmin](dfsdm0_exmin) module"]
pub type DFSDM0_EXMIN = crate::Reg<u32, _DFSDM0_EXMIN>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_EXMIN;
#[doc = "`read()` method returns [dfsdm0_exmin::R](dfsdm0_exmin::R) reader structure"]
impl crate::Readable for DFSDM0_EXMIN {}
#[doc = "DFSDM Extremes detector minimum register"]
pub mod dfsdm0_exmin;
#[doc = "DFSDM Extremes detector minimum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_exmin](dfsdm1_exmin) module"]
pub type DFSDM1_EXMIN = crate::Reg<u32, _DFSDM1_EXMIN>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_EXMIN;
#[doc = "`read()` method returns [dfsdm1_exmin::R](dfsdm1_exmin::R) reader structure"]
impl crate::Readable for DFSDM1_EXMIN {}
#[doc = "DFSDM Extremes detector minimum register"]
pub mod dfsdm1_exmin;
#[doc = "DFSDM Extremes detector minimum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_exmin](dfsdm2_exmin) module"]
pub type DFSDM2_EXMIN = crate::Reg<u32, _DFSDM2_EXMIN>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_EXMIN;
#[doc = "`read()` method returns [dfsdm2_exmin::R](dfsdm2_exmin::R) reader structure"]
impl crate::Readable for DFSDM2_EXMIN {}
#[doc = "DFSDM Extremes detector minimum register"]
pub mod dfsdm2_exmin;
#[doc = "DFSDM Extremes detector minimum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_exmin](dfsdm3_exmin) module"]
pub type DFSDM3_EXMIN = crate::Reg<u32, _DFSDM3_EXMIN>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_EXMIN;
#[doc = "`read()` method returns [dfsdm3_exmin::R](dfsdm3_exmin::R) reader structure"]
impl crate::Readable for DFSDM3_EXMIN {}
#[doc = "DFSDM Extremes detector minimum register"]
pub mod dfsdm3_exmin;
#[doc = "DFSDM conversion timer register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm0_cnvtimr](dfsdm0_cnvtimr) module"]
pub type DFSDM0_CNVTIMR = crate::Reg<u32, _DFSDM0_CNVTIMR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM0_CNVTIMR;
#[doc = "`read()` method returns [dfsdm0_cnvtimr::R](dfsdm0_cnvtimr::R) reader structure"]
impl crate::Readable for DFSDM0_CNVTIMR {}
#[doc = "DFSDM conversion timer register"]
pub mod dfsdm0_cnvtimr;
#[doc = "DFSDM conversion timer register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm1_cnvtimr](dfsdm1_cnvtimr) module"]
pub type DFSDM1_CNVTIMR = crate::Reg<u32, _DFSDM1_CNVTIMR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM1_CNVTIMR;
#[doc = "`read()` method returns [dfsdm1_cnvtimr::R](dfsdm1_cnvtimr::R) reader structure"]
impl crate::Readable for DFSDM1_CNVTIMR {}
#[doc = "DFSDM conversion timer register"]
pub mod dfsdm1_cnvtimr;
#[doc = "DFSDM conversion timer register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm2_cnvtimr](dfsdm2_cnvtimr) module"]
pub type DFSDM2_CNVTIMR = crate::Reg<u32, _DFSDM2_CNVTIMR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM2_CNVTIMR;
#[doc = "`read()` method returns [dfsdm2_cnvtimr::R](dfsdm2_cnvtimr::R) reader structure"]
impl crate::Readable for DFSDM2_CNVTIMR {}
#[doc = "DFSDM conversion timer register"]
pub mod dfsdm2_cnvtimr;
#[doc = "DFSDM conversion timer register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm3_cnvtimr](dfsdm3_cnvtimr) module"]
pub type DFSDM3_CNVTIMR = crate::Reg<u32, _DFSDM3_CNVTIMR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DFSDM3_CNVTIMR;
#[doc = "`read()` method returns [dfsdm3_cnvtimr::R](dfsdm3_cnvtimr::R) reader structure"]
impl crate::Readable for DFSDM3_CNVTIMR {}
#[doc = "DFSDM conversion timer register"]
pub mod dfsdm3_cnvtimr;
|
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_activity_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateActivityOutput, crate::error::CreateActivityError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CreateActivityError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CreateActivityError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ActivityLimitExceeded" => crate::error::CreateActivityError {
meta: generic,
kind: crate::error::CreateActivityErrorKind::ActivityLimitExceeded({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::activity_limit_exceeded::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_activity_limit_exceededjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateActivityError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidName" => crate::error::CreateActivityError {
meta: generic,
kind: crate::error::CreateActivityErrorKind::InvalidName({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_name::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_namejson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateActivityError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TooManyTags" => crate::error::CreateActivityError {
meta: generic,
kind: crate::error::CreateActivityErrorKind::TooManyTags({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::too_many_tags::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_too_many_tagsjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateActivityError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::CreateActivityError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_activity_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::CreateActivityOutput, crate::error::CreateActivityError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::create_activity_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_create_activity(response.body().as_ref(), output)
.map_err(crate::error::CreateActivityError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_state_machine_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::CreateStateMachineOutput,
crate::error::CreateStateMachineError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::CreateStateMachineError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::CreateStateMachineError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidArn" => crate::error::CreateStateMachineError {
meta: generic,
kind: crate::error::CreateStateMachineErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidDefinition" => crate::error::CreateStateMachineError {
meta: generic,
kind: crate::error::CreateStateMachineErrorKind::InvalidDefinition({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_definition::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_definitionjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidLoggingConfiguration" => {
crate::error::CreateStateMachineError {
meta: generic,
kind: crate::error::CreateStateMachineErrorKind::InvalidLoggingConfiguration({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_logging_configuration::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_logging_configurationjson_err(response.body().as_ref(), output).map_err(crate::error::CreateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InvalidName" => crate::error::CreateStateMachineError {
meta: generic,
kind: crate::error::CreateStateMachineErrorKind::InvalidName({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_name::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_namejson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidTracingConfiguration" => {
crate::error::CreateStateMachineError {
meta: generic,
kind: crate::error::CreateStateMachineErrorKind::InvalidTracingConfiguration({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_tracing_configuration::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_tracing_configurationjson_err(response.body().as_ref(), output).map_err(crate::error::CreateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"StateMachineAlreadyExists" => {
crate::error::CreateStateMachineError {
meta: generic,
kind: crate::error::CreateStateMachineErrorKind::StateMachineAlreadyExists({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::state_machine_already_exists::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_already_existsjson_err(response.body().as_ref(), output).map_err(crate::error::CreateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"StateMachineDeleting" => crate::error::CreateStateMachineError {
meta: generic,
kind: crate::error::CreateStateMachineErrorKind::StateMachineDeleting({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::state_machine_deleting::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_deletingjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"StateMachineLimitExceeded" => {
crate::error::CreateStateMachineError {
meta: generic,
kind: crate::error::CreateStateMachineErrorKind::StateMachineLimitExceeded({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::state_machine_limit_exceeded::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_limit_exceededjson_err(response.body().as_ref(), output).map_err(crate::error::CreateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"StateMachineTypeNotSupported" => crate::error::CreateStateMachineError {
meta: generic,
kind: crate::error::CreateStateMachineErrorKind::StateMachineTypeNotSupported({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::state_machine_type_not_supported::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_type_not_supportedjson_err(response.body().as_ref(), output).map_err(crate::error::CreateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TooManyTags" => crate::error::CreateStateMachineError {
meta: generic,
kind: crate::error::CreateStateMachineErrorKind::TooManyTags({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::too_many_tags::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_too_many_tagsjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::CreateStateMachineError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_create_state_machine_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::CreateStateMachineOutput,
crate::error::CreateStateMachineError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::create_state_machine_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_create_state_machine(
response.body().as_ref(),
output,
)
.map_err(crate::error::CreateStateMachineError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_activity_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteActivityOutput, crate::error::DeleteActivityError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DeleteActivityError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DeleteActivityError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidArn" => crate::error::DeleteActivityError {
meta: generic,
kind: crate::error::DeleteActivityErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DeleteActivityError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DeleteActivityError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_activity_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DeleteActivityOutput, crate::error::DeleteActivityError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::delete_activity_output::Builder::default();
let _ = response;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_state_machine_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DeleteStateMachineOutput,
crate::error::DeleteStateMachineError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DeleteStateMachineError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DeleteStateMachineError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidArn" => crate::error::DeleteStateMachineError {
meta: generic,
kind: crate::error::DeleteStateMachineErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DeleteStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DeleteStateMachineError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_delete_state_machine_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DeleteStateMachineOutput,
crate::error::DeleteStateMachineError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::delete_state_machine_output::Builder::default();
let _ = response;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_activity_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeActivityOutput, crate::error::DescribeActivityError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeActivityError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeActivityError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ActivityDoesNotExist" => crate::error::DescribeActivityError {
meta: generic,
kind: crate::error::DescribeActivityErrorKind::ActivityDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::activity_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_activity_does_not_existjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeActivityError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidArn" => crate::error::DescribeActivityError {
meta: generic,
kind: crate::error::DescribeActivityErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeActivityError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeActivityError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_activity_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeActivityOutput, crate::error::DescribeActivityError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_activity_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_describe_activity(response.body().as_ref(), output)
.map_err(crate::error::DescribeActivityError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_execution_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeExecutionOutput, crate::error::DescribeExecutionError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeExecutionError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeExecutionError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ExecutionDoesNotExist" => crate::error::DescribeExecutionError {
meta: generic,
kind: crate::error::DescribeExecutionErrorKind::ExecutionDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::execution_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_execution_does_not_existjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidArn" => crate::error::DescribeExecutionError {
meta: generic,
kind: crate::error::DescribeExecutionErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeExecutionError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_execution_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::DescribeExecutionOutput, crate::error::DescribeExecutionError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_execution_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_describe_execution(response.body().as_ref(), output)
.map_err(crate::error::DescribeExecutionError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_state_machine_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeStateMachineOutput,
crate::error::DescribeStateMachineError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeStateMachineError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::DescribeStateMachineError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidArn" => crate::error::DescribeStateMachineError {
meta: generic,
kind: crate::error::DescribeStateMachineErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"StateMachineDoesNotExist" => {
crate::error::DescribeStateMachineError {
meta: generic,
kind: crate::error::DescribeStateMachineErrorKind::StateMachineDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::state_machine_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_does_not_existjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
_ => crate::error::DescribeStateMachineError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_state_machine_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeStateMachineOutput,
crate::error::DescribeStateMachineError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::describe_state_machine_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_describe_state_machine(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeStateMachineError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_state_machine_for_execution_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeStateMachineForExecutionOutput,
crate::error::DescribeStateMachineForExecutionError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::DescribeStateMachineForExecutionError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => {
return Err(crate::error::DescribeStateMachineForExecutionError::unhandled(generic))
}
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ExecutionDoesNotExist" => crate::error::DescribeStateMachineForExecutionError {
meta: generic,
kind: crate::error::DescribeStateMachineForExecutionErrorKind::ExecutionDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::execution_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_execution_does_not_existjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeStateMachineForExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidArn" => crate::error::DescribeStateMachineForExecutionError {
meta: generic,
kind: crate::error::DescribeStateMachineForExecutionErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeStateMachineForExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::DescribeStateMachineForExecutionError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_describe_state_machine_for_execution_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::DescribeStateMachineForExecutionOutput,
crate::error::DescribeStateMachineForExecutionError,
> {
Ok({
#[allow(unused_mut)]
let mut output =
crate::output::describe_state_machine_for_execution_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_describe_state_machine_for_execution(
response.body().as_ref(),
output,
)
.map_err(crate::error::DescribeStateMachineForExecutionError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_get_activity_task_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::GetActivityTaskOutput, crate::error::GetActivityTaskError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::GetActivityTaskError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::GetActivityTaskError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ActivityDoesNotExist" => crate::error::GetActivityTaskError {
meta: generic,
kind: crate::error::GetActivityTaskErrorKind::ActivityDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::activity_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_activity_does_not_existjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::GetActivityTaskError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ActivityWorkerLimitExceeded" => {
crate::error::GetActivityTaskError {
meta: generic,
kind: crate::error::GetActivityTaskErrorKind::ActivityWorkerLimitExceeded({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::activity_worker_limit_exceeded::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_activity_worker_limit_exceededjson_err(response.body().as_ref(), output).map_err(crate::error::GetActivityTaskError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InvalidArn" => crate::error::GetActivityTaskError {
meta: generic,
kind: crate::error::GetActivityTaskErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::GetActivityTaskError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::GetActivityTaskError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_get_activity_task_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::GetActivityTaskOutput, crate::error::GetActivityTaskError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::get_activity_task_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_get_activity_task(response.body().as_ref(), output)
.map_err(crate::error::GetActivityTaskError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_get_execution_history_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::GetExecutionHistoryOutput,
crate::error::GetExecutionHistoryError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::GetExecutionHistoryError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::GetExecutionHistoryError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ExecutionDoesNotExist" => crate::error::GetExecutionHistoryError {
meta: generic,
kind: crate::error::GetExecutionHistoryErrorKind::ExecutionDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::execution_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_execution_does_not_existjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::GetExecutionHistoryError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidArn" => crate::error::GetExecutionHistoryError {
meta: generic,
kind: crate::error::GetExecutionHistoryErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::GetExecutionHistoryError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidToken" => crate::error::GetExecutionHistoryError {
meta: generic,
kind: crate::error::GetExecutionHistoryErrorKind::InvalidToken({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_token::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_tokenjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::GetExecutionHistoryError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::GetExecutionHistoryError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_get_execution_history_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::GetExecutionHistoryOutput,
crate::error::GetExecutionHistoryError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::get_execution_history_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_get_execution_history(
response.body().as_ref(),
output,
)
.map_err(crate::error::GetExecutionHistoryError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_activities_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListActivitiesOutput, crate::error::ListActivitiesError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::ListActivitiesError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::ListActivitiesError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidToken" => crate::error::ListActivitiesError {
meta: generic,
kind: crate::error::ListActivitiesErrorKind::InvalidToken({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_token::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_tokenjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListActivitiesError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::ListActivitiesError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_activities_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListActivitiesOutput, crate::error::ListActivitiesError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::list_activities_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_list_activities(response.body().as_ref(), output)
.map_err(crate::error::ListActivitiesError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_executions_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListExecutionsOutput, crate::error::ListExecutionsError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::ListExecutionsError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::ListExecutionsError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidArn" => crate::error::ListExecutionsError {
meta: generic,
kind: crate::error::ListExecutionsErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListExecutionsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidToken" => crate::error::ListExecutionsError {
meta: generic,
kind: crate::error::ListExecutionsErrorKind::InvalidToken({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_token::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_tokenjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListExecutionsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"StateMachineDoesNotExist" => {
crate::error::ListExecutionsError {
meta: generic,
kind: crate::error::ListExecutionsErrorKind::StateMachineDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::state_machine_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_does_not_existjson_err(response.body().as_ref(), output).map_err(crate::error::ListExecutionsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"StateMachineTypeNotSupported" => crate::error::ListExecutionsError {
meta: generic,
kind: crate::error::ListExecutionsErrorKind::StateMachineTypeNotSupported({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::state_machine_type_not_supported::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_type_not_supportedjson_err(response.body().as_ref(), output).map_err(crate::error::ListExecutionsError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::ListExecutionsError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_executions_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListExecutionsOutput, crate::error::ListExecutionsError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::list_executions_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_list_executions(response.body().as_ref(), output)
.map_err(crate::error::ListExecutionsError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_state_machines_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListStateMachinesOutput, crate::error::ListStateMachinesError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::ListStateMachinesError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::ListStateMachinesError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidToken" => crate::error::ListStateMachinesError {
meta: generic,
kind: crate::error::ListStateMachinesErrorKind::InvalidToken({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_token::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_tokenjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListStateMachinesError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::ListStateMachinesError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_state_machines_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::ListStateMachinesOutput, crate::error::ListStateMachinesError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::list_state_machines_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_list_state_machines(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListStateMachinesError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_tags_for_resource_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::ListTagsForResourceOutput,
crate::error::ListTagsForResourceError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::ListTagsForResourceError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::ListTagsForResourceError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidArn" => crate::error::ListTagsForResourceError {
meta: generic,
kind: crate::error::ListTagsForResourceErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListTagsForResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFound" => crate::error::ListTagsForResourceError {
meta: generic,
kind: crate::error::ListTagsForResourceErrorKind::ResourceNotFound({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_resource_not_foundjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListTagsForResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::ListTagsForResourceError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_list_tags_for_resource_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::ListTagsForResourceOutput,
crate::error::ListTagsForResourceError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::list_tags_for_resource_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_list_tags_for_resource(
response.body().as_ref(),
output,
)
.map_err(crate::error::ListTagsForResourceError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_send_task_failure_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::SendTaskFailureOutput, crate::error::SendTaskFailureError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::SendTaskFailureError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::SendTaskFailureError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidToken" => crate::error::SendTaskFailureError {
meta: generic,
kind: crate::error::SendTaskFailureErrorKind::InvalidToken({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_token::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_tokenjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::SendTaskFailureError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TaskDoesNotExist" => crate::error::SendTaskFailureError {
meta: generic,
kind: crate::error::SendTaskFailureErrorKind::TaskDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::task_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_task_does_not_existjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::SendTaskFailureError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TaskTimedOut" => crate::error::SendTaskFailureError {
meta: generic,
kind: crate::error::SendTaskFailureErrorKind::TaskTimedOut({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::task_timed_out::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_task_timed_outjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::SendTaskFailureError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::SendTaskFailureError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_send_task_failure_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::SendTaskFailureOutput, crate::error::SendTaskFailureError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::send_task_failure_output::Builder::default();
let _ = response;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_send_task_heartbeat_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::SendTaskHeartbeatOutput, crate::error::SendTaskHeartbeatError>
{
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::SendTaskHeartbeatError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::SendTaskHeartbeatError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidToken" => crate::error::SendTaskHeartbeatError {
meta: generic,
kind: crate::error::SendTaskHeartbeatErrorKind::InvalidToken({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_token::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_tokenjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::SendTaskHeartbeatError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TaskDoesNotExist" => crate::error::SendTaskHeartbeatError {
meta: generic,
kind: crate::error::SendTaskHeartbeatErrorKind::TaskDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::task_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_task_does_not_existjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::SendTaskHeartbeatError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TaskTimedOut" => crate::error::SendTaskHeartbeatError {
meta: generic,
kind: crate::error::SendTaskHeartbeatErrorKind::TaskTimedOut({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::task_timed_out::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_task_timed_outjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::SendTaskHeartbeatError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::SendTaskHeartbeatError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_send_task_heartbeat_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::SendTaskHeartbeatOutput, crate::error::SendTaskHeartbeatError>
{
Ok({
#[allow(unused_mut)]
let mut output = crate::output::send_task_heartbeat_output::Builder::default();
let _ = response;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_send_task_success_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::SendTaskSuccessOutput, crate::error::SendTaskSuccessError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::SendTaskSuccessError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::SendTaskSuccessError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidOutput" => crate::error::SendTaskSuccessError {
meta: generic,
kind: crate::error::SendTaskSuccessErrorKind::InvalidOutput({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_outputjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::SendTaskSuccessError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidToken" => crate::error::SendTaskSuccessError {
meta: generic,
kind: crate::error::SendTaskSuccessErrorKind::InvalidToken({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_token::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_tokenjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::SendTaskSuccessError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TaskDoesNotExist" => crate::error::SendTaskSuccessError {
meta: generic,
kind: crate::error::SendTaskSuccessErrorKind::TaskDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::task_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_task_does_not_existjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::SendTaskSuccessError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TaskTimedOut" => crate::error::SendTaskSuccessError {
meta: generic,
kind: crate::error::SendTaskSuccessErrorKind::TaskTimedOut({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::task_timed_out::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_task_timed_outjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::SendTaskSuccessError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::SendTaskSuccessError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_send_task_success_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::SendTaskSuccessOutput, crate::error::SendTaskSuccessError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::send_task_success_output::Builder::default();
let _ = response;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_start_execution_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::StartExecutionOutput, crate::error::StartExecutionError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::StartExecutionError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::StartExecutionError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ExecutionAlreadyExists" => crate::error::StartExecutionError {
meta: generic,
kind: crate::error::StartExecutionErrorKind::ExecutionAlreadyExists({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::execution_already_exists::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_execution_already_existsjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::StartExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ExecutionLimitExceeded" => crate::error::StartExecutionError {
meta: generic,
kind: crate::error::StartExecutionErrorKind::ExecutionLimitExceeded({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::execution_limit_exceeded::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_execution_limit_exceededjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::StartExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidArn" => crate::error::StartExecutionError {
meta: generic,
kind: crate::error::StartExecutionErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::StartExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidExecutionInput" => crate::error::StartExecutionError {
meta: generic,
kind: crate::error::StartExecutionErrorKind::InvalidExecutionInput({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_execution_input::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_execution_inputjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::StartExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidName" => crate::error::StartExecutionError {
meta: generic,
kind: crate::error::StartExecutionErrorKind::InvalidName({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_name::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_namejson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::StartExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"StateMachineDeleting" => crate::error::StartExecutionError {
meta: generic,
kind: crate::error::StartExecutionErrorKind::StateMachineDeleting({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::state_machine_deleting::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_deletingjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::StartExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"StateMachineDoesNotExist" => {
crate::error::StartExecutionError {
meta: generic,
kind: crate::error::StartExecutionErrorKind::StateMachineDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::state_machine_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_does_not_existjson_err(response.body().as_ref(), output).map_err(crate::error::StartExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
_ => crate::error::StartExecutionError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_start_execution_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::StartExecutionOutput, crate::error::StartExecutionError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::start_execution_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_start_execution(response.body().as_ref(), output)
.map_err(crate::error::StartExecutionError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_start_sync_execution_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::StartSyncExecutionOutput,
crate::error::StartSyncExecutionError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::StartSyncExecutionError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::StartSyncExecutionError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidArn" => crate::error::StartSyncExecutionError {
meta: generic,
kind: crate::error::StartSyncExecutionErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::StartSyncExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidExecutionInput" => crate::error::StartSyncExecutionError {
meta: generic,
kind: crate::error::StartSyncExecutionErrorKind::InvalidExecutionInput({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_execution_input::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_execution_inputjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::StartSyncExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidName" => crate::error::StartSyncExecutionError {
meta: generic,
kind: crate::error::StartSyncExecutionErrorKind::InvalidName({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_name::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_namejson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::StartSyncExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"StateMachineDeleting" => crate::error::StartSyncExecutionError {
meta: generic,
kind: crate::error::StartSyncExecutionErrorKind::StateMachineDeleting({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::state_machine_deleting::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_deletingjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::StartSyncExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"StateMachineDoesNotExist" => {
crate::error::StartSyncExecutionError {
meta: generic,
kind: crate::error::StartSyncExecutionErrorKind::StateMachineDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::state_machine_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_does_not_existjson_err(response.body().as_ref(), output).map_err(crate::error::StartSyncExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"StateMachineTypeNotSupported" => crate::error::StartSyncExecutionError {
meta: generic,
kind: crate::error::StartSyncExecutionErrorKind::StateMachineTypeNotSupported({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::state_machine_type_not_supported::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_type_not_supportedjson_err(response.body().as_ref(), output).map_err(crate::error::StartSyncExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::StartSyncExecutionError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_start_sync_execution_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::StartSyncExecutionOutput,
crate::error::StartSyncExecutionError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::start_sync_execution_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_start_sync_execution(
response.body().as_ref(),
output,
)
.map_err(crate::error::StartSyncExecutionError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_stop_execution_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::StopExecutionOutput, crate::error::StopExecutionError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::StopExecutionError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::StopExecutionError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"ExecutionDoesNotExist" => crate::error::StopExecutionError {
meta: generic,
kind: crate::error::StopExecutionErrorKind::ExecutionDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::execution_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_execution_does_not_existjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::StopExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidArn" => crate::error::StopExecutionError {
meta: generic,
kind: crate::error::StopExecutionErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::StopExecutionError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::StopExecutionError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_stop_execution_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::StopExecutionOutput, crate::error::StopExecutionError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::stop_execution_output::Builder::default();
let _ = response;
output =
crate::json_deser::deser_operation_stop_execution(response.body().as_ref(), output)
.map_err(crate::error::StopExecutionError::unhandled)?;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_tag_resource_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::TagResourceOutput, crate::error::TagResourceError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::TagResourceError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::TagResourceError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidArn" => crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFound" => crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::ResourceNotFound({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_resource_not_foundjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"TooManyTags" => crate::error::TagResourceError {
meta: generic,
kind: crate::error::TagResourceErrorKind::TooManyTags({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::too_many_tags::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_too_many_tagsjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::TagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::TagResourceError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_tag_resource_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::TagResourceOutput, crate::error::TagResourceError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::tag_resource_output::Builder::default();
let _ = response;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_untag_resource_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UntagResourceOutput, crate::error::UntagResourceError> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::UntagResourceError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::UntagResourceError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidArn" => crate::error::UntagResourceError {
meta: generic,
kind: crate::error::UntagResourceErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"ResourceNotFound" => crate::error::UntagResourceError {
meta: generic,
kind: crate::error::UntagResourceErrorKind::ResourceNotFound({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::resource_not_found::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_resource_not_foundjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UntagResourceError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
_ => crate::error::UntagResourceError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_untag_resource_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<crate::output::UntagResourceOutput, crate::error::UntagResourceError> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::untag_resource_output::Builder::default();
let _ = response;
output.build()
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_state_machine_error(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::UpdateStateMachineOutput,
crate::error::UpdateStateMachineError,
> {
let generic = crate::json_deser::parse_http_generic_error(response)
.map_err(crate::error::UpdateStateMachineError::unhandled)?;
let error_code = match generic.code() {
Some(code) => code,
None => return Err(crate::error::UpdateStateMachineError::unhandled(generic)),
};
let _error_message = generic.message().map(|msg| msg.to_owned());
Err(match error_code {
"InvalidArn" => crate::error::UpdateStateMachineError {
meta: generic,
kind: crate::error::UpdateStateMachineErrorKind::InvalidArn({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_arn::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_arnjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidDefinition" => crate::error::UpdateStateMachineError {
meta: generic,
kind: crate::error::UpdateStateMachineErrorKind::InvalidDefinition({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::invalid_definition::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_definitionjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"InvalidLoggingConfiguration" => {
crate::error::UpdateStateMachineError {
meta: generic,
kind: crate::error::UpdateStateMachineErrorKind::InvalidLoggingConfiguration({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_logging_configuration::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_logging_configurationjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"InvalidTracingConfiguration" => {
crate::error::UpdateStateMachineError {
meta: generic,
kind: crate::error::UpdateStateMachineErrorKind::InvalidTracingConfiguration({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::invalid_tracing_configuration::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_invalid_tracing_configurationjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
"MissingRequiredParameter" => crate::error::UpdateStateMachineError {
meta: generic,
kind: crate::error::UpdateStateMachineErrorKind::MissingRequiredParameter({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::missing_required_parameter::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_missing_required_parameterjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"StateMachineDeleting" => crate::error::UpdateStateMachineError {
meta: generic,
kind: crate::error::UpdateStateMachineErrorKind::StateMachineDeleting({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output = crate::error::state_machine_deleting::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_deletingjson_err(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
},
"StateMachineDoesNotExist" => {
crate::error::UpdateStateMachineError {
meta: generic,
kind: crate::error::UpdateStateMachineErrorKind::StateMachineDoesNotExist({
#[allow(unused_mut)]
let mut tmp = {
#[allow(unused_mut)]
let mut output =
crate::error::state_machine_does_not_exist::Builder::default();
let _ = response;
output = crate::json_deser::deser_structure_state_machine_does_not_existjson_err(response.body().as_ref(), output).map_err(crate::error::UpdateStateMachineError::unhandled)?;
output.build()
};
if (&tmp.message).is_none() {
tmp.message = _error_message;
}
tmp
}),
}
}
_ => crate::error::UpdateStateMachineError::generic(generic),
})
}
#[allow(clippy::unnecessary_wraps)]
pub fn parse_update_state_machine_response(
response: &http::Response<bytes::Bytes>,
) -> std::result::Result<
crate::output::UpdateStateMachineOutput,
crate::error::UpdateStateMachineError,
> {
Ok({
#[allow(unused_mut)]
let mut output = crate::output::update_state_machine_output::Builder::default();
let _ = response;
output = crate::json_deser::deser_operation_update_state_machine(
response.body().as_ref(),
output,
)
.map_err(crate::error::UpdateStateMachineError::unhandled)?;
output.build()
})
}
|
use std::sync::Arc;
use mixer::{Controller, MixerIn, ChannelIn};
use sequence::{Sequence, Field, Command, Note};
pub struct Track {
pub seq: Sequence,
chan: Vec<Channel>,
row_jump: Option<usize>,
row: usize,
tick_count: u8,
tick_rate: u8,
bpm: u8,
pcm: Arc<Vec<i8>>,
}
#[derive(Clone)]
pub struct Channel {
note: u16,
add_note: u16,
porta_note: u8,
cmd: Command,
vol: i16,
}
impl Channel {
fn new() -> Self {
Channel {
note: 0,
add_note: 0,
porta_note: 0,
cmd: Command::zero(),
vol: 0,
}
}
}
impl Track {
pub fn new(fields: Vec<Vec<Field>>) -> Self {
Track {
seq: Sequence::new(fields),
chan: vec![],
row: 0,
row_jump: None,
tick_count: 0,
tick_rate: 6,
bpm: 120,
pcm: Arc::new((0..256)
.map(|i| ((i as f64 / 128.0 * 3.1415).sin() * 127.0) as i8)
.collect()),
}
}
fn channel_beat(&mut self, i: usize) {
let field = &self.seq.get_field(self.row, i);
let chan = &mut self.chan[i];
match field.note {
Note::On(n) => {
match field.cmd.id {
b'3' => chan.porta_note = n,
_ => chan.note = (n as u16)<<8,
}
chan.vol = 0x40;
}
Note::Off => chan.vol = 0,
Note::Hold => {},
}
// effect memory: Only overwrite command data on a new id,
// or on nonzero data.
if field.cmd.data != 0 || field.cmd.id != chan.cmd.id {
chan.cmd.data = field.cmd.data;
}
chan.cmd.id = field.cmd.id;
}
fn channel_tick(&mut self, i: usize) {
let chan = &mut self.chan[i];
let field = &self.seq.get_field(self.row, i);
match field.cmd.id {
b'0' => {
chan.add_note =
// arpeggio has no effect memory;
// use the immediate command data.
match self.tick_count % 3 {
0 => 0,
1 => (field.cmd.hi() as u16)<<8,
2 => (field.cmd.lo() as u16)<<8,
_ => unreachable!(),
};
}
b'1' => chan.note = chan.note
.saturating_add((chan.cmd.data as u16)<<4),
b'2' => chan.note = chan.note
.saturating_sub((chan.cmd.data as u16)<<4),
b'3' => {
let porta_note = (chan.porta_note as u16)<<8;
let rate = (chan.cmd.data as u16)<<4;
let diff = chan.note - porta_note;
if diff.abs() < rate {
chan.note = porta_note;
} else if diff > 0 {
chan.note -= rate;
} else {
chan.note += rate;
}
}
b'F' => {
match chan.cmd.data {
0...31 => self.tick_rate = chan.cmd.data + 1,
32...255 => self.bpm = chan.cmd.data,
_ => unreachable!(),
}
}
b'B' => self.row_jump = Some(chan.cmd.data as usize),
c @ _ => panic!("unknown command id: {}", c as char),
}
}
}
impl Controller for Track {
fn next(&mut self) -> MixerIn {
let width = self.seq.width();
self.chan.resize(width, Channel::new());
if self.tick_count == self.tick_rate {
self.tick_count = 0;
self.row = self.row_jump.unwrap_or(
(self.row + 1) % self.seq.len());
self.row_jump = None;
}
if self.tick_count == 0 {
for i in 0..width {
self.channel_beat(i);
}
}
for i in 0..width {
self.channel_tick(i)
}
self.tick_count += 1;
MixerIn {
tick_rate: self.bpm as u16 * self.tick_rate as u16,
pcm: self.pcm.clone(),
chan: self.chan.iter().map(|c|
ChannelIn{
note: c.note + c.add_note,
pcm_off: 0,
pcm_len: 256,
pcm_rate: 256,
vol: c.vol,
}).collect(),
}
}
}
|
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
pub fn merge_two_lists(
list1: Option<Box<ListNode>>,
_list2: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
// while let (Some(one), Some(two)) = (&list1, &list2) {
// let next_one_node = Box::new(ListNode::new(one.val));
// let next_two_node = Box::new(ListNode::new(two.val));
// if two.next.is_some() {
// next_two_node.next = two.next;
// }
// }
list1
}
|
use std::fmt;
use std::rc::Rc;
use super::{ffi, PowerDevice, PowerManager};
use crate::platform::traits::BatteryIterator;
use crate::Result;
pub struct PowerIterator {
#[allow(dead_code)]
manager: Rc<PowerManager>,
inner: ffi::DeviceIterator,
}
impl Iterator for PowerIterator {
type Item = Result<PowerDevice>;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.inner.next() {
None => return None,
Some(handle) => {
match PowerDevice::try_from(handle) {
Ok(Some(device)) => return Some(Ok(device)),
Ok(None) => continue,
Err(e) => return Some(Err(e)),
};
}
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl BatteryIterator for PowerIterator {
type Manager = PowerManager;
type Device = PowerDevice;
fn new(manager: Rc<Self::Manager>) -> Result<Self> {
let inner = ffi::DeviceIterator::new()?;
Ok(Self {
manager,
inner,
})
}
}
impl fmt::Debug for PowerIterator {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (start, end) = self.size_hint();
f.debug_struct("WindowsIterator")
.field("start", &start)
.field("end", &end)
.finish()
}
}
|
use crate::interface::model::lock::StakeLock;
use crate::interface::{BlockHeight, ContractBalances, StorageUsage};
use crate::{
domain::RedeemLock,
interface::{
BatchId, BlockTimeHeight, RedeemStakeBatch, StakeBatch, StakeTokenValue,
TimestampedNearBalance, TimestampedStakeBalance,
},
};
use near_sdk::{
json_types::U128,
serde::{Deserialize, Serialize},
AccountId,
};
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(crate = "near_sdk::serde")]
pub struct ContractState {
pub block: BlockTimeHeight,
pub config_change_block_height: BlockHeight,
pub staking_pool_id: AccountId,
pub registered_accounts_count: U128,
pub total_unstaked_near: TimestampedNearBalance,
pub total_stake_supply: TimestampedStakeBalance,
/// STAKE token value snapshot that was last taken when processing a batch
pub stake_token_value: StakeTokenValue,
pub batch_id_sequence: BatchId,
pub stake_batch: Option<StakeBatch>,
pub next_stake_batch: Option<StakeBatch>,
pub redeem_stake_batch: Option<RedeemStakeBatch>,
pub next_redeem_stake_batch: Option<RedeemStakeBatch>,
pub stake_batch_lock: Option<StakeLock>,
pub redeem_stake_batch_lock: Option<RedeemLock>,
pub balances: ContractBalances,
/// total contract storage usage = [initial_storage_usage](ContractState::initial_storage_usage) + [storage_usage_growth](ContractState::storage_usage_growth)
pub initial_storage_usage: StorageUsage,
/// how much storage usage has grown since the contract was deployed
/// - contract storage should be covered by the account storage fees that are escrowed
pub storage_usage_growth: StorageUsage,
}
|
use itertools::{EitherOrBoth, Itertools};
use crate::{BitPage, BitPageVec};
// @author shailendra.sharma
use crate::bit_page::{zero_masks, BitPageWithPosition};
use crate::bit_page_vec::BitPageVecKind;
impl BitPageVec {
pub fn active_bits_count(&self) -> usize {
match self.kind {
BitPageVecKind::AllZeroes => 0,
// bit pages are zero based
BitPageVecKind::AllOnes => self.last_bit_index.0 * BitPage::MAX_BITS + (self.last_bit_index.1),
BitPageVecKind::SparseWithZeroesHole => {
// if log_enabled!(target: "bit_page_vec_log", Level::Debug) {
// debug!(target: "bit_page_vec_log", "active_bits_count(kind=SparseWithZeroesHole) #pages={}", self.size());
// }
if let Some(ref pages) = self.pages {
let last_page = self.last_bit_index.0;
let last_bit = self.last_bit_index.1;
pages
.iter()
.filter(move |value| value.page_idx <= last_page)
.map(move |value| {
if value.page_idx == last_page {
let bit_page = value.bit_page & zero_masks()[last_bit];
bit_page.count_ones() as usize
} else {
value.bit_page.count_ones() as usize
}
})
.sum::<usize>()
} else {
0
}
}
BitPageVecKind::SparseWithOnesHole => {
// if log_enabled!(target: "bit_page_vec_log", Level::Debug) {
// debug!(target: "bit_page_vec_log", "active_bits_count(kind=SparseWithOnesHole) #pages={}", self.size());
// }
if let Some(ref pages) = self.pages {
(0..self.last_bit_index.0)
.merge_join_by(pages.iter(), |page_1_idx, BitPageWithPosition { page_idx: page_2_idx, .. }| {
page_1_idx.cmp(page_2_idx)
})
.map(move |either| match either {
EitherOrBoth::Both(_, BitPageWithPosition { bit_page, .. }) => bit_page.count_ones() as usize,
EitherOrBoth::Left(_) => BitPage::MAX_BITS,
EitherOrBoth::Right(BitPageWithPosition { .. }) => 0,
})
.sum::<usize>()
+ self.last_bit_index.1
} else {
(0..self.last_bit_index.0).map(|_| BitPage::MAX_BITS).sum::<usize>() + self.last_bit_index.1
}
}
}
}
pub fn active_bits(&self) -> BitPageVecActiveBitsIterator {
match self.kind {
BitPageVecKind::AllZeroes => BitPageVecActiveBitsIterator::None,
BitPageVecKind::AllOnes => {
let iter = (0..self.last_bit_index.0)
.flat_map(|page_idx| BitPage::active_bits(BitPage::ones()).map(move |bit_idx| (page_idx, bit_idx)))
.chain(
BitPage::active_bits(BitPage::ones())
.filter(move |bit_idx| bit_idx.lt(&self.last_bit_index.1))
.map(move |bit_idx| (self.last_bit_index.0, bit_idx)),
);
BitPageVecActiveBitsIterator::Some { iter: Box::new(iter) }
}
BitPageVecKind::SparseWithZeroesHole => {
if let Some(ref pages) = self.pages {
let last_page = self.last_bit_index.0;
let last_bit = self.last_bit_index.1;
let iter = pages.iter().filter(move |value| value.page_idx <= last_page).flat_map(
move |BitPageWithPosition { page_idx, bit_page }| {
BitPage::active_bits(*bit_page)
.filter(move |bit_idx| page_idx.lt(&last_page) || bit_idx.lt(&last_bit))
.map(move |bit_idx| (*page_idx, bit_idx))
},
);
BitPageVecActiveBitsIterator::Some { iter: Box::new(iter) }
} else {
BitPageVecActiveBitsIterator::None
}
}
BitPageVecKind::SparseWithOnesHole => {
if let Some(ref pages) = self.pages {
let iter = (0..=self.last_bit_index.0)
.merge_join_by(pages.iter(), |page_1_idx, BitPageWithPosition { page_idx: page_2_idx, .. }| {
page_1_idx.cmp(page_2_idx)
})
.flat_map(move |either| match either {
EitherOrBoth::Both(_, BitPageWithPosition { page_idx, bit_page }) => {
let iter: Box<dyn Iterator<Item = (usize, usize)>> =
Box::new(BitPage::active_bits(*bit_page).map(move |bit_idx| (*page_idx, bit_idx)));
iter
}
EitherOrBoth::Left(page_idx) => {
if page_idx.eq(&self.last_bit_index.0) {
let bit_page = BitPage::ones();
let iter: Box<dyn Iterator<Item = (usize, usize)>> = Box::new(
BitPage::active_bits(bit_page)
.filter(move |bit_idx| bit_idx.lt(&self.last_bit_index.1))
.map(move |bit_idx| (page_idx, bit_idx)),
);
iter
} else {
let bit_page = BitPage::ones();
let iter: Box<dyn Iterator<Item = (usize, usize)>> =
Box::new(BitPage::active_bits(bit_page).map(move |bit_idx| (page_idx, bit_idx)));
iter
}
}
EitherOrBoth::Right(BitPageWithPosition { page_idx, .. }) => {
let bit_page = BitPage::zeroes();
let iter: Box<dyn Iterator<Item = (usize, usize)>> =
Box::new(BitPage::active_bits(bit_page).map(move |bit_idx| (*page_idx, bit_idx)));
iter
}
});
BitPageVecActiveBitsIterator::Some { iter: Box::new(iter) }
} else {
// duplicate of AllOnes case
let iter = (0..self.last_bit_index.0)
.flat_map(|page_idx| BitPage::active_bits(BitPage::ones()).map(move |bit_idx| (page_idx, bit_idx)))
.chain(
BitPage::active_bits(BitPage::ones())
.filter(move |bit_idx| bit_idx.lt(&self.last_bit_index.1))
.map(move |bit_idx| (self.last_bit_index.0, bit_idx)),
);
BitPageVecActiveBitsIterator::Some { iter: Box::new(iter) }
}
}
}
}
}
pub enum BitPageVecActiveBitsIterator<'a> {
None,
Some {
iter: Box<dyn Iterator<Item = (usize, usize)> + 'a>,
},
}
impl<'a> Iterator for BitPageVecActiveBitsIterator<'a> {
type Item = (usize, usize);
fn next(&mut self) -> Option<Self::Item> {
match self {
BitPageVecActiveBitsIterator::None => None,
BitPageVecActiveBitsIterator::Some { iter } => iter.next(),
}
}
}
#[cfg(test)]
mod tests {
use itertools::Itertools;
use crate::BitPageVec;
#[test]
fn test_bit_page_active_bits() {
let last_page = 0;
let last_bit = 1;
let mut bit_page_vec = BitPageVec::all_zeros((last_page, last_bit));
for page in 0..2 {
for bit in 0..4 {
bit_page_vec.set_bit(page, bit);
}
}
println!("Vector = {:?}", bit_page_vec);
println!("Active Bits Count = {}", bit_page_vec.active_bits_count());
println!("Active Bits = {:?}", bit_page_vec.active_bits().collect_vec());
}
}
|
use super::{random_bytes, SrpClient};
use bytes::Buf;
use dh::{mod_p::Dh, DH};
use encoding::hex;
use hmac::{Hmac, Mac};
use hyper::{Body, client::Client, Method, Request, Uri};
use num::BigUint;
use rocket::{self, get, post, routes};
use rocket::{
config::{Config, Environment, LoggingLevel},
http::Status,
State,
};
use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize};
use serde_json::json;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::sync::RwLock;
const EMAIL: &str = "outlook@gmail.com";
const PASSWORD: &str = "password_is_username";
#[derive(Debug)]
struct ServerState {
dh: Dh,
k: u32,
salt: Vec<u8>,
b: BigUint,
K: Vec<u8>,
database: HashMap<String, BigUint>,
}
impl ServerState {
pub fn new() -> ServerState {
ServerState {
dh: Dh::new(),
k: 0,
salt: vec![],
b: BigUint::default(),
K: vec![],
database: HashMap::new(),
}
}
/// initialize
pub fn init(&mut self) {
self.dh = Dh::new();
self.k = 3;
self.salt = random_bytes(32); // 32 is arbitary, can be any number
let mut hasher = Sha256::new();
hasher.input([self.salt.clone(), PASSWORD.as_bytes().to_vec()].concat());
let x = bytes_to_biguint(&hasher.result().to_vec());
self.database.insert(EMAIL.to_string(), self.dh.exp(&x));
}
/// input: A; returns (salt, B)
pub fn kex(&mut self, email: &str, A: &BigUint) -> (Vec<u8>, BigUint) {
let v = self.database.get(&email.to_string()).unwrap(); // more graceful way would be return a Result
// randomly generate ephermal key pair
let (b, B) = self.dh.key_gen();
self.b = b;
// B = k*v + g^b mod p
let B = (B + self.k * v.clone()) % &self.dh.p;
// compute u = Sha256(A || B)
let mut hasher = Sha256::new();
hasher.input([A.to_str_radix(16).as_bytes(), B.to_str_radix(16).as_bytes()].concat());
let u = bytes_to_biguint(&hasher.result().to_vec());
let S = (A * v.modpow(&u, &self.dh.p)).modpow(&self.b, &self.dh.p);
let mut hasher = Sha256::new();
hasher.input(S.to_bytes_le());
self.K = hasher.result().to_vec();
(self.salt.clone(), B)
}
/// verify Hmac upon key exchange
pub fn verify(&self, tag: &[u8]) -> bool {
let mut hmac_sha256 = Hmac::<Sha256>::new_varkey(&self.K).expect("HMAC can take varkey");
hmac_sha256.input(&self.salt);
if hmac_sha256.verify(&tag).is_ok() {
return true;
}
false
}
/// reset state
pub fn reset(&mut self) {
self.dh = Dh::new();
self.k = 0;
self.salt = vec![];
self.b = BigUint::default();
self.K = vec![];
self.database = HashMap::new();
}
}
struct ServerStateWrapper {
ss: RwLock<ServerState>,
}
#[get("/init")]
fn init(state: State<ServerStateWrapper>) {
state.inner().ss.write().unwrap().init();
}
#[derive(Serialize, Deserialize)]
struct KexInput {
email: String,
A: String, // A is BigUint.to_str_radix(16)
}
#[derive(Serialize, Deserialize, Debug)]
struct KexOutput {
salt: Vec<u8>,
B: String, // B is BigUint.to_str_radix(16)
}
#[post("/kex", format = "json", data = "<input>")]
fn kex(input: Json<KexInput>, state: State<ServerStateWrapper>) -> Json<KexOutput> {
let email = input.0.email;
let A = BigUint::parse_bytes(&input.0.A.as_bytes(), 16).unwrap();
let (salt, B) = state.inner().ss.write().unwrap().kex(&email, &A);
let B = B.to_str_radix(16);
Json(KexOutput { salt, B })
}
#[get("/verify?<tag>")]
fn verify(tag: String, state: State<ServerStateWrapper>) -> Status {
let tag = hex::hexstr_to_bytes(&tag).unwrap();
if state.inner().ss.read().unwrap().verify(&tag) {
return Status::Ok;
}
Status::InternalServerError
}
#[get("/reset")]
fn reset(state: State<ServerStateWrapper>) -> Status {
state.inner().ss.write().unwrap().reset();
Status::Ok
}
pub fn bytes_to_biguint(b: &[u8]) -> BigUint {
BigUint::from_bytes_le(&b)
}
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
async fn query_init() -> Result<()> {
let client = Client::new();
client.get(Uri::from_static("http://localhost:9000/init")).await?;
Ok(())
}
async fn query_kex(email: &str, A: &BigUint) -> Result<(Vec<u8>, BigUint)> {
let client = Client::new();
let req = Request::builder()
.method(Method::POST)
.uri("http://localhost:9000/kex")
.header("content-type", "application/json")
.body(Body::from(
json!({
"email": email,
"A": A.to_str_radix(16),
})
.to_string(),
))?;
let resp = client.request(req).await?;
// asynchronously aggregate the chunks of the body
let body = hyper::body::aggregate(resp).await?;
let server_output: KexOutput = serde_json::from_reader(body.reader())?;
Ok((
server_output.salt,
BigUint::parse_bytes(&server_output.B.as_bytes(), 16).unwrap(),
))
}
async fn query_verify(tag: &[u8]) -> Result<bool> {
let client = Client::new();
let uri = format!("http://localhost:9000/verify?tag={}", hex::bytes_to_hexstr(&tag));
let resp = client.get(uri.parse()?).await?;
if resp.status() == 200 {
return Ok(true);
}
Ok(false)
}
async fn query_reset() -> Result<bool> {
let client = Client::new();
let uri = "http://localhost:9000/reset".parse()?;
let resp = client.get(uri).await?;
if resp.status() == 200 {
Ok(true)
} else {
Ok(false)
}
}
pub async fn srp_run<T: SrpClient>(client: &mut T) -> Result<bool> {
// client query
query_init().await?; // initialize server
let (email, A) = client.init(); // initialize client
let (salt, B) = query_kex(&email, &A).await?;
let tag = client.kex(&salt, &B);
let login_success = query_verify(&tag).await?;
query_reset().await?;
if login_success {
Ok(true)
} else {
Ok(false)
}
}
pub fn launch_server() {
let server_config = Config::build(Environment::Development)
.port(9000)
.log_level(LoggingLevel::Normal)
.finalize()
.unwrap();
rocket::custom(server_config)
.mount("/", routes![init, kex, verify, reset])
.manage(ServerStateWrapper {
ss: RwLock::new(ServerState::new()),
})
.launch();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.