text stringlengths 8 4.13M |
|---|
use crate::syscalls;
use crate::ALLOCATOR;
use core::intrinsics;
use core::ptr;
// _start and rust_start are the first two procedures executed when a Tock
// application starts. _start is invoked directly by the Tock kernel; it
// performs stack setup then calls rust_start. rust_start performs data
// relocation and sets up the heap before calling the rustc-generated main.
// rust_start and _start are tightly coupled.
//
// The memory layout is controlled by the linker script.
//
// When the kernel gives control to us, we get r0-r3 values that is as follows.
//
// +--------------+ <- (r2) mem.len()
// | Grant |
// +--------------+
// | Unused |
// S +--------------+ <- (r3) app_heap_break
// R | Heap | (hardcoded to mem_start + 3072 in
// A +--------------| Processs::create which could be lesser than
// M | .bss | mem_start + stack + .data + .bss)
// +--------------|
// | .data |
// +--------------+
// | Stack |
// +--------------+ <- (r1) mem_start
//
// +--------------+
// | .text |
// F +--------------+
// L | .crt0_header |
// A +--------------+ <- (r0) app_start
// S | Protected |
// H | Region |
// +--------------+
//
// We want to organize the memory as follows.
//
// +--------------+ <- app_heap_break
// | Heap |
// +--------------| <- heap_start
// | .bss |
// +--------------|
// | .data |
// +--------------+ <- stack_start (stacktop)
// | Stack |
// | (grows down) |
// +--------------+ <- mem_start
//
// app_heap_break and mem_start are given to us by the kernel. The stack size is
// determined using pointer app_start, and is used with mem_start to compute
// stack_start (stacktop). The placement of .data and .bss are given to us by
// the linker script; the heap is located between the end of .bss and
// app_heap_break. This requires that .bss is the last (highest-address) section
// placed by the linker script.
/// Tock programs' entry point. Called by the kernel at program start. Sets up
/// the stack then calls rust_start() for the remainder of setup.
#[doc(hidden)]
#[no_mangle]
#[naked]
#[link_section = ".start"]
pub unsafe extern "C" fn _start(
app_start: usize,
mem_start: usize,
_memory_len: usize,
app_heap_break: usize,
) -> ! {
asm!("
// Because ROPI-RWPI support in LLVM/rustc is incomplete, Rust
// applications must be statically linked. An offset between the
// location the program is linked at and its actual location in flash
// would cause references in .data and .rodata to point to the wrong
// data. To mitigate this, this section checks that .text (and .start)
// are loaded at the correct location. If the application was linked and
// loaded correctly, the location of the first instruction (read using
// the Program Counter) will match the intended location of .start. We
// don't have an easy way to signal an error, so for now we just yield
// if the location is wrong.
sub r4, pc, #4 // r4 = pc
ldr r5, =.start // r5 = address of .start
cmp r4, r5
beq .Lstack_init // Jump to stack initialization if pc was correct
.Lyield_loop:
svc 0 // yield() syscall
b .Lyield_loop
.Lstack_init:
// Compute the stacktop (stack_start). The stacktop is computed as
// stack_size + mem_start plus padding to align the stack to a multiple
// of 8 bytes. The 8 byte alignment is to follow ARM AAPCS:
// http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka4127.html
ldr r4, [r0, #36] // r4 = app_start->stack_size
add r4, r4, r1 // r4 = app_start->stack_size + mem_start
add r4, #7 // r4 = app_start->stack_size + mem_start + 7
bic r4, r4, #7 // r4 = (app_start->stack_size + mem_start + 7) & ~0x7
mov sp, r4 // sp = r4
// We need to pass app_start, stacktop and app_heap_break to rust_start.
// Temporarily store them in r6, r7 and r8
mov r6, r0
mov r7, sp
// Debug support, tell the kernel the stack location
//
// memop(10, stacktop)
// r7 contains stacktop
mov r0, #10
mov r1, r7
svc 4
// Debug support, tell the kernel the heap_start location
mov r0, r6
ldr r4, [r0, #24] // r4 = app_start->bss_start
ldr r5, [r0, #28] // r5 = app_start->bss_size
add r4, r4, r5 // r4 = bss_start + bss_size
//
// memop(11, r4)
mov r0, #11
mov r1, r4
svc 4
// Store heap_start (and soon to be app_heap_break) in r8
mov r8, r4
// There is a possibility that stack + .data + .bss is greater than
// 3072. Therefore setup the initial app_heap_break to heap_start (that
// is zero initial heap) and let rust_start determine where the actual
// app_heap_break should go.
//
// Also, because app_heap_break is where the unprivileged MPU region
// ends, in case mem_start + stack + .data + .bss is greater than
// initial app_heap_break (mem_start + 3072), we will get a memory fault
// in rust_start when initializing .data and .bss. Setting
// app_heap_break to heap_start avoids that.
// memop(0, r8)
mov r0, #0
mov r1, r8
svc 4
// NOTE: If there is a hard-fault before this point, then
// process_detail_fmt in kernel/src/process.rs panics which
// will result in us losing the PC of the instruction
// generating the hard-fault. Therefore any code before
// this point is critical code
// Setup parameters needed by rust_start
// r6 (app_start), r7 (stacktop), r8 (app_heap_break)
mov r0, r6
mov r1, r7
mov r2, r8
// Call rust_start
bl rust_start"
: // No output operands
: "{r0}"(app_start), "{r1}"(mem_start), "{r3}"(app_heap_break) // Input operands
: "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r12",
"cc", "memory" // Clobbers
: "volatile" // Options
);
intrinsics::unreachable();
}
/// The header encoded at the beginning of .text by the linker script. It is
/// accessed by rust_start() using its app_start parameter.
#[repr(C)]
struct LayoutHeader {
got_sym_start: usize,
got_start: usize,
got_size: usize,
data_sym_start: usize,
data_start: usize,
data_size: usize,
bss_start: usize,
bss_size: usize,
reldata_start: usize,
stack_size: usize,
}
/// Rust setup, called by _start. Uses the extern "C" calling convention so that
/// the assembly in _start knows how to call it (the Rust ABI is not defined).
/// Sets up the data segment (including relocations) and the heap, then calls
/// into the rustc-generated main(). This cannot use mutable global variables or
/// global references to globals until it is done setting up the data segment.
#[no_mangle]
pub unsafe extern "C" fn rust_start(app_start: usize, stacktop: usize, app_heap_break: usize) -> ! {
extern "C" {
// This function is created internally by `rustc`. See
// `src/lang_items.rs` for more details.
fn main(argc: isize, argv: *const *const u8) -> isize;
}
// Copy .data into its final location in RAM (determined by the linker
// script -- should be immediately above the stack).
let layout_header: &LayoutHeader = core::mem::transmute(app_start);
let data_flash_start_addr = app_start + layout_header.data_sym_start;
intrinsics::copy_nonoverlapping(
data_flash_start_addr as *const u8,
stacktop as *mut u8,
layout_header.data_size,
);
// Zero .bss (specified by the linker script).
let bss_end = layout_header.bss_start + layout_header.bss_size; // 1 past the end of .bss
for i in layout_header.bss_start..bss_end {
core::ptr::write(i as *mut u8, 0);
}
// TODO: Wait for rustc to have working ROPI-RWPI relocation support, then
// implement dynamic relocations here. At the moment, rustc does not have
// working ROPI-RWPI support, and it is not clear what that support would
// look like at the LLVM level. Once we know what the relocation strategy
// looks like we can write the dynamic linker.
// Initialize the heap. Unlike libtock-c's newlib allocator, which can use
// `sbrk` system call to dynamically request heap memory from the kernel, we
// need to tell `linked_list_allocator` where the heap starts and ends.
//
// Heap size is set using `elf2tab` with `--heap-size` option, which is
// currently at 1024. If you change the `elf2tab` heap size, make sure to
// make the corresponding change here.
const HEAP_SIZE: usize = 1024;
// we could have also bss_end for app_heap_start
let app_heap_start = app_heap_break;
let app_heap_end = app_heap_break + HEAP_SIZE;
// tell the kernel the new app heap break
syscalls::memop(0, app_heap_end);
ALLOCATOR.lock().init(app_heap_start, HEAP_SIZE);
main(0, ptr::null());
loop {
syscalls::yieldk();
}
}
|
// Copyright (c) 2015, <daggerbot@gmail.com>
// All rights reserved.
use std::ffi::CString;
use std::mem::zeroed;
use std::ptr::{
null,
null_mut,
};
use std::sync::atomic::{
AtomicBool,
Ordering,
ATOMIC_BOOL_INIT,
};
use libc::{
c_char,
c_int,
c_uint,
c_ulong,
c_void,
};
use ::colormap::{
Color,
Colormap,
};
use ::drawable::{
Drawable,
Geometry,
};
use ::event::{
Event,
EventMask,
};
use ::gc::{
ClipOrdering,
Gcid,
GcValues,
Rectangle,
};
use ::internal::{
FieldMask,
FromNative,
ToNative,
};
use ::visual::{
Visual,
VisualInfo,
VisualTemplate,
};
use ::window::{
SetWindowAttributes,
SizeHints,
Window,
WindowAttributes,
WindowClass,
};
// resource identifier types
pub type Atom = Xid;
pub type Xid = u32;
//
// Display
//
pub struct Display {
ptr: *mut ::ffi::Display,
}
impl Display {
pub fn alloc_color (&mut self, colormap: Colormap, color: Color) -> Option<Color> {
unsafe {
let mut xcolor = color.to_native();
if ::ffi::XAllocColor(self.ptr, colormap as c_ulong, &mut xcolor) == 0 {
return None;
}
return Some(FromNative::from_native(xcolor));
}
}
pub fn black_pixel (&mut self, screen_num: i32) -> u32 {
unsafe {
if screen_num < 0 || screen_num >= self.screen_count() {
return 0;
}
return ::ffi::XBlackPixel(self.ptr, screen_num as c_int) as u32;
}
}
pub fn create_colormap (&mut self, window: Window, visual: Visual, alloc: bool) -> Colormap {
unsafe {
return ::ffi::XCreateColormap(self.ptr, window as c_ulong, visual.to_native(),
if alloc {::ffi::AllocAll} else {::ffi::AllocNone}) as Colormap;
}
}
pub fn create_gc (&mut self, drawable: Drawable, values: GcValues) -> Gcid {
unsafe {
let xgcvalues = values.to_native();
return ::ffi::XCreateGC(self.ptr, drawable as c_ulong, values.field_mask(), &xgcvalues) as Gcid;
}
}
pub fn create_simple_window (&mut self, parent: Window, x: i32, y: i32, width: i32, height: i32, border_width: i32,
border_pixel: u32, background_pixel: u32) -> Window
{
unsafe {
return ::ffi::XCreateSimpleWindow(self.ptr, parent as c_ulong, x as c_int, y as c_int, width as c_uint,
height as c_uint, border_width as c_uint, border_pixel as c_ulong, background_pixel as c_ulong) as Window;
}
}
pub fn create_window (&mut self, parent: Window, x: i32, y: i32, width: i32, height: i32, border_width: i32,
depth: Option<i32>, class: WindowClass, visual: Option<Visual>, attr: SetWindowAttributes) -> Window
{
unsafe {
let c_depth = if let Some(d) = depth {d as c_int} else {0};
let c_visual = if let Some(v) = visual {v.to_native()} else {null()};
let c_attr = attr.to_native();
return ::ffi::XCreateWindow(self.ptr, parent as c_ulong, x as c_int, y as c_int, width as c_uint,
height as c_uint, border_width as c_uint, c_depth, class.to_native(), c_visual, attr.field_mask(), &c_attr)
as Window;
}
}
pub fn default_colormap (&mut self, screen_num: i32) -> Colormap {
unsafe {
if screen_num < 0 || screen_num >= self.screen_count() {
return 0;
}
return ::ffi::XDefaultColormap(self.ptr, screen_num as c_int) as Colormap;
}
}
pub fn default_screen (&mut self) -> i32 {
unsafe {
return ::ffi::XDefaultScreen(self.ptr) as i32;
}
}
pub fn default_visual (&mut self, screen_num: i32) -> Visual {
unsafe {
if screen_num < 0 || screen_num >= self.screen_count() {
return FromNative::from_native(null());
}
return FromNative::from_native(::ffi::XDefaultVisual(self.ptr, screen_num as c_int));
}
}
pub fn destroy_window (&mut self, window: Window) {
unsafe {
return ::ffi::XDestroyWindow(self.ptr, window as c_ulong);;
}
}
pub fn draw_line (&mut self, drawable: Drawable, gc: Gcid, x0: i32, y0: i32, x1: i32, y1: i32) {
unsafe {
::ffi::XDrawLine(self.ptr, drawable as c_ulong, gc as c_ulong, x0 as c_int, y0 as c_int,
x1 as c_int, y1 as c_int);
}
}
pub fn draw_rectangle (&mut self, drawable: Drawable, gc: Gcid, x: i32, y: i32, width: i32, height: i32) {
unsafe {
::ffi::XDrawRectangle(self.ptr, drawable as c_ulong, gc as c_ulong, x as c_int, y as c_int,
width as c_uint, height as c_uint);
}
}
pub fn fetch_name (&mut self, window: Window) -> String {
unsafe {
let mut name_ptr: *mut c_char = null_mut();
if ::ffi::XFetchName(self.ptr, window as c_ulong, &mut name_ptr) == 0 {
if name_ptr != null_mut() {
::ffi::XFree(name_ptr as *mut c_void);
}
return String::new();
}
if name_ptr == null_mut() {
return String::new();
}
let name_byte_ptr = name_ptr as *const c_char as *const u8;
let name_len = ::libc::strlen(name_ptr as *const c_char) as usize;
let name_slice = ::std::slice::from_raw_buf(&name_byte_ptr, name_len);
let name_string = String::from_utf8_lossy(name_slice).into_owned();
::ffi::XFree(name_ptr as *mut c_void);
return name_string;
}
}
pub fn fill_rectangle (&mut self, drawable: Drawable, gc: Gcid, x: i32, y: i32, width: i32, height: i32) {
unsafe {
::ffi::XFillRectangle(self.ptr, drawable as c_ulong, gc as c_ulong, x as c_int, y as c_int,
width as c_uint, height as c_uint);
}
}
pub fn flush (&mut self) {
unsafe {
::ffi::XFlush(self.ptr);
}
}
pub fn free_colormap (&mut self, colormap: Colormap) {
unsafe {
::ffi::XFreeColormap(self.ptr, colormap as c_ulong);
}
}
pub fn free_gc (&mut self, gc: Gcid) {
unsafe {
::ffi::XFreeGC(self.ptr, gc as c_ulong);
}
}
pub fn get_geometry (&mut self, drawable: Drawable) -> Option<Geometry> {
unsafe {
let mut root = 0;
let mut x = 0;
let mut y = 0;
let mut width = 0;
let mut height = 0;
let mut border_width = 0;
let mut depth = 0;
if ::ffi::XGetGeometry(self.ptr, drawable as c_ulong, &mut root, &mut x, &mut y, &mut width, &mut height,
&mut border_width, &mut depth) == 0
{
return None;
}
let geometry = Geometry {
root: root as Window,
x: x as i32,
y: y as i32,
width: width as i32,
height: height as i32,
border_width: border_width as i32,
depth: depth as i32,
};
return Some(geometry);
}
}
pub fn get_visual_info (&mut self, template: VisualTemplate) -> Vec<VisualInfo> {
unsafe {
let mut info_vec = Vec::new();
let xtemplate = template.to_native();
let mut nitems = 0;
let xinfo_ptr = ::ffi::XGetVisualInfo(self.ptr, template.field_mask(), &xtemplate, &mut nitems);
if xinfo_ptr == null_mut() {
return info_vec;
}
let xinfo_const_ptr = xinfo_ptr as *const ::ffi::XVisualInfo;
let xinfo_slice = ::std::slice::from_raw_buf(&xinfo_const_ptr, nitems as usize);
for xinfo in xinfo_slice.iter() {
if let Some(info) = FromNative::from_native(*xinfo) {
info_vec.push(info);
} else {
error!("XGetVisualInfo returned invalid data");
}
}
::ffi::XFree(xinfo_ptr as *mut c_void);
return info_vec;
}
}
pub fn get_window_attributes (&mut self, window: Window) -> Option<WindowAttributes> {
unsafe {
let mut xattr: ::ffi::XWindowAttributes = zeroed();
if ::ffi::XGetWindowAttributes(self.ptr, window as c_ulong, &mut xattr) == 0 {
return None;
}
if let Some(attr) = FromNative::from_native(xattr) {
return Some(attr);
} else {
error!("XGetWindowAttributes returned invalid data");
return None;
}
}
}
pub fn intern_atom (&mut self, name: &str, only_if_exists: bool) -> Option<Atom> {
unsafe {
let name_c_str = CString::from_slice(name.as_bytes());
let atom = ::ffi::XInternAtom(self.ptr, name_c_str.as_ptr(), if only_if_exists {1} else {0});
if atom == 0 {
return None;
} else {
return Some(atom as Atom);
}
}
}
pub fn map_window (&mut self, window: Window) {
unsafe {
::ffi::XMapWindow(self.ptr, window as c_ulong);
}
}
pub fn move_window (&mut self, window: Window, x: i32, y: i32) {
unsafe {
::ffi::XMoveWindow(self.ptr, window as c_ulong, x as c_int, y as c_int);
}
}
pub fn next_event (&mut self) -> Event {
unsafe {
let mut xevent: ::ffi::XEvent = zeroed();
loop {
::ffi::XNextEvent(self.ptr, &mut xevent);
if let Some(event) = FromNative::from_native(xevent) {
return event;
}
}
}
}
pub fn open (name: &str) -> Option<Display> {
unsafe {
init();
let name_c_str = CString::from_slice(name.as_bytes());
let ptr = ::ffi::XOpenDisplay(name_c_str.as_ptr());
if ptr == null_mut() {
return None;
}
let display = Display {
ptr: ptr,
};
return Some(display);
}
}
pub fn open_default () -> Option<Display> {
unsafe {
init();
let ptr = ::ffi::XOpenDisplay(null());
if ptr == null_mut() {
return None;
}
let display = Display {
ptr: ptr,
};
return Some(display);
}
}
pub fn pending (&self) -> i32 {
unsafe {
::ffi::XPending(self.ptr) as i32
}
}
pub fn resize_window (&mut self, window: Window, width: i32, height: i32) {
unsafe {
::ffi::XResizeWindow(self.ptr, window as c_ulong, width as c_uint, height as c_uint);
}
}
pub fn root_window (&mut self, screen_num: i32) -> Window {
unsafe {
if screen_num < 0 || screen_num >= self.screen_count() {
return 0;
}
return ::ffi::XRootWindow(self.ptr, screen_num as c_int) as Window;
}
}
pub fn screen_count (&mut self) -> i32 {
unsafe {
return ::ffi::XScreenCount(self.ptr);
}
}
pub fn send_event (&mut self, propagate: bool, event_mask: EventMask, event: Event) -> bool {
unsafe {
let xevent = event.to_native();
let window = (*(&xevent as *const ::ffi::XEvent as *const ::ffi::XAnyEvent)).window;
return ::ffi::XSendEvent(self.ptr, window, if propagate {1} else {0}, event_mask.to_native(), &xevent) != 0;
}
}
pub fn set_clip_rectangles (&mut self, gc: Gcid, x_origin: i32, y_origin: i32, rects: &[Rectangle],
ordering: ClipOrdering)
{
unsafe {
let mut xrects: Vec<::ffi::XRectangle> = Vec::with_capacity(rects.len());
for rect in rects.iter() {
xrects.push(rect.to_native());
}
::ffi::XSetClipRectangles(self.ptr, gc as c_ulong, x_origin as c_int, y_origin as c_int, &xrects[0],
xrects.len() as c_int, ordering.to_native());
}
}
pub fn set_foreground (&mut self, gc: Gcid, pixel: u32) {
unsafe {
::ffi::XSetForeground(self.ptr, gc as c_ulong, pixel as c_ulong);
}
}
pub fn set_wm_normal_hints (&mut self, window: Window, hints: SizeHints) {
unsafe {
let xhints = hints.to_native();
::ffi::XSetWMNormalHints(self.ptr, window as c_ulong, &xhints);
}
}
pub fn set_wm_protocols (&mut self, window: Window, protocols: &[Atom]) {
unsafe {
let mut protocol_vec: Vec<c_ulong> = Vec::with_capacity(protocols.len());
for protocol in protocols.iter() {
protocol_vec.push(*protocol as c_ulong);
}
if ::ffi::XSetWMProtocols(self.ptr, window as c_ulong, &protocol_vec[0], protocols.len() as c_int) == 0 {
error!("XSetWMProtocols failed");
}
}
}
pub fn store_name (&mut self, window: Window, name: &str) {
unsafe {
let name_c_str = CString::from_slice(name.as_bytes());
::ffi::XStoreName(self.ptr, window as c_ulong, name_c_str.as_ptr());
}
}
pub fn unmap_window (&mut self, window: Window) {
unsafe {
::ffi::XUnmapWindow(self.ptr, window as c_ulong);
}
}
pub fn white_pixel (&mut self, screen_num: i32) -> u32 {
unsafe {
if screen_num < 0 || screen_num >= self.screen_count() {
return 0;
}
return ::ffi::XWhitePixel(self.ptr, screen_num as c_int) as u32;
}
}
}
impl Drop for Display {
fn drop (&mut self) {
unsafe {
::ffi::XCloseDisplay(self.ptr);
}
}
}
//
// initialize before connecting
//
static mut _was_init: AtomicBool = ATOMIC_BOOL_INIT;
unsafe extern "C"
fn handle_error (display: *mut ::ffi::Display, event: *const ::ffi::XErrorEvent) -> c_int {
let mut error_buf = [0u8; 64];
let error_ptr = &mut error_buf[0] as *mut u8 as *mut c_char;
::ffi::XGetErrorText(display, (*event).error_code as c_int, error_ptr, error_buf.len() as c_int);
let error_string = String::from_utf8_lossy(&error_buf[]).into_owned();
error!("Xlib: Serial {}, Error Code {} ({}), Request Code {}, Minor Code {}, Resource ID {}",
(*event).serial, (*event).error_code, error_string, (*event).request_code, (*event).minor_code,
(*event).resourceid);
return 0;
}
#[allow(unused_variables)]
unsafe extern "C"
fn handle_io_error (display: *mut ::ffi::Display) -> c_int {
panic!("Xlib: A fatal I/O error has occurred!");
}
fn init () {
unsafe {
if !_was_init.swap(false, Ordering::SeqCst) {
::ffi::XSetErrorHandler(handle_error);
::ffi::XSetIOErrorHandler(handle_io_error);
}
}
}
|
#![cfg_attr(feature = "unstable-testing", feature(plugin))]
#![cfg_attr(feature = "unstable-testing", plugin(clippy))]
extern crate gssapi_sys;
pub mod buffer;
pub mod context;
pub mod credentials;
pub mod error;
pub mod name;
pub mod oid;
pub mod oid_set;
pub use buffer::Buffer;
pub use credentials::Credentials;
pub use context::{Context, InitiateContext, AcceptContext};
pub use error::{Error, Result};
pub use name::Name;
pub use oid::OID;
pub use oid_set::OIDSet;
|
use common::race_run::NewRaceRun;
pub trait RunStore {
type Error;
type Key;
fn create_racerun(&self, new_run: &NewRaceRun) -> Result<Self::Key, Self::Error>;
fn get_racerun(&self, id: &Self::Key) -> Result<Option<NewRaceRun>, Self::Error>;
}
|
use std::f32::INFINITY;
use std::collections::{HashSet, VecDeque};
use generational_arena::Arena;
use crate::consts::EPSILON;
use crate::types::{Vec3, Mat3, Quat, ColliderHandle, EntityHandle};
use crate::collider::InternalCollider;
use crate::orientation::Orientation;
/// The internal representation of any physical object.
/// This generally has NO data hiding to keep things simple.
pub struct InternalEntity {
/// The current position and rotation.
pub orientation : Orientation,
/// The mass of this entity at the center of mass (as a point mass).
/// This is NOT the total mass.
pub own_mass : f32,
/// The (cached) total mass (including all colliders).
///
/// This should only ever be udpated by calling recalculate_mass().
total_mass : f32,
/// The (cached) of the moment-of-inertia tensor (including all colliders) BEFORE it's been rotated to be in world space.
///
/// This should only ever be udpated by calling recalculate_mass().
prepped_moment_of_inertia : Mat3,
/// The current linear velocity.
pub velocity : Vec3,
/// The current angular velocity (about the center of mass).
pub angular_velocity : Vec3,
/// All colliders that are attached/linked to this.
pub colliders : HashSet<ColliderHandle>,
/// Whether this entity is trying to go to sleep.
pub falling_asleep : bool,
/// How long (in seconds) that this entity has been falling asleep.
/// Above a certain threshold, it will completely go to sleep.
pub falling_asleep_time : f32,
/// Whether this has been put to sleep.
pub asleep : bool,
/// Other entities to wake up when this entity wakes up.
/// These are also the entities that won't wake up this entity if they're colliding with it (and vise versa).
/// This should always be empty if the entity isn't asleep.
pub neighbors : HashSet<EntityHandle>,
}
impl InternalEntity {
/// Creates a new instance.
pub fn new_from(source : Entity) -> Result<InternalEntity, ()> {
if 0.0 > source.own_mass { return Err(()); }
Ok(InternalEntity {
orientation: source.make_orientation(),
own_mass: source.own_mass,
total_mass: source.own_mass,
prepped_moment_of_inertia: Mat3::zeros(),
velocity: source.velocity,
angular_velocity: source.angular_velocity,
colliders: HashSet::new(),
falling_asleep: false,
falling_asleep_time: 0.0,
asleep: false,
neighbors: HashSet::new(),
})
}
/// Creates the public interface for this instance.
pub fn make_pub(&self) -> Entity {
Entity {
position: self.orientation.position.clone(),
rotation: self.orientation.rotation_vec(),
last_orientation: self.orientation.clone(),
own_mass: self.own_mass,
last_total_mass: self.get_total_mass(),
velocity: self.velocity.clone(),
angular_velocity: self.angular_velocity,
colliders: self.colliders.clone(),
last_prepped_moment_of_inertia: self.prepped_moment_of_inertia.clone(),
asleep: self.asleep,
}
}
/// Updates from the passed in Entity object.
pub fn update_from(&mut self, source : Entity) -> Result<bool,()> {
if 0.0 > source.own_mass { return Err(()); }
let new_rotation = Quat::from_scaled_axis(source.rotation);
let rotation_delta = (
(new_rotation.w - self.orientation.rotation.w) * (new_rotation.w - self.orientation.rotation.w) +
(new_rotation.i - self.orientation.rotation.i) * (new_rotation.i - self.orientation.rotation.i) +
(new_rotation.j - self.orientation.rotation.j) * (new_rotation.j - self.orientation.rotation.j) +
(new_rotation.k - self.orientation.rotation.k) * (new_rotation.k - self.orientation.rotation.k)
).sqrt();
#[allow(unused_parens)]
let changed = (
self.own_mass != source.own_mass ||
EPSILON < (self.orientation.position - source.position).magnitude() ||
EPSILON < rotation_delta ||
EPSILON < (self.velocity - source.velocity).magnitude() ||
EPSILON < (self.angular_velocity - source.angular_velocity).magnitude()
);
self.own_mass = source.own_mass;
self.orientation.position = source.position;
self.orientation.rotation = new_rotation;
self.velocity = source.velocity;
self.angular_velocity = source.angular_velocity;
Ok(changed)
}
/// Recalculates the (cached) mass and inertia values.
pub fn recalculate_mass(&mut self, colliders : &Arena<Box<dyn InternalCollider>>) {
// First find the center of mass.
self.total_mass = self.own_mass;
let mut center_of_mass = Vec3::zeros();
let mut total_other_mass = 0.0;
let mut found_infinite = false;
for handle in self.colliders.iter() {
let collider = colliders.get(*handle).unwrap();
let collider_mass = collider.get_mass();
if collider_mass.is_infinite() {
found_infinite = true;
break;
}
total_other_mass += collider_mass;
center_of_mass += self.orientation.position_into_world(&collider.get_local_center_of_mass()).scale(collider_mass);
}
if found_infinite { self.total_mass = INFINITY; }
if 0.0 < total_other_mass && !found_infinite {
self.total_mass += total_other_mass;
// If there are colliders with mass, then use them to decide where this entity's center-of-mass is.
//
// Note that this entity's center of mass decides where it's own_mass is distributed. And that the center of mass calculation doesn't affix that mass to any point.
// SO the own_mass practically just teleports to where ever the center of mass moves to.
center_of_mass /= total_other_mass;
let center_of_mass_movement = center_of_mass - self.orientation.position; // How much the center of mass moves in world space.
self.orientation.internal_origin_offset -= self.orientation.direction_into_local(¢er_of_mass_movement); // Keep the origin of the local space at the same position as the position of the local space moves.
self.orientation.position += center_of_mass_movement; // Then move the center-of-mass accordingly.
} else {
// If there are no colliders then move the center-of-mass to the origin of the local space.
let local_center_of_mass_movement = self.orientation.internal_origin_offset;
self.orientation.internal_origin_offset -= local_center_of_mass_movement; // Keep the origin of the local space at the same position as the position of the local space moves.
self.orientation.position += self.orientation.direction_into_world(&local_center_of_mass_movement); // Then move the center-of-mass accordingly.
}
// Then find the moment of inertia relative to the center-of-mass.
// Note that everything here is done in WORLD space not local.
self.prepped_moment_of_inertia = Mat3::zeros();
if !found_infinite {
// TODO? Do orientation.rotation and angular_velocity need to change since the center-of-mass changed?
for handle in self.colliders.iter() {
let collider = colliders.get(*handle).unwrap();
self.prepped_moment_of_inertia += self.orientation.prep_moment_of_inertia(
&collider.get_local_center_of_mass(),
collider.get_mass(),
&collider.get_moment_of_inertia_tensor(),
);
}
}
}
/// Gets the total mass of this entity and all of its colliders.
pub fn get_total_mass(&self) -> f32 {
self.total_mass
}
/// Gets the moment of inertia tensor in WORLD space.
pub fn get_moment_of_inertia(&self) -> Mat3 {
self.orientation.finalize_moment_of_inertia(&self.prepped_moment_of_inertia)
}
/// Gets the moment of inertia tensor in WORLD space.
pub fn get_inverse_moment_of_inertia(&self) -> Mat3 {
let moment = self.get_moment_of_inertia();
if let Some(inverse) = moment.try_inverse() {
inverse
} else {
if EPSILON < moment.magnitude() {
println!("WARNING! No inverse found for moment of inertia! {:?}", moment);
}
Mat3::zeros()
}
}
/// Gets the velocity at a point (that's specified in world coordinates).
pub fn get_velocity_at_world_position(&self, position : &Vec3) -> Vec3 {
self.velocity + self.angular_velocity.cross(&(position - self.orientation.position))
}
/// Gets the total energy of this object.
pub fn get_total_energy(&self) -> f32 {
if self.total_mass.is_infinite() {
if self.velocity.magnitude() < EPSILON && self.angular_velocity.magnitude() < EPSILON {
0.0
} else {
INFINITY
}
} else {
let linear_energy = (self.total_mass * self.velocity).dot(&self.velocity) / 2.0;
let angular_energy = (self.get_moment_of_inertia() * self.angular_velocity).dot(&self.angular_velocity) / 2.0;
linear_energy + angular_energy
}
}
/// Applies an impulse at a (world) position to this instance's linear and angular velocities.
pub fn apply_impulse(&mut self, position : &Vec3, impulse : &Vec3) {
self.velocity += impulse.scale(1.0 / self.get_total_mass());
self.angular_velocity += self.get_inverse_moment_of_inertia() * (position - self.orientation.position).cross(&impulse);
}
/// Wakes up this entity and any neighbors it is in contact with (recursively).
pub fn wake_up(start : EntityHandle, all_entities : &mut Arena<InternalEntity>, debug : &mut Vec<String>) {
let mut completed = HashSet::new();
let mut queue = VecDeque::new();
queue.push_back(start);
while let Some(target_handle) = queue.pop_front() {
completed.insert(target_handle);
let target_neighbors = all_entities.get_mut(target_handle).unwrap().neighbors.clone();
for neighbor_handle in target_neighbors {
if completed.contains(&neighbor_handle) { continue; }
let neighbor = all_entities.get_mut(neighbor_handle).unwrap();
if neighbor.total_mass.is_infinite() {
// Remove self from neighbor's neighbor set.
// Must do this as infinite-mass neighbors can't be woken up when collided with.
// But having something in the "neighbor" set means it won't be checked for collision (which is bad as the target just woke up and may need to hit/bounce off of the infinite-mass entity).
neighbor.neighbors.remove(&target_handle);
println!("Removed {:?} from neighbor set of {:?}.", target_handle, neighbor_handle);
debug.push(format!("Removed {:?} from neighbor set of {:?}.", target_handle, neighbor_handle));
// Also don't bother trying to wake it up.
continue;
}
queue.push_back(neighbor_handle);
}
{ // Then wake up the target.
let target = all_entities.get_mut(target_handle).unwrap();
if target.asleep {
println!("Waking up {:?}.", target_handle);
debug.push(format!("Waking up {:?}.", target_handle));
}
target.asleep = false;
target.neighbors.clear();
}
}
}
}
/// A copy of all of the publicly-accessible properties of a physical object in the world.
#[derive(Debug, Clone)]
pub struct Entity {
/// The current position of the center of mass in WORLD space.
///
/// Defaults to origin.
pub position : Vec3,
/// The current rotation about the center of mass in WORLD space.
///
/// Defaults to no rotation (zero vector).
pub rotation : Vec3,
/// The current velocity of the center of mass in WORLD space.
///
/// Defaults to no movement (zero vector).
pub velocity : Vec3,
/// The current angular velocity about the center of mass in WORLD space.
///
/// Defaults to no rotation (zero vector).
pub angular_velocity : Vec3,
/// All colliders that are attached/linked to this.
///
/// Defaults to an empty set.
colliders : HashSet<ColliderHandle>,
/// The current mass that just this entity contributes as a point-mass at the center of mass.
///
/// This does NOT include collider masses.
///
/// Note that this mass does NOT affect how the center of mass is decided. That's strictly a weighted sum with the colliders.
///
/// Defaults to zero.
pub own_mass : f32,
/// The last known orientation. This is very much read-only.
///
/// Defaults to having no offset or transform.
last_orientation : Orientation,
/// Last known total mass (including colliders). This is very much read-only.
///
/// Defaults to zero.
last_total_mass : f32,
/// Last known moment of inertia in world space (but BEFORE it was rotated according to 'rotation'). This is very much read-only.
///
/// Defaults to a zero matrix.
last_prepped_moment_of_inertia : Mat3,
/// Whether the entity has been put to sleep.
///
/// When asleep, the entity won't receive physics updates until it (or something it's in contact with) is hit.
///
/// Defaults to `false`.
asleep : bool,
}
impl Entity {
/// Creates a new store for entity information with everything set to its defaults.
/// Can use this to store info for an [crate::physics_system::PhysicsSystem::add_entity] call later.
pub fn new() -> Entity {
Entity {
position: Vec3::zeros(),
rotation: Vec3::zeros(),
velocity: Vec3::zeros(),
angular_velocity: Vec3::zeros(),
colliders: HashSet::new(),
own_mass: 0.0,
last_orientation: Orientation::new(
&Vec3::zeros(),
&Vec3::zeros(),
&Vec3::zeros(),
),
last_total_mass: 0.0,
last_prepped_moment_of_inertia: Mat3::zeros(),
asleep: false,
}
}
/// Gets all collider handles.
///
/// Notibly this is just the getter, as this object cannot be used to modify what colliders are attached to this entity (must use [crate::PhysicsSystem::link_collider] for that).
pub fn get_colliders(&self) -> HashSet<ColliderHandle> {
self.colliders.clone()
}
/// Gets the last known total mass of this entity.
pub fn get_last_total_mass(&self) -> f32 { self.last_total_mass }
/// Gets the last orientation used by the entity.
///
/// This makes it easy to convert from local coordinates to global ones.
pub fn get_last_orientation<'a>(&'a self) -> &'a Orientation {
&self.last_orientation
}
/// Creates a new orientation using the current values of position and rotation along with the center of mass offset from the last orientation.
pub fn make_orientation(&self) -> Orientation {
Orientation::new(
&self.position,
&self.rotation,
&self.last_orientation.internal_origin_offset,
)
}
/// Gets the moment of inertia in WORLD space.
/// This uses the last known good moment of inertia, but inverted and passed through the **current** orientation of this Entity instance.
///
/// So this responds to changes in `self.position` and `self.rotation` but NOT changes to the mass distribution.
pub fn get_last_moment_of_inertia(&self) -> Mat3 {
self.make_orientation().finalize_moment_of_inertia(&self.last_prepped_moment_of_inertia)
}
/// Gets the total energy of this object.
pub fn get_total_energy(&self) -> f32 {
let linear_energy = (self.last_total_mass * self.velocity).dot(&self.velocity) / 2.0;
let angular_energy = (self.get_last_moment_of_inertia() * self.angular_velocity).dot(&self.angular_velocity) / 2.0;
linear_energy + angular_energy
}
/// Checks whether the entity was asleep.
pub fn was_asleep(&self) -> bool {
self.asleep
}
}
|
#[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::VCFG {
#[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 `IOCLKEN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum IOCLKENR {
#[doc = "Disable FIFO read. value."]
DIS,
#[doc = "Enable FIFO read. value."]
EN,
}
impl IOCLKENR {
#[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 {
IOCLKENR::DIS => false,
IOCLKENR::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> IOCLKENR {
match value {
false => IOCLKENR::DIS,
true => IOCLKENR::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == IOCLKENR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == IOCLKENR::EN
}
}
#[doc = "Possible values of the field `RSTB`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RSTBR {
#[doc = "Reset the core. value."]
RESET,
#[doc = "Enable the core. value."]
NORM,
}
impl RSTBR {
#[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 {
RSTBR::RESET => false,
RSTBR::NORM => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> RSTBR {
match value {
false => RSTBR::RESET,
true => RSTBR::NORM,
}
}
#[doc = "Checks if the value of the field is `RESET`"]
#[inline]
pub fn is_reset(&self) -> bool {
*self == RSTBR::RESET
}
#[doc = "Checks if the value of the field is `NORM`"]
#[inline]
pub fn is_norm(&self) -> bool {
*self == RSTBR::NORM
}
}
#[doc = "Possible values of the field `PDMCLKSEL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PDMCLKSELR {
#[doc = "Static value. value."]
DISABLE,
#[doc = "PDM clock is 12 MHz. value."]
_12MHZ,
#[doc = "PDM clock is 6 MHz. value."]
_6MHZ,
#[doc = "PDM clock is 3 MHz. value."]
_3MHZ,
#[doc = "PDM clock is 1.5 MHz. value."]
_1_5MHZ,
#[doc = "PDM clock is 750 KHz. value."]
_750KHZ,
#[doc = "PDM clock is 375 KHz. value."]
_375KHZ,
#[doc = "PDM clock is 187.5 KHz. value."]
_187KHZ,
}
impl PDMCLKSELR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
PDMCLKSELR::DISABLE => 0,
PDMCLKSELR::_12MHZ => 1,
PDMCLKSELR::_6MHZ => 2,
PDMCLKSELR::_3MHZ => 3,
PDMCLKSELR::_1_5MHZ => 4,
PDMCLKSELR::_750KHZ => 5,
PDMCLKSELR::_375KHZ => 6,
PDMCLKSELR::_187KHZ => 7,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> PDMCLKSELR {
match value {
0 => PDMCLKSELR::DISABLE,
1 => PDMCLKSELR::_12MHZ,
2 => PDMCLKSELR::_6MHZ,
3 => PDMCLKSELR::_3MHZ,
4 => PDMCLKSELR::_1_5MHZ,
5 => PDMCLKSELR::_750KHZ,
6 => PDMCLKSELR::_375KHZ,
7 => PDMCLKSELR::_187KHZ,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DISABLE`"]
#[inline]
pub fn is_disable(&self) -> bool {
*self == PDMCLKSELR::DISABLE
}
#[doc = "Checks if the value of the field is `_12MHZ`"]
#[inline]
pub fn is_12mhz(&self) -> bool {
*self == PDMCLKSELR::_12MHZ
}
#[doc = "Checks if the value of the field is `_6MHZ`"]
#[inline]
pub fn is_6mhz(&self) -> bool {
*self == PDMCLKSELR::_6MHZ
}
#[doc = "Checks if the value of the field is `_3MHZ`"]
#[inline]
pub fn is_3mhz(&self) -> bool {
*self == PDMCLKSELR::_3MHZ
}
#[doc = "Checks if the value of the field is `_1_5MHZ`"]
#[inline]
pub fn is_1_5mhz(&self) -> bool {
*self == PDMCLKSELR::_1_5MHZ
}
#[doc = "Checks if the value of the field is `_750KHZ`"]
#[inline]
pub fn is_750khz(&self) -> bool {
*self == PDMCLKSELR::_750KHZ
}
#[doc = "Checks if the value of the field is `_375KHZ`"]
#[inline]
pub fn is_375khz(&self) -> bool {
*self == PDMCLKSELR::_375KHZ
}
#[doc = "Checks if the value of the field is `_187KHZ`"]
#[inline]
pub fn is_187khz(&self) -> bool {
*self == PDMCLKSELR::_187KHZ
}
}
#[doc = "Possible values of the field `PDMCLKEN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PDMCLKENR {
#[doc = "Disable serial clock. value."]
DIS,
#[doc = "Enable serial clock. value."]
EN,
}
impl PDMCLKENR {
#[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 {
PDMCLKENR::DIS => false,
PDMCLKENR::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> PDMCLKENR {
match value {
false => PDMCLKENR::DIS,
true => PDMCLKENR::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == PDMCLKENR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == PDMCLKENR::EN
}
}
#[doc = "Possible values of the field `I2SEN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum I2SENR {
#[doc = "Disable I2S interface. value."]
DIS,
#[doc = "Enable I2S interface. value."]
EN,
}
impl I2SENR {
#[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 {
I2SENR::DIS => false,
I2SENR::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> I2SENR {
match value {
false => I2SENR::DIS,
true => I2SENR::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == I2SENR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == I2SENR::EN
}
}
#[doc = "Possible values of the field `BCLKINV`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BCLKINVR {
#[doc = "BCLK inverted. value."]
INV,
#[doc = "BCLK not inverted. value."]
NORM,
}
impl BCLKINVR {
#[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 {
BCLKINVR::INV => false,
BCLKINVR::NORM => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> BCLKINVR {
match value {
false => BCLKINVR::INV,
true => BCLKINVR::NORM,
}
}
#[doc = "Checks if the value of the field is `INV`"]
#[inline]
pub fn is_inv(&self) -> bool {
*self == BCLKINVR::INV
}
#[doc = "Checks if the value of the field is `NORM`"]
#[inline]
pub fn is_norm(&self) -> bool {
*self == BCLKINVR::NORM
}
}
#[doc = "Possible values of the field `DMICKDEL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DMICKDELR {
#[doc = "No delay. value."]
_0CYC,
#[doc = "1 cycle delay. value."]
_1CYC,
}
impl DMICKDELR {
#[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 {
DMICKDELR::_0CYC => false,
DMICKDELR::_1CYC => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> DMICKDELR {
match value {
false => DMICKDELR::_0CYC,
true => DMICKDELR::_1CYC,
}
}
#[doc = "Checks if the value of the field is `_0CYC`"]
#[inline]
pub fn is_0cyc(&self) -> bool {
*self == DMICKDELR::_0CYC
}
#[doc = "Checks if the value of the field is `_1CYC`"]
#[inline]
pub fn is_1cyc(&self) -> bool {
*self == DMICKDELR::_1CYC
}
}
#[doc = "Possible values of the field `SELAP`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SELAPR {
#[doc = "Clock source from I2S BCLK. value."]
I2S,
#[doc = "Clock source from internal clock generator. value."]
INTERNAL,
}
impl SELAPR {
#[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 {
SELAPR::I2S => true,
SELAPR::INTERNAL => false,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> SELAPR {
match value {
true => SELAPR::I2S,
false => SELAPR::INTERNAL,
}
}
#[doc = "Checks if the value of the field is `I2S`"]
#[inline]
pub fn is_i2s(&self) -> bool {
*self == SELAPR::I2S
}
#[doc = "Checks if the value of the field is `INTERNAL`"]
#[inline]
pub fn is_internal(&self) -> bool {
*self == SELAPR::INTERNAL
}
}
#[doc = "Possible values of the field `PCMPACK`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PCMPACKR {
#[doc = "Disable PCM packing. value."]
DIS,
#[doc = "Enable PCM packing. value."]
EN,
}
impl PCMPACKR {
#[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 {
PCMPACKR::DIS => false,
PCMPACKR::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> PCMPACKR {
match value {
false => PCMPACKR::DIS,
true => PCMPACKR::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == PCMPACKR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == PCMPACKR::EN
}
}
#[doc = "Possible values of the field `CHSET`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CHSETR {
#[doc = "Channel disabled. value."]
DIS,
#[doc = "Mono left channel. value."]
LEFT,
#[doc = "Mono right channel. value."]
RIGHT,
#[doc = "Stereo channels. value."]
STEREO,
}
impl CHSETR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
CHSETR::DIS => 0,
CHSETR::LEFT => 1,
CHSETR::RIGHT => 2,
CHSETR::STEREO => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> CHSETR {
match value {
0 => CHSETR::DIS,
1 => CHSETR::LEFT,
2 => CHSETR::RIGHT,
3 => CHSETR::STEREO,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == CHSETR::DIS
}
#[doc = "Checks if the value of the field is `LEFT`"]
#[inline]
pub fn is_left(&self) -> bool {
*self == CHSETR::LEFT
}
#[doc = "Checks if the value of the field is `RIGHT`"]
#[inline]
pub fn is_right(&self) -> bool {
*self == CHSETR::RIGHT
}
#[doc = "Checks if the value of the field is `STEREO`"]
#[inline]
pub fn is_stereo(&self) -> bool {
*self == CHSETR::STEREO
}
}
#[doc = "Values that can be written to the field `IOCLKEN`"]
pub enum IOCLKENW {
#[doc = "Disable FIFO read. value."]
DIS,
#[doc = "Enable FIFO read. value."]
EN,
}
impl IOCLKENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
IOCLKENW::DIS => false,
IOCLKENW::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _IOCLKENW<'a> {
w: &'a mut W,
}
impl<'a> _IOCLKENW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: IOCLKENW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable FIFO read. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(IOCLKENW::DIS)
}
#[doc = "Enable FIFO read. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(IOCLKENW::EN)
}
#[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 = 31;
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 `RSTB`"]
pub enum RSTBW {
#[doc = "Reset the core. value."]
RESET,
#[doc = "Enable the core. value."]
NORM,
}
impl RSTBW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
RSTBW::RESET => false,
RSTBW::NORM => true,
}
}
}
#[doc = r" Proxy"]
pub struct _RSTBW<'a> {
w: &'a mut W,
}
impl<'a> _RSTBW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: RSTBW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Reset the core. value."]
#[inline]
pub fn reset(self) -> &'a mut W {
self.variant(RSTBW::RESET)
}
#[doc = "Enable the core. value."]
#[inline]
pub fn norm(self) -> &'a mut W {
self.variant(RSTBW::NORM)
}
#[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 = 30;
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 `PDMCLKSEL`"]
pub enum PDMCLKSELW {
#[doc = "Static value. value."]
DISABLE,
#[doc = "PDM clock is 12 MHz. value."]
_12MHZ,
#[doc = "PDM clock is 6 MHz. value."]
_6MHZ,
#[doc = "PDM clock is 3 MHz. value."]
_3MHZ,
#[doc = "PDM clock is 1.5 MHz. value."]
_1_5MHZ,
#[doc = "PDM clock is 750 KHz. value."]
_750KHZ,
#[doc = "PDM clock is 375 KHz. value."]
_375KHZ,
#[doc = "PDM clock is 187.5 KHz. value."]
_187KHZ,
}
impl PDMCLKSELW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
PDMCLKSELW::DISABLE => 0,
PDMCLKSELW::_12MHZ => 1,
PDMCLKSELW::_6MHZ => 2,
PDMCLKSELW::_3MHZ => 3,
PDMCLKSELW::_1_5MHZ => 4,
PDMCLKSELW::_750KHZ => 5,
PDMCLKSELW::_375KHZ => 6,
PDMCLKSELW::_187KHZ => 7,
}
}
}
#[doc = r" Proxy"]
pub struct _PDMCLKSELW<'a> {
w: &'a mut W,
}
impl<'a> _PDMCLKSELW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: PDMCLKSELW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Static value. value."]
#[inline]
pub fn disable(self) -> &'a mut W {
self.variant(PDMCLKSELW::DISABLE)
}
#[doc = "PDM clock is 12 MHz. value."]
#[inline]
pub fn _12mhz(self) -> &'a mut W {
self.variant(PDMCLKSELW::_12MHZ)
}
#[doc = "PDM clock is 6 MHz. value."]
#[inline]
pub fn _6mhz(self) -> &'a mut W {
self.variant(PDMCLKSELW::_6MHZ)
}
#[doc = "PDM clock is 3 MHz. value."]
#[inline]
pub fn _3mhz(self) -> &'a mut W {
self.variant(PDMCLKSELW::_3MHZ)
}
#[doc = "PDM clock is 1.5 MHz. value."]
#[inline]
pub fn _1_5mhz(self) -> &'a mut W {
self.variant(PDMCLKSELW::_1_5MHZ)
}
#[doc = "PDM clock is 750 KHz. value."]
#[inline]
pub fn _750khz(self) -> &'a mut W {
self.variant(PDMCLKSELW::_750KHZ)
}
#[doc = "PDM clock is 375 KHz. value."]
#[inline]
pub fn _375khz(self) -> &'a mut W {
self.variant(PDMCLKSELW::_375KHZ)
}
#[doc = "PDM clock is 187.5 KHz. value."]
#[inline]
pub fn _187khz(self) -> &'a mut W {
self.variant(PDMCLKSELW::_187KHZ)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 7;
const OFFSET: u8 = 27;
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 `PDMCLKEN`"]
pub enum PDMCLKENW {
#[doc = "Disable serial clock. value."]
DIS,
#[doc = "Enable serial clock. value."]
EN,
}
impl PDMCLKENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
PDMCLKENW::DIS => false,
PDMCLKENW::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _PDMCLKENW<'a> {
w: &'a mut W,
}
impl<'a> _PDMCLKENW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: PDMCLKENW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable serial clock. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(PDMCLKENW::DIS)
}
#[doc = "Enable serial clock. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(PDMCLKENW::EN)
}
#[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 = 26;
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 `I2SEN`"]
pub enum I2SENW {
#[doc = "Disable I2S interface. value."]
DIS,
#[doc = "Enable I2S interface. value."]
EN,
}
impl I2SENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
I2SENW::DIS => false,
I2SENW::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _I2SENW<'a> {
w: &'a mut W,
}
impl<'a> _I2SENW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: I2SENW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable I2S interface. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(I2SENW::DIS)
}
#[doc = "Enable I2S interface. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(I2SENW::EN)
}
#[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 = 20;
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 `BCLKINV`"]
pub enum BCLKINVW {
#[doc = "BCLK inverted. value."]
INV,
#[doc = "BCLK not inverted. value."]
NORM,
}
impl BCLKINVW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
BCLKINVW::INV => false,
BCLKINVW::NORM => true,
}
}
}
#[doc = r" Proxy"]
pub struct _BCLKINVW<'a> {
w: &'a mut W,
}
impl<'a> _BCLKINVW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: BCLKINVW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "BCLK inverted. value."]
#[inline]
pub fn inv(self) -> &'a mut W {
self.variant(BCLKINVW::INV)
}
#[doc = "BCLK not inverted. value."]
#[inline]
pub fn norm(self) -> &'a mut W {
self.variant(BCLKINVW::NORM)
}
#[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 = 19;
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 `DMICKDEL`"]
pub enum DMICKDELW {
#[doc = "No delay. value."]
_0CYC,
#[doc = "1 cycle delay. value."]
_1CYC,
}
impl DMICKDELW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
DMICKDELW::_0CYC => false,
DMICKDELW::_1CYC => true,
}
}
}
#[doc = r" Proxy"]
pub struct _DMICKDELW<'a> {
w: &'a mut W,
}
impl<'a> _DMICKDELW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: DMICKDELW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "No delay. value."]
#[inline]
pub fn _0cyc(self) -> &'a mut W {
self.variant(DMICKDELW::_0CYC)
}
#[doc = "1 cycle delay. value."]
#[inline]
pub fn _1cyc(self) -> &'a mut W {
self.variant(DMICKDELW::_1CYC)
}
#[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 = 17;
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 `SELAP`"]
pub enum SELAPW {
#[doc = "Clock source from I2S BCLK. value."]
I2S,
#[doc = "Clock source from internal clock generator. value."]
INTERNAL,
}
impl SELAPW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
SELAPW::I2S => true,
SELAPW::INTERNAL => false,
}
}
}
#[doc = r" Proxy"]
pub struct _SELAPW<'a> {
w: &'a mut W,
}
impl<'a> _SELAPW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: SELAPW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Clock source from I2S BCLK. value."]
#[inline]
pub fn i2s(self) -> &'a mut W {
self.variant(SELAPW::I2S)
}
#[doc = "Clock source from internal clock generator. value."]
#[inline]
pub fn internal(self) -> &'a mut W {
self.variant(SELAPW::INTERNAL)
}
#[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 = 16;
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 `PCMPACK`"]
pub enum PCMPACKW {
#[doc = "Disable PCM packing. value."]
DIS,
#[doc = "Enable PCM packing. value."]
EN,
}
impl PCMPACKW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
PCMPACKW::DIS => false,
PCMPACKW::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _PCMPACKW<'a> {
w: &'a mut W,
}
impl<'a> _PCMPACKW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: PCMPACKW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable PCM packing. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(PCMPACKW::DIS)
}
#[doc = "Enable PCM packing. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(PCMPACKW::EN)
}
#[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 = 8;
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 `CHSET`"]
pub enum CHSETW {
#[doc = "Channel disabled. value."]
DIS,
#[doc = "Mono left channel. value."]
LEFT,
#[doc = "Mono right channel. value."]
RIGHT,
#[doc = "Stereo channels. value."]
STEREO,
}
impl CHSETW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
CHSETW::DIS => 0,
CHSETW::LEFT => 1,
CHSETW::RIGHT => 2,
CHSETW::STEREO => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _CHSETW<'a> {
w: &'a mut W,
}
impl<'a> _CHSETW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: CHSETW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Channel disabled. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(CHSETW::DIS)
}
#[doc = "Mono left channel. value."]
#[inline]
pub fn left(self) -> &'a mut W {
self.variant(CHSETW::LEFT)
}
#[doc = "Mono right channel. value."]
#[inline]
pub fn right(self) -> &'a mut W {
self.variant(CHSETW::RIGHT)
}
#[doc = "Stereo channels. value."]
#[inline]
pub fn stereo(self) -> &'a mut W {
self.variant(CHSETW::STEREO)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 3;
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 31 - Enable the IO clock."]
#[inline]
pub fn ioclken(&self) -> IOCLKENR {
IOCLKENR::_from({
const MASK: bool = true;
const OFFSET: u8 = 31;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 30 - Reset the IP core."]
#[inline]
pub fn rstb(&self) -> RSTBR {
RSTBR::_from({
const MASK: bool = true;
const OFFSET: u8 = 30;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 27:29 - Select the PDM input clock."]
#[inline]
pub fn pdmclksel(&self) -> PDMCLKSELR {
PDMCLKSELR::_from({
const MASK: u8 = 7;
const OFFSET: u8 = 27;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 26 - Enable the serial clock."]
#[inline]
pub fn pdmclken(&self) -> PDMCLKENR {
PDMCLKENR::_from({
const MASK: bool = true;
const OFFSET: u8 = 26;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 20 - I2S interface enable."]
#[inline]
pub fn i2sen(&self) -> I2SENR {
I2SENR::_from({
const MASK: bool = true;
const OFFSET: u8 = 20;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 19 - I2S BCLK input inversion."]
#[inline]
pub fn bclkinv(&self) -> BCLKINVR {
BCLKINVR::_from({
const MASK: bool = true;
const OFFSET: u8 = 19;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 17 - PDM clock sampling delay."]
#[inline]
pub fn dmickdel(&self) -> DMICKDELR {
DMICKDELR::_from({
const MASK: bool = true;
const OFFSET: u8 = 17;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 16 - Select PDM input clock source."]
#[inline]
pub fn selap(&self) -> SELAPR {
SELAPR::_from({
const MASK: bool = true;
const OFFSET: u8 = 16;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 8 - PCM data packing enable."]
#[inline]
pub fn pcmpack(&self) -> PCMPACKR {
PCMPACKR::_from({
const MASK: bool = true;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 3:4 - Set PCM channels."]
#[inline]
pub fn chset(&self) -> CHSETR {
CHSETR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 8 }
}
#[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 31 - Enable the IO clock."]
#[inline]
pub fn ioclken(&mut self) -> _IOCLKENW {
_IOCLKENW { w: self }
}
#[doc = "Bit 30 - Reset the IP core."]
#[inline]
pub fn rstb(&mut self) -> _RSTBW {
_RSTBW { w: self }
}
#[doc = "Bits 27:29 - Select the PDM input clock."]
#[inline]
pub fn pdmclksel(&mut self) -> _PDMCLKSELW {
_PDMCLKSELW { w: self }
}
#[doc = "Bit 26 - Enable the serial clock."]
#[inline]
pub fn pdmclken(&mut self) -> _PDMCLKENW {
_PDMCLKENW { w: self }
}
#[doc = "Bit 20 - I2S interface enable."]
#[inline]
pub fn i2sen(&mut self) -> _I2SENW {
_I2SENW { w: self }
}
#[doc = "Bit 19 - I2S BCLK input inversion."]
#[inline]
pub fn bclkinv(&mut self) -> _BCLKINVW {
_BCLKINVW { w: self }
}
#[doc = "Bit 17 - PDM clock sampling delay."]
#[inline]
pub fn dmickdel(&mut self) -> _DMICKDELW {
_DMICKDELW { w: self }
}
#[doc = "Bit 16 - Select PDM input clock source."]
#[inline]
pub fn selap(&mut self) -> _SELAPW {
_SELAPW { w: self }
}
#[doc = "Bit 8 - PCM data packing enable."]
#[inline]
pub fn pcmpack(&mut self) -> _PCMPACKW {
_PCMPACKW { w: self }
}
#[doc = "Bits 3:4 - Set PCM channels."]
#[inline]
pub fn chset(&mut self) -> _CHSETW {
_CHSETW { w: self }
}
}
|
use super::{
Typeck,
Load,
Unload,
ty::{
GetTy,
Inference
}
};
use ty::{
Ty,
};
use mutable::Mutability;
use expr::{
Expr,
};
use ident::Identifier;
use std::cell::RefCell;
use ir::{
Chunk,
hir::HIRInstruction,
};
use ir_traits::{
WriteInstruction
};
use notices::{
DiagnosticSourceBuilder,
DiagnosticLevel,
};
use stmt::{
property::Property
};
impl Inference for Property{
fn infer_type(&self, typeck: &Typeck) -> Result<(),()> {
let ty_inner = self.ty.clone().into_inner();
let expr_ty = self.expr.get_ty();
if ty_inner.ident == "Unknown"{
self.ty.replace(Ty{
ident: expr_ty.ident.clone(),
pos: ty_inner.pos,
});
return Ok(());
}
if ty_inner != *expr_ty{
let ty_source = match typeck.request_source_snippet(ty_inner.pos){
Ok(source) => source,
Err(diag) => {
typeck.emit_diagnostic(&[], &[diag]);
return Err(())
}
};
let expr_source = match typeck.request_source_snippet(self.expr.pos){
Ok(source) => source,
Err(diag) => {
typeck.emit_diagnostic(&[], &[diag]);
return Err(())
}
};
let ty_diag_source = DiagnosticSourceBuilder::new(typeck.module_name.clone(), ty_inner.pos.start.0)
.level(DiagnosticLevel::Error)
.message(format!(
"Expected an assignment of type {:?}",
ty_inner.ident,
))
.source(ty_source)
.range(ty_inner.pos.col_range())
.build();
let expr_diag_source = DiagnosticSourceBuilder::new(typeck.module_name.clone(), ty_inner.pos.start.0)
.level(DiagnosticLevel::Error)
.message(format!(
"But instead found an assignment of type {:?}",
expr_ty.ident,
))
.source(expr_source)
.range(ty_inner.pos.col_range())
.build();
typeck.emit_diagnostic(&[], &[ty_diag_source, expr_diag_source]);
return Err(())
}
Ok(())
}
}
impl Load for Property{
type Output = Property;
fn load(chunk: &Chunk, typeck: &Typeck) -> Result<Option<Self::Output>, ()> {
let pos = match chunk.read_pos(){
Ok(pos) => pos,
Err(msg) => {
let diag_source = DiagnosticSourceBuilder::new(typeck.module_name.clone(), 0)
.level(DiagnosticLevel::Error)
.message(msg)
.build();
typeck.emit_diagnostic(&[], &[diag_source]);
return Err(())
}
};
let mutable = match Mutability::load(chunk, typeck){
Ok(Some(mutable)) => mutable,
Ok(None) => return Ok(None),
Err(msg) => return Err(msg)
};
let ident = match Identifier::load(chunk, typeck){
Ok(Some(ident)) => ident,
Ok(None) => return Ok(None),
Err(msg) => return Err(msg)
};
let ty = match Ty::load(chunk, typeck){
Ok(Some(ty)) => ty,
Ok(None) => return Ok(None),
Err(msg) => return Err(msg)
};
let expr_chunk = if let Ok(Some(expr_chunk)) = typeck.chunk_rx.recv(){
expr_chunk
}else{
let diag_source = DiagnosticSourceBuilder::new(typeck.module_name.clone(), 0)
.level(DiagnosticLevel::Error)
.message(format!("Failed to get HIR chunk for expression while loading property"))
.build();
typeck.emit_diagnostic(&[], &[diag_source]);
return Err(())
};
let expr = match Expr::load(&expr_chunk, typeck){
Ok(Some(expr)) => expr,
Ok(None) => return Ok(None),
Err(msg) => return Err(msg)
};
return Ok(Some(
Property{
ident,
pos,
ty: RefCell::new(ty),
expr,
mutable
}
))
}
}
impl<'a> super::Check<'a> for Property{
fn check(&self, typeck: &'a Typeck) -> Result<(),()>{
self.infer_type(typeck)?;
Ok(())
}
}
impl Unload for Property{
fn unload(&self) -> Result<Chunk, ()> {
let mut chunk = Chunk::new();
chunk.write_instruction(HIRInstruction::Property);
chunk.write_pos(self.pos);
match self.ident.unload(){
Ok(ch) => chunk.write_chunk(ch),
Err(notice) => return Err(notice)
}
match self.mutable.unload(){
Ok(ch) => chunk.write_chunk(ch),
Err(notice) => return Err(notice)
}
match self.ty.clone().into_inner().unload(){
Ok(ch) => chunk.write_chunk(ch),
Err(notice) => return Err(notice)
}
match self.expr.unload(){
Ok(ch) => chunk.write_chunk(ch),
Err(notice) => return Err(notice)
}
Ok(chunk)
}
} |
use std::convert::TryInto;
use napi::*;
use crate::sk::*;
impl Path {
#[inline(always)]
pub fn create_js_class(env: &Env) -> Result<JsFunction> {
env.define_class(
"Path2D",
path_constructor,
&vec![
// Standard Path2d methods
Property::new(&env, "addPath")?.with_method(add_path),
Property::new(&env, "closePath")?.with_method(close_path),
Property::new(&env, "moveTo")?.with_method(move_to),
Property::new(&env, "lineTo")?.with_method(line_to),
Property::new(&env, "bezierCurveTo")?.with_method(bezier_curve_to),
Property::new(&env, "quadraticCurveTo")?.with_method(quadratic_curve_to),
Property::new(&env, "arc")?.with_method(arc),
Property::new(&env, "arcTo")?.with_method(arc_to),
Property::new(&env, "ellipse")?.with_method(ellipse),
Property::new(&env, "rect")?.with_method(rect),
// extra methods in PathKit
Property::new(&env, "op")?.with_method(op),
Property::new(&env, "simplify")?.with_method(simplify),
Property::new(&env, "setFillType")?.with_method(set_fill_type),
Property::new(&env, "getFillType")?.with_method(get_fill_type),
Property::new(&env, "asWinding")?.with_method(as_winding),
Property::new(&env, "toSVGString")?.with_method(to_svg_string),
Property::new(&env, "getBounds")?.with_method(get_bounds),
Property::new(&env, "computeTightBounds")?.with_method(compute_tight_bounds),
Property::new(&env, "transform")?.with_method(transform),
Property::new(&env, "trim")?.with_method(trim),
Property::new(&env, "dash")?.with_method(dash),
Property::new(&env, "equals")?.with_method(equals),
Property::new(&env, "_stroke")?.with_method(stroke),
],
)
}
}
#[js_function(1)]
fn path_constructor(ctx: CallContext) -> Result<JsUndefined> {
let mut this = ctx.this_unchecked::<JsObject>();
let p = if ctx.length == 0 {
Path::new()
} else {
let input = ctx.get::<JsUnknown>(0)?;
match input.get_type()? {
ValueType::String => {
let path_string = unsafe { input.cast::<JsString>() }.into_utf8()?;
Path::from_svg_path(path_string.as_str()?).ok_or_else(|| {
Error::new(
Status::InvalidArg,
"Create path from provided path string failed.".to_owned(),
)
})?
}
ValueType::Object => {
let path_object = unsafe { input.cast::<JsObject>() };
let input_path = ctx.env.unwrap::<Path>(&path_object)?;
input_path.clone()
}
_ => {
return Err(Error::new(
Status::InvalidArg,
"Invalid Path2D constructor argument".to_string(),
))
}
}
};
ctx.env.wrap(&mut this, p)?;
ctx.env.get_undefined()
}
#[js_function(2)]
fn add_path(ctx: CallContext) -> Result<JsUndefined> {
let this = ctx.this_unchecked::<JsObject>();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let sub_path_obj = ctx.get::<JsObject>(0)?;
let sub_path = ctx.env.unwrap::<Path>(&sub_path_obj)?;
let transform = if ctx.length == 2 {
let transform_object = ctx.get::<JsObject>(1)?;
let a: f64 = transform_object
.get_named_property::<JsNumber>("a")?
.try_into()?;
let b: f64 = transform_object
.get_named_property::<JsNumber>("b")?
.try_into()?;
let c: f64 = transform_object
.get_named_property::<JsNumber>("c")?
.try_into()?;
let d: f64 = transform_object
.get_named_property::<JsNumber>("d")?
.try_into()?;
let e: f64 = transform_object
.get_named_property::<JsNumber>("e")?
.try_into()?;
let f: f64 = transform_object
.get_named_property::<JsNumber>("f")?
.try_into()?;
Transform::new(a as f32, b as f32, c as f32, d as f32, e as f32, f as f32)
} else {
Default::default()
};
path_2d.add_path(sub_path, transform);
ctx.env.get_undefined()
}
#[js_function]
fn close_path(ctx: CallContext) -> Result<JsUndefined> {
let this = ctx.this_unchecked::<JsObject>();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
path_2d.close();
ctx.env.get_undefined()
}
#[js_function(2)]
fn move_to(ctx: CallContext) -> Result<JsUndefined> {
let this = ctx.this_unchecked::<JsObject>();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?;
let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?;
path_2d.move_to(x as f32, y as f32);
ctx.env.get_undefined()
}
#[js_function(2)]
fn line_to(ctx: CallContext) -> Result<JsUndefined> {
let this = ctx.this_unchecked::<JsObject>();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?;
let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?;
path_2d.line_to(x as f32, y as f32);
ctx.env.get_undefined()
}
#[js_function(6)]
fn bezier_curve_to(ctx: CallContext) -> Result<JsUndefined> {
let this = ctx.this_unchecked::<JsObject>();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let cp1x: f64 = ctx.get::<JsNumber>(0)?.try_into()?;
let cp1y: f64 = ctx.get::<JsNumber>(1)?.try_into()?;
let cp2x: f64 = ctx.get::<JsNumber>(2)?.try_into()?;
let cp2y: f64 = ctx.get::<JsNumber>(3)?.try_into()?;
let x: f64 = ctx.get::<JsNumber>(4)?.try_into()?;
let y: f64 = ctx.get::<JsNumber>(5)?.try_into()?;
path_2d.cubic_to(
cp1x as f32,
cp1y as f32,
cp2x as f32,
cp2y as f32,
x as f32,
y as f32,
);
ctx.env.get_undefined()
}
#[js_function(4)]
fn quadratic_curve_to(ctx: CallContext) -> Result<JsUndefined> {
let this = ctx.this_unchecked::<JsObject>();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let cpx: f64 = ctx.get::<JsNumber>(0)?.try_into()?;
let cpy: f64 = ctx.get::<JsNumber>(1)?.try_into()?;
let x: f64 = ctx.get::<JsNumber>(2)?.try_into()?;
let y: f64 = ctx.get::<JsNumber>(3)?.try_into()?;
path_2d.quad_to(cpx as f32, cpy as f32, x as f32, y as f32);
ctx.env.get_undefined()
}
#[js_function(6)]
fn arc(ctx: CallContext) -> Result<JsUndefined> {
let this = ctx.this_unchecked::<JsObject>();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let center_x: f64 = ctx.get::<JsNumber>(0)?.try_into()?;
let center_y: f64 = ctx.get::<JsNumber>(1)?.try_into()?;
let radius: f64 = ctx.get::<JsNumber>(2)?.try_into()?;
let start_angle: f64 = ctx.get::<JsNumber>(3)?.try_into()?;
let end_angle: f64 = ctx.get::<JsNumber>(4)?.try_into()?;
let from_end = if ctx.length == 6 {
ctx.get::<JsBoolean>(5)?.get_value()?
} else {
false
};
path_2d.arc(
center_x as f32,
center_y as f32,
radius as f32,
start_angle as f32,
end_angle as f32,
from_end,
);
ctx.env.get_undefined()
}
#[js_function(5)]
fn arc_to(ctx: CallContext) -> Result<JsUndefined> {
let this = ctx.this_unchecked::<JsObject>();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let ctrl_x: f64 = ctx.get::<JsNumber>(0)?.try_into()?;
let ctrl_y: f64 = ctx.get::<JsNumber>(1)?.try_into()?;
let to_x: f64 = ctx.get::<JsNumber>(2)?.try_into()?;
let to_y: f64 = ctx.get::<JsNumber>(3)?.try_into()?;
let radius: f64 = ctx.get::<JsNumber>(4)?.try_into()?;
path_2d.arc_to_tangent(
ctrl_x as f32,
ctrl_y as f32,
to_x as f32,
to_y as f32,
radius as f32,
);
ctx.env.get_undefined()
}
#[js_function(8)]
fn ellipse(ctx: CallContext) -> Result<JsUndefined> {
let this = ctx.this_unchecked::<JsObject>();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?;
let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?;
let radius_x: f64 = ctx.get::<JsNumber>(2)?.try_into()?;
let radius_y: f64 = ctx.get::<JsNumber>(3)?.try_into()?;
let rotation: f64 = ctx.get::<JsNumber>(4)?.try_into()?;
let start_angle: f64 = ctx.get::<JsNumber>(5)?.try_into()?;
let end_angle: f64 = ctx.get::<JsNumber>(6)?.try_into()?;
let from_end = if ctx.length == 8 {
ctx.get::<JsBoolean>(7)?.get_value()?
} else {
false
};
path_2d.ellipse(
x as f32,
y as f32,
radius_x as f32,
radius_y as f32,
rotation as f32,
start_angle as f32,
end_angle as f32,
from_end,
);
ctx.env.get_undefined()
}
#[js_function(4)]
fn rect(ctx: CallContext) -> Result<JsUndefined> {
let this = ctx.this_unchecked::<JsObject>();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?;
let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?;
let width: f64 = ctx.get::<JsNumber>(2)?.try_into()?;
let height: f64 = ctx.get::<JsNumber>(3)?.try_into()?;
path_2d.add_rect(x as f32, y as f32, width as f32, height as f32);
ctx.env.get_undefined()
}
#[js_function(2)]
fn op(ctx: CallContext) -> Result<JsObject> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let other = ctx.get::<JsObject>(0)?;
let other_path = ctx.env.unwrap::<Path>(&other)?;
let operation = ctx.get::<JsNumber>(1)?.get_int32()?;
path_2d.op(other_path, operation.into());
Ok(this)
}
#[js_function]
fn to_svg_string(ctx: CallContext) -> Result<JsString> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let sk_string = path_2d.to_svg_string();
unsafe {
ctx
.env
.create_string_from_c_char(sk_string.ptr, sk_string.length)
}
}
#[js_function]
fn simplify(ctx: CallContext) -> Result<JsObject> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
path_2d.simplify();
Ok(this)
}
#[js_function(1)]
fn set_fill_type(ctx: CallContext) -> Result<JsUndefined> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let fill_type = ctx.get::<JsNumber>(0)?.get_uint32()?;
path_2d.set_fill_type(fill_type.into());
ctx.env.get_undefined()
}
#[js_function]
fn get_fill_type(ctx: CallContext) -> Result<JsNumber> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
ctx.env.create_int32(path_2d.get_fill_type())
}
#[js_function]
fn as_winding(ctx: CallContext) -> Result<JsObject> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
path_2d.as_winding();
Ok(this)
}
#[js_function(4)]
fn stroke(ctx: CallContext) -> Result<JsObject> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let stroke_width = ctx.get::<JsNumber>(0)?;
let miter_limit = ctx.get::<JsNumber>(1)?;
let join = ctx.get::<JsNumber>(2)?;
let cap = ctx.get::<JsNumber>(3)?;
path_2d.stroke(
StrokeCap::from_raw(cap.get_int32()?)?,
StrokeJoin::from_raw(join.get_uint32()? as u8)?,
stroke_width.get_double()? as f32,
miter_limit.get_double()? as f32,
);
Ok(this)
}
#[js_function]
fn compute_tight_bounds(ctx: CallContext) -> Result<JsObject> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let ltrb = path_2d.compute_tight_bounds();
let mut arr = ctx.env.create_array_with_length(4)?;
arr.set_element(0, ctx.env.create_double(ltrb.0 as f64)?)?;
arr.set_element(1, ctx.env.create_double(ltrb.1 as f64)?)?;
arr.set_element(2, ctx.env.create_double(ltrb.2 as f64)?)?;
arr.set_element(3, ctx.env.create_double(ltrb.3 as f64)?)?;
Ok(arr)
}
#[js_function]
fn get_bounds(ctx: CallContext) -> Result<JsObject> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let ltrb = path_2d.get_bounds();
let mut arr = ctx.env.create_array_with_length(4)?;
arr.set_element(0, ctx.env.create_double(ltrb.0 as f64)?)?;
arr.set_element(1, ctx.env.create_double(ltrb.1 as f64)?)?;
arr.set_element(2, ctx.env.create_double(ltrb.2 as f64)?)?;
arr.set_element(3, ctx.env.create_double(ltrb.3 as f64)?)?;
Ok(arr)
}
#[js_function(1)]
fn transform(ctx: CallContext) -> Result<JsObject> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let transform_object = ctx.get::<JsObject>(0)?;
let a: f64 = transform_object
.get_named_property::<JsNumber>("a")?
.get_double()?;
let b: f64 = transform_object
.get_named_property::<JsNumber>("b")?
.get_double()?;
let c: f64 = transform_object
.get_named_property::<JsNumber>("c")?
.get_double()?;
let d: f64 = transform_object
.get_named_property::<JsNumber>("d")?
.get_double()?;
let e: f64 = transform_object
.get_named_property::<JsNumber>("e")?
.get_double()?;
let f: f64 = transform_object
.get_named_property::<JsNumber>("f")?
.get_double()?;
let trans = Transform::new(a as f32, b as f32, c as f32, d as f32, e as f32, f as f32);
path_2d.transform(&trans);
Ok(this)
}
#[js_function(3)]
fn trim(ctx: CallContext) -> Result<JsObject> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let start = ctx.get::<JsNumber>(0)?.get_double()?;
let end = ctx.get::<JsNumber>(1)?.get_double()?;
let is_complement = ctx
.get::<JsBoolean>(2)
.and_then(|v| v.get_value())
.unwrap_or(false);
path_2d.trim(start as f32, end as f32, is_complement);
Ok(this)
}
#[js_function(3)]
fn dash(ctx: CallContext) -> Result<JsObject> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let on = ctx.get::<JsNumber>(0)?.get_double()?;
let off = ctx.get::<JsNumber>(1)?.get_double()?;
let phase = ctx.get::<JsNumber>(1)?.get_double()?;
path_2d.dash(on as f32, off as f32, phase as f32);
Ok(this)
}
#[js_function(1)]
fn equals(ctx: CallContext) -> Result<JsBoolean> {
let this: JsObject = ctx.this_unchecked();
let path_2d = ctx.env.unwrap::<Path>(&this)?;
let other = ctx.get::<JsObject>(0)?;
let is_eq = path_2d == ctx.env.unwrap::<Path>(&other)?;
ctx.env.get_boolean(is_eq)
}
|
// 12 days of xmahs
//
// loop incrementing for days
// match on days
// loop decrementing gifts
fn main() {
println!("days of xmas!");
// increment loop for days
let mut days = 1;
while days < 13 {
println!("on day {} of xmas, somebody gave to me...", days);
// decrement loop for gifts
let mut gift_counter = days;
while gift_counter >= 0 {
println!("{}", gifts(&gift_counter));
gift_counter -= 1;
}
days += 1;
}
}
fn gifts(x: &i32) -> &str {
// static because str value is unknown at runtime/can change?
// https://doc.rust-lang.org/rust-by-example/scope/lifetime/static_lifetime.html
// compiler, yo
let gift = match x {
12 => "12 drummers drumming,",
11 => "11 pipers piping,",
10 => "10 lords a-leaping,",
9 => "9 ladies dancing,",
8 => "8 maids a-milking,",
7 => "7 swans a-swimming,",
6 => "6 geese a-laying,",
5 => "FIVE! GOLDEN! RINGS!",
4 => "4 calling birds,",
3 => "3 french hens,",
2 => "2 turtle doves, and",
1 => "a partridge in a pear tree",
_ => "",
};
return gift;
}
|
//! Replaces parts of the game's streaming system to allow the loading of replacement files inside IMGs,
//! and also manages the loaded replacements.
// fixme: The `stream` module is messy, poorly documented and full of hacky code.
// fixme: Opcode 0x04ee seems to break when animations have been swapped.
use std::{
collections::HashMap,
io::{Read, Seek, SeekFrom},
path::Path,
sync::Mutex,
};
use byteorder::{LittleEndian, ReadBytesExt};
use libc::c_char;
use crate::{call_original, hook, targets};
fn zero_memory(ptr: *mut u8, bytes: usize) {
for i in 0..bytes {
unsafe {
ptr.add(i).write(0);
}
}
}
fn streaming_queue() -> &'static mut Queue {
unsafe {
hook::slide::<*mut Queue>(0x100939120)
.as_mut()
.expect("how tf how did we manage to slide and get zero?")
}
}
fn streams_array() -> *mut Stream {
hook::get_global(0x100939118)
}
fn stream_init(stream_count: i32) {
// Zero the image handles.
zero_memory(hook::slide(0x100939140), 0x100);
// Zero the image names.
zero_memory(hook::slide(0x1006ac0e0), 2048);
// Write the stream count to the global count variable.
unsafe {
hook::slide::<*mut i32>(0x100939110).write(stream_count);
}
let streams = {
let streams_double_ptr: *mut *mut Stream = hook::slide(0x100939118);
unsafe {
// Allocate the stream array. Each stream structure is 48 (0x30) bytes.
let byte_count = stream_count as usize * 0x30;
let allocated = libc::malloc(byte_count).cast();
zero_memory(allocated, byte_count);
streams_double_ptr.write(allocated.cast());
*streams_double_ptr
}
};
let stream_struct_size = std::mem::size_of::<Stream>();
if stream_struct_size != 0x30 {
panic!(
"Incorrect size for Stream structure: expected 0x30, got {:#?}.",
stream_struct_size
);
}
for i in 0..stream_count as usize {
let stream: &mut Stream = unsafe { &mut *streams.add(i) };
// eq: OS_SemaphoreCreate()
stream.semaphore = hook::slide::<fn() -> *mut u8>(0x1004e8b18)();
// eq: OS_MutexCreate(...)
stream.mutex = hook::slide::<fn(usize) -> *mut u8>(0x1004e8a5c)(0x0);
if stream.semaphore.is_null() {
panic!("Stream {} semaphore is null!", i);
}
if stream.mutex.is_null() {
panic!("Stream {} mutex is null!", i);
}
}
*streaming_queue() = Queue::with_capacity(stream_count as u32 + 1);
unsafe {
// Create the global stream semaphore.
// eq: OS_SemaphoreCreate()
let semaphore = hook::slide::<fn() -> *mut u8>(0x1004e8b18)();
if semaphore.is_null() {
panic!("Failed to create global stream semaphore!");
}
// Write to the variable.
hook::slide::<*mut *mut u8>(0x1006ac8e0).write(semaphore);
// "CdStream"
let cd_stream_name: *const u8 = hook::slide(0x10058a2eb);
let global_stream_thread: *mut *mut u8 = hook::slide(0x100939138);
// Launch the thread.
let launch =
hook::slide::<fn(fn(usize), usize, u32, *const u8, i32, u32) -> *mut u8>(0x1004e8888);
// eq: OS_ThreadLaunch(...)
let thread = launch(stream_thread, 0x0, 3, cd_stream_name, 0, 3);
if thread.is_null() {
panic!("Failed to start streaming thread!");
}
global_stream_thread.write(thread);
}
}
fn stream_thread(_: usize) {
log::trace!("Streaming thread started!");
let mut image_names: Vec<Option<String>> = std::iter::repeat(None).take(32).collect();
loop {
let stream_semaphore = hook::get_global(0x1006ac8e0);
// eq: OS_SemaphoreWait(...)
hook::slide::<fn(*mut u8)>(0x1004e8b84)(stream_semaphore);
let queue = streaming_queue();
let streams = streams_array();
// Get the first stream index from the queue and then get a reference to the stream.
let stream_index = queue.first() as isize;
let mut stream = unsafe { &mut *streams.offset(stream_index) };
// Mark the stream as in use.
stream.processing = true;
// A status of 0 means that the last read was successful.
if stream.status == 0 {
let stream_source = StreamSource::new(stream.img_index, stream.sector_offset);
let stream_index_usize = stream.img_index as usize;
// We cache image names because obtaining them is quite expensive.
let image_name = match &image_names[stream_index_usize] {
Some(name) => name,
None => {
let image_name = unsafe {
let name_ptr = hook::slide::<*mut i8>(0x1006ac0e0)
.offset(stream.img_index as isize * 64);
let path_string = std::ffi::CStr::from_ptr(name_ptr)
.to_str()
.unwrap()
.to_lowercase()
.replace('\\', "/");
// The game actually uses paths from the PC version, but we only want the file names.
Path::new(&path_string)
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string()
};
let slot = &mut image_names[stream_index_usize];
*slot = Some(image_name);
slot.as_ref().unwrap()
}
};
let read_custom = with_replacements(&mut |replacements| {
let replacements = replacements.get_mut(image_name)?;
let model_name = with_model_names(|models| models.get(&stream_source).cloned())?;
let folder_child = replacements.get_mut(&model_name)?;
// Reset the file to offset 0 so we are definitely reading from the start.
folder_child.reset();
let file = &mut folder_child.file;
let mut buffer = vec![0u8; stream.sectors_to_read as usize * 2048];
// read_exact here would cause a crash for models that don't have aligned sizes, since
// we can't read enough to fill the whole buffer.
if let Err(err) = file.read(&mut buffer) {
log::error!("Failed to read model data: {}", err);
stream.status = 0xfe;
} else {
unsafe {
// todo: Read directly into streaming buffer rather than reading and copying.
std::ptr::copy(buffer.as_ptr(), stream.buffer, buffer.len());
}
stream.status = 0;
}
Some(())
});
if read_custom.is_none() {
// Multiply the sector values by 2048 (the sector size) in order to get byte values.
let byte_offset = stream.sector_offset * 2048;
let bytes_to_read = stream.sectors_to_read * 2048;
// eq: OS_FileSetPosition(...)
hook::slide::<fn(*mut u8, u32) -> u32>(0x1004e51dc)(stream.file, byte_offset);
// eq: OS_FileRead(...)
let read_result = hook::slide::<fn(*mut u8, *mut u8, u32) -> u32>(0x1004e5300)(
stream.file,
stream.buffer,
bytes_to_read,
);
stream.status = if read_result != 0 { 0xfe } else { 0 };
}
}
// Remove the queue entry we just processed so the next iteration processes the item after.
queue.remove_first();
// eq: pthread_mutex_lock(...)
hook::slide::<fn(*mut u8)>(0x1004fbd34)(stream.mutex);
stream.sectors_to_read = 0;
if stream.locked {
// eq: OS_SemaphorePost(...)
hook::slide::<fn(*mut u8)>(0x1004e8b5c)(stream.semaphore);
}
stream.processing = false;
// eq: pthread_mutex_unlock(...)
hook::slide::<fn(*mut u8)>(0x1004fbd40)(stream.mutex);
}
}
fn stream_read(
stream_index: u32,
buffer: *mut u8,
source: StreamSource,
sector_count: u32,
) -> bool {
unsafe {
hook::slide::<*mut u32>(0x100939240).write(source.0 + sector_count);
}
let stream = unsafe { &mut *streams_array().offset(stream_index as isize) };
unsafe {
let handle_arr_base: *mut *mut u8 = hook::slide(0x100939140);
let handle_ptr: *mut u8 = *handle_arr_base.offset(source.image_index() as isize);
stream.file = handle_ptr;
}
if stream.sectors_to_read != 0 || stream.processing {
return false;
}
// Set up the stream for getting the resource we want.
stream.status = 0;
stream.sector_offset = source.sector_offset();
stream.sectors_to_read = sector_count;
stream.buffer = buffer;
stream.locked = false;
stream.img_index = source.image_index();
streaming_queue().add(stream_index as i32);
let stream_semaphore = hook::get_global(0x1006ac8e0);
// eq: OS_SemaphorePost(...)
hook::slide::<fn(*mut u8)>(0x1004e8b5c)(stream_semaphore);
true
}
fn stream_open(path: *const c_char, _: bool) -> i32 {
let handles: *mut *mut u8 = hook::slide(0x100939140);
// Find the first available place in the handles array.
let mut index = 0;
for i in 0..32isize {
unsafe {
if handles.offset(i).read().is_null() {
break;
}
}
index += 1;
}
if index == 32 {
log::error!("No available slot for image.");
return 0;
}
// eq: OS_FileOpen(...)
let file_open: fn(u64, *mut *mut u8, *const c_char, u64) = hook::slide(0x1004e4f94);
file_open(0, unsafe { handles.offset(index) }, path, 0);
unsafe {
if handles.offset(index).read().is_null() {
return 0;
}
}
let image_names: *mut i8 = hook::slide(0x1006ac0e0);
unsafe {
let dest = image_names.offset(index * 64);
libc::strcpy(dest, path.cast());
}
(index as i32) << 24
}
fn get_archive_path(path: &str) -> Option<(String, String)> {
let path = path.to_lowercase();
let absolute = std::path::Path::new(&crate::loader::find_absolute_path(&path)?).to_owned();
Some((
absolute.display().to_string(),
absolute.file_name()?.to_str()?.to_lowercase(),
))
}
fn with_model_names<T>(with: impl Fn(&mut HashMap<StreamSource, String>) -> T) -> T {
lazy_static::lazy_static! {
static ref NAMES: Mutex<HashMap<StreamSource, String>> = Mutex::new(HashMap::new());
}
let mut locked = NAMES.lock();
with(locked.as_mut().unwrap())
}
type ArchiveReplacements = HashMap<String, HashMap<String, ArchiveFileReplacement>>;
fn with_replacements<T>(with: &mut impl FnMut(&mut ArchiveReplacements) -> T) -> T {
lazy_static::lazy_static! {
static ref REPLACEMENTS: Mutex<ArchiveReplacements> = Mutex::new(HashMap::new());
}
let mut locked = REPLACEMENTS.lock();
with(locked.as_mut().unwrap())
}
// fixme: Loading archives causes a visible delay during loading.
fn load_archive_into_database(path: &str, img_id: i32) -> eyre::Result<()> {
// We use a BufReader because we do many small reads.
let mut file = std::io::BufReader::new(std::fs::File::open(path)?);
let identifier = file.read_u32::<LittleEndian>()?;
// 0x32524556 is VER2 as an unsigned integer.
if identifier != 0x32524556 {
log::error!("Archive does not have a VER2 identifier! Processing will continue anyway.");
}
let entry_count = file.read_u32::<LittleEndian>()?;
log::info!("Archive has {} entries.", entry_count);
for _ in 0..entry_count {
let offset = file.read_u32::<LittleEndian>()?;
// Ignore the two u16 size values.
file.seek(SeekFrom::Current(4))?;
let name = {
let mut name_buf = [0u8; 24];
file.read_exact(&mut name_buf)?;
let name = unsafe { std::ffi::CStr::from_ptr(name_buf.as_ptr().cast()) }
.to_str()
.unwrap();
name.to_string()
};
let source = StreamSource::new(img_id as u8, offset);
with_model_names(|models| {
models.insert(source, name.clone());
});
}
Ok(())
}
fn load_directory(path_c: *const i8, archive_id: i32) {
let path = unsafe { std::ffi::CStr::from_ptr(path_c) }
.to_str()
.unwrap();
let (path, archive_name) = get_archive_path(path).expect("Unable to resolve path name.");
log::info!("Registering contents of archive '{}'.", archive_name);
if let Err(err) = load_archive_into_database(&path, archive_id) {
log::error!("Failed to load archive: {}", err);
call_original!(targets::load_cd_directory, path_c, archive_id);
return;
} else {
log::info!("Registered archive contents successfully.");
}
call_original!(targets::load_cd_directory, path_c, archive_id);
let model_info_arr: *mut ModelInfo = hook::slide(0x1006ac8f4);
with_model_names(|model_names| {
with_replacements(&mut |replacements| {
let replacement_map = if let Some(map) = replacements.get(&archive_name) {
map
} else {
return;
};
// 26316 is the total number of models in the model array.
for i in 0..26316 {
let info = unsafe { model_info_arr.offset(i as isize).as_mut().unwrap() };
let stream_source = StreamSource::new(info.img_id, info.cd_pos);
if let Some(name) = model_names.get_mut(&stream_source) {
let name = name.to_lowercase();
if let Some(child) = replacement_map.get(&name) {
log::info!(
"{} at ({}, {}) will be replaced",
name,
info.img_id,
info.cd_pos
);
let size_segments = child.size_in_segments();
info.cd_size = size_segments;
}
}
// Increase the size of the streaming buffer to accommodate the model's data (if it isn't big enough
// already).
let streaming_buffer_size: u32 =
hook::get_global::<u32>(0x10072d320).max(info.cd_size as u32);
unsafe {
*hook::slide::<*mut u32>(0x10072d320) = streaming_buffer_size;
}
}
});
});
}
pub fn init() {
const CD_STREAM_INIT: hook::Target<fn(i32)> = hook::Target::Address(0x100177eb8);
CD_STREAM_INIT.hook_hard(stream_init);
const CD_STREAM_READ: hook::Target<fn(u32, *mut u8, StreamSource, u32) -> bool> =
hook::Target::Address(0x100178048);
CD_STREAM_READ.hook_hard(stream_read);
const CD_STREAM_OPEN: hook::Target<fn(*const c_char, bool) -> i32> =
hook::Target::Address(0x1001782b0);
CD_STREAM_OPEN.hook_hard(stream_open);
targets::load_cd_directory::install(load_directory);
}
struct ArchiveFileReplacement {
size_bytes: u32,
// We keep the file open so it can't be modified while the game is running, because that could cause
// issues with the buffer size.
file: std::fs::File,
}
impl ArchiveFileReplacement {
fn reset(&mut self) {
if let Err(err) = self.file.seek(SeekFrom::Start(0)) {
log::error!(
"Could not seek to start of archive replacement file: {}",
err
);
}
}
fn size_in_segments(&self) -> u32 {
(self.size_bytes + 2047) / 2048
}
}
pub fn load_replacement(image_name: &str, path: &impl AsRef<Path>) -> eyre::Result<()> {
with_replacements(&mut |replacements| {
let size = path.as_ref().metadata()?.len();
let replacement = ArchiveFileReplacement {
size_bytes: size as u32,
file: std::fs::File::open(&path)?,
};
let name = path
.as_ref()
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_lowercase();
if let Some(map) = replacements.get_mut(image_name) {
map.insert(name, replacement);
} else {
let mut map = HashMap::new();
map.insert(name, replacement);
replacements.insert(image_name.into(), map);
}
Ok(())
})
}
#[repr(C)]
#[derive(Debug)]
struct ModelInfo {
next_index: i16,
prev_index: i16,
next_index_on_cd: i16,
flags: u8,
img_id: u8,
cd_pos: u32,
cd_size: u32,
load_state: u8,
_pad: [u8; 3],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct StreamSource(u32);
impl StreamSource {
fn new(image_index: u8, sector_offset: u32) -> StreamSource {
StreamSource(((image_index as u32) << 24) | sector_offset)
}
fn image_index(&self) -> u8 {
// The top 8 bits encode the index of the image that the resource is from in the global
// image handle array.
(self.0 >> 24) as u8
}
fn sector_offset(&self) -> u32 {
// The bottom 24 bits encode the number of sectors the resource is from the beginning of
// the file.
self.0 & 0xffffff
}
}
#[repr(C)]
#[derive(Debug)]
struct Stream {
sector_offset: u32,
sectors_to_read: u32,
buffer: *mut u8,
// CLEO addition.
// hack: We shouldn't really need to add another field to Stream.
img_index: u8,
locked: bool,
processing: bool,
_pad: u8,
status: u32,
semaphore: *mut u8,
mutex: *mut u8,
file: *mut u8,
}
#[repr(C)]
#[derive(Debug)]
struct Queue {
data: *mut i32,
head: u32,
tail: u32,
capacity: u32,
}
impl Queue {
fn with_capacity(capacity: u32) -> Queue {
Queue {
data: unsafe { libc::malloc(capacity as usize * 4).cast() },
head: 0,
tail: 0,
capacity,
}
}
fn add(&mut self, value: i32) {
unsafe {
self.data.offset(self.tail as isize).write(value);
}
self.tail = (self.tail + 1) % self.capacity;
}
fn first(&self) -> i32 {
if self.head == self.tail {
-1
} else {
unsafe { self.data.offset(self.head as isize).read() }
}
}
fn remove_first(&mut self) {
if self.head != self.tail {
self.head = (self.head + 1) % self.capacity;
}
}
}
|
#![allow(missing_docs, dead_code)]
pub(crate) mod factory;
pub mod fixture;
|
use std::sync::Arc;
use bevy::prelude::*;
use crate::{
actions::{ActionBuilder, ActionBuilderWrapper},
scorers::{Score, ScorerBuilder},
thinker::ScorerEnt,
};
// Contains different types of Considerations and Actions
#[derive(Clone)]
pub struct Choice {
pub(crate) scorer: ScorerEnt,
pub(crate) action: ActionBuilderWrapper,
}
impl Choice {
pub fn calculate(&self, scores: &Query<&Score>) -> f32 {
scores
.get(self.scorer.0)
.expect("Where did the score go?")
.0
}
}
pub struct ChoiceBuilder {
pub when: Arc<dyn ScorerBuilder>,
pub then: Arc<dyn ActionBuilder>,
}
impl ChoiceBuilder {
pub fn new(scorer: Arc<dyn ScorerBuilder>, action: Arc<dyn ActionBuilder>) -> Self {
Self {
when: scorer,
then: action,
}
}
pub fn build(&self, cmd: &mut Commands, actor: Entity, parent: Entity) -> Choice {
let scorer_ent = self.when.attach(cmd, actor);
cmd.entity(parent).push_children(&[scorer_ent]);
Choice {
scorer: ScorerEnt(scorer_ent),
action: ActionBuilderWrapper::new(self.then.clone()),
}
}
}
|
//! This module conveniently exports common subroutines necessary for hacspecs
pub use crate::array::*;
pub use crate::bigint_integers::*;
pub use crate::buf::*;
pub use crate::machine_integers::*;
pub use crate::math_integers::*;
pub use crate::math_util::{ct_util::*, *};
pub use crate::seq::*;
pub use crate::traits::*;
pub use crate::transmute::*;
pub use crate::util::*;
pub use crate::vec_integers::*;
pub use crate::vec_integers_public::*;
pub use crate::vec_integers_secret::*;
pub(crate) use crate::vec_util::*;
pub use crate::*;
pub use abstract_integers::*;
#[cfg(feature = "use_attributes")]
pub use hacspec_attributes::*;
pub use secret_integers::*;
pub use alloc::fmt::Display;
pub use alloc::format;
pub use alloc::string::{String, ToString};
pub use alloc::vec;
pub use alloc::vec::Vec;
pub use core::num::ParseIntError;
pub use core::ops::*;
pub use core::str::FromStr;
pub use core::{cmp::min, cmp::PartialEq, fmt, fmt::Debug};
pub use num::{self, traits::sign::Signed, CheckedSub, Num, Zero};
bytes!(U16Word, 2);
bytes!(U32Word, 4);
bytes!(U64Word, 8);
bytes!(U128Word, 16);
public_bytes!(u16Word, 2);
public_bytes!(u32Word, 4);
public_bytes!(u64Word, 8);
public_bytes!(u128Word, 16);
// Re-export some std lib functions
pub use core::convert::TryFrom; // Allow down-casting of integers.
|
extern crate shared;
use shared::primes::PrimeStream;
fn main() {
let primes = PrimeStream::new().take(10001);
println!("{}", primes.last().unwrap());
}
|
use crate::ctx::ClientContext;
use anyhow::Result;
use maud::html;
use rustimate_core::poll::{Poll, PollStatus};
use rustimate_core::util::NotificationLevel;
use rustimate_core::RequestMessage;
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::RwLock;
use uuid::Uuid;
pub(crate) fn on_update_poll(ctx: &RwLock<ClientContext>, poll: Poll) -> Result<()> {
{
let mut svc = ctx.write().expect("Cannot lock ClientContext for write");
if let Some(ref mut x) = svc.session_ctx_mut() {
x.set_poll(poll);
}
}
{
let svc = ctx.read().expect("Cannot lock ClientContext for read");
if let Some(session) = svc.session_ctx() {
render_polls(&svc, session.polls())?;
}
}
Ok(())
}
pub(crate) fn render_polls(svc: &ClientContext, polls: &HashMap<Uuid, Poll>) -> Result<()> {
let mut polls: Vec<&Poll> = polls.iter().map(|x| x.1).collect();
match get_active_poll_id(svc) {
Ok(active) => match polls.iter().find(|x| x.id() == &active) {
Some(p) => poll_status_dom(svc, p.status().clone()),
None => Ok(())
},
Err(_) => Ok(())
}?;
polls.sort_by(|x, y| x.idx().partial_cmp(&y.idx()).expect("No index?"));
svc.replace_template("poll-listing", crate::templates::poll::polls(svc, polls))
}
pub(crate) fn get_active_poll_id(ctx: &ClientContext) -> Result<Uuid> {
Uuid::from_str(&ctx.get_input_value("active-poll-id")?).map_err(|_| anyhow::anyhow!("Unable to find active poll id"))
}
pub(crate) fn on_poll_detail(ctx: &ClientContext, id: Uuid) -> Result<()> {
if let Some(sc) = ctx.session_ctx() {
if let Some(p) = sc.polls().get(&id) {
ctx.replace_template("poll-detail-title", html!((p.title())))?;
ctx.set_input_value("active-poll-id", &format!("{}", id))?;
poll_status_dom(ctx, p.status().clone())?;
}
}
crate::js::show_modal("poll-detail-modal");
Ok(())
}
pub(crate) fn on_set_poll_status(ctx: &ClientContext, status: PollStatus) -> Result<()> {
ctx.send(&RequestMessage::SetPollStatus {
poll: get_active_poll_id(ctx)?,
status
})?;
Ok(())
}
pub(crate) fn on_poll_submit(ctx: &ClientContext, v: &str) -> Result<()> {
if v.is_empty() {
crate::logging::notify(&NotificationLevel::Warn, "Enter a question next time")
} else {
ctx.send(&RequestMessage::SetPollTitle {
id: Uuid::new_v4(),
title: v.into()
})
}
}
fn poll_status_dom(ctx: &ClientContext, status: PollStatus) -> Result<()> {
ctx.set_visible("poll-section-pending", status == PollStatus::Pending)?;
ctx.set_visible("poll-section-active", status == PollStatus::Active)?;
ctx.set_visible("poll-section-complete", status == PollStatus::Complete)?;
if status == PollStatus::Active {
crate::votes::render_votes(ctx)?;
}
if status == PollStatus::Complete {
crate::votes::render_results(ctx)?;
}
Ok(())
}
|
//! The page for viewing a single repository and its tags
use crate::registry::{self, RepoName};
use seed::browser::fetch;
use seed::prelude::*;
use seed::{a, attrs, button, div, error, h2, img, input, span, C};
use semver::Version;
use std::cmp::Ordering;
pub struct Model {
repo: RepoName,
tags: Vec<Tag>,
}
struct Tag {
name: String,
copied: bool,
}
#[derive(Debug)]
pub enum Msg {
FetchedTags(fetch::Result<Vec<String>>),
CopyLink(usize, String),
}
fn copy_to_clipboard(text: &str) {
seed::window().navigator().clipboard().write_text(text);
}
pub fn init(repo: RepoName, orders: &mut impl Orders<Msg>) -> Model {
{
let repo = repo.clone();
orders.perform_cmd(async move { Msg::FetchedTags(registry::get_image_tags(repo).await) });
}
Model { repo, tags: vec![] }
}
fn is_latest(a: &str, b: &str) -> Ordering {
match (a, b) {
("latest", _) => Ordering::Less,
(_, "latest") => Ordering::Greater,
_ => Ordering::Equal,
}
}
fn is_version(a: &str, b: &str) -> Ordering {
match (Version::parse(a).is_ok(), Version::parse(b).is_ok()) {
(true, true) => b.cmp(a),
(true, false) => Ordering::Less,
(false, true) => Ordering::Greater,
_ => Ordering::Equal,
}
}
pub fn update(msg: Msg, model: &mut Model, _orders: &mut impl Orders<Msg>) {
match msg {
Msg::FetchedTags(result) => match result {
Ok(mut tags) => {
tags.sort_by(|a, b| is_latest(a, b).then(is_version(a, b)).then(a.cmp(b)));
model.tags = tags
.into_iter()
.map(|name| Tag {
name,
copied: false,
})
.collect()
}
Err(e) => {
error!(e);
}
},
Msg::CopyLink(i, link) => {
copy_to_clipboard(&link);
for (j, tag) in model.tags.iter_mut().enumerate() {
tag.copied = i == j;
}
}
}
}
pub fn view(model: &Model) -> Node<Msg> {
let view_card = |(i, tag): (usize, &Tag)| {
let link: String = format!("docker.chalmers.it/{}:{}", model.repo, tag.name);
div![
C!["repo_card"],
a![C!["repo_card_header"], &tag.name],
input![
C!["repo_link"],
attrs! {
At::Value => link.clone(),
At::ReadOnly => true,
},
],
button![
C!["copy_button"],
ev(Ev::Click, move |_| Msg::CopyLink(i, link)),
if tag.copied {
span!["✔️"]
} else {
span![img![attrs! { At::Src => "/images/clipboard.svg" },],]
},
],
]
};
div![
div![
C!["list"],
h2![C!["repo-name"], &model.repo.to_string()],
model.tags.iter().enumerate().map(view_card)
] // Iter<&Tag> -> Iter<(usize, &Tag)>
]
}
|
use crate::components::Tabs;
use crate::components::Token;
use crate::root::{AppRoute, DataHandle};
use crate::{
data::{MealPlans, MealPlansItem, MealPlansItemRecipesItem},
date::next_seven_days,
services::{Error, MealPlansService, RecipeService},
};
use oikos_api::components::schemas::RecipeList;
use wasm_bindgen::prelude::*;
use yew::prelude::*;
use yew_router::{
agent::RouteRequest,
prelude::{Route, RouteAgentDispatcher},
RouterState,
};
use yew_state::SharedStateComponent;
use yewtil::NeqAssign;
pub struct RecipeListPageComponent<STATE: RouterState = ()> {
handle: DataHandle,
link: ComponentLink<Self>,
router: RouteAgentDispatcher<STATE>,
meal_plans_service: MealPlansService,
recipes_service: RecipeService,
recipe_id: Option<String>,
}
pub enum Message {
Response(Result<RecipeList, Error>),
ChangeRoute(AppRoute),
MealPlansResponse(Result<MealPlans, Error>),
PlanRecipe(String),
OpenModal(String),
}
impl<STATE: RouterState> Component for RecipeListPageComponent<STATE> {
type Message = Message;
type Properties = DataHandle;
fn create(handle: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
meal_plans_service: MealPlansService::new(),
recipes_service: RecipeService::new(),
link,
router: RouteAgentDispatcher::new(),
recipe_id: None,
handle,
}
}
fn rendered(&mut self, first_render: bool) {
if first_render {
self.meal_plans_service
.get_meal_plans(self.link.callback(Message::MealPlansResponse));
self.recipes_service
.get_recipes2(self.link.callback(Message::Response));
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Message::Response(recipes) => {
let recipes = self.recipes_service.get_all.response(recipes);
self.handle.reduce(move |state| state.recipes = recipes);
}
Message::MealPlansResponse(meal_plans) => {
let meal_plans = self.meal_plans_service.get_meal_plans.response(meal_plans);
self.handle
.reduce(move |state| state.meal_plans = meal_plans);
}
Message::ChangeRoute(route) => {
let route = Route::from(route);
self.router.send(RouteRequest::ChangeRoute(route));
}
Message::PlanRecipe(meal_date) => {
let mut meal_plans = self.handle.state().meal_plans.clone();
if let Some(meals_plans_option) = meal_plans.as_mut() {
if let Some(recipe_id) = self.recipe_id.clone() {
if let Some(meal) = meals_plans_option
.iter_mut()
.find(|meals| meals.date == meal_date)
{
meal.recipes.push(MealPlansItemRecipesItem {
done: false,
id: recipe_id,
servings: None,
})
} else {
meals_plans_option.push(MealPlansItem {
date: meal_date,
recipes: vec![MealPlansItemRecipesItem {
done: false,
id: recipe_id,
servings: None,
}],
})
}
}
}
if let Some(meal_plans) = &meal_plans {
self.meal_plans_service.update_meal_plans(
meal_plans.clone(),
self.link.callback(Message::MealPlansResponse),
);
}
self.handle.reduce(move |state| {
state.meal_plans = meal_plans;
});
close_modal();
}
Message::OpenModal(recipe_id) => {
self.recipe_id = Some(recipe_id);
open_modal();
}
}
true
}
fn change(&mut self, handle: Self::Properties) -> ShouldRender {
self.handle.neq_assign(handle)
}
fn view(&self) -> Html {
let on_add_callback = self
.link
.callback(move |_| Message::ChangeRoute(AppRoute::NewRecipe));
let recipe_list = self
.handle
.state()
.recipes
.clone()
.map(|recipe_list| {
recipe_list
.iter()
.map(|recipe| {
let recipe_id = recipe.id.clone();
let onclick = self.link.callback(move |_| {
let recipe_id = recipe_id.clone();
Message::ChangeRoute(AppRoute::Recipe(recipe_id))
});
let recipe_id = recipe.id.clone();
let on_planning_callback = self.link.callback(move |_| {
let recipe_id = recipe_id.clone();
Message::OpenModal(recipe_id)
});
html! {
<div class="card horizontal">
<div class="card-stacked">
<ul class="list">
<li class="waves-effect with-action">
<div class="valign-wrapper">
<div class="list-elem" onclick=onclick>
<div class="title" >
{ voca_rs::case::capitalize(&recipe.name, &true) }
</div>
</div>
<div onclick=on_planning_callback class="action event">
<i class="material-icons">{"event"}</i>
</div>
</div>
</li>
</ul>
</div>
</div>
}
})
.collect::<Html>()
})
.unwrap_or_else(|| html! { <></> });
let next_date = next_seven_days()
.iter()
.map(|(day_code, day_string)| {
let day_code = day_code.clone();
let callback = self.link.callback(move |_| {
let day_code = day_code.clone();
Message::PlanRecipe(day_code)
});
html! {
<li onclick=callback class="waves-effect">
<div class="valign-wrapper">{day_string}</div>
</li>
}
})
.collect::<Html>();
if self.handle.state().meal_plans.is_none() || self.handle.state().recipes.is_none() {
return html! {
<>
<Token/>
<Tabs title="Recettes"/>
<div class="loader-page">
<div class="preloader-wrapper active">
<div class="spinner-layer spinner-red-only">
<div class="circle-clipper left">
<div class="circle"></div>
</div><div class="gap-patch">
<div class="circle"></div>
</div><div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
</div>
</div>
</>
};
}
html! {
<>
<Token/>
<Tabs title="Recettes"/>
<div class="planning container">
<div class="row">
<div class="col s12 m6">
{recipe_list}
</div>
</div>
</div>
<div class="fixed-action-btn">
<a class="btn-floating btn-large red" onclick=on_add_callback>
<i class="large material-icons">{"add"}</i>
</a>
</div>
<div id="modal1" class="modal bottom-sheet">
<div class="modal-content">
<ul class="list">
{next_date}
</ul>
</div>
</div>
</>
}
}
}
pub type RecipeListPage = SharedStateComponent<RecipeListPageComponent>;
#[wasm_bindgen(inline_js = "
export function open_modal() {
var elems = document.querySelectorAll('.modal');
var instances = M.Modal.init(elems);
var instance = M.Modal.getInstance(elems[0]);
instance.open();
}")]
extern "C" {
fn open_modal();
}
#[wasm_bindgen(inline_js = "
export function close_modal() {
var elems = document.querySelectorAll('.modal');
var instances = M.Modal.init(elems);
var instance = M.Modal.getInstance(elems[0]);
instance.close();
}")]
extern "C" {
fn close_modal();
}
|
use futures::future::FutureExt;
use std::alloc::Layout;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio_util::sync::ReusableBoxFuture;
#[test]
fn test_different_futures() {
let fut = async move { 10 };
// Not zero sized!
assert_eq!(Layout::for_value(&fut).size(), 1);
let mut b = ReusableBoxFuture::new(fut);
assert_eq!(b.get_pin().now_or_never(), Some(10));
b.try_set(async move { 20 })
.unwrap_or_else(|_| panic!("incorrect size"));
assert_eq!(b.get_pin().now_or_never(), Some(20));
b.try_set(async move { 30 })
.unwrap_or_else(|_| panic!("incorrect size"));
assert_eq!(b.get_pin().now_or_never(), Some(30));
}
#[test]
fn test_different_sizes() {
let fut1 = async move { 10 };
let val = [0u32; 1000];
let fut2 = async move { val[0] };
let fut3 = ZeroSizedFuture {};
assert_eq!(Layout::for_value(&fut1).size(), 1);
assert_eq!(Layout::for_value(&fut2).size(), 4004);
assert_eq!(Layout::for_value(&fut3).size(), 0);
let mut b = ReusableBoxFuture::new(fut1);
assert_eq!(b.get_pin().now_or_never(), Some(10));
b.set(fut2);
assert_eq!(b.get_pin().now_or_never(), Some(0));
b.set(fut3);
assert_eq!(b.get_pin().now_or_never(), Some(5));
}
struct ZeroSizedFuture {}
impl Future for ZeroSizedFuture {
type Output = u32;
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<u32> {
Poll::Ready(5)
}
}
#[test]
fn test_zero_sized() {
let fut = ZeroSizedFuture {};
// Zero sized!
assert_eq!(Layout::for_value(&fut).size(), 0);
let mut b = ReusableBoxFuture::new(fut);
assert_eq!(b.get_pin().now_or_never(), Some(5));
assert_eq!(b.get_pin().now_or_never(), Some(5));
b.try_set(ZeroSizedFuture {})
.unwrap_or_else(|_| panic!("incorrect size"));
assert_eq!(b.get_pin().now_or_never(), Some(5));
assert_eq!(b.get_pin().now_or_never(), Some(5));
}
|
use crate::grammar::ast::eq::ast_eq;
use crate::grammar::ast::{eq::AstEq, Expression};
use crate::grammar::model::{HasSourceReference, WrightInput};
use crate::grammar::parsers::expression::binary_expression::primary::parse_expr;
use crate::grammar::tracing::trace_result;
use nom::IResult;
use std::mem::discriminant;
/// Binary expression parser and utilities.
pub mod binary_expression;
#[cfg(test)]
mod binary_expression_tests;
/// Unary expression parser.
pub(self) mod unary_expression;
/// Index expression parsers.
pub(self) mod index_expression;
/// Function call expression parser.
pub(self) mod func_call;
#[cfg(test)]
mod func_call_tests;
/// Conditional expression parsers.
pub(crate) mod conditional;
/// Parentheses parser.
pub(crate) mod parens;
#[cfg(test)]
mod parens_tests;
/// Block parser.
pub(crate) mod block;
// #[cfg(test)]
// mod block_tests;
#[cfg(test)]
mod expression_tests;
impl<T: Clone + std::fmt::Debug> Expression<T> {
/// The name of this parser when appearing in traces.
pub const TRACE_NAME: &'static str = "Expression";
}
impl<I: WrightInput> Expression<I> {
/// Parse an expression in source code.
pub fn parse(input: I) -> IResult<I, Self> {
trace_result(
Self::TRACE_NAME,
parse_expr(input.trace_start_clone(Self::TRACE_NAME)),
)
}
}
impl<I: std::fmt::Debug + Clone> HasSourceReference<I> for Expression<I> {
fn get_source_ref(&self) -> &I {
use Expression::*;
match self {
NumLit(i) => i.get_source_ref(),
CharLit(i) => i.get_source_ref(),
StringLit(i) => i.get_source_ref(),
BooleanLit(i) => i.get_source_ref(),
ScopedName(i) => i.get_source_ref(),
Parens(i) => i.get_source_ref(),
BinaryExpression(i) => i.get_source_ref(),
SelfLit(i) => i.get_source_ref(),
Block(i) => i.get_source_ref(),
UnaryExpression(i) => i.get_source_ref(),
Conditional(i) => i.get_source_ref(),
IndexExpression(i) => i.get_source_ref(),
FuncCall(i) => i.get_source_ref(),
}
}
}
impl<T: Clone + std::fmt::Debug + PartialEq> AstEq for Expression<T> {
fn ast_eq(fst: &Self, snd: &Self) -> bool {
use Expression::*;
// discriminant is a function from std::mem
// (https://doc.rust-lang.org/std/mem/fn.discriminant.html)
// that returns an opaque type represents which variant of an enum
// a value uses.
// this check allows us to return `unimplemented!()` at the bottom of
// the match block instead of false. This will help us to catch bugs at
// testing time.
if discriminant(fst) != discriminant(snd) {
return false;
}
match (fst, snd) {
(NumLit(a), NumLit(b)) => ast_eq(a, b),
(CharLit(a), CharLit(b)) => ast_eq(a, b),
(StringLit(a), StringLit(b)) => ast_eq(a, b),
(BooleanLit(a), BooleanLit(b)) => ast_eq(a, b),
(ScopedName(a), ScopedName(b)) => ast_eq(a, b),
(Parens(a), Parens(b)) => ast_eq(a, b),
(BinaryExpression(a), BinaryExpression(b)) => ast_eq(a, b),
(SelfLit(a), SelfLit(b)) => ast_eq(a, b),
(Block(a), Block(b)) => ast_eq(a, b),
(UnaryExpression(a), UnaryExpression(b)) => ast_eq(a, b),
(Conditional(a), Conditional(b)) => ast_eq(a, b),
(IndexExpression(a), IndexExpression(b)) => ast_eq(a, b),
(_, _) => unimplemented!(),
}
}
}
|
/**********************************************
> File Name : _TextEditor.rs
> Author : lunar
> Email : lunar_ubuntu@qq.com
> Created Time : Sun Aug 14 11:52:27 2022
> Location : Shanghai
> Copyright@ https://github.com/xiaoqixian
**********************************************/
use std::cell::{RefCell, Ref};
use std::rc::Rc;
use std::fmt::Debug;
trait NodeMove {
type Output;
fn prev(&self) -> Self::Output;
fn next(&self) -> Self::Output;
}
struct Node<T> {
prev: RefCell<Option<Rc<Node<T>>>>,
next: RefCell<Option<Rc<Node<T>>>>,
inner: T
}
struct SafeNode<T> {
inner: RefCell<Option<Rc<Node<T>>>>
}
struct LinkedList<T> {
head: SafeNode<T>,
tail: SafeNode<T>
}
struct TextEditor {
editor: LinkedList<String>,
cursor: SafeNode<String>,
offset: usize
}
impl<T> Clone for SafeNode<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone()
}
}
}
impl<T> PartialEq for SafeNode<T> {
fn eq(&self, other: &Self) -> bool {
if self.is_none() ^ other.is_none() {
return false;
}
let p1 = Rc::as_ptr(self.inner.borrow().as_ref().unwrap());
let p2 = Rc::as_ptr(other.inner.borrow().as_ref().unwrap());
return p1 == p2;
}
}
impl<T> Node<T> {
fn new(inner: T) -> Self {
Self {
prev: RefCell::new(None),
next: RefCell::new(None),
inner
}
}
fn set_prev(&self, node: Option<Rc<Node<T>>>) {
*self.prev.borrow_mut() = node;
}
fn set_next(&self, node: Option<Rc<Node<T>>>) {
*self.next.borrow_mut() = node;
}
}
impl<T> SafeNode<T> {
fn new(inner: T) -> Self {
Self {
inner: RefCell::new(Some(Rc::new(Node::new(inner))))
}
}
fn new_none() -> Self {
Self {
inner: RefCell::new(None)
}
}
fn clone_node(&self) -> Option<Rc<Node<T>>> {
self.inner.borrow().clone()
}
fn set_prev(&self, node: Option<Rc<Node<T>>>) {
self.inner.borrow().as_ref().unwrap().set_prev(node);
}
fn set_next(&self, node: Option<Rc<Node<T>>>) {
self.inner.borrow().as_ref().unwrap().set_next(node);
}
#[inline]
fn is_none(&self) -> bool {
self.inner.borrow().is_none()
}
#[inline]
fn is_some(&self) -> bool {
self.inner.borrow().is_some()
}
fn next(&self) -> Self {
Self {
inner: self.inner.borrow().as_ref().unwrap().next.clone()
}
}
fn prev(&self) -> Self {
Self {
inner: self.inner.borrow().as_ref().unwrap().prev.clone()
}
}
}
impl SafeNode<String> {
fn len(&self) -> usize {
self.inner.borrow().as_ref().unwrap().inner.len()
}
fn as_str(&self) -> &str {
self.inner.borrow().as_ref().unwrap().inner.as_str()
}
}
impl<T> LinkedList<T> {
fn new() -> Self {
Self {
head: SafeNode::new_none(),
tail: SafeNode::new_none()
}
}
#[inline]
fn is_empty(&self) -> bool {
self.head.is_none()
}
fn link_before(&self, pos: &SafeNode<T>, node: SafeNode<T>) {
let prev = pos.prev();
pos.set_prev(node.clone_node());
node.set_next(pos.clone_node());
if prev.is_some() {
prev.set_next(node.clone_node());
node.set_prev(prev.clone_node());
}
}
fn unlink_before(&mut self, pos: SafeNode<T>) {
assert!(pos.is_some());
let prev = pos.prev();
if prev.is_none() {return;}
let prev_prev = prev.prev();
if prev_prev.is_none() {
pos.set_prev(None);
self.head = pos;
} else {
prev_prev.set_next(pos.clone_node());
pos.set_prev(prev_prev.clone_node());
}
}
fn unlink_range(&mut self, begin: SafeNode<T>, end: SafeNode<T>) {
assert!(begin.is_some());
let begin_prev = begin.prev();
if begin_prev.is_none() {
end.set_prev(None);
if end.is_none() {
self.tail = end.clone();
}
self.head = end;
} else {
begin_prev.set_next(end.clone_node());
if end.is_none() {
self.tail = begin_prev;
}
}
}
#[inline]
fn push_back_node(&mut self, node: SafeNode<T>) {
if self.head.is_none() {
assert!(self.tail.is_none());
self.head = node.clone();
self.tail = node;
} else {
self.tail.set_next(node.clone_node());
node.set_prev(self.tail.clone_node());
self.tail = node;
}
}
#[inline]
fn push_front_node(&mut self, node: SafeNode<T>) {
if self.head.is_none() {
assert!(self.tail.is_none());
self.head = node.clone();
self.tail = node;
} else {
self.head.set_prev(node.clone_node());
node.set_next(self.head.clone_node());
self.head = node;
}
}
fn push_front(&mut self, element: T) {
self.push_front_node(SafeNode::new(element));
}
fn push_back(&mut self, element: T) {
self.push_back_node(SafeNode::new(element));
}
}
impl TextEditor {
fn new() -> Self {
Self {
editor: LinkedList::new(),
cursor: SafeNode::new_none(),
offset: 0
}
}
fn add_text(&mut self, text: String) {
if self.editor.is_empty() {
self.offset = text.len();
self.editor.push_back(text);
self.cursor = self.editor.head.clone();
return;
}
assert!(self.cursor.is_some());
if self.offset == self.cursor.len() {
self.offset = text.len();
if self.cursor.next().is_none() {
self.editor.push_back(text);
self.cursor = self.editor.tail.clone();
} else {
self.cursor = self.cursor.next();
self.editor.link_before(&self.cursor, SafeNode::new(text));
self.cursor = self.cursor.prev();
}
return;
}
}
}
impl<T: Debug> Debug for Node<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.inner)
}
}
impl<T: Debug> Debug for SafeNode<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", &self)
}
}
fn main() {
}
|
use crate::ctypes::{c_char, c_void, wchar_t};
use crate::shared::basetsd::{INT8, LONG_PTR, SIZE_T, UINT16, UINT32, UINT64, UINT8};
use crate::shared::dxgiformat::DXGI_FORMAT;
use crate::shared::dxgitype::DXGI_SAMPLE_DESC;
use crate::shared::guiddef::{GUID, IID, REFGUID, REFIID};
use crate::shared::minwindef::{BOOL, BYTE, DWORD, FLOAT, INT, LPCVOID, UINT};
use crate::shared::windef::RECT;
use crate::um::d3dcommon::{ID3DBlob, D3D_FEATURE_LEVEL, D3D_PRIMITIVE, D3D_PRIMITIVE_TOPOLOGY};
use crate::um::minwinbase::SECURITY_ATTRIBUTES;
use crate::um::unknwnbase::{IUnknown, IUnknownVtbl};
use crate::um::winnt::{HANDLE, HRESULT, LPCSTR, LPCWSTR, LUID};
pub const D3D12_16BIT_INDEX_STRIP_CUT_VALUE: UINT = 0xffff;
pub const D3D12_32BIT_INDEX_STRIP_CUT_VALUE: UINT = 0xffffffff;
pub const D3D12_8BIT_INDEX_STRIP_CUT_VALUE: UINT = 0xff;
pub const D3D12_APPEND_ALIGNED_ELEMENT: UINT = 0xffffffff;
pub const D3D12_ARRAY_AXIS_ADDRESS_RANGE_BIT_COUNT: UINT = 9;
pub const D3D12_CLIP_OR_CULL_DISTANCE_COUNT: UINT = 8;
pub const D3D12_CLIP_OR_CULL_DISTANCE_ELEMENT_COUNT: UINT = 2;
pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT: UINT = 14;
pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_COMPONENTS: UINT = 4;
pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_HW_SLOT_COUNT: UINT = 15;
pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT: UINT = 16;
pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COUNT: UINT = 15;
pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READS_PER_INST: UINT = 1;
pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_COMMONSHADER_FLOWCONTROL_NESTING_LIMIT: UINT = 64;
pub const D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COUNT: UINT = 1;
pub const D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READS_PER_INST: UINT = 1;
pub const D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_COMMONSHADER_IMMEDIATE_VALUE_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_COUNT: UINT = 128;
pub const D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_READS_PER_INST: UINT = 1;
pub const D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT: UINT = 128;
pub const D3D12_COMMONSHADER_SAMPLER_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_COMMONSHADER_SAMPLER_REGISTER_COUNT: UINT = 16;
pub const D3D12_COMMONSHADER_SAMPLER_REGISTER_READS_PER_INST: UINT = 1;
pub const D3D12_COMMONSHADER_SAMPLER_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_COMMONSHADER_SAMPLER_SLOT_COUNT: UINT = 16;
pub const D3D12_COMMONSHADER_SUBROUTINE_NESTING_LIMIT: UINT = 32;
pub const D3D12_COMMONSHADER_TEMP_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_COMMONSHADER_TEMP_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_COMMONSHADER_TEMP_REGISTER_COUNT: UINT = 4096;
pub const D3D12_COMMONSHADER_TEMP_REGISTER_READS_PER_INST: UINT = 3;
pub const D3D12_COMMONSHADER_TEMP_REGISTER_READ_PORTS: UINT = 3;
pub const D3D12_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MAX: INT = 10;
pub const D3D12_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MIN: INT = -10;
pub const D3D12_COMMONSHADER_TEXEL_OFFSET_MAX_NEGATIVE: INT = -8;
pub const D3D12_COMMONSHADER_TEXEL_OFFSET_MAX_POSITIVE: INT = 7;
pub const D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT: UINT = 256;
pub const D3D12_CS_4_X_BUCKET00_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 256;
pub const D3D12_CS_4_X_BUCKET00_MAX_NUM_THREADS_PER_GROUP: UINT = 64;
pub const D3D12_CS_4_X_BUCKET01_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 240;
pub const D3D12_CS_4_X_BUCKET01_MAX_NUM_THREADS_PER_GROUP: UINT = 68;
pub const D3D12_CS_4_X_BUCKET02_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 224;
pub const D3D12_CS_4_X_BUCKET02_MAX_NUM_THREADS_PER_GROUP: UINT = 72;
pub const D3D12_CS_4_X_BUCKET03_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 208;
pub const D3D12_CS_4_X_BUCKET03_MAX_NUM_THREADS_PER_GROUP: UINT = 76;
pub const D3D12_CS_4_X_BUCKET04_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 192;
pub const D3D12_CS_4_X_BUCKET04_MAX_NUM_THREADS_PER_GROUP: UINT = 84;
pub const D3D12_CS_4_X_BUCKET05_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 176;
pub const D3D12_CS_4_X_BUCKET05_MAX_NUM_THREADS_PER_GROUP: UINT = 92;
pub const D3D12_CS_4_X_BUCKET06_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 160;
pub const D3D12_CS_4_X_BUCKET06_MAX_NUM_THREADS_PER_GROUP: UINT = 100;
pub const D3D12_CS_4_X_BUCKET07_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 144;
pub const D3D12_CS_4_X_BUCKET07_MAX_NUM_THREADS_PER_GROUP: UINT = 112;
pub const D3D12_CS_4_X_BUCKET08_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 128;
pub const D3D12_CS_4_X_BUCKET08_MAX_NUM_THREADS_PER_GROUP: UINT = 128;
pub const D3D12_CS_4_X_BUCKET09_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 112;
pub const D3D12_CS_4_X_BUCKET09_MAX_NUM_THREADS_PER_GROUP: UINT = 144;
pub const D3D12_CS_4_X_BUCKET10_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 96;
pub const D3D12_CS_4_X_BUCKET10_MAX_NUM_THREADS_PER_GROUP: UINT = 168;
pub const D3D12_CS_4_X_BUCKET11_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 80;
pub const D3D12_CS_4_X_BUCKET11_MAX_NUM_THREADS_PER_GROUP: UINT = 204;
pub const D3D12_CS_4_X_BUCKET12_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 64;
pub const D3D12_CS_4_X_BUCKET12_MAX_NUM_THREADS_PER_GROUP: UINT = 256;
pub const D3D12_CS_4_X_BUCKET13_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 48;
pub const D3D12_CS_4_X_BUCKET13_MAX_NUM_THREADS_PER_GROUP: UINT = 340;
pub const D3D12_CS_4_X_BUCKET14_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 32;
pub const D3D12_CS_4_X_BUCKET14_MAX_NUM_THREADS_PER_GROUP: UINT = 512;
pub const D3D12_CS_4_X_BUCKET15_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: UINT = 16;
pub const D3D12_CS_4_X_BUCKET15_MAX_NUM_THREADS_PER_GROUP: UINT = 768;
pub const D3D12_CS_4_X_DISPATCH_MAX_THREAD_GROUPS_IN_Z_DIMENSION: UINT = 1;
pub const D3D12_CS_4_X_RAW_UAV_BYTE_ALIGNMENT: UINT = 256;
pub const D3D12_CS_4_X_THREAD_GROUP_MAX_THREADS_PER_GROUP: UINT = 768;
pub const D3D12_CS_4_X_THREAD_GROUP_MAX_X: UINT = 768;
pub const D3D12_CS_4_X_THREAD_GROUP_MAX_Y: UINT = 768;
pub const D3D12_CS_4_X_UAV_REGISTER_COUNT: UINT = 1;
pub const D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION: UINT = 65535;
pub const D3D12_CS_TGSM_REGISTER_COUNT: UINT = 8192;
pub const D3D12_CS_TGSM_REGISTER_READS_PER_INST: UINT = 1;
pub const D3D12_CS_TGSM_RESOURCE_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_CS_TGSM_RESOURCE_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_CS_THREADGROUPID_REGISTER_COMPONENTS: UINT = 3;
pub const D3D12_CS_THREADGROUPID_REGISTER_COUNT: UINT = 1;
pub const D3D12_CS_THREADIDINGROUPFLATTENED_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_CS_THREADIDINGROUPFLATTENED_REGISTER_COUNT: UINT = 1;
pub const D3D12_CS_THREADIDINGROUP_REGISTER_COMPONENTS: UINT = 3;
pub const D3D12_CS_THREADIDINGROUP_REGISTER_COUNT: UINT = 1;
pub const D3D12_CS_THREADID_REGISTER_COMPONENTS: UINT = 3;
pub const D3D12_CS_THREADID_REGISTER_COUNT: UINT = 1;
pub const D3D12_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP: UINT = 1024;
pub const D3D12_CS_THREAD_GROUP_MAX_X: UINT = 1024;
pub const D3D12_CS_THREAD_GROUP_MAX_Y: UINT = 1024;
pub const D3D12_CS_THREAD_GROUP_MAX_Z: UINT = 64;
pub const D3D12_CS_THREAD_GROUP_MIN_X: UINT = 1;
pub const D3D12_CS_THREAD_GROUP_MIN_Y: UINT = 1;
pub const D3D12_CS_THREAD_GROUP_MIN_Z: UINT = 1;
pub const D3D12_CS_THREAD_LOCAL_TEMP_REGISTER_POOL: UINT = 16384;
pub const D3D12_DEFAULT_BLEND_FACTOR_ALPHA: FLOAT = 1.0;
pub const D3D12_DEFAULT_BLEND_FACTOR_BLUE: FLOAT = 1.0;
pub const D3D12_DEFAULT_BLEND_FACTOR_GREEN: FLOAT = 1.0;
pub const D3D12_DEFAULT_BLEND_FACTOR_RED: FLOAT = 1.0;
pub const D3D12_DEFAULT_BORDER_COLOR_COMPONENT: FLOAT = 0.0;
pub const D3D12_DEFAULT_DEPTH_BIAS: UINT = 0;
pub const D3D12_DEFAULT_DEPTH_BIAS_CLAMP: FLOAT = 0.0;
pub const D3D12_DEFAULT_MAX_ANISOTROPY: UINT = 16;
pub const D3D12_DEFAULT_MIP_LOD_BIAS: FLOAT = 0.0;
pub const D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT: UINT = 4194304;
pub const D3D12_DEFAULT_RENDER_TARGET_ARRAY_INDEX: UINT = 0;
pub const D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT: UINT = 65536;
pub const D3D12_DEFAULT_SAMPLE_MASK: UINT = 0xffffffff;
pub const D3D12_DEFAULT_SCISSOR_ENDX: UINT = 0;
pub const D3D12_DEFAULT_SCISSOR_ENDY: UINT = 0;
pub const D3D12_DEFAULT_SCISSOR_STARTX: UINT = 0;
pub const D3D12_DEFAULT_SCISSOR_STARTY: UINT = 0;
pub const D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS: FLOAT = 0.0;
pub const D3D12_DEFAULT_STENCIL_READ_MASK: UINT = 0xff;
pub const D3D12_DEFAULT_STENCIL_REFERENCE: UINT = 0;
pub const D3D12_DEFAULT_STENCIL_WRITE_MASK: UINT = 0xff;
pub const D3D12_DEFAULT_VIEWPORT_AND_SCISSORRECT_INDEX: UINT = 0;
pub const D3D12_DEFAULT_VIEWPORT_HEIGHT: UINT = 0;
pub const D3D12_DEFAULT_VIEWPORT_MAX_DEPTH: FLOAT = 0.0;
pub const D3D12_DEFAULT_VIEWPORT_MIN_DEPTH: FLOAT = 0.0;
pub const D3D12_DEFAULT_VIEWPORT_TOPLEFTX: UINT = 0;
pub const D3D12_DEFAULT_VIEWPORT_TOPLEFTY: UINT = 0;
pub const D3D12_DEFAULT_VIEWPORT_WIDTH: UINT = 0;
pub const D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND: UINT = 0xffffffff;
pub const D3D12_DRIVER_RESERVED_REGISTER_SPACE_VALUES_END: UINT = 0xfffffff7;
pub const D3D12_DRIVER_RESERVED_REGISTER_SPACE_VALUES_START: UINT = 0xfffffff0;
pub const D3D12_DS_INPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS: UINT = 3968;
pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_COUNT: UINT = 32;
pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENTS: UINT = 3;
pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_COUNT: UINT = 1;
pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_COUNT: UINT = 32;
pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_COUNT: UINT = 1;
pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_DS_OUTPUT_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_DS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_DS_OUTPUT_REGISTER_COUNT: UINT = 32;
pub const D3D12_FLOAT16_FUSED_TOLERANCE_IN_ULP: FLOAT = 0.6;
pub const D3D12_FLOAT32_MAX: FLOAT = 3.402823466e+38;
pub const D3D12_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP: FLOAT = 0.6;
pub const D3D12_FLOAT_TO_SRGB_EXPONENT_DENOMINATOR: FLOAT = 2.4;
pub const D3D12_FLOAT_TO_SRGB_EXPONENT_NUMERATOR: FLOAT = 1.0;
pub const D3D12_FLOAT_TO_SRGB_OFFSET: FLOAT = 0.055;
pub const D3D12_FLOAT_TO_SRGB_SCALE_1: FLOAT = 12.92;
pub const D3D12_FLOAT_TO_SRGB_SCALE_2: FLOAT = 1.055;
pub const D3D12_FLOAT_TO_SRGB_THRESHOLD: FLOAT = 0.0031308;
pub const D3D12_FTOI_INSTRUCTION_MAX_INPUT: FLOAT = 2147483647.999;
pub const D3D12_FTOI_INSTRUCTION_MIN_INPUT: FLOAT = -2147483648.999;
pub const D3D12_FTOU_INSTRUCTION_MAX_INPUT: FLOAT = 4294967295.999;
pub const D3D12_FTOU_INSTRUCTION_MIN_INPUT: FLOAT = 0.0;
pub const D3D12_GS_INPUT_INSTANCE_ID_READS_PER_INST: UINT = 2;
pub const D3D12_GS_INPUT_INSTANCE_ID_READ_PORTS: UINT = 1;
pub const D3D12_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_GS_INPUT_INSTANCE_ID_REGISTER_COUNT: UINT = 1;
pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_COUNT: UINT = 1;
pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_GS_INPUT_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_GS_INPUT_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_GS_INPUT_REGISTER_COUNT: UINT = 32;
pub const D3D12_GS_INPUT_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_GS_INPUT_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_GS_INPUT_REGISTER_VERTICES: UINT = 32;
pub const D3D12_GS_MAX_INSTANCE_COUNT: UINT = 32;
pub const D3D12_GS_MAX_OUTPUT_VERTEX_COUNT_ACROSS_INSTANCES: UINT = 1024;
pub const D3D12_GS_OUTPUT_ELEMENTS: UINT = 32;
pub const D3D12_GS_OUTPUT_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_GS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_GS_OUTPUT_REGISTER_COUNT: UINT = 32;
pub const D3D12_HS_CONTROL_POINT_PHASE_INPUT_REGISTER_COUNT: UINT = 32;
pub const D3D12_HS_CONTROL_POINT_PHASE_OUTPUT_REGISTER_COUNT: UINT = 32;
pub const D3D12_HS_CONTROL_POINT_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_HS_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_HS_CONTROL_POINT_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_HS_CONTROL_POINT_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_HS_FORK_PHASE_INSTANCE_COUNT_UPPER_BOUND: UINT = 0xffffffff;
pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COUNT: UINT = 1;
pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COUNT: UINT = 1;
pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_COUNT: UINT = 1;
pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_HS_JOIN_PHASE_INSTANCE_COUNT_UPPER_BOUND: UINT = 0xffffffff;
pub const D3D12_HS_MAXTESSFACTOR_LOWER_BOUND: FLOAT = 1.0;
pub const D3D12_HS_MAXTESSFACTOR_UPPER_BOUND: FLOAT = 64.0;
pub const D3D12_HS_OUTPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS: UINT = 3968;
pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COUNT: UINT = 1;
pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COUNT: UINT = 32;
pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_SCALAR_COMPONENTS: UINT = 128;
pub const D3D12_IA_DEFAULT_INDEX_BUFFER_OFFSET_IN_BYTES: UINT = 0;
pub const D3D12_IA_DEFAULT_PRIMITIVE_TOPOLOGY: UINT = 0;
pub const D3D12_IA_DEFAULT_VERTEX_BUFFER_OFFSET_IN_BYTES: UINT = 0;
pub const D3D12_IA_INDEX_INPUT_RESOURCE_SLOT_COUNT: UINT = 1;
pub const D3D12_IA_INSTANCE_ID_BIT_COUNT: UINT = 32;
pub const D3D12_IA_INTEGER_ARITHMETIC_BIT_COUNT: UINT = 32;
pub const D3D12_IA_PATCH_MAX_CONTROL_POINT_COUNT: UINT = 32;
pub const D3D12_IA_PRIMITIVE_ID_BIT_COUNT: UINT = 32;
pub const D3D12_IA_VERTEX_ID_BIT_COUNT: UINT = 32;
pub const D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT: UINT = 32;
pub const D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENTS_COMPONENTS: UINT = 128;
pub const D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT: UINT = 32;
pub const D3D12_INTEGER_DIVIDE_BY_ZERO_QUOTIENT: UINT = 0xffffffff;
pub const D3D12_INTEGER_DIVIDE_BY_ZERO_REMAINDER: UINT = 0xffffffff;
pub const D3D12_KEEP_RENDER_TARGETS_AND_DEPTH_STENCIL: UINT = 0xffffffff;
pub const D3D12_KEEP_UNORDERED_ACCESS_VIEWS: UINT = 0xffffffff;
pub const D3D12_LINEAR_GAMMA: FLOAT = 1.0;
pub const D3D12_MAJOR_VERSION: UINT = 12;
pub const D3D12_MAX_BORDER_COLOR_COMPONENT: FLOAT = 1.0;
pub const D3D12_MAX_DEPTH: FLOAT = 1.0;
pub const D3D12_MAX_LIVE_STATIC_SAMPLERS: UINT = 2032;
pub const D3D12_MAX_MAXANISOTROPY: UINT = 16;
pub const D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT: UINT = 32;
pub const D3D12_MAX_POSITION_VALUE: FLOAT = 3.402823466e+34;
pub const D3D12_MAX_ROOT_COST: UINT = 64;
pub const D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_1: UINT = 1000000;
pub const D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_2: UINT = 1000000;
pub const D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE: UINT = 2048;
pub const D3D12_MAX_TEXTURE_DIMENSION_2_TO_EXP: UINT = 17;
pub const D3D12_MINOR_VERSION: UINT = 0;
pub const D3D12_MIN_BORDER_COLOR_COMPONENT: FLOAT = 0.0;
pub const D3D12_MIN_DEPTH: FLOAT = 0.0;
pub const D3D12_MIN_MAXANISOTROPY: UINT = 0;
pub const D3D12_MIP_LOD_BIAS_MAX: FLOAT = 15.99;
pub const D3D12_MIP_LOD_BIAS_MIN: FLOAT = -16.0;
pub const D3D12_MIP_LOD_FRACTIONAL_BIT_COUNT: UINT = 8;
pub const D3D12_MIP_LOD_RANGE_BIT_COUNT: UINT = 8;
pub const D3D12_MULTISAMPLE_ANTIALIAS_LINE_WIDTH: FLOAT = 1.4;
pub const D3D12_NONSAMPLE_FETCH_OUT_OF_RANGE_ACCESS_RESULT: UINT = 0;
pub const D3D12_OS_RESERVED_REGISTER_SPACE_VALUES_END: UINT = 0xffffffff;
pub const D3D12_OS_RESERVED_REGISTER_SPACE_VALUES_START: UINT = 0xfffffff8;
pub const D3D12_PACKED_TILE: UINT = 0xffffffff;
pub const D3D12_PIXEL_ADDRESS_RANGE_BIT_COUNT: UINT = 15;
pub const D3D12_PRE_SCISSOR_PIXEL_ADDRESS_RANGE_BIT_COUNT: UINT = 16;
pub const D3D12_PS_CS_UAV_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_PS_CS_UAV_REGISTER_COUNT: UINT = 8;
pub const D3D12_PS_CS_UAV_REGISTER_READS_PER_INST: UINT = 1;
pub const D3D12_PS_CS_UAV_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_PS_FRONTFACING_DEFAULT_VALUE: UINT = 0xffffffff;
pub const D3D12_PS_FRONTFACING_FALSE_VALUE: UINT = 0;
pub const D3D12_PS_FRONTFACING_TRUE_VALUE: UINT = 0xffffffff;
pub const D3D12_PS_INPUT_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_PS_INPUT_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_PS_INPUT_REGISTER_COUNT: UINT = 32;
pub const D3D12_PS_INPUT_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_PS_INPUT_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_PS_LEGACY_PIXEL_CENTER_FRACTIONAL_COMPONENT: FLOAT = 0.0;
pub const D3D12_PS_OUTPUT_DEPTH_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_PS_OUTPUT_DEPTH_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_PS_OUTPUT_DEPTH_REGISTER_COUNT: UINT = 1;
pub const D3D12_PS_OUTPUT_MASK_REGISTER_COMPONENTS: UINT = 1;
pub const D3D12_PS_OUTPUT_MASK_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_PS_OUTPUT_MASK_REGISTER_COUNT: UINT = 1;
pub const D3D12_PS_OUTPUT_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_PS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_PS_OUTPUT_REGISTER_COUNT: UINT = 8;
pub const D3D12_PS_PIXEL_CENTER_FRACTIONAL_COMPONENT: FLOAT = 0.5;
pub const D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT: UINT = 16;
pub const D3D12_RAYTRACING_AABB_BYTE_ALIGNMENT: UINT = 8;
pub const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT: UINT = 256;
pub const D3D12_RAYTRACING_INSTANCE_DESCS_BYTE_ALIGNMENT: UINT = 16;
pub const D3D12_RAYTRACING_MAX_ATTRIBUTE_SIZE_IN_BYTES: UINT = 32;
pub const D3D12_RAYTRACING_MAX_DECLARABLE_TRACE_RECURSION_DEPTH: UINT = 31;
pub const D3D12_RAYTRACING_MAX_GEOMETRIES_PER_BOTTOM_LEVEL_ACCELERATION_STRUCTURE: UINT = 16777216;
pub const D3D12_RAYTRACING_MAX_INSTANCES_PER_TOP_LEVEL_ACCELERATION_STRUCTURE: UINT = 16777216;
pub const D3D12_RAYTRACING_MAX_PRIMITIVES_PER_BOTTOM_LEVEL_ACCELERATION_STRUCTURE: UINT = 536870912;
pub const D3D12_RAYTRACING_MAX_RAY_GENERATION_SHADER_THREADS: UINT = 1073741824;
pub const D3D12_RAYTRACING_MAX_SHADER_RECORD_STRIDE: UINT = 4096;
pub const D3D12_RAYTRACING_SHADER_RECORD_BYTE_ALIGNMENT: UINT = 32;
pub const D3D12_RAYTRACING_SHADER_TABLE_BYTE_ALIGNMENT: UINT = 64;
pub const D3D12_RAYTRACING_TRANSFORM3X4_BYTE_ALIGNMENT: UINT = 16;
pub const D3D12_REQ_BLEND_OBJECT_COUNT_PER_DEVICE: UINT = 4096;
pub const D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP: UINT = 27;
pub const D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT: UINT = 4096;
pub const D3D12_REQ_DEPTH_STENCIL_OBJECT_COUNT_PER_DEVICE: UINT = 4096;
pub const D3D12_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP: UINT = 32;
pub const D3D12_REQ_DRAW_VERTEX_COUNT_2_TO_EXP: UINT = 32;
pub const D3D12_REQ_FILTERING_HW_ADDRESSABLE_RESOURCE_DIMENSION: UINT = 16384;
pub const D3D12_REQ_GS_INVOCATION_32BIT_OUTPUT_COMPONENT_LIMIT: UINT = 1024;
pub const D3D12_REQ_IMMEDIATE_CONSTANT_BUFFER_ELEMENT_COUNT: UINT = 4096;
pub const D3D12_REQ_MAXANISOTROPY: UINT = 16;
pub const D3D12_REQ_MIP_LEVELS: UINT = 15;
pub const D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES: UINT = 2048;
pub const D3D12_REQ_RASTERIZER_OBJECT_COUNT_PER_DEVICE: UINT = 4096;
pub const D3D12_REQ_RENDER_TO_BUFFER_WINDOW_WIDTH: UINT = 16384;
pub const D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM: UINT = 128;
pub const D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_B_TERM: FLOAT = 0.25;
pub const D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_C_TERM: UINT = 2048;
pub const D3D12_REQ_RESOURCE_VIEW_COUNT_PER_DEVICE_2_TO_EXP: UINT = 20;
pub const D3D12_REQ_SAMPLER_OBJECT_COUNT_PER_DEVICE: UINT = 4096;
pub const D3D12_REQ_SUBRESOURCES: UINT = 30720;
pub const D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION: UINT = 2048;
pub const D3D12_REQ_TEXTURE1D_U_DIMENSION: UINT = 16384;
pub const D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION: UINT = 2048;
pub const D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION: UINT = 16384;
pub const D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION: UINT = 2048;
pub const D3D12_REQ_TEXTURECUBE_DIMENSION: UINT = 16384;
pub const D3D12_RESINFO_INSTRUCTION_MISSING_COMPONENT_RETVAL: UINT = 0;
pub const D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES: UINT = 0xffffffff;
pub const D3D12_RS_SET_SHADING_RATE_COMBINER_COUNT: UINT = 2;
pub const D3D12_SDK_VERSION: UINT = 3;
pub const D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES: UINT = 32;
pub const D3D12_SHADER_MAJOR_VERSION: UINT = 5;
pub const D3D12_SHADER_MAX_INSTANCES: UINT = 65535;
pub const D3D12_SHADER_MAX_INTERFACES: UINT = 253;
pub const D3D12_SHADER_MAX_INTERFACE_CALL_SITES: UINT = 4096;
pub const D3D12_SHADER_MAX_TYPES: UINT = 65535;
pub const D3D12_SHADER_MINOR_VERSION: UINT = 1;
pub const D3D12_SHIFT_INSTRUCTION_PAD_VALUE: UINT = 0;
pub const D3D12_SHIFT_INSTRUCTION_SHIFT_VALUE_BIT_COUNT: UINT = 5;
pub const D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT: UINT = 8;
pub const D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT: UINT = 65536;
pub const D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT: UINT = 4096;
pub const D3D12_SO_BUFFER_MAX_STRIDE_IN_BYTES: UINT = 2048;
pub const D3D12_SO_BUFFER_MAX_WRITE_WINDOW_IN_BYTES: UINT = 512;
pub const D3D12_SO_BUFFER_SLOT_COUNT: UINT = 4;
pub const D3D12_SO_DDI_REGISTER_INDEX_DENOTING_GAP: UINT = 0xffffffff;
pub const D3D12_SO_NO_RASTERIZED_STREAM: UINT = 0xffffffff;
pub const D3D12_SO_OUTPUT_COMPONENT_COUNT: UINT = 128;
pub const D3D12_SO_STREAM_COUNT: UINT = 4;
pub const D3D12_SPEC_DATE_DAY: UINT = 14;
pub const D3D12_SPEC_DATE_MONTH: UINT = 11;
pub const D3D12_SPEC_DATE_YEAR: UINT = 2014;
pub const D3D12_SPEC_VERSION: FLOAT = 1.16;
pub const D3D12_SRGB_GAMMA: FLOAT = 2.2;
pub const D3D12_SRGB_TO_FLOAT_DENOMINATOR_1: FLOAT = 12.92;
pub const D3D12_SRGB_TO_FLOAT_DENOMINATOR_2: FLOAT = 1.055;
pub const D3D12_SRGB_TO_FLOAT_EXPONENT: FLOAT = 2.4;
pub const D3D12_SRGB_TO_FLOAT_OFFSET: FLOAT = 0.055;
pub const D3D12_SRGB_TO_FLOAT_THRESHOLD: FLOAT = 0.04045;
pub const D3D12_SRGB_TO_FLOAT_TOLERANCE_IN_ULP: FLOAT = 0.5;
pub const D3D12_STANDARD_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_STANDARD_COMPONENT_BIT_COUNT_DOUBLED: UINT = 64;
pub const D3D12_STANDARD_MAXIMUM_ELEMENT_ALIGNMENT_BYTE_MULTIPLE: UINT = 4;
pub const D3D12_STANDARD_PIXEL_COMPONENT_COUNT: UINT = 128;
pub const D3D12_STANDARD_PIXEL_ELEMENT_COUNT: UINT = 32;
pub const D3D12_STANDARD_VECTOR_SIZE: UINT = 4;
pub const D3D12_STANDARD_VERTEX_ELEMENT_COUNT: UINT = 32;
pub const D3D12_STANDARD_VERTEX_TOTAL_COMPONENT_COUNT: UINT = 64;
pub const D3D12_SUBPIXEL_FRACTIONAL_BIT_COUNT: UINT = 8;
pub const D3D12_SUBTEXEL_FRACTIONAL_BIT_COUNT: UINT = 8;
pub const D3D12_SYSTEM_RESERVED_REGISTER_SPACE_VALUES_END: UINT = 0xffffffff;
pub const D3D12_SYSTEM_RESERVED_REGISTER_SPACE_VALUES_START: UINT = 0xfffffff0;
pub const D3D12_TESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR: UINT = 64;
pub const D3D12_TESSELLATOR_MAX_ISOLINE_DENSITY_TESSELLATION_FACTOR: UINT = 64;
pub const D3D12_TESSELLATOR_MAX_ODD_TESSELLATION_FACTOR: UINT = 63;
pub const D3D12_TESSELLATOR_MAX_TESSELLATION_FACTOR: UINT = 64;
pub const D3D12_TESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR: UINT = 2;
pub const D3D12_TESSELLATOR_MIN_ISOLINE_DENSITY_TESSELLATION_FACTOR: UINT = 1;
pub const D3D12_TESSELLATOR_MIN_ODD_TESSELLATION_FACTOR: UINT = 1;
pub const D3D12_TEXEL_ADDRESS_RANGE_BIT_COUNT: UINT = 16;
pub const D3D12_TEXTURE_DATA_PITCH_ALIGNMENT: UINT = 256;
pub const D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT: UINT = 512;
pub const D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES: UINT = 65536;
pub const D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT: UINT = 4096;
pub const D3D12_UAV_SLOT_COUNT: UINT = 64;
pub const D3D12_UNBOUND_MEMORY_ACCESS_RESULT: UINT = 0;
pub const D3D12_VIEWPORT_AND_SCISSORRECT_MAX_INDEX: UINT = 15;
pub const D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE: UINT = 16;
pub const D3D12_VIEWPORT_BOUNDS_MAX: INT = 32767;
pub const D3D12_VIEWPORT_BOUNDS_MIN: INT = -32768;
pub const D3D12_VS_INPUT_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_VS_INPUT_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_VS_INPUT_REGISTER_COUNT: UINT = 32;
pub const D3D12_VS_INPUT_REGISTER_READS_PER_INST: UINT = 2;
pub const D3D12_VS_INPUT_REGISTER_READ_PORTS: UINT = 1;
pub const D3D12_VS_OUTPUT_REGISTER_COMPONENTS: UINT = 4;
pub const D3D12_VS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: UINT = 32;
pub const D3D12_VS_OUTPUT_REGISTER_COUNT: UINT = 32;
pub const D3D12_WHQL_CONTEXT_COUNT_FOR_RESOURCE_LIMIT: UINT = 10;
pub const D3D12_WHQL_DRAWINDEXED_INDEX_COUNT_2_TO_EXP: UINT = 25;
pub const D3D12_WHQL_DRAW_VERTEX_COUNT_2_TO_EXP: UINT = 25;
pub type D3D12_GPU_VIRTUAL_ADDRESS = UINT64;
ENUM! {enum D3D12_COMMAND_LIST_TYPE {
D3D12_COMMAND_LIST_TYPE_DIRECT = 0,
D3D12_COMMAND_LIST_TYPE_BUNDLE = 1,
D3D12_COMMAND_LIST_TYPE_COMPUTE = 2,
D3D12_COMMAND_LIST_TYPE_COPY = 3,
D3D12_COMMAND_LIST_TYPE_VIDEO_DECODE = 4,
D3D12_COMMAND_LIST_TYPE_VIDEO_PROCESS = 5,
D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE = 6,
}}
ENUM! {enum D3D12_COMMAND_QUEUE_FLAGS {
D3D12_COMMAND_QUEUE_FLAG_NONE = 0x0,
D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT = 0x1,
}}
ENUM! {enum D3D12_COMMAND_QUEUE_PRIORITY {
D3D12_COMMAND_QUEUE_PRIORITY_NORMAL = 0,
D3D12_COMMAND_QUEUE_PRIORITY_HIGH = 100,
D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME = 10000,
}}
STRUCT! {struct D3D12_COMMAND_QUEUE_DESC {
Type: D3D12_COMMAND_LIST_TYPE,
Priority: INT,
Flags: D3D12_COMMAND_QUEUE_FLAGS,
NodeMask: UINT,
}}
ENUM! {enum D3D12_PRIMITIVE_TOPOLOGY_TYPE {
D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED = 0,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT = 1,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE = 2,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE = 3,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH = 4,
}}
ENUM! {enum D3D12_INPUT_CLASSIFICATION {
D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA = 0,
D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA = 1,
}}
STRUCT! {struct D3D12_INPUT_ELEMENT_DESC {
SemanticName: LPCSTR,
SemanticIndex: UINT,
Format: DXGI_FORMAT,
InputSlot: UINT,
AlignedByteOffset: UINT,
InputSlotClass: D3D12_INPUT_CLASSIFICATION,
InstanceDataStepRate: UINT,
}}
ENUM! {enum D3D12_FILL_MODE {
D3D12_FILL_MODE_WIREFRAME = 2,
D3D12_FILL_MODE_SOLID = 3,
}}
pub type D3D12_PRIMITIVE_TOPOLOGY = D3D_PRIMITIVE_TOPOLOGY;
pub type D3D12_PRIMITIVE = D3D_PRIMITIVE;
ENUM! {enum D3D12_CULL_MODE {
D3D12_CULL_MODE_NONE = 1,
D3D12_CULL_MODE_FRONT = 2,
D3D12_CULL_MODE_BACK = 3,
}}
STRUCT! {struct D3D12_SO_DECLARATION_ENTRY {
Stream: UINT,
SemanticName: LPCSTR,
SemanticIndex: UINT,
StartComponent: BYTE,
ComponentCount: BYTE,
OutputSlot: BYTE,
}}
STRUCT! {struct D3D12_VIEWPORT {
TopLeftX: FLOAT,
TopLeftY: FLOAT,
Width: FLOAT,
Height: FLOAT,
MinDepth: FLOAT,
MaxDepth: FLOAT,
}}
pub type D3D12_RECT = RECT;
STRUCT! {struct D3D12_BOX {
left: UINT,
top: UINT,
front: UINT,
right: UINT,
bottom: UINT,
back: UINT,
}}
ENUM! {enum D3D12_COMPARISON_FUNC {
D3D12_COMPARISON_FUNC_NEVER = 1,
D3D12_COMPARISON_FUNC_LESS = 2,
D3D12_COMPARISON_FUNC_EQUAL = 3,
D3D12_COMPARISON_FUNC_LESS_EQUAL = 4,
D3D12_COMPARISON_FUNC_GREATER = 5,
D3D12_COMPARISON_FUNC_NOT_EQUAL = 6,
D3D12_COMPARISON_FUNC_GREATER_EQUAL = 7,
D3D12_COMPARISON_FUNC_ALWAYS = 8,
}}
ENUM! {enum D3D12_DEPTH_WRITE_MASK {
D3D12_DEPTH_WRITE_MASK_ZERO = 0,
D3D12_DEPTH_WRITE_MASK_ALL = 1,
}}
ENUM! {enum D3D12_STENCIL_OP {
D3D12_STENCIL_OP_KEEP = 1,
D3D12_STENCIL_OP_ZERO = 2,
D3D12_STENCIL_OP_REPLACE = 3,
D3D12_STENCIL_OP_INCR_SAT = 4,
D3D12_STENCIL_OP_DECR_SAT = 5,
D3D12_STENCIL_OP_INVERT = 6,
D3D12_STENCIL_OP_INCR = 7,
D3D12_STENCIL_OP_DECR = 8,
}}
STRUCT! {struct D3D12_DEPTH_STENCILOP_DESC {
StencilFailOp: D3D12_STENCIL_OP,
StencilDepthFailOp: D3D12_STENCIL_OP,
StencilPassOp: D3D12_STENCIL_OP,
StencilFunc: D3D12_COMPARISON_FUNC,
}}
STRUCT! {struct D3D12_DEPTH_STENCIL_DESC {
DepthEnable: BOOL,
DepthWriteMask: D3D12_DEPTH_WRITE_MASK,
DepthFunc: D3D12_COMPARISON_FUNC,
StencilEnable: BOOL,
StencilReadMask: UINT8,
StencilWriteMask: UINT8,
FrontFace: D3D12_DEPTH_STENCILOP_DESC,
BackFace: D3D12_DEPTH_STENCILOP_DESC,
}}
STRUCT! {struct D3D12_DEPTH_STENCIL_DESC1 {
DepthEnable: BOOL,
DepthWriteMask: D3D12_DEPTH_WRITE_MASK,
DepthFunc: D3D12_COMPARISON_FUNC,
StencilEnable: BOOL,
StencilReadMask: UINT8,
StencilWriteMask: UINT8,
FrontFace: D3D12_DEPTH_STENCILOP_DESC,
BackFace: D3D12_DEPTH_STENCILOP_DESC,
DepthBoundsTestEnable: BOOL,
}}
ENUM! {enum D3D12_BLEND {
D3D12_BLEND_ZERO = 1,
D3D12_BLEND_ONE = 2,
D3D12_BLEND_SRC_COLOR = 3,
D3D12_BLEND_INV_SRC_COLOR = 4,
D3D12_BLEND_SRC_ALPHA = 5,
D3D12_BLEND_INV_SRC_ALPHA = 6,
D3D12_BLEND_DEST_ALPHA = 7,
D3D12_BLEND_INV_DEST_ALPHA = 8,
D3D12_BLEND_DEST_COLOR = 9,
D3D12_BLEND_INV_DEST_COLOR = 10,
D3D12_BLEND_SRC_ALPHA_SAT = 11,
D3D12_BLEND_BLEND_FACTOR = 14,
D3D12_BLEND_INV_BLEND_FACTOR = 15,
D3D12_BLEND_SRC1_COLOR = 16,
D3D12_BLEND_INV_SRC1_COLOR = 17,
D3D12_BLEND_SRC1_ALPHA = 18,
D3D12_BLEND_INV_SRC1_ALPHA = 19,
}}
ENUM! {enum D3D12_BLEND_OP {
D3D12_BLEND_OP_ADD = 1,
D3D12_BLEND_OP_SUBTRACT = 2,
D3D12_BLEND_OP_REV_SUBTRACT = 3,
D3D12_BLEND_OP_MIN = 4,
D3D12_BLEND_OP_MAX = 5,
}}
ENUM! {enum D3D12_COLOR_WRITE_ENABLE {
D3D12_COLOR_WRITE_ENABLE_RED = 1,
D3D12_COLOR_WRITE_ENABLE_GREEN = 2,
D3D12_COLOR_WRITE_ENABLE_BLUE = 4,
D3D12_COLOR_WRITE_ENABLE_ALPHA = 8,
D3D12_COLOR_WRITE_ENABLE_ALL = D3D12_COLOR_WRITE_ENABLE_RED | D3D12_COLOR_WRITE_ENABLE_GREEN
| D3D12_COLOR_WRITE_ENABLE_BLUE | D3D12_COLOR_WRITE_ENABLE_ALPHA,
}}
ENUM! {enum D3D12_LOGIC_OP {
D3D12_LOGIC_OP_CLEAR = 0,
D3D12_LOGIC_OP_SET = 1,
D3D12_LOGIC_OP_COPY = 2,
D3D12_LOGIC_OP_COPY_INVERTED = 3,
D3D12_LOGIC_OP_NOOP = 4,
D3D12_LOGIC_OP_INVERT = 5,
D3D12_LOGIC_OP_AND = 6,
D3D12_LOGIC_OP_NAND = 7,
D3D12_LOGIC_OP_OR = 8,
D3D12_LOGIC_OP_NOR = 9,
D3D12_LOGIC_OP_XOR = 10,
D3D12_LOGIC_OP_EQUIV = 11,
D3D12_LOGIC_OP_AND_REVERSE = 12,
D3D12_LOGIC_OP_AND_INVERTED = 13,
D3D12_LOGIC_OP_OR_REVERSE = 14,
D3D12_LOGIC_OP_OR_INVERTED = 15,
}}
STRUCT! {struct D3D12_RENDER_TARGET_BLEND_DESC {
BlendEnable: BOOL,
LogicOpEnable: BOOL,
SrcBlend: D3D12_BLEND,
DestBlend: D3D12_BLEND,
BlendOp: D3D12_BLEND_OP,
SrcBlendAlpha: D3D12_BLEND,
DestBlendAlpha: D3D12_BLEND,
BlendOpAlpha: D3D12_BLEND_OP,
LogicOp: D3D12_LOGIC_OP,
RenderTargetWriteMask: UINT8,
}}
STRUCT! {struct D3D12_BLEND_DESC {
AlphaToCoverageEnable: BOOL,
IndependentBlendEnable: BOOL,
RenderTarget: [D3D12_RENDER_TARGET_BLEND_DESC; 8],
}}
ENUM! {enum D3D12_CONSERVATIVE_RASTERIZATION_MODE {
D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF = 0,
D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON = 1,
}}
STRUCT! {struct D3D12_RASTERIZER_DESC {
FillMode: D3D12_FILL_MODE,
CullMode: D3D12_CULL_MODE,
FrontCounterClockwise: BOOL,
DepthBias: INT,
DepthBiasClamp: FLOAT,
SlopeScaledDepthBias: FLOAT,
DepthClipEnable: BOOL,
MultisampleEnable: BOOL,
AntialiasedLineEnable: BOOL,
ForcedSampleCount: UINT,
ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE,
}}
RIDL! {#[uuid(0xc54a6b66, 0x72df, 0x4ee8, 0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14)]
interface ID3D12RootSignature(ID3D12RootSignatureVtbl):
ID3D12DeviceChild(ID3D12DeviceChildVtbl) {}}
STRUCT! {struct D3D12_SHADER_BYTECODE {
pShaderBytecode: *const c_void,
BytecodeLength: SIZE_T,
}}
STRUCT! {struct D3D12_STREAM_OUTPUT_DESC {
pSODeclaration: *const D3D12_SO_DECLARATION_ENTRY,
NumEntries: UINT,
pBufferStrides: *const UINT,
NumStrides: UINT,
RasterizedStream: UINT,
}}
STRUCT! {struct D3D12_INPUT_LAYOUT_DESC {
pInputElementDescs: *const D3D12_INPUT_ELEMENT_DESC,
NumElements: UINT,
}}
ENUM! {enum D3D12_INDEX_BUFFER_STRIP_CUT_VALUE {
D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED = 0,
D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF = 1,
D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF = 2,
}}
STRUCT! {struct D3D12_CACHED_PIPELINE_STATE {
pCachedBlob: *const c_void,
CachedBlobSizeInBytes: SIZE_T,
}}
ENUM! {enum D3D12_PIPELINE_STATE_FLAGS {
D3D12_PIPELINE_STATE_FLAG_NONE = 0,
D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG = 0x1,
}}
STRUCT! {struct D3D12_GRAPHICS_PIPELINE_STATE_DESC {
pRootSignature: *mut ID3D12RootSignature,
VS: D3D12_SHADER_BYTECODE,
PS: D3D12_SHADER_BYTECODE,
DS: D3D12_SHADER_BYTECODE,
HS: D3D12_SHADER_BYTECODE,
GS: D3D12_SHADER_BYTECODE,
StreamOutput: D3D12_STREAM_OUTPUT_DESC,
BlendState: D3D12_BLEND_DESC,
SampleMask: UINT,
RasterizerState: D3D12_RASTERIZER_DESC,
DepthStencilState: D3D12_DEPTH_STENCIL_DESC,
InputLayout: D3D12_INPUT_LAYOUT_DESC,
IBStripCutValue: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE,
PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE,
NumRenderTargets: UINT,
RTVFormats: [DXGI_FORMAT; 8],
DSVFormat: DXGI_FORMAT,
SampleDesc: DXGI_SAMPLE_DESC,
NodeMask: UINT,
CachedPSO: D3D12_CACHED_PIPELINE_STATE,
Flags: D3D12_PIPELINE_STATE_FLAGS,
}}
STRUCT! {struct D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: *mut ID3D12RootSignature,
CS: D3D12_SHADER_BYTECODE,
NodeMask: UINT,
CachedPSO: D3D12_CACHED_PIPELINE_STATE,
Flags: D3D12_PIPELINE_STATE_FLAGS,
}}
STRUCT! {struct D3D12_RT_FORMAT_ARRAY {
RTFormats: [DXGI_FORMAT; 8],
NumRenderTargets: UINT,
}}
STRUCT! {struct D3D12_PIPELINE_STATE_STREAM_DESC {
SizeInBytes: SIZE_T,
pPipelineStateSubobjectStream: *mut c_void,
}}
ENUM! {enum D3D12_PIPELINE_STATE_SUBOBJECT_TYPE {
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE = 0,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS = 1,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS = 2,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS = 3,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS = 4,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS = 5,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS = 6,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT = 7,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND = 8,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK = 9,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER = 10,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL = 11,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT = 12,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE = 13,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY = 14,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS = 15,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT = 16,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC = 17,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK = 18,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO = 19,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS = 20,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 = 21,
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID = 22,
}}
ENUM! {enum D3D12_FEATURE {
D3D12_FEATURE_D3D12_OPTIONS = 0,
D3D12_FEATURE_ARCHITECTURE = 1,
D3D12_FEATURE_FEATURE_LEVELS = 2,
D3D12_FEATURE_FORMAT_SUPPORT = 3,
D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS = 4,
D3D12_FEATURE_FORMAT_INFO = 5,
D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT = 6,
D3D12_FEATURE_SHADER_MODEL = 7,
D3D12_FEATURE_D3D12_OPTIONS1 = 8,
D3D12_FEATURE_ROOT_SIGNATURE = 12,
D3D12_FEATURE_ARCHITECTURE1 = 16,
D3D12_FEATURE_D3D12_OPTIONS2 = 18,
D3D12_FEATURE_SHADER_CACHE = 19,
D3D12_FEATURE_COMMAND_QUEUE_PRIORITY = 20,
D3D12_FEATURE_D3D12_OPTIONS3 = 21,
D3D12_FEATURE_EXISTING_HEAPS = 22,
D3D12_FEATURE_D3D12_OPTIONS4 = 23,
D3D12_FEATURE_SERIALIZATION = 24,
D3D12_FEATURE_CROSS_NODE = 25,
D3D12_FEATURE_D3D12_OPTIONS5 = 27,
D3D12_FEATURE_D3D12_OPTIONS6 = 30,
D3D12_FEATURE_QUERY_META_COMMAND = 31,
D3D12_FEATURE_D3D12_OPTIONS7 = 32,
D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_TYPE_COUNT = 33,
D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_TYPES = 34,
D3D12_FEATURE_D3D12_OPTIONS8 = 36,
D3D12_FEATURE_D3D12_OPTIONS9 = 37,
D3D12_FEATURE_WAVE_MMA = 38,
}}
ENUM! {enum D3D12_SHADER_MIN_PRECISION_SUPPORT {
D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE = 0,
D3D12_SHADER_MIN_PRECISION_SUPPORT_10_BIT = 0x1,
D3D12_SHADER_MIN_PRECISION_SUPPORT_16_BIT = 0x2,
}}
ENUM! {enum D3D12_TILED_RESOURCES_TIER {
D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED = 0,
D3D12_TILED_RESOURCES_TIER_1 = 1,
D3D12_TILED_RESOURCES_TIER_2 = 2,
D3D12_TILED_RESOURCES_TIER_3 = 3,
D3D12_TILED_RESOURCES_TIER_4 = 4,
}}
ENUM! {enum D3D12_RESOURCE_BINDING_TIER {
D3D12_RESOURCE_BINDING_TIER_1 = 1,
D3D12_RESOURCE_BINDING_TIER_2 = 2,
D3D12_RESOURCE_BINDING_TIER_3 = 3,
}}
ENUM! {enum D3D12_CONSERVATIVE_RASTERIZATION_TIER {
D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED = 0,
D3D12_CONSERVATIVE_RASTERIZATION_TIER_1 = 1,
D3D12_CONSERVATIVE_RASTERIZATION_TIER_2 = 2,
D3D12_CONSERVATIVE_RASTERIZATION_TIER_3 = 3,
}}
ENUM! {enum D3D12_FORMAT_SUPPORT1 {
D3D12_FORMAT_SUPPORT1_NONE = 0,
D3D12_FORMAT_SUPPORT1_BUFFER = 0x1,
D3D12_FORMAT_SUPPORT1_IA_VERTEX_BUFFER = 0x2,
D3D12_FORMAT_SUPPORT1_IA_INDEX_BUFFER = 0x4,
D3D12_FORMAT_SUPPORT1_SO_BUFFER = 0x8,
D3D12_FORMAT_SUPPORT1_TEXTURE1D = 0x10,
D3D12_FORMAT_SUPPORT1_TEXTURE2D = 0x20,
D3D12_FORMAT_SUPPORT1_TEXTURE3D = 0x40,
D3D12_FORMAT_SUPPORT1_TEXTURECUBE = 0x80,
D3D12_FORMAT_SUPPORT1_SHADER_LOAD = 0x100,
D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE = 0x200,
D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_COMPARISON = 0x400,
D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_MONO_TEXT = 0x800,
D3D12_FORMAT_SUPPORT1_MIP = 0x1000,
D3D12_FORMAT_SUPPORT1_RENDER_TARGET = 0x4000,
D3D12_FORMAT_SUPPORT1_BLENDABLE = 0x8000,
D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL = 0x10000,
D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RESOLVE = 0x40000,
D3D12_FORMAT_SUPPORT1_DISPLAY = 0x80000,
D3D12_FORMAT_SUPPORT1_CAST_WITHIN_BIT_LAYOUT = 0x100000,
D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RENDERTARGET = 0x200000,
D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD = 0x400000,
D3D12_FORMAT_SUPPORT1_SHADER_GATHER = 0x800000,
D3D12_FORMAT_SUPPORT1_BACK_BUFFER_CAST = 0x1000000,
D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW = 0x2000000,
D3D12_FORMAT_SUPPORT1_SHADER_GATHER_COMPARISON = 0x4000000,
D3D12_FORMAT_SUPPORT1_DECODER_OUTPUT = 0x8000000,
D3D12_FORMAT_SUPPORT1_VIDEO_PROCESSOR_OUTPUT = 0x10000000,
D3D12_FORMAT_SUPPORT1_VIDEO_PROCESSOR_INPUT = 0x20000000,
D3D12_FORMAT_SUPPORT1_VIDEO_ENCODER = 0x40000000,
}}
ENUM! {enum D3D12_FORMAT_SUPPORT2 {
D3D12_FORMAT_SUPPORT2_NONE = 0,
D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD = 0x1,
D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_BITWISE_OPS = 0x2,
D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_COMPARE_STORE_OR_COMPARE_EXCHANGE = 0x4,
D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_EXCHANGE = 0x8,
D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_SIGNED_MIN_OR_MAX = 0x10,
D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_UNSIGNED_MIN_OR_MAX = 0x20,
D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD = 0x40,
D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE = 0x80,
D3D12_FORMAT_SUPPORT2_OUTPUT_MERGER_LOGIC_OP = 0x100,
D3D12_FORMAT_SUPPORT2_TILED = 0x200,
D3D12_FORMAT_SUPPORT2_MULTIPLANE_OVERLAY = 0x4000,
}}
ENUM! {enum D3D12_MULTISAMPLE_QUALITY_LEVEL_FLAGS {
D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE = 0,
D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE = 0x1,
}}
ENUM! {enum D3D12_CROSS_NODE_SHARING_TIER {
D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED = 0,
D3D12_CROSS_NODE_SHARING_TIER_1_EMULATED = 1,
D3D12_CROSS_NODE_SHARING_TIER_1 = 2,
D3D12_CROSS_NODE_SHARING_TIER_2 = 3,
D3D12_CROSS_NODE_SHARING_TIER_3 = 4,
}}
ENUM! {enum D3D12_RESOURCE_HEAP_TIER {
D3D12_RESOURCE_HEAP_TIER_1 = 1,
D3D12_RESOURCE_HEAP_TIER_2 = 2,
}}
ENUM! {enum D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER {
D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED = 0,
D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_1 = 1,
D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_2 = 2,
}}
ENUM! {enum D3D12_VIEW_INSTANCING_TIER {
D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED = 0,
D3D12_VIEW_INSTANCING_TIER_1 = 1,
D3D12_VIEW_INSTANCING_TIER_2 = 2,
D3D12_VIEW_INSTANCING_TIER_3 = 3,
}}
STRUCT! {struct D3D12_FEATURE_DATA_D3D12_OPTIONS {
DoublePrecisionFloatShaderOps: BOOL,
OutputMergerLogicOp: BOOL,
MinPrecisionSupport: D3D12_SHADER_MIN_PRECISION_SUPPORT,
TiledResourcesTier: D3D12_TILED_RESOURCES_TIER,
ResourceBindingTier: D3D12_RESOURCE_BINDING_TIER,
PSSpecifiedStencilRefSupported: BOOL,
TypedUAVLoadAdditionalFormats: BOOL,
ROVsSupported: BOOL,
ConservativeRasterizationTier: D3D12_CONSERVATIVE_RASTERIZATION_TIER,
MaxGPUVirtualAddressBitsPerResource: UINT,
StandardSwizzle64KBSupported: BOOL,
CrossNodeSharingTier: D3D12_CROSS_NODE_SHARING_TIER,
CrossAdapterRowMajorTextureSupported: BOOL,
VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation: BOOL,
ResourceHeapTier: D3D12_RESOURCE_HEAP_TIER,
}}
STRUCT! {struct D3D12_FEATURE_DATA_D3D12_OPTIONS1 {
WaveOps: BOOL,
WaveLaneCountMin: UINT,
WaveLaneCountMax: UINT,
TotalLaneCount: UINT,
ExpandedComputeResourceStates: BOOL,
Int64ShaderOps: BOOL,
}}
STRUCT! {struct D3D12_FEATURE_DATA_D3D12_OPTIONS2 {
DepthBoundsTestSupported: BOOL,
ProgrammableSamplePositionsTier: D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER,
}}
ENUM! {enum D3D_ROOT_SIGNATURE_VERSION {
D3D_ROOT_SIGNATURE_VERSION_1 = 0x1,
D3D_ROOT_SIGNATURE_VERSION_1_0 = 0x1,
D3D_ROOT_SIGNATURE_VERSION_1_1 = 0x2,
}}
STRUCT! {struct D3D12_FEATURE_DATA_ROOT_SIGNATURE {
HighestVersion: D3D_ROOT_SIGNATURE_VERSION,
}}
STRUCT! {struct D3D12_FEATURE_DATA_ARCHITECTURE {
NodeIndex: UINT,
TileBasedRenderer: BOOL,
UMA: BOOL,
CacheCoherentUMA: BOOL,
}}
STRUCT! {struct D3D12_FEATURE_DATA_ARCHITECTURE1 {
NodeIndex: UINT,
TileBasedRenderer: BOOL,
UMA: BOOL,
CacheCoherentUMA: BOOL,
IsolatedMMU: BOOL,
}}
STRUCT! {struct D3D12_FEATURE_DATA_FEATURE_LEVELS {
NumFeatureLevels: UINT,
pFeatureLevelsRequested: *const D3D_FEATURE_LEVEL,
MaxSupportedFeatureLevel: D3D_FEATURE_LEVEL,
}}
ENUM! {enum D3D_SHADER_MODEL {
D3D_SHADER_MODEL_5_1 = 0x51,
D3D_SHADER_MODEL_6_0 = 0x60,
D3D_SHADER_MODEL_6_1 = 0x61,
D3D_SHADER_MODEL_6_2 = 0x62,
D3D_SHADER_MODEL_6_3 = 0x63,
D3D_SHADER_MODEL_6_4 = 0x64,
D3D_SHADER_MODEL_6_5 = 0x65,
D3D_SHADER_MODEL_6_6 = 0x66,
D3D_SHADER_MODEL_6_7 = 0x67,
}}
STRUCT! {struct D3D12_FEATURE_DATA_SHADER_MODEL {
HighestShaderModel: D3D_SHADER_MODEL,
}}
STRUCT! {struct D3D12_FEATURE_DATA_FORMAT_SUPPORT {
Format: DXGI_FORMAT,
Support1: D3D12_FORMAT_SUPPORT1,
Support2: D3D12_FORMAT_SUPPORT2,
}}
STRUCT! {struct D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS {
Format: DXGI_FORMAT,
SampleCount: UINT,
Flags: D3D12_MULTISAMPLE_QUALITY_LEVEL_FLAGS,
NumQualityLevels: UINT,
}}
STRUCT! {struct D3D12_FEATURE_DATA_FORMAT_INFO {
Format: DXGI_FORMAT,
PlaneCount: UINT8,
}}
STRUCT! {struct D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT {
MaxGPUVirtualAddressBitsPerResource: UINT,
MaxGPUVirtualAddressBitsPerProcess: UINT,
}}
ENUM! {enum D3D12_SHADER_CACHE_SUPPORT_FLAGS {
D3D12_SHADER_CACHE_SUPPORT_NONE = 0,
D3D12_SHADER_CACHE_SUPPORT_SINGLE_PSO = 0x1,
D3D12_SHADER_CACHE_SUPPORT_LIBRARY = 0x2,
D3D12_SHADER_CACHE_SUPPORT_AUTOMATIC_INPROC_CACHE = 0x4,
D3D12_SHADER_CACHE_SUPPORT_AUTOMATIC_DISK_CACHE = 0x8,
D3D12_SHADER_CACHE_SUPPORT_DRIVER_MANAGED_CACHE = 0x10,
}}
STRUCT! {struct D3D12_FEATURE_DATA_SHADER_CACHE {
SupportFlags: D3D12_SHADER_CACHE_SUPPORT_FLAGS,
}}
STRUCT! {struct D3D12_FEATURE_DATA_COMMAND_QUEUE_PRIORITY {
CommandListType: D3D12_COMMAND_LIST_TYPE,
Priority: UINT,
PriorityForTypeIsSupported: BOOL,
}}
ENUM! {enum D3D12_COMMAND_LIST_SUPPORT_FLAGS {
D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE = 0,
D3D12_COMMAND_LIST_SUPPORT_FLAG_DIRECT = 1 << D3D12_COMMAND_LIST_TYPE_DIRECT,
D3D12_COMMAND_LIST_SUPPORT_FLAG_BUNDLE = 1 << D3D12_COMMAND_LIST_TYPE_BUNDLE,
D3D12_COMMAND_LIST_SUPPORT_FLAG_COMPUTE = 1 << D3D12_COMMAND_LIST_TYPE_COMPUTE,
D3D12_COMMAND_LIST_SUPPORT_FLAG_COPY = 1 << D3D12_COMMAND_LIST_TYPE_COPY,
D3D12_COMMAND_LIST_SUPPORT_FLAG_VIDEO_DECODE = 1 << D3D12_COMMAND_LIST_TYPE_VIDEO_DECODE,
D3D12_COMMAND_LIST_SUPPORT_FLAG_VIDEO_PROCESS = 1 << D3D12_COMMAND_LIST_TYPE_VIDEO_PROCESS,
D3D12_COMMAND_LIST_SUPPORT_FLAG_VIDEO_ENCODE = 1 << D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE,
}}
STRUCT! {struct D3D12_FEATURE_DATA_D3D12_OPTIONS3 {
CopyQueueTimestampQueriesSupported: BOOL,
CastingFullyTypedFormatSupported: BOOL,
WriteBufferImmediateSupportFlags: D3D12_COMMAND_LIST_SUPPORT_FLAGS,
ViewInstancingTier: D3D12_VIEW_INSTANCING_TIER,
BarycentricsSupported: BOOL,
}}
STRUCT! {struct D3D12_FEATURE_DATA_EXISTING_HEAPS {
Supported: BOOL,
}}
ENUM! {enum D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER {
D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0 = 0,
D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_1 = 1,
}}
STRUCT! {struct D3D12_FEATURE_DATA_D3D12_OPTIONS4 {
MSAA64KBAlignedTextureSupported: BOOL,
SharedResourceCompatibilityTier: D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER,
Native16BitShaderOpsSupported: BOOL,
}}
ENUM! {enum D3D12_HEAP_SERIALIZATION_TIER {
D3D12_HEAP_SERIALIZATION_TIER_0 = 0,
D3D12_HEAP_SERIALIZATION_TIER_10 = 10,
}}
STRUCT! {struct D3D12_FEATURE_DATA_SERIALIZATION {
NodeIndex: UINT,
HeapSerializationTier: D3D12_HEAP_SERIALIZATION_TIER,
}}
STRUCT! {struct D3D12_FEATURE_DATA_CROSS_NODE {
SharingTier: D3D12_CROSS_NODE_SHARING_TIER,
AtomicShaderInstructions: BOOL,
}}
ENUM! {enum D3D12_RENDER_PASS_TIER {
D3D12_RENDER_PASS_TIER_0 = 0,
D3D12_RENDER_PASS_TIER_1 = 1,
D3D12_RENDER_PASS_TIER_2 = 2,
}}
ENUM! {enum D3D12_RAYTRACING_TIER {
D3D12_RAYTRACING_TIER_NOT_SUPPORTED = 0,
D3D12_RAYTRACING_TIER_1_0 = 10,
}}
STRUCT! {struct D3D12_FEATURE_DATA_D3D12_OPTIONS5 {
SRVOnlyTiledResourceTier3: BOOL,
RenderPassesTier: D3D12_RENDER_PASS_TIER,
RaytracingTier: D3D12_RAYTRACING_TIER,
}}
ENUM! {enum D3D12_VARIABLE_SHADING_RATE_TIER {
D3D12_VARIABLE_SHADING_RATE_TIER_NOT_SUPPORTED = 0,
D3D12_VARIABLE_SHADING_RATE_TIER_1 = 1,
D3D12_VARIABLE_SHADING_RATE_TIER_2 = 2,
}}
STRUCT! {struct D3D12_FEATURE_DATA_D3D12_OPTIONS6 {
AdditionalShadingRatesSupported: BOOL,
PerPrimitiveShadingRateSupportedWithViewportIndexing: BOOL,
VariableShadingRateTier: D3D12_VARIABLE_SHADING_RATE_TIER,
ShadingRateImageTileSize: UINT,
BackgroundProcessingSupported: BOOL,
}}
ENUM! {enum D3D12_MESH_SHADER_TIER {
D3D12_MESH_SHADER_TIER_NOT_SUPPORTED = 0,
D3D12_MESH_SHADER_TIER_1 = 10,
}}
ENUM! {enum D3D12_SAMPLER_FEEDBACK_TIER {
D3D12_SAMPLER_FEEDBACK_TIER_NOT_SUPPORTED = 0,
D3D12_SAMPLER_FEEDBACK_TIER_0_9 = 90,
D3D12_SAMPLER_FEEDBACK_TIER_1_0 = 100,
}}
STRUCT! {struct D3D12_FEATURE_DATA_D3D12_OPTIONS7 {
MeshShaderTier: D3D12_MESH_SHADER_TIER,
SamplerFeedbackTier: D3D12_SAMPLER_FEEDBACK_TIER,
}}
STRUCT! {struct D3D12_FEATURE_DATA_QUERY_META_COMMAND {
CommandId: GUID,
NodeMask: UINT,
pQueryInputData: *const c_void,
QueryInputDataSizeInBytes: SIZE_T,
pQueryOutputData: *mut c_void,
QueryOutputDataSizeInBytes: SIZE_T,
}}
STRUCT! {struct D3D12_FEATURE_DATA_D3D12_OPTIONS8{
UnalignedBlockTexturesSupported: BOOL,
}}
ENUM! {enum D3D12_WAVE_MMA_TIER {
D3D12_WAVE_MMA_TIER_NOT_SUPPORTED = 0,
D3D12_WAVE_MMA_TIER_1_0 = 10,
}}
STRUCT! {struct D3D12_FEATURE_DATA_D3D12_OPTIONS9 {
MeshShaderPipelineStatsSupported: BOOL,
MeshShaderSupportsFullRangeRenderTargetArrayIndex: BOOL,
AtomicInt64OnTypedResourceSupported: BOOL,
AtomicInt64OnGroupSharedSupported: BOOL,
DerivativesInMeshAndAmplificationShadersSupported: BOOL,
WaveMMATier: D3D12_WAVE_MMA_TIER,
}}
ENUM! {enum D3D12_WAVE_MMA_INPUT_DATATYPE {
D3D12_WAVE_MMA_INPUT_DATATYPE_INVALID = 0,
D3D12_WAVE_MMA_INPUT_DATATYPE_BYTE,
D3D12_WAVE_MMA_INPUT_DATATYPE_FLOAT16,
D3D12_WAVE_MMA_INPUT_DATATYPE_FLOAT,
}}
ENUM! {enum D3D12_WAVE_MMA_DIMENSION {
D3D12_WAVE_MMA_DIMENSION_INVALID = 0,
D3D12_WAVE_MMA_DIMENSION_16,
D3D12_WAVE_MMA_DIMENSION_64,
// Expandable to other M sizes if needed
}}
ENUM! {enum D3D12_WAVE_MMA_ACCUM_DATATYPE {
D3D12_WAVE_MMA_ACCUM_DATATYPE_NONE = 0,
D3D12_WAVE_MMA_ACCUM_DATATYPE_INT32 = 0x1,
D3D12_WAVE_MMA_ACCUM_DATATYPE_FLOAT16 = 0x2,
D3D12_WAVE_MMA_ACCUM_DATATYPE_FLOAT = 0x4,
}}
STRUCT! {struct D3D12_FEATURE_DATA_WAVE_MMA {
InputDataType: D3D12_WAVE_MMA_INPUT_DATATYPE,
M: D3D12_WAVE_MMA_DIMENSION,
N: D3D12_WAVE_MMA_DIMENSION,
Supported: BOOL,
K: UINT,
AccumDataTypes: D3D12_WAVE_MMA_ACCUM_DATATYPE,
RequiredWaveLaneCountMin: UINT,
RequiredWaveLaneCountMax: UINT,
}}
STRUCT! {struct D3D12_RESOURCE_ALLOCATION_INFO {
SizeInBytes: UINT64,
Alignment: UINT64,
}}
STRUCT! {struct D3D12_RESOURCE_ALLOCATION_INFO1 {
Offset: UINT64,
Alignment: UINT64,
SizeInBytes: UINT64,
}}
ENUM! {enum D3D12_HEAP_TYPE {
D3D12_HEAP_TYPE_DEFAULT = 1,
D3D12_HEAP_TYPE_UPLOAD = 2,
D3D12_HEAP_TYPE_READBACK = 3,
D3D12_HEAP_TYPE_CUSTOM = 4,
}}
ENUM! {enum D3D12_CPU_PAGE_PROPERTY {
D3D12_CPU_PAGE_PROPERTY_UNKNOWN = 0,
D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE = 1,
D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE = 2,
D3D12_CPU_PAGE_PROPERTY_WRITE_BACK = 3,
}}
ENUM! {enum D3D12_MEMORY_POOL {
D3D12_MEMORY_POOL_UNKNOWN = 0,
D3D12_MEMORY_POOL_L0 = 1,
D3D12_MEMORY_POOL_L1 = 2,
}}
STRUCT! {struct D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE,
CPUPageProperty: D3D12_CPU_PAGE_PROPERTY,
MemoryPoolPreference: D3D12_MEMORY_POOL,
CreationNodeMask: UINT,
VisibleNodeMask: UINT,
}}
ENUM! {enum D3D12_HEAP_FLAGS {
D3D12_HEAP_FLAG_NONE = 0,
D3D12_HEAP_FLAG_SHARED = 0x1,
D3D12_HEAP_FLAG_DENY_BUFFERS = 0x4,
D3D12_HEAP_FLAG_ALLOW_DISPLAY = 0x8,
D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER = 0x20,
D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES = 0x40,
D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES = 0x80,
D3D12_HEAP_FLAG_HARDWARE_PROTECTED = 0x100,
D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH = 0x200,
D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES = 0,
D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS = 0xc0,
D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES = 0x44,
D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES = 0x84,
}}
STRUCT! {struct D3D12_HEAP_DESC {
SizeInBytes: UINT64,
Properties: D3D12_HEAP_PROPERTIES,
Alignment: UINT64,
Flags: D3D12_HEAP_FLAGS,
}}
ENUM! {enum D3D12_RESOURCE_DIMENSION {
D3D12_RESOURCE_DIMENSION_UNKNOWN = 0,
D3D12_RESOURCE_DIMENSION_BUFFER = 1,
D3D12_RESOURCE_DIMENSION_TEXTURE1D = 2,
D3D12_RESOURCE_DIMENSION_TEXTURE2D = 3,
D3D12_RESOURCE_DIMENSION_TEXTURE3D = 4,
}}
ENUM! {enum D3D12_TEXTURE_LAYOUT {
D3D12_TEXTURE_LAYOUT_UNKNOWN = 0,
D3D12_TEXTURE_LAYOUT_ROW_MAJOR = 1,
D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE = 2,
D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE = 3,
}}
ENUM! {enum D3D12_RESOURCE_FLAGS {
D3D12_RESOURCE_FLAG_NONE = 0,
D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET = 0x1,
D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL = 0x2,
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS = 0x4,
D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE = 0x8,
D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER = 0x10,
D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS = 0x20,
D3D12_RESOURCE_FLAG_VIDEO_DECODE_REFERENCE_ONLY = 0x40,
D3D12_RESOURCE_FLAG_VIDEO_ENCODE_REFERENCE_ONLY = 0x80,
}}
STRUCT! {struct D3D12_MIP_REGION{
Width: UINT,
Height: UINT,
Depth: UINT,
}}
STRUCT! {struct D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION,
Alignment: UINT64,
Width: UINT64,
Height: UINT,
DepthOrArraySize: UINT16,
MipLevels: UINT16,
Format: DXGI_FORMAT,
SampleDesc: DXGI_SAMPLE_DESC,
Layout: D3D12_TEXTURE_LAYOUT,
Flags: D3D12_RESOURCE_FLAGS,
}}
STRUCT! {struct D3D12_RESOURCE_DESC1 {
Dimension: D3D12_RESOURCE_DIMENSION,
Alignment: UINT64,
Width: UINT64,
Height: UINT,
DepthOrArraySize: UINT16,
MipLevels: UINT16,
Format: DXGI_FORMAT,
SampleDesc: DXGI_SAMPLE_DESC,
Layout: D3D12_TEXTURE_LAYOUT,
Flags: D3D12_RESOURCE_FLAGS,
SamplerFeedbackMipRegion: D3D12_MIP_REGION,
}}
STRUCT! {struct D3D12_DEPTH_STENCIL_VALUE {
Depth: FLOAT,
Stencil: UINT8,
}}
UNION! {union D3D12_CLEAR_VALUE_u {
[u32; 4],
Color Color_mut: [FLOAT; 4],
DepthStencil DepthStencil_mut: D3D12_DEPTH_STENCIL_VALUE,
}}
STRUCT! {struct D3D12_CLEAR_VALUE {
Format: DXGI_FORMAT,
u: D3D12_CLEAR_VALUE_u,
}}
STRUCT! {struct D3D12_RANGE {
Begin: SIZE_T,
End: SIZE_T,
}}
STRUCT! {struct D3D12_RANGE_UINT64 {
Begin: UINT64,
End: UINT64,
}}
STRUCT! {struct D3D12_SUBRESOURCE_RANGE_UINT64 {
Subresource: UINT,
Range: D3D12_RANGE_UINT64,
}}
STRUCT! {struct D3D12_SUBRESOURCE_INFO {
Offset: UINT64,
RowPitch: UINT,
DepthPitch: UINT,
}}
STRUCT! {struct D3D12_TILED_RESOURCE_COORDINATE {
X: UINT,
Y: UINT,
Z: UINT,
Subresource: UINT,
}}
STRUCT! {struct D3D12_TILE_REGION_SIZE {
NumTiles: UINT,
UseBox: BOOL,
Width: UINT,
Height: UINT16,
Depth: UINT16,
}}
ENUM! {enum D3D12_TILE_RANGE_FLAGS {
D3D12_TILE_RANGE_FLAG_NONE = 0,
D3D12_TILE_RANGE_FLAG_NULL = 1,
D3D12_TILE_RANGE_FLAG_SKIP = 2,
D3D12_TILE_RANGE_FLAG_REUSE_SINGLE_TILE = 4,
}}
STRUCT! {struct D3D12_SUBRESOURCE_TILING {
WidthInTiles: UINT,
HeightInTiles: UINT16,
DepthInTiles: UINT16,
StartTileIndexInOverallResource: UINT,
}}
STRUCT! {struct D3D12_TILE_SHAPE {
WidthInTexels: UINT,
HeightInTexels: UINT,
DepthInTexels: UINT,
}}
STRUCT! {struct D3D12_PACKED_MIP_INFO {
NumStandardMips: UINT8,
NumPackedMips: UINT8,
NumTilesForPackedMips: UINT,
StartTileIndexInOverallResource: UINT,
}}
ENUM! {enum D3D12_TILE_MAPPING_FLAGS {
D3D12_TILE_MAPPING_FLAG_NONE = 0,
D3D12_TILE_MAPPING_FLAG_NO_HAZARD = 0x1,
}}
ENUM! {enum D3D12_TILE_COPY_FLAGS {
D3D12_TILE_COPY_FLAG_NONE = 0,
D3D12_TILE_COPY_FLAG_NO_HAZARD = 0x1,
D3D12_TILE_COPY_FLAG_LINEAR_BUFFER_TO_SWIZZLED_TILED_RESOURCE = 0x2,
D3D12_TILE_COPY_FLAG_SWIZZLED_TILED_RESOURCE_TO_LINEAR_BUFFER = 0x4,
}}
ENUM! {enum D3D12_RESOURCE_STATES {
D3D12_RESOURCE_STATE_COMMON = 0,
D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER = 0x1,
D3D12_RESOURCE_STATE_INDEX_BUFFER = 0x2,
D3D12_RESOURCE_STATE_RENDER_TARGET = 0x4,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS = 0x8,
D3D12_RESOURCE_STATE_DEPTH_WRITE = 0x10,
D3D12_RESOURCE_STATE_DEPTH_READ = 0x20,
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE = 0x40,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE = 0x80,
D3D12_RESOURCE_STATE_STREAM_OUT = 0x100,
D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT = 0x200,
D3D12_RESOURCE_STATE_COPY_DEST = 0x400,
D3D12_RESOURCE_STATE_COPY_SOURCE = 0x800,
D3D12_RESOURCE_STATE_RESOLVE_DEST = 0x1000,
D3D12_RESOURCE_STATE_RESOLVE_SOURCE = 0x2000,
D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE = 0x400000,
D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE = 0x1000000,
D3D12_RESOURCE_STATE_GENERIC_READ = 0x1 | 0x2 | 0x40 | 0x80 | 0x200 | 0x800,
D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE = 0x40 | 0x80,
D3D12_RESOURCE_STATE_PRESENT = 0,
D3D12_RESOURCE_STATE_PREDICATION = 0x200,
D3D12_RESOURCE_STATE_VIDEO_DECODE_READ = 0x10000,
D3D12_RESOURCE_STATE_VIDEO_DECODE_WRITE = 0x20000,
D3D12_RESOURCE_STATE_VIDEO_PROCESS_READ = 0x40000,
D3D12_RESOURCE_STATE_VIDEO_PROCESS_WRITE = 0x80000,
D3D12_RESOURCE_STATE_VIDEO_ENCODE_READ = 0x200000,
D3D12_RESOURCE_STATE_VIDEO_ENCODE_WRITE = 0x800000,
}}
ENUM! {enum D3D12_RESOURCE_BARRIER_TYPE {
D3D12_RESOURCE_BARRIER_TYPE_TRANSITION = 0,
D3D12_RESOURCE_BARRIER_TYPE_ALIASING = 1,
D3D12_RESOURCE_BARRIER_TYPE_UAV = 2,
}}
STRUCT! {struct D3D12_RESOURCE_TRANSITION_BARRIER {
pResource: *mut ID3D12Resource,
Subresource: UINT,
StateBefore: D3D12_RESOURCE_STATES,
StateAfter: D3D12_RESOURCE_STATES,
}}
STRUCT! {struct D3D12_RESOURCE_ALIASING_BARRIER {
pResourceBefore: *mut ID3D12Resource,
pResourceAfter: *mut ID3D12Resource,
}}
STRUCT! {struct D3D12_RESOURCE_UAV_BARRIER {
pResource: *mut ID3D12Resource,
}}
ENUM! {enum D3D12_RESOURCE_BARRIER_FLAGS {
D3D12_RESOURCE_BARRIER_FLAG_NONE = 0x0,
D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY = 0x1,
D3D12_RESOURCE_BARRIER_FLAG_END_ONLY = 0x2,
}}
UNION! {union D3D12_RESOURCE_BARRIER_u {
[u32; 4] [u64; 3],
Transition Transition_mut: D3D12_RESOURCE_TRANSITION_BARRIER,
Aliasing Aliasing_mut: D3D12_RESOURCE_ALIASING_BARRIER,
UAV UAV_mut: D3D12_RESOURCE_UAV_BARRIER,
}}
STRUCT! {struct D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE,
Flags: D3D12_RESOURCE_BARRIER_FLAGS,
u: D3D12_RESOURCE_BARRIER_u,
}}
STRUCT! {struct D3D12_SUBRESOURCE_FOOTPRINT {
Format: DXGI_FORMAT,
Width: UINT,
Height: UINT,
Depth: UINT,
RowPitch: UINT,
}}
STRUCT! {struct D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: UINT64,
Footprint: D3D12_SUBRESOURCE_FOOTPRINT,
}}
ENUM! {enum D3D12_TEXTURE_COPY_TYPE {
D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX = 0,
D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT = 1,
}}
UNION! {union D3D12_TEXTURE_COPY_LOCATION_u {
[u64; 4],
PlacedFootprint PlacedFootprint_mut: D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
SubresourceIndex SubresourceIndex_mut: UINT,
}}
STRUCT! {struct D3D12_TEXTURE_COPY_LOCATION {
pResource: *mut ID3D12Resource,
Type: D3D12_TEXTURE_COPY_TYPE,
u: D3D12_TEXTURE_COPY_LOCATION_u,
}}
ENUM! {enum D3D12_RESOLVE_MODE {
D3D12_RESOLVE_MODE_DECOMPRESS = 0,
D3D12_RESOLVE_MODE_MIN = 1,
D3D12_RESOLVE_MODE_MAX = 2,
D3D12_RESOLVE_MODE_AVERAGE = 3,
}}
STRUCT! {struct D3D12_SAMPLE_POSITION {
X: INT8,
Y: INT8,
}}
ENUM! {enum D3D12_SHADER_COMPONENT_MAPPING {
D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_0 = 0,
D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_1 = 1,
D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_2 = 2,
D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_3 = 3,
D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0 = 4,
D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1 = 5,
}}
pub const D3D12_SHADER_COMPONENT_MAPPING_MASK: UINT = 0x7;
pub const D3D12_SHADER_COMPONENT_MAPPING_SHIFT: UINT = 3;
pub const D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES: UINT =
1 << (D3D12_SHADER_COMPONENT_MAPPING_SHIFT * 4);
pub fn D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(
Src0: UINT,
Src1: UINT,
Src2: UINT,
Src3: UINT,
) -> UINT {
(Src0 & D3D12_SHADER_COMPONENT_MAPPING_MASK)
| ((Src1 & D3D12_SHADER_COMPONENT_MAPPING_MASK) << (D3D12_SHADER_COMPONENT_MAPPING_SHIFT))
| ((Src2 & D3D12_SHADER_COMPONENT_MAPPING_MASK)
<< (D3D12_SHADER_COMPONENT_MAPPING_SHIFT * 2))
| ((Src3 & D3D12_SHADER_COMPONENT_MAPPING_MASK)
<< (D3D12_SHADER_COMPONENT_MAPPING_SHIFT * 3))
| D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES
}
pub fn D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(
ComponentToExtract: UINT,
Mapping: UINT,
) -> D3D12_SHADER_COMPONENT_MAPPING {
(Mapping >> (D3D12_SHADER_COMPONENT_MAPPING_SHIFT * ComponentToExtract)
& D3D12_SHADER_COMPONENT_MAPPING_MASK) as u32
}
pub fn D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING() -> UINT {
D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 1, 2, 3)
}
ENUM! {enum D3D12_BUFFER_SRV_FLAGS {
D3D12_BUFFER_SRV_FLAG_NONE = 0x0,
D3D12_BUFFER_SRV_FLAG_RAW = 0x1,
}}
STRUCT! {struct D3D12_BUFFER_SRV {
FirstElement: UINT64,
NumElements: UINT,
StructureByteStride: UINT,
Flags: D3D12_BUFFER_SRV_FLAGS,
}}
STRUCT! {struct D3D12_TEX1D_SRV {
MostDetailedMip: UINT,
MipLevels: UINT,
ResourceMinLODClamp: FLOAT,
}}
STRUCT! {struct D3D12_TEX1D_ARRAY_SRV {
MostDetailedMip: UINT,
MipLevels: UINT,
FirstArraySlice: UINT,
ArraySize: UINT,
ResourceMinLODClamp: FLOAT,
}}
STRUCT! {struct D3D12_TEX2D_SRV {
MostDetailedMip: UINT,
MipLevels: UINT,
PlaneSlice: UINT,
ResourceMinLODClamp: FLOAT,
}}
STRUCT! {struct D3D12_TEX2D_ARRAY_SRV {
MostDetailedMip: UINT,
MipLevels: UINT,
FirstArraySlice: UINT,
ArraySize: UINT,
PlaneSlice: UINT,
ResourceMinLODClamp: FLOAT,
}}
STRUCT! {struct D3D12_TEX3D_SRV {
MostDetailedMip: UINT,
MipLevels: UINT,
ResourceMinLODClamp: FLOAT,
}}
STRUCT! {struct D3D12_TEXCUBE_SRV {
MostDetailedMip: UINT,
MipLevels: UINT,
ResourceMinLODClamp: FLOAT,
}}
STRUCT! {struct D3D12_TEXCUBE_ARRAY_SRV {
MostDetailedMip: UINT,
MipLevels: UINT,
First2DArrayFace: UINT,
NumCubes: UINT,
ResourceMinLODClamp: FLOAT,
}}
STRUCT! {struct D3D12_TEX2DMS_SRV {
UnusedField_NothingToDefine: UINT,
}}
STRUCT! {struct D3D12_TEX2DMS_ARRAY_SRV {
FirstArraySlice: UINT,
ArraySize: UINT,
}}
STRUCT! {struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_SRV {
Location: D3D12_GPU_VIRTUAL_ADDRESS,
}}
ENUM! {enum D3D12_SRV_DIMENSION {
D3D12_SRV_DIMENSION_UNKNOWN = 0,
D3D12_SRV_DIMENSION_BUFFER = 1,
D3D12_SRV_DIMENSION_TEXTURE1D = 2,
D3D12_SRV_DIMENSION_TEXTURE1DARRAY = 3,
D3D12_SRV_DIMENSION_TEXTURE2D = 4,
D3D12_SRV_DIMENSION_TEXTURE2DARRAY = 5,
D3D12_SRV_DIMENSION_TEXTURE2DMS = 6,
D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY = 7,
D3D12_SRV_DIMENSION_TEXTURE3D = 8,
D3D12_SRV_DIMENSION_TEXTURECUBE = 9,
D3D12_SRV_DIMENSION_TEXTURECUBEARRAY = 10,
D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE = 11,
}}
UNION! {union D3D12_SHADER_RESOURCE_VIEW_DESC_u {
[u64; 3],
Buffer Buffer_mut: D3D12_BUFFER_SRV,
Texture1D Texture1D_mut: D3D12_TEX1D_SRV,
Texture1DArray Texture1DArray_mut: D3D12_TEX1D_ARRAY_SRV,
Texture2D Texture2D_mut: D3D12_TEX2D_SRV,
Texture2DArray Texture2DArray_mut: D3D12_TEX2D_ARRAY_SRV,
Texture2DMS Texture2DMS_mut: D3D12_TEX2DMS_SRV,
Texture2DMSArray Texture2DMSArray_mut: D3D12_TEX2DMS_ARRAY_SRV,
Texture3D Texture3D_mut: D3D12_TEX3D_SRV,
TextureCube TextureCube_mut: D3D12_TEXCUBE_SRV,
TextureCubeArray TextureCubeArray_mut: D3D12_TEXCUBE_ARRAY_SRV,
RaytracingAccelerationStructure RaytracingAccelerationStructure_mut
: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_SRV,
}}
STRUCT! {struct D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT,
ViewDimension: D3D12_SRV_DIMENSION,
Shader4ComponentMapping: UINT,
u: D3D12_SHADER_RESOURCE_VIEW_DESC_u,
}}
STRUCT! {struct D3D12_CONSTANT_BUFFER_VIEW_DESC {
BufferLocation: D3D12_GPU_VIRTUAL_ADDRESS,
SizeInBytes: UINT,
}}
ENUM! {enum D3D12_FILTER {
D3D12_FILTER_MIN_MAG_MIP_POINT = 0,
D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR = 0x1,
D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4,
D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR = 0x5,
D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT = 0x10,
D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11,
D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT = 0x14,
D3D12_FILTER_MIN_MAG_MIP_LINEAR = 0x15,
D3D12_FILTER_ANISOTROPIC = 0x55,
D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 0x80,
D3D12_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81,
D3D12_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84,
D3D12_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85,
D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90,
D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91,
D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94,
D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 0x95,
D3D12_FILTER_COMPARISON_ANISOTROPIC = 0xd5,
D3D12_FILTER_MINIMUM_MIN_MAG_MIP_POINT = 0x100,
D3D12_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x101,
D3D12_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x104,
D3D12_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x105,
D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x110,
D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x111,
D3D12_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x114,
D3D12_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR = 0x115,
D3D12_FILTER_MINIMUM_ANISOTROPIC = 0x155,
D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_POINT = 0x180,
D3D12_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x181,
D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x184,
D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x185,
D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x190,
D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x191,
D3D12_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x194,
D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR = 0x195,
D3D12_FILTER_MAXIMUM_ANISOTROPIC = 0x1d5,
}}
ENUM! {enum D3D12_FILTER_TYPE {
D3D12_FILTER_TYPE_POINT = 0,
D3D12_FILTER_TYPE_LINEAR = 1,
}}
ENUM! {enum D3D12_FILTER_REDUCTION_TYPE {
D3D12_FILTER_REDUCTION_TYPE_STANDARD = 0,
D3D12_FILTER_REDUCTION_TYPE_COMPARISON = 1,
D3D12_FILTER_REDUCTION_TYPE_MINIMUM = 2,
D3D12_FILTER_REDUCTION_TYPE_MAXIMUM = 3,
}}
pub const D3D12_FILTER_REDUCTION_TYPE_MASK: UINT = 0x3;
pub const D3D12_FILTER_REDUCTION_TYPE_SHIFT: UINT = 7;
pub const D3D12_FILTER_TYPE_MASK: UINT = 0x3;
pub const D3D12_MIN_FILTER_SHIFT: UINT = 4;
pub const D3D12_MAG_FILTER_SHIFT: UINT = 2;
pub const D3D12_MIP_FILTER_SHIFT: UINT = 0;
pub const D3D12_ANISOTROPIC_FILTERING_BIT: UINT = 0x40;
pub fn D3D12_ENCODE_BASIC_FILTER(
min: D3D12_FILTER_TYPE,
mag: D3D12_FILTER_TYPE,
mip: D3D12_FILTER_TYPE,
reduction: D3D12_FILTER_REDUCTION_TYPE,
) -> D3D12_FILTER {
((min & D3D12_FILTER_TYPE_MASK) << D3D12_MIN_FILTER_SHIFT)
| ((mag & D3D12_FILTER_TYPE_MASK) << D3D12_MAG_FILTER_SHIFT)
| ((mip & D3D12_FILTER_TYPE_MASK) << D3D12_MIP_FILTER_SHIFT)
| ((reduction & D3D12_FILTER_REDUCTION_TYPE_MASK) << D3D12_FILTER_REDUCTION_TYPE_SHIFT)
}
pub fn D3D12_ENCODE_ANISOTROPIC_FILTER(reduction: D3D12_FILTER_REDUCTION_TYPE) -> D3D12_FILTER {
D3D12_ANISOTROPIC_FILTERING_BIT
| D3D12_ENCODE_BASIC_FILTER(
D3D12_FILTER_TYPE_LINEAR,
D3D12_FILTER_TYPE_LINEAR,
D3D12_FILTER_TYPE_LINEAR,
reduction,
)
}
pub fn D3D12_DECODE_MIN_FILTER(filter: D3D12_FILTER) -> D3D12_FILTER {
(filter >> D3D12_MIN_FILTER_SHIFT) & D3D12_FILTER_TYPE_MASK
}
pub fn D3D12_DECODE_MAG_FILTER(filter: D3D12_FILTER) -> D3D12_FILTER {
(filter >> D3D12_MAG_FILTER_SHIFT) & D3D12_FILTER_TYPE_MASK
}
pub fn D3D12_DECODE_MIP_FILTER(filter: D3D12_FILTER) -> D3D12_FILTER {
(filter >> D3D12_MIP_FILTER_SHIFT) & D3D12_FILTER_TYPE_MASK
}
pub fn D3D12_DECODE_FILTER_REDUCTION(filter: D3D12_FILTER) -> D3D12_FILTER {
(filter >> D3D12_FILTER_REDUCTION_TYPE_SHIFT) & D3D12_FILTER_REDUCTION_TYPE_MASK
}
pub fn D3D12_DECODE_IS_COMPARISON_FILTER(filter: D3D12_FILTER) -> bool {
D3D12_DECODE_FILTER_REDUCTION(filter) == D3D12_FILTER_REDUCTION_TYPE_COMPARISON
}
pub fn D3D12_DECODE_IS_ANISOTROPIC_FILTER(filter: D3D12_FILTER) -> bool {
((filter & D3D12_ANISOTROPIC_FILTERING_BIT) != 0)
&& (D3D12_DECODE_MIN_FILTER(filter) == D3D12_FILTER_TYPE_LINEAR)
&& (D3D12_DECODE_MAG_FILTER(filter) == D3D12_FILTER_TYPE_LINEAR)
&& (D3D12_DECODE_MIP_FILTER(filter) == D3D12_FILTER_TYPE_LINEAR)
}
ENUM! {enum D3D12_TEXTURE_ADDRESS_MODE {
D3D12_TEXTURE_ADDRESS_MODE_WRAP = 1,
D3D12_TEXTURE_ADDRESS_MODE_MIRROR = 2,
D3D12_TEXTURE_ADDRESS_MODE_CLAMP = 3,
D3D12_TEXTURE_ADDRESS_MODE_BORDER = 4,
D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE = 5,
}}
STRUCT! {struct D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER,
AddressU: D3D12_TEXTURE_ADDRESS_MODE,
AddressV: D3D12_TEXTURE_ADDRESS_MODE,
AddressW: D3D12_TEXTURE_ADDRESS_MODE,
MipLODBias: FLOAT,
MaxAnisotropy: UINT,
ComparisonFunc: D3D12_COMPARISON_FUNC,
BorderColor: [FLOAT; 4],
MinLOD: FLOAT,
MaxLOD: FLOAT,
}}
ENUM! {enum D3D12_BUFFER_UAV_FLAGS {
D3D12_BUFFER_UAV_FLAG_NONE = 0,
D3D12_BUFFER_UAV_FLAG_RAW = 0x1,
}}
STRUCT! {struct D3D12_BUFFER_UAV {
FirstElement: UINT64,
NumElements: UINT,
StructureByteStride: UINT,
CounterOffsetInBytes: UINT64,
Flags: D3D12_BUFFER_UAV_FLAGS,
}}
STRUCT! {struct D3D12_TEX1D_UAV {
MipSlice: UINT,
}}
STRUCT! {struct D3D12_TEX1D_ARRAY_UAV {
MipSlice: UINT,
FirstArraySlice: UINT,
ArraySize: UINT,
}}
STRUCT! {struct D3D12_TEX2D_UAV {
MipSlice: UINT,
PlaneSlice: UINT,
}}
STRUCT! {struct D3D12_TEX2D_ARRAY_UAV {
MipSlice: UINT,
FirstArraySlice: UINT,
ArraySize: UINT,
PlaneSlice: UINT,
}}
STRUCT! {struct D3D12_TEX3D_UAV {
MipSlice: UINT,
FirstWSlice: UINT,
WSize: UINT,
}}
ENUM! {enum D3D12_UAV_DIMENSION {
D3D12_UAV_DIMENSION_UNKNOWN = 0,
D3D12_UAV_DIMENSION_BUFFER = 1,
D3D12_UAV_DIMENSION_TEXTURE1D = 2,
D3D12_UAV_DIMENSION_TEXTURE1DARRAY = 3,
D3D12_UAV_DIMENSION_TEXTURE2D = 4,
D3D12_UAV_DIMENSION_TEXTURE2DARRAY = 5,
D3D12_UAV_DIMENSION_TEXTURE3D = 8,
}}
UNION! {union D3D12_UNORDERED_ACCESS_VIEW_DESC_u {
[u64; 4],
Buffer Buffer_mut: D3D12_BUFFER_UAV,
Texture1D Texture1D_mut: D3D12_TEX1D_UAV,
Texture1DArray Texture1DArray_mut: D3D12_TEX1D_ARRAY_UAV,
Texture2D Texture2D_mut: D3D12_TEX2D_UAV,
Texture2DArray Texture2DArray_mut: D3D12_TEX2D_ARRAY_UAV,
Texture3D Texture3D_mut: D3D12_TEX3D_UAV,
}}
STRUCT! {struct D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: DXGI_FORMAT,
ViewDimension: D3D12_UAV_DIMENSION,
u: D3D12_UNORDERED_ACCESS_VIEW_DESC_u,
}}
STRUCT! {struct D3D12_BUFFER_RTV {
FirstElement: UINT64,
NumElements: UINT,
}}
STRUCT! {struct D3D12_TEX1D_RTV {
MipSlice: UINT,
}}
STRUCT! {struct D3D12_TEX1D_ARRAY_RTV {
MipSlice: UINT,
FirstArraySlice: UINT,
ArraySize: UINT,
}}
STRUCT! {struct D3D12_TEX2D_RTV {
MipSlice: UINT,
PlaneSlice: UINT,
}}
STRUCT! {struct D3D12_TEX2DMS_RTV {
UnusedField_NothingToDefine: UINT,
}}
STRUCT! {struct D3D12_TEX2D_ARRAY_RTV {
MipSlice: UINT,
FirstArraySlice: UINT,
ArraySize: UINT,
PlaneSlice: UINT,
}}
STRUCT! {struct D3D12_TEX2DMS_ARRAY_RTV {
FirstArraySlice: UINT,
ArraySize: UINT,
}}
STRUCT! {struct D3D12_TEX3D_RTV {
MipSlice: UINT,
FirstWSlice: UINT,
WSize: UINT,
}}
ENUM! {enum D3D12_RTV_DIMENSION {
D3D12_RTV_DIMENSION_UNKNOWN = 0,
D3D12_RTV_DIMENSION_BUFFER = 1,
D3D12_RTV_DIMENSION_TEXTURE1D = 2,
D3D12_RTV_DIMENSION_TEXTURE1DARRAY = 3,
D3D12_RTV_DIMENSION_TEXTURE2D = 4,
D3D12_RTV_DIMENSION_TEXTURE2DARRAY = 5,
D3D12_RTV_DIMENSION_TEXTURE2DMS = 6,
D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY = 7,
D3D12_RTV_DIMENSION_TEXTURE3D = 8,
}}
UNION! {union D3D12_RENDER_TARGET_VIEW_DESC_u {
[u64; 2],
Buffer Buffer_mut: D3D12_BUFFER_RTV,
Texture1D Texture1D_mut: D3D12_TEX1D_RTV,
Texture1DArray Texture1DArray_mut: D3D12_TEX1D_ARRAY_RTV,
Texture2D Texture2D_mut: D3D12_TEX2D_RTV,
Texture2DArray Texture2DArray_mut: D3D12_TEX2D_ARRAY_RTV,
Texture2DMS Texture2DMS_mut: D3D12_TEX2DMS_RTV,
Texture2DMSArray Texture2DMSArray_mut: D3D12_TEX2DMS_ARRAY_RTV,
Texture3D Texture3D_mut: D3D12_TEX3D_RTV,
}}
STRUCT! {struct D3D12_RENDER_TARGET_VIEW_DESC {
Format: DXGI_FORMAT,
ViewDimension: D3D12_RTV_DIMENSION,
u: D3D12_RENDER_TARGET_VIEW_DESC_u,
}}
STRUCT! {struct D3D12_TEX1D_DSV {
MipSlice: UINT,
}}
STRUCT! {struct D3D12_TEX1D_ARRAY_DSV {
MipSlice: UINT,
FirstArraySlice: UINT,
ArraySize: UINT,
}}
STRUCT! {struct D3D12_TEX2D_DSV {
MipSlice: UINT,
}}
STRUCT! {struct D3D12_TEX2D_ARRAY_DSV {
MipSlice: UINT,
FirstArraySlice: UINT,
ArraySize: UINT,
}}
STRUCT! {struct D3D12_TEX2DMS_DSV {
UnusedField_NothingToDefine: UINT,
}}
STRUCT! {struct D3D12_TEX2DMS_ARRAY_DSV {
FirstArraySlice: UINT,
ArraySize: UINT,
}}
ENUM! {enum D3D12_DSV_FLAGS {
D3D12_DSV_FLAG_NONE = 0x0,
D3D12_DSV_FLAG_READ_ONLY_DEPTH = 0x1,
D3D12_DSV_FLAG_READ_ONLY_STENCIL = 0x2,
}}
ENUM! {enum D3D12_DSV_DIMENSION {
D3D12_DSV_DIMENSION_UNKNOWN = 0,
D3D12_DSV_DIMENSION_TEXTURE1D = 1,
D3D12_DSV_DIMENSION_TEXTURE1DARRAY = 2,
D3D12_DSV_DIMENSION_TEXTURE2D = 3,
D3D12_DSV_DIMENSION_TEXTURE2DARRAY = 4,
D3D12_DSV_DIMENSION_TEXTURE2DMS = 5,
D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY = 6,
}}
UNION! {union D3D12_DEPTH_STENCIL_VIEW_DESC_u {
[u32; 3],
Texture1D Texture1D_mut: D3D12_TEX1D_DSV,
Texture1DArray Texture1DArray_mut: D3D12_TEX1D_ARRAY_DSV,
Texture2D Texture2D_mut: D3D12_TEX2D_DSV,
Texture2DArray Texture2DArray_mut: D3D12_TEX2D_ARRAY_DSV,
Texture2DMS Texture2DMS_mut: D3D12_TEX2DMS_DSV,
Texture2DMSArray Texture2DMSArray_mut: D3D12_TEX2DMS_ARRAY_DSV,
}}
STRUCT! {struct D3D12_DEPTH_STENCIL_VIEW_DESC {
Format: DXGI_FORMAT,
ViewDimension: D3D12_DSV_DIMENSION,
Flags: D3D12_DSV_FLAGS,
u: D3D12_DEPTH_STENCIL_VIEW_DESC_u,
}}
ENUM! {enum D3D12_CLEAR_FLAGS {
D3D12_CLEAR_FLAG_DEPTH = 0x1,
D3D12_CLEAR_FLAG_STENCIL = 0x2,
}}
ENUM! {enum D3D12_FENCE_FLAGS {
D3D12_FENCE_FLAG_NONE = 0x0,
D3D12_FENCE_FLAG_SHARED = 0x1,
D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER = 0x2,
D3D12_FENCE_FLAG_NON_MONITORED = 0x4,
}}
ENUM! {enum D3D12_DESCRIPTOR_HEAP_TYPE {
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV = 0,
D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER = 1,
D3D12_DESCRIPTOR_HEAP_TYPE_RTV = 2,
D3D12_DESCRIPTOR_HEAP_TYPE_DSV = 3,
D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES = 4,
}}
ENUM! {enum D3D12_DESCRIPTOR_HEAP_FLAGS {
D3D12_DESCRIPTOR_HEAP_FLAG_NONE = 0x0,
D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE = 0x1,
}}
STRUCT! {struct D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE,
NumDescriptors: UINT,
Flags: D3D12_DESCRIPTOR_HEAP_FLAGS,
NodeMask: UINT,
}}
ENUM! {enum D3D12_DESCRIPTOR_RANGE_TYPE {
D3D12_DESCRIPTOR_RANGE_TYPE_SRV = 0,
D3D12_DESCRIPTOR_RANGE_TYPE_UAV = 1,
D3D12_DESCRIPTOR_RANGE_TYPE_CBV = 2,
D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER = 3,
}}
STRUCT! {struct D3D12_DESCRIPTOR_RANGE {
RangeType: D3D12_DESCRIPTOR_RANGE_TYPE,
NumDescriptors: UINT,
BaseShaderRegister: UINT,
RegisterSpace: UINT,
OffsetInDescriptorsFromTableStart: UINT,
}}
STRUCT! {struct D3D12_ROOT_DESCRIPTOR_TABLE {
NumDescriptorRanges: UINT,
pDescriptorRanges: *const D3D12_DESCRIPTOR_RANGE,
}}
STRUCT! {struct D3D12_ROOT_CONSTANTS {
ShaderRegister: UINT,
RegisterSpace: UINT,
Num32BitValues: UINT,
}}
STRUCT! {struct D3D12_ROOT_DESCRIPTOR {
ShaderRegister: UINT,
RegisterSpace: UINT,
}}
ENUM! {enum D3D12_SHADER_VISIBILITY {
D3D12_SHADER_VISIBILITY_ALL = 0,
D3D12_SHADER_VISIBILITY_VERTEX = 1,
D3D12_SHADER_VISIBILITY_HULL = 2,
D3D12_SHADER_VISIBILITY_DOMAIN = 3,
D3D12_SHADER_VISIBILITY_GEOMETRY = 4,
D3D12_SHADER_VISIBILITY_PIXEL = 5,
}}
ENUM! {enum D3D12_ROOT_PARAMETER_TYPE {
D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE = 0,
D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS = 1,
D3D12_ROOT_PARAMETER_TYPE_CBV = 2,
D3D12_ROOT_PARAMETER_TYPE_SRV = 3,
D3D12_ROOT_PARAMETER_TYPE_UAV = 4,
}}
UNION! {union D3D12_ROOT_PARAMETER_u {
[u32; 3] [u64; 2],
DescriptorTable DescriptorTable_mut: D3D12_ROOT_DESCRIPTOR_TABLE,
Constants Constants_mut: D3D12_ROOT_CONSTANTS,
Descriptor Descriptor_mut: D3D12_ROOT_DESCRIPTOR,
}}
STRUCT! {struct D3D12_ROOT_PARAMETER {
ParameterType: D3D12_ROOT_PARAMETER_TYPE,
u: D3D12_ROOT_PARAMETER_u,
ShaderVisibility: D3D12_SHADER_VISIBILITY,
}}
ENUM! {enum D3D12_ROOT_SIGNATURE_FLAGS {
D3D12_ROOT_SIGNATURE_FLAG_NONE = 0x0,
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT = 0x1,
D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS = 0x2,
D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS = 0x4,
D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS = 0x8,
D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS = 0x10,
D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS = 0x20,
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT = 0x40,
D3D12_ROOT_SIGNATURE_FLAG_LOCAL_ROOT_SIGNATURE = 0x80,
D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS = 0x100,
D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS = 0x200,
D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED = 0x400,
D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED = 0x800,
}}
ENUM! {enum D3D12_STATIC_BORDER_COLOR {
D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK = 0,
D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK = 1,
D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE = 2,
}}
STRUCT! {struct D3D12_STATIC_SAMPLER_DESC {
Filter: D3D12_FILTER,
AddressU: D3D12_TEXTURE_ADDRESS_MODE,
AddressV: D3D12_TEXTURE_ADDRESS_MODE,
AddressW: D3D12_TEXTURE_ADDRESS_MODE,
MipLODBias: FLOAT,
MaxAnisotropy: UINT,
ComparisonFunc: D3D12_COMPARISON_FUNC,
BorderColor: D3D12_STATIC_BORDER_COLOR,
MinLOD: FLOAT,
MaxLOD: FLOAT,
ShaderRegister: UINT,
RegisterSpace: UINT,
ShaderVisibility: D3D12_SHADER_VISIBILITY,
}}
STRUCT! {struct D3D12_ROOT_SIGNATURE_DESC {
NumParameters: UINT,
pParameters: *const D3D12_ROOT_PARAMETER,
NumStaticSamplers: UINT,
pStaticSamplers: *const D3D12_STATIC_SAMPLER_DESC,
Flags: D3D12_ROOT_SIGNATURE_FLAGS,
}}
ENUM! {enum D3D12_DESCRIPTOR_RANGE_FLAGS {
D3D12_DESCRIPTOR_RANGE_FLAG_NONE = 0,
D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE = 0x1,
D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE = 0x2,
D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE = 0x4,
D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC = 0x8,
D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_STATIC_KEEPING_BUFFER_BOUNDS_CHECKS = 0x10000,
}}
STRUCT! {struct D3D12_DESCRIPTOR_RANGE1 {
RangeType: D3D12_DESCRIPTOR_RANGE_TYPE,
NumDescriptors: UINT,
BaseShaderRegister: UINT,
RegisterSpace: UINT,
Flags: D3D12_DESCRIPTOR_RANGE_FLAGS,
OffsetInDescriptorsFromTableStart: UINT,
}}
STRUCT! {struct D3D12_ROOT_DESCRIPTOR_TABLE1 {
NumDescriptorRanges: UINT,
pDescriptorRanges: *const D3D12_DESCRIPTOR_RANGE1,
}}
ENUM! {enum D3D12_ROOT_DESCRIPTOR_FLAGS {
D3D12_ROOT_DESCRIPTOR_FLAG_NONE = 0,
D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE = 0x2,
D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE = 0x4,
D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC = 0x8,
}}
STRUCT! {struct D3D12_ROOT_DESCRIPTOR1 {
ShaderRegister: UINT,
RegisterSpace: UINT,
Flags: D3D12_ROOT_DESCRIPTOR_FLAGS,
}}
UNION! {union D3D12_ROOT_PARAMETER1_u {
[u32; 3] [u64; 2],
DescriptorTable DescriptorTable_mut: D3D12_ROOT_DESCRIPTOR_TABLE1,
Constants Constants_mut: D3D12_ROOT_CONSTANTS,
Descriptor Descriptor_mut: D3D12_ROOT_DESCRIPTOR1,
}}
STRUCT! {struct D3D12_ROOT_PARAMETER1 {
ParameterType: D3D12_ROOT_PARAMETER_TYPE,
u: D3D12_ROOT_PARAMETER1_u,
ShaderVisibility: D3D12_SHADER_VISIBILITY,
}}
STRUCT! {struct D3D12_ROOT_SIGNATURE_DESC1 {
NumParameters: UINT,
pParameters: *const D3D12_ROOT_PARAMETER1,
NumStaticSamplers: UINT,
pStaticSamplers: *const D3D12_STATIC_SAMPLER_DESC,
Flags: D3D12_ROOT_SIGNATURE_FLAGS,
}}
UNION! {union D3D12_VERSIONED_ROOT_SIGNATURE_DESC_u {
[u32; 5] [u64; 5],
Desc_1_0 Desc_1_0_mut: D3D12_ROOT_SIGNATURE_DESC,
Desc_1_1 Desc_1_1_mut: D3D12_ROOT_SIGNATURE_DESC1,
}}
STRUCT! {struct D3D12_VERSIONED_ROOT_SIGNATURE_DESC {
Version: UINT,
u: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_u,
}}
RIDL! {#[uuid(0x34ab647b, 0x3cc8, 0x46ac, 0x84, 0x1b, 0xc0, 0x96, 0x56, 0x45, 0xc0, 0x46)]
interface ID3D12RootSignatureDeserializer(ID3D12RootSignatureDeserializerVtbl):
IUnknown(IUnknownVtbl) {
fn GetRootSignatureDesc() -> *const D3D12_ROOT_SIGNATURE_DESC,
}}
RIDL! {#[uuid(0x7f91ce67, 0x090c, 0x4bb7, 0xb7, 0x8e, 0xed, 0x8f, 0xf2, 0xe3, 0x1d, 0xa0)]
interface ID3D12VersionedRootSignatureDeserializer(ID3D12VersionedRootSignatureDeserializerVtbl):
IUnknown(IUnknownVtbl) {
fn GetRootSignatureDescAtVersion(
convertToVersion: D3D_ROOT_SIGNATURE_VERSION,
ppDesc: *mut *mut D3D12_VERSIONED_ROOT_SIGNATURE_DESC,
) -> HRESULT,
fn GetUnconvertedRootSignatureDesc() -> *const D3D12_VERSIONED_ROOT_SIGNATURE_DESC,
}}
FN! {stdcall PFN_D3D12_SERIALIZE_ROOT_SIGNATURE(
pRootSignature: *const D3D12_ROOT_SIGNATURE_DESC,
Version: D3D_ROOT_SIGNATURE_VERSION,
ppBlob: *mut *mut ID3DBlob,
ppErrorBlob: *mut *mut ID3DBlob,
) -> HRESULT}
extern "system" {
pub fn D3D12SerializeRootSignature(
pRootSignature: *const D3D12_ROOT_SIGNATURE_DESC,
Version: D3D_ROOT_SIGNATURE_VERSION,
ppBlob: *mut *mut ID3DBlob,
ppErrorBlob: *mut *mut ID3DBlob,
) -> HRESULT;
}
FN! {stdcall PFN_D3D12_CREATE_ROOT_SIGNATURE_DESERIALIZER(
pSrcData: LPCVOID,
SrcDataSizeInBytes: SIZE_T,
pRootSignatureDeserializerInterface: REFIID,
ppRootSignatureDeserializer: *mut *mut c_void,
) -> HRESULT}
extern "system" {
pub fn D3D12CreateRootSignatureDeserializer(
pSrcData: LPCVOID,
SrcDataSizeInBytes: SIZE_T,
pRootSignatureDeserializerInterface: REFGUID,
ppRootSignatureDeserializer: *mut *mut c_void,
) -> HRESULT;
}
FN! {stdcall PFN_D3D12_SERIALIZE_VERSIONED_ROOT_SIGNATURE(
pRootSignature: *const D3D12_VERSIONED_ROOT_SIGNATURE_DESC,
ppBlob: *mut *mut ID3DBlob,
ppErrorBlob: *mut *mut ID3DBlob,
) -> HRESULT}
extern "system" {
pub fn D3D12SerializeVersionedRootSignature(
pRootSignature: *const D3D12_VERSIONED_ROOT_SIGNATURE_DESC,
ppBlob: *mut *mut ID3DBlob,
ppErrorBlob: *mut *mut ID3DBlob,
) -> HRESULT;
}
FN! {stdcall PFN_D3D12_CREATE_VERSIONED_ROOT_SIGNATURE_DESERIALIZER(
pSrcData: LPCVOID,
SrcDataSizeInBytes: SIZE_T,
pRootSignatureDeserializerInterface: REFIID,
ppRootSignatureDeserializer: *mut *mut c_void,
) -> HRESULT}
extern "system" {
pub fn D3D12CreateVersionedRootSignatureDeserializer(
pSrcData: LPCVOID,
SrcDataSizeInBytes: SIZE_T,
pRootSignatureDeserializerInterface: REFIID,
ppRootSignatureDeserializer: *mut *mut c_void,
) -> HRESULT;
}
STRUCT! {struct D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: SIZE_T,
}}
STRUCT! {struct D3D12_GPU_DESCRIPTOR_HANDLE {
ptr: UINT64,
}}
STRUCT! {struct D3D12_DISCARD_REGION {
NumRects: UINT,
pRects: *const D3D12_RECT,
FirstSubresource: UINT,
NumSubresources: UINT,
}}
ENUM! {enum D3D12_QUERY_HEAP_TYPE {
D3D12_QUERY_HEAP_TYPE_OCCLUSION = 0,
D3D12_QUERY_HEAP_TYPE_TIMESTAMP = 1,
D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS = 2,
D3D12_QUERY_HEAP_TYPE_SO_STATISTICS = 3,
D3D12_QUERY_HEAP_TYPE_VIDEO_DECODE_STATISTICS = 4,
D3D12_QUERY_HEAP_TYPE_COPY_QUEUE_TIMESTAMP = 5,
D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS1 = 7,
}}
STRUCT! {struct D3D12_QUERY_HEAP_DESC {
Type: D3D12_QUERY_HEAP_TYPE,
Count: UINT,
NodeMask: UINT,
}}
ENUM! {enum D3D12_QUERY_TYPE {
D3D12_QUERY_TYPE_OCCLUSION = 0,
D3D12_QUERY_TYPE_BINARY_OCCLUSION = 1,
D3D12_QUERY_TYPE_TIMESTAMP = 2,
D3D12_QUERY_TYPE_PIPELINE_STATISTICS = 3,
D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0 = 4,
D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1 = 5,
D3D12_QUERY_TYPE_SO_STATISTICS_STREAM2 = 6,
D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3 = 7,
D3D12_QUERY_TYPE_VIDEO_DECODE_STATISTICS = 8,
D3D12_QUERY_TYPE_PIPELINE_STATISTICS1 = 10,
}}
ENUM! {enum D3D12_PREDICATION_OP {
D3D12_PREDICATION_OP_EQUAL_ZERO = 0,
D3D12_PREDICATION_OP_NOT_EQUAL_ZERO = 1,
}}
STRUCT! {struct D3D12_QUERY_DATA_PIPELINE_STATISTICS {
IAVertices: UINT64,
IAPrimitives: UINT64,
VSInvocations: UINT64,
GSInvocations: UINT64,
GSPrimitives: UINT64,
CInvocations: UINT64,
CPrimitives: UINT64,
PSInvocations: UINT64,
HSInvocations: UINT64,
DSInvocations: UINT64,
CSInvocations: UINT64,
}}
STRUCT! {struct D3D12_QUERY_DATA_PIPELINE_STATISTICS1 {
IAVertices: UINT64,
IAPrimitives: UINT64,
VSInvocations: UINT64,
GSInvocations: UINT64,
GSPrimitives: UINT64,
CInvocations: UINT64,
CPrimitives: UINT64,
PSInvocations: UINT64,
HSInvocations: UINT64,
DSInvocations: UINT64,
CSInvocations: UINT64,
ASInvocations: UINT64,
MSInvocations: UINT64,
MSPrimitives: UINT64,
}}
STRUCT! {struct D3D12_QUERY_DATA_SO_STATISTICS {
NumPrimitivesWritten: UINT64,
PrimitivesStorageNeeded: UINT64,
}}
STRUCT! {struct D3D12_STREAM_OUTPUT_BUFFER_VIEW {
BufferLocation: D3D12_GPU_VIRTUAL_ADDRESS,
SizeInBytes: UINT64,
BufferFilledSizeLocation: D3D12_GPU_VIRTUAL_ADDRESS,
}}
STRUCT! {struct D3D12_DRAW_ARGUMENTS {
VertexCountPerInstance: UINT,
InstanceCount: UINT,
StartVertexLocation: UINT,
StartInstanceLocation: UINT,
}}
STRUCT! {struct D3D12_DRAW_INDEXED_ARGUMENTS {
IndexCountPerInstance: UINT,
InstanceCount: UINT,
StartIndexLocation: UINT,
BaseVertexLocation: INT,
StartInstanceLocation: UINT,
}}
STRUCT! {struct D3D12_DISPATCH_ARGUMENTS {
ThreadGroupCountX: UINT,
ThreadGroupCountY: UINT,
ThreadGroupCountZ: UINT,
}}
STRUCT! {struct D3D12_VERTEX_BUFFER_VIEW {
BufferLocation: D3D12_GPU_VIRTUAL_ADDRESS,
SizeInBytes: UINT,
StrideInBytes: UINT,
}}
STRUCT! {struct D3D12_INDEX_BUFFER_VIEW {
BufferLocation: D3D12_GPU_VIRTUAL_ADDRESS,
SizeInBytes: UINT,
Format: DXGI_FORMAT,
}}
ENUM! {enum D3D12_INDIRECT_ARGUMENT_TYPE {
D3D12_INDIRECT_ARGUMENT_TYPE_DRAW = 0,
D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED = 1,
D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH = 2,
D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW = 3,
D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW = 4,
D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT = 5,
D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW = 6,
D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW = 7,
D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW = 8,
}}
STRUCT! {struct D3D12_INDIRECT_ARGUMENT_DESC_VertexBuffer {
Slot: UINT,
}}
STRUCT! {struct D3D12_INDIRECT_ARGUMENT_DESC_Constant {
RootParameterIndex: UINT,
DestOffsetIn32BitValues: UINT,
Num32BitValuesToSet: UINT,
}}
STRUCT! {struct D3D12_INDIRECT_ARGUMENT_DESC_ConstantBufferView {
RootParameterIndex: UINT,
}}
STRUCT! {struct D3D12_INDIRECT_ARGUMENT_DESC_ShaderResourceView {
RootParameterIndex: UINT,
}}
STRUCT! {struct D3D12_INDIRECT_ARGUMENT_DESC_UnorderedAccessView {
RootParameterIndex: UINT,
}}
UNION! {union D3D12_INDIRECT_ARGUMENT_DESC_u {
[u32; 3],
VertexBuffer VertexBuffer_mut: D3D12_INDIRECT_ARGUMENT_DESC_VertexBuffer,
Constant Constant_mut: D3D12_INDIRECT_ARGUMENT_DESC_Constant,
ConstantBufferView ConstantBufferView_mut: D3D12_INDIRECT_ARGUMENT_DESC_ConstantBufferView,
ShaderResourceView ShaderResourceView_mut: D3D12_INDIRECT_ARGUMENT_DESC_ShaderResourceView,
UnorderedAccessView UnorderedAccessView_mut: D3D12_INDIRECT_ARGUMENT_DESC_UnorderedAccessView,
}}
STRUCT! {struct D3D12_INDIRECT_ARGUMENT_DESC {
Type: D3D12_INDIRECT_ARGUMENT_TYPE,
u: D3D12_INDIRECT_ARGUMENT_DESC_u,
}}
STRUCT! {struct D3D12_COMMAND_SIGNATURE_DESC {
ByteStride: UINT,
NumArgumentDescs: UINT,
pArgumentDescs: *const D3D12_INDIRECT_ARGUMENT_DESC,
NodeMask: UINT,
}}
RIDL! {#[uuid(0xc4fec28f, 0x7966, 0x4e95, 0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8)]
interface ID3D12Object(ID3D12ObjectVtbl): IUnknown(IUnknownVtbl) {
fn GetPrivateData(
guid: REFGUID,
pDataSize: *mut UINT,
pData: *mut c_void,
) -> HRESULT,
fn SetPrivateData(
guid: REFGUID,
DataSize: UINT,
pData: *const c_void,
) -> HRESULT,
fn SetPrivateDataInterface(
guid: REFGUID,
pData: *const IUnknown,
) -> HRESULT,
fn SetName(
Name: LPCWSTR,
) -> HRESULT,
}}
RIDL! {#[uuid(0x905db94b, 0xa00c, 0x4140, 0x9d, 0xf5, 0x2b, 0x64, 0xca, 0x9e, 0xa3, 0x57)]
interface ID3D12DeviceChild(ID3D12DeviceChildVtbl): ID3D12Object(ID3D12ObjectVtbl) {
fn GetDevice(
riid: REFIID,
ppvDevice: *mut *mut c_void,
) -> HRESULT,
}}
RIDL! {#[uuid(0x63ee58fb, 0x1268, 0x4835, 0x86, 0xda, 0xf0, 0x08, 0xce, 0x62, 0xf0, 0xd6)]
interface ID3D12Pageable(ID3D12PageableVtbl): ID3D12DeviceChild(ID3D12DeviceChildVtbl) {}}
RIDL! {#[uuid(0x6b3b2502, 0x6e51, 0x45b3, 0x90, 0xee, 0x98, 0x84, 0x26, 0x5e, 0x8d, 0xf3)]
interface ID3D12Heap(ID3D12HeapVtbl): ID3D12Pageable(ID3D12PageableVtbl) {
#[fixme] fn GetDesc() -> D3D12_HEAP_DESC,
}}
RIDL! {#[uuid(0x696442be, 0xa72e, 0x4059, 0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad)]
interface ID3D12Resource(ID3D12ResourceVtbl): ID3D12Pageable(ID3D12PageableVtbl) {
fn Map(
Subresource: UINT,
pReadRange: *const D3D12_RANGE,
ppData: *mut *mut c_void,
) -> HRESULT,
fn Unmap(
Subresource: UINT,
pWrittenRange: *const D3D12_RANGE,
) -> (),
#[fixme] fn GetDesc() -> D3D12_RESOURCE_DESC,
fn GetGPUVirtualAddress() -> D3D12_GPU_VIRTUAL_ADDRESS,
fn WriteToSubresource(
DstSubresource: UINT,
pDstBox: *const D3D12_BOX,
pSrcData: *const c_void,
SrcRowPitch: UINT,
SrcDepthPitch: UINT,
) -> HRESULT,
fn ReadFromSubresource(
pDstData: *mut c_void,
DstRowPitch: UINT,
DstDepthPitch: UINT,
SrcSubresource: UINT,
pSrcBox: *const D3D12_BOX,
) -> HRESULT,
fn GetHeapProperties(
pHeapProperties: *mut D3D12_HEAP_PROPERTIES,
pHeapFlags: *mut D3D12_HEAP_FLAGS,
) -> HRESULT,
}}
RIDL! {#[uuid(0x6102dee4, 0xaf59, 0x4b09, 0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24)]
interface ID3D12CommandAllocator(ID3D12CommandAllocatorVtbl): ID3D12Pageable(ID3D12PageableVtbl) {
fn Reset() -> HRESULT,
}}
RIDL! {#[uuid(0x0a753dcf, 0xc4d8, 0x4b91, 0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76)]
interface ID3D12Fence(ID3D12FenceVtbl): ID3D12Pageable(ID3D12PageableVtbl) {
fn GetCompletedValue() -> UINT64,
fn SetEventOnCompletion(
Value: UINT64,
hEvent: HANDLE,
) -> HRESULT,
fn Signal(
Value: UINT64,
) -> HRESULT,
}}
RIDL! {#[uuid(0x433685fe, 0xe22b, 0x4ca0, 0xa8, 0xdb, 0xb5, 0xb4, 0xf4, 0xdd, 0x0e, 0x4a)]
interface ID3D12Fence1(ID3D12Fence1Vtbl): ID3D12Fence(ID3D12FenceVtbl) {
fn GetCreationFlags() -> D3D12_FENCE_FLAGS,
}}
RIDL! {#[uuid(0x765a30f3, 0xf624, 0x4c6f, 0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45)]
interface ID3D12PipelineState(ID3D12PipelineStateVtbl): ID3D12Pageable(ID3D12PageableVtbl) {
fn GetCachedBlob(
ppBlob: *mut *mut ID3DBlob,
) -> HRESULT,
}}
RIDL! {#[uuid(0x8efb471d, 0x616c, 0x4f49, 0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51)]
interface ID3D12DescriptorHeap(ID3D12DescriptorHeapVtbl): ID3D12Pageable(ID3D12PageableVtbl) {
#[fixme] fn GetDesc() -> D3D12_DESCRIPTOR_HEAP_DESC,
#[fixme] fn GetCPUDescriptorHandleForHeapStart() -> D3D12_CPU_DESCRIPTOR_HANDLE,
#[fixme] fn GetGPUDescriptorHandleForHeapStart() -> D3D12_GPU_DESCRIPTOR_HANDLE,
}}
RIDL! {#[uuid(0x0d9658ae, 0xed45, 0x469e, 0xa6, 0x1d, 0x97, 0x0e, 0xc5, 0x83, 0xca, 0xb4)]
interface ID3D12QueryHeap(ID3D12QueryHeapVtbl): ID3D12Pageable(ID3D12PageableVtbl) {}}
RIDL! {#[uuid(0xc36a797c, 0xec80, 0x4f0a, 0x89, 0x85, 0xa7, 0xb2, 0x47, 0x50, 0x82, 0xd1)]
interface ID3D12CommandSignature(ID3D12CommandSignatureVtbl):
ID3D12Pageable(ID3D12PageableVtbl) {}}
RIDL! {#[uuid(0x7116d91c, 0xe7e4, 0x47ce, 0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5)]
interface ID3D12CommandList(ID3D12CommandListVtbl): ID3D12DeviceChild(ID3D12DeviceChildVtbl) {
fn GetType() -> D3D12_COMMAND_LIST_TYPE,
}}
RIDL! {#[uuid(0x5b160d0f, 0xac1b, 0x4185, 0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55)]
interface ID3D12GraphicsCommandList(ID3D12GraphicsCommandListVtbl):
ID3D12CommandList(ID3D12CommandListVtbl) {
fn Close() -> HRESULT,
fn Reset(
pAllocator: *mut ID3D12CommandAllocator,
pInitialState: *mut ID3D12PipelineState,
) -> HRESULT,
fn ClearState(
pPipelineState: *mut ID3D12PipelineState,
) -> (),
fn DrawInstanced(
VertexCountPerInstance: UINT,
InstanceCount: UINT,
StartVertexLocation: UINT,
StartInstanceLocation: UINT,
) -> (),
fn DrawIndexedInstanced(
IndexCountPerInstance: UINT,
InstanceCount: UINT,
StartIndexLocation: UINT,
BaseVertexLocation: INT,
StartInstanceLocation: UINT,
) -> (),
fn Dispatch(
ThreadGroupCountX: UINT,
ThreadGroupCountY: UINT,
ThreadGroupCountZ: UINT,
) -> (),
fn CopyBufferRegion(
pDstBuffer: *mut ID3D12Resource,
DstOffset: UINT64,
pSrcBuffer: *mut ID3D12Resource,
SrcOffset: UINT64,
NumBytes: UINT64,
) -> (),
fn CopyTextureRegion(
pDst: *const D3D12_TEXTURE_COPY_LOCATION,
DstX: UINT,
DstY: UINT,
DstZ: UINT,
pSrc: *const D3D12_TEXTURE_COPY_LOCATION,
pSrcBox: *const D3D12_BOX,
) -> (),
fn CopyResource(
pDstResource: *mut ID3D12Resource,
pSrcResource: *mut ID3D12Resource,
) -> (),
fn CopyTiles(
pTiledResource: *mut ID3D12Resource,
pTileRegionStartCoordinate: *const D3D12_TILED_RESOURCE_COORDINATE,
pTileRegionSize: *const D3D12_TILE_REGION_SIZE,
pBuffer: *mut ID3D12Resource,
BufferStartOffsetInBytes: UINT64,
Flags: D3D12_TILE_COPY_FLAGS,
) -> (),
fn ResolveSubresource(
pDstResource: *mut ID3D12Resource,
DstSubresource: UINT,
pSrcResource: *mut ID3D12Resource,
SrcSubresource: UINT,
Format: DXGI_FORMAT,
) -> (),
fn IASetPrimitiveTopology(
PrimitiveTopology: D3D12_PRIMITIVE_TOPOLOGY,
) -> (),
fn RSSetViewports(
NumViewports: UINT,
pViewports: *const D3D12_VIEWPORT,
) -> (),
fn RSSetScissorRects(
NumRects: UINT,
pRects: *const D3D12_RECT,
) -> (),
fn OMSetBlendFactor(
BlendFactor: *const [FLOAT; 4],
) -> (),
fn OMSetStencilRef(
StencilRef: UINT,
) -> (),
fn SetPipelineState(
pPipelineState: *mut ID3D12PipelineState,
) -> (),
fn ResourceBarrier(
NumBarriers: UINT,
pBarriers: *const D3D12_RESOURCE_BARRIER,
) -> (),
fn ExecuteBundle(
pCommandList: *mut ID3D12GraphicsCommandList,
) -> (),
fn SetDescriptorHeaps(
NumDescriptorHeaps: UINT,
ppDescriptorHeaps: *mut *mut ID3D12DescriptorHeap,
) -> (),
fn SetComputeRootSignature(
pRootSignature: *mut ID3D12RootSignature,
) -> (),
fn SetGraphicsRootSignature(
pRootSignature: *mut ID3D12RootSignature,
) -> (),
fn SetComputeRootDescriptorTable(
RootParameterIndex: UINT,
BaseDescriptor: D3D12_GPU_DESCRIPTOR_HANDLE,
) -> (),
fn SetGraphicsRootDescriptorTable(
RootParameterIndex: UINT,
BaseDescriptor: D3D12_GPU_DESCRIPTOR_HANDLE,
) -> (),
fn SetComputeRoot32BitConstant(
RootParameterIndex: UINT,
SrcData: UINT,
DestOffsetIn32BitValues: UINT,
) -> (),
fn SetGraphicsRoot32BitConstant(
RootParameterIndex: UINT,
SrcData: UINT,
DestOffsetIn32BitValues: UINT,
) -> (),
fn SetComputeRoot32BitConstants(
RootParameterIndex: UINT,
Num32BitValuesToSet: UINT,
pSrcData: *const c_void,
DestOffsetIn32BitValues: UINT,
) -> (),
fn SetGraphicsRoot32BitConstants(
RootParameterIndex: UINT,
Num32BitValuesToSet: UINT,
pSrcData: *const c_void,
DestOffsetIn32BitValues: UINT,
) -> (),
fn SetComputeRootConstantBufferView(
RootParameterIndex: UINT,
BufferLocation: D3D12_GPU_VIRTUAL_ADDRESS,
) -> (),
fn SetGraphicsRootConstantBufferView(
RootParameterIndex: UINT,
BufferLocation: D3D12_GPU_VIRTUAL_ADDRESS,
) -> (),
fn SetComputeRootShaderResourceView(
RootParameterIndex: UINT,
BufferLocation: D3D12_GPU_VIRTUAL_ADDRESS,
) -> (),
fn SetGraphicsRootShaderResourceView(
RootParameterIndex: UINT,
BufferLocation: D3D12_GPU_VIRTUAL_ADDRESS,
) -> (),
fn SetComputeRootUnorderedAccessView(
RootParameterIndex: UINT,
BufferLocation: D3D12_GPU_VIRTUAL_ADDRESS,
) -> (),
fn SetGraphicsRootUnorderedAccessView(
RootParameterIndex: UINT,
BufferLocation: D3D12_GPU_VIRTUAL_ADDRESS,
) -> (),
fn IASetIndexBuffer(
pView: *const D3D12_INDEX_BUFFER_VIEW,
) -> (),
fn IASetVertexBuffers(
StartSlot: UINT,
NumViews: UINT,
pViews: *const D3D12_VERTEX_BUFFER_VIEW,
) -> (),
fn SOSetTargets(
StartSlot: UINT,
NumViews: UINT,
pViews: *const D3D12_STREAM_OUTPUT_BUFFER_VIEW,
) -> (),
fn OMSetRenderTargets(
NumRenderTargetDescriptors: UINT,
pRenderTargetDescriptors: *const D3D12_CPU_DESCRIPTOR_HANDLE,
RTsSingleHandleToDescriptorRange: BOOL,
pDepthStencilDescriptor: *const D3D12_CPU_DESCRIPTOR_HANDLE,
) -> (),
fn ClearDepthStencilView(
DepthStencilView: D3D12_CPU_DESCRIPTOR_HANDLE,
ClearFlags: D3D12_CLEAR_FLAGS,
Depth: FLOAT,
Stencil: UINT8,
NumRects: UINT,
pRects: *const D3D12_RECT,
) -> (),
fn ClearRenderTargetView(
RenderTargetView: D3D12_CPU_DESCRIPTOR_HANDLE,
ColorRGBA: *const [FLOAT; 4],
NumRects: UINT,
pRects: *const D3D12_RECT,
) -> (),
fn ClearUnorderedAccessViewUint(
ViewGPUHandleInCurrentHeap: D3D12_GPU_DESCRIPTOR_HANDLE,
ViewCPUHandle: D3D12_CPU_DESCRIPTOR_HANDLE,
pResource: *mut ID3D12Resource,
Values: *const [UINT; 4],
NumRects: UINT,
pRects: *const D3D12_RECT,
) -> (),
fn ClearUnorderedAccessViewFloat(
ViewGPUHandleInCurrentHeap: D3D12_GPU_DESCRIPTOR_HANDLE,
ViewCPUHandle: D3D12_CPU_DESCRIPTOR_HANDLE,
pResource: *mut ID3D12Resource,
Values: *const [FLOAT; 4],
NumRects: UINT,
pRects: *const D3D12_RECT,
) -> (),
fn DiscardResource(
pResource: *mut ID3D12Resource,
pRegion: *const D3D12_DISCARD_REGION,
) -> (),
fn BeginQuery(
pQueryHeap: *mut ID3D12QueryHeap,
Type: D3D12_QUERY_TYPE,
Index: UINT,
) -> (),
fn EndQuery(
pQueryHeap: *mut ID3D12QueryHeap,
Type: D3D12_QUERY_TYPE,
Index: UINT,
) -> (),
fn ResolveQueryData(
pQueryHeap: *mut ID3D12QueryHeap,
Type: D3D12_QUERY_TYPE,
StartIndex: UINT,
NumQueries: UINT,
pDestinationBuffer: *mut ID3D12Resource,
AlignedDestinationBufferOffset: UINT64,
) -> (),
fn SetPredication(
pBuffer: *mut ID3D12Resource,
AlignedBufferOffset: UINT64,
Operation: D3D12_PREDICATION_OP,
) -> (),
fn SetMarker(
Metadata: UINT,
pData: *const c_void,
Size: UINT,
) -> (),
fn BeginEvent(
Metadata: UINT,
pData: *const c_void,
Size: UINT,
) -> (),
fn EndEvent() -> (),
fn ExecuteIndirect(
pCommandSignature: *mut ID3D12CommandSignature,
MaxCommandCount: UINT,
pArgumentBuffer: *mut ID3D12Resource,
ArgumentBufferOffset: UINT64,
pCountBuffer: *mut ID3D12Resource,
CountBufferOffset: UINT64,
) -> (),
}}
RIDL! {#[uuid(0x553103fb, 0x1fe7, 0x4557, 0xbb, 0x38, 0x94, 0x6d, 0x7d, 0x0e, 0x7c, 0xa7)]
interface ID3D12GraphicsCommandList1(ID3D12GraphicsCommandList1Vtbl):
ID3D12GraphicsCommandList(ID3D12GraphicsCommandListVtbl) {
fn AtomicCopyBufferUINT(
pDstBuffer: *mut ID3D12Resource,
DstOffset: UINT64,
pSrcBuffer: *mut ID3D12Resource,
SrcOffset: UINT64,
Dependencies: UINT,
ppDependentResources: *const *mut ID3D12Resource,
pDependentSubresourceRanges: *mut D3D12_SUBRESOURCE_RANGE_UINT64,
) -> (),
fn AtomicCopyBufferUINT64(
pDstBuffer: *mut ID3D12Resource,
DstOffset: UINT64,
pSrcBuffer: *mut ID3D12Resource,
SrcOffset: UINT64,
Dependencies: UINT,
ppDependentResources: *const *mut ID3D12Resource,
pDependentSubresourceRanges: *mut D3D12_SUBRESOURCE_RANGE_UINT64,
) -> (),
fn OMSetDepthBounds(
Min: FLOAT,
Max: FLOAT,
) -> (),
fn SetSamplePositions(
NumSamplesPerPixel: UINT,
NumPixels: UINT,
pSamplePositions: *mut D3D12_SAMPLE_POSITION,
) -> (),
fn ResolveSubresourceRegion(
pDstResource: *mut ID3D12Resource,
DstSubresource: UINT,
DstX: UINT,
DstY: UINT,
pSrcResource: *mut ID3D12Resource,
SrcSubresource: UINT,
pSrcRect: *mut D3D12_RECT,
Format: DXGI_FORMAT,
ResolveMode: D3D12_RESOLVE_MODE,
) -> (),
fn SetViewInstanceMask(
Mask: UINT,
) -> (),
}}
STRUCT! {struct D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
Dest: D3D12_GPU_VIRTUAL_ADDRESS,
Value: UINT32,
}}
ENUM! {enum D3D12_WRITEBUFFERIMMEDIATE_MODE {
D3D12_WRITEBUFFERIMMEDIATE_MODE_DEFAULT = 0,
D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN = 0x1,
D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT = 0x2,
}}
RIDL! {#[uuid(0x38C3E585, 0xFF17, 0x412C, 0x91, 0x50, 0x4F, 0xC6, 0xF9, 0xD7, 0x2A, 0x28)]
interface ID3D12GraphicsCommandList2(ID3D12GraphicsCommandList2Vtbl)
: ID3D12GraphicsCommandList1(ID3D12GraphicsCommandList1Vtbl) {
fn WriteBufferImmediate(
Count: UINT,
pParams: *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER,
pModes: *const D3D12_WRITEBUFFERIMMEDIATE_MODE,
) -> (),
}}
RIDL! {#[uuid(0x0ec870a6, 0x5d7e, 0x4c22, 0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed)]
interface ID3D12CommandQueue(ID3D12CommandQueueVtbl): ID3D12Pageable(ID3D12PageableVtbl) {
fn UpdateTileMappings(
pResource: *mut ID3D12Resource,
NumResourceRegions: UINT,
pResourceRegionStartCoordinates: *const D3D12_TILED_RESOURCE_COORDINATE,
pResourceRegionSizes: *const D3D12_TILE_REGION_SIZE,
pHeap: *mut ID3D12Heap,
NumRanges: UINT,
pRangeFlags: *const D3D12_TILE_RANGE_FLAGS,
pHeapRangeStartOffsets: *const UINT,
pRangeTileCounts: *const UINT,
Flags: D3D12_TILE_MAPPING_FLAGS,
) -> (),
fn CopyTileMappings(
pDstResource: *mut ID3D12Resource,
pDstRegionStartCoordinate: *const D3D12_TILED_RESOURCE_COORDINATE,
pSrcResource: *mut ID3D12Resource,
pSrcRegionStartCoordinate: *const D3D12_TILED_RESOURCE_COORDINATE,
pRegionSize: *const D3D12_TILE_REGION_SIZE,
Flags: D3D12_TILE_MAPPING_FLAGS,
) -> (),
fn ExecuteCommandLists(
NumCommandLists: UINT,
ppCommandLists: *const *mut ID3D12CommandList,
) -> (),
fn SetMarker(
Metadata: UINT,
pData: *const c_void,
Size: UINT,
) -> (),
fn BeginEvent(
Metadata: UINT,
pData: *const c_void,
Size: UINT,
) -> (),
fn EndEvent() -> (),
fn Signal(
pFence: *mut ID3D12Fence,
Value: UINT64,
) -> HRESULT,
fn Wait(
pFence: *mut ID3D12Fence,
Value: UINT64,
) -> HRESULT,
fn GetTimestampFrequency(
pFrequency: *mut UINT64,
) -> HRESULT,
fn GetClockCalibration(
pGpuTimestamp: *mut UINT64,
pCpuTimestamp: *mut UINT64,
) -> HRESULT,
#[fixme] fn GetDesc() -> D3D12_COMMAND_QUEUE_DESC,
}}
RIDL! {#[uuid(0x189819f1, 0x1db6, 0x4b57, 0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7)]
interface ID3D12Device(ID3D12DeviceVtbl): ID3D12Object(ID3D12ObjectVtbl) {
fn GetNodeCount() -> UINT,
fn CreateCommandQueue(
pDesc: *const D3D12_COMMAND_QUEUE_DESC,
riid: REFGUID,
ppCommandQueue: *mut *mut c_void,
) -> HRESULT,
fn CreateCommandAllocator(
type_: D3D12_COMMAND_LIST_TYPE,
riid: REFGUID,
ppCommandAllocator: *mut *mut c_void,
) -> HRESULT,
fn CreateGraphicsPipelineState(
pDesc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC,
riid: REFGUID,
ppPipelineState: *mut *mut c_void,
) -> HRESULT,
fn CreateComputePipelineState(
pDesc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC,
riid: REFGUID,
ppPipelineState: *mut *mut c_void,
) -> HRESULT,
fn CreateCommandList(
nodeMask: UINT,
type_: D3D12_COMMAND_LIST_TYPE,
pCommandAllocator: *mut ID3D12CommandAllocator,
pInitialState: *mut ID3D12PipelineState,
riid: REFGUID,
ppCommandList: *mut *mut c_void,
) -> HRESULT,
fn CheckFeatureSupport(
Feature: D3D12_FEATURE,
pFeatureSupportData: *mut c_void,
FeatureSupportDataSize: UINT,
) -> HRESULT,
fn CreateDescriptorHeap(
pDescriptorHeapDesc: *const D3D12_DESCRIPTOR_HEAP_DESC,
riid: REFGUID,
ppvHeap: *mut *mut c_void,
) -> HRESULT,
fn GetDescriptorHandleIncrementSize(
DescriptorHeapType: D3D12_DESCRIPTOR_HEAP_TYPE,
) -> UINT,
fn CreateRootSignature(
nodeMask: UINT,
pBlobWithRootSignature: *const c_void,
blobLengthInBytes: SIZE_T,
riid: REFGUID,
ppvRootSignature: *mut *mut c_void,
) -> HRESULT,
fn CreateConstantBufferView(
pDesc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC,
DestDescriptor: D3D12_CPU_DESCRIPTOR_HANDLE,
) -> (),
fn CreateShaderResourceView(
pResource: *mut ID3D12Resource,
pDesc: *const D3D12_SHADER_RESOURCE_VIEW_DESC,
DestDescriptor: D3D12_CPU_DESCRIPTOR_HANDLE,
) -> (),
fn CreateUnorderedAccessView(
pResource: *mut ID3D12Resource,
pCounterResource: *mut ID3D12Resource,
pDesc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC,
DestDescriptor: D3D12_CPU_DESCRIPTOR_HANDLE,
) -> (),
fn CreateRenderTargetView(
pResource: *mut ID3D12Resource,
pDesc: *const D3D12_RENDER_TARGET_VIEW_DESC,
DestDescriptor: D3D12_CPU_DESCRIPTOR_HANDLE,
) -> (),
fn CreateDepthStencilView(
pResource: *mut ID3D12Resource,
pDesc: *const D3D12_DEPTH_STENCIL_VIEW_DESC,
DestDescriptor: D3D12_CPU_DESCRIPTOR_HANDLE,
) -> (),
fn CreateSampler(
pDesc: *const D3D12_SAMPLER_DESC,
DestDescriptor: D3D12_CPU_DESCRIPTOR_HANDLE,
) -> (),
fn CopyDescriptors(
NumDestDescriptorRanges: UINT,
pDestDescriptorRangeStarts: *const D3D12_CPU_DESCRIPTOR_HANDLE,
pDestDescriptorRangeSizes: *const UINT,
NumSrcDescriptorRanges: UINT,
pSrcDescriptorRangeStarts: *const D3D12_CPU_DESCRIPTOR_HANDLE,
pSrcDescriptorRangeSizes: *const UINT,
DescriptorHeapsType: D3D12_DESCRIPTOR_HEAP_TYPE,
) -> (),
fn CopyDescriptorsSimple(
NumDescriptors: UINT,
DestDescriptorRangeStart: D3D12_CPU_DESCRIPTOR_HANDLE,
SrcDescriptorRangeStart: D3D12_CPU_DESCRIPTOR_HANDLE,
DescriptorHeapsType: D3D12_DESCRIPTOR_HEAP_TYPE,
) -> (),
#[fixme] fn GetResourceAllocationInfo(
visibleMask: UINT,
numResourceDescs: UINT,
pResourceDescs: *const D3D12_RESOURCE_DESC,
) -> D3D12_RESOURCE_ALLOCATION_INFO,
#[fixme] fn GetCustomHeapProperties(
nodeMask: UINT,
heapType: D3D12_HEAP_TYPE,
) -> D3D12_HEAP_PROPERTIES,
fn CreateCommittedResource(
pHeapProperties: *const D3D12_HEAP_PROPERTIES,
HeapFlags: D3D12_HEAP_FLAGS,
pResourceDesc: *const D3D12_RESOURCE_DESC,
InitialResourceState: D3D12_RESOURCE_STATES,
pOptimizedClearValue: *const D3D12_CLEAR_VALUE,
riidResource: REFGUID,
ppvResource: *mut *mut c_void,
) -> HRESULT,
fn CreateHeap(
pDesc: *const D3D12_HEAP_DESC,
riid: REFGUID,
ppvHeap: *mut *mut c_void,
) -> HRESULT,
fn CreatePlacedResource(
pHeap: *mut ID3D12Heap,
HeapOffset: UINT64,
pDesc: *const D3D12_RESOURCE_DESC,
InitialState: D3D12_RESOURCE_STATES,
pOptimizedClearValue: *const D3D12_CLEAR_VALUE,
riid: REFGUID,
ppvResource: *mut *mut c_void,
) -> HRESULT,
fn CreateReservedResource(
pDesc: *const D3D12_RESOURCE_DESC,
InitialState: D3D12_RESOURCE_STATES,
pOptimizedClearValue: *const D3D12_CLEAR_VALUE,
riid: REFGUID,
ppvResource: *mut *mut c_void,
) -> HRESULT,
fn CreateSharedHandle(
pObject: *mut ID3D12DeviceChild,
pAttributes: *const SECURITY_ATTRIBUTES,
Access: DWORD,
Name: LPCWSTR,
pHandle: *mut HANDLE,
) -> HRESULT,
fn OpenSharedHandle(
NTHandle: HANDLE,
riid: REFGUID,
ppvObj: *mut *mut c_void,
) -> HRESULT,
fn OpenSharedHandleByName(
Name: LPCWSTR,
Access: DWORD,
pNTHandle: *mut HANDLE,
) -> HRESULT,
fn MakeResident(
NumObjects: UINT,
ppObjects: *mut *mut ID3D12Pageable,
) -> HRESULT,
fn Evict(
NumObjects: UINT,
ppObjects: *mut *mut ID3D12Pageable,
) -> HRESULT,
fn CreateFence(
InitialValue: UINT64,
Flags: D3D12_FENCE_FLAGS,
riid: REFGUID,
ppFence: *mut *mut c_void,
) -> HRESULT,
fn GetDeviceRemovedReason() -> HRESULT,
fn GetCopyableFootprints(
pResourceDesc: *const D3D12_RESOURCE_DESC,
FirstSubresource: UINT,
NumSubresources: UINT,
BaseOffset: UINT64,
pLayouts: *mut D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
pNumRows: *mut UINT,
pRowSizeInBytes: *mut UINT64,
pTotalBytes: *mut UINT64,
) -> (),
fn CreateQueryHeap(
pDesc: *const D3D12_QUERY_HEAP_DESC,
riid: REFGUID,
ppvHeap: *mut *mut c_void,
) -> HRESULT,
fn SetStablePowerState(
Enable: BOOL,
) -> HRESULT,
fn CreateCommandSignature(
pDesc: *const D3D12_COMMAND_SIGNATURE_DESC,
pRootSignature: *mut ID3D12RootSignature,
riid: REFGUID,
ppvCommandSignature: *mut *mut c_void,
) -> HRESULT,
fn GetResourceTiling(
pTiledResource: *mut ID3D12Resource,
pNumTilesForEntireResource: *mut UINT,
pPackedMipDesc: *mut D3D12_PACKED_MIP_INFO,
pStandardTileShapeForNonPackedMips: *mut D3D12_TILE_SHAPE,
pNumSubresourceTilings: *mut UINT,
FirstSubresourceTilingToGet: UINT,
pSubresourceTilingsForNonPackedMips: *mut D3D12_SUBRESOURCE_TILING,
) -> (),
#[fixme] fn GetAdapterLuid() -> LUID,
}}
RIDL! {#[uuid(0xc64226a8, 0x9201, 0x46af, 0xb4, 0xcc, 0x53, 0xfb, 0x9f, 0xf7, 0x41, 0x4f)]
interface ID3D12PipelineLibrary(ID3D12PipelineLibraryVtbl):
ID3D12DeviceChild(ID3D12DeviceChildVtbl) {
fn StorePipeline(
pName: LPCWSTR,
pPipeline: *mut ID3D12PipelineState,
) -> HRESULT,
fn LoadGraphicsPipeline(
pName: LPCWSTR,
pDesc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC,
riid: REFIID,
ppPipelineState: *mut *mut c_void,
) -> HRESULT,
fn LoadComputePipeline(
pName: LPCWSTR,
pDesc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC,
riid: REFIID,
ppPipelineState: *mut *mut c_void,
) -> HRESULT,
fn GetSerializedSize() -> SIZE_T,
fn Serialize(
pData: *mut c_void,
DataSizeInBytes: SIZE_T,
) -> HRESULT,
}}
RIDL! {#[uuid(0x80eabf42, 0x2568, 0x4e5e, 0xbd, 0x82, 0xc3, 0x7f, 0x86, 0x96, 0x1d, 0xc3)]
interface ID3D12PipelineLibrary1(ID3D12PipelineLibrary1Vtbl):
ID3D12PipelineLibrary(ID3D12PipelineLibraryVtbl) {
fn LoadPipeline(
pName: LPCWSTR,
pDesc: *const D3D12_PIPELINE_STATE_STREAM_DESC,
riid: REFIID,
ppPipelineState: *mut *mut c_void,
) -> HRESULT,
}}
ENUM! {enum D3D12_MULTIPLE_FENCE_WAIT_FLAGS {
D3D12_MULTIPLE_FENCE_WAIT_FLAG_NONE = 0,
D3D12_MULTIPLE_FENCE_WAIT_FLAG_ANY = 0x1,
D3D12_MULTIPLE_FENCE_WAIT_FLAG_ALL = 0,
}}
ENUM! {enum D3D12_RESIDENCY_PRIORITY {
D3D12_RESIDENCY_PRIORITY_MINIMUM = 0x28000000,
D3D12_RESIDENCY_PRIORITY_LOW = 0x50000000,
D3D12_RESIDENCY_PRIORITY_NORMAL = 0x78000000,
D3D12_RESIDENCY_PRIORITY_HIGH = 0xa0010000,
D3D12_RESIDENCY_PRIORITY_MAXIMUM = 0xc8000000,
}}
RIDL! {#[uuid(0x77acce80, 0x638e, 0x4e65, 0x88, 0x95, 0xc1, 0xf2, 0x33, 0x86, 0x86, 0x3e)]
interface ID3D12Device1(ID3D12Device1Vtbl): ID3D12Device(ID3D12DeviceVtbl) {
fn CreatePipelineLibrary(
pLibraryBlob: *const c_void,
BlobLength: SIZE_T,
riid: REFIID,
ppPipelineLibrary: *mut *mut c_void,
) -> HRESULT,
fn SetEventOnMultipleFenceCompletion(
ppFences: *const *mut ID3D12Fence,
pFenceValues: *const UINT64,
NumFences: UINT,
Flags: D3D12_MULTIPLE_FENCE_WAIT_FLAGS,
hEvent: HANDLE,
) -> HRESULT,
fn SetResidencyPriority(
NumObjects: UINT,
ppObjects: *const *mut ID3D12Pageable,
pPriorities: *const D3D12_RESIDENCY_PRIORITY,
) -> HRESULT,
}}
RIDL! {#[uuid(0x30baa41e, 0xb15b, 0x475c, 0xa0, 0xbb, 0x1a, 0xf5, 0xc5, 0xb6, 0x43, 0x28)]
interface ID3D12Device2(ID3D12Device2Vtbl): ID3D12Device1(ID3D12Device1Vtbl) {
fn CreatePipelineState(
pDesc: *const D3D12_PIPELINE_STATE_STREAM_DESC,
riid: REFIID,
ppPipelineState: *mut *mut c_void,
) -> HRESULT,
}}
ENUM! {enum D3D12_RESIDENCY_FLAGS {
D3D12_RESIDENCY_FLAG_NONE = 0,
D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET = 0x1,
}}
RIDL! {#[uuid(0x81dadc15, 0x2bad, 0x4392, 0x93, 0xc5, 0x10, 0x13, 0x45, 0xc4, 0xaa, 0x98)]
interface ID3D12Device3(ID3D12Device3Vtbl): ID3D12Device2(ID3D12Device2Vtbl) {
fn OpenExistingHeapFromAddress(
pAddress: *const c_void,
riid: REFIID,
ppvHeap: *mut *mut c_void,
) -> HRESULT,
fn OpenExistingHeapFromFileMapping(
hFileMapping: HANDLE,
riid: REFIID,
ppvHeap: *mut *mut c_void,
) -> HRESULT,
fn EnqueueMakeResident(
Flags: D3D12_RESIDENCY_FLAGS,
NumObjects: UINT,
ppObjects: *const *mut ID3D12Pageable,
pFenceToSignal: *mut ID3D12Fence,
FenceValueToSignal: UINT64,
) -> HRESULT,
}}
ENUM! {enum D3D12_COMMAND_LIST_FLAGS {
D3D12_COMMAND_LIST_FLAG_NONE = 0,
}}
ENUM! {enum D3D12_COMMAND_POOL_FLAGS {
D3D12_COMMAND_POOL_FLAG_NONE = 0,
}}
ENUM! {enum D3D12_COMMAND_RECORDER_FLAGS {
D3D12_COMMAND_RECORDER_FLAG_NONE = 0,
}}
ENUM! {enum D3D12_PROTECTED_SESSION_STATUS {
D3D12_PROTECTED_SESSION_STATUS_OK = 0,
D3D12_PROTECTED_SESSION_STATUS_INVALID = 1,
}}
RIDL! {#[uuid(0xA1533D18, 0x0AC1, 0x4084, 0x85, 0xB9, 0x89, 0xA9, 0x61, 0x16, 0x80, 0x6B)]
interface ID3D12ProtectedSession(ID3D12ProtectedSessionVtbl)
: ID3D12DeviceChild(ID3D12DeviceChildVtbl) {
fn GetStatusFence(
riid: REFIID,
ppFence: *mut *mut c_void,
) -> HRESULT,
fn GetSessionStatus() -> D3D12_PROTECTED_SESSION_STATUS,
}}
ENUM! {enum D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAGS {
D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAG_NONE = 0,
D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAG_SUPPORTED = 0x1,
}}
STRUCT! {struct D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT {
NodeIndex: UINT,
Support: D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAGS,
}}
ENUM! {enum D3D12_PROTECTED_RESOURCE_SESSION_FLAGS {
D3D12_PROTECTED_RESOURCE_SESSION_FLAG_NONE = 0,
}}
STRUCT! {struct D3D12_PROTECTED_RESOURCE_SESSION_DESC {
NodeMask: UINT,
Flags: D3D12_PROTECTED_RESOURCE_SESSION_FLAGS,
}}
RIDL! {#[uuid(0x6CD696F4, 0xF289, 0x40CC, 0x80, 0x91, 0x5A, 0x6C, 0xA0, 0x09, 0x9C, 0x3D)]
interface ID3D12ProtectedResourceSession(ID3D12ProtectedResourceSessionVtbl)
: ID3D12ProtectedSession(ID3D12ProtectedSessionVtbl) {
fn GetDesc() -> D3D12_PROTECTED_RESOURCE_SESSION_DESC,
}}
RIDL! {#[uuid(0xe865df17, 0xa9ee, 0x46f9, 0xa4, 0x63, 0x30, 0x98, 0x31, 0x5a, 0xa2, 0xe5)]
interface ID3D12Device4(ID3D12Device4Vtbl): ID3D12Device3(ID3D12Device3Vtbl) {
fn CreateCommandList1(
nodeMask: UINT,
cmdlist_type: D3D12_COMMAND_LIST_TYPE,
flags: D3D12_COMMAND_LIST_FLAGS,
riid: REFIID,
ppCommandList: *mut *mut c_void,
) -> HRESULT,
fn CreateProtectedResourceSession(
pDesc: *const D3D12_PROTECTED_RESOURCE_SESSION_DESC,
riid: REFIID,
ppSession: *mut *mut c_void,
) -> HRESULT,
fn CreateCommittedResource1(
pHeapProperties: *const D3D12_HEAP_PROPERTIES,
HeapFlags: D3D12_HEAP_FLAGS,
pDesc: *const D3D12_RESOURCE_DESC,
InitialResourceState: D3D12_RESOURCE_STATES,
pOptimizedClearValue: *const D3D12_CLEAR_VALUE,
pProtectedSession: *mut ID3D12ProtectedResourceSession,
riidResource: REFIID,
ppvResource: *mut *mut c_void,
) -> HRESULT,
fn CreateHeap1(
pDesc: *const D3D12_HEAP_DESC,
pProtectedSession: *mut ID3D12ProtectedResourceSession,
riid: REFIID,
ppvHeap: *mut *mut c_void,
) -> HRESULT,
fn CreateReservedResource1(
pDesc: *const D3D12_RESOURCE_DESC,
InitialState: D3D12_RESOURCE_STATES,
pOptimizedClearValue: *const D3D12_CLEAR_VALUE,
pProtectedSession: *mut ID3D12ProtectedResourceSession,
riid: REFIID,
ppvResource: *mut *mut c_void,
) -> HRESULT,
fn GetResourceAllocationInfo1(
visibleMask: UINT,
numResourceDescs: UINT,
pResourceDescs: *const D3D12_RESOURCE_DESC,
pResourceAllocationInfo1: *mut D3D12_RESOURCE_ALLOCATION_INFO1,
) -> D3D12_RESOURCE_ALLOCATION_INFO,
}}
ENUM! {enum D3D12_LIFETIME_STATE {
D3D12_LIFETIME_STATE_IN_USE = 0,
D3D12_LIFETIME_STATE_NOT_IN_USE = 1,
}}
RIDL! {#[uuid(0xe667af9f, 0xcd56, 0x4f46, 0x83, 0xce, 0x03, 0x2e, 0x59, 0x5d, 0x70, 0xa8)]
interface ID3D12LifetimeOwner(ID3D12LifetimeOwnerVtlb): IUnknown(IUnknownVtbl) {
fn LifetimeStateUpdated(
NewState: D3D12_LIFETIME_STATE,
) -> (),
}}
RIDL! {#[uuid(0xf1df64b6, 0x57fd, 0x49cd, 0x88, 0x07, 0xc0, 0xeb, 0x88, 0xb4, 0x5c, 0x8f)]
interface ID3D12SwapChainAssistant(ID3D12SwapChainAssistantVtlb): IUnknown(IUnknownVtbl) {
fn GetLUID() -> LUID,
fn GetSwapChainObject(
riid: REFIID,
ppv: *mut *mut c_void,
) -> HRESULT,
fn GetCurrentResourceAndCommandQueue(
riidResource: REFIID,
ppvResource: *mut *mut c_void,
riidQueue: REFIID,
ppvQueue: *mut *mut c_void,
) -> HRESULT,
fn InsertImplicitSync() -> HRESULT,
}}
RIDL! {#[uuid(0x3fd03d36, 0x4eb1, 0x424a, 0xa5, 0x82, 0x49, 0x4e, 0xcb, 0x8b, 0xa8, 0x13)]
interface ID3D12LifetimeTracker(ID3D12LifetimeTrackerVtbl)
: ID3D12DeviceChild(ID3D12DeviceChildVtbl) {
fn DestroyOwnedObject(
pObject: *mut ID3D12DeviceChild,
) -> HRESULT,
}}
ENUM! {enum D3D12_META_COMMAND_PARAMETER_TYPE {
D3D12_META_COMMAND_PARAMETER_TYPE_FLOAT = 0,
D3D12_META_COMMAND_PARAMETER_TYPE_UINT64 = 1,
D3D12_META_COMMAND_PARAMETER_TYPE_GPU_VIRTUAL_ADDRESS = 2,
D3D12_META_COMMAND_PARAMETER_TYPE_CPU_DESCRIPTOR_HANDLE_HEAP_TYPE_CBV_SRV_UAV = 3,
D3D12_META_COMMAND_PARAMETER_TYPE_GPU_DESCRIPTOR_HANDLE_HEAP_TYPE_CBV_SRV_UAV = 4,
}}
ENUM! {enum D3D12_META_COMMAND_PARAMETER_FLAGS {
D3D12_META_COMMAND_PARAMETER_FLAG_INPUT = 0x1,
D3D12_META_COMMAND_PARAMETER_FLAG_OUTPUT = 0x2,
}}
ENUM! {enum D3D12_META_COMMAND_PARAMETER_STAGE {
D3D12_META_COMMAND_PARAMETER_STAGE_CREATION = 0,
D3D12_META_COMMAND_PARAMETER_STAGE_INITIALIZATION = 1,
D3D12_META_COMMAND_PARAMETER_STAGE_EXECUTION = 2,
}}
STRUCT! {struct D3D12_META_COMMAND_PARAMETER_DESC {
Name: LPCWSTR,
Type: D3D12_META_COMMAND_PARAMETER_TYPE,
Flags: D3D12_META_COMMAND_PARAMETER_FLAGS,
RequiredResourceState: D3D12_RESOURCE_STATES,
StructureOffset: UINT,
}}
ENUM! {enum D3D12_GRAPHICS_STATES {
D3D12_GRAPHICS_STATE_NONE = 0,
D3D12_GRAPHICS_STATE_IA_VERTEX_BUFFERS = 1 << 0,
D3D12_GRAPHICS_STATE_IA_INDEX_BUFFER = 1 << 1,
D3D12_GRAPHICS_STATE_IA_PRIMITIVE_TOPOLOGY = 1 << 2,
D3D12_GRAPHICS_STATE_DESCRIPTOR_HEAP = 1 << 3,
D3D12_GRAPHICS_STATE_GRAPHICS_ROOT_SIGNATURE = 1 << 4,
D3D12_GRAPHICS_STATE_COMPUTE_ROOT_SIGNATURE = 1 << 5,
D3D12_GRAPHICS_STATE_RS_VIEWPORTS = 1 << 6,
D3D12_GRAPHICS_STATE_RS_SCISSOR_RECTS = 1 << 7,
D3D12_GRAPHICS_STATE_PREDICATION = 1 << 8,
D3D12_GRAPHICS_STATE_OM_RENDER_TARGETS = 1 << 9,
D3D12_GRAPHICS_STATE_OM_STENCIL_REF = 1 << 10,
D3D12_GRAPHICS_STATE_OM_BLEND_FACTOR = 1 << 11,
D3D12_GRAPHICS_STATE_PIPELINE_STATE = 1 << 12,
D3D12_GRAPHICS_STATE_SO_TARGETS = 1 << 13,
D3D12_GRAPHICS_STATE_OM_DEPTH_BOUNDS = 1 << 14,
D3D12_GRAPHICS_STATE_SAMPLE_POSITIONS = 1 << 15,
D3D12_GRAPHICS_STATE_VIEW_INSTANCE_MASK = 1 << 16,
}}
STRUCT! {struct D3D12_META_COMMAND_DESC {
Id: GUID,
Name: LPCWSTR,
InitializationDirtyState: D3D12_GRAPHICS_STATES,
ExecutionDirtyState: D3D12_GRAPHICS_STATES,
}}
RIDL! {#[uuid(0x47016943, 0xfca8, 0x4594, 0x93, 0xea, 0xaf, 0x25, 0x8b, 0x55, 0x34, 0x6d)]
interface ID3D12StateObject(ID3D12StateObjectVtbl): ID3D12Pageable(ID3D12PageableVtbl) {}}
RIDL! {#[uuid(0xde5fa827, 0x9bf9, 0x4f26, 0x89, 0xff, 0xd7, 0xf5, 0x6f, 0xde, 0x38, 0x60)]
interface ID3D12StateObjectProperties(ID3D12StateObjectPropertiesVtbl): IUnknown(IUnknownVtbl) {
fn GetShaderIdentifier(
pExportName: LPCWSTR,
) -> *mut c_void,
fn GetShaderStackSize(
pExportName: LPCWSTR,
) -> UINT64,
fn GetPipelineStackSize() -> UINT64,
fn SetPipelineStackSize(
PipelineStackSizeInBytes: UINT64,
) -> (),
}}
ENUM! {enum D3D12_STATE_SUBOBJECT_TYPE {
D3D12_STATE_SUBOBJECT_TYPE_STATE_OBJECT_CONFIG = 0,
D3D12_STATE_SUBOBJECT_TYPE_GLOBAL_ROOT_SIGNATURE = 1,
D3D12_STATE_SUBOBJECT_TYPE_LOCAL_ROOT_SIGNATURE = 2,
D3D12_STATE_SUBOBJECT_TYPE_NODE_MASK = 3,
D3D12_STATE_SUBOBJECT_TYPE_DXIL_LIBRARY = 5,
D3D12_STATE_SUBOBJECT_TYPE_EXISTING_COLLECTION = 6,
D3D12_STATE_SUBOBJECT_TYPE_SUBOBJECT_TO_EXPORTS_ASSOCIATION = 7,
D3D12_STATE_SUBOBJECT_TYPE_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION = 8,
D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_SHADER_CONFIG = 9,
D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_PIPELINE_CONFIG = 10,
D3D12_STATE_SUBOBJECT_TYPE_HIT_GROUP = 11,
D3D12_STATE_SUBOBJECT_TYPE_MAX_VALID = 12,
}}
STRUCT! {struct D3D12_STATE_SUBOBJECT {
Type: D3D12_STATE_SUBOBJECT_TYPE,
pDesc: *const c_void,
}}
ENUM! {enum D3D12_STATE_OBJECT_FLAGS {
D3D12_STATE_OBJECT_FLAG_NONE = 0,
D3D12_STATE_OBJECT_FLAG_ALLOW_LOCAL_DEPENDENCIES_ON_EXTERNAL_DEFINITIONS = 0x1,
D3D12_STATE_OBJECT_FLAG_ALLOW_EXTERNAL_DEPENDENCIES_ON_LOCAL_DEFINITIONS = 0x2,
}}
STRUCT! {struct D3D12_STATE_OBJECT_CONFIG {
Flags: D3D12_STATE_OBJECT_FLAGS,
}}
STRUCT! {struct D3D12_GLOBAL_ROOT_SIGNATURE {
pGlobalRootSignature: *mut ID3D12RootSignature,
}}
STRUCT! {struct D3D12_LOCAL_ROOT_SIGNATURE {
pLocalRootSignature: *mut ID3D12RootSignature,
}}
STRUCT! {struct D3D12_NODE_MASK {
NodeMask: UINT,
}}
ENUM! {enum D3D12_EXPORT_FLAGS {
D3D12_EXPORT_FLAG_NONE = 0,
}}
STRUCT! {struct D3D12_EXPORT_DESC {
Name: LPCWSTR,
ExportToRename: LPCWSTR,
Flags: D3D12_EXPORT_FLAGS,
}}
STRUCT! {struct D3D12_DXIL_LIBRARY_DESC {
DXILLibrary: D3D12_SHADER_BYTECODE,
NumExports: UINT,
pExports: *mut D3D12_EXPORT_DESC,
}}
STRUCT! {struct D3D12_EXISTING_COLLECTION_DESC {
pExistingCollection: * mut ID3D12StateObject,
NumExports: UINT,
pExports: *mut D3D12_EXPORT_DESC,
}}
STRUCT! {struct D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION {
pSubobjectToAssociate: *const D3D12_STATE_SUBOBJECT,
NumExports: UINT,
pExports: *mut LPCWSTR,
}}
STRUCT! {struct D3D12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION {
SubobjectToAssociate: LPCWSTR,
NumExports: UINT,
pExports: *mut LPCWSTR,
}}
ENUM! {enum D3D12_HIT_GROUP_TYPE {
D3D12_HIT_GROUP_TYPE_TRIANGLES = 0,
D3D12_HIT_GROUP_TYPE_PROCEDURAL_PRIMITIVE = 0x1,
}}
STRUCT! {struct D3D12_HIT_GROUP_DESC {
HitGroupExport: LPCWSTR,
Type: D3D12_HIT_GROUP_TYPE,
AnyHitShaderImport: LPCWSTR,
ClosestHitShaderImport: LPCWSTR,
IntersectionShaderImport: LPCWSTR,
}}
STRUCT! {struct D3D12_RAYTRACING_SHADER_CONFIG {
MaxPayloadSizeInBytes: UINT,
MaxAttributeSizeInBytes: UINT,
}}
STRUCT! {struct D3D12_RAYTRACING_PIPELINE_CONFIG {
MaxTraceRecursionDepth: UINT,
}}
ENUM! {enum D3D12_STATE_OBJECT_TYPE {
D3D12_STATE_OBJECT_TYPE_COLLECTION = 0,
D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE = 3,
}}
STRUCT! {struct D3D12_STATE_OBJECT_DESC {
Type: D3D12_STATE_OBJECT_TYPE,
NumSubobjects: UINT,
pSubobjects: *const D3D12_STATE_SUBOBJECT,
}}
ENUM! {enum D3D12_RAYTRACING_GEOMETRY_FLAGS {
D3D12_RAYTRACING_GEOMETRY_FLAG_NONE = 0,
D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE = 0x1,
D3D12_RAYTRACING_GEOMETRY_FLAG_NO_DUPLICATE_ANYHIT_INVOCATION = 0x2,
}}
ENUM! {enum D3D12_RAYTRACING_GEOMETRY_TYPE {
D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES = 0,
D3D12_RAYTRACING_GEOMETRY_TYPE_PROCEDURAL_PRIMITIVE_AABBS = 1,
}}
ENUM! {enum D3D12_RAYTRACING_INSTANCE_FLAGS {
D3D12_RAYTRACING_INSTANCE_FLAG_NONE = 0,
D3D12_RAYTRACING_INSTANCE_FLAG_TRIANGLE_CULL_DISABLE = 0x1,
D3D12_RAYTRACING_INSTANCE_FLAG_TRIANGLE_FRONT_COUNTERCLOCKWISE = 0x2,
D3D12_RAYTRACING_INSTANCE_FLAG_FORCE_OPAQUE = 0x4,
D3D12_RAYTRACING_INSTANCE_FLAG_FORCE_NON_OPAQUE = 0x8,
}}
STRUCT! {struct D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE {
StartAddress: D3D12_GPU_VIRTUAL_ADDRESS,
StrideInBytes: UINT64,
}}
STRUCT! {struct D3D12_GPU_VIRTUAL_ADDRESS_RANGE {
StartAddress: D3D12_GPU_VIRTUAL_ADDRESS,
SizeInBytes: UINT64,
}}
STRUCT! {struct D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE {
StartAddress: D3D12_GPU_VIRTUAL_ADDRESS,
SizeInBytes: UINT64,
StrideInBytes: UINT64,
}}
STRUCT! {struct D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC {
Transform3x4: D3D12_GPU_VIRTUAL_ADDRESS,
IndexFormat: DXGI_FORMAT,
VertexFormat: DXGI_FORMAT,
IndexCount: UINT,
VertexCount: UINT,
IndexBuffer: D3D12_GPU_VIRTUAL_ADDRESS,
VertexBuffer: D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE,
}}
STRUCT! {struct D3D12_RAYTRACING_AABB {
MinX: FLOAT,
MinY: FLOAT,
MinZ: FLOAT,
MaxX: FLOAT,
MaxY: FLOAT,
MaxZ: FLOAT,
}}
STRUCT! {struct D3D12_RAYTRACING_GEOMETRY_AABBS_DESC {
AABBCount: UINT64,
AABBs: D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE,
}}
ENUM! {enum D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS {
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_NONE = 0,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE = 0x1,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_COMPACTION = 0x2,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE = 0x4,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_BUILD = 0x8,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY = 0x10,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE = 0x20,
}}
ENUM! {enum D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE {
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE = 0,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT = 0x1,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_VISUALIZATION_DECODE_FOR_TOOLS = 0x2,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_SERIALIZE = 0x3,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_DESERIALIZE = 0x4,
}}
ENUM! {enum D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE {
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL = 0,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL = 0x1,
}}
ENUM! {enum D3D12_ELEMENTS_LAYOUT {
D3D12_ELEMENTS_LAYOUT_ARRAY = 0,
D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS = 0x1,
}}
ENUM! {enum D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE {
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE = 0,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION = 0x1,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION = 0x2,
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE = 0x3,
}}
STRUCT! {struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC {
DestBuffer: D3D12_GPU_VIRTUAL_ADDRESS,
InfoType: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE,
}}
STRUCT! {struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE_DESC {
CompactedSizeInBytes: UINT64,
}}
STRUCT! {struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION_DESC {
DecodedSizeInBytes: UINT64,
}}
STRUCT! {struct D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_TOOLS_VISUALIZATION_HEADER {
Type: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE,
NumDescs: UINT,
}}
STRUCT! {struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION_DESC {
SerializedSizeInBytes: UINT64,
NumBottomLevelAccelerationStructurePointers: UINT64,
}}
STRUCT! {struct D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER {
DriverOpaqueGUID: GUID,
DriverOpaqueVersioningData: [BYTE; 16],
}}
ENUM! {enum D3D12_SERIALIZED_DATA_TYPE {
D3D12_SERIALIZED_DATA_RAYTRACING_ACCELERATION_STRUCTURE = 0,
}}
ENUM! {enum D3D12_DRIVER_MATCHING_IDENTIFIER_STATUS {
D3D12_DRIVER_MATCHING_IDENTIFIER_COMPATIBLE_WITH_DEVICE = 0,
D3D12_DRIVER_MATCHING_IDENTIFIER_UNSUPPORTED_TYPE = 0x1,
D3D12_DRIVER_MATCHING_IDENTIFIER_UNRECOGNIZED = 0x2,
D3D12_DRIVER_MATCHING_IDENTIFIER_INCOMPATIBLE_VERSION = 0x3,
D3D12_DRIVER_MATCHING_IDENTIFIER_INCOMPATIBLE_TYPE = 0x4,
}}
STRUCT! {struct D3D12_SERIALIZED_RAYTRACING_ACCELERATION_STRUCTURE_HEADER {
DriverMatchingIdentifier: D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER,
SerializedSizeInBytesIncludingHeader: UINT64,
DeserializedSizeInBytes: UINT64,
NumBottomLevelAccelerationStructurePointersAfterHeader: UINT64,
}}
STRUCT! {struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE_DESC {
CurrentSizeInBytes: UINT64,
}}
STRUCT! {struct D3D12_RAYTRACING_INSTANCE_DESC {
Transform: [[FLOAT; 4]; 3],
InstanceID_24_InstanceMask_8: UINT,
InstanceContributionToHitGroupIndex_24_Flags_8: UINT,
AccelerationStructure: D3D12_GPU_VIRTUAL_ADDRESS,
}}
UNION! {union D3D12_RAYTRACING_GEOMETRY_DESC_u {
[u64; 6],
Triangles Triangles_mut: D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC,
AABBs AABBs_mut: D3D12_RAYTRACING_GEOMETRY_AABBS_DESC,
}}
STRUCT! {struct D3D12_RAYTRACING_GEOMETRY_DESC {
Type: D3D12_RAYTRACING_GEOMETRY_TYPE,
Flags: D3D12_RAYTRACING_GEOMETRY_FLAGS,
u: D3D12_RAYTRACING_GEOMETRY_DESC_u,
}}
UNION! {union D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_u {
[u64; 1],
InstanceDescs InstanceDescs_mut: D3D12_GPU_VIRTUAL_ADDRESS,
pGeometryDescs pGeometryDescs_mut: *const D3D12_RAYTRACING_GEOMETRY_DESC,
ppGeometryDescs ppGeometryDescs_mut: *const *mut D3D12_RAYTRACING_GEOMETRY_DESC,
}}
STRUCT! {struct D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS {
Type: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE,
Flags: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS,
NumDescs: UINT,
DescsLayout: D3D12_ELEMENTS_LAYOUT,
u: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_u,
}}
STRUCT! {struct D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC {
DestAccelerationStructureData: D3D12_GPU_VIRTUAL_ADDRESS,
Inputs: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS,
SourceAccelerationStructureData: D3D12_GPU_VIRTUAL_ADDRESS,
ScratchAccelerationStructureData: D3D12_GPU_VIRTUAL_ADDRESS,
}}
STRUCT! {struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO {
ResultDataMaxSizeInBytes: UINT64,
ScratchDataSizeInBytes: UINT64,
UpdateScratchDataSizeInBytes: UINT64,
}}
ENUM! {enum D3D12_RAY_FLAGS {
D3D12_RAY_FLAG_NONE = 0,
D3D12_RAY_FLAG_FORCE_OPAQUE = 0x1,
D3D12_RAY_FLAG_FORCE_NON_OPAQUE = 0x2,
D3D12_RAY_FLAG_ACCEPT_FIRST_HIT_AND_END_SEARCH = 0x4,
D3D12_RAY_FLAG_SKIP_CLOSEST_HIT_SHADER = 0x8,
D3D12_RAY_FLAG_CULL_BACK_FACING_TRIANGLES = 0x10,
D3D12_RAY_FLAG_CULL_FRONT_FACING_TRIANGLES = 0x20,
D3D12_RAY_FLAG_CULL_OPAQUE = 0x40,
D3D12_RAY_FLAG_CULL_NON_OPAQUE = 0x80,
}}
ENUM! {enum D3D12_HIT_KIND {
D3D12_HIT_KIND_TRIANGLE_FRONT_FACE = 0xfe,
D3D12_HIT_KIND_TRIANGLE_BACK_FACE = 0xff,
}}
RIDL! {#[uuid(0x8b4f173b, 0x2fea, 0x4b80, 0x8f, 0x58, 0x43, 0x07, 0x19, 0x1a, 0xb9, 0x5d)]
interface ID3D12Device5(ID3D12Device5Vtbl) : ID3D12Device4(ID3D12Device4Vtbl) {
fn CreateLifetimeTracker(
pOwner: *mut ID3D12LifetimeOwner,
riid: REFIID,
ppvTracker: *mut *mut c_void,
) -> HRESULT,
fn RemoveDevice() -> (),
fn EnumerateMetaCommands(
pNumMetaCommands: *mut UINT,
pDescs: *mut D3D12_META_COMMAND_DESC,
) -> HRESULT,
fn EnumerateMetaCommandParameters(
CommandId: REFGUID,
Stage: D3D12_META_COMMAND_PARAMETER_STAGE,
pTotalStructureSizeInBytes: *mut UINT,
pParameterCount: *mut UINT,
pParameterDescs: *mut D3D12_META_COMMAND_PARAMETER_DESC,
) -> HRESULT,
fn CreateMetaCommand(
CommandId: REFGUID,
NodeMask: UINT,
pCreationParametersData: *const c_void,
CreationParametersDataSizeInBytes: SIZE_T,
riid: REFIID,
ppMetaCommand: *mut *mut c_void,
) -> HRESULT,
fn CreateStateObject(
pDesc: *const D3D12_STATE_OBJECT_DESC,
riid: REFIID,
ppStateObject: *mut *mut c_void,
) -> HRESULT,
fn GetRaytracingAccelerationStructurePrebuildInfo(
pDesc: *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS,
pInfo: *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO,
) -> (),
fn CheckDriverMatchingIdentifier(
SerializedDataType: D3D12_SERIALIZED_DATA_TYPE,
pIdentifierToCheck: *const D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER,
) -> D3D12_DRIVER_MATCHING_IDENTIFIER_STATUS,
}}
ENUM! {enum D3D12_AUTO_BREADCRUMB_OP {
D3D12_AUTO_BREADCRUMB_OP_SETMARKER = 0,
D3D12_AUTO_BREADCRUMB_OP_BEGINEVENT = 1,
D3D12_AUTO_BREADCRUMB_OP_ENDEVENT = 2,
D3D12_AUTO_BREADCRUMB_OP_DRAWINSTANCED = 3,
D3D12_AUTO_BREADCRUMB_OP_DRAWINDEXEDINSTANCED = 4,
D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT = 5,
D3D12_AUTO_BREADCRUMB_OP_DISPATCH = 6,
D3D12_AUTO_BREADCRUMB_OP_COPYBUFFERREGION = 7,
D3D12_AUTO_BREADCRUMB_OP_COPYTEXTUREREGION = 8,
D3D12_AUTO_BREADCRUMB_OP_COPYRESOURCE = 9,
D3D12_AUTO_BREADCRUMB_OP_COPYTILES = 10,
D3D12_AUTO_BREADCRUMB_OP_RESOLVESUBRESOURCE = 11,
D3D12_AUTO_BREADCRUMB_OP_CLEARRENDERTARGETVIEW = 12,
D3D12_AUTO_BREADCRUMB_OP_CLEARUNORDEREDACCESSVIEW = 13,
D3D12_AUTO_BREADCRUMB_OP_CLEARDEPTHSTENCILVIEW = 14,
D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER = 15,
D3D12_AUTO_BREADCRUMB_OP_EXECUTEBUNDLE = 16,
D3D12_AUTO_BREADCRUMB_OP_PRESENT = 17,
D3D12_AUTO_BREADCRUMB_OP_RESOLVEQUERYDATA = 18,
D3D12_AUTO_BREADCRUMB_OP_BEGINSUBMISSION = 19,
D3D12_AUTO_BREADCRUMB_OP_ENDSUBMISSION = 20,
D3D12_AUTO_BREADCRUMB_OP_DECODEFRAME = 21,
D3D12_AUTO_BREADCRUMB_OP_PROCESSFRAMES = 22,
D3D12_AUTO_BREADCRUMB_OP_ATOMICCOPYBUFFERUINT = 23,
D3D12_AUTO_BREADCRUMB_OP_ATOMICCOPYBUFFERUINT64 = 24,
D3D12_AUTO_BREADCRUMB_OP_RESOLVESUBRESOURCEREGION = 25,
D3D12_AUTO_BREADCRUMB_OP_WRITEBUFFERIMMEDIATE = 26,
D3D12_AUTO_BREADCRUMB_OP_DECODEFRAME1 = 27,
D3D12_AUTO_BREADCRUMB_OP_SETPROTECTEDRESOURCESESSION = 28,
D3D12_AUTO_BREADCRUMB_OP_DECODEFRAME2 = 29,
D3D12_AUTO_BREADCRUMB_OP_PROCESSFRAMES1 = 30,
D3D12_AUTO_BREADCRUMB_OP_BUILDRAYTRACINGACCELERATIONSTRUCTURE = 31,
D3D12_AUTO_BREADCRUMB_OP_EMITRAYTRACINGACCELERATIONSTRUCTUREPOSTBUILDINFO = 32,
D3D12_AUTO_BREADCRUMB_OP_COPYRAYTRACINGACCELERATIONSTRUCTURE = 33,
D3D12_AUTO_BREADCRUMB_OP_DISPATCHRAYS = 34,
D3D12_AUTO_BREADCRUMB_OP_INITIALIZEMETACOMMAND = 35,
D3D12_AUTO_BREADCRUMB_OP_EXECUTEMETACOMMAND = 36,
D3D12_AUTO_BREADCRUMB_OP_ESTIMATEMOTION = 37,
D3D12_AUTO_BREADCRUMB_OP_RESOLVEMOTIONVECTORHEAP = 38,
D3D12_AUTO_BREADCRUMB_OP_SETPIPELINESTATE1 = 39,
D3D12_AUTO_BREADCRUMB_OP_INITIALIZEEXTENSIONCOMMAND = 40,
D3D12_AUTO_BREADCRUMB_OP_EXECUTEEXTENSIONCOMMAND = 41,
D3D12_AUTO_BREADCRUMB_OP_DISPATCHMESH = 42,
D3D12_AUTO_BREADCRUMB_OP_ENCODEFRAME = 43,
D3D12_AUTO_BREADCRUMB_OP_RESOLVEENCODEROUTPUTMETADATA = 44,
}}
STRUCT! {struct D3D12_AUTO_BREADCRUMB_NODE {
pCommandListDebugNameA: *const c_char,
pCommandListDebugNameW: *const wchar_t,
pCommandQueueDebugNameA: *const c_char,
pCommandQueueDebugNameW: *const wchar_t,
pCommandList: *mut ID3D12GraphicsCommandList,
pCommandQueue: *mut ID3D12CommandQueue,
BreadcrumbCount: UINT32,
pLastBreadcrumbValue: *const UINT32,
pCommandHistory: *const D3D12_AUTO_BREADCRUMB_OP,
pNext: *const D3D12_AUTO_BREADCRUMB_NODE,
}}
STRUCT! {struct D3D12_DRED_BREADCRUMB_CONTEXT {
BreadcrumbIndex: UINT,
pContextString: *const wchar_t,
}}
STRUCT! {struct D3D12_AUTO_BREADCRUMB_NODE1 {
pCommandListDebugNameA: *const char,
pCommandListDebugNameW: *const wchar_t,
pCommandQueueDebugNameA: *const c_char,
pCommandQueueDebugNameW: *const wchar_t,
pCommandList: *mut ID3D12GraphicsCommandList,
pCommandQueue: *mut ID3D12CommandQueue,
BreadcrumbCount: UINT32,
pLastBreadcrumbValue: *const UINT32,
pCommandHistory: *const D3D12_AUTO_BREADCRUMB_OP,
pNext: *const D3D12_AUTO_BREADCRUMB_NODE1,
BreadcrumbContextsCount: UINT,
pBreadcrumbContexts: *mut D3D12_DRED_BREADCRUMB_CONTEXT,
}}
ENUM! {enum D3D12_DRED_VERSION {
D3D12_DRED_VERSION_1_0 = 0x1,
D3D12_DRED_VERSION_1_1 = 0x2,
D3D12_DRED_VERSION_1_2 = 0x3,
D3D12_DRED_VERSION_1_3 = 0x4,
}}
ENUM! {enum D3D12_DRED_FLAGS {
D3D12_DRED_FLAG_NONE = 0,
D3D12_DRED_FLAG_FORCE_ENABLE = 1,
D3D12_DRED_FLAG_DISABLE_AUTOBREADCRUMBS = 2,
}}
ENUM! {enum D3D12_DRED_ENABLEMENT {
D3D12_DRED_ENABLEMENT_SYSTEM_CONTROLLED = 0,
D3D12_DRED_ENABLEMENT_FORCED_OFF = 1,
D3D12_DRED_ENABLEMENT_FORCED_ON = 2,
}}
STRUCT! {struct D3D12_DEVICE_REMOVED_EXTENDED_DATA {
Flags: D3D12_DRED_FLAGS,
pHeadAutoBreadcrumbNode: *mut D3D12_AUTO_BREADCRUMB_NODE,
}}
ENUM! {enum D3D12_DRED_ALLOCATION_TYPE {
D3D12_DRED_ALLOCATION_TYPE_COMMAND_QUEUE = 19,
D3D12_DRED_ALLOCATION_TYPE_COMMAND_ALLOCATOR = 20,
D3D12_DRED_ALLOCATION_TYPE_PIPELINE_STATE = 21,
D3D12_DRED_ALLOCATION_TYPE_COMMAND_LIST = 22,
D3D12_DRED_ALLOCATION_TYPE_FENCE = 23,
D3D12_DRED_ALLOCATION_TYPE_DESCRIPTOR_HEAP = 24,
D3D12_DRED_ALLOCATION_TYPE_HEAP = 25,
D3D12_DRED_ALLOCATION_TYPE_QUERY_HEAP = 27,
D3D12_DRED_ALLOCATION_TYPE_COMMAND_SIGNATURE = 28,
D3D12_DRED_ALLOCATION_TYPE_PIPELINE_LIBRARY = 29,
D3D12_DRED_ALLOCATION_TYPE_VIDEO_DECODER = 30,
D3D12_DRED_ALLOCATION_TYPE_VIDEO_PROCESSOR = 32,
D3D12_DRED_ALLOCATION_TYPE_RESOURCE = 34,
D3D12_DRED_ALLOCATION_TYPE_PASS = 35,
D3D12_DRED_ALLOCATION_TYPE_CRYPTOSESSION = 36,
D3D12_DRED_ALLOCATION_TYPE_CRYPTOSESSIONPOLICY = 37,
D3D12_DRED_ALLOCATION_TYPE_PROTECTEDRESOURCESESSION = 38,
D3D12_DRED_ALLOCATION_TYPE_VIDEO_DECODER_HEAP = 39,
D3D12_DRED_ALLOCATION_TYPE_COMMAND_POOL = 40,
D3D12_DRED_ALLOCATION_TYPE_COMMAND_RECORDER = 41,
D3D12_DRED_ALLOCATION_TYPE_STATE_OBJECT = 42,
D3D12_DRED_ALLOCATION_TYPE_METACOMMAND = 43,
D3D12_DRED_ALLOCATION_TYPE_SCHEDULINGGROUP = 44,
D3D12_DRED_ALLOCATION_TYPE_VIDEO_MOTION_ESTIMATOR = 45,
D3D12_DRED_ALLOCATION_TYPE_VIDEO_MOTION_VECTOR_HEAP = 46,
D3D12_DRED_ALLOCATION_TYPE_VIDEO_EXTENSION_COMMAND = 47,
D3D12_DRED_ALLOCATION_TYPE_VIDEO_ENCODER = 48,
D3D12_DRED_ALLOCATION_TYPE_VIDEO_ENCODER_HEAP = 49,
D3D12_DRED_ALLOCATION_TYPE_INVALID = 0xffffffff,
}}
STRUCT! {struct D3D12_DRED_ALLOCATION_NODE {
ObjectNameA: *const char,
ObjectNameW: *const wchar_t,
AllocationType: D3D12_DRED_ALLOCATION_TYPE,
pNext: *const D3D12_DRED_ALLOCATION_NODE,
}}
STRUCT! {struct D3D12_DRED_ALLOCATION_NODE1 {
ObjectNameA: *const char,
ObjectNameW: *const wchar_t,
AllocationType: D3D12_DRED_ALLOCATION_TYPE,
pNext: *const D3D12_DRED_ALLOCATION_NODE1,
pObject: *const IUnknown,
}}
STRUCT! {struct D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT {
pHeadAutoBreadcrumbNode: *const D3D12_AUTO_BREADCRUMB_NODE,
}}
STRUCT! {struct D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1 {
pHeadAutoBreadcrumbNode: *const D3D12_AUTO_BREADCRUMB_NODE1,
}}
STRUCT! {struct D3D12_DRED_PAGE_FAULT_OUTPUT {
PageFaultVA: D3D12_GPU_VIRTUAL_ADDRESS,
pHeadExistingAllocationNode: *const D3D12_DRED_ALLOCATION_NODE,
pHeadRecentFreedAllocationNode: *const D3D12_DRED_ALLOCATION_NODE,
}}
STRUCT! {struct D3D12_DRED_PAGE_FAULT_OUTPUT1 {
PageFaultVA: D3D12_GPU_VIRTUAL_ADDRESS,
pHeadExistingAllocationNode: *const D3D12_DRED_ALLOCATION_NODE1,
pHeadRecentFreedAllocationNode: *const D3D12_DRED_ALLOCATION_NODE1,
}}
ENUM! {enum D3D12_DRED_PAGE_FAULT_FLAGS {
D3D12_DRED_PAGE_FAULT_FLAGS_NONE = 0,
}}
ENUM! {enum D3D12_DRED_DEVICE_STATE {
D3D12_DRED_DEVICE_STATE_UNKNOWN = 0,
D3D12_DRED_DEVICE_STATE_HUNG = 3,
D3D12_DRED_DEVICE_STATE_FAULT = 6,
D3D12_DRED_DEVICE_STATE_PAGEFAULT = 7,
}}
STRUCT! {struct D3D12_DRED_PAGE_FAULT_OUTPUT2 {
PageFaultVA: D3D12_GPU_VIRTUAL_ADDRESS,
pHeadExistingAllocationNode: *const D3D12_DRED_ALLOCATION_NODE1,
pHeadRecentFreedAllocationNode: *const D3D12_DRED_ALLOCATION_NODE1,
PageFaultFlags: D3D12_DRED_PAGE_FAULT_FLAGS,
}}
STRUCT! {struct D3D12_DEVICE_REMOVED_EXTENDED_DATA1 {
DeviceRemovedReason: HRESULT,
AutoBreadcrumbsOutput: D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT,
PageFaultOutput: D3D12_DRED_PAGE_FAULT_OUTPUT,
}}
UNION! {union D3D12_VERSIONED_DEVICE_REMOVED_EXTENDED_DATA_u {
[u64; 5],
Dred_1_0 Dred_1_0_mut: D3D12_DEVICE_REMOVED_EXTENDED_DATA,
Dred_1_1 Dred_1_1_mut: D3D12_DEVICE_REMOVED_EXTENDED_DATA1,
Dred_1_2 Dred_1_2_mut: D3D12_DEVICE_REMOVED_EXTENDED_DATA2,
Dred_1_3 Dred_1_3_mut: D3D12_DEVICE_REMOVED_EXTENDED_DATA3,
}}
STRUCT! {struct D3D12_DEVICE_REMOVED_EXTENDED_DATA2 {
DeviceRemovedReason: HRESULT,
AutoBreadcrumbsOutput: D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1,
PageFaultOutput: D3D12_DRED_PAGE_FAULT_OUTPUT1,
}}
STRUCT! {struct D3D12_DEVICE_REMOVED_EXTENDED_DATA3 {
DeviceRemovedReason: HRESULT,
AutoBreadcrumbsOutput: D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1,
PageFaultOutput: D3D12_DRED_PAGE_FAULT_OUTPUT2,
DeviceState: D3D12_DRED_DEVICE_STATE,
}}
STRUCT! {struct D3D12_VERSIONED_DEVICE_REMOVED_EXTENDED_DATA {
Version: D3D12_DRED_VERSION,
u: D3D12_VERSIONED_DEVICE_REMOVED_EXTENDED_DATA_u,
}}
RIDL! {#[uuid(0x82BC481C, 0x6B9B, 0x4030, 0xAE, 0xDB, 0x7E, 0xE3, 0xD1, 0xDF, 0x1E, 0x63)]
interface ID3D12DeviceRemovedExtendedDataSettings(ID3D12DeviceRemovedExtendedDataSettingsVtbl)
: IUnknown(IUnknownVtbl) {
fn SetAutoBreadcrumbsEnablement(
__MIDL__ID3D12DeviceRemovedExtendedDataSettings0000: D3D12_DRED_ENABLEMENT,
) -> (),
fn SetPageFaultEnablement(
__MIDL__ID3D12DeviceRemovedExtendedDataSettings0001: D3D12_DRED_ENABLEMENT,
) -> (),
fn SetWatsonDumpEnablement(
__MIDL__ID3D12DeviceRemovedExtendedDataSettings0002: D3D12_DRED_ENABLEMENT,
) -> (),
}}
RIDL! {#[uuid(0x98931D33, 0x5AE8, 0x4791, 0xAA, 0x3C, 0x1A, 0x73, 0xA2, 0x93, 0x4E, 0x71)]
interface ID3D12DeviceRemovedExtendedData(ID3D12DeviceRemovedExtendedDataVtbl)
: IUnknown(IUnknownVtbl) {
fn GetAutoBreadcrumbsOutput(
pOutput: *mut D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT,
) -> HRESULT,
fn GetPageFaultAllocationOutput(
pOutput: *mut D3D12_DRED_PAGE_FAULT_OUTPUT,
) -> HRESULT,
}}
RIDL! {#[uuid(0x9727A022, 0xCF1D, 0x4DDA, 0x9E, 0xBA, 0xEF, 0xFA, 0x65, 0x3F, 0xC5, 0x06)]
interface ID3D12DeviceRemovedExtendedData1(ID3D12DeviceRemovedExtendedData1Vtbl)
: ID3D12DeviceRemovedExtendedData(ID3D12DeviceRemovedExtendedDataVtbl) {
fn GetAutoBreadcrumbsOutput1(
pOutput: *mut D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1,
) -> HRESULT,
fn GetPageFaultAllocationOutput1(
pOutput: *mut D3D12_DRED_PAGE_FAULT_OUTPUT1,
) -> HRESULT,
}
}
RIDL! {#[uuid(0x67FC5816, 0xE4CA, 0x4915, 0xBF, 0x18, 0x42, 0x54, 0x12, 0x72, 0xDA, 0x54)]
interface ID3D12DeviceRemovedExtendedData2(ID3D12DeviceRemovedExtendedData2Vtbl)
: ID3D12DeviceRemovedExtendedData1(ID3D12DeviceRemovedExtendedData1Vtbl) {
fn GetPageFaultAllocationOutput2(
pOutput: *mut D3D12_DRED_PAGE_FAULT_OUTPUT2,
) -> HRESULT,
fn GetDeviceState() -> D3D12_DRED_DEVICE_STATE,
}
}
ENUM! {enum D3D12_BACKGROUND_PROCESSING_MODE {
D3D12_BACKGROUND_PROCESSING_MODE_ALLOWED = 0,
D3D12_BACKGROUND_PROCESSING_MODE_ALLOW_INTRUSIVE_MEASUREMENTS = 1,
D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK = 2,
D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_PROFILING_BY_SYSTEM = 3,
}}
ENUM! {enum D3D12_MEASUREMENTS_ACTION {
D3D12_MEASUREMENTS_ACTION_KEEP_ALL = 0,
D3D12_MEASUREMENTS_ACTION_COMMIT_RESULTS = 1,
D3D12_MEASUREMENTS_ACTION_COMMIT_RESULTS_HIGH_PRIORITY = 2,
D3D12_MEASUREMENTS_ACTION_DISCARD_PREVIOUS = 3,
}}
RIDL! {#[uuid(0xc70b221b, 0x40e4, 0x4a17, 0x89, 0xaf, 0x02, 0x5a, 0x07, 0x27, 0xa6, 0xdc)]
interface ID3D12Device6(ID3D12Device6Vtbl): ID3D12Device5(ID3D12Device5Vtbl) {
fn SetBackgroundProcessingMode(
Mode: D3D12_BACKGROUND_PROCESSING_MODE,
MeasurementsAction: D3D12_MEASUREMENTS_ACTION,
hEventToSignalUponCompletion: HANDLE,
pbFurtherMeasurementsDesired: *mut BOOL,
) -> HRESULT,
}}
STRUCT! {struct D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPE_COUNT{
NodeIndex: UINT,
Count: UINT,
}}
STRUCT! {struct D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPES{
NodeIndex: UINT,
Count: UINT,
pTypes: *mut GUID,
}}
STRUCT! {struct D3D12_PROTECTED_RESOURCE_SESSION_DESC1{
NodeMask: UINT,
Flags: D3D12_PROTECTED_RESOURCE_SESSION_FLAGS,
ProtectionType: GUID,
}}
RIDL! {#[uuid(0xD6F12DD6, 0x76FB, 0x406E, 0x89, 0x61, 0x42, 0x96, 0xEE, 0xFC, 0x04, 0x09)]
interface ID3D12ProtectedResourceSession1(ID3D12ProtectedResourceSession1Vtbl)
: ID3D12ProtectedResourceSession(ID3D12ProtectedResourceSessionVtbl) {
fn GetDesc1() -> D3D12_PROTECTED_RESOURCE_SESSION_DESC1,
}}
RIDL! {#[uuid(0x5c014b53, 0x68a1, 0x4b9b, 0x8b, 0xd1, 0xdd, 0x60, 0x46, 0xb9, 0x35, 0x8b)]
interface ID3D12Device7(ID3D12Device7Vtbl)
: ID3D12Device6(ID3D12Device6Vtbl) {
fn AddToStateObject(
pAddition: *const D3D12_STATE_OBJECT_DESC,
pStateObjectToGrowFrom: *mut ID3D12StateObject,
riid: REFIID,
ppNewStateObject: *mut *mut c_void,
) -> HRESULT,
fn CreateProtectedResourceSession1(
pDesc: *const D3D12_PROTECTED_RESOURCE_SESSION_DESC1,
riid: REFIID,
ppSession: *mut *mut c_void,
) -> HRESULT,
}}
RIDL! {#[uuid(0x9218E6BB, 0xF944, 0x4F7E, 0xA7, 0x5C, 0xB1, 0xB2, 0xC7, 0xB7, 0x01, 0xF3)]
interface ID3D12Device8(ID3D12Device8Vtbl)
: ID3D12Device7(ID3D12Device7Vtbl) {
fn GetResourceAllocationInfo2(
visibleMask: UINT,
numResourceDescs: UINT,
pResourceDescs: *const D3D12_RESOURCE_DESC1,
pResourceAllocationInfo1: *mut D3D12_RESOURCE_ALLOCATION_INFO1,
) -> D3D12_RESOURCE_ALLOCATION_INFO,
fn CreateCommittedResource2(
pHeapProperties: *const D3D12_HEAP_PROPERTIES,
HeapFlags: D3D12_HEAP_FLAGS,
pDesc: *const D3D12_RESOURCE_DESC1,
InitialResourceState: D3D12_RESOURCE_STATES,
pOptimizedClearValue: *const D3D12_CLEAR_VALUE,
pProtectedSession: *mut ID3D12ProtectedResourceSession,
riidResource: REFIID,
ppvResource: *mut *mut c_void,
) -> HRESULT,
fn CreatePlacedResource1(
pHeap: *mut ID3D12Heap,
HeapOffset: UINT64,
pDesc: *const D3D12_RESOURCE_DESC1,
InitialState: D3D12_RESOURCE_STATES,
pOptimizedClearValue: *const D3D12_CLEAR_VALUE,
riid: REFIID,
ppvResource: *mut *mut c_void,
) -> HRESULT,
fn CreateSamplerFeedbackUnorderedAccessView(
pTargetedResource: *mut ID3D12Resource,
pFeedbackResource: *mut ID3D12Resource,
DestDescriptor: D3D12_CPU_DESCRIPTOR_HANDLE,
) -> (),
fn GetCopyableFootprints1(
pResourceDesc: *const D3D12_RESOURCE_DESC1,
FirstSubresource: UINT,
NumSubresources: UINT,
BaseOffset: UINT64,
pLayouts: *mut D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
pNumRows: *mut UINT,
pRowSizeInBytes: *mut UINT64,
pTotalBytes: *mut UINT64,
) -> (),
}}
RIDL! {#[uuid(0x9D5E227A, 0x4430, 0x4161, 0x88, 0xB3, 0x3E, 0xCA, 0x6B, 0xB1, 0x6E, 0x19)]
interface ID3D12Resource1(ID3D12Resource1Vtbl): ID3D12Resource(ID3D12ResourceVtbl) {
fn GetProtectedResourceSession(
riid: REFIID,
ppProtectedSession: *mut *mut c_void,
) -> HRESULT,
}}
RIDL! {#[uuid(0xBE36EC3B, 0xEA85, 0x4AEB, 0xA4, 0x5A, 0xE9, 0xD7, 0x64, 0x04, 0xA4, 0x95)]
interface ID3D12Resource2(ID3D12Resource2Vtbl): ID3D12Resource1(ID3D12Resource1Vtbl) {
fn GetDesc1() -> D3D12_RESOURCE_DESC1,
}}
RIDL! {#[uuid(0x572F7389, 0x2168, 0x49E3, 0x96, 0x93, 0xD6, 0xDF, 0x58, 0x71, 0xBF, 0x6D)]
interface ID3D12Heap1(ID3D12Heap1Vtbl): ID3D12Heap(ID3D12HeapVtbl) {
fn GetProtectedResourceSession(
riid: REFIID,
ppProtectedSession: *mut *mut c_void,
) -> HRESULT,
}}
RIDL! {#[uuid(0x6FDA83A7, 0xB84C, 0x4E38, 0x9A, 0xC8, 0xC7, 0xBD, 0x22, 0x01, 0x6B, 0x3D)]
interface ID3D12GraphicsCommandList3(ID3D12GraphicsCommandList3Vtbl)
: ID3D12GraphicsCommandList2(ID3D12GraphicsCommandList2Vtbl) {
fn SetProtectedResourceSession(
pProtectedResourceSession: *mut ID3D12ProtectedResourceSession,
) -> (),
}}
ENUM! {enum D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE {
D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_DISCARD = 0,
D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_PRESERVE = 1,
D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR = 2,
D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_NO_ACCESS = 3,
}}
STRUCT! {struct D3D12_RENDER_PASS_BEGINNING_ACCESS_CLEAR_PARAMETERS {
ClearValue: D3D12_CLEAR_VALUE,
}}
UNION! {union D3D12_RENDER_PASS_BEGINNING_ACCESS_u {
[u32; 4],
Clear Clear_mut: D3D12_RENDER_PASS_BEGINNING_ACCESS_CLEAR_PARAMETERS,
}}
STRUCT! {struct D3D12_RENDER_PASS_BEGINNING_ACCESS {
Type: D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE,
u: D3D12_RENDER_PASS_BEGINNING_ACCESS_u,
}}
ENUM! {enum D3D12_RENDER_PASS_ENDING_ACCESS_TYPE {
D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_DISCARD = 0,
D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_PRESERVE = 1,
D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE = 2,
D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_NO_ACCESS = 3,
}}
STRUCT! {struct D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_SUBRESOURCE_PARAMETERS {
SrcSubresource: UINT,
DstSubresource: UINT,
DstX: UINT,
DstY: UINT,
SrcRect: D3D12_RECT,
}}
STRUCT! {struct D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_PARAMETERS {
pSrcResource: *mut ID3D12Resource,
pDstResource: *mut ID3D12Resource,
SubresourceCount: UINT,
pSubresourceParameters: *const D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_SUBRESOURCE_PARAMETERS,
Format: DXGI_FORMAT,
ResolveMode: D3D12_RESOLVE_MODE,
PreserveResolveSource: BOOL,
}}
UNION! {union D3D12_RENDER_PASS_ENDING_ACCESS_u {
[u64; 6],
Resolve Resolve_mut: D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_PARAMETERS,
}}
STRUCT! {struct D3D12_RENDER_PASS_ENDING_ACCESS {
Type: D3D12_RENDER_PASS_ENDING_ACCESS_TYPE,
u: D3D12_RENDER_PASS_ENDING_ACCESS_u,
}}
STRUCT! {struct D3D12_RENDER_PASS_RENDER_TARGET_DESC {
cpuDescriptor: D3D12_CPU_DESCRIPTOR_HANDLE,
BeginningAccess: D3D12_RENDER_PASS_BEGINNING_ACCESS,
EndingAccess: D3D12_RENDER_PASS_ENDING_ACCESS,
}}
STRUCT! {struct D3D12_RENDER_PASS_DEPTH_STENCIL_DESC {
cpuDescriptor: D3D12_CPU_DESCRIPTOR_HANDLE,
DepthBeginningAccess: D3D12_RENDER_PASS_BEGINNING_ACCESS,
StencilBeginningAccess: D3D12_RENDER_PASS_BEGINNING_ACCESS,
DepthEndingAccess: D3D12_RENDER_PASS_ENDING_ACCESS,
StencilEndingAccess: D3D12_RENDER_PASS_ENDING_ACCESS,
}}
ENUM! {enum D3D12_RENDER_PASS_FLAGS {
D3D12_RENDER_PASS_FLAG_NONE = 0,
D3D12_RENDER_PASS_FLAG_ALLOW_UAV_WRITES = 0x1,
D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS = 0x2,
D3D12_RENDER_PASS_FLAG_RESUMING_PASS = 0x4,
}}
RIDL! {#[uuid(0xDBB84C27, 0x36CE, 0x4FC9, 0xB8, 0x01, 0xF0, 0x48, 0xC4, 0x6A, 0xC5, 0x70)]
interface ID3D12MetaCommand(ID3D12MetaCommandVtbl) : ID3D12Pageable(ID3D12PageableVtbl) {
fn GetRequiredParameterResourceSize(
Stage: D3D12_META_COMMAND_PARAMETER_STAGE,
ParameterIndex: UINT,
) -> UINT64,
}}
STRUCT! {struct D3D12_DISPATCH_RAYS_DESC {
RayGenerationShaderRecord: D3D12_GPU_VIRTUAL_ADDRESS_RANGE,
MissShaderTable: D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE,
HitGroupTable: D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE,
CallableShaderTable: D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE,
Width: UINT,
Height: UINT,
Depth: UINT,
}}
RIDL! {#[uuid(0x8754318e, 0xd3a9, 0x4541, 0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74)]
interface ID3D12GraphicsCommandList4(ID3D12GraphicsCommandList4Vtbl)
: ID3D12GraphicsCommandList3(ID3D12GraphicsCommandList3Vtbl) {
fn BeginRenderPass(
NumRenderTargets: UINT,
pRenderTargets: *const D3D12_RENDER_PASS_RENDER_TARGET_DESC,
pDepthStencil: *const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC,
Flags: D3D12_RENDER_PASS_FLAGS,
) -> (),
fn EndRenderPass() -> (),
fn InitializeMetaCommand(
pMetaCommand: *mut ID3D12MetaCommand,
pInitializationParametersData: *const c_void,
InitializationParametersDataSizeInBytes: SIZE_T,
) -> (),
fn ExecuteMetaCommand(
pMetaCommand: *mut ID3D12MetaCommand,
pExecutionParametersData: *const c_void,
ExecutionParametersDataSizeInBytes: SIZE_T,
) -> (),
fn BuildRaytracingAccelerationStructure(
pDesc: *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC,
NumPostbuildInfoDescs: UINT,
pPostbuildInfoDescs: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC,
) -> (),
fn EmitRaytracingAccelerationStructurePostbuildInfo(
pDesc: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC,
NumSourceAccelerationStructures: UINT,
pSourceAccelerationStructureData: *const D3D12_GPU_VIRTUAL_ADDRESS,
) -> (),
fn CopyRaytracingAccelerationStructure(
DestAccelerationStructureData: D3D12_GPU_VIRTUAL_ADDRESS,
SourceAccelerationStructureData: D3D12_GPU_VIRTUAL_ADDRESS,
Mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE,
) -> (),
fn SetPipelineState1(
pStateObject: *mut ID3D12StateObject,
) -> (),
fn DispatchRays(
pDesc: *const D3D12_DISPATCH_RAYS_DESC,
) -> (),
}}
ENUM! {enum D3D12_SHADER_CACHE_MODE {
D3D12_SHADER_CACHE_MODE_MEMORY,
D3D12_SHADER_CACHE_MODE_DISK,
}}
ENUM! {enum D3D12_SHADER_CACHE_FLAGS {
D3D12_SHADER_CACHE_FLAG_NONE = 0x0,
D3D12_SHADER_CACHE_FLAG_DRIVER_VERSIONED = 0x1,
D3D12_SHADER_CACHE_FLAG_USE_WORKING_DIR = 0x2,
}}
STRUCT! {struct D3D12_SHADER_CACHE_SESSION_DESC {
Identifier: GUID,
Mode: D3D12_SHADER_CACHE_MODE,
Flags: D3D12_SHADER_CACHE_FLAGS,
MaximumInMemoryCacheSizeBytes: UINT,
MaximumInMemoryCacheEntries: UINT,
MaximumValueFileSizeBytes: UINT,
Version: UINT64,
}}
RIDL! {#[uuid(0x28e2495d, 0x0f64, 0x4ae4, 0xa6, 0xec, 0x12, 0x92, 0x55, 0xdc, 0x49, 0xa8)]
interface ID3D12ShaderCacheSession(ID3D12ShaderCacheSessionVtbl): ID3D12DeviceChild(ID3D12DeviceChildVtbl) {
fn FindValue(
pKey: *const c_void,
KeySize: UINT,
pValue: *mut c_void,
pValueSize: *mut UINT,
) -> HRESULT,
fn StoreValue(
pKey: *const c_void,
KeySize: UINT,
pValue: *const c_void,
ValueSize: UINT,
) -> HRESULT,
fn SetDeleteOnDestroy() -> (),
fn GetDesc() -> D3D12_SHADER_CACHE_SESSION_DESC,
}}
ENUM! {enum D3D12_SHADER_CACHE_KIND_FLAGS {
D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER = 0x1,
D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CONVERSIONS = 0x2,
D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED = 0x4,
D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED = 0x8,
}}
ENUM! {enum D3D12_SHADER_CACHE_CONTROL_FLAGS{
D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE = 0x1,
D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE = 0x2,
D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR = 0x4,
}}
RIDL! {#[uuid(0x4c80e962, 0xf032, 0x4f60, 0xbc, 0x9e, 0xeb, 0xc2, 0xcf, 0xa1, 0xd8, 0x8c)]
interface ID3D12Device9(ID3D12Device9Vtbl): ID3D12Device8(ID3D12Device8Vtbl) {
fn CreateShaderCacheSession(
pDesc: *const D3D12_SHADER_CACHE_SESSION_DESC,
riid: REFIID,
ppvSession: *mut *mut c_void,
) -> HRESULT,
fn ShaderCacheControl(
Kinds: D3D12_SHADER_CACHE_KIND_FLAGS,
Control: D3D12_SHADER_CACHE_CONTROL_FLAGS,
) -> HRESULT,
fn CreateCommandQueue1(
pDesc: *const D3D12_COMMAND_QUEUE_DESC,
CreatorID: REFIID,
riid: REFIID,
ppCommandQueue: *mut *mut c_void,
) -> HRESULT,
}}
RIDL! {#[uuid(0x7071e1f0, 0xe84b, 0x4b33, 0x97, 0x4f, 0x12, 0xfa, 0x49, 0xde, 0x65, 0xc5)]
interface ID3D12Tools(ID3D12ToolsVtbl): IUnknown(IUnknownVtbl) {
fn EnableShaderInstrumentation(
bEnable: BOOL,
) -> (),
fn ShaderInstrumentationEnabled() -> BOOL,
}}
STRUCT! {struct D3D12_SUBRESOURCE_DATA {
pData: *const c_void,
RowPitch: LONG_PTR,
SlicePitch: LONG_PTR,
}}
STRUCT! {struct D3D12_MEMCPY_DEST {
pData: *mut c_void,
RowPitch: SIZE_T,
SlicePitch: SIZE_T,
}}
FN! {stdcall PFN_D3D12_CREATE_DEVICE(
*mut IUnknown,
D3D_FEATURE_LEVEL,
REFIID,
*mut *mut c_void,
) -> HRESULT}
extern "system" {
pub fn D3D12CreateDevice(
pAdapter: *mut IUnknown,
MinimumFeatureLevel: D3D_FEATURE_LEVEL,
riid: REFGUID,
ppDevice: *mut *mut c_void,
) -> HRESULT;
}
FN! {stdcall PFN_D3D12_GET_DEBUG_INTERFACE(
REFIID,
*mut *mut c_void,
) -> HRESULT}
extern "system" {
pub fn D3D12GetDebugInterface(riid: REFGUID, ppvDebug: *mut *mut c_void) -> HRESULT;
pub fn D3D12EnableExperimentalFeatures(
NumFeatures: UINT,
pIIDs: *const IID,
pConfigurationStructs: *mut c_void,
pConfigurationStructSizes: *mut UINT,
) -> HRESULT;
}
// experimental features
DEFINE_GUID! {D3D12ExperimentalShaderModels,
0x76f5573e, 0xf13a, 0x40f5, 0xb2, 0x97, 0x81, 0xce, 0x9e, 0x18, 0x93, 0x3f}
DEFINE_GUID! {D3D12TiledResourceTier4,
0xc9c4725f, 0xa81a, 0x4f56, 0x8c, 0x5b, 0xc5, 0x10, 0x39, 0xd6, 0x94, 0xfb}
DEFINE_GUID! {D3D12MetaCommand,
0xc734c97e, 0x8077, 0x48c8, 0x9f, 0xdc, 0xd9, 0xd1, 0xdd, 0x31, 0xdd, 0x77}
DEFINE_GUID! {D3D12ComputeOnlyDevices,
0x50f7ab08, 0x4b6d, 0x4e14, 0x89, 0xa5, 0x5d, 0x16, 0xcd, 0x27, 0x25, 0x94}
RIDL! {#[uuid(0xe9eb5314, 0x33aa, 0x42b2, 0xa7, 0x18, 0xd7, 0x7f, 0x58, 0xb1, 0xf1, 0xc7)]
interface ID3D12SDKConfiguration(ID3D12SDKConfigurationVtbl): IUnknown(IUnknownVtbl) {
fn GetSDKVersion(
SDKVersion: UINT,
SDKPath: LPCSTR,
) -> HRESULT,
}}
ENUM! {enum D3D12_AXIS_SHADING_RATE {
D3D12_AXIS_SHADING_RATE_1X = 0,
D3D12_AXIS_SHADING_RATE_2X = 0x1,
D3D12_AXIS_SHADING_RATE_4X = 0x2,
}}
pub const D3D12_SHADING_RATE_X_AXIS_SHIFT: UINT = 2;
pub const D3D12_SHADING_RATE_VALID_MASK: UINT = 3;
pub fn D3D12_MAKE_COARSE_SHADING_RATE(x: UINT, y: UINT) -> UINT {
(x << D3D12_SHADING_RATE_X_AXIS_SHIFT) | y
}
pub fn D3D12_GET_COARSE_SHADING_RATE_X_AXIS(x: UINT) -> UINT {
(x >> D3D12_SHADING_RATE_X_AXIS_SHIFT) & D3D12_SHADING_RATE_VALID_MASK
}
pub fn D3D12_GET_COARSE_SHADING_RATE_Y_AXIS(y: UINT) -> UINT {
y & D3D12_SHADING_RATE_VALID_MASK
}
ENUM! {enum D3D12_SHADING_RATE {
D3D12_SHADING_RATE_1X1 = 0,
D3D12_SHADING_RATE_1X2 = 0x1,
D3D12_SHADING_RATE_2X1 = 0x4,
D3D12_SHADING_RATE_2X2 = 0x5,
D3D12_SHADING_RATE_2X4 = 0x6,
D3D12_SHADING_RATE_4X2 = 0x9,
D3D12_SHADING_RATE_4X4 = 0xa,
}}
ENUM! {enum D3D12_SHADING_RATE_COMBINER {
D3D12_SHADING_RATE_COMBINER_PASSTHROUGH = 0,
D3D12_SHADING_RATE_COMBINER_OVERRIDE = 1,
D3D12_SHADING_RATE_COMBINER_MIN = 2,
D3D12_SHADING_RATE_COMBINER_MAX = 3,
D3D12_SHADING_RATE_COMBINER_SUM = 4,
}}
RIDL! {#[uuid(0x55050859, 0x4024, 0x474c, 0x87, 0xf5, 0x64, 0x72, 0xea, 0xee, 0x44, 0xea)]
interface ID3D12GraphicsCommandList5(ID3D12GraphicsCommandList5Vtbl)
: ID3D12GraphicsCommandList4(ID3D12GraphicsCommandList4Vtbl) {
fn RSSetShadingRate(
baseShadingRate: D3D12_SHADING_RATE,
combiners: *const D3D12_SHADING_RATE_COMBINER,
) -> (),
fn RSSetShadingRateImage(
shadingRateImage: *mut ID3D12Resource,
) -> (),
}}
DEFINE_GUID! {IID_ID3D12Object,
0xc4fec28f, 0x7966, 0x4e95, 0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}
DEFINE_GUID! {IID_ID3D12DeviceChild,
0x905db94b, 0xa00c, 0x4140, 0x9d, 0xf5, 0x2b, 0x64, 0xca, 0x9e, 0xa3, 0x57}
DEFINE_GUID! {IID_ID3D12RootSignature,
0xc54a6b66, 0x72df, 0x4ee8, 0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14}
DEFINE_GUID! {IID_ID3D12RootSignatureDeserializer,
0x34AB647B, 0x3CC8, 0x46AC, 0x84, 0x1B, 0xC0, 0x96, 0x56, 0x45, 0xC0, 0x46}
DEFINE_GUID! {IID_ID3D12VersionedRootSignatureDeserializer,
0x7F91CE67, 0x090C, 0x4BB7, 0xB7, 0x8E, 0xED, 0x8F, 0xF2, 0xE3, 0x1D, 0xA0}
DEFINE_GUID! {IID_ID3D12Pageable,
0x63ee58fb, 0x1268, 0x4835, 0x86, 0xda, 0xf0, 0x08, 0xce, 0x62, 0xf0, 0xd6}
DEFINE_GUID! {IID_ID3D12Heap,
0x6b3b2502, 0x6e51, 0x45b3, 0x90, 0xee, 0x98, 0x84, 0x26, 0x5e, 0x8d, 0xf3}
DEFINE_GUID! {IID_ID3D12Resource,
0x696442be, 0xa72e, 0x4059, 0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad}
DEFINE_GUID! {IID_ID3D12CommandAllocator,
0x6102dee4, 0xaf59, 0x4b09, 0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24}
DEFINE_GUID! {IID_ID3D12Fence,
0x0a753dcf, 0xc4d8, 0x4b91, 0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76}
DEFINE_GUID! {IID_ID3D12Fence1,
0x433685fe, 0xe22b, 0x4ca0, 0xa8, 0xdb, 0xb5, 0xb4, 0xf4, 0xdd, 0x0e, 0x4a}
DEFINE_GUID! {IID_ID3D12PipelineState,
0x765a30f3, 0xf624, 0x4c6f, 0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45}
DEFINE_GUID! {IID_ID3D12DescriptorHeap,
0x8efb471d, 0x616c, 0x4f49, 0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51}
DEFINE_GUID! {IID_ID3D12QueryHeap,
0x0d9658ae, 0xed45, 0x469e, 0xa6, 0x1d, 0x97, 0x0e, 0xc5, 0x83, 0xca, 0xb4}
DEFINE_GUID! {IID_ID3D12CommandSignature,
0xc36a797c, 0xec80, 0x4f0a, 0x89, 0x85, 0xa7, 0xb2, 0x47, 0x50, 0x82, 0xd1}
DEFINE_GUID! {IID_ID3D12CommandList,
0x7116d91c, 0xe7e4, 0x47ce, 0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5}
DEFINE_GUID! {IID_ID3D12GraphicsCommandList,
0x5b160d0f, 0xac1b, 0x4185, 0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55}
DEFINE_GUID! {IID_ID3D12GraphicsCommandList1,
0x553103fb, 0x1fe7, 0x4557, 0xbb, 0x38, 0x94, 0x6d, 0x7d, 0x0e, 0x7c, 0xa7}
DEFINE_GUID! {IID_ID3D12GraphicsCommandList2,
0x38C3E585, 0xFF17, 0x412C, 0x91, 0x50, 0x4F, 0xC6, 0xF9, 0xD7, 0x2A, 0x28}
DEFINE_GUID! {IID_ID3D12CommandQueue,
0x0ec870a6, 0x5d7e, 0x4c22, 0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed}
DEFINE_GUID! {IID_ID3D12Device,
0x189819f1, 0x1db6, 0x4b57, 0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7}
DEFINE_GUID! {IID_ID3D12PipelineLibrary,
0xc64226a8, 0x9201, 0x46af, 0xb4, 0xcc, 0x53, 0xfb, 0x9f, 0xf7, 0x41, 0x4f}
DEFINE_GUID! {IID_ID3D12PipelineLibrary1,
0x80eabf42, 0x2568, 0x4e5e, 0xbd, 0x82, 0xc3, 0x7f, 0x86, 0x96, 0x1d, 0xc3}
DEFINE_GUID! {IID_ID3D12Device1,
0x77acce80, 0x638e, 0x4e65, 0x88, 0x95, 0xc1, 0xf2, 0x33, 0x86, 0x86, 0x3e}
DEFINE_GUID! {IID_ID3D12Device2,
0x30baa41e, 0xb15b, 0x475c, 0xa0, 0xbb, 0x1a, 0xf5, 0xc5, 0xb6, 0x43, 0x28}
DEFINE_GUID! {IID_ID3D12Device3,
0x81dadc15, 0x2bad, 0x4392, 0x93, 0xc5, 0x10, 0x13, 0x45, 0xc4, 0xaa, 0x98}
DEFINE_GUID! {IID_ID3D12ProtectedSession,
0xA1533D18, 0x0AC1, 0x4084, 0x85, 0xB9, 0x89, 0xA9, 0x61, 0x16, 0x80, 0x6B}
DEFINE_GUID! {IID_ID3D12ProtectedResourceSession,
0x6CD696F4, 0xF289, 0x40CC, 0x80, 0x91, 0x5A, 0x6C, 0x0A, 0x09, 0x9C, 0x3D}
DEFINE_GUID! {IID_ID3D12Device4,
0xe865df17, 0xa9ee, 0x46f9, 0xa4, 0x63, 0x30, 0x98, 0x31, 0x5a, 0xa2, 0xe5}
DEFINE_GUID! {IID_ID3D12LifetimeOwner,
0xe667af9f, 0xcd56, 0x4f46, 0x83, 0xce, 0x03, 0x2e, 0x59, 0x5d, 0x70, 0xa8}
DEFINE_GUID! {IID_ID3D12SwapChainAssistant,
0xf1df64b6, 0x57fd, 0x49cd, 0x88, 0x07, 0xc0, 0xeb, 0x88, 0xb4, 0x5c, 0x8f}
DEFINE_GUID! {IID_ID3D12LifetimeTracker,
0x3fd03d36, 0x4eb1, 0x424a, 0xa5, 0x82, 0x49, 0x4e, 0xcb, 0x8b, 0xa8, 0x13}
DEFINE_GUID! {IID_ID3D12StateObject,
0x47016943, 0xfca8, 0x4594, 0x93, 0xea, 0xaf, 0x25, 0x8b, 0x55, 0x34, 0x6d}
DEFINE_GUID! {IID_ID3D12StateObjectProperties,
0xde5fa827, 0x9bf9, 0x4f26, 0x89, 0xff, 0xd7, 0xf5, 0x6f, 0xde, 0x38, 0x60}
DEFINE_GUID! {IID_ID3D12Device5,
0x8b4f173b, 0x2fea, 0x4b80, 0x8f, 0x58, 0x43, 0x07, 0x19, 0x1a, 0xb9, 0x5d}
DEFINE_GUID! {IID_ID3D12DeviceRemovedExtendedDataSettings,
0x82BC481C, 0x6B9B, 0x4030, 0xAE, 0xDB, 0x7E, 0xE3, 0xD1, 0xDF, 0x1E, 0x63}
DEFINE_GUID! {IID_ID3D12DeviceRemovedExtendedData,
0x98931D33, 0x5AE8, 0x4791, 0xAA, 0x3C, 0x1A, 0x73, 0xA2, 0x93, 0x4E, 0x71}
DEFINE_GUID! {IID_ID3D12DeviceRemovedExtendedData1,
0x9727A022, 0xCF1D, 0x4DDA, 0x9E, 0xBA, 0xEF, 0xFA, 0x65, 0x3F, 0xC5, 0x06}
DEFINE_GUID! {IID_ID3D12DeviceRemovedExtendedData2,
0x67FC5816, 0xE4CA, 0x4915, 0xBF, 0x18, 0x42, 0x54, 0x12, 0x72, 0xDA, 0x54}
DEFINE_GUID! {IID_ID3D12Device6,
0xc70b221b, 0x40e4, 0x4a17, 0x89, 0xaf, 0x02, 0x5a, 0x07, 0x27, 0xa6, 0xdc}
DEFINE_GUID! {IID_ID3D12ProtectedResourceSession1,
0xD6F12DD6, 0x76FB, 0x406E, 0x89, 0x61, 0x42, 0x96, 0xEE, 0xFC, 0x04, 0x09}
DEFINE_GUID! {IID_ID3D12Device7,
0x5c014b53, 0x68a1, 0x4b9b, 0x8b, 0xd1, 0xdd, 0x60, 0x46, 0xb9, 0x35, 0x8b}
DEFINE_GUID! {IID_ID3D12Device8,
0x9218E6BB, 0xF944, 0x4F7E, 0xA7, 0x5C, 0xB1, 0xB2, 0xC7, 0xB7, 0x01, 0xF3}
DEFINE_GUID! {IID_ID3D12Resource1,
0x9D5E227A, 0x4430, 0x4161, 0x88, 0xB3, 0x3E, 0xCA, 0x6B, 0xB1, 0x6E, 0x19}
DEFINE_GUID! {IID_ID3D12Resource2,
0xBE36EC3B, 0xEA85, 0x4AEB, 0xA4, 0x5A, 0xE9, 0xD7, 0x64, 0x04, 0xA4, 0x95}
DEFINE_GUID! {IID_ID3D12Heap1,
0x572F7389, 0x2168, 0x49E3, 0x96, 0x93, 0xD6, 0xDF, 0x58, 0x71, 0xBF, 0x6D}
DEFINE_GUID! {IID_ID3D12GraphicsCommandList3,
0x6FDA83A7, 0xB84C, 0x4E38, 0x9A, 0xC8, 0xC7, 0xBD, 0x22, 0x01, 0x6B, 0x3D}
DEFINE_GUID! {IID_ID3D12MetaCommand,
0xDBB84C27, 0x36CE, 0x4FC9, 0xB8, 0x01, 0xF0, 0x48, 0xC4, 0x6A, 0xC5, 0x70}
DEFINE_GUID! {IID_ID3D12GraphicsCommandList4,
0x8754318e, 0xd3a9, 0x4541, 0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74}
DEFINE_GUID! {IID_ID3D12ShaderCacheSession,
0x28e2495d, 0x0f64, 0x4ae4, 0xa6, 0xec, 0x12, 0x92, 0x55, 0xdc, 0x49, 0xa8}
DEFINE_GUID! {IID_ID3D12Device9,
0x4c80e962, 0xf032, 0x4f60, 0xbc, 0x9e, 0xeb, 0xc2, 0xcf, 0xa1, 0xd8, 0x3c}
DEFINE_GUID! {IID_ID3D12Tools,
0x7071e1f0, 0xe84b, 0x4b33, 0x97, 0x4f, 0x12, 0xfa, 0x49, 0xde, 0x65, 0xc5}
DEFINE_GUID! {IID_ID3D12SDKConfiguration,
0xe9eb5314, 0x33aa, 0x42b2, 0xa7, 0x18, 0xd7, 0x7f, 0x58, 0xb1, 0xf1, 0xc}
DEFINE_GUID! {IID_ID3D12GraphicsCommandList5,
0x55050859, 0x4024, 0x474c, 0x87, 0xf5, 0x64, 0x72, 0xea, 0xee, 0x44, 0xea}
DEFINE_GUID! {IID_ID3D12GraphicsCommandList6,
0xc3827890, 0xe548, 0x4cfa, 0x96, 0xcf, 0x56, 0x89, 0xa9, 0x37, 0x0f, 0x80}
|
use eval::lua_hash;
use eval::LuaErr;
use eval::LuaNative;
use eval::LV;
// pub fn lua_getattr(tlb: &LV, key: &LV) -> Result<LV, LuaErr> {}
pub fn lua_ssetattr(tbl: &mut LV, key: &str, value: LV) -> Result<(), LuaErr> {
return lua_setattr(tbl, &LV::LuaS(key.to_string()), value);
}
pub fn lua_setattr(tbl: &mut LV, key: &LV, value: LV) -> Result<(), LuaErr> {
let table_inner = match tbl {
LV::LuaTable { v, .. } => v,
_ => return LuaErr::msg("Called lua_setattr on a non-table"),
};
let mut table_data = table_inner.borrow_mut();
table_data.insert(lua_hash(key), value);
return Ok(());
}
pub fn lua_set_native(tbl: &mut LV, key: &str, func: LuaNative) -> Result<(), LuaErr> {
let lua_func = LV::NativeFunc {
name: key.to_string(),
f: func,
returns_multiple: false,
};
return lua_ssetattr(tbl, key, lua_func);
}
pub fn lua_getattr(tbl: &LV, key: &LV) -> Result<LV, LuaErr> {
// try to do tbl[key], basically
let hashed_key = lua_hash(key);
let tbl_inner = match tbl {
LV::LuaTable { v, .. } => v,
_ => return LuaErr::msg("Called lua_getattr on a non-table"),
};
match tbl_inner.borrow().get(&hashed_key) {
Some(v) => Ok(v.clone()),
None => Ok(LV::LuaNil),
}
}
|
pub mod errors;
use async_trait::async_trait;
use ldap3::{exop::WhoAmI, Ldap, LdapConnAsync, LdapError as Error};
pub type Pool = deadpool::managed::Pool<Ldap, errors::LdapError>;
pub struct Manager(pub &'static str);
#[async_trait]
impl deadpool::managed::Manager<Ldap, Error> for Manager {
async fn create(&self) -> Result<Ldap, Error> {
let (conn, ldap) = LdapConnAsync::new(self.0).await?;
#[cfg(feature = "default")]
ldap3::drive!(conn);
#[cfg(feature = "rt-actix")]
actix_rt::spawn(async move {
if let Err(e) = conn.drive().await {
log::warn!("LDAP connection error: {}", e);
}
});
Ok(ldap)
}
async fn recycle(&self, conn: &mut Ldap) -> deadpool::managed::RecycleResult<Error> {
conn.extended(WhoAmI).await?;
Ok(())
}
}
|
#[doc = "Reader of register PID1"]
pub type R = crate::R<u32, super::PID1>;
#[doc = "Reader of field `PER_ID_1`"]
pub type PER_ID_1_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:7 - Peripheral ID 1"]
#[inline(always)]
pub fn per_id_1(&self) -> PER_ID_1_R {
PER_ID_1_R::new((self.bits & 0xff) as u8)
}
}
|
extern crate opencv;
extern crate time;
use opencv::core;
use opencv::highgui;
use opencv::imgproc;
//use opencv::highgui::VideoCapture;
use std::time::Instant;
//int lowH[4] = { 0, 51, 75, 20 };
//int highH[4] = { 10, 75, 107, 35 };
//int lowS[4] = { 158, 127, 127, 85 };
//int highS[4] = { 255, 255, 255, 255 };
//int lowV[4] = { 158, 127, 127, 150 };
//int highV[4] = { 255, 255, 255, 255 };
fn get_colour(mut frame: core::Mat) -> Result<i32,String> {
let now = Instant::now();
println!("Start {:#?}",Instant::now().duration_since(now));
let mut ret = -1;
let red2 = 0;
let red = 1;
let green = 2;
let blue = 3;
let yellow = 4;
let colours = [ red2, red, green, blue, yellow ];
let red2_lower = core::Scalar{ data:[0f64,158f64,158f64,-1f64] };
let red2_upper = core::Scalar{ data:[10f64,255f64,255f64,-1f64] };
let red_lower = core::Scalar{ data:[150f64,128f64,0f64,-1f64] };
let red_upper = core::Scalar{ data:[230f64,255f64,255f64,-1f64] };
//let green_lower = core::Scalar{ data:[51f64,127f64,127f64,-1f64] };
//let green_upper = core::Scalar{ data:[75f64,255f64,255f64,-1f64] };
let green_lower = core::Scalar{ data:[55f64,60f64,91f64,-1f64] };
let green_upper = core::Scalar{ data:[96f64,192f64,255f64,-1f64] };
let blue_lower = core::Scalar{ data:[75f64,127f64,127f64,-1f64] };
let blue_upper = core::Scalar{ data:[107f64,255f64,255f64,-1f64] };
//let yellow_lower = core::Scalar{ data:[20f64,85f64,150f64,-1f64] };
//let yellow_upper = core::Scalar{ data:[35f64,255f64,255f64,-1f64] };
let yellow_lower = core::Scalar{ data:[10f64,170f64,150f64,-1f64] };
let yellow_upper = core::Scalar{ data:[49f64,255f64,255f64,-1f64] };
let window = "Video Capture";
try!(highgui::named_window(window,1));
let window2 = "Overlay";
try!(highgui::named_window(window2,1));
println!("Now {:#?}",Instant::now().duration_since(now));
//let mut cam = try!(highgui::VideoCapture::device(0));
//let mut frame = try!(core::Mat::new());
//try!(cam.read(&mut frame));
if try!(frame.size()).width == 0 {
println!("Failed to create camera frame");
let ret =-999;
return Ok(ret);
}
println!("Now {:#?}",Instant::now().duration_since(now));
//let mut frame2 = try!(core::Mat::clone( &frame ) );
let mut frame2 = try!(core::Mat::rect( &frame, core::Rect{x:0,y:0,width:640,height:80}) );
let mut img_hsv = try!(core::Mat::new());
try!(imgproc::cvt_color(&mut frame, &mut img_hsv, imgproc::COLOR_BGR2HSV, 0));
let mut img_thresholded = try!(core::Mat::new());
println!("Now {:#?}",Instant::now().duration_since(now));
for colour in colours.iter()
{
let mut _img_final = try!(core::Mat::new());
if *colour == red2 {
let img_lower = try!(core::Mat::new_size_with_default( try!(img_hsv.size()), try!(img_hsv.typ()), red2_lower ));
let img_upper = try!(core::Mat::new_size_with_default( try!(img_hsv.size()), try!(img_hsv.typ()), red2_upper ));
try!(core::in_range( &mut img_hsv, &img_lower, &img_upper, &mut img_thresholded));
}
if *colour == red {
let img_lower = try!(core::Mat::new_size_with_default( try!(img_hsv.size()), try!(img_hsv.typ()), red_lower ));
let img_upper = try!(core::Mat::new_size_with_default( try!(img_hsv.size()), try!(img_hsv.typ()), red_upper ));
try!(core::in_range( &mut img_hsv, &img_lower, &img_upper, &mut img_thresholded));
}
else if *colour == green {
let img_lower = try!(core::Mat::new_size_with_default( try!(img_hsv.size()), try!(img_hsv.typ()), green_lower ));
let img_upper = try!(core::Mat::new_size_with_default( try!(img_hsv.size()), try!(img_hsv.typ()), green_upper ));
try!(core::in_range( &mut img_hsv, &img_lower, &img_upper, &mut img_thresholded));
}
else if *colour == blue {
let img_lower = try!(core::Mat::new_size_with_default( try!(img_hsv.size()), try!(img_hsv.typ()), blue_lower ));
let img_upper = try!(core::Mat::new_size_with_default( try!(img_hsv.size()), try!(img_hsv.typ()), blue_upper ));
try!(core::in_range( &mut img_hsv, &img_lower, &img_upper, &mut img_thresholded));
}
else if *colour == yellow {
let img_lower = try!(core::Mat::new_size_with_default( try!(img_hsv.size()), try!(img_hsv.typ()), yellow_lower ));
let img_upper = try!(core::Mat::new_size_with_default( try!(img_hsv.size()), try!(img_hsv.typ()), yellow_upper ));
try!(core::in_range( &mut img_hsv, &img_lower, &img_upper, &mut img_thresholded));
}
let kernel = try!(imgproc::get_structuring_element(imgproc::MORPH_ELLIPSE, core::Size{width:5, height:5}, core::Point{x:-1, y:-1}));
let border_value = try!(imgproc::morphology_default_border_value());
let mut img_dilated = try!(core::Mat::new());
let mut img_eroded = try!(core::Mat::new());
let mut img_final = try!(core::Mat::new());
//morphological opening (removes small objects from the foreground)
try!(imgproc::erode( &mut img_thresholded, &mut img_eroded, &kernel, core::Point{x:-1, y:-1}, 1, imgproc::BORDER_CONSTANT, border_value));
try!(imgproc::dilate( &mut img_eroded, &mut img_dilated, &kernel, core::Point{x:-1, y:-1}, 1, imgproc::BORDER_CONSTANT, border_value));
//morphological closing (removes small holes from the foreground)
try!(imgproc::dilate( &mut img_dilated, &mut img_eroded, &kernel, core::Point{x:-1, y:-1}, 1, imgproc::BORDER_CONSTANT, border_value));
try!(imgproc::erode( &mut img_eroded, &mut img_final, &kernel, core::Point{x:-1, y:-1}, 1, imgproc::BORDER_CONSTANT, border_value));
let result = imgproc::moments(&mut img_final, false);
assert!( result.is_ok() );
let moments = result.unwrap();
let area = moments.m00;
//println!("Area {:#?}",area);
if area > 5000f64
{
try!(highgui::imshow(window2, &mut img_final));
if *colour == red || *colour == red2 {
try!(core::rectangle(&mut frame2,core::Rect{x:0,y:0,width:30,height:30},core::Scalar{ data:[0f64,0f64,255f64,-1f64] },-1 ,8 ,0));
ret = red;
break;
}
else if *colour == green {
try!(core::rectangle(&mut frame2,core::Rect{x:0,y:0,width:30,height:30},core::Scalar{ data:[0f64,255f64,0f64,-1f64] },-1 ,8 ,0));
ret = green;
break;
}
else if *colour == blue {
try!(core::rectangle(&mut frame2,core::Rect{x:0,y:0,width:30,height:30},core::Scalar{ data:[255f64,0f64,0f64,-1f64] },-1 ,8 ,0));
ret = blue;
break;
}
else if *colour == yellow {
try!(core::rectangle(&mut frame2,core::Rect{x:0,y:0,width:30,height:30},core::Scalar{ data:[0f64,255f64,255f64,-1f64] },-1 ,8 ,0));
ret = yellow;
break;
}
}
}
try!(highgui::imshow(window, &mut frame2));
try!(highgui::wait_key(5));
println!("Now {:#?}",Instant::now().duration_since(now));
Ok(ret)
}
fn main() {
let mut cam = highgui::VideoCapture::device(0).unwrap();
loop {
let mut frame = core::Mat::new().unwrap();
cam.read(&mut frame);
let colour = get_colour(frame).unwrap();
if colour == -999 {
break;
}
println!("Colour {:#?}",colour);
}
}
|
use std::io;
use std::io::ErrorKind;
use std::{collections::HashSet, ffi::OsStr};
/// Mount options accepted by the FUSE filesystem type
/// See 'man mount.fuse' for details
// TODO: add all options that 'man mount.fuse' documents and libfuse supports
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub enum MountOption {
/// Set the name of the source in mtab
FSName(String),
/// Set the filesystem subtype in mtab
Subtype(String),
/// Allows passing an option which is not otherwise supported in these enums
#[allow(clippy::upper_case_acronyms)]
CUSTOM(String),
/* Parameterless options */
/// Allow all users to access files on this filesystem. By default access is restricted to the
/// user who mounted it
AllowOther,
/// Allow the root user to access this filesystem, in addition to the user who mounted it
AllowRoot,
/// Automatically unmount when the mounting process exits
///
/// `AutoUnmount` requires `AllowOther` or `AllowRoot`. If `AutoUnmount` is set and neither `Allow...` is set, the FUSE configuration must permit `allow_other`, otherwise mounting will fail.
AutoUnmount,
/// Enable permission checking in the kernel
DefaultPermissions,
/* Flags */
/// Enable special character and block devices
Dev,
/// Disable special character and block devices
NoDev,
/// Honor set-user-id and set-groupd-id bits on files
Suid,
/// Don't honor set-user-id and set-groupd-id bits on files
NoSuid,
/// Read-only filesystem
RO,
/// Read-write filesystem
RW,
/// Allow execution of binaries
Exec,
/// Don't allow execution of binaries
NoExec,
/// Support inode access time
Atime,
/// Don't update inode access time
NoAtime,
/// All modifications to directories will be done synchronously
DirSync,
/// All I/O will be done synchronously
Sync,
/// All I/O will be done asynchronously
Async,
/* libfuse library options, such as "direct_io", are not included since they are specific
to libfuse, and not part of the kernel ABI */
}
impl MountOption {
pub(crate) fn from_str(s: &str) -> MountOption {
match s {
"auto_unmount" => MountOption::AutoUnmount,
"allow_other" => MountOption::AllowOther,
"allow_root" => MountOption::AllowRoot,
"default_permissions" => MountOption::DefaultPermissions,
"dev" => MountOption::Dev,
"nodev" => MountOption::NoDev,
"suid" => MountOption::Suid,
"nosuid" => MountOption::NoSuid,
"ro" => MountOption::RO,
"rw" => MountOption::RW,
"exec" => MountOption::Exec,
"noexec" => MountOption::NoExec,
"atime" => MountOption::Atime,
"noatime" => MountOption::NoAtime,
"dirsync" => MountOption::DirSync,
"sync" => MountOption::Sync,
"async" => MountOption::Async,
x if x.starts_with("fsname=") => MountOption::FSName(x[7..].into()),
x if x.starts_with("subtype=") => MountOption::Subtype(x[8..].into()),
x => MountOption::CUSTOM(x.into()),
}
}
}
pub fn check_option_conflicts(options: &[MountOption]) -> Result<(), io::Error> {
let mut options_set = HashSet::new();
options_set.extend(options.iter().cloned());
let conflicting: HashSet<MountOption> = options.iter().map(conflicts_with).flatten().collect();
let intersection: Vec<MountOption> = conflicting.intersection(&options_set).cloned().collect();
if !intersection.is_empty() {
Err(io::Error::new(
ErrorKind::InvalidInput,
format!("Conflicting mount options found: {:?}", intersection),
))
} else {
Ok(())
}
}
fn conflicts_with(option: &MountOption) -> Vec<MountOption> {
match option {
MountOption::FSName(_) => vec![],
MountOption::Subtype(_) => vec![],
MountOption::CUSTOM(_) => vec![],
MountOption::AllowOther => vec![MountOption::AllowRoot],
MountOption::AllowRoot => vec![MountOption::AllowOther],
MountOption::AutoUnmount => vec![],
MountOption::DefaultPermissions => vec![],
MountOption::Dev => vec![MountOption::NoDev],
MountOption::NoDev => vec![MountOption::Dev],
MountOption::Suid => vec![MountOption::NoSuid],
MountOption::NoSuid => vec![MountOption::Suid],
MountOption::RO => vec![MountOption::RW],
MountOption::RW => vec![MountOption::RO],
MountOption::Exec => vec![MountOption::NoExec],
MountOption::NoExec => vec![MountOption::Exec],
MountOption::Atime => vec![MountOption::NoAtime],
MountOption::NoAtime => vec![MountOption::Atime],
MountOption::DirSync => vec![],
MountOption::Sync => vec![MountOption::Async],
MountOption::Async => vec![MountOption::Sync],
}
}
// Format option to be passed to libfuse or kernel
pub fn option_to_string(option: &MountOption) -> String {
match option {
MountOption::FSName(name) => format!("fsname={}", name),
MountOption::Subtype(subtype) => format!("subtype={}", subtype),
MountOption::CUSTOM(value) => value.to_string(),
MountOption::AutoUnmount => "auto_unmount".to_string(),
MountOption::AllowOther => "allow_other".to_string(),
// AllowRoot is implemented by allowing everyone access and then restricting to
// root + owner within fuser
MountOption::AllowRoot => "allow_other".to_string(),
MountOption::DefaultPermissions => "default_permissions".to_string(),
MountOption::Dev => "dev".to_string(),
MountOption::NoDev => "nodev".to_string(),
MountOption::Suid => "suid".to_string(),
MountOption::NoSuid => "nosuid".to_string(),
MountOption::RO => "ro".to_string(),
MountOption::RW => "rw".to_string(),
MountOption::Exec => "exec".to_string(),
MountOption::NoExec => "noexec".to_string(),
MountOption::Atime => "atime".to_string(),
MountOption::NoAtime => "noatime".to_string(),
MountOption::DirSync => "dirsync".to_string(),
MountOption::Sync => "sync".to_string(),
MountOption::Async => "async".to_string(),
}
}
/// Parses mount command args.
///
/// Input: ["-o", "suid", "-o", "ro,nodev,noexec", "-osync"]
/// Output Ok([Suid, RO, NoDev, NoExec, Sync])
pub(crate) fn parse_options_from_args(args: &[&OsStr]) -> io::Result<Vec<MountOption>> {
let err = |x| io::Error::new(ErrorKind::InvalidInput, x);
let args: Option<Vec<_>> = args.iter().map(|x| x.to_str()).collect();
let args = args.ok_or_else(|| err("Error parsing args: Invalid UTF-8".to_owned()))?;
let mut it = args.iter();
let mut out = vec![];
loop {
let opt = match it.next() {
None => break,
Some(&"-o") => *it.next().ok_or_else(|| {
err("Error parsing args: Expected option, reached end of args".to_owned())
})?,
Some(x) if x.starts_with("-o") => &x[2..],
Some(x) => return Err(err(format!("Error parsing args: expected -o, got {}", x))),
};
for x in opt.split(',') {
out.push(MountOption::from_str(x))
}
}
Ok(out)
}
#[cfg(test)]
mod test {
use std::os::unix::prelude::OsStrExt;
use super::*;
#[test]
fn option_checking() {
assert!(check_option_conflicts(&[MountOption::Suid, MountOption::NoSuid]).is_err());
assert!(check_option_conflicts(&[MountOption::Suid, MountOption::NoExec]).is_ok());
}
#[test]
fn option_round_trip() {
use super::MountOption::*;
for x in [
FSName("Blah".to_owned()),
Subtype("Bloo".to_owned()),
CUSTOM("bongos".to_owned()),
AllowOther,
AutoUnmount,
DefaultPermissions,
Dev,
NoDev,
Suid,
NoSuid,
RO,
RW,
Exec,
NoExec,
Atime,
NoAtime,
DirSync,
Sync,
Async,
]
.iter()
{
assert_eq!(*x, MountOption::from_str(option_to_string(x).as_ref()))
}
}
#[test]
fn test_parse_options() {
use super::MountOption::*;
assert_eq!(parse_options_from_args(&[]).unwrap(), &[]);
let o: Vec<_> = "-o suid -o ro,nodev,noexec -osync"
.split(' ')
.map(OsStr::new)
.collect();
let out = parse_options_from_args(o.as_ref()).unwrap();
assert_eq!(out, [Suid, RO, NoDev, NoExec, Sync]);
assert!(parse_options_from_args(&[OsStr::new("-o")]).is_err());
assert!(parse_options_from_args(&[OsStr::new("not o")]).is_err());
assert!(parse_options_from_args(&[OsStr::from_bytes(b"-o\xc3\x28")]).is_err());
}
}
|
extern crate buplab;
#[macro_use]
extern crate log;
use buplab::types::Size2;
use buplab::Config;
static CONFIG: Config = Config {
app_name: "Buplab",
app_organization: "Proggerij",
app_qualifier: "nl",
default_window_config: buplab::sdl::WindowConfig {
size: Size2 { w: 320, h: 240 },
},
};
fn main() -> ! {
let exit_code = if let Err(e) = buplab::run(&CONFIG) {
error!("{}", e);
1
} else {
0
};
std::process::exit(exit_code)
}
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use core::{
ops::{Add, Sub},
cmp::{Ord, PartialOrd, Ordering},
fmt::{self, Debug},
};
use crate::{
kty::{timespec, time_t, k_long},
result::{Result},
util::int::{Int},
};
use std::fmt::Formatter;
pub mod clock;
pub mod timer;
//pub mod tz;
pub fn time_from_timespec(t: timespec) -> Time {
Time {
seconds: t.tv_sec as i64,
nanoseconds: t.tv_nsec as i64,
}
}
pub fn time_to_timespec(d: Time) -> timespec {
timespec {
tv_sec: d.seconds as time_t,
tv_nsec: d.nanoseconds as k_long,
}
}
const NANOS_PER_SEC: i64 = 1_000_000_000;
const NANOS_PER_MILLI: i64 = 1_000_000;
const NANOS_PER_MICRO: i64 = 1_000;
const MICROS_PER_SEC: i64 = 1_000_000;
const MILLIS_PER_SEC: i64 = 1_000;
const SECS_PER_MIN: i64 = 60;
const SECS_PER_HOUR: i64 = 60 * SECS_PER_MIN;
const SECS_PER_DAY: i64 = 24 * SECS_PER_HOUR;
/// A time offset.
///
/// = Remarks
///
/// This can have various meanings such as the duration of a timeout parameter or the
/// offset from the epoch when a file was created.
#[derive(Pod, Copy, Clone, PartialEq, Eq)]
pub struct Time {
/// The seconds part of the offset.
pub seconds: i64,
/// The nanoseconds part of the offset.
pub nanoseconds: i64,
}
impl Time {
/// Normalizes the time.
///
/// = Remarks
///
/// That is, transforms `self` into an equivalent representation where `nanoseconds`
/// is in [0, 1_000_000_000).
pub fn normalize(self) -> Time {
let (mut sec, mut nano) = self.nanoseconds.div_rem(NANOS_PER_SEC);
if nano < 0 {
sec -= 1;
nano += NANOS_PER_SEC;
}
Time { seconds: self.seconds.saturating_add(sec), nanoseconds: nano }
}
/// Creates a `Time` that represents a number of nanoseconds.
///
/// [argument, n]
/// The number of nanoseconds.
pub fn nanoseconds(n: i64) -> Time {
let (s, n) = n.div_rem(NANOS_PER_SEC);
Time { seconds: s, nanoseconds: n }
}
/// Creates a `Time` that represents a number of microseconds.
///
/// [argument, m]
/// The number of microseconds.
pub fn microseconds(m: i64) -> Time {
let (s, m) = m.div_rem(MICROS_PER_SEC);
Time { seconds: s, nanoseconds: m * NANOS_PER_MICRO }
}
/// Creates a `Time` that represents a number of milliseconds.
///
/// [argument, m]
/// The number of milliseconds.
pub fn milliseconds(m: i64) -> Time {
let (s, m) = m.div_rem(MILLIS_PER_SEC);
Time { seconds: s, nanoseconds: m * NANOS_PER_MILLI }
}
/// Creates a `Time` that represents a number of seconds.
///
/// [argument, s]
/// The number of seconds.
pub fn seconds(s: i64) -> Time {
Time { seconds: s, nanoseconds: 0 }
}
/// Creates a `Time` that represents a number of minutes.
///
/// [argument, m]
/// The number of minutes.
pub fn minutes(m: i64) -> Time {
Time::seconds(m.wrapping_mul(SECS_PER_MIN))
}
/// Creates a `Time` that represents a number of hours.
///
/// [argument, h]
/// The number of hours.
pub fn hours(h: i64) -> Time {
Time::seconds(h.wrapping_mul(SECS_PER_HOUR))
}
/// Creates a `Time` that represents a number of days.
///
/// [argument, d]
/// The number of days.
pub fn days(d: i64) -> Time {
Time::seconds(d.wrapping_mul(SECS_PER_DAY))
}
}
impl Debug for Time {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let time = self.normalize();
core::write!(f, "\"{}s {}ns\"", time.seconds, time.nanoseconds)
}
}
impl Add for Time {
type Output = Time;
fn add(self, other: Time) -> Time {
let one = self.normalize();
let two = other.normalize();
let time = Time {
seconds: one.seconds.saturating_add(two.seconds),
nanoseconds: one.nanoseconds + two.nanoseconds,
};
time.normalize()
}
}
impl Sub for Time {
type Output = Time;
fn sub(self, other: Time) -> Time {
let one = self.normalize();
let two = other.normalize();
let time = Time {
seconds: one.seconds.saturating_sub(two.seconds),
nanoseconds: one.nanoseconds - two.nanoseconds,
};
time.normalize()
}
}
impl PartialOrd for Time {
fn partial_cmp(&self, other: &Time) -> Option<Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for Time {
fn cmp(&self, other: &Time) -> Ordering {
let one = self.normalize();
let two = other.normalize();
(one.seconds, one.nanoseconds).cmp(&(two.seconds, two.nanoseconds))
}
}
|
//! This crate provides various matcher algorithms for line oriented search given the query string.
//!
//! The matcher result consists of the score and the indices of matched items.
//!
//! There two steps to match a line:
//!
//! // RawSearchLine
//! // |
//! // |
//! // |
//! // ↓
//! // Apply exact/inverse search term
//! // |
//! // |
//! // |
//! // ↓
//! // Apply fuzzy search term
//! // |
//! // | MatchType: extract the content to match.
//! // | FuzzyAlgorithm: run the match algorithm on MatchText.
//! // |
//! // ↓
//! // MatchResult
//!
mod algo;
mod bonus;
pub use self::algo::{fzy, skim, substring, FuzzyAlgorithm};
pub use self::bonus::cwd::Cwd;
pub use self::bonus::language::Language;
pub use self::bonus::Bonus;
// Re-export types
pub use types::{
ExactTerm, ExactTermType, FuzzyTermType, MatchType, MatchingText, Query, SearchTerm,
SourceItem, TermType,
};
/// Score of base matching algorithm(fzy, skim, etc).
pub type Score = i64;
/// A tuple of (score, matched_indices) for the line has a match given the query string.
pub type MatchResult = Option<(Score, Vec<usize>)>;
// TODO: the shorter search line has a higher score for the exact matching?
pub fn search_exact_terms<'a>(
terms: impl Iterator<Item = &'a ExactTerm>,
full_search_line: &str,
) -> Option<(Score, Vec<usize>)> {
use ExactTermType::*;
let mut indices = Vec::<usize>::new();
let mut exact_score = Score::default();
for term in terms {
let sub_query = &term.word;
match term.ty {
Exact => {
if let Some((score, sub_indices)) =
substring::substr_indices(full_search_line, sub_query)
{
indices.extend_from_slice(&sub_indices);
exact_score += std::cmp::max(score, sub_query.len() as Score);
} else {
return None;
}
}
PrefixExact => {
let trimmed = full_search_line.trim_start();
let white_space_len = if full_search_line.len() > trimmed.len() {
full_search_line.len() - trimmed.len()
} else {
0
};
if trimmed.starts_with(sub_query) {
let new_len = indices.len() + sub_query.len();
let mut start = -1i32 + white_space_len as i32;
indices.resize_with(new_len, || {
start += 1;
start as usize
});
exact_score += sub_query.len() as Score;
} else {
return None;
}
}
SuffixExact => {
let trimmed = full_search_line.trim_end();
let white_space_len = if full_search_line.len() > trimmed.len() {
full_search_line.len() - trimmed.len()
} else {
0
};
if trimmed.ends_with(sub_query) {
let total_len = full_search_line.len();
// In case of underflow, we use i32 here.
let mut start =
total_len as i32 - sub_query.len() as i32 - 1i32 - white_space_len as i32;
let new_len = indices.len() + sub_query.len();
indices.resize_with(new_len, || {
start += 1;
start as usize
});
exact_score += sub_query.len() as Score;
} else {
return None;
}
}
}
}
Some((exact_score, indices))
}
/// `Matcher` is composed of two components:
///
/// * `match_type`: represents the way of extracting the matching piece from the raw line.
/// * `algo`: algorithm used for matching the text.
/// * `bonus`: add a bonus to the result of base `algo`.
#[derive(Debug, Clone)]
pub struct Matcher {
fuzzy_algo: FuzzyAlgorithm,
match_type: MatchType,
bonuses: Vec<Bonus>,
}
impl Matcher {
/// Constructs a new instance of [`Matcher`].
pub fn new(fuzzy_algo: FuzzyAlgorithm, match_type: MatchType, bonus: Bonus) -> Self {
Self {
fuzzy_algo,
match_type,
bonuses: vec![bonus],
}
}
/// Constructs a new instance of [`Matcher`] with multiple bonuses.
pub fn with_bonuses(
fuzzy_algo: FuzzyAlgorithm,
match_type: MatchType,
bonuses: Vec<Bonus>,
) -> Self {
Self {
fuzzy_algo,
match_type,
bonuses,
}
}
/// Match the item without considering the bonus.
#[inline]
fn fuzzy_match<'a, T: MatchingText<'a>>(&self, item: &T, query: &str) -> MatchResult {
self.fuzzy_algo.fuzzy_match(query, item, &self.match_type)
}
/// Returns the sum of bonus score.
fn calc_bonus<'a, T: MatchingText<'a>>(
&self,
item: &T,
base_score: Score,
base_indices: &[usize],
) -> Score {
self.bonuses
.iter()
.map(|b| b.bonus_score(item, base_score, base_indices))
.sum()
}
/// Actually performs the matching algorithm.
pub fn match_query<'a, T: MatchingText<'a>>(&self, item: &T, query: &Query) -> MatchResult {
// Try the inverse terms against the full search line.
for inverse_term in query.inverse_terms.iter() {
if inverse_term.match_full_line(item.full_text()) {
return None;
}
}
// Try the exact terms against the full search line.
let (exact_score, mut indices) =
match search_exact_terms(query.exact_terms.iter(), item.full_text()) {
Some(ret) => ret,
None => return None,
};
// Try the fuzzy terms against the matched text.
let mut fuzzy_indices = Vec::<usize>::new();
let mut fuzzy_score = Score::default();
for term in query.fuzzy_terms.iter() {
let query = &term.word;
if let Some((score, sub_indices)) = self.fuzzy_match(item, query) {
fuzzy_indices.extend_from_slice(&sub_indices);
fuzzy_score += score;
} else {
return None;
}
}
if fuzzy_indices.is_empty() {
let bonus_score = self.calc_bonus(item, exact_score, &indices);
indices.sort_unstable();
indices.dedup();
Some((exact_score + bonus_score, indices))
} else {
fuzzy_indices.sort_unstable();
fuzzy_indices.dedup();
let bonus_score = self.calc_bonus(item, fuzzy_score, &fuzzy_indices);
indices.extend_from_slice(fuzzy_indices.as_slice());
indices.sort_unstable();
indices.dedup();
Some((exact_score + bonus_score + fuzzy_score, indices))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fzy;
#[test]
fn test_resize() {
let total_len = 100;
let sub_query = "hello";
let new_indices1 = {
let mut indices = [1, 2, 3].to_vec();
let sub_indices = (total_len - sub_query.len()..total_len).collect::<Vec<_>>();
indices.extend_from_slice(&sub_indices);
indices
};
let new_indices2 = {
let mut indices = [1, 2, 3].to_vec();
let mut start = total_len - sub_query.len() - 1;
let new_len = indices.len() + sub_query.len();
indices.resize_with(new_len, || {
start += 1;
start
});
indices
};
assert_eq!(new_indices1, new_indices2);
}
#[test]
fn test_exclude_grep_filepath() {
fn apply_on_grep_line_fzy(item: &SourceItem, query: &str) -> MatchResult {
FuzzyAlgorithm::Fzy.fuzzy_match(query, item, &MatchType::IgnoreFilePath)
}
let query = "rules";
let line = "crates/maple_cli/src/lib.rs:2:1:macro_rules! println_json {";
let (_, origin_indices) = fzy::fuzzy_indices(line, query).unwrap();
let (_, indices) = apply_on_grep_line_fzy(&line.to_string().into(), query).unwrap();
assert_eq!(origin_indices, indices);
}
#[test]
fn test_file_name_only() {
fn apply_on_file_line_fzy(item: &SourceItem, query: &str) -> MatchResult {
FuzzyAlgorithm::Fzy.fuzzy_match(query, item, &MatchType::FileName)
}
let query = "lib";
let line = "crates/extracted_fzy/src/lib.rs";
let (_, origin_indices) = fzy::fuzzy_indices(line, query).unwrap();
let (_, indices) = apply_on_file_line_fzy(&line.to_string().into(), query).unwrap();
assert_eq!(origin_indices, indices);
}
#[test]
fn test_filename_bonus() {
let lines = vec![
"autoload/clap/filter.vim",
"autoload/clap/provider/files.vim",
"lua/fzy_filter.lua",
];
let matcher = Matcher::new(FuzzyAlgorithm::Fzy, MatchType::Full, Bonus::FileName);
let query = "fil";
for line in lines {
let (base_score, indices1) =
matcher.fuzzy_match(&SourceItem::from(line), query).unwrap();
let (score_with_bonus, indices2) = matcher.match_query(&line, &query.into()).unwrap();
assert!(indices1 == indices2);
assert!(score_with_bonus > base_score);
}
}
#[test]
fn test_filetype_bonus() {
let lines = vec!["hellorsr foo", "function foo"];
let matcher = Matcher::new(
FuzzyAlgorithm::Fzy,
MatchType::Full,
Bonus::Language("vim".into()),
);
let query: Query = "fo".into();
let (score_1, indices1) = matcher.match_query(&lines[0], &query).unwrap();
let (score_2, indices2) = matcher.match_query(&lines[1], &query).unwrap();
assert!(indices1 == indices2);
assert!(score_1 < score_2);
}
#[test]
fn test_search_syntax() {
let items: Vec<SourceItem> = vec![
"autoload/clap/provider/search_history.vim".into(),
"autoload/clap/provider/files.vim".into(),
"vim-clap/crates/matcher/src/algo.rs".into(),
"pythonx/clap/scorer.py".into(),
];
let matcher = Matcher::new(FuzzyAlgorithm::Fzy, MatchType::Full, Bonus::FileName);
let query: Query = "clap .vim$ ^auto".into();
let matched_results: Vec<_> = items
.iter()
.map(|item| matcher.match_query(item, &query))
.collect();
assert_eq!(
vec![
Some((751, [0, 1, 2, 3, 9, 10, 11, 12, 37, 38, 39, 40].to_vec())),
Some((760, [0, 1, 2, 3, 9, 10, 11, 12, 28, 29, 30, 31].to_vec())),
None,
None
],
matched_results
);
let query: Query = ".rs$".into();
let matched_results: Vec<_> = items
.iter()
.map(|item| matcher.match_query(item, &query))
.collect();
assert_eq!(
vec![None, None, Some((4, [32, 33, 34].to_vec())), None],
matched_results
);
let query: Query = "py".into();
let matched_results: Vec<_> = items
.iter()
.map(|item| matcher.match_query(item, &query))
.collect();
assert_eq!(
vec![
Some((126, [14, 36].to_vec())),
None,
None,
Some((360, [0, 1].to_vec()))
],
matched_results
);
let query: Query = "'py".into();
let matched_results: Vec<_> = items
.iter()
.map(|item| matcher.match_query(item, &query))
.collect();
assert_eq!(
vec![None, None, None, Some((2, [0, 1].to_vec()))],
matched_results
);
}
}
|
//! Nonspecific utilities and helpers for matters tangential to hyphenation.
use std::iter::Fuse;
pub struct Intersperse<I> where I: Iterator {
inner: Fuse<I>,
element: I::Item,
sequent: Option<I::Item>
}
impl<I> Iterator for Intersperse<I> where
I: Iterator,
I::Item: Clone
{
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
match self.sequent {
Some(_) => self.sequent.take(),
None => self.inner.next().and_then(|e| {
self.sequent = Some(e);
Some(self.element.clone())
})
}
}
}
pub trait Interspersable : Iterator {
fn intersperse(self, e: Self::Item) -> Intersperse<Self> where Self: Sized;
}
impl<I> Interspersable for I where I: Iterator {
fn intersperse(self: I, e: I::Item) -> Intersperse<I> {
let mut i = self.fuse();
let s = i.next();
Intersperse {
inner: i,
element: e,
sequent: s
}
}
}
|
#![doc(html_no_source)]
include!("src/impl.rs");
fn main() {
resource_dir("./tests").build().unwrap();
}
|
use std::collections::HashMap;
use std::net::SocketAddr;
use std::ops::Deref;
use std::time::Duration;
use crate::packet::{self, KeyExchange, Packet, Version};
/// The `Hassh` of SSH fingerprinting
#[derive(Clone, Debug, PartialEq)]
pub struct Hassh {
pub ts: Option<Duration>,
pub src: SocketAddr,
pub dest: SocketAddr,
pub version: Version,
pub kex: KeyExchange,
}
impl Deref for Hassh {
type Target = KeyExchange;
fn deref(&self) -> &Self::Target {
&self.kex
}
}
impl KeyExchange {
pub fn client_algo(&self) -> String {
format!(
"{};{};{};{}",
self.kex_algs,
self.encr_algs_client_to_server,
self.mac_algs_client_to_server,
self.comp_algs_client_to_server,
)
}
pub fn server_algo(&self) -> String {
format!(
"{};{};{};{}",
self.kex_algs,
self.encr_algs_server_to_client,
self.mac_algs_server_to_client,
self.comp_algs_server_to_client,
)
}
pub fn client_hash(&self) -> md5::Digest {
md5::compute(self.client_algo())
}
pub fn server_hash(&self) -> md5::Digest {
md5::compute(self.server_algo())
}
}
/// Analyze SSH fingerprinting for Hassh
#[derive(Debug, Default)]
pub struct Hassher {
versions: HashMap<(SocketAddr, SocketAddr), Version>,
}
impl Hassher {
/// Anaylze a buffered packet
pub fn process_packet(&mut self, data: &[u8], ts: Option<Duration>) -> Option<Hassh> {
let (src, dest, packet) = packet::parse(data).ok().flatten()?;
match packet {
Packet::Version(version) => {
self.versions.insert((src, dest), version);
None
}
Packet::KeyExchange(kex) => Some(Hassh {
ts,
src,
dest,
version: self.versions.get(&(src, dest)).cloned()?,
kex,
}),
}
}
}
|
use std::ops::{Range, Deref, DerefMut};
use std::cmp::Ordering;
use crate::microvm::memory::MemoryError;
use crate::microvm::memory::address::*;
use crate::microvm::memory::address_space::AddressSpace;
pub struct SparseAddressSpace<Address: AddressType> {
spaces: Vec<OffsetAddressSpace<Address, dyn AddressSpace<Address>, Box<dyn AddressSpace<Address>>>>,
size: Address,
}
pub struct OffsetAddressSpace<Address, Space, SpaceStorage> where
Address: AddressType,
Space: AddressSpace<Address> + ?Sized,
SpaceStorage: Deref<Target=Space> {
offset: Address,
space: SpaceStorage
}
pub struct OffsetAddressSpaceMut<Address, Space, SpaceStorage> where
Address: AddressType,
Space: AddressSpace<Address> + ?Sized,
SpaceStorage: Deref<Target=Space> + DerefMut {
offset: Address,
space: SpaceStorage
}
impl<'a, Address, Space, SpaceStorage> OffsetAddressSpaceMut<Address, Space, SpaceStorage> where
Address: AddressType,
Space: AddressSpace<Address> + ?Sized,
SpaceStorage: Deref<Target=Space> + DerefMut {
pub fn as_ref(&self) -> OffsetAddressSpace<Address, Space, &Space> {
OffsetAddressSpace { offset: self.offset, space: &self.space.deref() }
}
}
impl<Address, Space, SpaceStorage> OffsetAddressSpace<Address, Space, SpaceStorage> where
Address: AddressType,
Space: AddressSpace<Address> + ?Sized,
SpaceStorage: Deref<Target=Space> {
pub fn address_range(&self) -> Range<Address> {
Range { start: self.offset, end: self.space.size()+self.offset }
}
pub fn sub_offset(&self, range: Range<Address>) -> Result<Range<Address>, MemoryError> {
Ok(Range { start: range.start.checked_sub(&self.offset).ok_or(MemoryError::Underflow)?, end: range.end-self.offset })
}
pub fn relative_range(&self, range: Range<Address>) -> Result<Range<Address>, MemoryError> {
match self.sub_offset(range) {
Ok(r) => Ok(r),
Err(e) => {
if e == MemoryError::Underflow {
Err(MemoryError::OutOfBounds)
} else {
Err(e)
}
},
}
}
pub fn does_overlap<OSpaceStorage: Deref<Target=Space>>(&self, other: &OffsetAddressSpace<Address, Space, OSpaceStorage>) -> bool {
let r1 = self.address_range();
let r2 = other.address_range();
r1.contains(&r2.start) || r1.contains(&r2.end) || r2.contains(&r1.start) || r2.contains(&r1.end)
}
}
impl<Address, Space, SpaceStorage> AddressSpace<Address> for OffsetAddressSpaceMut<Address, Space, SpaceStorage> where
Address: AddressType,
Space: AddressSpace<Address> + ?Sized,
SpaceStorage: Deref<Target=Space> + DerefMut {
fn size(&self) -> Address {
self.space.deref().size()
}
fn read_byte(&self, address: Address) -> Result<u8, MemoryError> {
self.space.read_byte(self.offset.checked_add(&address).ok_or(MemoryError::Overflow)?)
}
fn write_bytes(&mut self, address: Address, bytes: &[u8]) -> Result<(), MemoryError> {
self.space.deref_mut().write_bytes(address.checked_sub(&self.offset).ok_or(MemoryError::OutOfBounds)?, bytes)
}
fn address_in_space(&self, address: Address) -> bool {
self.as_ref().address_range().contains(&address)
}
}
impl<Address, Space, SpaceStorage> AddressSpace<Address> for OffsetAddressSpace<Address, Space, SpaceStorage> where
Address: AddressType,
Space: AddressSpace<Address> + ?Sized,
SpaceStorage: Deref<Target=Space> {
fn size(&self) -> Address {
self.space.deref().size()
}
fn read_byte(&self, address: Address) -> Result<u8, MemoryError> {
self.space.read_byte(self.offset.checked_add(&address).ok_or(MemoryError::Overflow)?)
}
fn address_in_space(&self, address: Address) -> bool {
self.address_range().contains(&address)
}
}
impl<'a, Address: AddressType> SparseAddressSpace< Address> {
pub fn new(size: Address) -> SparseAddressSpace< Address> {
SparseAddressSpace {
spaces: Vec::with_capacity(4),
size
}
}
pub fn add_space(&mut self, offset: Address, new_space: Box<dyn AddressSpace<Address>>) -> Result<(), MemoryError> {
if offset+new_space.as_ref().size() > self.size {
return Err(MemoryError::Overflow)
}
let new_offset_space = OffsetAddressSpace {
offset: offset,
space: new_space
};
for space in self.spaces.iter() {
if space.does_overlap(&new_offset_space) {
return Err(MemoryError::Overlap)
}
}
let position = self.find_space_position(offset).err().ok_or(MemoryError::Overlap)?;
self.spaces.insert(position, new_offset_space);
Ok(())
}
fn find_space_position(&self, containing_address: Address) -> Result<usize, usize> {
self.spaces.binary_search_by(|space| {
if space.offset > containing_address {
Ordering::Greater
} else if space.address_in_space(containing_address) {
Ordering::Equal
} else {
Ordering::Less
}
})
}
pub fn find_space(&'a self, containing_address: Address) -> Option<OffsetAddressSpace<Address, dyn AddressSpace<Address>+'a, &'a dyn AddressSpace<Address>>> {
let i = self.find_space_position(containing_address).ok()?;
let oa = self.spaces.get(i)?;
let out = OffsetAddressSpace { offset: oa.offset, space: oa.space.deref() };
return Some(out);
}
pub fn find_space_mut(&'a mut self, containing_address: Address) -> Option<OffsetAddressSpace<Address, dyn AddressSpace<Address>+'a, &'a mut dyn AddressSpace<Address>>> {
let i = self.find_space_position(containing_address).ok()?;
let oa = self.spaces.get_mut(i)?;
let space = oa.space.deref_mut();
//FIXME:
// work around for https://github.com/rust-lang/rust/issues/53613
let fixxed_space: &mut dyn AddressSpace<Address> = unsafe {
std::mem::transmute(space)
};
Some(OffsetAddressSpace { offset: oa.offset, space: fixxed_space })
}
}
impl< Address: AddressType> AddressSpace<Address> for SparseAddressSpace< Address> {
fn size(&self) -> Address {
self.size.clone()
}
fn read_byte(&self, address: Address) -> Result<u8, MemoryError> {
self.find_space(address).ok_or(MemoryError::InvalidAccess)?.read_byte(address)
}
fn write_bytes(&mut self, address: Address, bytes: &[u8]) -> Result<(), MemoryError> {
let space = self.find_space_mut(address).ok_or(MemoryError::InvalidAccess)?;
let start = address - space.offset;
let end = start+Address::from_usize(bytes.len()).ok_or(MemoryError::Overflow)?;
if end > space.offset.checked_add(&space.space.size()).ok_or(MemoryError::Overflow)? {
Err(MemoryError::InvalidAccess)
} else {
space.space.write_bytes(start, bytes)
}
}
}
|
use crate::utils::{sleep, wait_until};
use crate::{Net, Spec};
use log::info;
pub struct IBDProcess;
impl Spec for IBDProcess {
crate::name!("ibd_process");
crate::setup!(num_nodes: 7, connect_all: false);
fn run(&self, net: &mut Net) {
info!("Running IBD process");
let node0 = &net.nodes[0];
let node1 = &net.nodes[1];
let node2 = &net.nodes[2];
let node3 = &net.nodes[3];
let node4 = &net.nodes[4];
let node5 = &net.nodes[5];
let node6 = &net.nodes[6];
node0.connect(node1);
node0.connect(node2);
node0.connect(node3);
node0.connect(node4);
// The node's outbound connection does not retain the peer which in the ibd state
node0.generate_blocks(1);
// will never connect
node0.connect_uncheck(node5);
node0.connect_uncheck(node6);
sleep(5);
let rpc_client0 = node0.rpc_client();
let is_connect_peer_num_eq_4 = wait_until(10, || {
let peers = rpc_client0.get_peers();
peers.len() == 4
});
if !is_connect_peer_num_eq_4 {
panic!("refuse to connect fail");
}
// IBD only with outbound/whitelist node
let rpc_client1 = node1.rpc_client();
let rpc_client2 = node2.rpc_client();
let rpc_client3 = node3.rpc_client();
let rpc_client4 = node4.rpc_client();
let rpc_client5 = node5.rpc_client();
let rpc_client6 = node6.rpc_client();
let is_nodes_ibd_sync = wait_until(10, || {
let header1 = rpc_client1.get_tip_header();
let header2 = rpc_client2.get_tip_header();
let header3 = rpc_client3.get_tip_header();
let header4 = rpc_client4.get_tip_header();
let header5 = rpc_client5.get_tip_header();
let header6 = rpc_client6.get_tip_header();
header1.inner.number.value() == 0
&& header1 == header6
&& header1 == header5
&& header1 == header4
&& header1 == header3
&& header1 == header2
});
assert!(is_nodes_ibd_sync, "node 1-6 must not sync with node0");
node5.connect(node0);
node6.connect(node0);
let is_node_sync = wait_until(10, || {
let header5 = rpc_client5.get_tip_header();
let header6 = rpc_client6.get_tip_header();
header5 == header6 && header5.inner.number.value() == 1
});
assert!(is_node_sync, "node 5-6 must sync with node0");
}
}
pub struct IBDProcessWithWhiteList;
impl Spec for IBDProcessWithWhiteList {
crate::name!("ibd_process_with_whitelist");
crate::setup!(num_nodes: 7, connect_all: false);
fn run(&self, net: &mut Net) {
info!("Running IBD process with whitelist");
{
let node6_listen = format!(
"/ip4/127.0.0.1/tcp/{}/p2p/{}",
net.nodes[6].p2p_port(),
net.nodes[6].node_id()
);
net.nodes[0].stop();
// whitelist will be connected on outbound on node start
net.nodes[0].edit_config_file(
Box::new(|_| ()),
Box::new(move |config| {
config.network.whitelist_peers = vec![node6_listen.parse().unwrap()]
}),
);
net.nodes[0].start();
}
let node0 = &net.nodes[0];
let node1 = &net.nodes[1];
let node2 = &net.nodes[2];
let node3 = &net.nodes[3];
let node4 = &net.nodes[4];
let node5 = &net.nodes[5];
let node6 = &net.nodes[6];
node0.connect(node1);
node0.connect(node2);
node0.connect(node3);
node0.connect(node4);
// will never connect, protect node default is 4, see
// https://github.com/nervosnetwork/ckb/blob/da8897dbc8382293bdf8fadea380a0b79c1efa92/sync/src/lib.rs#L57
node0.connect_uncheck(node5);
let rpc_client0 = node0.rpc_client();
let is_connect_peer_num_eq_5 = wait_until(10, || {
let peers = rpc_client0.get_peers();
peers.len() == 5
});
if !is_connect_peer_num_eq_5 {
panic!("refuse to connect fail");
}
// After the whitelist is disconnected, it will always try to reconnect.
// In order to ensure that the node6 has already generated two blocks when reconnecting,
// it must be in the connected state, and then disconnected.
node6.generate_blocks(2);
let generate_res = wait_until(10, || net.nodes[6].get_tip_block_number() == 2);
if !generate_res {
panic!("node6 can't generate blocks to 2");
}
// Although the disconnection of the whitelist is automatically reconnected for node0,
// the disconnect operation is still needed here to instantly refresh the state of node6 in node0.
node6.disconnect(node0);
// Make sure node0 re-connect with node6
node0.connect(node6);
// IBD only with outbound/whitelist node
let rpc_client1 = node1.rpc_client();
let rpc_client2 = node2.rpc_client();
let rpc_client3 = node3.rpc_client();
let rpc_client4 = node4.rpc_client();
let rpc_client5 = node5.rpc_client();
let rpc_client6 = node6.rpc_client();
let is_nodes_ibd_sync = wait_until(10, || {
let header0 = rpc_client0.get_tip_header();
let header1 = rpc_client1.get_tip_header();
let header2 = rpc_client2.get_tip_header();
let header3 = rpc_client3.get_tip_header();
let header4 = rpc_client4.get_tip_header();
let header5 = rpc_client5.get_tip_header();
let header6 = rpc_client6.get_tip_header();
header1.inner.number.value() == 0
&& header1 == header5
&& header1 == header4
&& header1 == header3
&& header1 == header2
&& header6.inner.number.value() == 2
&& header0 == header6
});
assert!(
is_nodes_ibd_sync,
"node 1-5 must not sync with node0, node 6 must sync with node0"
);
}
}
|
use amethyst::{
core::Transform,
core::timing::Time,
ecs::{Join, ReadStorage, ReadExpect, System, WriteStorage, Write},
shrev::EventChannel,
};
use crate::pong::{Ball, Paddle, AREA_HEIGHT, PongEvent};
use crate::audio::SoundEvent;
pub struct BounceSystem {
last_bounce: f32,
}
impl BounceSystem {
pub fn new() -> Self {
Self { last_bounce: 0.5 }
}
}
impl <'s> System<'s> for BounceSystem {
type SystemData = (
WriteStorage<'s, Ball>,
ReadStorage<'s, Paddle>,
ReadStorage<'s, Transform>,
ReadExpect<'s, Time>,
Write<'s, EventChannel<SoundEvent>>,
Write<'s, EventChannel<PongEvent>>,
);
fn run(&mut self, (mut balls, paddles, transforms, time, mut event_channel, mut pong_event_channel): Self::SystemData) {
if self.last_bounce > 0. {
self.last_bounce -= time.delta_seconds();
}
for (ball, transform) in (&mut balls, &transforms).join() {
let ball_x = transform.translation().x;
let ball_y = transform.translation().y;
let ball_y_velocity = ball.velocity[1];
if (ball_y <= ball.radius && ball_y_velocity < 0.0) || (ball_y >= AREA_HEIGHT - ball.radius && ball_y_velocity > 0.0) {
ball.velocity[1] = -ball.velocity[1];
}
for (paddle, paddle_transform) in (&paddles, &transforms).join() {
let paddle_x = paddle_transform.translation().x - (paddle.width * 0.5);
let paddle_y = paddle_transform.translation().y - (paddle.height * 0.5);
if point_in_rect(
ball_x, ball_y,
paddle_x - ball.radius, paddle_y - ball.radius,
paddle_x + paddle.width + ball.radius,
paddle_y + paddle.height + ball.radius
) {
if self.last_bounce > 0.0 {
return
}
ball.velocity[0] = -ball.velocity[0];
event_channel.single_write(SoundEvent::Bounce);
pong_event_channel.single_write(PongEvent::Bounce(ball.id));
self.last_bounce = 0.5;
}
}
}
}
}
fn point_in_rect(x: f32, y: f32, left: f32, bottom: f32, right: f32, top: f32) -> bool {
x >= left && x <= right && y >= bottom && y <= top
}
|
use serde::{Serialize, Deserialize, Serializer};
use serde::ser::SerializeStruct;
use blake2::{Blake2b, Digest};
use libp2p::PeerId;
use std::net::SocketAddr;
#[derive(Debug, Serialize, Deserialize)]
pub enum Message {
ClientRequest(ClientRequest),
PrePrepare(PrePrepare),
Prepare(Prepare),
Commit(Commit),
}
impl From<Vec<u8>> for Message {
fn from(item: Vec<u8>) -> Self {
serde_json::from_str(&String::from_utf8(item).unwrap()).unwrap()
}
}
impl From<String> for Message {
fn from(s: String) -> Self {
serde_json::from_str(&s).unwrap()
}
}
impl std::fmt::Display for Message {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", serde_json::to_string(self).unwrap())
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ClientRequest {
operation: String,
timestamp: u64,
client: SocketAddr,
}
impl ClientRequest {
pub fn operation(&self) -> String {
self.operation.clone()
}
pub fn timestamp(&self) -> u64 {
self.timestamp
}
pub fn client(&self) -> SocketAddr {
self.client.clone()
}
}
#[derive(Debug)]
pub struct ClientReply {
view: u64,
timestamp: u64,
client: SocketAddr, // Is this correct as `c`?
peer_id: PeerId,
result: String,
}
impl ClientReply {
pub fn new(peer_id: PeerId, client_request: &ClientRequest, commit: &Commit) -> Self {
Self {
view: commit.view(),
timestamp: client_request.timestamp(),
client: client_request.client(),
peer_id,
result: "awesome!".to_owned(), // TODO
}
}
}
impl ClientReply {
pub fn timestamp(&self) -> u64 {
self.timestamp
}
pub fn client_address(&self) -> SocketAddr {
self.client.clone()
}
}
impl Serialize for ClientReply {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("ClientReply", 4)?;
state.serialize_field("view", &self.view)?;
state.serialize_field("timestamp", &self.timestamp)?;
state.serialize_field("peer_id", &self.peer_id.to_string())?;
state.serialize_field("result", &self.result)?;
state.end()
}
}
impl std::fmt::Display for ClientReply {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", serde_json::to_string(self).unwrap())
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PrePrepare {
// view indicates the view in which the message is being sent
view: u64,
// sequence number for pre-prepare messages
sequence_number: u64,
// client message's digest
digest: String,
// client message
message: ClientRequest,
}
impl PrePrepare {
pub fn view(&self) -> u64 {
self.view
}
pub fn sequence_number(&self) -> u64 {
self.sequence_number
}
pub fn digest(&self) -> &String {
&self.digest
}
pub fn client_reqeust(&self) -> &ClientRequest {
&self.message
}
pub fn from(view: u64, n: u64, client_request: ClientRequest) -> Self {
let digest = digest(client_request.operation.as_bytes());
Self { view, sequence_number: n, digest, message: client_request }
}
pub fn validate_digest(&self) -> Result<(), String> {
if self.digest == digest(&self.message.operation.as_bytes()) {
Ok(())
} else {
Err(format!("The digest is not matched with message. digest: {}, message.operation: {}", self.digest, self.message.operation))
}
}
}
impl std::fmt::Display for PrePrepare {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", serde_json::to_string(self).unwrap())
}
}
pub struct PrePrepareSequence {
value: u64,
}
impl PrePrepareSequence {
pub fn new() -> Self {
Self { value: 0 }
}
pub fn increment(&mut self) {
let from = self.value.clone();
self.value += 1;
println!("[PrePrepareSequence::increment] value has been incremented from {} to {}", from, self.value);
}
pub fn value(&self) -> u64 {
self.value
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Prepare {
view: u64,
sequence_number: u64,
digest: String,
}
impl Prepare {
pub fn from(pre_prepare: &PrePrepare) -> Self {
Self {
view: pre_prepare.view,
sequence_number: pre_prepare.sequence_number,
digest: pre_prepare.digest.clone(),
}
}
pub fn view(&self) -> u64 {
self.view
}
pub fn sequence_number(&self) -> u64 {
self.sequence_number
}
pub fn digest(&self) -> &String {
&self.digest
}
}
impl std::fmt::Display for Prepare {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", serde_json::to_string(self).unwrap())
}
}
fn digest(message: &[u8]) -> String {
let hash = Blake2b::digest(message);
format!("{:x}", hash)
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Commit {
view: u64,
sequence_number: u64,
digest: String,
}
impl Commit {
pub fn view(&self) -> u64 {
self.view
}
pub fn sequence_number(&self) -> u64 {
self.sequence_number
}
}
impl From<Prepare> for Commit {
fn from(prepare: Prepare) -> Self {
Self {
view: prepare.view(),
sequence_number: prepare.sequence_number(),
digest: prepare.digest().clone(),
}
}
}
impl std::fmt::Display for Commit {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", serde_json::to_string(self).unwrap())
}
}
|
mod mod_ops;
extern crate byteorder;
use byteorder::{BigEndian, WriteBytesExt};
use std::mem;
use getopts::Options;
use yaml_rust::YamlLoader;
use std::fs;
use std::env;
use num_traits::cast::ToPrimitive;
fn main() {
// --- Adding cmd line arguments: ------------------
// -f: Path to input data yaml-file
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optopt("f", "file", "input file path", "input.yaml");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
if !matches.opt_present("f") {
println!("You must specify the input file path!");
return;
}
// -------------------------------------------------
// --- Parsing input yaml-file ---------------------
let file_contents = fs::read_to_string(matches.opt_str("f")
.unwrap()).unwrap();
let docs = YamlLoader::load_from_str(&file_contents).unwrap();
let doc = &docs[0];
let n = doc["N"].as_i64().unwrap();
let e = doc["e"].as_i64().unwrap();
// -------------------------------------------------
// --- Decoding every present chunk of data --------
let mut in_c = Vec::new(); // initialte input data vector
for c in doc["C"].as_vec().unwrap() {
in_c.push(c.as_i64().unwrap());
}
println!("Parsed {}\nN: {}\ne: {}\n{} chunks of data",
matches.opt_str("f").unwrap(), n, e, in_c.len());
println!("Trying to compute the exponent rank...");
let mut res = in_c.clone(); // result vector
let mut i = 1;
// in this loop we calculate [last_res[i]^e mod n] for every element
// and update last_res on every iteration until the first element
// of vector will match the initial chunk of data. That would mean
// that we have the decoded text in res
loop {
let mut last_res = res.clone();
for j in 0..in_c.len() {
last_res[j] = mod_ops::mod_exp(&res[j], &e, &n).to_i64().unwrap();
}
if last_res[0] == in_c[0] {
break;
}
res = last_res;
i += 1;
}
// Print the answer
println!("Found the exponent rank: {}", i);
let mut bs = [0u8; mem::size_of::<i64>()];
let mut res_s = String::new();
for r in res {
bs.as_mut()
.write_i64::<BigEndian>(r)
.expect("Unable to write");
let encoder = encoding_rs::WINDOWS_1251;
let (s, _, _) = encoder.decode(&bs);
res_s.push_str(&s);
}
println!("Message: {}", res_s);
}
|
#![cfg_attr(not(feature = "std"), no_std)]
use liquid::storage;
use liquid_lang as liquid;
#[liquid::contract]
mod parallel_ok {
use super::*;
type Balance = u128;
#[liquid(storage)]
struct ParallelOk {
balances: storage::Mapping<String, Balance>,
}
#[liquid(methods)]
impl ParallelOk {
pub fn new(&mut self) {
self.balances.initialize();
}
pub fn balance_of(&self, name: String) -> Balance {
*self.balances.get(&name).unwrap_or(&0)
}
pub fn set(&mut self, name: String, num: Balance) {
self.balances.insert(name, num);
}
pub fn transfer(&mut self, from: String, to: String, value: Balance) -> bool {
let from_balance = self.balance_of(from.clone());
if from_balance < value {
return false;
}
self.balances.insert(from.clone(), from_balance - value);
let to_balance = self.balance_of(to.clone());
self.balances.insert(to.clone(), to_balance + value);
true
}
}
}
|
#[derive(Debug)]
struct U {
i: i32,
s: String,
}
fn mod_u(u: &U) -> U {
// update syntax requires value not reference.
// copies values. fails if trying to reuse String value.
U {
s: String::from("new"),
..*u
}
}
fn main() {
let u = U { i: 100, s: String::from("string"), };
println!("{:?}, {:?}", u, mod_u(&u));
}
|
#![allow(unused_variables)]
use std::collections::HashMap;
use std::str::FromStr;
type Database = HashMap<String, String>;
type CmdOutput = Result<String, CmdError>;
type ErrorMsg = Option<String>;
#[derive(Debug, PartialEq)]
pub enum Cmd {
Ping,
Echo { output: String },
Set { key: String, value: String },
Get { key: String },
Del { key: String },
}
#[derive(Debug, PartialEq)]
pub enum CmdError {
UnknownCommandError(ErrorMsg),
InvalidCommandError(ErrorMsg),
InvalidArgumentError(ErrorMsg),
DatabaseError(ErrorMsg),
}
fn parse_args(args: Option<String>) -> Vec<String> {
args.clone()
.get_or_insert("".to_string())
.split_ascii_whitespace()
.map(|s| s.to_string())
.collect()
}
impl Cmd {
pub fn handle(self, db: &mut Database) -> CmdOutput {
use Cmd::*; // let's us use the Cmd invariants without prefixing them with `Self::`
match self {
Ping => Ok(String::from("PONG")),
Echo { output } => Ok(output),
Set { key, value } => Self::handle_set(key, value, db),
Get { key } => Self::handle_get(key, db),
Del { key } => Self::handle_del(key, db),
}
}
fn handle_set(key: String, value: String, db: &mut Database) -> CmdOutput {
db.insert(key.clone(), value.clone());
Ok(format!("\"{}\":\"{}\"", key, value))
}
fn handle_get(key: String, db: &mut Database) -> CmdOutput {
db.get(key.as_str())
.ok_or_else(|| CmdError::DatabaseError(Some("No value for key".to_string())))
.map(|s| s.to_string())
}
fn handle_del(key: String, db: &mut Database) -> CmdOutput {
if db.remove(key.as_str()).is_some() {
Ok(format!("Key \"{}\" deleted", key))
} else {
Err(CmdError::DatabaseError(Some(format!(
"Key \"{}\" does not exist",
key
))))
}
}
}
impl FromStr for Cmd {
type Err = CmdError;
fn from_str(input: &str) -> Result<Cmd, Self::Err> {
use CmdError::InvalidArgumentError;
let mut splitter = input.trim_end().splitn(2, ' ');
let cmd_str = splitter.next().unwrap().to_uppercase();
let args = parse_args(splitter.next().map(|s| s.to_string()));
match cmd_str.as_str() {
"PING" => Ok(Cmd::Ping),
"ECHO" => match &args[..] {
[_, ..] => Ok(Cmd::Echo {
output: args.join(" "),
}),
_ => Err(InvalidArgumentError(Some("Nothing to echo".to_string()))),
},
"SET" => match &args[..] {
[_] => Err(InvalidArgumentError(Some("No key specified".to_string()))),
[k, _, ..] => Ok(Cmd::Set {
key: k.to_string(),
value: args[1..].join(" "),
}),
_ => Err(InvalidArgumentError(Some("No key specified".to_string()))),
},
"GET" => match &args[..] {
[k, ..] => Ok(Cmd::Get { key: k.to_string() }),
_ => Err(InvalidArgumentError(Some("No key specified".to_string()))),
},
"DEL" => match &args[..] {
[k, ..] => Ok(Cmd::Del { key: k.to_string() }),
_ => Err(InvalidArgumentError(Some("No key specified".to_string()))),
},
_ => Err(CmdError::UnknownCommandError(Some(cmd_str.to_string()))),
}
}
}
impl CmdError {
fn get_full_msg(&self, name: &'static str, msg: &ErrorMsg) -> String {
let mut full_msg = String::from(name);
if let Some(m) = msg {
full_msg.push_str(format!(": {}", m).as_str())
}
full_msg
}
}
impl ToString for CmdError {
fn to_string(&self) -> String {
// TODO: Maybe look up how to do reflection to extract the symbol name
match self {
Self::UnknownCommandError(msg) => self.get_full_msg("UnknownCommandError", msg),
Self::InvalidCommandError(msg) => self.get_full_msg("InvalidCommandError", msg),
Self::InvalidArgumentError(msg) => self.get_full_msg("InvalidArgumentError", msg),
Self::DatabaseError(msg) => self.get_full_msg("DatabaseError", msg),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn str_to_cmd() {
assert_eq!(Cmd::from_str("pInG"), Ok(Cmd::Ping));
assert_eq!(
Cmd::from_str("get schwifty"),
Ok(Cmd::Get {
key: "get schwifty".to_string()
})
);
assert!(matches!(
Cmd::from_str("spiarmf slurmp"),
Err(CmdError::UnknownCommandError(_))
));
}
// #[test]
// fn handle_echo_cmd() {
// let mut db = Database::new();
// let cmd = Cmd::Echo(None);
// assert!(matches!(
// cmd.handle(&mut db),
// Err(CmdError::InvalidArgumentError(_))
// ));
// assert!(matches!(
// Cmd::Echo(Some("ermahgerd dergs".to_string())).handle(&mut db),
// Ok(_)
// ));
// assert!(matches!(
// Cmd::Echo(Some("".to_string())).handle(&mut db),
// Err(CmdError::InvalidArgumentError(_))
// ));
// assert!(matches!(
// Cmd::Echo(Some(" \n".to_string())).handle(&mut db),
// Err(CmdError::InvalidArgumentError(_))
// ));
// assert_eq!(
// Cmd::Echo(Some("Slurm\r\n".to_string())).handle(&mut db),
// Ok("Slurm".to_string())
// );
// }
}
|
use amethyst::core::{SystemDesc, Transform};
use amethyst::derive::SystemDesc;
use amethyst::ecs::{
Entities, Join, LazyUpdate, Read, ReadStorage, System, SystemData, World, Write, WriteStorage,
};
use amethyst::renderer::SpriteRender;
use ncollide2d::bounding_volume::{BoundingVolume, AABB};
use ncollide2d::math::Point;
use log::info;
use std::time::Duration;
use crate::state::{
AssetType, GameTimeController, Map, SpriteSheetList, TileStatus, ARENA_HEIGHT, ARENA_WIDTH,
TILE_COUNT_HORIZONTAL, TILE_COUNT_VERTICAL, TILE_HEIGHT, TILE_HEIGHT_HALF, TILE_WIDTH,
TILE_WIDTH_HALF,
};
use crate::entities::bomb::Bomb;
use crate::entities::explosion::{create_explosion, Explosion};
use crate::entities::player::{Player, PLAYER_HEIGHT_HALF, PLAYER_WIDTH_HALF};
const THREE_SECS: Duration = Duration::from_secs(3);
const EXPLOSION_DURATION: Duration = Duration::from_millis(500);
#[derive(SystemDesc)]
pub struct ExplosionSystem;
impl<'s> System<'s> for ExplosionSystem {
type SystemData = (
Entities<'s>,
Read<'s, LazyUpdate>,
ReadStorage<'s, Transform>,
WriteStorage<'s, Player>,
Read<'s, SpriteSheetList>,
Write<'s, Map>,
WriteStorage<'s, Bomb>,
WriteStorage<'s, Explosion>,
Read<'s, GameTimeController>,
);
fn run(
&mut self,
(
entities,
lazy_update,
transforms,
mut players,
sprite_sheet_list,
mut map,
mut bombs,
mut explosions,
game_time_controller,
): Self::SystemData,
) {
for (entity, explosion) in (&*entities, &mut explosions).join() {
for (entity, player, transform) in (&*entities, &mut players, &transforms).join() {
let bbox = AABB::new(
Point::new(
transform.translation().x - PLAYER_WIDTH_HALF,
transform.translation().y - PLAYER_HEIGHT_HALF,
),
Point::new(
transform.translation().x + PLAYER_WIDTH_HALF,
transform.translation().y + PLAYER_HEIGHT_HALF,
),
);
let collided = explosion.collision_polygon.intersects(&bbox);
if collided {
entities.delete(entity).unwrap();
info!("player {} dead", player.number);
}
}
let duration = game_time_controller
.stopwatch
.elapsed()
.checked_sub(explosion.created_time);
if let Some(d) = duration {
if d >= EXPLOSION_DURATION {
entities.delete(entity).unwrap();
}
}
}
for (entity, bomb, bomb_transform) in (&*entities, &mut bombs, &transforms).join() {
let duration = game_time_controller
.stopwatch
.elapsed()
.checked_sub(bomb.created_time);
if let Some(d) = duration {
if d < THREE_SECS {
continue;
}
entities.delete(entity).unwrap();
let bomb_tile = map.get_tile(
bomb_transform.translation().x,
bomb_transform.translation().y,
);
let coordinates = bomb_tile.coordinates;
let x = coordinates[0] as i32;
let y = coordinates[1] as i32;
let initial_coordinates = (
Point::new(
x as f32 * ARENA_WIDTH / TILE_COUNT_HORIZONTAL,
y as f32 * ARENA_HEIGHT / TILE_COUNT_VERTICAL,
),
Point::new(
x as f32 * ARENA_WIDTH / TILE_COUNT_HORIZONTAL + TILE_WIDTH,
y as f32 * ARENA_HEIGHT / TILE_COUNT_VERTICAL + TILE_HEIGHT,
),
);
let mut collision_polygons: Vec<AABB<f32>> = Vec::with_capacity(4);
for i in 0..4 {
// check all four directions
let mut collision_polygon;
for j in 1..(bomb.power + 1) {
let j = j as i32;
let (x, y) = match i {
0 => (x, y + j),
1 => (x + j, y),
2 => (x, y - j),
3 => (x - j, y),
_ => panic!("HOW?"),
};
if x < 0 || x > 12 || y < 0 || y > 10 {
continue;
}
let next_tile = map.get_tile_by_key(x as usize, y as usize);
match next_tile.status {
TileStatus::Wall => {
map.update_tile(x as usize, y as usize, TileStatus::Free);
let new_tile_entity = entities.create();
let mut new_tile_transform = Transform::default();
new_tile_transform.set_translation_xyz(
x as f32 * ARENA_WIDTH / TILE_COUNT_HORIZONTAL
+ TILE_WIDTH_HALF,
y as f32 * ARENA_HEIGHT / TILE_COUNT_VERTICAL
+ TILE_HEIGHT_HALF,
0.1,
);
let sprite_render = SpriteRender {
sprite_sheet: sprite_sheet_list
.get(AssetType::Bomb)
.unwrap()
.clone(),
sprite_number: 1,
};
lazy_update.insert(new_tile_entity, sprite_render);
lazy_update.insert(new_tile_entity, new_tile_transform);
break;
}
TileStatus::Free => {
if i < 2 {
collision_polygon = AABB::new(
initial_coordinates.0,
Point::new(
x as f32 * ARENA_WIDTH / TILE_COUNT_HORIZONTAL
+ TILE_WIDTH,
y as f32 * ARENA_HEIGHT / TILE_COUNT_VERTICAL
+ TILE_HEIGHT,
),
);
} else {
collision_polygon = AABB::new(
Point::new(
x as f32 * ARENA_WIDTH / TILE_COUNT_HORIZONTAL,
y as f32 * ARENA_HEIGHT / TILE_COUNT_VERTICAL,
),
initial_coordinates.1,
);
}
}
TileStatus::PermanentWall => break,
}
collision_polygons.push(collision_polygon);
}
create_explosion(
&entities,
&lazy_update,
&sprite_sheet_list,
&collision_polygons,
&AABB::new(initial_coordinates.0, initial_coordinates.1),
&game_time_controller.stopwatch,
);
for player in (&mut players).join() {
if player.number == bomb.player_number {
player.num_bombs = 1;
}
}
}
}
}
}
}
|
use ic_cdk::export::candid::Principal;
use ic_cdk::export::candid::{CandidType, Deserialize};
use ic_cdk::storage;
use ic_cdk::*;
use ic_cdk_macros::*;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
type Wall = Vec<Post>;
type Admins = Vec<Principal>;
type Addresses = BTreeMap<String, String>;
static mut OWNER: Option<Principal> = None;
#[derive(Clone, Debug, CandidType, Deserialize)]
struct Answer {
pub user: String,
pub eth_address: String,
pub text: String,
}
#[derive(Clone, Debug, CandidType, Deserialize)]
struct Post {
pub id: String,
pub user: String,
pub eth_address: String,
pub question: String,
pub answers: Vec<Answer>,
}
#[init]
fn init() {
unsafe{
OWNER = Some(ic_cdk::caller());
}
let admins = storage::get_mut::<Admins>();
admins.push(ic_cdk::caller());
}
#[query]
fn get_my_principal() -> Principal {
let p = ic_cdk::caller();
p
}
fn get_id(now_str: &String) -> String {
let mut hasher = Sha256::new();
let now: String = now_str.parse().unwrap();
hasher.update(now);
let short_id = hasher.finalize();
let b64_url = base64::encode_config(&short_id, base64::URL_SAFE);
b64_url
}
#[query]
fn get() -> &'static Vec<Post> {
storage::get::<Wall>()
}
#[query]
fn get_question(question_id: String) -> Post {
let wall = storage::get::<Wall>();
for post in wall {
if post.id == question_id {
return post.clone();
}
}
let void_post = Post {
id: String::new(),
user: String::new(),
eth_address: String::new(),
question: String::new(),
answers: Vec::new(),
};
void_post
}
#[update]
fn write(input: String, name: String, eth_address: String) -> String {
let answers = Vec::new();
let idnew = get_id(&input);
let address_hash = get_id(ð_address);
let post = Post {
id: idnew.clone(),
user: name,
eth_address: address_hash.clone(),
question: input.clone(),
answers: answers,
};
storage::get_mut::<Wall>().push(post);
storage::get_mut::<Addresses>().insert(address_hash, eth_address);
idnew
}
#[update]
fn add_answer(text: String, name: String, eth_address: String, question_id: String) -> () {
let address_hash = get_id(ð_address);
let answer = Answer {
user: name,
eth_address: address_hash.clone(),
text,
};
let wall = storage::get_mut::<Wall>();
for post in wall {
if post.id == question_id {
post.answers.push(answer.clone())
}
}
storage::get_mut::<Addresses>().insert(address_hash, eth_address);
}
//Admin commands
#[update]
fn add_admin(principal: Principal) -> bool {
if !is_caller_admin() {
return false;
}
if is_admin(principal.clone()) {
return false;
}
let admin = storage::get_mut::<Admins>();
admin.push(principal);
true
}
#[query]
fn get_admin_list() -> Option<&'static Vec<Principal>> {
if !is_caller_admin() {
return None;
}
Some(storage::get::<Admins>())
}
#[query]
fn is_caller_admin() -> bool {
is_admin(ic_cdk::caller())
}
fn is_caller_owner(principal: &Principal) -> bool {
match OWNER{
Some(o) => return *principal == OWNER.unwrap(),
None => return false,
}
}
#[query]
fn is_admin(principal: Principal) -> bool {
crate::println!("{:?}", principal.clone());
let admins = storage::get::<Admins>();
crate::println!("{:?}", admins.clone());
admins.contains(&principal) || is_caller_owner(&principal)
}
#[update]
fn delete_all_data() -> bool {
if !is_caller_admin() {
return false;
}
let wall = storage::get_mut::<Wall>();
wall.clear();
true
}
#[update]
fn delete_question(question_id: String) -> bool {
if !is_caller_admin() {
return false;
}
let wall = storage::get_mut::<Wall>();
let idx: usize;
match wall.iter().position(|p| p.id == question_id) {
Some(v) => idx = v,
None => return false,
}
crate::println!("{:?}", idx.clone());
wall.remove(idx);
true
}
#[update]
fn delete_answer(question_id: String, answer_idx: usize) -> bool {
if !is_caller_admin() {
return false;
}
let wall = storage::get_mut::<Wall>();
let idx: usize;
match wall.iter().position(|p| p.id == question_id) {
Some(v) => idx = v,
None => return false,
}
if wall.clone()[idx].answers.len() > answer_idx {
wall[idx].answers.remove(answer_idx);
return true;
}
false
}
#[pre_upgrade]
fn pre_upgrade() {
let wall = storage::get::<Wall>();
let admins = storage::get::<Admins>();
let addresses = storage::get::<Addresses>();
storage::stable_save((wall, admins, addresses)).unwrap();
return;
}
#[post_upgrade]
fn post_upgrade() {
let wall = storage::get_mut::<Wall>();
let admins = storage::get_mut::<Admins>();
let addresses = storage::get_mut::<Addresses>();
let res: Result<(Vec<Post>, Vec<Principal>, BTreeMap<String, String>), String> =
storage::stable_restore();
match res {
Ok((old_posts, old_admins, old_addresses)) => {
for post in old_posts {
wall.push(post);
}
for admin in old_admins {
admins.push(admin);
}
for (k, v) in old_addresses {
addresses.insert(k, v);
}
return;
}
Err(_) => return,
}
}
|
#[allow(clippy::pub_enum_variant_names)]
#[derive(Clone, Copy, EnumIter, Debug, Display, PartialEq)]
pub(in crate) enum DraftVersion {
Draft4,
}
impl Default for DraftVersion {
fn default() -> Self {
Self::Draft4
}
}
|
// fn main() {
// let ten: f64 = 10.0;
// let mut longest = 0;
// let mut longest_i = 0;
// for i in 1..1000 {
// // easy pickings
// // 10's proper divisors except 1
// if i % 2 == 0 || i % 5 == 0 {
// continue;
// }
// // long division
// // once the remainder reaches 1 again, the sequence repeats
// let mut len = 0;
// for j in 1.. {
// let rem = (ten.powi(j) as i128) % i;
// println!("i: {}, j: {}, rem: {}", i, j, rem);
// if rem == 1 {
// len = j;
// break;
// } else if rem == 0 {
// len = 0;
// break;
// } else if ten.powi(j) == std::f64::INFINITY {
// len = j;
// break;
// }
// }
// if len > longest {
// longest = len;
// longest_i = i;
// }
// }
// println!("{}: {}", longest_i, longest);
// }
fn main() {
// better solution may be generating primes
let mut max_len: usize = 0;
let mut max_den: usize = 0;
let mut den: usize = 999;
while max_len < den {
let size = {
let mut num: usize = 1;
let mut a = [0; 1000];
let mut index: usize = 0;
let mut last_index: usize;
loop {
num %= den;
last_index = a[num];
if last_index != 0 {
break index - last_index;
}
a[num] = index;
num *= 10;
index += 1;
}
};
if size > max_len {
max_len = size;
max_den = den
}
den -= 2;
}
println!("{}", max_den);
} |
//! This project is used for creating a digital sawtooth signal.
//!
//! Runs entirely locally without hardware. Rounding might be different than on
//! device. Except for when printing you must be vigilent to not become reliant
//! on any std tools that can't otherwise port over no no_std without alloc.
//!
//! `cargo run --example 2_9`
use itertools::Itertools;
use textplots::{Chart, Plot, Shape};
use typenum::Unsigned;
type N = heapless::consts::U100;
const SAW_AMPLITUDE: f32 = 0.75;
const SAW_PERIOD: usize = 20;
fn main() {
// Collecting to turn the Cycle into a clean iterator for our naive display fn
let sawtooth = (0..SAW_PERIOD)
.map(|n| (2.0 * SAW_AMPLITUDE / (SAW_PERIOD as f32 - 1.0)) * n as f32 - SAW_AMPLITUDE)
.cycle()
.take(N::to_usize())
.collect::<heapless::Vec<f32, N>>();
display::<N, _>("sawtooth signal", sawtooth.iter().cloned());
}
// Points isn't a great representation as you can lose the line in the graph,
// however while Lines occasionally looks good it also can be terrible.
// Continuous requires to be in a fn pointer closure which cant capture any
// external data so not useful without lots of code duplication.
fn display<N, I>(name: &str, input: I)
where
N: Unsigned,
I: Iterator<Item = f32> + core::clone::Clone + std::fmt::Debug,
{
println!("{:?}: {:.4?}", name, input.clone().format(", "));
let display = input
.enumerate()
.map(|(n, y)| (n as f32, y))
.collect::<Vec<(f32, f32)>>();
Chart::new(120, 60, 0.0, N::to_usize() as f32)
.lineplot(Shape::Lines(&display[..]))
.display();
}
|
use std::ops::{Index, IndexMut};
use enum_iterator::IntoEnumIterator;
use matrix::prelude::Conventional;
use matrix::{Element, Position, Size};
use crate::action::ActionError::PieceOnMove;
use crate::action::{Action, ActionError, ActionType};
use crate::coordinate::Coordinate;
use crate::direction::Direction;
#[derive(Clone, Debug)]
pub struct GameBoard {
pub board: Conventional<BoardSpace>,
}
impl GameBoard {
pub fn new<S: Size>(board_size: S, goal_pos: &[usize]) -> Self {
assert!(!goal_pos.is_empty(), "Must have at least 1 goal position");
let rows = board_size.rows() + 2;
let columns = board_size.columns();
assert!(rows >= 1, "Rows must be >= 1");
assert!(columns >= 2, "Columns must be >= 2");
let mut board = Conventional::new((rows, columns));
for index in 0..columns {
if !goal_pos.contains(&index) {
*board.index_mut((0, index)) = BoardSpace::Invalid;
*board.index_mut((rows - 1, index)) = BoardSpace::Invalid;
}
}
Self { board }
}
pub fn is_valid_position(&self, position: impl Position) -> bool {
self.board.columns > position.column()
&& self.board.rows > position.row()
&& self.board.index(position) != &BoardSpace::Invalid
}
fn check_valid_position(&self, position: impl Position) -> GameBoardResult<()> {
if self.is_valid_position(position) {
Ok(())
} else {
Err(GameBoardError::InvalidPosition)
}
}
pub fn pieces_of_size(&self, size: PieceSize) -> Vec<(impl Position, Piece)> {
let mut out = Vec::new();
for (index, space) in self.board.values.iter().enumerate() {
match space {
BoardSpace::Normal(piece) | BoardSpace::Goal { goal_for: _, piece } => {
if let Some(piece) = piece {
if piece.size() == size {
out.push((index_to_position(&self.board, index), *piece));
}
}
}
_ => {}
}
}
out
}
pub fn pieces_of_color(&self, color: Color) -> Vec<(impl Position, Piece)> {
let mut out = Vec::new();
for (index, space) in self.board.values.iter().enumerate() {
match space {
BoardSpace::Normal(piece) | BoardSpace::Goal { goal_for: _, piece } => {
if let Some(piece) = piece {
if piece.color() == color {
out.push((index_to_position(&self.board, index), *piece));
}
}
}
_ => {}
}
}
out
}
pub fn piece(&self, position: impl Position + Copy) -> GameBoardResult<Option<Piece>> {
self.check_valid_position(position)?;
match self.board.index(position) {
BoardSpace::Normal(piece) | BoardSpace::Goal { goal_for: _, piece } => Ok(*piece),
_ => unreachable!("Should have been checked with check_valid_position"),
}
}
pub fn piece_mut(
&mut self,
position: impl Position + Copy,
) -> GameBoardResult<&mut Option<Piece>> {
self.check_valid_position(position)?;
match self.board.index_mut(position) {
BoardSpace::Normal(piece) | BoardSpace::Goal { goal_for: _, piece } => Ok(piece),
_ => unreachable!("Should have been checked with check_valid_position"),
}
}
pub fn apply_action(
&self,
action: &Action,
capture_callback: impl Fn(Coordinate, Piece),
) -> Result<GameBoard, ActionError> {
self.is_valid_action(action)?;
let mut board = self.clone();
let piece_start = board.piece_mut(action.start_pos).unwrap();
let piece = piece_start.unwrap();
*piece_start = None;
match &action.action_type {
ActionType::Move(direction) => {
*board
.piece_mut(direction.offset() + action.start_pos)
.unwrap() = Some(piece);
}
ActionType::Jump(directions) => {
let mut position = action.start_pos;
for direction in directions {
let middle_pos = direction.offset() + position;
let middle_piece = board.piece_mut(middle_pos).unwrap();
if middle_piece.unwrap().color() != piece.color() {
capture_callback(middle_pos, middle_piece.unwrap());
*middle_piece = None;
}
position = direction.offset() * 2 + position;
}
*board.piece_mut(position).unwrap() = Some(piece);
}
}
Ok(board)
}
pub fn is_valid_action(&self, action: &Action) -> Result<(), ActionError> {
let piece = match self.piece(action.start_pos) {
Ok(piece) => piece,
Err(error) => {
return match error {
GameBoardError::InvalidPosition => Err(ActionError::InvalidStartPosition),
};
}
};
if piece.is_none() {
return Err(ActionError::NoPieceAtStart);
}
let piece = piece.unwrap();
match &action.action_type {
ActionType::Move(direction) => self.is_valid_move(action.start_pos, *direction)?,
ActionType::Jump(directions) => {
self.is_valid_jump(piece, action.start_pos, directions)?
}
}
Ok(())
}
pub fn is_valid_move(
&self,
start_pos: Coordinate,
direction: Direction,
) -> Result<(), ActionError> {
let new_pos = direction.offset() + start_pos;
match self.piece(new_pos) {
Ok(piece) => {
if let Some(piece) = piece {
Err(PieceOnMove(piece))
} else {
Ok(())
}
}
Err(error) => match error {
GameBoardError::InvalidPosition => Err(ActionError::MoveOffBoard),
},
}
}
pub fn is_valid_jump(
&self,
piece: Piece,
start_pos: Coordinate,
directions: &[Direction],
) -> Result<(), ActionError> {
if directions.is_empty() {
return Err(ActionError::EmptyJump);
}
if piece.size().is_small() && directions.len() > 1 {
return Err(ActionError::MultipleJumpsForSmall);
}
let mut prev_positions = Vec::with_capacity(directions.len());
prev_positions.push(start_pos);
for direction in directions {
let middle_pos = direction.offset() + *prev_positions.last().unwrap();
let new_pos = direction.offset() + middle_pos;
if let Some(piece) = match self.piece(new_pos) {
Ok(piece) => piece,
Err(error) => {
return match error {
GameBoardError::InvalidPosition => Err(ActionError::JumpOffBoard),
};
}
} {
return Err(ActionError::PieceOnJump(piece));
}
if prev_positions.contains(&new_pos) {
return Err(ActionError::JumpedBackToPrevPosition);
}
prev_positions.push(new_pos);
if self.piece(middle_pos).unwrap().is_none() {
return Err(ActionError::NoPieceJumped);
}
}
Ok(())
}
}
pub fn index_to_position<T: Element>(matrix: &Conventional<T>, index: usize) -> impl Position {
(index % matrix.rows, index / matrix.rows)
}
pub type GameBoardResult<T> = Result<T, GameBoardError>;
#[derive(Copy, Clone, Debug)]
pub enum GameBoardError {
InvalidPosition,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum BoardSpace {
Invalid,
Normal(Option<Piece>),
Goal {
goal_for: Color,
piece: Option<Piece>,
},
}
impl Element for BoardSpace {
fn zero() -> Self {
Self::Normal(None)
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum Piece {
SmallRed,
LargeRed,
SmallBlue,
LargeBlue,
}
impl Piece {
pub fn color(&self) -> Color {
match self {
Piece::SmallRed => Color::Red,
Piece::LargeRed => Color::Red,
Piece::SmallBlue => Color::Blue,
Piece::LargeBlue => Color::Blue,
}
}
pub fn size(&self) -> PieceSize {
match self {
Piece::SmallRed => PieceSize::Small,
Piece::LargeRed => PieceSize::Large,
Piece::SmallBlue => PieceSize::Small,
Piece::LargeBlue => PieceSize::Large,
}
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, IntoEnumIterator)]
pub enum Color {
Red,
Blue,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum PieceSize {
Small,
Large,
}
impl PieceSize {
pub fn is_small(&self) -> bool {
matches!(self, PieceSize::Small)
}
pub fn is_large(&self) -> bool {
matches!(self, PieceSize::Large)
}
}
#[cfg(test)]
mod test {
use std::ops::Index;
use matrix::format::Conventional;
use matrix::matrix;
use crate::game_board::index_to_position;
#[test]
fn index_position_test() {
let matrix = Conventional::from_vec(
(4, 4),
matrix![
1, 2, 3, 4;
5, 6, 7, 8;
9, 10, 11, 12;
13, 14, 15, 16;
],
);
for (index, val) in matrix.values.iter().enumerate() {
assert_eq!(val, matrix.index(index_to_position(&matrix, index)));
}
}
}
|
fn main() {
let input = "1113122113";
println!("Part 1: {}", part1(input));
println!("Part 2: {}", part2(input));
}
fn part1(input: &str) -> usize {
let mut result = input.to_string();
for _ in 0..40 {
result = look_and_say(&result);
}
result.len()
}
fn part2(input: &str) -> usize {
let mut result = input.to_string();
for _ in 0..50 {
result = look_and_say(&result);
}
result.len()
}
fn look_and_say(input: &str) -> String {
let mut chars = input.chars().peekable();
let mut result = String::new();
let mut run = 1;
while let Some(c1) = chars.next() {
match chars.peek() {
Some(&c2) if c1 == c2 => run += 1,
_ => {
result.push_str(&run.to_string());
result.push(c1);
run = 1;
}
}
}
result
}
#[test]
fn test1() {
aoc::test(look_and_say, [
("1", "11"),
("11", "21"),
("21", "1211"),
("1211", "111221"),
("111221", "312211")
])
}
|
use crate::migrations;
use crate::types::{
CellTransaction, IndexerConfig, LiveCell, LockHashCapacity, LockHashCellOutput, LockHashIndex,
LockHashIndexState, TransactionPoint,
};
use ckb_db::{
db::RocksDB, Col, DBIterator, DefaultMigration, Direction, IteratorMode, Migrations,
RocksDBTransaction,
};
use ckb_logger::{debug, error, trace};
use ckb_shared::shared::Shared;
use ckb_store::ChainStore;
use ckb_types::{
core::{self, BlockNumber, Capacity},
packed::{self, Byte32, LiveCellOutput, OutPoint},
prelude::*,
};
use ckb_util::Mutex;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
const COLUMNS: u32 = 4;
/// +---------------------------------+---------------+--------------------------+
/// | Column | Key | Value |
/// +---------------------------------+---------------+--------------------------+
/// | COLUMN_LOCK_HASH_INDEX_STATE | Byte32 | LockHashIndexState |
/// | COLUMN_LOCK_HASH_LIVE_CELL | LockHashIndex | LiveCellOutput |
/// | COLUMN_LOCK_HASH_TRANSACTION | LockHashIndex | Option<TransactionPoint> |
/// | COLUMN_OUT_POINT_LOCK_HASH | OutPoint | LockHashCellOutput |
/// +---------------------------------+---------------+--------------------------+
const COLUMN_LOCK_HASH_INDEX_STATE: Col = "0";
const COLUMN_LOCK_HASH_LIVE_CELL: Col = "1";
const COLUMN_LOCK_HASH_TRANSACTION: Col = "2";
const COLUMN_OUT_POINT_LOCK_HASH: Col = "3";
pub trait IndexerStore: Sync + Send {
fn get_live_cells(
&self,
lock_hash: &Byte32,
skip_num: usize,
take_num: usize,
reverse_order: bool,
) -> Vec<LiveCell>;
fn get_transactions(
&self,
lock_hash: &Byte32,
skip_num: usize,
take_num: usize,
reverse_order: bool,
) -> Vec<CellTransaction>;
fn get_capacity(&self, lock_hash: &Byte32) -> Option<LockHashCapacity>;
fn get_lock_hash_index_states(&self) -> HashMap<Byte32, LockHashIndexState>;
fn insert_lock_hash(
&self,
lock_hash: &Byte32,
index_from: Option<BlockNumber>,
) -> LockHashIndexState;
fn remove_lock_hash(&self, lock_hash: &Byte32);
}
#[derive(Clone)]
pub struct DefaultIndexerStore {
db: Arc<RocksDB>,
shared: Shared,
batch_interval: Duration,
batch_size: usize,
sync_lock: Arc<Mutex<()>>,
}
impl IndexerStore for DefaultIndexerStore {
fn get_live_cells(
&self,
lock_hash: &Byte32,
skip_num: usize,
take_num: usize,
reverse_order: bool,
) -> Vec<LiveCell> {
let mut from_key = lock_hash.as_slice().to_owned();
let iter = if reverse_order {
from_key.extend_from_slice(&BlockNumber::max_value().to_be_bytes());
self.db.iter(
COLUMN_LOCK_HASH_LIVE_CELL,
IteratorMode::From(&from_key, Direction::Reverse),
)
} else {
self.db.iter(
COLUMN_LOCK_HASH_LIVE_CELL,
IteratorMode::From(&from_key, Direction::Forward),
)
};
iter.expect("indexer db iter should be ok")
.skip(skip_num)
.take(take_num)
.take_while(|(key, _)| key.starts_with(lock_hash.as_slice()))
.map(|(key, value)| {
let live_cell_output = LiveCellOutput::from_slice(&value)
.expect("verify LiveCellOutput in storage should be ok");
let lock_hash_index = LockHashIndex::from_packed(
packed::LockHashIndexReader::from_slice(&key).unwrap(),
);
LiveCell {
created_by: lock_hash_index.into(),
cell_output: live_cell_output.cell_output(),
output_data_len: live_cell_output.output_data_len().unpack(),
cellbase: live_cell_output.cellbase().unpack(),
}
})
.collect()
}
fn get_transactions(
&self,
lock_hash: &Byte32,
skip_num: usize,
take_num: usize,
reverse_order: bool,
) -> Vec<CellTransaction> {
let mut from_key = lock_hash.as_slice().to_owned();
let iter = if reverse_order {
from_key.extend_from_slice(&BlockNumber::max_value().to_be_bytes());
self.db.iter(
COLUMN_LOCK_HASH_TRANSACTION,
IteratorMode::From(&from_key, Direction::Reverse),
)
} else {
self.db.iter(
COLUMN_LOCK_HASH_TRANSACTION,
IteratorMode::From(&from_key, Direction::Forward),
)
};
iter.expect("indexer db iter should be ok")
.skip(skip_num)
.take(take_num)
.take_while(|(key, _)| key.starts_with(lock_hash.as_slice()))
.map(|(key, value)| {
let consumed_by = packed::TransactionPointOptReader::from_slice(&value)
.expect("verify TransactionPointOpt in storage should be ok")
.to_opt()
.map(TransactionPoint::from_packed);
let lock_hash_index = LockHashIndex::from_packed(
packed::LockHashIndexReader::from_slice(&key).unwrap(),
);
CellTransaction {
created_by: lock_hash_index.into(),
consumed_by,
}
})
.collect()
}
fn get_lock_hash_index_states(&self) -> HashMap<Byte32, LockHashIndexState> {
self.db
.iter(COLUMN_LOCK_HASH_INDEX_STATE, IteratorMode::Start)
.expect("indexer db iter should be ok")
.map(|(key, value)| {
(
Byte32::from_slice(&key).expect("db safe access"),
LockHashIndexState::from_packed(
packed::LockHashIndexStateReader::from_slice(&value)
.expect("verify LockHashIndexState in storage should be ok"),
),
)
})
.collect()
}
fn get_capacity(&self, lock_hash: &Byte32) -> Option<LockHashCapacity> {
let snapshot = self.db.get_snapshot();
let from_key = lock_hash.as_slice();
let iter = snapshot
.iter(
COLUMN_LOCK_HASH_LIVE_CELL,
IteratorMode::From(from_key, Direction::Forward),
)
.expect("indexer db snapshot iter should be ok");
snapshot
.get_pinned(COLUMN_LOCK_HASH_INDEX_STATE, lock_hash.as_slice())
.expect("indexer db snapshot get should be ok")
.map(|value| {
let index_state = LockHashIndexState::from_packed(
packed::LockHashIndexStateReader::from_slice(&value)
.expect("verify LockHashIndexState in storage should be ok"),
);
let (capacity, cells_count) =
iter.take_while(|(key, _)| key.starts_with(from_key)).fold(
(Capacity::zero(), 0),
|(capacity, cells_count), (_key, value)| {
let cell_output_capacity: Capacity = LiveCellOutput::from_slice(&value)
.expect("verify LiveCellOutput in storage should be ok")
.cell_output()
.capacity()
.unpack();
(
capacity
.safe_add(cell_output_capacity)
.expect("capacity should not overflow"),
cells_count + 1,
)
},
);
LockHashCapacity {
capacity,
cells_count,
block_number: index_state.block_number,
}
})
}
fn insert_lock_hash(
&self,
lock_hash: &Byte32,
index_from: Option<BlockNumber>,
) -> LockHashIndexState {
let index_state = {
let snapshot = self.shared.snapshot();
let tip_number = snapshot.tip_header().number();
let block_number = index_from.unwrap_or_else(|| tip_number).min(tip_number);
LockHashIndexState {
block_number,
block_hash: snapshot.get_block_hash(block_number).expect("block exists"),
}
};
let sync_lock = self.sync_lock.lock();
self.commit_txn(|txn| {
txn.insert_lock_hash_index_state(lock_hash, &index_state);
});
drop(sync_lock);
index_state
}
fn remove_lock_hash(&self, lock_hash: &Byte32) {
let sync_lock = self.sync_lock.lock();
self.commit_txn(|txn| {
let iter = self
.db
.iter(
COLUMN_LOCK_HASH_LIVE_CELL,
IteratorMode::From(lock_hash.as_slice(), Direction::Forward),
)
.expect("indexer db iter should be ok");
iter.take_while(|(key, _)| key.starts_with(lock_hash.as_slice()))
.for_each(|(key, _)| {
let lock_hash_index = LockHashIndex::from_packed(
packed::LockHashIndexReader::from_slice(&key).unwrap(),
);
txn.delete_lock_hash_live_cell(&lock_hash_index);
txn.delete_cell_out_point_lock_hash(&lock_hash_index.out_point);
});
let iter = self
.db
.iter(
COLUMN_LOCK_HASH_TRANSACTION,
IteratorMode::From(lock_hash.as_slice(), Direction::Forward),
)
.expect("indexer db iter should be ok");
iter.take_while(|(key, _)| key.starts_with(lock_hash.as_slice()))
.for_each(|(key, _)| {
let lock_hash_index = LockHashIndex::from_packed(
packed::LockHashIndexReader::from_slice(&key).unwrap(),
);
txn.delete_lock_hash_transaction(&lock_hash_index);
});
txn.delete_lock_hash_index_state(&lock_hash);
});
drop(sync_lock);
}
}
const INIT_DB_VERSION: &str = "20191127135521";
impl DefaultIndexerStore {
pub fn new(config: &IndexerConfig, shared: Shared) -> Self {
let mut migrations = Migrations::default();
migrations.add_migration(Box::new(DefaultMigration::new(INIT_DB_VERSION)));
migrations.add_migration(Box::new(migrations::AddFieldsToLiveCell::new(
shared.clone(),
)));
let db = RocksDB::open(&config.db, COLUMNS, migrations);
DefaultIndexerStore {
db: Arc::new(db),
shared,
batch_interval: Duration::from_millis(config.batch_interval),
batch_size: config.batch_size,
sync_lock: Arc::new(Mutex::new(())),
}
}
pub fn start<S: ToString>(self, thread_name: Option<S>) {
let mut thread_builder = thread::Builder::new();
if let Some(name) = thread_name {
thread_builder = thread_builder.name(name.to_string());
}
thread_builder
.spawn(move || loop {
self.sync_index_states();
thread::sleep(self.batch_interval);
})
.expect("start DefaultIndexerStore failed");
}
// helper function
fn commit_txn<F>(&self, process: F)
where
F: FnOnce(&IndexerStoreTransaction),
{
let db_txn = self.db.transaction();
let mut txn = IndexerStoreTransaction { txn: db_txn };
process(&mut txn);
txn.commit();
}
pub fn sync_index_states(&self) {
let sync_lock = self.sync_lock.lock();
debug!("Start sync index states with chain store");
let mut lock_hash_index_states = self.get_lock_hash_index_states();
if lock_hash_index_states.is_empty() {
return;
}
let snapshot = self.shared.snapshot();
// retains the lock hashes on fork chain and detach blocks
lock_hash_index_states.retain(|_, index_state| {
snapshot.get_block_number(&index_state.block_hash.clone())
!= Some(index_state.block_number)
});
lock_hash_index_states
.iter()
.for_each(|(lock_hash, index_state)| {
let mut index_lock_hashes = HashSet::new();
index_lock_hashes.insert(lock_hash.to_owned());
let mut block = snapshot
.get_block(&index_state.block_hash.clone())
.expect("block exists");
// detach blocks until reach a block on main chain
self.commit_txn(|txn| {
self.detach_block(txn, &index_lock_hashes, &block);
while snapshot.get_block_hash(block.header().number() - 1)
!= Some(block.data().header().raw().parent_hash())
{
block = snapshot
.get_block(&block.data().header().raw().parent_hash())
.expect("block exists");
self.detach_block(txn, &index_lock_hashes, &block);
}
let index_state = LockHashIndexState {
block_number: block.header().number() - 1,
block_hash: block.header().parent_hash(),
};
txn.insert_lock_hash_index_state(lock_hash, &index_state);
});
});
// attach blocks until reach tip or txn limit
let mut lock_hash_index_states = self.get_lock_hash_index_states();
let min_block_number: BlockNumber = lock_hash_index_states
.values()
.min_by_key(|index_state| index_state.block_number)
.expect("none empty index states")
.block_number;
// should index genesis block also
let start_number = if min_block_number == 0 {
0
} else {
min_block_number + 1
};
let tip_number = snapshot.tip_header().number();
self.commit_txn(|txn| {
(start_number..=tip_number)
.take(self.batch_size)
.for_each(|block_number| {
let index_lock_hashes = lock_hash_index_states
.iter()
.filter(|(_, index_state)| index_state.block_number <= block_number)
.map(|(lock_hash, _)| lock_hash)
.cloned()
.collect();
let block = snapshot
.get_block_hash(block_number)
.as_ref()
.and_then(|hash| snapshot.get_block(hash))
.expect("block exists");
self.attach_block(txn, &index_lock_hashes, &block);
let index_state = LockHashIndexState {
block_number,
block_hash: block.hash(),
};
index_lock_hashes.into_iter().for_each(|lock_hash| {
lock_hash_index_states.insert(lock_hash, index_state.clone());
})
});
lock_hash_index_states
.iter()
.for_each(|(lock_hash, index_state)| {
txn.insert_lock_hash_index_state(lock_hash, index_state);
})
});
drop(sync_lock);
debug!("End sync index states with chain store");
}
fn detach_block(
&self,
txn: &IndexerStoreTransaction,
index_lock_hashes: &HashSet<Byte32>,
block: &core::BlockView,
) {
trace!("detach block {}", block.header().hash());
let snapshot = self.shared.snapshot();
let block_number = block.header().number();
block.transactions().iter().rev().for_each(|tx| {
let tx_hash = tx.hash();
tx.outputs()
.into_iter()
.enumerate()
.for_each(|(index, output)| {
let index = index as u32;
let lock_hash = output.calc_lock_hash();
if index_lock_hashes.contains(&lock_hash) {
let lock_hash_index =
LockHashIndex::new(lock_hash, block_number, tx_hash.clone(), index);
txn.delete_lock_hash_live_cell(&lock_hash_index);
txn.delete_lock_hash_transaction(&lock_hash_index);
txn.delete_cell_out_point_lock_hash(&lock_hash_index.out_point);
}
});
if !tx.is_cellbase() {
tx.inputs().into_iter().for_each(|input| {
let out_point = input.previous_output();
if let Some(lock_hash_cell_output) = txn.get_lock_hash_cell_output(&out_point) {
if index_lock_hashes.contains(&lock_hash_cell_output.lock_hash) {
if let Some(cell_output) = lock_hash_cell_output.cell_output {
if let Some((out_point_tx, _)) =
snapshot.get_transaction(&out_point.tx_hash())
{
let lock_hash_index = LockHashIndex::new(
lock_hash_cell_output.lock_hash.clone(),
lock_hash_cell_output.block_number,
out_point.tx_hash(),
out_point.index().unpack(),
);
let live_cell_output = LiveCellOutput::new_builder()
.cell_output(cell_output)
.output_data_len(
(out_point_tx
.outputs_data()
.get(lock_hash_index.out_point.index().unpack())
.expect("verified tx")
.len()
as u64)
.pack(),
)
.cellbase(out_point_tx.is_cellbase().pack())
.build();
txn.generate_live_cell(lock_hash_index, live_cell_output);
}
}
}
}
});
}
})
}
fn attach_block(
&self,
txn: &IndexerStoreTransaction,
index_lock_hashes: &HashSet<Byte32>,
block: &core::BlockView,
) {
trace!("attach block {}", block.hash());
let block_number = block.header().number();
block.transactions().iter().for_each(|tx| {
let tx_hash = tx.hash();
if !tx.is_cellbase() {
tx.inputs()
.into_iter()
.enumerate()
.for_each(|(index, input)| {
let index = index as u32;
let out_point = input.previous_output();
if let Some(lock_hash_cell_output) =
txn.get_lock_hash_cell_output(&out_point)
{
if index_lock_hashes.contains(&lock_hash_cell_output.lock_hash) {
let lock_hash_index = LockHashIndex::new(
lock_hash_cell_output.lock_hash,
lock_hash_cell_output.block_number,
out_point.tx_hash(),
out_point.index().unpack(),
);
let consumed_by = TransactionPoint {
block_number,
tx_hash: tx_hash.clone(),
index,
};
txn.consume_live_cell(lock_hash_index, consumed_by);
}
}
});
}
tx.outputs()
.into_iter()
.enumerate()
.for_each(|(index, output)| {
let lock_hash = output.calc_lock_hash();
if index_lock_hashes.contains(&lock_hash) {
let lock_hash_index = LockHashIndex::new(
lock_hash,
block_number,
tx_hash.clone(),
index as u32,
);
let live_cell_output = LiveCellOutput::new_builder()
.cell_output(output)
.output_data_len(
(tx.outputs_data().get(index).expect("verified tx").len() as u64)
.pack(),
)
.cellbase(tx.is_cellbase().pack())
.build();
txn.generate_live_cell(lock_hash_index, live_cell_output);
}
});
})
}
}
struct IndexerStoreTransaction {
pub txn: RocksDBTransaction,
}
impl IndexerStoreTransaction {
fn generate_live_cell(&self, lock_hash_index: LockHashIndex, live_cell_output: LiveCellOutput) {
self.insert_lock_hash_live_cell(&lock_hash_index, &live_cell_output);
self.insert_lock_hash_transaction(&lock_hash_index, &None);
let lock_hash_cell_output = LockHashCellOutput {
lock_hash: lock_hash_index.lock_hash.clone(),
block_number: lock_hash_index.block_number,
cell_output: Some(live_cell_output.cell_output()),
};
self.insert_cell_out_point_lock_hash(&lock_hash_index.out_point, &lock_hash_cell_output);
}
fn consume_live_cell(&self, lock_hash_index: LockHashIndex, consumed_by: TransactionPoint) {
if let Some(lock_hash_cell_output) = self
.txn
.get(
COLUMN_LOCK_HASH_LIVE_CELL,
lock_hash_index.pack().as_slice(),
)
.expect("indexer db read should be ok")
.map(|value| {
LiveCellOutput::from_slice(&value)
.expect("verify CellOutput in storage should be ok")
})
.map(|live_cell_output: LiveCellOutput| LockHashCellOutput {
lock_hash: lock_hash_index.lock_hash.clone(),
block_number: lock_hash_index.block_number,
cell_output: Some(live_cell_output.cell_output()),
})
{
self.delete_lock_hash_live_cell(&lock_hash_index);
self.insert_lock_hash_transaction(&lock_hash_index, &Some(consumed_by));
self.insert_cell_out_point_lock_hash(
&lock_hash_index.out_point,
&lock_hash_cell_output,
);
}
}
fn insert_lock_hash_index_state(&self, lock_hash: &Byte32, index_state: &LockHashIndexState) {
let value = index_state.pack();
self.txn
.put(
COLUMN_LOCK_HASH_INDEX_STATE,
lock_hash.as_slice(),
value.as_slice(),
)
.expect("txn insert COLUMN_LOCK_HASH_INDEX_STATE failed");
}
fn insert_lock_hash_live_cell(
&self,
lock_hash_index: &LockHashIndex,
live_cell_output: &LiveCellOutput,
) {
self.txn
.put(
COLUMN_LOCK_HASH_LIVE_CELL,
lock_hash_index.pack().as_slice(),
live_cell_output.as_slice(),
)
.expect("txn insert COLUMN_LOCK_HASH_LIVE_CELL failed");
}
fn insert_lock_hash_transaction(
&self,
lock_hash_index: &LockHashIndex,
consumed_by: &Option<TransactionPoint>,
) {
let value = {
packed::TransactionPointOpt::new_builder()
.set(consumed_by.as_ref().map(|i| i.pack()))
.build()
};
self.txn
.put(
COLUMN_LOCK_HASH_TRANSACTION,
lock_hash_index.pack().as_slice(),
value.as_slice(),
)
.expect("txn insert COLUMN_LOCK_HASH_TRANSACTION failed");
}
fn insert_cell_out_point_lock_hash(
&self,
out_point: &OutPoint,
lock_hash_cell_output: &LockHashCellOutput,
) {
self.txn
.put(
COLUMN_OUT_POINT_LOCK_HASH,
out_point.as_slice(),
lock_hash_cell_output.pack().as_slice(),
)
.expect("txn insert COLUMN_OUT_POINT_LOCK_HASH failed");
}
fn delete_lock_hash_index_state(&self, lock_hash: &Byte32) {
self.txn
.delete(COLUMN_LOCK_HASH_INDEX_STATE, lock_hash.as_slice())
.expect("txn delete COLUMN_LOCK_HASH_INDEX_STATE failed");
}
fn delete_lock_hash_live_cell(&self, lock_hash_index: &LockHashIndex) {
self.txn
.delete(
COLUMN_LOCK_HASH_LIVE_CELL,
lock_hash_index.pack().as_slice(),
)
.expect("txn delete COLUMN_LOCK_HASH_LIVE_CELL failed");
}
fn delete_lock_hash_transaction(&self, lock_hash_index: &LockHashIndex) {
self.txn
.delete(
COLUMN_LOCK_HASH_TRANSACTION,
lock_hash_index.pack().as_slice(),
)
.expect("txn delete COLUMN_LOCK_HASH_TRANSACTION failed");
}
fn delete_cell_out_point_lock_hash(&self, out_point: &OutPoint) {
self.txn
.delete(COLUMN_OUT_POINT_LOCK_HASH, out_point.as_slice())
.expect("txn delete COLUMN_OUT_POINT_LOCK_HASH failed");
}
fn get_lock_hash_cell_output(&self, out_point: &OutPoint) -> Option<LockHashCellOutput> {
self.txn
.get(COLUMN_OUT_POINT_LOCK_HASH, out_point.as_slice())
.expect("indexer db read should be ok")
.map(|value| {
LockHashCellOutput::from_packed(
packed::LockHashCellOutputReader::from_slice(&value)
.expect("verify LockHashCellOutput in storage should be ok"),
)
})
}
fn commit(self) {
// only log the error, indexer store commit failure should not causing the thread to panic entirely.
if let Err(err) = self.txn.commit() {
error!("indexer db failed to commit txn, error: {:?}", err)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ckb_chain::{
chain::{ChainController, ChainService},
switch::Switch,
};
use ckb_chain_spec::consensus::Consensus;
use ckb_resource::CODE_HASH_DAO;
use ckb_shared::shared::{Shared, SharedBuilder};
use ckb_types::{
bytes::Bytes,
core::{
capacity_bytes, BlockBuilder, Capacity, HeaderBuilder, ScriptHashType,
TransactionBuilder,
},
packed::{Byte32, CellInput, CellOutputBuilder, OutPoint, ScriptBuilder},
utilities::{difficulty_to_compact, DIFF_TWO},
U256,
};
use std::sync::Arc;
use tempfile;
fn setup(prefix: &str) -> (DefaultIndexerStore, ChainController, Shared) {
let builder = SharedBuilder::default();
let (shared, table) = builder.consensus(Consensus::default()).build().unwrap();
let tmp_dir = tempfile::Builder::new().prefix(prefix).tempdir().unwrap();
let mut config = IndexerConfig::default();
config.db.path = tmp_dir.as_ref().to_path_buf();
let chain_service = ChainService::new(shared.clone(), table);
let chain_controller = chain_service.start::<&str>(None);
(
DefaultIndexerStore::new(&config, shared.clone()),
chain_controller,
shared,
)
}
#[test]
fn lock_hash_index() {
let (store, _, _) = setup("lock_hash_index");
store.insert_lock_hash(&CODE_HASH_DAO.pack(), None);
store.insert_lock_hash(&Byte32::zero(), None);
assert_eq!(2, store.get_lock_hash_index_states().len());
store.remove_lock_hash(&CODE_HASH_DAO.pack());
assert_eq!(1, store.get_lock_hash_index_states().len());
}
#[test]
fn get_live_cells() {
let (store, chain, shared) = setup("get_live_cells");
let script1 = ScriptBuilder::default()
.code_hash(CODE_HASH_DAO.pack())
.hash_type(ScriptHashType::Data.into())
.build();
let script2 = ScriptBuilder::default()
.code_hash(CODE_HASH_DAO.pack())
.hash_type(ScriptHashType::Data.into())
.args(Bytes::from(b"script2".to_vec()).pack())
.build();
store.insert_lock_hash(&script1.calc_script_hash(), None);
store.insert_lock_hash(&script2.calc_script_hash(), None);
let tx11 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(1000).pack())
.lock(script1.clone())
.build(),
)
.output_data(Default::default())
.build();
let tx12 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(2000).pack())
.lock(script2.clone())
.build(),
)
.output_data(Default::default())
.build();
let block1 = BlockBuilder::default()
.transaction(tx11.clone())
.transaction(tx12.clone())
.header(
HeaderBuilder::default()
.compact_target(DIFF_TWO.pack())
.number(1.pack())
.parent_hash(shared.genesis_hash())
.build(),
)
.build();
let tx21_output_data = Bytes::from(vec![1, 2, 3]);
let tx21 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(3000).pack())
.lock(script1.clone())
.build(),
)
.output_data(tx21_output_data.pack())
.build();
let tx22 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(4000).pack())
.lock(script2.clone())
.build(),
)
.output_data(Default::default())
.build();
let block2 = BlockBuilder::default()
.transaction(tx21)
.transaction(tx22)
.header(
HeaderBuilder::default()
.compact_target(difficulty_to_compact(U256::from(4u64)).pack())
.number(2.pack())
.parent_hash(block1.header().hash())
.build(),
)
.build();
let tx31 = TransactionBuilder::default()
.input(CellInput::new(OutPoint::new(tx11.hash(), 0), 0))
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(5000).pack())
.lock(script1.clone())
.build(),
)
.output_data(Default::default())
.build();
let tx32 = TransactionBuilder::default()
.input(CellInput::new(OutPoint::new(tx12.hash(), 0), 0))
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(6000).pack())
.lock(script2.clone())
.build(),
)
.output_data(Default::default())
.build();
let block2_fork = BlockBuilder::default()
.transaction(tx31)
.transaction(tx32)
.header(
HeaderBuilder::default()
.compact_target(difficulty_to_compact(U256::from(20u64)).pack())
.number(2.pack())
.parent_hash(block1.header().hash())
.build(),
)
.build();
chain
.internal_process_block(Arc::new(block1), Switch::DISABLE_ALL)
.unwrap();
chain
.internal_process_block(Arc::new(block2), Switch::DISABLE_ALL)
.unwrap();
store.sync_index_states();
let cells = store.get_live_cells(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(2, cells.len());
assert_eq!(
capacity_bytes!(1000),
cells[0].cell_output.capacity().unpack()
);
assert_eq!(
capacity_bytes!(3000),
cells[1].cell_output.capacity().unpack()
);
assert_eq!(tx21_output_data.len() as u64, cells[1].output_data_len);
assert_eq!(false, cells[1].cellbase,);
// test reverse order
let cells = store.get_live_cells(&script1.calc_script_hash(), 0, 100, true);
assert_eq!(2, cells.len());
assert_eq!(
capacity_bytes!(3000),
cells[0].cell_output.capacity().unpack()
);
assert_eq!(
capacity_bytes!(1000),
cells[1].cell_output.capacity().unpack()
);
// test get_capacity
let lock_hash_capacity = store.get_capacity(&script1.calc_script_hash()).unwrap();
assert_eq!(capacity_bytes!(4000), lock_hash_capacity.capacity);
assert_eq!(2, lock_hash_capacity.cells_count);
assert_eq!(2, lock_hash_capacity.block_number);
let cells = store.get_live_cells(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(2, cells.len());
assert_eq!(
capacity_bytes!(2000),
cells[0].cell_output.capacity().unpack()
);
assert_eq!(
capacity_bytes!(4000),
cells[1].cell_output.capacity().unpack()
);
chain
.internal_process_block(Arc::new(block2_fork), Switch::DISABLE_ALL)
.unwrap();
store.sync_index_states();
let cells = store.get_live_cells(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(1, cells.len());
assert_eq!(
capacity_bytes!(5000),
cells[0].cell_output.capacity().unpack()
);
let cells = store.get_live_cells(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(1, cells.len());
assert_eq!(
capacity_bytes!(6000),
cells[0].cell_output.capacity().unpack()
);
// remove script1's lock hash should remove its indexed data also
store.remove_lock_hash(&script1.calc_script_hash());
let cells = store.get_live_cells(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(0, cells.len());
let cells = store.get_live_cells(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(1, cells.len());
assert!(store.get_capacity(&script1.calc_script_hash()).is_none());
}
#[test]
fn get_transactions() {
let (store, chain, shared) = setup("get_transactions");
let script1 = ScriptBuilder::default()
.code_hash(CODE_HASH_DAO.pack())
.hash_type(ScriptHashType::Data.into())
.build();
let script2 = ScriptBuilder::default()
.code_hash(CODE_HASH_DAO.pack())
.hash_type(ScriptHashType::Data.into())
.args(Bytes::from(b"script2".to_vec()).pack())
.build();
store.insert_lock_hash(&script1.calc_script_hash(), None);
store.insert_lock_hash(&script2.calc_script_hash(), None);
let tx11 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(1000).pack())
.lock(script1.clone())
.build(),
)
.output_data(Default::default())
.build();
let tx12 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(2000).pack())
.lock(script2.clone())
.build(),
)
.output_data(Default::default())
.build();
let block1 = BlockBuilder::default()
.transaction(tx11.clone())
.transaction(tx12.clone())
.header(
HeaderBuilder::default()
.compact_target(DIFF_TWO.pack())
.number(1.pack())
.parent_hash(shared.genesis_hash())
.build(),
)
.build();
let tx21 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(3000).pack())
.lock(script1.clone())
.build(),
)
.output_data(Default::default())
.build();
let tx22 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(4000).pack())
.lock(script2.clone())
.build(),
)
.output_data(Default::default())
.build();
let block2 = BlockBuilder::default()
.transaction(tx21.clone())
.transaction(tx22.clone())
.header(
HeaderBuilder::default()
.compact_target(difficulty_to_compact(U256::from(4u64)).pack())
.number(2.pack())
.parent_hash(block1.header().hash())
.build(),
)
.build();
let tx31 = TransactionBuilder::default()
.input(CellInput::new(OutPoint::new(tx11.hash(), 0), 0))
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(5000).pack())
.lock(script1.clone())
.build(),
)
.output_data(Default::default())
.build();
let tx32 = TransactionBuilder::default()
.input(CellInput::new(OutPoint::new(tx12.hash(), 0), 0))
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(6000).pack())
.lock(script2.clone())
.build(),
)
.output_data(Default::default())
.build();
let block2_fork = BlockBuilder::default()
.transaction(tx31.clone())
.transaction(tx32.clone())
.header(
HeaderBuilder::default()
.compact_target(difficulty_to_compact(U256::from(20u64)).pack())
.number(2.pack())
.parent_hash(block1.header().hash())
.build(),
)
.build();
chain
.internal_process_block(Arc::new(block1), Switch::DISABLE_ALL)
.unwrap();
chain
.internal_process_block(Arc::new(block2), Switch::DISABLE_ALL)
.unwrap();
store.sync_index_states();
let transactions = store.get_transactions(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(2, transactions.len());
assert_eq!(tx11.hash(), transactions[0].created_by.tx_hash);
assert_eq!(tx21.hash(), transactions[1].created_by.tx_hash);
// test reverse order
let transactions = store.get_transactions(&script1.calc_script_hash(), 0, 100, true);
assert_eq!(2, transactions.len());
assert_eq!(tx21.hash(), transactions[0].created_by.tx_hash);
assert_eq!(tx11.hash(), transactions[1].created_by.tx_hash);
let transactions = store.get_transactions(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(2, transactions.len());
assert_eq!(tx12.hash(), transactions[0].created_by.tx_hash);
assert_eq!(tx22.hash(), transactions[1].created_by.tx_hash);
chain
.internal_process_block(Arc::new(block2_fork), Switch::DISABLE_ALL)
.unwrap();
store.sync_index_states();
let transactions = store.get_transactions(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(2, transactions.len());
assert_eq!(tx11.hash(), transactions[0].created_by.tx_hash);
assert_eq!(
Some(tx31.hash()),
transactions[0]
.consumed_by
.as_ref()
.map(|transaction_point| transaction_point.tx_hash.clone())
);
assert_eq!(tx31.hash(), transactions[1].created_by.tx_hash);
let transactions = store.get_transactions(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(2, transactions.len());
assert_eq!(tx12.hash(), transactions[0].created_by.tx_hash);
assert_eq!(tx32.hash(), transactions[1].created_by.tx_hash);
// remove script1's lock hash should remove its indexed data also
store.remove_lock_hash(&script1.calc_script_hash());
let transactions = store.get_transactions(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(0, transactions.len());
let transactions = store.get_transactions(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(2, transactions.len());
}
#[test]
fn sync_index_states() {
let (store, chain, shared) = setup("sync_index_states");
let script1 = ScriptBuilder::default()
.code_hash(CODE_HASH_DAO.pack())
.hash_type(ScriptHashType::Data.into())
.build();
let script2 = ScriptBuilder::default()
.code_hash(CODE_HASH_DAO.pack())
.hash_type(ScriptHashType::Data.into())
.args(Bytes::from(b"script2".to_vec()).pack())
.build();
store.insert_lock_hash(&script1.calc_script_hash(), None);
store.insert_lock_hash(&script2.calc_script_hash(), None);
let tx11 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(1000).pack())
.lock(script1.clone())
.build(),
)
.output_data(Default::default())
.build();
let tx12_output_data = Bytes::from(vec![1, 2, 3]);
let tx12 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(2000).pack())
.lock(script2.clone())
.build(),
)
.output_data(tx12_output_data.pack())
.build();
let block1 = BlockBuilder::default()
.transaction(tx11.clone())
.transaction(tx12.clone())
.header(
HeaderBuilder::default()
.compact_target(DIFF_TWO.pack())
.number(1.pack())
.parent_hash(shared.genesis_hash())
.build(),
)
.build();
let tx21 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(3000).pack())
.lock(script1.clone())
.build(),
)
.output_data(Default::default())
.build();
let tx22 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(4000).pack())
.lock(script2.clone())
.build(),
)
.output_data(Default::default())
.build();
let block2 = BlockBuilder::default()
.transaction(tx21.clone())
.transaction(tx22.clone())
.header(
HeaderBuilder::default()
.compact_target(difficulty_to_compact(U256::from(4u64)).pack())
.number(2.pack())
.parent_hash(block1.header().hash())
.build(),
)
.build();
let tx31 = TransactionBuilder::default()
.input(CellInput::new(OutPoint::new(tx11.hash(), 0), 0))
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(5000).pack())
.lock(script1.clone())
.build(),
)
.output_data(Default::default())
.build();
let tx32_output_data = Bytes::from(vec![1, 2, 3, 4]);
let tx32 = TransactionBuilder::default()
.input(CellInput::new(OutPoint::new(tx12.hash(), 0), 0))
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(6000).pack())
.lock(script2.clone())
.build(),
)
.output_data(tx32_output_data.pack())
.build();
let block2_fork = BlockBuilder::default()
.header(
HeaderBuilder::default()
.compact_target(difficulty_to_compact(U256::from(20u64)).pack())
.number(2.pack())
.parent_hash(block1.header().hash())
.build(),
)
.build();
let block3 = BlockBuilder::default()
.transaction(tx31.clone())
.transaction(tx32.clone())
.header(
HeaderBuilder::default()
.compact_target(difficulty_to_compact(U256::from(22u64)).pack())
.number(3.pack())
.parent_hash(block2_fork.header().hash())
.build(),
)
.build();
chain
.internal_process_block(Arc::new(block1), Switch::DISABLE_ALL)
.unwrap();
chain
.internal_process_block(Arc::new(block2), Switch::DISABLE_ALL)
.unwrap();
store.sync_index_states();
let transactions = store.get_transactions(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(2, transactions.len());
assert_eq!(tx11.hash(), transactions[0].created_by.tx_hash);
assert_eq!(tx21.hash(), transactions[1].created_by.tx_hash);
let transactions = store.get_transactions(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(2, transactions.len());
assert_eq!(tx12.hash(), transactions[0].created_by.tx_hash);
assert_eq!(tx22.hash(), transactions[1].created_by.tx_hash);
chain
.internal_process_block(Arc::new(block2_fork), Switch::DISABLE_ALL)
.unwrap();
store.sync_index_states();
let cells = store.get_live_cells(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(1, cells.len());
assert_eq!(tx12_output_data.len() as u64, cells[0].output_data_len);
let transactions = store.get_transactions(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(1, transactions.len());
assert_eq!(tx12.hash(), transactions[0].created_by.tx_hash);
chain
.internal_process_block(Arc::new(block3), Switch::DISABLE_ALL)
.unwrap();
store.sync_index_states();
let cells = store.get_live_cells(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(1, cells.len());
assert_eq!(tx32_output_data.len() as u64, cells[0].output_data_len);
let transactions = store.get_transactions(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(2, transactions.len());
assert_eq!(tx11.hash(), transactions[0].created_by.tx_hash);
assert_eq!(
Some(tx31.hash()),
transactions[0]
.consumed_by
.as_ref()
.map(|transaction_point| transaction_point.tx_hash.clone())
);
assert_eq!(tx31.hash(), transactions[1].created_by.tx_hash);
let transactions = store.get_transactions(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(2, transactions.len());
assert_eq!(tx12.hash(), transactions[0].created_by.tx_hash);
assert_eq!(tx32.hash(), transactions[1].created_by.tx_hash);
}
#[test]
fn consume_txs_in_same_block() {
let (store, chain, shared) = setup("consume_txs_in_same_block");
let script1 = ScriptBuilder::default()
.code_hash(CODE_HASH_DAO.pack())
.hash_type(ScriptHashType::Data.into())
.build();
let script2 = ScriptBuilder::default()
.code_hash(CODE_HASH_DAO.pack())
.hash_type(ScriptHashType::Data.into())
.args(Bytes::from(b"script2".to_vec()).pack())
.build();
store.insert_lock_hash(&script1.calc_script_hash(), None);
store.insert_lock_hash(&script2.calc_script_hash(), None);
let cells = store.get_live_cells(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(0, cells.len());
let tx11 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(1000).pack())
.lock(script1.clone())
.build(),
)
.output_data(Default::default())
.build();
let tx12 = TransactionBuilder::default()
.input(CellInput::new(OutPoint::new(tx11.hash(), 0), 0))
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(900).pack())
.lock(script1.clone())
.build(),
)
.output_data(Default::default())
.build();
let tx13_output_data = Bytes::from(vec![1, 2, 3]);
let tx13 = TransactionBuilder::default()
.input(CellInput::new(OutPoint::new(tx12.hash(), 0), 0))
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(800).pack())
.lock(script2.clone())
.build(),
)
.output_data(tx13_output_data.pack())
.build();
let block1 = BlockBuilder::default()
.transaction(tx11)
.transaction(tx12)
.transaction(tx13)
.header(
HeaderBuilder::default()
.compact_target(DIFF_TWO.pack())
.number(1.pack())
.parent_hash(shared.genesis_hash())
.build(),
)
.build();
let block1_fork = BlockBuilder::default()
.header(
HeaderBuilder::default()
.compact_target(difficulty_to_compact(U256::from(20u64)).pack())
.number(1.pack())
.parent_hash(shared.genesis_hash())
.build(),
)
.build();
chain
.internal_process_block(Arc::new(block1), Switch::DISABLE_ALL)
.unwrap();
store.sync_index_states();
let cells = store.get_live_cells(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(0, cells.len());
let cell_transactions = store.get_transactions(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(2, cell_transactions.len());
let cells = store.get_live_cells(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(1, cells.len());
assert_eq!(tx13_output_data.len() as u64, cells[0].output_data_len);
assert_eq!(false, cells[0].cellbase,);
chain
.internal_process_block(Arc::new(block1_fork), Switch::DISABLE_ALL)
.unwrap();
store.sync_index_states();
let cells = store.get_live_cells(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(0, cells.len());
let cell_transactions = store.get_transactions(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(0, cell_transactions.len());
let cells = store.get_live_cells(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(0, cells.len());
}
#[test]
fn detach_blocks() {
let (store, chain, shared) = setup("detach_blocks");
let script1 = ScriptBuilder::default()
.code_hash(CODE_HASH_DAO.pack())
.hash_type(ScriptHashType::Data.into())
.build();
let script2 = ScriptBuilder::default()
.code_hash(CODE_HASH_DAO.pack())
.hash_type(ScriptHashType::Data.into())
.args(Bytes::from(b"script2".to_vec()).pack())
.build();
store.insert_lock_hash(&script1.calc_script_hash(), None);
store.insert_lock_hash(&script2.calc_script_hash(), None);
let cells = store.get_live_cells(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(0, cells.len());
let tx11 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(1000).pack())
.lock(script1.clone())
.build(),
)
.output_data(Default::default())
.build();
let tx12 = TransactionBuilder::default()
.input(CellInput::new(OutPoint::new(tx11.hash(), 0), 0))
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(900).pack())
.lock(script1.clone())
.build(),
)
.output_data(Default::default())
.build();
let tx21_output_data = Bytes::from(vec![1, 2, 3]);
let tx21 = TransactionBuilder::default()
.input(CellInput::new(OutPoint::new(tx12.hash(), 0), 0))
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(800).pack())
.lock(script2.clone())
.build(),
)
.output_data(tx21_output_data.pack())
.build();
let block1 = BlockBuilder::default()
.transaction(tx11)
.transaction(tx12)
.header(
HeaderBuilder::default()
.compact_target(DIFF_TWO.pack())
.number(1.pack())
.parent_hash(shared.genesis_hash())
.build(),
)
.build();
let block2 = BlockBuilder::default()
.transaction(tx21)
.header(
HeaderBuilder::default()
.compact_target(difficulty_to_compact(U256::from(4u64)).pack())
.number(2.pack())
.parent_hash(block1.hash())
.build(),
)
.build();
let tx31 = TransactionBuilder::default()
.output(
CellOutputBuilder::default()
.capacity(capacity_bytes!(1100).pack())
.lock(script2.clone())
.build(),
)
.output_data(Default::default())
.build();
let block1_fork = BlockBuilder::default()
.transaction(tx31)
.header(
HeaderBuilder::default()
.compact_target(difficulty_to_compact(U256::from(20u64)).pack())
.number(1.pack())
.parent_hash(shared.genesis_hash())
.build(),
)
.build();
chain
.internal_process_block(Arc::new(block1), Switch::DISABLE_ALL)
.unwrap();
chain
.internal_process_block(Arc::new(block2), Switch::DISABLE_ALL)
.unwrap();
store.sync_index_states();
let cells = store.get_live_cells(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(0, cells.len());
let cell_transactions = store.get_transactions(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(2, cell_transactions.len());
let cells = store.get_live_cells(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(1, cells.len());
assert_eq!(
capacity_bytes!(800),
cells[0].cell_output.capacity().unpack()
);
assert_eq!(tx21_output_data.len() as u64, cells[0].output_data_len);
assert_eq! {
false,
cells[0].cellbase
};
chain
.internal_process_block(Arc::new(block1_fork), Switch::DISABLE_ALL)
.unwrap();
store.sync_index_states();
let cells = store.get_live_cells(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(0, cells.len());
let cell_transactions = store.get_transactions(&script1.calc_script_hash(), 0, 100, false);
assert_eq!(0, cell_transactions.len());
let cells = store.get_live_cells(&script2.calc_script_hash(), 0, 100, false);
assert_eq!(1, cells.len());
assert_eq!(
capacity_bytes!(1100),
cells[0].cell_output.capacity().unpack()
);
assert_eq!(0, cells[0].output_data_len);
}
}
|
use std::io::Cursor;
use std::io::prelude::*;
use byteorder::{LittleEndian, ReadBytesExt};
use std::fs::File;
use std::io::BufReader;
use std::io;
use std::convert;
#[derive(Debug)]
pub enum Error {
Err(String),
IOError(io::Error),
}
impl convert::From<io::Error> for Error {
fn from(e: io::Error) -> Error {
Error::IOError(e)
}
}
pub fn read_string(buf: &mut Cursor<Vec<u8>>, len: usize) -> Result<String, Error> {
let mut ret = String::new();
try!(buf.take(len as u64).read_to_string(&mut ret));
Result::Ok(ret)
}
pub fn read_stringz(buf: &mut Cursor<Vec<u8>>) -> Result<String, Error> {
let mut ret = String::new();
let mut buf_ret = Vec::new();
buf.read_until(0, &mut buf_ret);
try!(Cursor::new(buf_ret.clone())
.take(buf_ret.len() as u64)
.read_to_string(&mut ret));
Result::Ok(ret)
}
pub fn read_u8(buf: &mut Cursor<Vec<u8>>) -> Result<u8, Error> {
Result::Ok(try!(buf.read_u8()))
}
pub fn read_u32(buf: &mut Cursor<Vec<u8>>) -> Result<u32, Error> {
Result::Ok(try!(buf.read_u32::<LittleEndian>()))
}
pub fn skip_bytes(buf: &mut Cursor<Vec<u8>>, len: usize) {
let position = buf.position();
buf.set_position(position + 4);
}
#[derive(Clone)]
pub struct SongPattern {}
impl SongPattern {
pub fn new(buf: &mut Cursor<Vec<u8>>) -> SongPattern {
SongPattern {}
}
}
#[derive(Clone)]
pub struct SongSequenceRow {
pub pattern: Vec<u8>,
}
impl SongSequenceRow {
pub fn new() -> SongSequenceRow {
SongSequenceRow { pattern: Vec::new() }
}
}
#[derive(Clone)]
pub struct SongSequence {
pub rows: Vec<SongSequenceRow>,
}
impl SongSequence {
pub fn new(buf: &mut Cursor<Vec<u8>>) -> SongSequence {
let count = read_u8(buf).unwrap();
println!("INFO SEQ {:?}", count);
let mut rows = Vec::new();
for i in 0..count {
rows.push(SongSequenceRow::new());
}
for track in 0..4 {
for i in 0..count {
let track_value = read_u8(buf).unwrap();
rows[i as usize].pattern.push(track_value);
}
}
SongSequence { rows: rows.clone() }
}
}
#[derive(Clone)]
pub struct SongSection {
pub name: String,
pub size: u32,
pub version: u8,
pub section_name: String,
pub num_pattern_rows: u8,
pub num_sequence_rows: u8,
pub sequence: SongSequence,
pub patterns: Vec<SongPattern>,
}
impl SongSection {
pub fn new(buf: &mut Cursor<Vec<u8>>) -> SongSection {
let name = read_string(buf, 4);
let section_size = read_u32(buf);
println!("SIZE = {:?}", section_size);
let version = read_u8(buf);
println!("VERSION = {:?}", version);
let section_name = read_stringz(buf);
println!("SECTION NAME = {:?}", section_name);
let num_pattern_rows = read_u8(buf);
let num_sequence_rows = read_u8(buf);
println!("NUM {:?} {:?}", num_pattern_rows, num_sequence_rows);
println!("RE {:?}", read_string(buf, 4));
println!("SIZE {:?}", read_u32(buf));
let sequence = SongSequence::new(buf);
println!("RE {:?}", read_string(buf, 4));
println!("SIZE {:?}", read_u32(buf));
let mut patterns = Vec::new();
let count_pattern = read_u8(buf).unwrap();
println!("COUNT {:?}", count_pattern);
for _ in 0..count_pattern {
patterns.push(SongPattern::new(buf));
}
SongSection {
name: name.unwrap().clone(),
size: section_size.unwrap(),
version: version.unwrap(),
section_name: section_name.unwrap().clone(),
num_pattern_rows: num_pattern_rows.unwrap(),
num_sequence_rows: num_sequence_rows.unwrap(),
sequence: sequence,
patterns: patterns.clone(),
}
}
}
#[allow(dead_code)]
pub struct Song {
pub sections: Vec<SongSection>,
pub parsing: bool,
}
#[allow(dead_code)]
impl Song {
pub fn new(buf: &mut io::BufRead) -> Song {
let mut parsing = false;
let mut sections = Vec::new();
let mut buffer = Vec::new();
buf.read_to_end(&mut buffer).unwrap();
let mut cur_buf = Cursor::new(buffer);
sections.push(SongSection::new(&mut cur_buf));
parsing = true;
Song {
sections: sections.clone(),
parsing: parsing,
}
}
pub fn new_from_file(filename: String) -> Song {
let f = File::open(filename.clone()).unwrap();
let mut buf_reader = BufReader::new(f);
Song::new(&mut buf_reader)
}
pub fn valid(&mut self) -> bool {
self.parsing
}
}
#[cfg(test)]
mod tests {
use super::Song;
#[test]
fn parse_song_file() {
let mut s = Song::new_from_file("examples/assets/dub.song".to_string());
assert_eq!(s.sections.len(), 1);
assert!(s.valid());
}
}
|
use yew::prelude::*;
use yew_router::prelude::*;
use crate::app::Route;
#[derive(Debug, Properties, PartialEq)]
pub struct Props {
pub children: Children,
}
#[function_component(Container)]
pub fn container(props: &Props) -> Html {
// 用于跳转到不同的路由
let navigator = use_navigator().unwrap();
let set_title = Callback::from(move |content: String| {
// 设置网页标题
web_sys::window()
.unwrap()
.document()
.unwrap()
.set_title(&format!("{content} - Blog"));
});
let jump = move |route: Route| Callback::from(move |_| navigator.push(&route));
html! {
<>
<nav>
<a onclick={jump(Route::Home)} class="brand">
<span> { "Blog" }</span>
</a>
</nav>
<ContextProvider<Callback<String>> context={set_title}>
{ for props.children.iter() }
</ContextProvider<Callback<String>>>
</>
}
}
|
use crate::actions::Action;
use crate::error::Result;
use crate::shared::installer::InstallerRegistry;
use crate::shared::{FileSystemResource, PackageLog, PackageRepository};
// ------------------------------------------------------------------------------------------------
// Public Types
// ------------------------------------------------------------------------------------------------
///
/// This action displays the current path configuration for the installer registry and package
/// repository.
///
#[derive(Debug)]
pub struct ShowPathsAction {}
// ------------------------------------------------------------------------------------------------
// Implementations
// ------------------------------------------------------------------------------------------------
impl Action for ShowPathsAction {
fn run(&self) -> Result<()> {
let repository_location = PackageRepository::default_path();
println!("Package Repository path:\n\t{:?}", &repository_location);
let metadata = std::fs::symlink_metadata(&repository_location)?;
let file_type = metadata.file_type();
if file_type.is_symlink() {
let local_location = std::fs::read_link(repository_location)?;
println!("Package Repository symlinked to:\n\t{:?}", &local_location);
}
println!(
"Package Repository config file path:\n\t{:?}",
&PackageRepository::default_config_path()
);
println!(
"Package Repository local file path:\n\t{:?}",
&PackageRepository::default_local_path()
);
println!(
"Installer Registry path:\n\t{:?}",
InstallerRegistry::default_path()
);
println!(
"Package Installer log file path:\n\t{:?}",
PackageLog::default_path()
);
Ok(())
}
}
impl ShowPathsAction {
pub fn new_action() -> Result<Box<dyn Action>> {
Ok(Box::from(ShowPathsAction {}))
}
}
|
use super::expression::Expression;
use super::variable::LocalVariable;
use crate::ast_transform::Transformer;
use crate::scm::Scm;
use crate::source::SourceLocation;
use crate::syntax::Reify;
use crate::utils::Named;
#[derive(Debug, Copy, Clone)]
pub enum LetContKind {
IndefiniteContinuation,
ExitProcedure,
}
#[derive(Debug, Clone)]
pub struct LetContinuation {
pub kind: LetContKind,
pub variable: LocalVariable,
pub body: Box<Expression>,
pub span: SourceLocation,
}
impl_sourced!(LetContinuation);
impl LetContinuation {
pub fn new_cc(
variable: LocalVariable,
body: impl Into<Box<Expression>>,
span: SourceLocation,
) -> Self {
Self::new(LetContKind::IndefiniteContinuation, variable, body, span)
}
pub fn new_ep(
variable: LocalVariable,
body: impl Into<Box<Expression>>,
span: SourceLocation,
) -> Self {
Self::new(LetContKind::ExitProcedure, variable, body, span)
}
pub fn new(
kind: LetContKind,
variable: LocalVariable,
body: impl Into<Box<Expression>>,
span: SourceLocation,
) -> Self {
LetContinuation {
kind,
variable,
body: body.into(),
span,
}
}
pub fn default_transform(mut self, visitor: &mut impl Transformer) -> Self {
*self.body = self.body.transform(visitor);
self
}
}
impl Reify for LetContinuation {
fn reify(&self) -> Scm {
let name = Scm::symbol(match self.kind {
LetContKind::ExitProcedure => "let/ep",
LetContKind::IndefiniteContinuation => "let/cc",
});
Scm::list(vec![
name,
Scm::Symbol(self.variable.name()),
self.body.reify(),
])
}
}
|
#[macro_export]
macro_rules! bench_func {
($b: ident, op => $func: ident, ty => $t: ty) => {{
const LEN: usize = 1 << 13;
let elems = <$t as mathbench::RandomVec>::random_vec(0, LEN);
let mut i = 0;
$b.iter(|| {
i = (i + 1) & (LEN - 1);
unsafe { $func(elems.get_unchecked(i)) }
})
}};
($b: ident, op => $func: ident, ty1 => $ty1:ty, ty2 => $ty2:ty) => {{
const LEN: usize = 1 << 7;
let elems1 = <$ty1 as mathbench::RandomVec>::random_vec(0, LEN);
let elems2 = <$ty2 as mathbench::RandomVec>::random_vec(1, LEN);
let mut i = 0;
for lhs in elems1.iter() {
$b.iter(|| {
i = (i + 1) & (LEN - 1);
unsafe { $func(lhs, elems2.get_unchecked(i)) }
})
}
}};
}
#[macro_export]
macro_rules! bench_unop {
($b: ident, op => $unop: ident, ty => $t:ty) => {{
const LEN: usize = 1 << 13;
let elems = <$t as mathbench::RandomVec>::random_vec(0, LEN);
let mut i = 0;
$b.iter(|| {
i = (i + 1) & (LEN - 1);
unsafe { elems.get_unchecked(i).$unop() }
})
}};
}
#[macro_export]
macro_rules! by_value {
($e:expr) => {
*$e
};
}
#[macro_export]
macro_rules! by_ref {
($e:expr) => {
$e
};
}
#[macro_export]
macro_rules! bench_binop {
($b: ident, op => $binop: ident, ty1 => $ty1:ty, ty2 => $ty2:ty, param => $param:tt) => {{
const LEN: usize = 1 << 7;
let elems1 = <$ty1 as mathbench::RandomVec>::random_vec(0, LEN);
let elems2 = <$ty2 as mathbench::RandomVec>::random_vec(1, LEN);
let mut i = 0;
for lhs in elems1.iter() {
$b.iter(|| {
i = (i + 1) & (LEN - 1);
unsafe { lhs.$binop($param!(elems2.get_unchecked(i))) }
})
}
}};
($b: ident, op => $binop: ident, ty1 => $ty1:ty, ty2 => $ty2:ty) => {{
bench_binop!($b, op => $binop, ty1 => $ty1, ty2 => $ty2, param => by_value)
}};
($b: ident, op => $binop: ident, ty => $ty:ty, param => $param:tt) => {{
bench_binop!($b, op => $binop, ty1 => $ty, ty2 => $ty, param => $param)
}};
($b: ident, op => $binop: ident, ty => $ty:ty) => {{
bench_binop!($b, op => $binop, ty1 => $ty, ty2 => $ty)
}};
}
|
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult};
use crate::error::ContractError;
use crate::msg::{ConfigResponse, InstantiateMsg, QueryMsg};
use crate::state::{Config, read_config, store_config};
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
deps: DepsMut,
_env: Env,
info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
store_config(
deps.storage,
&Config {
owner: deps.api.addr_canonicalize(info.sender.as_str())?,
currency: deps.api.addr_canonicalize(&msg.currency)?,
count: msg.count
},
)?;
Ok(Response::default())
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg {
QueryMsg::GetConfig {} => to_binary(&query_config(deps)?),
}
}
fn query_config(deps: Deps) -> StdResult<ConfigResponse> {
let config = read_config(deps.storage)?;
Ok(ConfigResponse {
currency: deps.api.addr_humanize(&config.currency)?.to_string(),
count: config.count
})
}
#[cfg(test)]
mod tests {
use super::*;
use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info};
use cosmwasm_std::{coins, from_binary};
#[test]
fn proper_initialization() {
let mut deps = mock_dependencies(&[]);
let msg = InstantiateMsg {
currency: "uusd".to_string(),
count: 10
};
let info = mock_info("creator", &coins(1000, "earth"));
// we can just call .unwrap() to assert this was a success
let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
assert_eq!(0, res.messages.len());
// it worked, let's query the state
let res = query(deps.as_ref(), mock_env(), QueryMsg::GetConfig {}).unwrap();
let value: ConfigResponse = from_binary(&res).unwrap();
assert_eq!(17, value.count);
}
}
|
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::fmt::Write;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum State {
Unknown,
Known(String),
}
impl<S> From<S> for State
where
S: Into<String>,
{
fn from(s: S) -> Self {
State::Known(s.into())
}
}
impl Display for State {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
match self {
State::Unknown => f.write_char('#'),
State::Known(name) => f.write_str(&name),
}
}
}
|
#[test]
fn flex_grow_less_than_factor_one() {
let layout = stretch::node::Node::new(
stretch::style::Style {
size: stretch::geometry::Size {
width: stretch::style::Dimension::Points(500f32),
height: stretch::style::Dimension::Points(200f32),
..Default::default()
},
..Default::default()
},
vec![
&stretch::node::Node::new(
stretch::style::Style {
flex_grow: 0.2f32,
flex_shrink: 0f32,
flex_basis: stretch::style::Dimension::Points(40f32),
..Default::default()
},
vec![],
),
&stretch::node::Node::new(
stretch::style::Style { flex_grow: 0.2f32, flex_shrink: 0f32, ..Default::default() },
vec![],
),
&stretch::node::Node::new(
stretch::style::Style { flex_grow: 0.4f32, flex_shrink: 0f32, ..Default::default() },
vec![],
),
],
)
.compute_layout(stretch::geometry::Size::undefined())
.unwrap();
assert_eq!(layout.size.width, 500f32);
assert_eq!(layout.size.height, 200f32);
assert_eq!(layout.location.x, 0f32);
assert_eq!(layout.location.y, 0f32);
assert_eq!(layout.children[0usize].size.width, 132f32);
assert_eq!(layout.children[0usize].size.height, 200f32);
assert_eq!(layout.children[0usize].location.x, 0f32);
assert_eq!(layout.children[0usize].location.y, 0f32);
assert_eq!(layout.children[1usize].size.width, 92f32);
assert_eq!(layout.children[1usize].size.height, 200f32);
assert_eq!(layout.children[1usize].location.x, 132f32);
assert_eq!(layout.children[1usize].location.y, 0f32);
assert_eq!(layout.children[2usize].size.width, 184f32);
assert_eq!(layout.children[2usize].size.height, 200f32);
assert_eq!(layout.children[2usize].location.x, 224f32);
assert_eq!(layout.children[2usize].location.y, 0f32);
}
|
pub mod character;
pub mod movie;
pub mod user;
|
use aoc2020::aoc::load_data;
use nom::{
bits::complete::*, branch::*, bytes::complete::*, character::complete::*, combinator::*,
multi::*, sequence::*, IResult,
};
use regex::Regex;
use std::collections::HashMap;
use std::io::BufRead;
fn binary_partition(input: &str, lower: char, upper: char) -> u64 {
// 128 -> 0..127
let mut min_value = 0;
let mut max_value = 2u64.pow(input.len() as u32) - 1;
for c in input.chars() {
let half = (min_value + max_value)/ 2;
match c {
c if c == lower => max_value = half,
c if c == upper => min_value = half + 1,
c => panic!(format!("invalid char {}!", c))
}
}
assert_eq!(min_value, max_value);
min_value
}
fn decode(input: &str) -> (u64, u64, u64){
let (row_input, col_input) = input.split_at(input.len() - 3);
let row = binary_partition(row_input, 'F', 'B');
let col = binary_partition(col_input, 'L', 'R');
(row, col, row * 8 + col)
}
fn search_my_seat(seats: &[u64]) -> u64{
let mut seat = 0;
for (i, s) in seats.iter().enumerate(){
if seats[i+1] != s + 1 {
seat = s + 1;
break;
}
}
seat
}
fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
let reader = load_data("examples/data/day5.txt")?;
// let examples = vec![("FBFBBFFRLR", (44, 5, 357)),("BFFFBBFRRR", (70, 7, 567)) , ("FFFBBBFRRR", (14, 7, 119)), ("BBFFBBFRLL", (102, 4, 820))];
// for (src, res) in examples.iter(){
// let decoded = decode(src);
// assert_eq!(&decoded, res);
// println!("{:?}", decoded);
// }
let mut max = 0;
let mut seats = Vec::with_capacity(1024);
for line in reader.lines(){
let (_, _, id) = decode(line?.as_str());
if id > max {
max = id;
}
seats.push(id);
}
println!("max: {}", max);
seats.sort();
println!("{:?}", seats);
println!("my seat{}", search_my_seat(&seats.as_slice()));
Ok(())
}
|
use argon2::{self, Config};
use bson::{doc, oid::ObjectId};
use failure::Fail;
use mongodb::Database;
use rand::Rng;
use serde::{Deserialize, Serialize};
const USERS_COLLECTION: &str = "users";
#[derive(Debug, Fail)]
pub enum UserError {
#[fail(display = "NotFound")]
NotFound,
#[fail(display = "Database")]
DB,
#[fail(display = "Other")]
Other,
}
type Result<T> = std::result::Result<T, UserError>;
#[derive(Serialize, Deserialize, Debug)]
pub struct User {
#[serde(rename = "_id")]
id: ObjectId,
pub username: String,
password: String,
}
impl User {
pub fn new(username: &str, password: &str) -> Result<User> {
let hash = hash(password);
Ok(User {
id: ObjectId::new().map_err(|_| UserError::Other)?,
username: username.to_string(),
password: hash,
})
}
fn load(db: &Database, username: &str) -> Result<User> {
let collection = db.collection(USERS_COLLECTION);
let filter = doc! { "username": username };
let document = collection
.find_one(filter, None)
.map_err(|_| UserError::DB)?;
if document.is_none() {
return Err(UserError::NotFound);
}
Ok(bson::from_bson(bson::Bson::Document(document.unwrap()))
.map_err(|_| UserError::Other)?)
}
pub fn login(db: &Database, username: &str, password: &str) -> Result<User> {
let user = Self::load(db, username)?;
if !verify(password, &user.password) {
return Err(UserError::NotFound);
}
Ok(user)
}
pub fn save(&self, db: &Database) -> Result<()> {
let collection = db.collection(USERS_COLLECTION);
let serialized = bson::to_bson(self).map_err(|_| UserError::Other)?;
if let bson::Bson::Document(document) = serialized {
collection
.insert_one(document, None)
.map_err(|_| UserError::DB)?;
} else {
return Err(UserError::Other);
}
Ok(())
}
pub fn delete(&self, db: &Database) -> Result<()> {
let collection = db.collection(USERS_COLLECTION);
let filter = doc! { "_id": &self.id };
let result = collection
.delete_one(filter, None)
.map_err(|_| UserError::DB)?;
if result.deleted_count == 0 {
return Err(UserError::NotFound);
}
Ok(())
}
pub fn set_password(&mut self, password: &str) {
let hash = hash(password);
self.password = hash;
}
}
fn hash(password: &str) -> String {
let salt: [u8; 32] = rand::thread_rng().gen();
let config = Config::default();
argon2::hash_encoded(password.as_bytes(), &salt, &config).unwrap()
}
fn verify(password: &str, hash: &str) -> bool {
argon2::verify_encoded(hash, password.as_bytes()).unwrap_or(false)
}
|
use cosmwasm_std::{
to_binary, Api, CanonicalAddr, Extern, HumanAddr, Querier, QueryRequest, StdResult, Storage,
Uint128, WasmQuery,
};
use mirror_protocol::staking::{PoolInfoResponse, QueryMsg, RewardInfoResponse};
pub fn query_mirror_reward_info<S: Storage, A: Api, Q: Querier>(
deps: &Extern<S, A, Q>,
mirror_staking: &HumanAddr,
staker: &HumanAddr,
) -> StdResult<RewardInfoResponse> {
let res: RewardInfoResponse = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: HumanAddr::from(mirror_staking),
msg: to_binary(&QueryMsg::RewardInfo {
asset_token: None,
staker_addr: HumanAddr::from(staker),
})?,
}))?;
Ok(res)
}
pub fn query_mirror_pool_balance<S: Storage, A: Api, Q: Querier>(
deps: &Extern<S, A, Q>,
mirror_staking: &CanonicalAddr,
asset_token: &CanonicalAddr,
contract_addr: &CanonicalAddr,
) -> StdResult<Uint128> {
let staker = deps.api.human_address(contract_addr)?;
let reward_info =
query_mirror_reward_info(deps, &deps.api.human_address(mirror_staking)?, &staker)?;
let asset_token = deps.api.human_address(asset_token)?;
Ok(reward_info
.reward_infos
.into_iter()
.find(|it| it.asset_token == asset_token)
.map(|it| it.bond_amount)
.unwrap_or(Uint128::zero()))
}
pub fn query_mirror_pool_info<S: Storage, A: Api, Q: Querier>(
deps: &Extern<S, A, Q>,
mirror_staking: &HumanAddr,
asset_token: &HumanAddr,
) -> StdResult<PoolInfoResponse> {
let res: PoolInfoResponse = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: HumanAddr::from(mirror_staking),
msg: to_binary(&QueryMsg::PoolInfo {
asset_token: HumanAddr::from(asset_token),
})?,
}))?;
Ok(res)
}
|
use nom::*;
use super::*;
use std::str;
use std::str::{from_utf8,FromStr};
////////// Tokens
// Ignored
named!(comment_inline<()>,
do_parse!(
tag!("/*") >>
take_until_and_consume!("*/") >>
()
)
);
named!(comment_line<()>,
do_parse!(
tag!("//") >>
take_until_and_consume!("\n") >>
()
)
);
named!(toss<()>,
map!(
many0!(
alt_complete!( map!(eof!(),|_|{()})
| map!(multispace,|_|{()})
| comment_inline
| comment_line
)
),
|_|{()}
)
);
// Delimiters
named!(comma<()>, delimited!(toss,map!(tag!(","),|x| {()}),toss));
named!(implicates<()>, delimited!(toss,map!(tag!(":-"),|x| {()}),toss));
named!(open_paren<()>,delimited!(toss,map!(tag!("("),|x| {()}),toss));
named!(close_paren<()>,delimited!(toss,map!(tag!(")"),|x| {()}),toss));
named!(open_curly<()>,delimited!(toss,map!(tag!("{"),|x| {()}),toss));
named!(close_curly<()>,delimited!(toss,map!(tag!("}"),|x| {()}),toss));
named!(open_square<()>,delimited!(toss,map!(tag!("["),|x| {()}),toss));
named!(close_square<()>,delimited!(toss,map!(tag!("]"),|x| {()}),toss));
// Numbers
named!(integer<i64>,
do_parse!(
neg: opt!(tag!("-")) >>
i:map_res!(
delimited!(toss,digit,toss),
|x| {
if let Ok(y) = from_utf8(x) {
if let Ok(n) = FromStr::from_str(y) {
Ok(n)
} else {
Err(ParseErrors::NumericParseFailed)
}
} else {
Err(ParseErrors::UTF8ConversionError)
}
}
) >>
(match neg {Some(_) => -1*i, _ => i})
)
);
named!(float_nan,tag!("NaN"));
named!(float_inf,do_parse!(opt!(tag!("-")) >> a:tag!("inf") >> (a)));
named!(float_e,do_parse!(is_a!("eE") >> opt!(tag!("-")) >> a:digit >> (a)));
named!(float_happy,do_parse!(
opt!(tag!("-")) >>
opt!(digit) >>
a:tag!(".") >>
alt!(recognize!(eof!()) | recognize!(opt!(digit))) >>
alt!(recognize!(eof!()) | recognize!(opt!(float_e))) >>
(a)));
named!(float_alts<f64>,
delimited!(toss,
add_return_error!(ErrorKind::Custom(1),
map_res!(
map_res!(
recognize!(
alt_complete!(float_nan | float_inf | float_happy)
),
str::from_utf8
),
FromStr::from_str
)
),
toss)
);
// Booleans
named!(boolean<bool>,
delimited!(toss,
map_res!(
map_res!(
alt_complete!(tag!("true") | tag!("false")),
str::from_utf8
),
FromStr::from_str
),
toss
)
);
// Identifier
named!(identifier<&'a str>,
map_res!(
recognize!(
do_parse!(
alt_complete!(alpha | is_a!("_")) >>
alt!(recognize!(eof!())
| recognize!(opt!(alphanumeric))) >>
(())
)
),
str::from_utf8)
);
// Vars
named!(variable<Variable >,delimited!(toss,map_res!(identifier, Variable::from_str),toss));
// String Literals
fn to_s(i:Vec<u8>) -> String {
String::from_utf8_lossy(&i).into_owned()
}
named!(string_contents<String >,
map!(
escaped_transform!(is_not!("\\\""), '\\',
alt_complete!(
tag!("\\") => { |_| &b"\\"[..] }
| tag!("\"") => { |_| &b"\""[..] }
| tag!("n") => { |_| &b"\n"[..] }
)
), to_s
)
);
named!(string_lit<String>,
do_parse!(
toss >>
tag!("\"") >>
cont:opt!(string_contents) >>
tag!("\"") >>
toss >>
(cont.unwrap_or_default())
)
);
// Expressions
named!(number<Number>,alt_complete!(map!(float_alts, Number::Float) | map!(integer,Number::Int)));
named!(literal<Literal>,alt_complete!(map!(string_lit,Literal::String)
|map!(float_alts,Literal::Float)
|map!(integer,Literal::Int)
|map!(boolean,Literal::Bool)));
// Arithmetic Trees
named!(binary_operator_1<BinaryOperator>,
delimited!(toss,
map_res!(
map_res!(
tag!("%"),
str::from_utf8),
FromStr::from_str
),
toss
)
);
named!(binary_operator_2<BinaryOperator>,
delimited!(toss,
map_res!(
map_res!(
alt!(tag!("*") | tag!("/")),
str::from_utf8),
FromStr::from_str
),
toss
)
);
named!(binary_operator_3<BinaryOperator>,
delimited!(toss,
map_res!(
map_res!(
alt!(tag!("+") | tag!("-")),
str::from_utf8),
FromStr::from_str
),
toss
)
);
// Comparison Trees
named!(binary_operator_4<BinaryOperator>,
delimited!(toss,
map_res!(
map_res!(
alt_complete!( tag!("<=") | tag!("<")
| tag!("==") | tag!("!=")
| tag!(">=") | tag!(">")),
str::from_utf8),
FromStr::from_str
),
toss
)
);
named!(binary_operator_5<BinaryOperator>,
delimited!(toss,
map_res!(
map_res!(
tag!("^"),
str::from_utf8),
FromStr::from_str
),
toss
)
);
named!(binary_operator_6<BinaryOperator>,
delimited!(toss,
map_res!(
map_res!(
tag!("|"),
str::from_utf8),
FromStr::from_str
),
toss
)
);
named!(binary_operator_7<BinaryOperator>,
delimited!(toss,
map_res!(
map_res!(
tag!("&"),
str::from_utf8),
FromStr::from_str
),
toss
)
);
named!(expr_parens<Box<Expr> >,delimited!(open_paren,map!(expr,Box::new),close_paren) );
fn left_fold(initial: Expr,remainder: Vec<(BinaryOperator,Expr)>) -> Expr {
remainder.into_iter().fold(initial,|left,pair| {
let (op,right) = pair;
Expr::BinaryResult((Box::new(left),op,Box::new(right)))
})
}
named!(expr_bottom< Expr >,
alt_complete!(
map!(literal,|n| {Expr::Value(n)})
| map!(expr_parens,Expr::Paren)
| map!(variable,Expr::Variable)
)
);
named!(unary_operator<UnaryOperator>,
delimited!(toss,
map_res!(
map_res!(
alt!(tag!("!") | tag!("-")),
str::from_utf8),
FromStr::from_str
),
toss
)
);
named!(expr_0< Expr >,
do_parse!(
op: opt!(unary_operator) >>
exp : expr_bottom >>
(Expr::to_unary(op,exp))
)
);
named!(expr_1<Expr >,
do_parse!(
left: expr_0 >>
remainder: many0!(
do_parse!(op: binary_operator_1 >>
right:expr_0 >>
(op,right)
)) >>
(left_fold(left,remainder))
)
);
named!(expr_2<Expr >,
do_parse!(
left: expr_1 >>
remainder: many0!(
do_parse!(op: binary_operator_2 >>
right:expr_1 >>
(op,right)
)) >>
(left_fold(left,remainder))
)
);
named!(expr_3<Expr >,
do_parse!(
left: expr_2 >>
remainder: many0!(
do_parse!(op: binary_operator_3 >>
right:expr_2 >>
(op,right)
)) >>
(left_fold(left,remainder))
)
);
named!(expr_4<Expr >,
do_parse!(
left: expr_3 >>
remainder: many0!(
do_parse!(op: binary_operator_4 >>
right:expr_3 >>
(op,right)
)) >>
(left_fold(left,remainder))
)
// do_parse!(
// l: expr_3 >>
// m: opt!(tuple!(binary_operator_4,expr_3)) >>
// (if let Some((op,r)) = m {Expr::BinaryResult((Box::new(l),op,Box::new(r)))} else {l})
// )
);
named!(expr_5<Expr >,
do_parse!(
left: expr_4 >>
remainder: many0!(
do_parse!(op: binary_operator_5 >>
right:expr_4 >>
(op,right)
)) >>
(left_fold(left,remainder))
)
);
named!(expr_6<Expr >,
do_parse!(
left: expr_5 >>
remainder: many0!(
do_parse!(op: binary_operator_6 >>
right:expr_5 >>
(op,right)
)) >>
(left_fold(left,remainder))
)
);
named!(expr<Expr >,
do_parse!(
left: expr_6 >>
remainder: many0!(
do_parse!(op: binary_operator_7 >>
right:expr_6 >>
(op,right)
)) >>
(left_fold(left,remainder))
)
);
// Master Expr
// named!(expr<Expr>, call!(expr_7));
// Term
named!(term<Term >,
alt_complete!(map!(float_alts, |x| {Term::Literal(Literal::Float(x))})
| map!(integer, |x| {Term::Literal(Literal::Int(x))})
| map!(string_lit, |x| {Term::Literal(Literal::String(x))})
| map!(boolean, |x| {Term::Literal(Literal::Bool(x))})
| map!(variable, Term::Variable)
)
);
/////// Facts
// Equation
named!(pub equation<Equation >,
do_parse!(
var:variable >>
delimited!(toss,tag!("="),toss) >>
exp: expr >>
(Equation{value:var,expr:exp})
)
);
// Within clause
named!(within<SemiRange >,
do_parse!(
var: variable >>
toss >>
tag!("in") >>
toss >>
lbt: alt!(tag!("(") | tag!("[")) >>
toss >>
lower: opt!(term) >>
comma >>
upper: opt!(term) >>
ubt: alt!(tag!(")") | tag!("]")) >>
(SemiRange::new(var,lbt,lower,ubt,upper))
)
);
// Row
named!(row_fact<RowFact >,
do_parse!(
id: identifier >>
open_paren >>
terms: separated_nonempty_list!(tag!(","),term) >>
close_paren >>
(RowFact{head:Identifier::from(String::from(id)),terms:terms})
)
);
// Tree
named!(av_pair<(Term,TreeTerm)>,
do_parse!(
at: term >>
val: opt!(alt_complete!(subtree | map!(term,TreeTerm::Term))) >>
(at, val.unwrap_or(TreeTerm::Term(Term::Variable(Variable::Hole))))
)
);
named!(unnamed_subtree<Vec<(Term,TreeTerm)> >,
do_parse!(
open_curly >>
pairs: many1!(av_pair) >>
close_curly >>
(pairs)
)
);
named!(subtree<TreeTerm >,
alt_complete!(
map!(unnamed_subtree,
|avs|
TreeTerm::Tree(Box::new(TreeFact{entity: Term::Variable(Variable::Hole),
avs: avs,
t: Term::Variable(Variable::Hole)
}))
) |
map!(named_subtree, |x| {TreeTerm::Tree(Box::new(x))})
)
);
named!(named_subtree<TreeFact >,
do_parse!(
open_square >>
entity: opt!(term) >>
av: alt_complete!(unnamed_subtree | map!( av_pair, |x| vec![x] ) )>>
t: opt!(term) >>
close_square >>
(TreeFact{entity: entity.unwrap_or(Term::Variable(Variable::Hole)),
avs:av,
t:t.unwrap_or(Term::Variable(Variable::Hole))})
)
);
named!(tree_fact<TreeFact >,
alt_complete!(named_subtree
| map!(unnamed_subtree,
|avs| TreeFact{entity:Term::Variable(Variable::Hole),
avs:avs, t: Term::Variable(Variable::Hole)}
)
)
);
named!(prep<Pred>,
alt_complete!(map!(row_fact, Pred::RowFact)
| map!(tree_fact, Pred::TreeFact)
| map!(equation, Pred::Equation)
| map!(within, Pred::SemiRange)
)
);
named!(fact<Fact>,
do_parse!(
f: prep >>
tag!(";") >>
(Fact(f))
)
);
// Relation
named!(relation<Relation>,
do_parse!(
head: identifier >>
open_paren >>
vars: separated_nonempty_list!(comma,variable) >>
close_paren >>
implicates >>
preps: separated_nonempty_list!(comma,prep) >>
tag!(";") >>
(Relation{head:Identifier::from(String::from(head)),vars:vars,preps:preps})
)
);
#[cfg(test)]
mod tests {
use std::str;
use std::string::*;
use super::*;
use quickcheck::*;
use rand::thread_rng;
#[test]
fn floats() {
fn prop(s:String) -> bool {
if let IResult::Done(rem,out) = float_alts(&s[..].as_bytes()) {
let newstr = &s[0..(s.len()-rem.len())];
if let Ok(Ok(y)) = str::from_utf8(newstr.as_bytes()).map(|x| x.trim()).map(FromStr::from_str) {
out == y
} else {
println!("1: {:?}, ", float_alts(&s[..].as_bytes()));
false
}
} else {
if let Ok(y) = FromStr::from_str(&s) {
let _ :f64 = y;
if let Ok(z) = FromStr::from_str(&s) {
let _ : i64 = z;
// The nom parser should fail to recognize an integer, because we want to have it correctly typed
// Unlike Rust's FromStr, which is happy to cast your integer to a float
// ...
// It's just trying to be nice
true
} else {
println!("2: s:\"{}\", {:?}",s,float_alts(&s[..].as_bytes()));
false
}
} else {
true
}
}
}
assert!(prop(String::from("0. ")));
QuickCheck::new()
.tests(100000)
.max_tests(500000)
.quickcheck(prop as fn(String)-> bool);
}
#[test]
fn int_tower() {
let testa : Vec<String> = ["1","10"," 1","1 "," 1 "].into_iter().map(|x| String::from(*x)).collect();
for s in testa {
if let IResult::Done(_,_) = integer(&s[..].as_bytes()) {
assert!(true);
} else {
println!("{} failed at integer.",s);
assert!(false);
}
if let IResult::Done(_,_) = number(&s[..].as_bytes()) {
assert!(true);
} else {
println!("{} failed at number.",s);
assert!(false);
}
if let IResult::Done(_,_) = expr_bottom(&s[..].as_bytes()) {
assert!(true);
} else {
println!("{} failed at bottom.",s);
assert!(false);
}
if let IResult::Done(_,_) = expr_0(&s[..].as_bytes()) {
assert!(true);
} else {
println!("{} failed at 0.",s);
assert!(false);
}
if let IResult::Done(_,_) = expr_1(&s[..].as_bytes()) {
assert!(true);
} else {
println!("{} failed at 1.",s);
assert!(false);
}
if let IResult::Done(_,_) = expr_2(&s[..].as_bytes()) {
assert!(true);
} else {
println!("{} failed at 2.",s);
assert!(false);
}
if let IResult::Done(_,_) = expr_3(&s[..].as_bytes()) {
assert!(true);
} else {
println!("{} failed at 3.",s);
assert!(false);
}
if let IResult::Done(_,_) = expr_4(&s[..].as_bytes()) {
assert!(true);
} else {
println!("{} failed at 4.",s);
println!("{:?}",expr_4(&s[..].as_bytes()));
assert!(false);
}
if let IResult::Done(_,_) = expr_5(&s[..].as_bytes()) {
assert!(true);
} else {
println!("{} failed at 5.",s);
assert!(false);
}
if let IResult::Done(_,_) = expr_6(&s[..].as_bytes()) {
assert!(true);
} else {
println!("{} failed at 6.",s);
assert!(false);
}
if let IResult::Done(_,_) = expr(&s[..].as_bytes()) {
assert!(true);
} else {
println!("{} failed at master.",s);
assert!(false);
}
}
}
#[test]
fn display() {
let testo = String::from(" 1 + 2 * 3 - 4 % 5 + /* Happy Days */ ( foo * bar ) ");
println!("----------------\ntesto:{}",testo);
if let IResult::Done(_,r) = expr(&testo[..].as_bytes()) {
println!("{}",r);
} else {
println!("Failed to parse.");
}
let testo = String::from(" -1 + 2 * 3 - -4 % 5 + /* Happy Days */ ( -foo * bar ) ");
println!("----------------\ntesto:{}",testo);
if let IResult::Done(_,r) = expr(&testo[..].as_bytes()) {
println!("{}",r);
} else {
println!("Failed to parse.");
}
let testo = String::from("-1");
println!("----------------\ntesto:{}",testo);
if let IResult::Done(_,r) = expr(&testo[..].as_bytes()) {
println!("{}",r);
} else {
println!("Failed to parse.");
}
println!("Subtest:\n---");
if let IResult::Done(_,r) = expr_0(&testo[..].as_bytes()) {
println!("{}",r);
} else {
println!("Failed to parse.");
}
let testo = String::from("1");
println!("----------------\ntesto:{}",testo);
if let IResult::Done(_,r) = expr(&testo[..].as_bytes()) {
println!("{}",r);
} else {
println!("Failed to parse.");
}
}
#[test]
fn bool_display() {
let testo = String::from(" a & b | c ^ /* Bad Days */ (true & false) /* Happy Days */ ");
println!("----------------\ntesto:{}",testo);
if let IResult::Done(_,r) = expr(&testo[..].as_bytes()) {
println!("{}",r);
} else {
println!("Failed to parse.");
}
let testo = String::from(" ! true ^ true");
println!("----------------\ntesto:{}",testo);
match expr(&testo[..].as_bytes()) {
IResult::Done(_,r) => println!("{}",r),
o => println!("Failed with: {:?}",o)
}
let testo = String::from(" !true ");
println!("----------------\ntesto:{}",testo);
match expr(&testo[..].as_bytes()) {
IResult::Done(_,r) => println!("{}",r),
o => println!("Failed with: {:?}",o)
}
println!("Subtest:\n---");
match expr_0(&testo[..].as_bytes()) {
IResult::Done(_,r) => println!("{}",r),
o => println!("Failed with: {:?}",o)
}
let testo = String::from(" true ");
println!("----------------\ntesto:{}",testo);
match expr(&testo[..].as_bytes()) {
IResult::Done(_,r) => println!("{}",r),
o => println!("Failed with: {:?}",o)
}
}
#[test]
fn complex_expr() {
let tests = ["1 / 2",
"1 + x",
"x | y",
"y | x",
"_ / _",
"_ + _ - 10 / 2",
"1+x",
"(1 + x)",
"1+x < 10",
"(1+x) < 10",
"(1+x < 10)",
"((1 + x) < 10)",
"true|false",
"x|y",
"(x & true | y)",
"((1 + x) < 10) | y",
"((1 + x) < 10) ^ false"];
for s in tests.iter() {
let res = expr(&s[..].as_bytes());
println!("Parsing: {:?}",s);
println!("Result: {:?}",res);
if let IResult::Done(x,_) = res {
assert!(x.len() == 0);
} else {
assert!(false);
}
}
}
#[test]
fn equations() {
let tests = ["_ = _ / _"];
for s in tests.iter() {
let res = equation(&s[..].as_bytes());
println!("Parsing: {:?}",s);
println!("Result: {:?}",res);
if let IResult::Done(_,_) = res {
} else {
assert!(false);
}
}
}
#[test]
fn row_facts() {
let tests = ["foo(1,2,3)","bar(\"red\",\"blue\",\"green\")","bam(x,1.5)"];
for s in tests.iter() {
let res = row_fact(&s[..].as_bytes());
println!("Parsing: {:?}",s);
println!("Result: {:?}",res);
if let IResult::Done(_,_) = res {
} else {
assert!(false);
}
}
}
#[test]
fn tree_facts() {
let tests = ["[a b c d]","{\"foo\" x}",
"[x {1 2}]",
"{ \"\" 1}",
"{ \"\" [0 0 _ _]}",
"{ \"\" 1 2 3}",
"{ \"\" 1 2 [0 0 _ _]}",
"{ \"\" [0 0 _ _] 2 [0 0 _ _]}",
"{ \"\" [0 0 _ _] -1 [_ 0 _ false]}"];
for s in tests.iter() {
let res = tree_fact(&s[..].as_bytes());
println!("Parsing: {:?}",s);
println!("Result: {:?}",res);
if let IResult::Done(_,_) = res {
} else {
assert!(false);
}
}
}
#[test]
fn literals() {
let tests = ["1","1.0","\"foo\"","\"\"","true","-3.9574767075378148"];
for s in tests.iter() {
let res = term(&s[..].as_bytes());
println!("Parsing: {:?}",s);
println!("Result: {:?}",res);
if let IResult::Done(_,_) = res {
} else {
assert!(false);
}
}
}
#[test]
fn facts() {
let tests = ["x=y;","foo(x,y);","[{1 x}];","x in [1,10];","x in (,10);","x in (,\"\");","_ = _ / _;",
"[0 0 _ _];",
"[_ 0 _ false];",
"{ \"\" [0 0 _ _] -1 [_ 0 _ false]};",
"[0.0000000000000000000000000000000000000000000000000000000000000000 { \"\" [0 0 _ _] -1 [_ 0 _ false]} false];",
"[_ _ [0.0000000000000000000000000000000000000000000000000000000000000000 { \"\" [0 0 _ _] -1 [_ 0 _ false]} false] 0];",
"[false 0 [_ _ [0.0000000000000000000000000000000000000000000000000000000000000000 { \"\" [0 0 _ _] -1 [_ 0 _ false]} false] 0] _];",
];
for s in tests.iter() {
let res = fact(&s[..].as_bytes());
println!("Parsing: {:?}",s);
println!("Result: {:?}",res);
if let IResult::Done(_,_) = res {
} else {
assert!(false);
}
}
}
#[test]
fn relations() {
let tests = ["same( x , y ) :- x=y , foo( x ) , bar( y );","foo(x,y):-foo(y,x);","foo(x) :- [{1 x}];","q(_) :- _ = _;","e(_) :- _ in (0,\"\");","X(_) :- _ = 0;","E(_) :- _ = ((0));","w(_) :- [_ _ _ _];","Q(_) :- _ = _ + _ ;","Q(_) :- _ = _ - _ ;","Q(_) :- _ = _ % _ ;","Q(_) :- _ = _ * _ ;","Q(_) :- _ = _ / _ ;","b(_) :- [false 0 [_ _ [0.0000000000000000000000000000000000000000000000000000000000000000 { \"\" [0 0 _ _] -1 [_ 0 _ false]} false] 0] _];"];
for s in tests.iter() {
let res = relation(&s[..].as_bytes());
if let IResult::Done(_,_) = res {
} else {
println!("{} - {:?}",s,res);
assert!(false);
}
}
}
#[test]
fn roundtrip_relation() {
fn prop(r:Relation) -> bool {
println!("{}",r);
println!("-----------------");
let s = format!("{}",r);
let res = relation(&s.as_bytes());
if let IResult::Done(_,t) = res {
let ss = format!("{}",t);
let ret = s == ss;
if !ret {
println!("----------Alt---------");
println!("Orig: {}|{:?}",r,r);
println!("New: {}|{:?}",t,t);
}
ret
} else {
println!("----------------------");
println!("Orig: {}",s);
println!("New: {:?}",res);
false
}
}
match QuickCheck::new()
.gen(StdGen::new(thread_rng(),5))
.tests(10000)
.max_tests(50000)
.quicktest(prop as fn(Relation)-> bool) {
Ok(_) => {},
Err(fail) => {
println!("Failed.");
// println!("Str: {}",fail.);
println!("Dbg: {:?}",fail);
assert!(false);
}
};
}
#[test]
fn gen_expr() {
fn prop(e:Expr) -> bool {
let s = format!("{}",e);
let res = expr(&s.as_bytes());
if let IResult::Done(_,t) = res {
let ss = format!("{}",t);
let ret = s == ss;
if !ret {
println!("----------------");
println!("Orig: {}",s);
println!("Dbg: {:?}",e);
println!("Round: {}",t);
println!("Dbg: {:?}",t);
}
ret
} else {
println!("Failed {} - {:?}",s,res);
false
}
}
QuickCheck::new()
.gen(StdGen::new(thread_rng(),10))
.tests(10000)
.max_tests(50000)
.quickcheck(prop as fn(Expr)-> bool);
}
#[test]
fn roundtrip_literal() {
fn prop(r:Literal) -> bool {
let s = format!("{}",r);
let res = term(&s.as_bytes());
if let IResult::Done(_,t) = res {
t == Term::Literal(r)
} else {
false
}
}
QuickCheck::new()
.gen(StdGen::new(thread_rng(),10))
.tests(10000)
.max_tests(50000)
.quickcheck(prop as fn(Literal)-> bool);
}
}
|
use std::fmt::Display;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom};
use std::path::Path;
use crate::savable::Savable;
use super::MirrorMode;
/// Size of one PRG bank
pub const PRG_PAGE_SIZE: usize = 0x4000;
/// Size of one CHR bank
pub const CHR_PAGE_SIZE: usize = 0x2000;
/// Size of the iNES header
const HEADER_SIZE: usize = 16;
/// iNES header tag. Must be at the start of the file
const NES_TAG: [u8; 4] = [b'N', b'E', b'S', 0x1A];
/// Header of the iNES file format
#[derive(Clone, Copy)]
pub struct INesHeader {
bytes: [u8; 16],
}
impl INesHeader {
pub fn new(bytes: [u8; HEADER_SIZE]) -> Self {
Self { bytes }
}
pub fn is_valid(&self) -> bool {
self.bytes[..4] == NES_TAG
}
/// PRG bank count
pub fn prg_count(&self) -> usize {
self.bytes[4] as usize
}
/// CHR bank count
pub fn chr_count(&self) -> usize {
self.bytes[5] as usize
}
/// Contains trainer data or not
pub fn has_trainer(&self) -> bool {
self.bytes[6] & 0x4 != 0
}
/// Hardware mirror mode
pub fn mirror_mode(&self) -> MirrorMode {
match self.bytes[6] & 0x1 != 0 {
true => MirrorMode::Vertical,
false => MirrorMode::Horizontal,
}
}
/// Uses 4 screen VRAM
pub fn four_screen(&self) -> bool {
self.bytes[6] & 0x8 != 0
}
/// ID of the iNES mapper
pub fn mapper_id(&self) -> u8 {
(self.bytes[7] & 0xF0) | (self.bytes[6] >> 4)
}
}
/// Game ROM data
pub struct Rom {
pub header: INesHeader,
pub prg: Vec<u8>,
pub chr: Vec<u8>,
}
impl Savable for Rom {
fn save(&self, output: &mut BufWriter<File>) -> bincode::Result<()> {
if self.header.chr_count() == 0 {
bincode::serialize_into(output, &self.chr)?;
}
Ok(())
}
fn load(&mut self, input: &mut BufReader<File>) -> bincode::Result<()> {
if self.header.chr_count() == 0 {
self.chr = bincode::deserialize_from(input)?;
}
Ok(())
}
}
impl Rom {
pub fn new<P: AsRef<Path> + Display>(romfile: P) -> io::Result<Self> {
let mut file = File::open(&romfile)?;
let mut buf = [0; HEADER_SIZE];
file.read_exact(&mut buf)?;
let header = INesHeader::new(buf);
if !header.is_valid() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Not iNES file format",
));
}
if header.has_trainer() {
file.seek(SeekFrom::Current(512))?;
}
let prg_size = PRG_PAGE_SIZE * header.prg_count();
let prg_start = 0;
let chr_size = CHR_PAGE_SIZE * header.chr_count();
let chr_start = prg_start + prg_size;
println!(
"PRG Size: {} * {:#06X} = {:#06X} ({} KB)",
header.prg_count(),
PRG_PAGE_SIZE,
prg_size,
header.prg_count() * 16,
);
if header.chr_count() == 0 {
println!(
"CHR Size (RAM): 1 * {:#06X} = {:#06X} (8 KB)",
CHR_PAGE_SIZE, CHR_PAGE_SIZE,
);
} else {
println!(
"CHR Size: {} * {:#06X} = {:#06X} ({} KB)",
header.chr_count(),
CHR_PAGE_SIZE,
chr_size,
header.chr_count() * 8
);
}
println!("Mapper ID: {}", header.mapper_id());
let mut rom_bytes = Vec::new();
file.read_to_end(&mut rom_bytes)?;
let prg = rom_bytes[prg_start..(prg_start + prg_size)].to_vec();
let chr = if header.chr_count() == 0 {
vec![0; CHR_PAGE_SIZE]
} else {
rom_bytes[chr_start..(chr_start + chr_size)].to_vec()
};
Ok(Self { header, prg, chr })
}
}
|
use std::process;
use dotenv::dotenv;
use std::env;
use rand::Rng;
extern crate querystring;
extern crate paho_mqtt as mqtt;
fn main() {
dotenv().ok();
let mut rng = rand::thread_rng();
let mqtt_server = env::var("MQTT_SERVER").unwrap();
let mqtt_publish = env::var("MQTT_PUBLISH").unwrap();
let cli = mqtt::Client::new(mqtt_server).unwrap_or_else(|err| {
println!("Error creating the client: {:?}", err);
process::exit(1);
});
let conn_opts = mqtt::ConnectOptionsBuilder::new()
.keep_alive_interval(std::time::Duration::from_secs(20))
.clean_session(true)
.finalize();
if let Err(e) = cli.connect(conn_opts) {
println!("Unable to connect:\n\t{:?}", e);
process::exit(1);
}
let temperature: u8 = rng.gen();
let temperature_string = temperature.to_string();
let mut sensor_values_vector = vec![
("field1", temperature_string.as_str())
];
let color: u8 = rng.gen();
let color_string = color.to_string();
sensor_values_vector.push(
("field2", color_string.as_str())
);
let humidity: u8 = rng.gen();
let humidity_string = humidity.to_string();
sensor_values_vector.push(
("field3", humidity_string.as_str())
);
let pressure: u8 = rng.gen();
let pressure_string = pressure.to_string();
sensor_values_vector.push(
("field4", pressure_string.as_str())
);
sensor_values_vector.push(
("status", "MQTTPUBLISH")
);
let qs: String = querystring::stringify(sensor_values_vector);
let msg = mqtt::Message::new(mqtt_publish, qs, 0);
let tok = cli.publish(msg);
if let Err(e) = tok {
println!("Error sending message: {:?}", e);
}
// Disconnect from the broker
let _tok = cli.disconnect(None);
}
|
//! popcnt
/// Count bits set.
pub trait Popcnt {
/// Counts the bits that are set.
///
/// **Keywords**: Population count, count ones, Hamming weight, Sideways
/// sum.
///
/// # Instructions
///
/// - [`POPCNT`](http://www.felixcloutier.com/x86/POPCNT.html):
/// - Description: Population Count.
/// - Architecture: x86.
/// - Instruction set: ABM, SSE 4.2.
/// - Registers: 16/32/64 bit.
/// - Note: Intel considers it part of SSE4.2 but advertises it with its
/// own CPUID flag.
///
/// # Example
/// ```
/// # use bitintr::*;
/// assert_eq!(0b0101_1010u16.popcnt(), 4);
/// ```
fn popcnt(self) -> Self;
}
macro_rules! impl_popcnt {
($id:ident) => {
impl Popcnt for $id {
#[inline]
fn popcnt(self) -> Self {
self.count_ones() as Self
}
}
};
}
impl_all!(impl_popcnt: u8, u16, u32, u64, i8, i16, i32, i64);
|
use std::collections::{HashMap, HashSet};
use apllodb_shared_components::{ApllodbError, ApllodbResult};
use apllodb_storage_engine_interface::{
ColumnName, RowProjectionQuery, RowSchema, TableColumnName,
};
use serde::{Deserialize, Serialize};
use crate::{
entity::Entity,
version::{active_versions::ActiveVersions, id::VersionId},
vtable::VTable,
};
/// Has projected columns for each version in a VTable.
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub struct RowProjectionResult {
result_per_version: HashMap<VersionId, ProjectionResultInVersion>,
}
impl RowProjectionResult {
/// Calculate and construct ProjectionResult
pub fn new(
vtable: &VTable,
active_versions: ActiveVersions,
query: &RowProjectionQuery,
) -> ApllodbResult<Self> {
let pk_columns: HashSet<ColumnName> = vtable
.table_wide_constraints()
.pk_column_names()
.into_iter()
.collect();
let versions_available_columns: HashSet<ColumnName> = active_versions
.as_sorted_slice()
.iter()
.map(|active_version| {
active_version
.column_data_types()
.iter()
.map(|cdt| cdt.column_name())
})
.flatten()
.cloned()
.collect();
let pk_query_columns: Vec<ColumnName> = match query {
RowProjectionQuery::All => pk_columns.iter().cloned().collect(),
RowProjectionQuery::ColumnIndexes(idxs) => pk_columns
.iter()
.filter(|cn| idxs.iter().any(|idx| cn.matches(idx)))
.cloned()
.collect(),
};
let non_pk_query_columns: Vec<ColumnName> = match &query {
RowProjectionQuery::All => versions_available_columns.iter().cloned().collect(),
RowProjectionQuery::ColumnIndexes(idxs) => versions_available_columns
.iter()
.filter(|cn| idxs.iter().any(|idx| cn.matches(idx)))
.cloned()
.collect(),
};
// check NameErrorNotFound
{
let available_columns: Vec<&ColumnName> = pk_columns
.iter()
.chain(versions_available_columns.iter())
.collect();
for q_cn in pk_query_columns.iter().chain(non_pk_query_columns.iter()) {
if !available_columns.contains(&q_cn) {
return Err(ApllodbError::name_error_not_found(format!(
"undefined column `{:?}` is queried",
q_cn
)));
}
}
}
let (pk_effective_columns, pk_void_columns): (Vec<ColumnName>, Vec<ColumnName>) =
pk_query_columns
.iter()
.cloned()
.partition(|q_cn| pk_columns.contains(q_cn));
let mut result_per_version: HashMap<VersionId, ProjectionResultInVersion> = HashMap::new();
for active_version in active_versions.as_sorted_slice() {
let version_id = active_version.id();
let version_columns: HashSet<&ColumnName> = active_version
.column_data_types()
.iter()
.map(|cdt| cdt.column_name())
.collect();
let (non_pk_effective_columns, non_pk_void_columns): (
Vec<ColumnName>,
Vec<ColumnName>,
) = non_pk_query_columns
.iter()
.cloned()
.partition(|q_cn| version_columns.contains(q_cn));
let result_in_version = ProjectionResultInVersion {
pk_effective: pk_effective_columns.clone(),
pk_void: pk_void_columns.clone(),
non_pk_effective: non_pk_effective_columns,
non_pk_void: non_pk_void_columns,
};
result_per_version.insert(version_id.clone(), result_in_version);
}
Ok(Self { result_per_version })
}
/// Columns included in [ProjectionQuery](apllodb-shared-components::ProjectionQuery) and primary key for this version.
pub fn pk_effective_projection(
&self,
version_id: &VersionId,
) -> ApllodbResult<&Vec<ColumnName>> {
self.get_projection_core(version_id, |result_in_version| {
&result_in_version.pk_effective
})
}
/// Columns included in [ProjectionQuery](apllodb-shared-components::ProjectionQuery) but not in the primary key for this version.
pub fn pk_void_projection(&self, version_id: &VersionId) -> ApllodbResult<&Vec<ColumnName>> {
self.get_projection_core(version_id, |result_in_version| &result_in_version.pk_void)
}
/// Columns included in [ProjectionQuery](apllodb-shared-components::ProjectionQuery) and non-PK for this version.
pub fn non_pk_effective_projection(
&self,
version_id: &VersionId,
) -> ApllodbResult<&Vec<ColumnName>> {
self.get_projection_core(version_id, |result_in_version| {
&result_in_version.non_pk_effective
})
}
/// Columns included in [ProjectionQuery](apllodb-shared-components::ProjectionQuery) but not in the non-PK for this version.
pub fn non_pk_void_projection(
&self,
version_id: &VersionId,
) -> ApllodbResult<&Vec<ColumnName>> {
self.get_projection_core(version_id, |result_in_version| {
&result_in_version.non_pk_void
})
}
fn get_projection_core<F: FnOnce(&ProjectionResultInVersion) -> &Vec<ColumnName>>(
&self,
version_id: &VersionId,
columns_from_result_in_version: F,
) -> ApllodbResult<&Vec<ColumnName>> {
self.result_per_version
.get(version_id)
.map(columns_from_result_in_version)
.ok_or_else(|| {
ApllodbError::name_error_not_found(format!(
"invalid columns are queried from version `{:?}`",
version_id
))
})
}
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Serialize, Deserialize)]
struct ProjectionResultInVersion {
pk_effective: Vec<ColumnName>,
pk_void: Vec<ColumnName>,
non_pk_effective: Vec<ColumnName>,
non_pk_void: Vec<ColumnName>,
}
impl From<RowProjectionResult> for RowSchema {
fn from(pr: RowProjectionResult) -> Self {
assert!(
!pr.result_per_version.is_empty(),
"at least 1 pr.result_per_version should exist for CREATEd table"
);
let (version_id, _) = pr.result_per_version.iter().next().unwrap();
let table_name = version_id.vtable_id().table_name().clone();
let mut all_column_names: Vec<ColumnName> = vec![];
for (_, mut projection_result_in_version) in pr.result_per_version {
all_column_names.append(&mut projection_result_in_version.pk_effective);
all_column_names.append(&mut projection_result_in_version.pk_void);
all_column_names.append(&mut projection_result_in_version.non_pk_effective);
all_column_names.append(&mut projection_result_in_version.non_pk_void);
}
let table_column_names: HashSet<TableColumnName> = all_column_names
.into_iter()
.map(|cn| TableColumnName::new(table_name.clone(), cn))
.collect();
RowSchema::from(table_column_names)
}
}
|
//! Uses the oauth library to set get an fresh access token
extern crate oauth2;
extern crate rustc_serialize;
use std;
use rustc_serialize::json;
use std::fs::File;
use std::io::Read;
#[derive(RustcDecodable, RustcEncodable)]
struct Secret {
client_id: String,
client_secret: String,
auth_url: String,
token_url: String
}
#[allow(dead_code)]
pub fn printcode () {
let mut f = File::open("secrets.json").unwrap();
let mut read_str = String::new();
let _ = f.read_to_string(&mut read_str);
let sec : Secret = json::decode(&read_str).unwrap();
let mut conf = oauth2::Config::new(
&sec.client_id,
&sec.client_secret,
&sec.auth_url,
&sec.token_url
);
conf.scopes = vec!["repo".to_owned()];
let url = conf.authorize_url("v0.0.1 gitbot".to_owned());
println!("please visit this url: {}", url);
let mut user_code = String::new();
let _ = std::io::stdin().read_line(&mut user_code).unwrap();
user_code.pop();
let tok = conf.exchange(user_code).unwrap();
println!("access code is: {}", tok.access_token);
}
|
// {% include 'doc.template' %}
use crate::core::expression::*;
/// Represents an attribute which a mathematical structure may exhibit.
pub enum Attribute {
/// Represents the anticommutative property of a binary operation.
Anticommutative,
/// Represents the associative property of a binary operation.
Associative,
/// Represents the commutative property of a binary operation.
Commutative,
/// Represents the distributive property of a binary operation over another operation by name.
Distributive(String),
/// Represents the idempotent property of a unary operation.
Idempotent,
/// Represents the identity property of a binary opertation over a specified expression.
Identity(Expression),
/// Represents that a structure is "intrinsicly" irreducible.
Irreducible,
/// Represents some other attribute with the specified name.
Other(String)
}
|
use std::convert::{TryFrom, TryInto};
use proc_macro2::Span;
use syn::{spanned::Spanned, Error, ExprReturn, Result};
use crate::glsl::Glsl;
use super::YaslExprLineScope;
#[derive(Debug)]
pub struct YaslExprReturn {
return_token: syn::token::Return,
expr: Option<Box<YaslExprLineScope>>,
}
impl YaslExprReturn {
pub fn span(&self) -> Span {
self.return_token.span()
}
}
impl From<&YaslExprReturn> for Glsl {
fn from(expr: &YaslExprReturn) -> Glsl {
let glsl_expr = if let Some(expr) = &expr.expr {
format!("{}", Glsl::from(&**expr))
} else {
String::new()
};
Glsl::Expr(format!("return {}", glsl_expr))
}
}
impl TryFrom<ExprReturn> for YaslExprReturn {
type Error = Error;
fn try_from(r: ExprReturn) -> Result<Self> {
let return_token = r.return_token;
let expr = if let Some(expr) = r.expr {
Some(Box::new(YaslExprLineScope::try_from(*expr)?))
} else {
None
};
Ok(Self { return_token, expr })
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Instruction and Data Tightly-Coupled Memory Control Registers"]
pub itcmcr: ITCMCR,
#[doc = "0x04 - Instruction and Data Tightly-Coupled Memory Control Registers"]
pub dtcmcr: DTCMCR,
#[doc = "0x08 - AHBP Control register"]
pub ahbpcr: AHBPCR,
#[doc = "0x0c - Auxiliary Cache Control register"]
pub cacr: CACR,
#[doc = "0x10 - AHB Slave Control register"]
pub ahbscr: AHBSCR,
_reserved5: [u8; 0x04],
#[doc = "0x18 - Auxiliary Bus Fault Status register"]
pub abfsr: ABFSR,
}
#[doc = "ITCMCR (rw) register accessor: Instruction and Data Tightly-Coupled Memory Control Registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`itcmcr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`itcmcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`itcmcr`]
module"]
pub type ITCMCR = crate::Reg<itcmcr::ITCMCR_SPEC>;
#[doc = "Instruction and Data Tightly-Coupled Memory Control Registers"]
pub mod itcmcr;
#[doc = "DTCMCR (rw) register accessor: Instruction and Data Tightly-Coupled Memory Control Registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dtcmcr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`dtcmcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`dtcmcr`]
module"]
pub type DTCMCR = crate::Reg<dtcmcr::DTCMCR_SPEC>;
#[doc = "Instruction and Data Tightly-Coupled Memory Control Registers"]
pub mod dtcmcr;
#[doc = "AHBPCR (rw) register accessor: AHBP Control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahbpcr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ahbpcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahbpcr`]
module"]
pub type AHBPCR = crate::Reg<ahbpcr::AHBPCR_SPEC>;
#[doc = "AHBP Control register"]
pub mod ahbpcr;
#[doc = "CACR (rw) register accessor: Auxiliary Cache Control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cacr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cacr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cacr`]
module"]
pub type CACR = crate::Reg<cacr::CACR_SPEC>;
#[doc = "Auxiliary Cache Control register"]
pub mod cacr;
#[doc = "AHBSCR (rw) register accessor: AHB Slave Control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahbscr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ahbscr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahbscr`]
module"]
pub type AHBSCR = crate::Reg<ahbscr::AHBSCR_SPEC>;
#[doc = "AHB Slave Control register"]
pub mod ahbscr;
#[doc = "ABFSR (rw) register accessor: Auxiliary Bus Fault Status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`abfsr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`abfsr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`abfsr`]
module"]
pub type ABFSR = crate::Reg<abfsr::ABFSR_SPEC>;
#[doc = "Auxiliary Bus Fault Status register"]
pub mod abfsr;
|
// 2019-01-09
// On va présenter l'intérêt de if let
fn main() {
// Voyons le cas de figure à remplacer.
// On fait passer match pour éxécuter du code si une_valeur_u8 égale 3
// Définir la variable 3u8 veut dire "entier positif à 8 bits, valeur 3"
// La définir avec Some() permet de... et bah en fait ça change rien.
// Ce code fonctionne très bien sans écrire Some().
let une_valeur_u8 = Some(3u8);
// faire passer la variable dans match
match une_valeur_u8 {
Some(3) => println!("Trois !"),
_ => (),
}
// Ce code avec match, il marche très bien, mais c'est un peu overkill
// if let permet d'éxécuter du code en fonction d'une seule condition
if let Some(3) = une_valeur_u8 { // mettre les termes dans cet ordre
println!("Trois encore !"); // un seul signe égal !
} else {
println!("C'était pas trois"); // on peut utiliser else
}
}
|
use std::cmp::Reverse;
use std::collections::HashMap;
use std::{env, fs};
use std::fs::File;
use std::io::BufWriter;
use csv::Writer;
use itertools::Itertools;
fn main() {
let dir = fs::read_dir(env::args().nth(1).expect("Pass the directory by the command line")).unwrap();
let needles = env::args().skip(2);
let mut words: HashMap<String, u64> = needles.map(|w| (w.to_lowercase(), 0)).collect();
let mut csv = Writer::from_writer(BufWriter::new(File::create("freqs.csv").unwrap()));
csv.write_record(&["filename", "word", "count"]).unwrap();
for entry in dir.map(Result::unwrap).sorted_by_key(|e| e.path()) {
let path = entry.path();
let file_name = path.file_name().unwrap().to_string_lossy();
let content = fs::read_to_string(&path).unwrap();
for word in content.split_whitespace() {
let word = word
.replace(|c: char| c.is_ascii_punctuation(), "")
.to_lowercase();
words.entry(word).and_modify(|count| *count += 1);
}
for (word, count) in words.iter_mut().sorted_by_key(|(_w, c)| Reverse(**c)) {
csv.write_record(&[&file_name as &str, &word, &count.to_string()]).unwrap();
*count = 0;
}
}
}
|
use super::*;
use crate::classification::{quotes::QuoteClassifiedBlock, ResumeClassifierBlockState, ResumeClassifierState};
use crate::debug;
struct Block<'i, I, const N: usize>
where
I: InputBlockIterator<'i, N>,
{
quote_classified: QuoteClassifiedBlock<I::Block, usize, N>,
idx: usize,
are_colons_on: bool,
are_commas_on: bool,
}
impl<'i, I, const N: usize> Block<'i, I, N>
where
I: InputBlockIterator<'i, N>,
{
fn new(
quote_classified_block: QuoteClassifiedBlock<I::Block, usize, N>,
are_colons_on: bool,
are_commas_on: bool,
) -> Self {
Self {
quote_classified: quote_classified_block,
idx: 0,
are_colons_on,
are_commas_on,
}
}
fn from_idx(
quote_classified_block: QuoteClassifiedBlock<I::Block, usize, N>,
idx: usize,
are_colons_on: bool,
are_commas_on: bool,
) -> Self {
Self {
quote_classified: quote_classified_block,
idx,
are_colons_on,
are_commas_on,
}
}
}
impl<'i, I, const N: usize> Iterator for Block<'i, I, N>
where
I: InputBlockIterator<'i, N>,
{
type Item = Structural;
fn next(&mut self) -> Option<Self::Item> {
while self.idx < self.quote_classified.block.len() {
let character = self.quote_classified.block[self.idx];
let idx_mask = 1_usize << self.idx;
let is_quoted = (self.quote_classified.within_quotes_mask & idx_mask) == idx_mask;
let structural = match character {
_ if is_quoted => None,
b':' if self.are_colons_on => Some(Colon(self.idx)),
b'{' => Some(Opening(BracketType::Curly, self.idx)),
b'[' => Some(Opening(BracketType::Square, self.idx)),
b',' if self.are_commas_on => Some(Comma(self.idx)),
b'}' => Some(Closing(BracketType::Curly, self.idx)),
b']' => Some(Closing(BracketType::Square, self.idx)),
_ => None,
};
self.idx += 1;
if structural.is_some() {
return structural;
};
}
None
}
}
pub(crate) struct SequentialClassifier<'i, I, Q, const N: usize>
where
I: InputBlockIterator<'i, N>,
{
iter: Q,
block: Option<Block<'i, I, N>>,
are_colons_on: bool,
are_commas_on: bool,
}
impl<'i, I, Q, const N: usize> SequentialClassifier<'i, I, Q, N>
where
I: InputBlockIterator<'i, N>,
Q: QuoteClassifiedIterator<'i, I, usize, N>,
{
#[inline(always)]
#[allow(dead_code)]
pub(crate) fn new(iter: Q) -> Self {
Self {
iter,
block: None,
are_colons_on: false,
are_commas_on: false,
}
}
#[inline]
fn reclassify(&mut self, idx: usize) {
if let Some(block) = self.block.take() {
let quote_classified_block = block.quote_classified;
let relevant_idx = idx + 1;
let block_idx = (idx + 1) % N;
debug!("relevant_idx is {relevant_idx}.");
if block_idx != 0 || relevant_idx == self.iter.get_offset() {
let new_block = Block::from_idx(
quote_classified_block,
block_idx,
self.are_colons_on,
self.are_commas_on,
);
self.block = Some(new_block);
}
}
}
}
impl<'i, I, Q, const N: usize> FallibleIterator for SequentialClassifier<'i, I, Q, N>
where
I: InputBlockIterator<'i, N>,
Q: QuoteClassifiedIterator<'i, I, usize, N>,
{
type Item = Structural;
type Error = InputError;
#[inline(always)]
fn next(&mut self) -> Result<Option<Structural>, InputError> {
let mut item = self.block.as_mut().and_then(Iterator::next);
while item.is_none() {
match self.iter.next()? {
Some(block) => {
let mut block = Block::new(block, self.are_colons_on, self.are_commas_on);
item = block.next();
self.block = Some(block);
}
None => return Ok(None),
}
}
Ok(item.map(|x| x.offset(self.iter.get_offset())))
}
}
impl<'i, I, Q, const N: usize> StructuralIterator<'i, I, Q, usize, N> for SequentialClassifier<'i, I, Q, N>
where
I: InputBlockIterator<'i, N>,
Q: QuoteClassifiedIterator<'i, I, usize, N>,
{
fn turn_colons_and_commas_on(&mut self, idx: usize) {
if !self.are_commas_on && !self.are_colons_on {
self.are_commas_on = true;
self.are_colons_on = true;
debug!("Turning both commas and colons on at {idx}.");
self.reclassify(idx);
} else if !self.are_commas_on {
self.turn_commas_on(idx);
} else if !self.are_colons_on {
self.turn_colons_on(idx);
}
}
fn turn_colons_and_commas_off(&mut self) {
if self.are_commas_on && self.are_colons_on {
self.are_commas_on = false;
self.are_colons_on = false;
debug!("Turning both commas and colons off.");
} else if self.are_commas_on {
self.turn_commas_off();
} else if self.are_colons_on {
self.turn_colons_off();
}
}
fn turn_commas_on(&mut self, idx: usize) {
if !self.are_commas_on {
self.are_commas_on = true;
debug!("Turning commas on at {idx}.");
self.reclassify(idx);
}
}
fn turn_commas_off(&mut self) {
self.are_commas_on = false;
debug!("Turning commas off.");
}
fn turn_colons_on(&mut self, idx: usize) {
if !self.are_colons_on {
self.are_colons_on = true;
debug!("Turning colons on at {idx}.");
self.reclassify(idx);
}
}
fn turn_colons_off(&mut self) {
self.are_colons_on = false;
debug!("Turning colons off.");
}
fn stop(self) -> ResumeClassifierState<'i, I, Q, usize, N> {
let block = self.block.map(|b| ResumeClassifierBlockState {
block: b.quote_classified,
idx: b.idx,
});
ResumeClassifierState {
iter: self.iter,
block,
are_colons_on: self.are_colons_on,
are_commas_on: self.are_commas_on,
}
}
fn resume(state: ResumeClassifierState<'i, I, Q, usize, N>) -> Self {
Self {
iter: state.iter,
block: state.block.map(|b| Block {
quote_classified: b.block,
idx: b.idx,
are_commas_on: state.are_commas_on,
are_colons_on: state.are_colons_on,
}),
are_commas_on: state.are_commas_on,
are_colons_on: state.are_colons_on,
}
}
}
|
/// Assume a condition is true.
///
/// * When true, return `Ok(true)`.
///
/// * Otherwise, return [`Err`] with a message and the values of the
/// expressions with their debug representations.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate assertable; fn main() {
/// let x = assume!(true);
/// //-> Ok(true)
/// # }
/// ```
///
/// ```rust
/// # #[macro_use] extern crate assertable; fn main() {
/// let x = assume!(false);
/// //-> Err("assumption failed: `false`")
/// # }
/// ```
///
/// This macro has a second form where a custom message can be provided.
#[macro_export]
macro_rules! assume {
($x:expr $(,)?) => ({
if $x {
Ok(true)
} else {
Err(format!("assumption failed: `{:?}`", $x))
}
});
($x:expr, $($arg:tt)+) => ({
if $x {
Ok(true)
} else {
Err($($arg)+)
}
});
}
#[cfg(test)]
mod tests {
#[test]
fn test_assume_x_arity_2_success() {
let a = true;
let x = assume!(a);
assert_eq!(
x.unwrap(),
true
);
}
#[test]
fn test_assume_x_arity_2_failure() {
let a = false;
let x = assume!(a);
assert_eq!(
x.unwrap_err(),
"assumption failed: `false`"
);
}
#[test]
fn test_assume_x_arity_3_success() {
let a = true;
let x = assume!(a, "message");
assert_eq!(
x.unwrap(),
true
);
}
#[test]
fn test_assume_x_arity_3_failure() {
let a = false;
let x = assume!(a, "message");
assert_eq!(
x.unwrap_err(),
"message"
);
}
}
|
extern crate combine;
extern crate combine_language;
use combine::parser::char::{alpha_num, letter, string};
use combine::{satisfy, EasyParser, Parser};
use combine_language::{Identifier, LanguageDef, LanguageEnv};
fn main() {
let env = LanguageEnv::new(LanguageDef {
ident: Identifier {
start: letter(),
rest: alpha_num(),
reserved: ["if", "then", "else", "let", "in", "type"]
.iter()
.map(|x| (*x).into())
.collect(),
},
op: Identifier {
start: satisfy(|c| "+-*/".chars().any(|x| x == c)),
rest: satisfy(|c| "+-*/".chars().any(|x| x == c)),
reserved: ["+", "-", "*", "/"].iter().map(|x| (*x).into()).collect(),
},
comment_start: string("/*").map(|_| ()),
comment_end: string("*/").map(|_| ()),
comment_line: string("//").map(|_| ()),
});
let id = env.identifier(); //An identifier parser
let integer = env.integer(); //An integer parser
let result = (id, integer).easy_parse("this /* Skips comments */ 42");
assert_eq!(result, Ok(((String::from("this"), 42), "")));
}
|
//! A runtime for writing reliable, asynchronous, and slim applications.
//!
//! Tokio is an event-driven, non-blocking I/O platform for writing asynchronous
//! applications with the Rust programming language. At a high level, it
//! provides a few major components:
//!
//! * A multi threaded, work-stealing based task [scheduler][runtime].
//! * A [reactor] backed by the operating system's event queue (epoll, kqueue,
//! IOCP, etc...).
//! * Asynchronous [TCP and UDP][net] sockets.
//! * Asynchronous [filesystem][fs] operations.
//! * [Timer][timer] API for scheduling work in the future.
//!
//! Tokio is built using [futures] as the abstraction for managing the
//! complexity of asynchronous programming.
//!
//! Guide level documentation is found on the [website].
//!
//! [website]: https://tokio.rs/docs/getting-started/hello-world/
//! [futures]: http://docs.rs/futures/0.1
//!
//! # Examples
//!
//! A simple TCP echo server:
//!
//! ```no_run
//! extern crate tokio;
//!
//! use tokio::prelude::*;
//! use tokio::io::copy;
//! use tokio::net::TcpListener;
//!
//! fn main() {
//! // Bind the server's socket.
//! let addr = "127.0.0.1:12345".parse().unwrap();
//! let listener = TcpListener::bind(&addr)
//! .expect("unable to bind TCP listener");
//!
//! // Pull out a stream of sockets for incoming connections
//! let server = listener.incoming()
//! .map_err(|e| eprintln!("accept failed = {:?}", e))
//! .for_each(|sock| {
//! // Split up the reading and writing parts of the
//! // socket.
//! let (reader, writer) = sock.split();
//!
//! // A future that echos the data and returns how
//! // many bytes were copied...
//! let bytes_copied = copy(reader, writer);
//!
//! // ... after which we'll print what happened.
//! let handle_conn = bytes_copied.map(|amt| {
//! println!("wrote {:?} bytes", amt)
//! }).map_err(|err| {
//! eprintln!("IO error {:?}", err)
//! });
//!
//! // Spawn the future as a concurrent task.
//! tokio::spawn(handle_conn)
//! });
//!
//! // Start the Tokio runtime
//! tokio::run(server);
//! }
//! ```
#![doc(html_root_url = "https://docs.rs/tokio/0.1.5")]
#![deny(missing_docs, warnings, missing_debug_implementations)]
#[macro_use]
extern crate futures;
extern crate mio;
extern crate tokio_current_thread;
extern crate tokio_io;
extern crate tokio_executor;
extern crate tokio_codec;
extern crate tokio_fs;
extern crate tokio_reactor;
extern crate tokio_threadpool;
extern crate tokio_timer;
extern crate tokio_tcp;
extern crate tokio_udp;
#[cfg(unix)]
extern crate tokio_uds;
pub mod clock;
pub mod executor;
pub mod fs;
pub mod net;
pub mod reactor;
pub mod runtime;
pub mod timer;
pub mod util;
pub use executor::spawn;
pub use runtime::run;
pub mod codec {
//! Utilities for encoding and decoding frames.
//!
//! Contains adapters to go from streams of bytes, [`AsyncRead`] and
//! [`AsyncWrite`], to framed streams implementing [`Sink`] and [`Stream`].
//! Framed streams are also known as [transports].
//!
//! [`AsyncRead`]: ../io/trait.AsyncRead.html
//! [`AsyncWrite`]: ../io/trait.AsyncWrite.html
//! [`Sink`]: https://docs.rs/futures/0.1/futures/sink/trait.Sink.html
//! [`Stream`]: https://docs.rs/futures/0.1/futures/stream/trait.Stream.html
//! [transports]: https://tokio.rs/docs/going-deeper/frames/
pub use tokio_codec::{
Decoder,
Encoder,
Framed,
FramedParts,
FramedRead,
FramedWrite,
BytesCodec,
LinesCodec,
};
}
pub mod io {
//! Asynchronous I/O.
//!
//! This module is the asynchronous version of `std::io`. Primarily, it
//! defines two traits, [`AsyncRead`] and [`AsyncWrite`], which extend the
//! `Read` and `Write` traits of the standard library.
//!
//! # AsyncRead and AsyncWrite
//!
//! [`AsyncRead`] and [`AsyncWrite`] must only be implemented for
//! non-blocking I/O types that integrate with the futures type system. In
//! other words, these types must never block the thread, and instead the
//! current task is notified when the I/O resource is ready.
//!
//! # Standard input and output
//!
//! Tokio provides asynchronous APIs to standard [input], [output], and [error].
//! These APIs are very similar to the ones provided by `std`, but they also
//! implement [`AsyncRead`] and [`AsyncWrite`].
//!
//! Unlike *most* other Tokio APIs, the standard input / output APIs
//! **must** be used from the context of the Tokio runtime as they require
//! Tokio specific features to function.
//!
//! [input]: fn.stdin.html
//! [output]: fn.stdout.html
//! [error]: fn.stderr.html
//!
//! # Utility functions
//!
//! Utilities functions are provided for working with [`AsyncRead`] /
//! [`AsyncWrite`] types. For example, [`copy`] asynchronously copies all
//! data from a source to a destination.
//!
//! # `std` re-exports
//!
//! Additionally, [`Read`], [`Write`], [`Error`], [`ErrorKind`], and
//! [`Result`] are re-exported from `std::io` for ease of use.
//!
//! [`AsyncRead`]: trait.AsyncRead.html
//! [`AsyncWrite`]: trait.AsyncWrite.html
//! [`copy`]: fn.copy.html
//! [`Read`]: trait.Read.html
//! [`Write`]: trait.Write.html
//! [`Error`]: struct.Error.html
//! [`ErrorKind`]: enum.ErrorKind.html
//! [`Result`]: type.Result.html
pub use tokio_io::{
AsyncRead,
AsyncWrite,
};
// standard input, output, and error
pub use tokio_fs::{
stdin,
Stdin,
stdout,
Stdout,
stderr,
Stderr,
};
// Utils
pub use tokio_io::io::{
copy,
Copy,
flush,
Flush,
lines,
Lines,
read_exact,
ReadExact,
read_to_end,
ReadToEnd,
read_until,
ReadUntil,
ReadHalf,
shutdown,
Shutdown,
write_all,
WriteAll,
WriteHalf,
};
// Re-export io::Error so that users don't have to deal
// with conflicts when `use`ing `futures::io` and `std::io`.
pub use ::std::io::{
Error,
ErrorKind,
Result,
Read,
Write,
};
}
pub mod prelude {
//! A "prelude" for users of the `tokio` crate.
//!
//! This prelude is similar to the standard library's prelude in that you'll
//! almost always want to import its entire contents, but unlike the standard
//! library's prelude you'll have to do so manually:
//!
//! ```
//! use tokio::prelude::*;
//! ```
//!
//! The prelude may grow over time as additional items see ubiquitous use.
pub use tokio_io::{
AsyncRead,
AsyncWrite,
};
pub use util::{
FutureExt,
};
pub use ::std::io::{
Read,
Write,
};
pub use futures::{
Future,
future,
Stream,
stream,
Sink,
IntoFuture,
Async,
AsyncSink,
Poll,
task,
};
}
|
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
fn main() {
let file = File::open("input.txt").expect("file not found");
let mut reader = BufReader::new(file);
let mut contents = String::new();
reader.read_to_string(&mut contents).expect("could not read input file");
let mut containers = Vec::new();
for line in contents.lines() {
containers.push(line.parse::<u32>().unwrap());
}
let mut findings = HashMap::new();
let mut result_a = 0;
// Brute-force 2^n combinations.
for i in 0..(1 << containers.len()) {
let mut t = i;
let mut parts = 0;
let mut sum = 0;
// Loop over containers:
for container_size in containers.iter() {
if t % 2 == 1 {
parts += 1;
sum += container_size;
}
t /= 2;
}
if sum == 150 {
result_a += 1;
let count = findings.entry(parts).or_insert(0);
*count += 1;
}
}
let mut min_containers = containers.len();
let mut result_b = 0;
for (combination_size, num_combinations) in findings {
if combination_size < min_containers {
min_containers = combination_size;
result_b = num_combinations;
}
}
println!("A: {}", result_a);
println!("B: {}", result_b);
}
|
extern crate rand;
extern crate base64;
use crate::commons::{AnswerInfo, CommitInfoPayload, CONCAT};
use uuid::Uuid;
use openssl::sha::Sha256;
use rand::Rng;
use rand::distributions::Alphanumeric;
use openssl::rsa::Rsa;
use openssl::pkey::{Public};
use openssl::bn::{BigNum, BigNumContext};
pub fn calculate_commit(amount: u32, k: u32, key: &Rsa<Public>) -> CommitInfoPayload {
let mut answers: Vec<AnswerInfo> = Vec::new();
let mut commits: Vec<String> = Vec::new();
let n = key.n();
let e = key.e();
for _i in 0..k {
let r: BigNum = generate_random_bytes(256);
let alfa: String = generate_random_string(32);
let beta: String = generate_random_string(32);
let u: String = BigNum::from_u32(amount).unwrap().to_string() + CONCAT + &alfa;
let id: Uuid = Uuid::new_v4();
let v: String = id.to_string() + CONCAT + β
let mut hasher: Sha256 = Sha256::new();
let to_hash: String = u.clone() + CONCAT + &v;
hasher.update(&to_hash.as_bytes());
let output_hash = BigNum::from_slice(&hasher.finish()).unwrap();
let mut m: BigNum = BigNum::new().unwrap();
let mut ctx = BigNumContext::new().unwrap();
m.mod_exp(&r, e, n, &mut ctx).unwrap();
let mut m_mod: BigNum = BigNum::new().unwrap();
m_mod.mod_mul(&m, &output_hash, n, &mut ctx).unwrap();
let info: AnswerInfo = AnswerInfo {
blinding: bignum_to_base64(r),
amount: u,
id: v
};
answers.push(info);
commits.push(bignum_to_base64(m_mod));
}
CommitInfoPayload {
answers: answers,
commits: commits,
}
}
pub fn unblind_signature(blinded: &String, random: &String, key: &Rsa<Public>) -> String {
let n = key.n();
let b: BigNum = base64_to_bignum(blinded);
let r: BigNum = base64_to_bignum(random);
let mut ctx = BigNumContext::new().unwrap();
let mut r_inverse: BigNum = BigNum::new().unwrap();
r_inverse.mod_inverse(&r, n, &mut ctx).unwrap();
let mut s: BigNum = BigNum::new().unwrap();
s.mod_mul(&b, &r_inverse, n, &mut ctx).unwrap();
bignum_to_base64(s)
}
fn generate_random_bytes(len: u32) -> BigNum {
let bytes: Vec<u8> = (0..len).map(|_| { rand::random::<u8>() }).collect();
BigNum::from_slice(&bytes).unwrap()
}
fn generate_random_string(len: usize) -> String {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(len)
.collect::<String>()
}
fn base64_to_bignum(base64: &String) -> BigNum {
BigNum::from_slice(&base64::decode(base64).unwrap()).unwrap()
}
fn bignum_to_base64(num: BigNum) -> String {
base64::encode(num.to_vec())
} |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use crate::utils::{are_equal, EvaluationResult};
use core::slice;
use winterfell::{
crypto::Hasher,
math::{fields::f128::BaseElement, FieldElement},
ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
};
/// Function state is set to 6 field elements or 96 bytes; 4 elements are reserved for rate
/// and 2 elements are reserved for capacity.
pub const STATE_WIDTH: usize = 6;
pub const RATE_WIDTH: usize = 4;
/// Two elements (32-bytes) are returned as digest.
const DIGEST_SIZE: usize = 2;
/// The number of rounds is set to 7 to provide 128-bit security level with 40% security margin;
/// computed using algorithm 7 from <https://eprint.iacr.org/2020/1143.pdf>
/// security margin here differs from Rescue Prime specification which suggests 50% security
/// margin (and would require 8 rounds) primarily to make AIR a bit simpler.
pub const NUM_ROUNDS: usize = 7;
/// Minimum cycle length required to describe Rescue permutation.
pub const CYCLE_LENGTH: usize = 8;
// TYPES AND INTERFACES
// ================================================================================================
pub struct Rescue128 {
state: [BaseElement; STATE_WIDTH],
idx: usize,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
pub struct Hash([BaseElement; DIGEST_SIZE]);
// RESCUE128 IMPLEMENTATION
// ================================================================================================
impl Rescue128 {
/// Returns a new hasher with the state initialized to all zeros.
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Rescue128 {
state: [BaseElement::ZERO; STATE_WIDTH],
idx: 0,
}
}
/// Absorbs data into the hasher state.
pub fn update(&mut self, data: &[BaseElement]) {
for &element in data {
self.state[self.idx] += element;
self.idx += 1;
if self.idx % RATE_WIDTH == 0 {
apply_permutation(&mut self.state);
self.idx = 0;
}
}
}
/// Returns hash of the data absorbed into the hasher.
pub fn finalize(mut self) -> Hash {
if self.idx > 0 {
// TODO: apply proper padding
apply_permutation(&mut self.state);
}
Hash([self.state[0], self.state[1]])
}
/// Returns hash of the provided data.
pub fn digest(data: &[BaseElement]) -> Hash {
// initialize state to all zeros
let mut state = [BaseElement::ZERO; STATE_WIDTH];
let mut i = 0;
for &element in data.iter() {
state[i] += element;
i += 1;
if i % RATE_WIDTH == 0 {
apply_permutation(&mut state);
i = 0;
}
}
if i > 0 {
// TODO: apply proper padding
apply_permutation(&mut state);
}
Hash([state[0], state[1]])
}
}
// HASHER IMPLEMENTATION
// ================================================================================================
impl Hasher for Rescue128 {
type Digest = Hash;
fn hash(_bytes: &[u8]) -> Self::Digest {
unimplemented!("not implemented")
}
fn merge(values: &[Self::Digest; 2]) -> Self::Digest {
Self::digest(Hash::hashes_as_elements(values))
}
fn merge_with_int(_seed: Self::Digest, _value: u64) -> Self::Digest {
unimplemented!("not implemented")
}
}
// HASH IMPLEMENTATION
// ================================================================================================
impl Hash {
pub fn new(v1: BaseElement, v2: BaseElement) -> Self {
Hash([v1, v2])
}
#[allow(dead_code)]
#[allow(clippy::wrong_self_convention)]
pub fn to_bytes(&self) -> [u8; 32] {
let mut bytes = [0; 32];
bytes[..16].copy_from_slice(&self.0[0].to_bytes());
bytes[16..].copy_from_slice(&self.0[1].to_bytes());
bytes
}
#[allow(clippy::wrong_self_convention)]
pub fn to_elements(&self) -> [BaseElement; DIGEST_SIZE] {
self.0
}
pub fn hashes_as_elements(hashes: &[Hash]) -> &[BaseElement] {
let p = hashes.as_ptr();
let len = hashes.len() * DIGEST_SIZE;
unsafe { slice::from_raw_parts(p as *const BaseElement, len) }
}
}
impl AsRef<[u8]> for Hash {
fn as_ref(&self) -> &[u8] {
BaseElement::elements_as_bytes(&self.0)
}
}
impl Serializable for Hash {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
target.write(self.0[0]);
target.write(self.0[1]);
}
}
impl Deserializable for Hash {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let v1 = BaseElement::read_from(source)?;
let v2 = BaseElement::read_from(source)?;
Ok(Self([v1, v2]))
}
}
// RESCUE PERMUTATION
// ================================================================================================
/// Applies Rescue-XLIX permutation to the provided state.
pub fn apply_permutation(state: &mut [BaseElement; STATE_WIDTH]) {
// apply round function 7 times; this provides 128-bit security with 40% security margin
for i in 0..NUM_ROUNDS {
apply_round(state, i);
}
}
/// Rescue-XLIX round function;
/// implementation based on algorithm 3 from <https://eprint.iacr.org/2020/1143.pdf>
#[inline(always)]
pub fn apply_round(state: &mut [BaseElement], step: usize) {
// determine which round constants to use
let ark = ARK[step % CYCLE_LENGTH];
// apply first half of Rescue round
apply_sbox(state);
apply_mds(state);
for i in 0..STATE_WIDTH {
state[i] += ark[i];
}
// apply second half of Rescue round
apply_inv_sbox(state);
apply_mds(state);
for i in 0..STATE_WIDTH {
state[i] += ark[STATE_WIDTH + i];
}
}
// CONSTRAINTS
// ================================================================================================
/// when flag = 1, enforces constraints for a single round of Rescue hash functions
pub fn enforce_round<E: FieldElement + From<BaseElement>>(
result: &mut [E],
current: &[E],
next: &[E],
ark: &[E],
flag: E,
) {
// compute the state that should result from applying the first half of Rescue round
// to the current state of the computation
let mut step1 = [E::ZERO; STATE_WIDTH];
step1.copy_from_slice(current);
apply_sbox(&mut step1);
apply_mds(&mut step1);
for i in 0..STATE_WIDTH {
step1[i] += ark[i];
}
// compute the state that should result from applying the inverse for the second
// half for Rescue round to the next step of the computation
let mut step2 = [E::ZERO; STATE_WIDTH];
step2.copy_from_slice(next);
for i in 0..STATE_WIDTH {
step2[i] -= ark[STATE_WIDTH + i];
}
apply_inv_mds(&mut step2);
apply_sbox(&mut step2);
// make sure that the results are equal
for i in 0..STATE_WIDTH {
result.agg_constraint(i, flag, are_equal(step2[i], step1[i]));
}
}
// ROUND CONSTANTS
// ================================================================================================
/// Returns Rescue round constants arranged in column-major form.
pub fn get_round_constants() -> Vec<Vec<BaseElement>> {
let mut constants = Vec::new();
for _ in 0..(STATE_WIDTH * 2) {
constants.push(vec![BaseElement::ZERO; CYCLE_LENGTH]);
}
#[allow(clippy::needless_range_loop)]
for i in 0..CYCLE_LENGTH {
for j in 0..(STATE_WIDTH * 2) {
constants[j][i] = ARK[i][j];
}
}
constants
}
// HELPER FUNCTIONS
// ================================================================================================
#[inline(always)]
#[allow(clippy::needless_range_loop)]
fn apply_sbox<E: FieldElement>(state: &mut [E]) {
for i in 0..STATE_WIDTH {
state[i] = state[i].exp(ALPHA.into());
}
}
#[inline(always)]
#[allow(clippy::needless_range_loop)]
fn apply_inv_sbox(state: &mut [BaseElement]) {
for i in 0..STATE_WIDTH {
state[i] = state[i].exp(INV_ALPHA);
}
}
#[inline(always)]
#[allow(clippy::needless_range_loop)]
fn apply_mds<E: FieldElement + From<BaseElement>>(state: &mut [E]) {
let mut result = [E::ZERO; STATE_WIDTH];
let mut temp = [E::ZERO; STATE_WIDTH];
for i in 0..STATE_WIDTH {
for j in 0..STATE_WIDTH {
temp[j] = E::from(MDS[i * STATE_WIDTH + j]) * state[j];
}
for j in 0..STATE_WIDTH {
result[i] += temp[j];
}
}
state.copy_from_slice(&result);
}
#[inline(always)]
#[allow(clippy::needless_range_loop)]
fn apply_inv_mds<E: FieldElement + From<BaseElement>>(state: &mut [E]) {
let mut result = [E::ZERO; STATE_WIDTH];
let mut temp = [E::ZERO; STATE_WIDTH];
for i in 0..STATE_WIDTH {
for j in 0..STATE_WIDTH {
temp[j] = E::from(INV_MDS[i * STATE_WIDTH + j]) * state[j];
}
for j in 0..STATE_WIDTH {
result[i] += temp[j];
}
}
state.copy_from_slice(&result);
}
// CONSTANTS
// ================================================================================================
/// S-Box and Inverse S-Box powers;
/// computed using algorithm 6 from <https://eprint.iacr.org/2020/1143.pdf>
const ALPHA: u32 = 5;
const INV_ALPHA: u128 = 272225893536750770770699646362995969229;
/// Rescue MDS matrix
/// Computed using algorithm 4 from <https://eprint.iacr.org/2020/1143.pdf>
const MDS: [BaseElement; STATE_WIDTH * STATE_WIDTH] = [
BaseElement::new(340282366920938463463374557953730612630),
BaseElement::new(21493836),
BaseElement::new(340282366920938463463374557953736934518),
BaseElement::new(914760),
BaseElement::new(340282366920938463463374557953744928504),
BaseElement::new(364),
BaseElement::new(340282366920938463463374557948521959389),
BaseElement::new(7809407397),
BaseElement::new(340282366920938463463374557950844620457),
BaseElement::new(324945621),
BaseElement::new(340282366920938463463374557953733852285),
BaseElement::new(99463),
BaseElement::new(340282366920938463463374556526559624596),
BaseElement::new(2132618407920),
BaseElement::new(340282366920938463463374557163162978137),
BaseElement::new(88084432800),
BaseElement::new(340282366920938463463374557950784345879),
BaseElement::new(25095280),
BaseElement::new(340282366920938463463374197863906102577),
BaseElement::new(537966647357139),
BaseElement::new(340282366920938463463374358646073999137),
BaseElement::new(22165576349400),
BaseElement::new(340282366920938463463374557212857010097),
BaseElement::new(6174066262),
BaseElement::new(340282366920938463463285966851139685903),
BaseElement::new(132344277849702072),
BaseElement::new(340282366920938463463325536573199985698),
BaseElement::new(5448481182864720),
BaseElement::new(340282366920938463463374376171390478291),
BaseElement::new(1506472167928),
BaseElement::new(340282366920938463441758328918057706841),
BaseElement::new(32291274613403616174),
BaseElement::new(340282366920938463451414421516665416977),
BaseElement::new(1329039099788841441),
BaseElement::new(340282366920938463463330243139804660633),
BaseElement::new(366573514642546),
];
const INV_MDS: [BaseElement; STATE_WIDTH * STATE_WIDTH] = [
BaseElement::new(133202720344903784697302507504318451498),
BaseElement::new(9109562341901685402869515497167051415),
BaseElement::new(187114562320006661061623258692072377978),
BaseElement::new(217977550980311337650875125151512141987),
BaseElement::new(274535269264332978809051716514493438195),
BaseElement::new(198907435511358942768401550501671423539),
BaseElement::new(107211340690419935719675873160429442610),
BaseElement::new(93035459208639798096019355873148696692),
BaseElement::new(34612840942819361370119536876515785819),
BaseElement::new(28124271099756519590702162721340502811),
BaseElement::new(220883180661145883341796932300840696133),
BaseElement::new(196697641239095428808435254975214799010),
BaseElement::new(48198755643822249649260269442324041679),
BaseElement::new(64419499747985404280993270855996080557),
BaseElement::new(280207800449835933431237404716657540948),
BaseElement::new(61755931245950637038951462642746253929),
BaseElement::new(206737575380416523686108693210925354496),
BaseElement::new(19245171373866178840198015038840651466),
BaseElement::new(133290479635000282395391929030461304726),
BaseElement::new(256035933367497105928763702353648605000),
BaseElement::new(97077987470620839632334052346344687963),
BaseElement::new(144638736603246051821344039641662500876),
BaseElement::new(323753713558453221824969500168839490204),
BaseElement::new(66050250127997888787320450320278295843),
BaseElement::new(107416947271017171483976049725783774207),
BaseElement::new(29799978553141132526384006297614595309),
BaseElement::new(112991183841517485419461727429810868869),
BaseElement::new(27096959906733835564333321118624482460),
BaseElement::new(197262955506413467422574209301409294301),
BaseElement::new(205996708763053834510019802034246907929),
BaseElement::new(114827794598835201662537916675749328586),
BaseElement::new(22232541983454090535685600849896663137),
BaseElement::new(84718265936029339288536427868493390350),
BaseElement::new(176534200716138685131361645691447579493),
BaseElement::new(304590074876810806644622682832255680729),
BaseElement::new(317944222651547267127379399943392242317),
];
/// Rescue round constants;
/// computed using algorithm 5 from <https://eprint.iacr.org/2020/1143.pdf>
pub const ARK: [[BaseElement; STATE_WIDTH * 2]; CYCLE_LENGTH] = [
[
BaseElement::new(232350694689151131917165570858777669544),
BaseElement::new(297138716840883070166239111380460167036),
BaseElement::new(262280230220923724082396709497064092149),
BaseElement::new(172158049344191113832187131208632037738),
BaseElement::new(49064466045797039562408393043269857959),
BaseElement::new(310779117230843293557874990285120450495),
BaseElement::new(256706820970445617734149759518940865107),
BaseElement::new(79123538858040670180278455836284339197),
BaseElement::new(78750303544367952484014721485273250812),
BaseElement::new(288861383492149579433903883762711410179),
BaseElement::new(59801749333456280387477464033868461625),
BaseElement::new(21443300235508431203706748477819269958),
],
[
BaseElement::new(58568963110264836729315799795504150465),
BaseElement::new(330748576252425315826992430477036516321),
BaseElement::new(186265990460580587588657915966473647991),
BaseElement::new(33474186560709631768594728335471560699),
BaseElement::new(158848462530608412921046130349797355353),
BaseElement::new(103951280788776493556470655637893338265),
BaseElement::new(143328281743837680325887693977200434046),
BaseElement::new(84141533915622931968833899936597847300),
BaseElement::new(8289043147167319381038668861607412243),
BaseElement::new(182690551456641207603161012621368395791),
BaseElement::new(189966993584382842241685332212477020587),
BaseElement::new(32137923394454105763485467845755642950),
],
[
BaseElement::new(37831789571282423629213813309051107559),
BaseElement::new(128553631204082467137622394929811125529),
BaseElement::new(267986778741944677472811189878493395927),
BaseElement::new(16604948458564067211433039503683613987),
BaseElement::new(336102510949899388907937615764984494068),
BaseElement::new(269515689098362827313089599343791905108),
BaseElement::new(299424679105391259942771484229152481303),
BaseElement::new(204910193356347483970850685012209050540),
BaseElement::new(297547986861132400067173315704469727918),
BaseElement::new(90994669428470088728996184833134573519),
BaseElement::new(194832530917116381832912394976136685925),
BaseElement::new(3544879195102182108390682435201981399),
],
[
BaseElement::new(339480205126523778084089852053600037139),
BaseElement::new(7584482258985997923597941079175892345),
BaseElement::new(293411952222390873312400094181647328549),
BaseElement::new(199529004542042321671242096609546451065),
BaseElement::new(67129123347758775813781826519244753478),
BaseElement::new(262358775581253675478636059962684988488),
BaseElement::new(214578730175648891816936630380713062555),
BaseElement::new(298888476681892954783673663609236117055),
BaseElement::new(28713802418311531156758766332916445632),
BaseElement::new(1440134829402109711440873134882900954),
BaseElement::new(136568912729847804743104940208565395935),
BaseElement::new(282333114631262903665175684297593586626),
],
[
BaseElement::new(179980515973143677823617972256218090691),
BaseElement::new(262324617228293661450608983002445445851),
BaseElement::new(101457408539557988072857167265007764003),
BaseElement::new(135015365700146217343913438445165565670),
BaseElement::new(160037359781136723784361845515476884821),
BaseElement::new(182530253870899012049936279038476084254),
BaseElement::new(135879876810809726132885131537021449499),
BaseElement::new(232021530889024386996643355214152586646),
BaseElement::new(145764181560102807472161589832442506602),
BaseElement::new(30096323905520593555387863391076216460),
BaseElement::new(26964230850883304384940372063347292502),
BaseElement::new(248723932438838238159920468579438468564),
],
[
BaseElement::new(294269904099379916907622037481357861347),
BaseElement::new(68547751515194812125080398554316505804),
BaseElement::new(206967528806115588933607920597265054243),
BaseElement::new(218563991130423186053843420486943196637),
BaseElement::new(271753381570791699387473121354016967661),
BaseElement::new(280821616954361601859332610476339898658),
BaseElement::new(10004341245328361103806488533574675264),
BaseElement::new(102737972201824925757345477497905200949),
BaseElement::new(181579715086871199454198713448655357907),
BaseElement::new(334443686013848360201749831728546200670),
BaseElement::new(43930702221243327593116820380585481596),
BaseElement::new(16744004758332429127464852702179311517),
],
[
BaseElement::new(310201738135125726809998762242791360596),
BaseElement::new(155126893730515639579436939964032992002),
BaseElement::new(61238650483248463229462616021804212788),
BaseElement::new(6693212157784826508674787451860949238),
BaseElement::new(197651057967963974372308220503477603713),
BaseElement::new(174221476673212934077040088950046690415),
BaseElement::new(287511813733819668564695051918836002922),
BaseElement::new(304531189544765525159398110881793396421),
BaseElement::new(276777415462914862553995344360435589651),
BaseElement::new(241036817921529641113885285343669990717),
BaseElement::new(320958231309550951576801366383624382828),
BaseElement::new(242260690344880997681123448650535822378),
],
[
BaseElement::new(201589105262974747061391276271612166799),
BaseElement::new(21009766855942890883171267876432289297),
BaseElement::new(303226336248222109074995022589884483065),
BaseElement::new(105515432862530091605210357969101266504),
BaseElement::new(235097661610089805414814372959229370626),
BaseElement::new(210361497167001742816223425802317150493),
BaseElement::new(218546747003262668455051521918398855294),
BaseElement::new(280724473534270362895764829061545243190),
BaseElement::new(179926408118748249708833901850481685351),
BaseElement::new(168859451670725335987760025077648496937),
BaseElement::new(127174659756870191527945451601624140498),
BaseElement::new(290826558340641225374953827677533570165),
],
];
|
// Copyright 2014 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.
/// Short circuiting evaluation on Err
///
/// `libstd` contains a more general `try!` macro that uses `From<E>`.
#[macro_export]
macro_rules! try {
($e:expr) => ({
use $crate::result::Result::{Ok, Err};
match $e {
Ok(e) => e,
Err(e) => return Err(e),
}
})
}
/// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
/// See `std::fmt` for more information.
///
/// # Examples
///
/// ```
/// # #![allow(unused_must_use)]
/// use std::io::Write;
///
/// let mut w = Vec::new();
/// write!(&mut w, "test");
/// write!(&mut w, "formatted {}", "arguments");
/// ```
#[macro_export]
macro_rules! write {
($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
}
/// Equivalent to the `write!` macro, except that a newline is appended after
/// the message is written.
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! writeln {
($dst:expr, $fmt:expr) => (
write!($dst, concat!($fmt, "\n"))
);
($dst:expr, $fmt:expr, $($arg:tt)*) => (
write!($dst, concat!($fmt, "\n"), $($arg)*)
);
}
|
#![allow(dead_code)]
//use ::fib;
pub mod fib;
pub mod matching;
pub mod mapping;
pub mod nest;
fn main() {
case1();
case2();
case3();
mapping::test_map2();
nest::apple()
}
fn case1() {
fn call_function_on(f: impl Fn(i64), x: i64) {
f(x)
}
// This works
call_function_on(|x| println!("{}", x), 5);
// This also works
let func = |x| println!("{}", x);
call_function_on(func, 5);
}
fn case2() {
fn call_function_on(f: impl Fn(Vec<i64>), x: Vec<i64>) {
f(x)
}
let xs: Vec<i64> = vec![1, 2];
// This works
call_function_on(|vs| println!("{:?}", vs), xs);
// This works
let xs: Vec<i64> = vec![1, 2];
let func = |vs| println!("{:?}", vs);
call_function_on(func, xs)
}
fn case3() {
fn call_function_on<'a>(f: impl Fn(&'a Vec<i64>), x: &'a Vec<i64>) {
f(x)
}
let xs: Vec<i64> = vec![1, 2];
// This works
call_function_on(|vs| println!("{:?}", &vs), &xs);
// This works
//let func = |&vs| println!("{:?}", vs);
//call_function_on(func, &xs)
}
//return_break_for::scope()
//return_break_for::break_outer_loop()
//return_break_for::return_from_loop();
//return_break_for::for_and_iterators()
//fib::go()
//matching::main();
//mapping::vec();
//mapping::array();
//mapping::for_array();
//mapping::test_map();
|
use std::fs;
use std::collections::HashMap;
#[derive(Debug)]
struct Object {
name: String,
parent: Option<String>,
}
impl Object {
fn new(name: &str) -> Self {
Object {
name: name.to_owned(),
parent: None,
}
}
}
fn parse_orbits(input: &str) -> HashMap<String, Object> {
let mut objects = HashMap::new();
for rel in input.lines() {
let mut pair = rel.split(')');
let name_a = pair.next().unwrap().to_owned();
let name_b = pair.next().unwrap().to_owned();
objects.entry(name_a.clone()).or_insert(Object::new(&name_a));
let b = objects.entry(name_b.clone()).or_insert(Object::new(&name_b));
b.parent.replace(name_a.clone());
}
objects
}
fn main() {
let objects = parse_orbits(&fs::read_to_string("input").unwrap());
part1(&objects);
part2(&objects);
}
fn part1(objects: &HashMap<String, Object>) {
let mut count = 0;
for object in objects.values() {
let mut current = object;
while let Some(ref parent_name) = current.parent {
count += 1;
current = objects.get(parent_name).unwrap();
}
}
println!("{}", count);
}
fn part2(objects: &HashMap<String, Object>) {
// Find trail from santa to COM
let mut santa_parents = Vec::new();
let mut santa = objects.get(&"SAN".to_owned()).unwrap();
while let Some(ref parent_name) = santa.parent {
santa_parents.push(parent_name.clone());
santa = objects.get(parent_name).unwrap();
}
// Move towards COM until a common parent with santa is found
let mut you = objects.get(&"YOU".to_owned()).unwrap();
let mut transfers = 0;
while let Some(ref parent_name) = you.parent {
let common_parent = santa_parents
.iter()
.enumerate()
.find(|(_, name)| name == &parent_name);
if let Some((i, _)) = common_parent {
transfers += i;
break;
}
transfers += 1;
you = objects.get(parent_name).unwrap();
}
println!("{}", transfers);
} |
#[doc = "Register `TIM4_SMCR` reader"]
pub type R = crate::R<TIM4_SMCR_SPEC>;
#[doc = "Register `TIM4_SMCR` writer"]
pub type W = crate::W<TIM4_SMCR_SPEC>;
#[doc = "Field `SMS1` reader - Slave mode selection When external signals are selected the active edge of the trigger signal (tim_trgi) is linked to the polarity selected on the external input (see Input Control register and Control Register description. Note: The gated mode must not be used if tim_ti1f_ed is selected as the trigger input (TS=00100). Indeed, tim_ti1f_ed outputs 1 pulse for each transition on tim_ti1f, whereas the gated mode checks the level of the trigger signal. Note: The clock of the slave peripherals (timer, ADC, ...) receiving the tim_trgo signal must be enabled prior to receive events from the master timer, and the clock frequency (prescaler) must not be changed on-the-fly while triggers are received from the master timer."]
pub type SMS1_R = crate::FieldReader;
#[doc = "Field `SMS1` writer - Slave mode selection When external signals are selected the active edge of the trigger signal (tim_trgi) is linked to the polarity selected on the external input (see Input Control register and Control Register description. Note: The gated mode must not be used if tim_ti1f_ed is selected as the trigger input (TS=00100). Indeed, tim_ti1f_ed outputs 1 pulse for each transition on tim_ti1f, whereas the gated mode checks the level of the trigger signal. Note: The clock of the slave peripherals (timer, ADC, ...) receiving the tim_trgo signal must be enabled prior to receive events from the master timer, and the clock frequency (prescaler) must not be changed on-the-fly while triggers are received from the master timer."]
pub type SMS1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `OCCS` reader - OCREF clear selection This bit is used to select the OCREF clear source Note: If the OCREF clear selection feature is not supported, this bit is reserved and forced by hardware to ‘0’. ."]
pub type OCCS_R = crate::BitReader;
#[doc = "Field `OCCS` writer - OCREF clear selection This bit is used to select the OCREF clear source Note: If the OCREF clear selection feature is not supported, this bit is reserved and forced by hardware to ‘0’. ."]
pub type OCCS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TS1` reader - Trigger selection (see bits 21:20 for TS\\[4:3\\]) This bit-field selects the trigger input to be used to synchronize the counter. Others: Reserved See for product specific implementation details. Note: These bits must be changed only when they are not used (e.g. when SMS=000) to avoid wrong edge detections at the transition."]
pub type TS1_R = crate::FieldReader;
#[doc = "Field `TS1` writer - Trigger selection (see bits 21:20 for TS\\[4:3\\]) This bit-field selects the trigger input to be used to synchronize the counter. Others: Reserved See for product specific implementation details. Note: These bits must be changed only when they are not used (e.g. when SMS=000) to avoid wrong edge detections at the transition."]
pub type TS1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `MSM` reader - Master/Slave mode"]
pub type MSM_R = crate::BitReader;
#[doc = "Field `MSM` writer - Master/Slave mode"]
pub type MSM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ETF` reader - External trigger filter This bit-field then defines the frequency used to sample tim_etrp signal and the length of the digital filter applied to tim_etrp. The digital filter is made of an event counter in which N consecutive events are needed to validate a transition on the output:"]
pub type ETF_R = crate::FieldReader;
#[doc = "Field `ETF` writer - External trigger filter This bit-field then defines the frequency used to sample tim_etrp signal and the length of the digital filter applied to tim_etrp. The digital filter is made of an event counter in which N consecutive events are needed to validate a transition on the output:"]
pub type ETF_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
#[doc = "Field `ETPS` reader - External trigger prescaler External trigger signal tim_etrp frequency must be at most 1/4 of tim_ker_ck frequency. A prescaler can be enabled to reduce tim_etrp frequency. It is useful when inputting fast external clocks on tim_etr_in."]
pub type ETPS_R = crate::FieldReader;
#[doc = "Field `ETPS` writer - External trigger prescaler External trigger signal tim_etrp frequency must be at most 1/4 of tim_ker_ck frequency. A prescaler can be enabled to reduce tim_etrp frequency. It is useful when inputting fast external clocks on tim_etr_in."]
pub type ETPS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `ECE` reader - External clock enable This bit enables External clock mode 2. Note: Setting the ECE bit has the same effect as selecting external clock mode 1 with tim_trgi connected to tim_etrf (SMS=111 and TS=00111). It is possible to simultaneously use external clock mode 2 with the following slave modes: reset mode, gated mode and trigger mode. Nevertheless, tim_trgi must not be connected to tim_etrf in this case (TS bits must not be 00111). If external clock mode 1 and external clock mode 2 are enabled at the same time, the external clock input is tim_etrf."]
pub type ECE_R = crate::BitReader;
#[doc = "Field `ECE` writer - External clock enable This bit enables External clock mode 2. Note: Setting the ECE bit has the same effect as selecting external clock mode 1 with tim_trgi connected to tim_etrf (SMS=111 and TS=00111). It is possible to simultaneously use external clock mode 2 with the following slave modes: reset mode, gated mode and trigger mode. Nevertheless, tim_trgi must not be connected to tim_etrf in this case (TS bits must not be 00111). If external clock mode 1 and external clock mode 2 are enabled at the same time, the external clock input is tim_etrf."]
pub type ECE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ETP` reader - External trigger polarity This bit selects whether tim_etr_in or tim_etr_in is used for trigger operations"]
pub type ETP_R = crate::BitReader;
#[doc = "Field `ETP` writer - External trigger polarity This bit selects whether tim_etr_in or tim_etr_in is used for trigger operations"]
pub type ETP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SMS2` reader - Slave mode selection When external signals are selected the active edge of the trigger signal (tim_trgi) is linked to the polarity selected on the external input (see Input Control register and Control Register description. Note: The gated mode must not be used if tim_ti1f_ed is selected as the trigger input (TS=00100). Indeed, tim_ti1f_ed outputs 1 pulse for each transition on tim_ti1f, whereas the gated mode checks the level of the trigger signal. Note: The clock of the slave peripherals (timer, ADC, ...) receiving the tim_trgo signal must be enabled prior to receive events from the master timer, and the clock frequency (prescaler) must not be changed on-the-fly while triggers are received from the master timer."]
pub type SMS2_R = crate::BitReader;
#[doc = "Field `SMS2` writer - Slave mode selection When external signals are selected the active edge of the trigger signal (tim_trgi) is linked to the polarity selected on the external input (see Input Control register and Control Register description. Note: The gated mode must not be used if tim_ti1f_ed is selected as the trigger input (TS=00100). Indeed, tim_ti1f_ed outputs 1 pulse for each transition on tim_ti1f, whereas the gated mode checks the level of the trigger signal. Note: The clock of the slave peripherals (timer, ADC, ...) receiving the tim_trgo signal must be enabled prior to receive events from the master timer, and the clock frequency (prescaler) must not be changed on-the-fly while triggers are received from the master timer."]
pub type SMS2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TS2` reader - Trigger selection (see bits 21:20 for TS\\[4:3\\]) This bit-field selects the trigger input to be used to synchronize the counter. Others: Reserved See for product specific implementation details. Note: These bits must be changed only when they are not used (e.g. when SMS=000) to avoid wrong edge detections at the transition."]
pub type TS2_R = crate::FieldReader;
#[doc = "Field `TS2` writer - Trigger selection (see bits 21:20 for TS\\[4:3\\]) This bit-field selects the trigger input to be used to synchronize the counter. Others: Reserved See for product specific implementation details. Note: These bits must be changed only when they are not used (e.g. when SMS=000) to avoid wrong edge detections at the transition."]
pub type TS2_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `SMSPE` reader - SMS preload enable This bit selects whether the SMS\\[3:0\\]
bitfield is preloaded"]
pub type SMSPE_R = crate::BitReader;
#[doc = "Field `SMSPE` writer - SMS preload enable This bit selects whether the SMS\\[3:0\\]
bitfield is preloaded"]
pub type SMSPE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SMSPS` reader - SMS preload source This bit selects whether the events that triggers the SMS\\[3:0\\]
bitfield transfer from preload to active"]
pub type SMSPS_R = crate::BitReader;
#[doc = "Field `SMSPS` writer - SMS preload source This bit selects whether the events that triggers the SMS\\[3:0\\]
bitfield transfer from preload to active"]
pub type SMSPS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bits 0:2 - Slave mode selection When external signals are selected the active edge of the trigger signal (tim_trgi) is linked to the polarity selected on the external input (see Input Control register and Control Register description. Note: The gated mode must not be used if tim_ti1f_ed is selected as the trigger input (TS=00100). Indeed, tim_ti1f_ed outputs 1 pulse for each transition on tim_ti1f, whereas the gated mode checks the level of the trigger signal. Note: The clock of the slave peripherals (timer, ADC, ...) receiving the tim_trgo signal must be enabled prior to receive events from the master timer, and the clock frequency (prescaler) must not be changed on-the-fly while triggers are received from the master timer."]
#[inline(always)]
pub fn sms1(&self) -> SMS1_R {
SMS1_R::new((self.bits & 7) as u8)
}
#[doc = "Bit 3 - OCREF clear selection This bit is used to select the OCREF clear source Note: If the OCREF clear selection feature is not supported, this bit is reserved and forced by hardware to ‘0’. ."]
#[inline(always)]
pub fn occs(&self) -> OCCS_R {
OCCS_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bits 4:6 - Trigger selection (see bits 21:20 for TS\\[4:3\\]) This bit-field selects the trigger input to be used to synchronize the counter. Others: Reserved See for product specific implementation details. Note: These bits must be changed only when they are not used (e.g. when SMS=000) to avoid wrong edge detections at the transition."]
#[inline(always)]
pub fn ts1(&self) -> TS1_R {
TS1_R::new(((self.bits >> 4) & 7) as u8)
}
#[doc = "Bit 7 - Master/Slave mode"]
#[inline(always)]
pub fn msm(&self) -> MSM_R {
MSM_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bits 8:11 - External trigger filter This bit-field then defines the frequency used to sample tim_etrp signal and the length of the digital filter applied to tim_etrp. The digital filter is made of an event counter in which N consecutive events are needed to validate a transition on the output:"]
#[inline(always)]
pub fn etf(&self) -> ETF_R {
ETF_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 12:13 - External trigger prescaler External trigger signal tim_etrp frequency must be at most 1/4 of tim_ker_ck frequency. A prescaler can be enabled to reduce tim_etrp frequency. It is useful when inputting fast external clocks on tim_etr_in."]
#[inline(always)]
pub fn etps(&self) -> ETPS_R {
ETPS_R::new(((self.bits >> 12) & 3) as u8)
}
#[doc = "Bit 14 - External clock enable This bit enables External clock mode 2. Note: Setting the ECE bit has the same effect as selecting external clock mode 1 with tim_trgi connected to tim_etrf (SMS=111 and TS=00111). It is possible to simultaneously use external clock mode 2 with the following slave modes: reset mode, gated mode and trigger mode. Nevertheless, tim_trgi must not be connected to tim_etrf in this case (TS bits must not be 00111). If external clock mode 1 and external clock mode 2 are enabled at the same time, the external clock input is tim_etrf."]
#[inline(always)]
pub fn ece(&self) -> ECE_R {
ECE_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - External trigger polarity This bit selects whether tim_etr_in or tim_etr_in is used for trigger operations"]
#[inline(always)]
pub fn etp(&self) -> ETP_R {
ETP_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - Slave mode selection When external signals are selected the active edge of the trigger signal (tim_trgi) is linked to the polarity selected on the external input (see Input Control register and Control Register description. Note: The gated mode must not be used if tim_ti1f_ed is selected as the trigger input (TS=00100). Indeed, tim_ti1f_ed outputs 1 pulse for each transition on tim_ti1f, whereas the gated mode checks the level of the trigger signal. Note: The clock of the slave peripherals (timer, ADC, ...) receiving the tim_trgo signal must be enabled prior to receive events from the master timer, and the clock frequency (prescaler) must not be changed on-the-fly while triggers are received from the master timer."]
#[inline(always)]
pub fn sms2(&self) -> SMS2_R {
SMS2_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bits 20:21 - Trigger selection (see bits 21:20 for TS\\[4:3\\]) This bit-field selects the trigger input to be used to synchronize the counter. Others: Reserved See for product specific implementation details. Note: These bits must be changed only when they are not used (e.g. when SMS=000) to avoid wrong edge detections at the transition."]
#[inline(always)]
pub fn ts2(&self) -> TS2_R {
TS2_R::new(((self.bits >> 20) & 3) as u8)
}
#[doc = "Bit 24 - SMS preload enable This bit selects whether the SMS\\[3:0\\]
bitfield is preloaded"]
#[inline(always)]
pub fn smspe(&self) -> SMSPE_R {
SMSPE_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - SMS preload source This bit selects whether the events that triggers the SMS\\[3:0\\]
bitfield transfer from preload to active"]
#[inline(always)]
pub fn smsps(&self) -> SMSPS_R {
SMSPS_R::new(((self.bits >> 25) & 1) != 0)
}
}
impl W {
#[doc = "Bits 0:2 - Slave mode selection When external signals are selected the active edge of the trigger signal (tim_trgi) is linked to the polarity selected on the external input (see Input Control register and Control Register description. Note: The gated mode must not be used if tim_ti1f_ed is selected as the trigger input (TS=00100). Indeed, tim_ti1f_ed outputs 1 pulse for each transition on tim_ti1f, whereas the gated mode checks the level of the trigger signal. Note: The clock of the slave peripherals (timer, ADC, ...) receiving the tim_trgo signal must be enabled prior to receive events from the master timer, and the clock frequency (prescaler) must not be changed on-the-fly while triggers are received from the master timer."]
#[inline(always)]
#[must_use]
pub fn sms1(&mut self) -> SMS1_W<TIM4_SMCR_SPEC, 0> {
SMS1_W::new(self)
}
#[doc = "Bit 3 - OCREF clear selection This bit is used to select the OCREF clear source Note: If the OCREF clear selection feature is not supported, this bit is reserved and forced by hardware to ‘0’. ."]
#[inline(always)]
#[must_use]
pub fn occs(&mut self) -> OCCS_W<TIM4_SMCR_SPEC, 3> {
OCCS_W::new(self)
}
#[doc = "Bits 4:6 - Trigger selection (see bits 21:20 for TS\\[4:3\\]) This bit-field selects the trigger input to be used to synchronize the counter. Others: Reserved See for product specific implementation details. Note: These bits must be changed only when they are not used (e.g. when SMS=000) to avoid wrong edge detections at the transition."]
#[inline(always)]
#[must_use]
pub fn ts1(&mut self) -> TS1_W<TIM4_SMCR_SPEC, 4> {
TS1_W::new(self)
}
#[doc = "Bit 7 - Master/Slave mode"]
#[inline(always)]
#[must_use]
pub fn msm(&mut self) -> MSM_W<TIM4_SMCR_SPEC, 7> {
MSM_W::new(self)
}
#[doc = "Bits 8:11 - External trigger filter This bit-field then defines the frequency used to sample tim_etrp signal and the length of the digital filter applied to tim_etrp. The digital filter is made of an event counter in which N consecutive events are needed to validate a transition on the output:"]
#[inline(always)]
#[must_use]
pub fn etf(&mut self) -> ETF_W<TIM4_SMCR_SPEC, 8> {
ETF_W::new(self)
}
#[doc = "Bits 12:13 - External trigger prescaler External trigger signal tim_etrp frequency must be at most 1/4 of tim_ker_ck frequency. A prescaler can be enabled to reduce tim_etrp frequency. It is useful when inputting fast external clocks on tim_etr_in."]
#[inline(always)]
#[must_use]
pub fn etps(&mut self) -> ETPS_W<TIM4_SMCR_SPEC, 12> {
ETPS_W::new(self)
}
#[doc = "Bit 14 - External clock enable This bit enables External clock mode 2. Note: Setting the ECE bit has the same effect as selecting external clock mode 1 with tim_trgi connected to tim_etrf (SMS=111 and TS=00111). It is possible to simultaneously use external clock mode 2 with the following slave modes: reset mode, gated mode and trigger mode. Nevertheless, tim_trgi must not be connected to tim_etrf in this case (TS bits must not be 00111). If external clock mode 1 and external clock mode 2 are enabled at the same time, the external clock input is tim_etrf."]
#[inline(always)]
#[must_use]
pub fn ece(&mut self) -> ECE_W<TIM4_SMCR_SPEC, 14> {
ECE_W::new(self)
}
#[doc = "Bit 15 - External trigger polarity This bit selects whether tim_etr_in or tim_etr_in is used for trigger operations"]
#[inline(always)]
#[must_use]
pub fn etp(&mut self) -> ETP_W<TIM4_SMCR_SPEC, 15> {
ETP_W::new(self)
}
#[doc = "Bit 16 - Slave mode selection When external signals are selected the active edge of the trigger signal (tim_trgi) is linked to the polarity selected on the external input (see Input Control register and Control Register description. Note: The gated mode must not be used if tim_ti1f_ed is selected as the trigger input (TS=00100). Indeed, tim_ti1f_ed outputs 1 pulse for each transition on tim_ti1f, whereas the gated mode checks the level of the trigger signal. Note: The clock of the slave peripherals (timer, ADC, ...) receiving the tim_trgo signal must be enabled prior to receive events from the master timer, and the clock frequency (prescaler) must not be changed on-the-fly while triggers are received from the master timer."]
#[inline(always)]
#[must_use]
pub fn sms2(&mut self) -> SMS2_W<TIM4_SMCR_SPEC, 16> {
SMS2_W::new(self)
}
#[doc = "Bits 20:21 - Trigger selection (see bits 21:20 for TS\\[4:3\\]) This bit-field selects the trigger input to be used to synchronize the counter. Others: Reserved See for product specific implementation details. Note: These bits must be changed only when they are not used (e.g. when SMS=000) to avoid wrong edge detections at the transition."]
#[inline(always)]
#[must_use]
pub fn ts2(&mut self) -> TS2_W<TIM4_SMCR_SPEC, 20> {
TS2_W::new(self)
}
#[doc = "Bit 24 - SMS preload enable This bit selects whether the SMS\\[3:0\\]
bitfield is preloaded"]
#[inline(always)]
#[must_use]
pub fn smspe(&mut self) -> SMSPE_W<TIM4_SMCR_SPEC, 24> {
SMSPE_W::new(self)
}
#[doc = "Bit 25 - SMS preload source This bit selects whether the events that triggers the SMS\\[3:0\\]
bitfield transfer from preload to active"]
#[inline(always)]
#[must_use]
pub fn smsps(&mut self) -> SMSPS_W<TIM4_SMCR_SPEC, 25> {
SMSPS_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "TIM4 slave mode control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_smcr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_smcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct TIM4_SMCR_SPEC;
impl crate::RegisterSpec for TIM4_SMCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`tim4_smcr::R`](R) reader structure"]
impl crate::Readable for TIM4_SMCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`tim4_smcr::W`](W) writer structure"]
impl crate::Writable for TIM4_SMCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets TIM4_SMCR to value 0"]
impl crate::Resettable for TIM4_SMCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[doc = "Register `DMACCARxBR` reader"]
pub type R = crate::R<DMACCARX_BR_SPEC>;
#[doc = "Register `DMACCARxBR` writer"]
pub type W = crate::W<DMACCARX_BR_SPEC>;
#[doc = "Field `CURRBUFAPTR` reader - Application Receive Buffer Address Pointer"]
pub type CURRBUFAPTR_R = crate::FieldReader<u32>;
#[doc = "Field `CURRBUFAPTR` writer - Application Receive Buffer Address Pointer"]
pub type CURRBUFAPTR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>;
impl R {
#[doc = "Bits 0:31 - Application Receive Buffer Address Pointer"]
#[inline(always)]
pub fn currbufaptr(&self) -> CURRBUFAPTR_R {
CURRBUFAPTR_R::new(self.bits)
}
}
impl W {
#[doc = "Bits 0:31 - Application Receive Buffer Address Pointer"]
#[inline(always)]
#[must_use]
pub fn currbufaptr(&mut self) -> CURRBUFAPTR_W<DMACCARX_BR_SPEC, 0> {
CURRBUFAPTR_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Channel current application receive buffer register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dmaccarx_br::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`dmaccarx_br::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DMACCARX_BR_SPEC;
impl crate::RegisterSpec for DMACCARX_BR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dmaccarx_br::R`](R) reader structure"]
impl crate::Readable for DMACCARX_BR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`dmaccarx_br::W`](W) writer structure"]
impl crate::Writable for DMACCARX_BR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DMACCARxBR to value 0"]
impl crate::Resettable for DMACCARX_BR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
pub use self::axpy::Axpy;
mod axpy;
|
//! Authorize using the client credentials flow
//!
//! For example:
//!
//! ```no_run
//! use azure_identity::client_credentials_flow;
//! use oauth2::{ClientId, ClientSecret};
//! use url::Url;
//!
//! use std::env;
//! use std::error::Error;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn Error>> {
//! let client_id =
//! ClientId::new(env::var("CLIENT_ID").expect("Missing CLIENT_ID environment variable."));
//! let client_secret = ClientSecret::new(
//! env::var("CLIENT_SECRET").expect("Missing CLIENT_SECRET environment variable."),
//! );
//! let tenant_id = env::var("TENANT_ID").expect("Missing TENANT_ID environment variable.");
//! let subscription_id =
//! env::var("SUBSCRIPTION_ID").expect("Missing SUBSCRIPTION_ID environment variable.");
//!
//! let client = reqwest::Client::new();
//! // This will give you the final token to use in authorization.
//! let token = client_credentials_flow::perform(
//! client,
//! &client_id,
//! &client_secret,
//! &["https://management.azure.com/"],
//! &tenant_id,
//! )
//! .await?;
//! Ok(())
//! }
//! ```
//!
//! You can learn more about this athorization flow [here](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow).
mod login_response;
use crate::Error;
use login_response::LoginResponse;
use url::form_urlencoded;
/// Perform the client credentials flow
pub async fn perform(
client: reqwest::Client,
client_id: &oauth2::ClientId,
client_secret: &oauth2::ClientSecret,
scopes: &[&str],
tenant_id: &str,
) -> Result<LoginResponse, Error> {
let encoded: String = form_urlencoded::Serializer::new(String::new())
.append_pair("client_id", client_id.as_str())
.append_pair("scope", &scopes.join(" "))
.append_pair("client_secret", client_secret.secret())
.append_pair("grant_type", "client_credentials")
.finish();
let url = url::Url::parse(&format!(
"https://login.microsoftonline.com/{}/oauth2/v2.0/token",
tenant_id
))?;
client
.post(url)
.header("ContentType", "Application / WwwFormUrlEncoded")
.body(encoded)
.send()
.await?
.text()
.await
.map(|s| -> Result<LoginResponse, Error> {
Ok(serde_json::from_str::<LoginResponse>(&s)?)
})?
// TODO The HTTP status code should be checked to deserialize an error response.
// serde_json::from_str::<crate::errors::ErrorResponse>(&s).map(Error::ErrorResponse)
}
|
//! Utilities for game state management.
use resource::resource_system::ResourcSystem;
use engine::event::WindowEvent;
use renderer::Pipeline;
use ecs::World;
/// Types of state transitions.
pub enum Trans {
/// Continue as normal.
None,
/// Remove the active state and resume the next state on the stack or stop
/// if there are none.
Pop,
/// Pause the active state and push a new state onto the stack.
Push(Box<State>),
/// Remove the current state on the stack and insert a different one.
Switch(Box<State>),
/// Stop and remove all states and shut down the engine.
Quit,
}
/// A trait which defines game states that can be used by the state machine.
pub trait State {
/// Executed when the game state begins.
fn on_start(&mut self, _world: &mut World, _assets: &mut AssetManager, _pipe: &mut Pipeline) {}
/// Executed when the game state exits.
fn on_stop(&mut self, _world: &mut World, _assets: &mut AssetManager, _pipe: &mut Pipeline) {}
/// Executed when a different game state is pushed onto the stack.
fn on_pause(&mut self, _world: &mut World, _assets: &mut AssetManager, _pipe: &mut Pipeline) {}
/// Executed when the application returns to this game state once again.
fn on_resume(&mut self, _world: &mut World, _assets: &mut AssetManager, _pipe: &mut Pipeline) {}
/// Executed on every frame before updating, for use in reacting to events.
fn handle_events(&mut self,
_events: &[WindowEvent],
_world: &mut World,
_assets: &mut AssetManager,
_pipe: &mut Pipeline)
-> Trans {
Trans::None
}
/// Executed repeatedly at stable, predictable intervals (1/60th of a second
/// by default).
fn fixed_update(&mut self,
_world: &mut World,
_assets: &mut AssetManager,
_pipe: &mut Pipeline)
-> Trans {
Trans::None
}
/// Executed on every frame immediately, as fast as the engine will allow.
fn update(&mut self,
_world: &mut World,
_assets: &mut AssetManager,
_pipe: &mut Pipeline)
-> Trans {
Trans::None
}
}
/// A simple stack-based state machine (pushdown automaton).
pub struct StateMachine {
running: bool,
state_stack: Vec<Box<State>>,
}
impl StateMachine {
/// Creates a new state machine with the given initial state.
pub fn new<T>(initial_state: T) -> StateMachine
where T: State + 'static
{
StateMachine {
running: false,
state_stack: vec![Box::new(initial_state)],
}
}
/// Checks whether the state machine is running.
pub fn is_running(&self) -> bool {
self.running
}
/// Initializes the state machine.
///
/// # Panics
/// Panics if no states are present in the stack.
pub fn start(&mut self, world: &mut World, assets: &mut AssetManager, pipe: &mut Pipeline) {
if !self.running {
let state = self.state_stack.last_mut().unwrap();
state.on_start(world, assets, pipe);
self.running = true;
}
}
/// Passes a vector of events to the active state to handle.
pub fn handle_events(&mut self,
events: &[WindowEvent],
world: &mut World,
assets: &mut AssetManager,
pipe: &mut Pipeline) {
if self.running {
let trans = match self.state_stack.last_mut() {
Some(state) => state.handle_events(events, world, assets, pipe),
None => Trans::None,
};
self.transition(trans, world, assets, pipe);
}
}
/// Updates the currently active state at a steady, fixed interval.
pub fn fixed_update(&mut self,
world: &mut World,
assets: &mut AssetManager,
pipe: &mut Pipeline) {
if self.running {
let trans = match self.state_stack.last_mut() {
Some(state) => state.fixed_update(world, assets, pipe),
None => Trans::None,
};
self.transition(trans, world, assets, pipe);
}
}
/// Updates the currently active state immediately.
pub fn update(&mut self, world: &mut World, assets: &mut AssetManager, pipe: &mut Pipeline) {
if self.running {
let trans = match self.state_stack.last_mut() {
Some(state) => state.update(world, assets, pipe),
None => Trans::None,
};
self.transition(trans, world, assets, pipe);
}
}
/// Performs a state transition, if requested by either update() or
/// fixed_update().
fn transition(&mut self,
request: Trans,
world: &mut World,
assets: &mut AssetManager,
pipe: &mut Pipeline) {
if self.running {
match request {
Trans::None => (),
Trans::Pop => self.pop(world, assets, pipe),
Trans::Push(state) => self.push(state, world, assets, pipe),
Trans::Switch(state) => self.switch(state, world, assets, pipe),
Trans::Quit => self.stop(world, assets, pipe),
}
}
}
/// Removes the current state on the stack and inserts a different one.
fn switch(&mut self,
state: Box<State>,
world: &mut World,
assets: &mut AssetManager,
pipe: &mut Pipeline) {
if self.running {
if let Some(mut state) = self.state_stack.pop() {
state.on_stop(world, assets, pipe);
}
self.state_stack.push(state);
let state = self.state_stack.last_mut().unwrap();
state.on_start(world, assets, pipe);
}
}
/// Pauses the active state and pushes a new state onto the state stack.
fn push(&mut self,
state: Box<State>,
world: &mut World,
assets: &mut AssetManager,
pipe: &mut Pipeline) {
if self.running {
if let Some(state) = self.state_stack.last_mut() {
state.on_pause(world, assets, pipe);
}
self.state_stack.push(state);
let state = self.state_stack.last_mut().unwrap();
state.on_start(world, assets, pipe);
}
}
/// Stops and removes the active state and un-pauses the next state on the
/// stack (if any).
fn pop(&mut self, world: &mut World, assets: &mut AssetManager, pipe: &mut Pipeline) {
if self.running {
if let Some(mut state) = self.state_stack.pop() {
state.on_stop(world, assets, pipe);
}
if let Some(mut state) = self.state_stack.last_mut() {
state.on_resume(world, assets, pipe);
} else {
self.running = false;
}
}
}
/// Shuts the state machine down.
fn stop(&mut self, world: &mut World, assets: &mut AssetManager, pipe: &mut Pipeline) {
if self.running {
while let Some(mut state) = self.state_stack.pop() {
state.on_stop(world, assets, pipe);
}
self.running = false;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
struct State1(u8);
struct State2;
impl State for State1 {
fn update(&mut self, _: &mut World, _: &mut AssetManager, _: &mut Pipeline) -> Trans {
if self.0 > 0 {
self.0 -= 1;
Trans::None
} else {
Trans::Switch(Box::new(State2))
}
}
}
impl State for State2 {
fn update(&mut self, _: &mut World, _: &mut AssetManager, _: &mut Pipeline) -> Trans {
Trans::Pop
}
}
#[test]
fn switch_pop() {
let mut assets = AssetManager::new();
let mut pipe = Pipeline::new();
let mut world = World::new();
let mut sm = StateMachine::new(State1(7));
sm.start(&mut world, &mut assets, &mut pipe);
for _ in 0..8 {
sm.update(&mut world, &mut assets, &mut pipe);
assert!(sm.is_running());
}
sm.update(&mut world, &mut assets, &mut pipe);
assert!(!sm.is_running());
}
}
|
use domain_runtime_primitives::{BlockNumber as DomainNumber, Hash as DomainHash};
use sc_transaction_pool::error::Result as TxPoolResult;
use sc_transaction_pool_api::error::Error as TxPoolError;
use sc_transaction_pool_api::TransactionSource;
use sp_api::ProvideRuntimeApi;
use sp_core::traits::SpawnNamed;
use sp_domains::transaction::{
InvalidTransactionCode, PreValidationObject, PreValidationObjectApi,
};
use sp_runtime::traits::Block as BlockT;
use std::marker::PhantomData;
use std::sync::Arc;
use subspace_fraud_proof::VerifyFraudProof;
use subspace_transaction_pool::PreValidateTransaction;
pub struct ConsensusChainTxPreValidator<Block, Client, Verifier> {
client: Arc<Client>,
spawner: Box<dyn SpawnNamed>,
fraud_proof_verifier: Verifier,
_phantom_data: PhantomData<Block>,
}
impl<Block, Client, Verifier> Clone for ConsensusChainTxPreValidator<Block, Client, Verifier>
where
Verifier: Clone,
{
fn clone(&self) -> Self {
Self {
client: self.client.clone(),
spawner: self.spawner.clone(),
fraud_proof_verifier: self.fraud_proof_verifier.clone(),
_phantom_data: self._phantom_data,
}
}
}
impl<Block, Client, Verifier> ConsensusChainTxPreValidator<Block, Client, Verifier> {
pub fn new(
client: Arc<Client>,
spawner: Box<dyn SpawnNamed>,
fraud_proof_verifier: Verifier,
) -> Self {
Self {
client,
spawner,
fraud_proof_verifier,
_phantom_data: Default::default(),
}
}
}
#[async_trait::async_trait]
impl<Block, Client, Verifier> PreValidateTransaction
for ConsensusChainTxPreValidator<Block, Client, Verifier>
where
Block: BlockT,
Client: ProvideRuntimeApi<Block> + Send + Sync,
Client::Api: PreValidationObjectApi<Block, DomainNumber, DomainHash>,
Verifier: VerifyFraudProof<Block> + Clone + Send + Sync + 'static,
{
type Block = Block;
async fn pre_validate_transaction(
&self,
at: Block::Hash,
_source: TransactionSource,
uxt: Block::Extrinsic,
) -> TxPoolResult<()> {
let pre_validation_object = self
.client
.runtime_api()
.extract_pre_validation_object(at, uxt.clone())
.map_err(|err| sc_transaction_pool::error::Error::Blockchain(err.into()))?;
match pre_validation_object {
PreValidationObject::Null => {
// No pre-validation is required.
}
PreValidationObject::Bundle(_bundle) => {
// TODO: perhaps move the bundle format check here
}
PreValidationObject::FraudProof(fraud_proof) => {
subspace_fraud_proof::validate_fraud_proof_in_tx_pool(
&self.spawner,
self.fraud_proof_verifier.clone(),
fraud_proof,
)
.await
.map_err(|err| {
tracing::debug!(target: "txpool", error = ?err, "Invalid fraud proof");
TxPoolError::InvalidTransaction(InvalidTransactionCode::FraudProof.into())
})?;
}
}
Ok(())
}
}
|
struct Solution;
/// https://leetcode.com/problems/house-robber/submissions/
impl Solution {
/// 0 ms 2 MB
pub fn rob(nums: Vec<i32>) -> i32 {
let mut dp = vec![0; nums.len() + 1];
dp[1] = nums[0];
for i in 2..dp.len() {
let robbed = dp[i - 2] + nums[i - 1];
let skipped = dp[i - 1];
dp[i] = if robbed > skipped { robbed } else { skipped }
}
dp[nums.len()]
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test() {
fn assert(nums: &[i32], expected: i32) {
assert_eq!(Solution::rob(nums.to_vec()), expected);
}
assert(&[1], 1);
assert(&[3, 2], 3);
assert(&[1, 2, 3, 1], 4);
assert(&[2, 7, 9, 3, 1], 12);
assert(&[2, 1, 1, 2], 4);
}
}
|
fn main() {
let x : _= "hello world";
let y = &Box::new(x);
println!("{:?}", x);
println!("{:?}", y);
}
|
// q0013_roman_to_integer
struct Solution;
impl Solution {
pub fn roman_to_int(s: String) -> i32 {
let c = [
"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M",
];
let n = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000];
let mut i = n.len() - 1;
let mut ret = 0;
let mut index = 0;
let mut sp = &s[..];
while sp.len() > 0 {
if sp.starts_with(c[i]) {
ret += n[i];
index += c[i].len();
sp = &s[index..];
} else {
i -= 1;
}
}
return ret;
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn it_works() {
assert_eq!(5, Solution::roman_to_int("V".to_string()));
assert_eq!(3, Solution::roman_to_int("III".to_string()));
assert_eq!(4, Solution::roman_to_int("IV".to_string()));
assert_eq!(9, Solution::roman_to_int("IX".to_string()));
assert_eq!(58, Solution::roman_to_int("LVIII".to_string()));
assert_eq!(1994, Solution::roman_to_int("MCMXCIV".to_string()));
}
}
|
use types::Int as Int;
use types::Float as Float;
pub type Cmplx = (Float, Float);
pub fn get_passes_mandelbrot(in_z: Cmplx, mx: Int, dr: Float) -> Int {
let mut cnt : Int = 0;
let c : Cmplx = in_z;
let mut z : Cmplx = c;
loop {
let xsq : Float = z.0*z.0;
let ysq : Float = z.1*z.1;
//mandelbrot
z = ((xsq-ysq)+c.0, (2.0*z.0*z.1)+c.1);
cnt += 1;
if (cnt == mx) || ((xsq+ysq).sqrt()>dr) {
break;
}
}
cnt
} |
// use builder::Builder;
use lltype::*;
pub static RANGE_GEN_ID : &'static str = "!range_gen";
pub static RANGE_GEN_INIT : &'static str = "!range_gen_init";
pub static RANGE_GEN_NEXT : &'static str = "!range_gen_next";
///All the info needed to create and use a Generator in llvm.
///llvm generator types are structured like this
///
///gen_type {
/// next_block,
/// state_var_1,
/// state_var_2,
/// ...
/// state_var_n,
/// ret_val_1,
/// ret_val_2,
/// ...
/// ret_val_n,
///}
pub struct Generator {
pub typ : Type,
pub gen : Value,
pub init_args : Vec<Value>,
pub init_func : String,
pub next_func : String,
pub var_count : uint, //might turn this into a hashmap of identifiers => gen_index
pub ret_count : uint //might turn this into a hashmap of identifiers => gen_index
} |
use core::time::Duration;
use core::fmt;
use core::sync::atomic::{AtomicPtr, AtomicU64, AtomicUsize, Ordering};
use core::ops::Deref;
use core::mem::transmute;
use alloc::collections::BTreeMap;
use alloc::alloc::{Allocator, Global, Layout};
use alloc::sync::{Arc, Weak};
use spin::Mutex;
use ptr::NonNull;
use sys_consts::SysErr;
use crate::uses::*;
use crate::ipc::Ipcid;
use crate::mem::phys_alloc::{zm, Allocation};
use crate::mem::virt_alloc::{
AllocType, FAllocerType, PageMappingFlags, VirtLayout, VirtLayoutElement, VirtMapper,
};
use crate::config::MSG_BUF_SIZE;
use crate::mem::{VirtRange, PAGE_SIZE};
use crate::upriv::PrivLevel;
use crate::util::{
Futex, FutexGuard, IMutex, IMutexGuard, ListNode, MemOwner, UniqueMut, UniquePtr, UniqueRef,
};
use crate::time::timer;
use super::process::Process;
use super::{int_sched, thread_c, tlist, KFutex, Registers, ThreadList, Pid};
// TODO: implement support for growing stack
#[derive(Debug)]
pub enum Stack
{
User(VirtRange),
Kernel(Allocation),
KernelNoAlloc(VirtRange),
}
impl Stack
{
pub const DEFAULT_SIZE: usize = PAGE_SIZE * 32;
pub const DEFAULT_KERNEL_SIZE: usize = PAGE_SIZE * 16;
// size in bytes
pub fn user_new(size: usize, mapper: &VirtMapper<FAllocerType>) -> Result<Self, Err>
{
let elem_vec = vec![
VirtLayoutElement::new(PAGE_SIZE, PageMappingFlags::NONE).ok_or(Err::new("out of memory"))?,
VirtLayoutElement::new(
size,
PageMappingFlags::READ | PageMappingFlags::WRITE | PageMappingFlags::USER,
).ok_or(Err::new("Out of memory"))?,
];
let vlayout = VirtLayout::from(elem_vec, AllocType::Protected);
let vrange = unsafe { mapper.map(vlayout).map_err(|_| Err::new("could not map stack in memory"))? };
Ok(Self::User(vrange))
}
// TODO: put guard page in this one
pub fn kernel_new(size: usize) -> Result<Self, Err>
{
let allocation = zm.alloc(size).ok_or(Err::new("Out of mem"))?;
Ok(Self::Kernel(allocation))
}
pub fn no_alloc_new(range: VirtRange) -> Self
{
Self::KernelNoAlloc(range)
}
pub unsafe fn dealloc(&self, mapper: &VirtMapper<FAllocerType>)
{
match self {
Self::User(vrange) => mapper
.unmap(*vrange, AllocType::Protected)
.unwrap()
.dealloc(),
Self::Kernel(allocation) => zm.dealloc(*allocation),
_ => (),
}
}
pub fn bottom(&self) -> usize
{
match self {
Self::User(vrange) => vrange.addr().as_u64() as usize + PAGE_SIZE,
Self::Kernel(allocation) => allocation.as_usize(),
Self::KernelNoAlloc(vrange) => vrange.addr().as_u64() as usize,
}
}
pub fn top(&self) -> usize
{
self.bottom() + self.size()
}
pub fn size(&self) -> usize
{
match self {
Self::User(vrange) => vrange.size() - PAGE_SIZE,
Self::Kernel(allocation) => allocation.len(),
Self::KernelNoAlloc(vrange) => vrange.size(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ThreadState
{
Running,
Ready,
// idle thread
Idle,
Destroy,
// waiting for thread to call int_sched
Waiting(Tuid),
// nsecs to sleep
Sleep(u64),
// tid to join with
Join(Tuid),
// virtual address currently waiting on
FutexBlock(*const KFutex),
// connection cpid we are waiting for a reply from
Listening(Ipcid),
}
impl ThreadState
{
// called by the scheduler when whole scheduler is locked so additional atomic steps can be done
pub fn atomic_process(&self)
{
match self {
Self::FutexBlock(id) => unsafe { id.as_ref().unwrap().force_unlock() },
_ => (),
}
}
}
#[derive(Debug)]
pub struct ConnSaveState
{
regs: Registers,
stack: Stack,
}
impl ConnSaveState
{
pub fn new(regs: Registers, stack: Stack) -> Self
{
ConnSaveState {
regs,
stack,
}
}
}
#[derive(Debug)]
pub struct MsgBuf {
mem: Allocation,
vrange: VirtRange,
}
impl MsgBuf {
pub fn new(&self, addr_space: &VirtMapper<FAllocerType>) -> Option<Self> {
let mem = zm.alloc(MSG_BUF_SIZE)?;
let flags = PageMappingFlags::USER | PageMappingFlags::READ | PageMappingFlags::WRITE | PageMappingFlags::EXACT_SIZE;
let vec = vec![VirtLayoutElement::from_mem(mem, MSG_BUF_SIZE, flags)];
let vlayout = VirtLayout::from(vec, AllocType::Protected);
let vrange = unsafe {
addr_space.map(vlayout).ok()?
};
Some(MsgBuf {
mem,
vrange,
})
}
pub fn vrange(&self) -> VirtRange {
self.vrange
}
pub unsafe fn dealloc(self, addr_space: &VirtMapper<FAllocerType>) {
let vlayout = addr_space.unmap(self.vrange, AllocType::Protected)
.expect("invalid addr_space passed to MsgBuf::dealloc");
vlayout.dealloc();
}
}
crate::make_id_type!(Tid);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Tuid
{
pid: Pid,
tid: Tid,
}
impl Tuid
{
pub const fn new(pid: Pid, tid: Tid) -> Tuid
{
Tuid {
pid,
tid,
}
}
pub fn pid(&self) -> Pid
{
self.pid
}
pub fn tid(&self) -> Tid
{
self.tid
}
}
impl Default for Tuid
{
fn default() -> Self
{
Self::new(Pid::default(), Tid::default())
}
}
#[derive(Debug)]
pub struct ThreadRef(MemOwner<Thread>);
impl ThreadRef {
pub fn from(thread: MemOwner<Thread>) -> Self {
thread.ref_count.fetch_add(1, Ordering::AcqRel);
ThreadRef(thread)
}
}
impl Deref for ThreadRef {
type Target = Thread;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Clone for ThreadRef {
fn clone(&self) -> Self {
ThreadRef::from(unsafe { self.0.clone() })
}
}
impl Drop for ThreadRef {
fn drop(&mut self) {
self.0.ref_count.fetch_sub(1, Ordering::AcqRel);
}
}
pub struct Thread
{
process: Weak<Process>,
tuid: Tuid,
name: String,
idle: bool,
ref_count: AtomicUsize,
state: IMutex<ThreadState>,
run_time: AtomicU64,
pub regs: IMutex<Registers>,
stack: Futex<Stack>,
kstack: Option<Stack>,
conn_data: Futex<Vec<ConnSaveState>>,
msg_recieve_regs: IMutex<Result<Registers, SysErr>>,
msg_bufs: Futex<BTreeMap<VirtAddr, Allocation>>,
prev: AtomicPtr<Self>,
next: AtomicPtr<Self>,
}
impl Thread
{
pub fn new(
process: Weak<Process>,
tid: Tid,
name: String,
regs: Registers,
) -> Result<MemOwner<Self>, Err>
{
Self::new_stack_size(
process,
tid,
name,
regs,
Stack::DEFAULT_SIZE,
Stack::DEFAULT_KERNEL_SIZE,
)
}
// kstack_size only applies for ring 3 processes, for ring 0 stack_size is used as the stack size, but the stack is still a kernel stack
// does not put thread inside scheduler queue
pub fn new_stack_size(
process: Weak<Process>,
tid: Tid,
name: String,
mut regs: Registers,
stack_size: usize,
kstack_size: usize,
) -> Result<MemOwner<Self>, Err>
{
let proc = &process
.upgrade()
.expect("somehow Thread::new ran in a destroyed process");
let mapper = &proc.addr_space;
let uid = proc.uid();
let stack = match uid {
PrivLevel::Kernel => Stack::kernel_new(stack_size)?,
_ => Stack::user_new(stack_size, mapper)?,
};
let kstack = match uid {
PrivLevel::Kernel => None,
_ => {
let stack = Stack::kernel_new(kstack_size)?;
regs.call_rsp = stack.top() - 8;
Some(stack)
},
};
regs.apply_priv(uid);
regs.apply_stack(&stack);
Ok(MemOwner::new(Thread {
process,
tuid: Tuid::new(proc.pid(), tid),
name,
idle: false,
ref_count: AtomicUsize::new(0),
state: IMutex::new(ThreadState::Ready),
run_time: AtomicU64::new(0),
regs: IMutex::new(regs),
stack: Futex::new(stack),
kstack,
conn_data: Futex::new(Vec::new()),
msg_recieve_regs: IMutex::new(Err(SysErr::Unknown)),
msg_bufs: Futex::new(BTreeMap::new()),
prev: AtomicPtr::new(null_mut()),
next: AtomicPtr::new(null_mut()),
}))
}
// only used for kernel idle thread
// uid is assumed kernel
pub fn new_idle(
process: Weak<Process>,
tid: Tid,
name: String,
mut regs: Registers,
range: VirtRange,
) -> Result<MemOwner<Self>, Err>
{
// TODO: this hass to be ensured in smp
let proc = &process
.upgrade()
.expect("somehow Thread::new ran in a destroyed process");
let stack = Stack::no_alloc_new(range);
regs.apply_priv(PrivLevel::Kernel);
regs.apply_stack(&stack);
Ok(MemOwner::new(Thread {
process,
tuid: Tuid::new(proc.pid(), tid),
name,
idle: true,
ref_count: AtomicUsize::new(0),
state: IMutex::new(ThreadState::Ready),
run_time: AtomicU64::new(0),
regs: IMutex::new(regs),
stack: Futex::new(stack),
kstack: None,
conn_data: Futex::new(Vec::new()),
msg_recieve_regs: IMutex::new(Err(SysErr::Unknown)),
msg_bufs: Futex::new(BTreeMap::new()),
prev: AtomicPtr::new(null_mut()),
next: AtomicPtr::new(null_mut()),
}))
}
// for future compatability, when thread could be dead because of other reasons
pub fn is_alive(&self) -> bool
{
match self.process() {
Some(process) => {
process.is_alive()
}
None => false
}
}
pub fn proc_alive(&self) -> bool
{
self.process.strong_count() != 0
}
pub fn ref_count(&self) -> usize {
self.ref_count.load(Ordering::Acquire)
}
pub fn process(&self) -> Option<Arc<Process>>
{
self.process.upgrade()
}
pub fn tuid(&self) -> Tuid
{
self.tuid
}
pub fn tid(&self) -> Tid
{
self.tuid.tid()
}
pub fn name(&self) -> &str
{
&self.name
}
pub fn default_state(&self) -> ThreadState
{
if self.idle {
ThreadState::Idle
} else {
ThreadState::Ready
}
}
pub fn state(&self) -> ThreadState
{
//ThreadState::from_u128 (self.state.load ())
*self.state.lock()
}
pub fn set_state(&self, state: ThreadState)
{
//self.state.store (state.as_u128 ())
*self.state.lock() = state;
}
/*pub fn rcv_regs(&self) -> &IMutex<Result<Registers, SysErr>>
{
&self.msg_recieve_regs
}
pub fn msg_rcv(&self, args: &MsgArgs)
{
let mut regs = *self.regs.lock();
regs.apply_msg_args(args);
*self.msg_recieve_regs.lock() = Ok(regs);
if let ThreadState::Listening(_) = self.state() {
// FIXME: ugly
let ptr = UniqueRef::new(self);
let mut thread_list = tlist.lock();
Thread::move_to(ptr, ThreadState::Ready, &mut thread_list);
}
}
pub fn push_conn_state(&self, args: &MsgArgs) -> Result<(), SysErr>
{
let new_stack =
match Stack::user_new(Stack::DEFAULT_SIZE, &self.process().unwrap().addr_space) {
Ok(stack) => stack,
Err(_) => return Err(SysErr::OutOfMem),
};
let regs = *self.regs.lock();
let mut new_regs = regs;
new_regs.apply_msg_args(args).apply_stack(&new_stack);
// shouldn't be race condition, because these are all leaf locks
let mut rcv_regs = self.msg_recieve_regs.lock();
let mut conn_state = self.conn_data.lock();
let mut stack = self.stack.lock();
let old_stack = core::mem::replace(&mut *stack, new_stack);
let save_state = ConnSaveState::new(regs, old_stack);
conn_state.push(save_state);
*rcv_regs = Ok(new_regs);
Ok(())
}
pub fn pop_conn_state(&self) -> Result<(), SysErr>
{
let mut rcv_regs = self.msg_recieve_regs.lock();
let mut conn_state = self.conn_data.lock();
let mut stack = self.stack.lock();
let save_state = conn_state.pop().ok_or(SysErr::InvlOp)?;
*rcv_regs = Ok(save_state.regs);
let old_stack = core::mem::replace(&mut *stack, save_state.stack);
drop(rcv_regs);
drop(conn_state);
drop(stack);
unsafe {
old_stack.dealloc(&self.process().unwrap().addr_space);
}
Ok(())
}*/
// returns false if failed to remove
pub fn remove_from_current<'a, T>(ptr: T, list: &mut ThreadList) -> MemOwner<Thread>
where
T: UniquePtr<Self> + 'a,
{
list[ptr.state()].remove_node(ptr)
}
// returns None if failed to insert into list
// inserts into current state list
pub fn insert_into(thread: MemOwner<Self>, list: &mut ThreadList) -> UniqueMut<Thread>
{
list[thread.state()].push(thread)
}
// moves ThreadLNode from old thread state data structure to specified new thread state data structure and return true
// will set state variable accordingly
// if the thread has already been destroyed via process exiting, this will return false
pub fn move_to<'a, 'b, T>(
ptr: T,
state: ThreadState,
list: &'a mut ThreadList,
) -> UniqueMut<'a, Thread>
where
T: UniquePtr<Self> + Clone + 'b,
{
let thread = Self::remove_from_current(ptr, list);
thread.set_state(state);
Self::insert_into(thread, list)
}
pub fn run_time(&self) -> u64
{
self.run_time.load(Ordering::Acquire)
}
pub fn inc_time(&self, nsec: u64)
{
self.run_time.fetch_add(nsec, Ordering::AcqRel);
}
// TODO: figure out if it is safe to drop data pointed to by self
// will also put threas that are waiting on this thread in ready queue,
// but only if process is still alive and thread_list is not None
// NOTE: don't call with any IMutexs locked
// TODO: make safer
// safety: must call with no other references pointing to self existing
pub unsafe fn dealloc(this: MemOwner<Self>)
{
if let Some(process) = this.process() {
process
.remove_thread(this.tid())
.expect("thread should have been in process");
}
ptr::drop_in_place(this.ptr_mut());
this.dealloc();
}
}
impl Drop for Thread
{
fn drop(&mut self)
{
if let Some(process) = self.process() {
let mapper = &process.addr_space;
unsafe {
self.stack.lock().dealloc(mapper);
if let Some(stack) = self.kstack.as_ref() {
stack.dealloc(mapper);
}
}
}
}
}
impl fmt::Debug for Thread
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
f.debug_struct("Thread")
.field("process", &self.process())
.field("tuid", &self.tuid)
.field("name", &self.name)
.field("state", &self.state)
.field("run_time", &self.run_time)
.field("regs", &self.regs)
.field("stack", &self.stack)
.field("kstack", &self.kstack)
.field("conn_data", &self.conn_data)
.field("prev", &self.prev)
.field("next", &self.next)
.finish()
}
}
libutil::impl_list_node!(Thread, prev, next);
|
pub mod boxblock;
pub mod character;
pub mod craftboard;
pub mod terran;
pub mod textboard;
mod util;
pub use boxblock::Boxblock;
pub use character::Character;
pub use craftboard::Craftboard;
pub use terran::Terran;
pub use textboard::Textboard;
const ORDER_BOXBLOCK: f64 = 1.0;
const ORDER_CRAFTBOARD: f64 = 10.0;
const ORDER_CHARACTER: f64 = 100.0;
|
/// This module contains user-friendly names for the various items in the AST, to report in case they are missing
pub trait UserFriendly {
const DESCRIPTION: &'static str;
}
// this is in a submodule so it can be switched off and replaced by a blanket implementation for test-cases
#[cfg(not(test))]
mod names {
use super::*;
use crate::sudoers::ast::*;
use crate::sudoers::tokens;
impl UserFriendly for tokens::Digits {
const DESCRIPTION: &'static str = "number";
}
impl UserFriendly for tokens::Numeric {
const DESCRIPTION: &'static str = "number";
}
impl UserFriendly for Identifier {
const DESCRIPTION: &'static str = "identifier";
}
impl<T: UserFriendly> UserFriendly for Vec<T> {
const DESCRIPTION: &'static str = T::DESCRIPTION;
}
impl<T: UserFriendly> UserFriendly for tokens::Meta<T> {
const DESCRIPTION: &'static str = T::DESCRIPTION;
}
impl<T: UserFriendly> UserFriendly for Qualified<T> {
const DESCRIPTION: &'static str = T::DESCRIPTION;
}
impl UserFriendly for tokens::Command {
const DESCRIPTION: &'static str = "path to binary (or sudoedit)";
}
impl UserFriendly
for (
SpecList<tokens::Hostname>,
Vec<(Option<RunAs>, CommandSpec)>,
)
{
const DESCRIPTION: &'static str = tokens::Hostname::DESCRIPTION;
}
impl UserFriendly for (Option<RunAs>, CommandSpec) {
const DESCRIPTION: &'static str = "(users:groups) specification";
}
// this can never happen, as parse<Sudo> always succeeds
impl UserFriendly for Sudo {
const DESCRIPTION: &'static str = "nothing";
}
impl UserFriendly for UserSpecifier {
const DESCRIPTION: &'static str = "user";
}
impl UserFriendly for tokens::Hostname {
const DESCRIPTION: &'static str = "host name";
}
impl UserFriendly for tokens::QuotedText {
const DESCRIPTION: &'static str = "non-empty string";
}
impl UserFriendly for tokens::QuotedInclude {
const DESCRIPTION: &'static str = "non-empty string";
}
impl UserFriendly for tokens::StringParameter {
const DESCRIPTION: &'static str = tokens::QuotedText::DESCRIPTION;
}
impl UserFriendly for tokens::IncludePath {
const DESCRIPTION: &'static str = "path to file";
}
impl UserFriendly for tokens::AliasName {
const DESCRIPTION: &'static str = "alias name";
}
impl UserFriendly for tokens::DefaultName {
const DESCRIPTION: &'static str = "configuration option";
}
impl UserFriendly for tokens::EnvVar {
const DESCRIPTION: &'static str = "environment variable";
}
impl UserFriendly for CommandSpec {
const DESCRIPTION: &'static str = tokens::Command::DESCRIPTION;
}
impl UserFriendly for tokens::ChDir {
const DESCRIPTION: &'static str = "directory or '*'";
}
impl UserFriendly for (String, ConfigValue) {
const DESCRIPTION: &'static str = "parameter";
}
impl<T> UserFriendly for Def<T> {
const DESCRIPTION: &'static str = "alias definition";
}
}
#[cfg(test)]
impl<T: super::basic_parser::Parse> UserFriendly for T {
const DESCRIPTION: &'static str = "elem";
}
|
use std::path::{PathBuf};
use std::{fs, io, fmt};
use std::fmt::Formatter;
use std::str::FromStr;
use std::time::{Instant, Duration};
use super::error::{ImagicError, GetFilesResult};
use image::{ImageFormat};
/// STRUCTURES ///
pub struct Elapsed(Duration);
#[derive(Debug, PartialEq)]
pub enum Mode {
Single,
All,
}
#[derive(Debug)]
pub enum SizeOption {
Small,
Medium,
Large,
}
/// IMPLEMENTATIONS ///
impl Elapsed {
fn from(start: &Instant) -> Self {
Elapsed(start.elapsed())
}
}
impl fmt::Display for Elapsed {
fn fmt(&self, out: &mut Formatter<'_>) -> fmt::Result {
match (self.0.as_secs(), self.0.subsec_nanos()) {
(0, n) if n < 1000 => write!(out, "{} ns", n),
(0, n) if n < 1_000_000 => write!(out, "{} µs", n / 1000),
(0, n) => write!(out, "{} ms", n / 1_000_000),
(s, n) if s < 10 => write!(out, "{}.{:02} s", s, n / 10_000_000),
(s, _) => write!(out, "{} s", s),
}
}
}
impl FromStr for SizeOption {
type Err = ImagicError;
fn from_str(size: &str) -> Result<Self, Self::Err> {
match size {
"small" => Ok(SizeOption::Small),
"medium" => Ok(SizeOption::Medium),
"large" => Ok(SizeOption::Large),
_ => Ok(SizeOption::Small) // Default value
}
}
}
impl FromStr for Mode {
type Err = ImagicError;
fn from_str(mode: &str) -> Result<Self, Self::Err> {
match mode {
"single" => Ok(Mode::Single),
"all" => Ok(Mode::All),
_ => Err(ImagicError::UserInputError("Wrong value for mode".to_string())),
}
}
}
pub fn resize_request(size: SizeOption, mode: Mode, src: &mut PathBuf) -> Result<(), ImagicError> {
let size: u32 = match size {
SizeOption::Small => 200,
SizeOption::Medium => 400,
SizeOption::Large => 800,
};
let _ = match mode {
Mode::All => resize_all(size, src)?,
Mode::Single => resize_single(size, src)?,
};
Ok(())
}
fn resize_single(size: u32, src: &mut PathBuf) -> Result<(), ImagicError> {
resize_image(src, size)?;
Ok(())
}
fn resize_all(size: u32, src: &mut PathBuf) -> Result<(), ImagicError> {
if let Ok(entries) = get_image_files(src.to_path_buf()) {
for mut entry in entries {
resize_image(&mut entry, size)?;
}
};
Ok(())
}
pub fn resize_image(src: &mut PathBuf, size: u32) -> Result<(), ImagicError> {
let mut img_name = src.clone();
img_name.set_extension("png");
let new_name = img_name
.file_name()
.unwrap()
.to_str()
.ok_or(io::ErrorKind::InvalidInput); // Transform Option into a Result, Some->Ok | None->Err(err)
let mut dest_folder = src.clone();
dest_folder.pop();
dest_folder.push("tmp/");
if !dest_folder.exists() {
fs::create_dir(&dest_folder)?;
}
dest_folder.pop();
dest_folder.push("tmp/tmp.png");
dest_folder.set_file_name(new_name?);
let timer = Instant::now();
let img = image::open(&src)
.expect("Read image failed");
let img_converted = img.thumbnail_exact(size, size);
let mut output = fs::File::create(&dest_folder)?;
img_converted.write_to(&mut output, ImageFormat::Png)?;
println!("Thumbnailed file: {:?} to size {}x{} in {}. Output file
in {:?}", src, size, size, Elapsed::from(&timer), dest_folder);
Ok(())
}
pub fn get_image_files(src_folder: PathBuf) -> GetFilesResult {
let entries = fs::read_dir(src_folder)
.map_err(ImagicError::FileIO)?
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, io::Error>>()?
.into_iter()
.filter(|r| {
r.extension() == Some("jpg".as_ref())
|| r.extension() == Some("png".as_ref())
})
.collect();
Ok(entries)
}
/// TESTS ///
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_reading_file() {
let path = PathBuf::from("img/");
let test = get_image_files(path).unwrap();
assert_eq!(true, test.contains(&PathBuf::from("img/gleb1.jpg")));
assert_eq!(true, test.contains(&PathBuf::from("img/gleb2.jpg")));
assert_eq!(false, test.contains(&PathBuf::from("img/gashishishpak.gif")));
}
#[test]
fn test_single_image_resize() {
let mut path = PathBuf::from("img/gleb1_2.jpg");
let dest_path = PathBuf::from("img/tmp/gleb1_2.png");
match resize_request(SizeOption::Small, Mode::Single, &mut path) {
Ok(_) => println!("Resize of single image completed"),
Err(e) => println!("Error occurred: {:?}", e),
}
assert_eq!(true, dest_path.exists());
}
#[test]
fn test_all_image_resize() {
let mut path = PathBuf::from("img/");
let dest_path1 = PathBuf::from("img/tmp/gleb1.png");
let dest_path2 = PathBuf::from("img/tmp/gleb1_2.png");
let dest_path3= PathBuf::from("img/tmp/gleb2.png");
let dest_path4= PathBuf::from("img/tmp/gleb23.png");
let _res = resize_request(SizeOption::Medium, Mode::All, &mut path);
assert_eq!(true, dest_path1.exists());
assert_eq!(true, dest_path2.exists());
assert_eq!(true, dest_path3.exists());
assert_eq!(true, dest_path4.exists());
}
} |
/* This is part of mktcb - which is under the MIT License ********************/
use log::{Record, Level, Metadata, LevelFilter};
use snafu::{OptionExt};
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
use crate::error::Result;
use crate::error;
use std::io::Write;
struct Logger;
static LOGGER: Logger = Logger;
impl log::Log for Logger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= log::max_level()
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
let mut spec = ColorSpec::new();
let (lvl, use_stderr) = match record.level() {
Level::Error => {
spec.set_fg(Some(Color::Red));
("error", true)
},
Level::Warn => {
spec.set_fg(Some(Color::Yellow));
("warning", true)
},
Level::Info => {
spec.set_fg(Some(Color::Green));
("info", true)
},
Level::Debug => {
spec.set_fg(Some(Color::Blue));
("debug", true)
},
Level::Trace => {
spec.set_fg(Some(Color::White));
("trace", true)
},
};
spec.set_intense(true).set_bold(true);
let (mut stream, use_color) = if use_stderr {
(StandardStream::stdout(ColorChoice::Auto),
atty::is(atty::Stream::Stdout))
} else {
(StandardStream::stderr(ColorChoice::Auto),
atty::is(atty::Stream::Stderr))
};
// Actually log... We purely ignore errors if we fail to set the
// color and other tty attributes, because logging is more important
// than fancyness. Also, if we fail to actually log, we try using
// eprintln!(), hoping for the best... If log fails anyway, we are
// likely screwed.
if use_color {
let _ = stream.set_color(&spec);
}
if let Err(_) = write!(&mut stream, "{}", lvl) {
eprintln!("{}", lvl);
}
if use_color {
spec.clear();
let _ = stream.set_color(&spec);
}
if let Err(_) = writeln!(&mut stream, ": {}", record.args()) {
eprintln!(": {}", record.args());
}
}
}
fn flush(&self) {}
}
pub fn init(max_level: LevelFilter) -> Result<()> {
log::set_logger(&LOGGER).map(|()| {
log::set_max_level(max_level)
}).ok().context(error::LogInitFailed{})
//let log = &mut LOGGER;
//LOG
//log.stdout_use_colors = atty::is(atty::Stream::Stdout);
//log.stderr_use_colors = atty::is(atty::Stream::Stderr);
}
|
use testutil::*;
mod testutil;
#[test]
fn instance() {
let client = get_client();
assert_eq!(get_api_key().to_string(), client.api_key);
assert_eq!(SENT_WITH, client.sent_with);
}
|
use super::{Operation, ShallowCopy};
use inner::Inner;
use read::ReadHandle;
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hash};
use std::sync::atomic;
use std::sync::{Arc, MutexGuard};
use std::{mem, thread};
/// A handle that may be used to modify the eventually consistent map.
///
/// Note that any changes made to the map will not be made visible to readers until `refresh()` is
/// called.
///
/// # Examples
/// ```
/// let x = ('x', 42);
///
/// let (r, mut w) = evmap::new();
///
/// // the map is uninitialized, so all lookups should return None
/// assert_eq!(r.get_and(&x.0, |rs| rs.len()), None);
///
/// w.refresh();
///
/// // after the first refresh, it is empty, but ready
/// assert_eq!(r.get_and(&x.0, |rs| rs.len()), None);
///
/// w.insert(x.0, x);
///
/// // it is empty even after an add (we haven't refresh yet)
/// assert_eq!(r.get_and(&x.0, |rs| rs.len()), None);
///
/// w.refresh();
///
/// // but after the swap, the record is there!
/// assert_eq!(r.get_and(&x.0, |rs| rs.len()), Some(1));
/// assert_eq!(r.get_and(&x.0, |rs| rs.iter().any(|v| v.0 == x.0 && v.1 == x.1)), Some(true));
/// ```
pub struct WriteHandle<K, V, M = (), S = RandomState>
where
K: Eq + Hash + Clone,
S: BuildHasher + Clone,
V: Eq + ShallowCopy,
M: 'static + Clone,
{
w_handle: Option<Box<Inner<K, V, M, S>>>,
oplog: Vec<Operation<K, V>>,
swap_index: usize,
r_handle: ReadHandle<K, V, M, S>,
last_epochs: Vec<usize>,
meta: M,
first: bool,
second: bool,
drop_dont_refresh: bool,
}
pub(crate) fn new<K, V, M, S>(
w_handle: Inner<K, V, M, S>,
r_handle: ReadHandle<K, V, M, S>,
) -> WriteHandle<K, V, M, S>
where
K: Eq + Hash + Clone,
S: BuildHasher + Clone,
V: Eq + ShallowCopy,
M: 'static + Clone,
{
let m = w_handle.meta.clone();
WriteHandle {
w_handle: Some(Box::new(w_handle)),
oplog: Vec::new(),
swap_index: 0,
r_handle: r_handle,
last_epochs: Vec::new(),
meta: m,
first: true,
second: false,
drop_dont_refresh: false,
}
}
impl<K, V, M, S> Drop for WriteHandle<K, V, M, S>
where
K: Eq + Hash + Clone,
S: BuildHasher + Clone,
V: Eq + ShallowCopy,
M: 'static + Clone,
{
fn drop(&mut self) {
if !self.drop_dont_refresh {
// eventually, the last Arc<Inner> will be dropped, and that will cause the entire read map
// to be dropped. this will, in turn, call the destructors for the values that are there.
// we need to make sure that we don't end up dropping some aliased values twice, and that
// we don't forget to drop any values.
//
// we *could* laboriously walk through .data and .oplog to figure out exactly what
// destructors we do or don't need to call to ensure exactly-once dropping. but, instead,
// we'll just let refresh do the work for us.
if !self.oplog.is_empty() {
// applies oplog entries that are in r_handle to w_handle and applies new oplog entries
// to w_handle, then swaps. oplog is *not* guaranteed to be empty, but *is* guaranteed
// to only have ops that have been applied to exactly one map.
self.refresh();
}
if !self.oplog.is_empty() {
// applies oplog entries that are in (old) w_handle to (old) r_handle. this leaves
// oplog empty, and the two data maps identical.
self.refresh();
}
}
assert!(self.oplog.is_empty());
// since the two maps are exactly equal, we need to make sure that we *don't* call the
// destructors of any of the values that are in our map, as they'll all be called when the
// last read handle goes out of scope.
for (_, mut vs) in self.w_handle.as_mut().unwrap().data.drain() {
for v in vs.drain(..) {
mem::forget(v);
}
}
}
}
impl<K, V, M, S> WriteHandle<K, V, M, S>
where
K: Eq + Hash + Clone,
S: BuildHasher + Clone,
V: Eq + ShallowCopy,
M: 'static + Clone,
{
fn wait(&mut self, epochs: &mut MutexGuard<Vec<Arc<atomic::AtomicUsize>>>) {
let mut iter = 0;
let mut starti = 0;
let high_bit = 1usize << (mem::size_of::<usize>() * 8 - 1);
self.last_epochs.resize(epochs.len(), 0);
'retry: loop {
// read all and see if all have changed (which is likely)
for (i, epoch) in epochs.iter().enumerate().skip(starti) {
if self.last_epochs[i] & high_bit != 0 {
// reader was not active right after last swap
// and therefore *must* only see new pointer
continue;
}
let now = epoch.load(atomic::Ordering::Acquire);
if (now != self.last_epochs[i]) | (now & high_bit != 0) | (now == 0) {
// reader must have seen last swap
} else {
// reader may not have seen swap
// continue from this reader's epoch
starti = i;
// how eagerly should we retry?
if iter != 20 {
iter += 1;
} else {
thread::yield_now();
}
continue 'retry;
}
}
break;
}
}
/// Refresh the handle used by readers so that pending writes are made visible.
///
/// This method needs to wait for all readers to move to the new handle so that it can replay
/// the operational log onto the stale map copy the readers used to use. This can take some
/// time, especially if readers are executing slow operations, or if there are many of them.
pub fn refresh(&mut self) {
// we need to wait until all epochs have changed since the swaps *or* until a "finished"
// flag has been observed to be on for two subsequent iterations (there still may be some
// readers present since we did the previous refresh)
//
// NOTE: it is safe for us to hold the lock for the entire duration of the swap. we will
// only block on pre-existing readers, and they are never waiting to push onto epochs
// unless they have finished reading.
let epochs = Arc::clone(&self.w_handle.as_ref().unwrap().epochs);
let mut epochs = epochs.lock().unwrap();
self.wait(&mut epochs);
{
// all the readers have left!
// we can safely bring the w_handle up to date.
let w_handle = self.w_handle.as_mut().unwrap();
if self.second {
// before the first refresh, all writes went directly to w_handle. then, at the
// first refresh, r_handle and w_handle were swapped. thus, the w_handle we
// have now is empty, *and* none of the writes in r_handle are in the oplog.
// we therefore have to first clone the entire state of the current r_handle
// and make that w_handle, and *then* replay the oplog (which holds writes
// following the first refresh).
//
// this may seem unnecessarily complex, but it has the major advantage that it
// is relatively efficient to do lots of writes to the evmap at startup to
// populate it, and then refresh().
let mut r_handle =
unsafe { Box::from_raw(self.r_handle.inner.load(atomic::Ordering::Relaxed)) };
// XXX: it really is too bad that we can't just .clone() the data here and save
// ourselves a lot of re-hashing, re-bucketization, etc.
w_handle
.data
.extend(r_handle.data.iter_mut().map(|(k, vs)| {
(
k.clone(),
vs.iter_mut().map(|v| unsafe { v.shallow_copy() }).collect(),
)
}));
mem::forget(r_handle);
}
// the w_handle map has not seen any of the writes in the oplog
// the r_handle map has not seen any of the writes following swap_index
if self.swap_index != 0 {
// we can drain out the operations that only the w_handle map needs
//
// NOTE: the if above is because drain(0..0) would remove 0
//
// NOTE: the distinction between apply_first and apply_second is the reason why our
// use of shallow_copy is safe. we apply each op in the oplog twice, first with
// apply_first, and then with apply_second. on apply_first, no destructors are
// called for removed values (since those values all still exist in the other map),
// and all new values are shallow copied in (since we need the original for the
// other map). on apply_second, we call the destructor for anything that's been
// removed (since those removals have already happened on the other map, and
// without calling their destructor).
for op in self.oplog.drain(0..self.swap_index) {
Self::apply_second(w_handle, op);
}
}
// the rest have to be cloned because they'll also be needed by the r_handle map
for op in self.oplog.iter_mut() {
Self::apply_first(w_handle, op);
}
// the w_handle map is about to become the r_handle, and can ignore the oplog
self.swap_index = self.oplog.len();
// ensure meta-information is up to date
w_handle.meta = self.meta.clone();
w_handle.mark_ready();
// w_handle (the old r_handle) is now fully up to date!
}
// at this point, we have exclusive access to w_handle, and it is up-to-date with all
// writes. the stale r_handle is accessed by readers through an Arc clone of atomic pointer
// inside the ReadHandle. oplog contains all the changes that are in w_handle, but not in
// r_handle.
//
// it's now time for us to swap the maps so that readers see up-to-date results from
// w_handle.
// prepare w_handle
let w_handle = self.w_handle.take().unwrap();
let w_handle = Box::into_raw(w_handle);
// swap in our w_handle, and get r_handle in return
let r_handle = self.r_handle
.inner
.swap(w_handle, atomic::Ordering::Release);
let r_handle = unsafe { Box::from_raw(r_handle) };
// ensure that the subsequent epoch reads aren't re-ordered to before the swap
atomic::fence(atomic::Ordering::SeqCst);
for (i, epoch) in epochs.iter().enumerate() {
self.last_epochs[i] = epoch.load(atomic::Ordering::Acquire);
}
// NOTE: at this point, there are likely still readers using the w_handle we got
self.w_handle = Some(r_handle);
self.second = self.first;
self.first = false;
}
/// Drop this map without preserving one side for reads.
///
/// Normally, the maps are not deallocated until all readers have also gone away.
/// When this method is called, the map is immediately (but safely) taken away from all
/// readers, causing all future lookups to return `None`.
///
/// ```
/// use std::thread;
/// let (r, mut w) = evmap::new();
///
/// // start some readers
/// let readers: Vec<_> = (0..4).map(|_| {
/// let r = r.clone();
/// thread::spawn(move || {
/// loop {
/// let l = r.len();
/// if l == 0 {
/// if r.is_destroyed() {
/// // the writer destroyed the map!
/// break;
/// }
/// thread::yield_now();
/// } else {
/// // the reader will either see all the reviews,
/// // or none of them, since refresh() is atomic.
/// assert_eq!(l, 4);
/// }
/// }
/// })
/// }).collect();
///
/// // do some writes
/// w.insert(0, String::from("foo"));
/// w.insert(1, String::from("bar"));
/// w.insert(2, String::from("baz"));
/// w.insert(3, String::from("qux"));
/// // expose the writes
/// w.refresh();
/// assert_eq!(r.len(), 4);
///
/// // refresh a few times to exercise the readers
/// for _ in 0..10 {
/// w.refresh();
/// }
///
/// // now blow the map away
/// w.destroy();
///
/// // all the threads should eventually see that the map was destroyed
/// for r in readers.into_iter() {
/// assert!(r.join().is_ok());
/// }
/// ```
pub fn destroy(mut self) {
use std::ptr;
// first, ensure both maps are up to date
// (otherwise safely dropping deduplicated rows is a pain)
// see also impl Drop
self.refresh();
self.refresh();
// next, grab the read handle and set it to NULL
let r_handle = self.r_handle
.inner
.swap(ptr::null_mut(), atomic::Ordering::Release);
let r_handle = unsafe { Box::from_raw(r_handle) };
// now, wait for all readers to depart
let epochs = Arc::clone(&self.w_handle.as_ref().unwrap().epochs);
let mut epochs = epochs.lock().unwrap();
self.wait(&mut epochs);
// ensure that the subsequent epoch reads aren't re-ordered to before the swap
atomic::fence(atomic::Ordering::SeqCst);
// all readers have now observed the NULL, so we own both handles.
// all records are duplicated between w_handle and r_handle.
// we should *only* call the destructor for each record once!
// first, we drop self, which will forget all the records in w_handle
self.drop_dont_refresh = true;
drop(self);
// then we drop r_handle, which will free all the records
drop(r_handle);
}
/// Gives the sequence of operations that have not yet been applied.
///
/// Note that until the *first* call to `refresh`, the sequence of operations is always empty.
///
/// ```
/// # use evmap::Operation;
/// let x = ('x', 42);
///
/// let (r, mut w) = evmap::new();
///
/// // before the first refresh, no oplog is kept
/// w.refresh();
///
/// assert_eq!(w.pending(), &[]);
/// w.insert(x.0, x);
/// assert_eq!(w.pending(), &[Operation::Add(x.0, x)]);
/// w.refresh();
/// w.remove(x.0, x);
/// assert_eq!(w.pending(), &[Operation::Remove(x.0, x)]);
/// w.refresh();
/// assert_eq!(w.pending(), &[]);
/// ```
pub fn pending(&self) -> &[Operation<K, V>] {
&self.oplog[self.swap_index..]
}
/// Refresh as necessary to ensure that all operations are visible to readers.
///
/// `WriteHandle::refresh` will *always* wait for old readers to depart and swap the maps.
/// This method will only do so if there are pending operations.
pub fn flush(&mut self) {
if !self.pending().is_empty() {
self.refresh();
}
}
/// Set the metadata.
///
/// Will only be visible to readers after the next call to `refresh()`.
pub fn set_meta(&mut self, mut meta: M) -> M {
mem::swap(&mut self.meta, &mut meta);
meta
}
fn add_op(&mut self, op: Operation<K, V>) {
if !self.first {
self.oplog.push(op);
} else {
// we know there are no outstanding w_handle readers, so we can modify it directly!
let inner = self.w_handle.as_mut().unwrap();
Self::apply_second(inner, op);
// NOTE: since we didn't record this in the oplog, r_handle *must* clone w_handle
}
}
/// Add the given value to the value-set of the given key.
///
/// The updated value-set will only be visible to readers after the next call to `refresh()`.
pub fn insert(&mut self, k: K, v: V) {
self.add_op(Operation::Add(k, v));
}
/// Replace the value-set of the given key with the given value.
///
/// The new value will only be visible to readers after the next call to `refresh()`.
pub fn update(&mut self, k: K, v: V) {
self.add_op(Operation::Replace(k, v));
}
/// Clear the value-set of the given key, without removing it.
///
/// This will allocate an empty value-set for the key if it does not already exist.
/// The new value will only be visible to readers after the next call to `refresh()`.
pub fn clear(&mut self, k: K) {
self.add_op(Operation::Clear(k));
}
/// Remove the given value from the value-set of the given key.
///
/// The updated value-set will only be visible to readers after the next call to `refresh()`.
pub fn remove(&mut self, k: K, v: V) {
self.add_op(Operation::Remove(k, v));
}
/// Remove the value-set for the given key.
///
/// The value-set will only disappear from readers after the next call to `refresh()`.
pub fn empty(&mut self, k: K) {
self.add_op(Operation::Empty(k));
}
/// Remove the value-set for a key at a specified index.
///
/// This is effectively random removal
/// The value-set will only disappear from readers after the next call to `refresh()`.
pub fn empty_at_index(&mut self, index: usize) -> Option<(&K, &Vec<V>)> {
self.add_op(Operation::EmptyRandom(index));
// the actual emptying won't happen until refresh(), which needs &mut self
// so it's okay for us to return the references here
// NOTE to future zealots intent on removing the unsafe code: it's **NOT** okay to use
// self.w_handle here, since that does not have all pending operations applied to it yet.
// Specifically, there may be an *eviction* pending that already has been applied to the
// r_handle side, but not to the w_handle (will be applied on the next swap). We must make
// sure that we read the most up to date map here.
let inner = self.r_handle.inner.load(atomic::Ordering::SeqCst);
unsafe { (*inner).data.at_index(index) }
}
fn apply_first(inner: &mut Inner<K, V, M, S>, op: &mut Operation<K, V>) {
match *op {
Operation::Replace(ref key, ref mut value) => {
let vs = inner.data.entry(key.clone()).or_insert_with(Vec::new);
// don't run destructors yet -- still in use by other map
for v in vs.drain(..) {
mem::forget(v);
}
vs.push(unsafe { value.shallow_copy() });
}
Operation::Clear(ref key) => {
// don't run destructors yet -- still in use by other map
for v in inner
.data
.entry(key.clone())
.or_insert_with(Vec::new)
.drain(..)
{
mem::forget(v);
}
}
Operation::Add(ref key, ref mut value) => {
inner
.data
.entry(key.clone())
.or_insert_with(Vec::new)
.push(unsafe { value.shallow_copy() });
}
Operation::Empty(ref key) => {
if let Some(mut vs) = inner.data.remove(key) {
// don't run destructors yet -- still in use by other map
for v in vs.drain(..) {
mem::forget(v);
}
}
}
Operation::EmptyRandom(index) => {
if let Some((_k, mut vs)) = inner.data.remove_at_index(index) {
// don't run destructors yet -- still in use by other map
for v in vs.drain(..) {
mem::forget(v);
}
}
}
Operation::Remove(ref key, ref value) => {
if let Some(e) = inner.data.get_mut(key) {
// find the first entry that matches all fields
if let Some(i) = e.iter().position(|v| v == value) {
let v = e.swap_remove(i);
// don't run destructor yet -- still in use by other map
mem::forget(v);
}
}
}
}
}
fn apply_second(inner: &mut Inner<K, V, M, S>, op: Operation<K, V>) {
match op {
Operation::Replace(key, value) => {
let v = inner.data.entry(key).or_insert_with(Vec::new);
v.clear();
v.push(value);
}
Operation::Clear(key) => {
let v = inner.data.entry(key).or_insert_with(Vec::new);
v.clear();
}
Operation::Add(key, value) => {
inner.data.entry(key).or_insert_with(Vec::new).push(value);
}
Operation::Empty(key) => {
inner.data.remove(&key);
}
Operation::EmptyRandom(index) => {
inner.data.remove_at_index(index);
}
Operation::Remove(key, value) => {
if let Some(e) = inner.data.get_mut(&key) {
// find the first entry that matches all fields
if let Some(i) = e.iter().position(|v| v == &value) {
e.swap_remove(i);
}
}
}
}
}
}
impl<K, V, M, S> Extend<(K, V)> for WriteHandle<K, V, M, S>
where
K: Eq + Hash + Clone,
S: BuildHasher + Clone,
V: Eq + ShallowCopy,
M: 'static + Clone,
{
fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
for (k, v) in iter {
self.insert(k, v);
}
}
}
// allow using write handle for reads
use std::ops::Deref;
impl<K, V, M, S> Deref for WriteHandle<K, V, M, S>
where
K: Eq + Hash + Clone,
S: BuildHasher + Clone,
V: Eq + ShallowCopy,
M: 'static + Clone,
{
type Target = ReadHandle<K, V, M, S>;
fn deref(&self) -> &Self::Target {
&self.r_handle
}
}
|
// Copyright 2021 The Simlin Authors. All rights reserved.
// Use of this source code is governed by the Apache License,
// Version 2.0, that can be found in the LICENSE file.
use std::borrow::BorrowMut;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::rc::Rc;
use float_cmp::approx_eq;
use crate::ast::{self, Ast, BinaryOp, Loc};
use crate::bytecode::{
BuiltinId, ByteCode, ByteCodeBuilder, ByteCodeContext, CompiledModule, GraphicalFunctionId,
ModuleDeclaration, ModuleId, ModuleInputOffset, Op2, Opcode, VariableOffset,
};
use crate::common::{quoteize, ErrorCode, ErrorKind, Ident, Result};
use crate::datamodel::{self, Dimension};
use crate::interpreter::UnaryOp;
use crate::model::{enumerate_modules, ModelStage1};
use crate::project::Project;
use crate::variable::Variable;
use crate::vm::{
is_truthy, pulse, ramp, step, CompiledSimulation, Results, Specs, StepPart, SubscriptIterator,
DT_OFF, FINAL_TIME_OFF, IMPLICIT_VAR_COUNT, INITIAL_TIME_OFF, TIME_OFF,
};
use crate::{sim_err, Error};
#[derive(Clone, Debug, PartialEq)]
pub struct Table {
pub data: Vec<(f64, f64)>,
}
impl Table {
fn new(ident: &str, t: &crate::variable::Table) -> Result<Self> {
if t.x.len() != t.y.len() {
return sim_err!(BadTable, ident.to_string());
}
let data: Vec<(f64, f64)> = t.x.iter().copied().zip(t.y.iter().copied()).collect();
Ok(Self { data })
}
}
type BuiltinFn = crate::builtins::BuiltinFn<Expr>;
#[derive(PartialEq, Clone, Debug)]
pub enum Expr {
Const(f64, Loc),
Var(usize, Loc), // offset
Subscript(usize, Vec<Expr>, Vec<usize>, Loc), // offset, index expression, bounds
Dt(Loc),
App(BuiltinFn, Loc),
EvalModule(Ident, Ident, Vec<Expr>),
ModuleInput(usize, Loc),
Op2(BinaryOp, Box<Expr>, Box<Expr>, Loc),
Op1(UnaryOp, Box<Expr>, Loc),
If(Box<Expr>, Box<Expr>, Box<Expr>, Loc),
AssignCurr(usize, Box<Expr>),
AssignNext(usize, Box<Expr>),
}
impl Expr {
fn get_loc(&self) -> Loc {
match self {
Expr::Const(_, loc) => *loc,
Expr::Var(_, loc) => *loc,
Expr::Subscript(_, _, _, loc) => *loc,
Expr::Dt(loc) => *loc,
Expr::App(_, loc) => *loc,
Expr::EvalModule(_, _, _) => Loc::default(),
Expr::ModuleInput(_, loc) => *loc,
Expr::Op2(_, _, _, loc) => *loc,
Expr::Op1(_, _, loc) => *loc,
Expr::If(_, _, _, loc) => *loc,
Expr::AssignCurr(_, _) => Loc::default(),
Expr::AssignNext(_, _) => Loc::default(),
}
}
#[cfg(test)]
pub(crate) fn strip_loc(self) -> Self {
let loc = Loc::default();
match self {
Expr::Const(c, _loc) => Expr::Const(c, loc),
Expr::Var(v, _loc) => Expr::Var(v, loc),
Expr::Subscript(off, subscripts, bounds, _) => {
let subscripts = subscripts
.into_iter()
.map(|expr| expr.strip_loc())
.collect();
Expr::Subscript(off, subscripts, bounds, loc)
}
Expr::Dt(_) => Expr::Dt(loc),
Expr::App(builtin, _loc) => {
let builtin = match builtin {
// nothing to strip from these simple ones
BuiltinFn::Inf
| BuiltinFn::Pi
| BuiltinFn::Time
| BuiltinFn::TimeStep
| BuiltinFn::StartTime
| BuiltinFn::FinalTime => builtin,
BuiltinFn::IsModuleInput(id, _loc) => BuiltinFn::IsModuleInput(id, loc),
BuiltinFn::Lookup(id, a, _loc) => {
BuiltinFn::Lookup(id, Box::new(a.strip_loc()), loc)
}
BuiltinFn::Abs(a) => BuiltinFn::Abs(Box::new(a.strip_loc())),
BuiltinFn::Arccos(a) => BuiltinFn::Arccos(Box::new(a.strip_loc())),
BuiltinFn::Arcsin(a) => BuiltinFn::Arcsin(Box::new(a.strip_loc())),
BuiltinFn::Arctan(a) => BuiltinFn::Arctan(Box::new(a.strip_loc())),
BuiltinFn::Cos(a) => BuiltinFn::Cos(Box::new(a.strip_loc())),
BuiltinFn::Exp(a) => BuiltinFn::Exp(Box::new(a.strip_loc())),
BuiltinFn::Int(a) => BuiltinFn::Int(Box::new(a.strip_loc())),
BuiltinFn::Ln(a) => BuiltinFn::Ln(Box::new(a.strip_loc())),
BuiltinFn::Log10(a) => BuiltinFn::Log10(Box::new(a.strip_loc())),
BuiltinFn::Mean(args) => {
BuiltinFn::Mean(args.into_iter().map(|arg| arg.strip_loc()).collect())
}
BuiltinFn::Sin(a) => BuiltinFn::Sin(Box::new(a.strip_loc())),
BuiltinFn::Sqrt(a) => BuiltinFn::Sqrt(Box::new(a.strip_loc())),
BuiltinFn::Tan(a) => BuiltinFn::Tan(Box::new(a.strip_loc())),
BuiltinFn::Max(a, b) => {
BuiltinFn::Max(Box::new(a.strip_loc()), Box::new(b.strip_loc()))
}
BuiltinFn::Min(a, b) => {
BuiltinFn::Min(Box::new(a.strip_loc()), Box::new(b.strip_loc()))
}
BuiltinFn::Step(a, b) => {
BuiltinFn::Step(Box::new(a.strip_loc()), Box::new(b.strip_loc()))
}
BuiltinFn::Pulse(a, b, c) => BuiltinFn::Pulse(
Box::new(a.strip_loc()),
Box::new(b.strip_loc()),
c.map(|expr| Box::new(expr.strip_loc())),
),
BuiltinFn::Ramp(a, b, c) => BuiltinFn::Ramp(
Box::new(a.strip_loc()),
Box::new(b.strip_loc()),
c.map(|expr| Box::new(expr.strip_loc())),
),
BuiltinFn::SafeDiv(a, b, c) => BuiltinFn::SafeDiv(
Box::new(a.strip_loc()),
Box::new(b.strip_loc()),
c.map(|expr| Box::new(expr.strip_loc())),
),
};
Expr::App(builtin, loc)
}
Expr::EvalModule(id1, id2, args) => {
let args = args.into_iter().map(|expr| expr.strip_loc()).collect();
Expr::EvalModule(id1, id2, args)
}
Expr::ModuleInput(mi, _loc) => Expr::ModuleInput(mi, loc),
Expr::Op2(op, l, r, _loc) => {
Expr::Op2(op, Box::new(l.strip_loc()), Box::new(r.strip_loc()), loc)
}
Expr::Op1(op, r, _loc) => Expr::Op1(op, Box::new(r.strip_loc()), loc),
Expr::If(cond, t, f, _loc) => Expr::If(
Box::new(cond.strip_loc()),
Box::new(t.strip_loc()),
Box::new(f.strip_loc()),
loc,
),
Expr::AssignCurr(off, rhs) => Expr::AssignCurr(off, Box::new(rhs.strip_loc())),
Expr::AssignNext(off, rhs) => Expr::AssignNext(off, Box::new(rhs.strip_loc())),
}
}
}
#[derive(Clone, Debug)]
struct VariableMetadata {
offset: usize,
size: usize,
// FIXME: this should be able to be borrowed
var: Variable,
}
#[derive(Clone, Debug)]
struct Context<'a> {
dimensions: &'a [datamodel::Dimension],
model_name: &'a str,
ident: &'a str,
active_dimension: Option<Vec<datamodel::Dimension>>,
active_subscript: Option<Vec<&'a str>>,
metadata: &'a HashMap<Ident, HashMap<Ident, VariableMetadata>>,
module_models: &'a HashMap<Ident, HashMap<Ident, Ident>>,
is_initial: bool,
inputs: &'a BTreeSet<Ident>,
}
impl<'a> Context<'a> {
fn get_offset(&self, ident: &str) -> Result<usize> {
self.get_submodel_offset(self.model_name, ident, false)
}
/// get_base_offset ignores arrays and should only be used from Var::new and Expr::Subscript
fn get_base_offset(&self, ident: &str) -> Result<usize> {
self.get_submodel_offset(self.model_name, ident, true)
}
fn get_metadata(&self, ident: &str) -> Result<&VariableMetadata> {
self.get_submodel_metadata(self.model_name, ident)
}
fn get_implicit_subscripts(&self, dims: &[Dimension], ident: &str) -> Result<Vec<&str>> {
if self.active_dimension.is_none() {
return sim_err!(ArrayReferenceNeedsExplicitSubscripts, ident.to_owned());
}
let active_dims = self.active_dimension.as_ref().unwrap();
let active_subscripts = self.active_subscript.as_ref().unwrap();
assert_eq!(active_dims.len(), active_subscripts.len());
// if we need more dimensions than are implicit, that's an error
if dims.len() > active_dims.len() {
return sim_err!(MismatchedDimensions, ident.to_owned());
}
// goal: if this is a valid equation, dims will be a subset of active_dims (order preserving)
let mut subscripts: Vec<&str> = Vec::with_capacity(dims.len());
let mut active_off = 0;
for dim in dims.iter() {
while active_off < active_dims.len() {
let off = active_off;
active_off += 1;
let candidate = &active_dims[off];
if candidate.name == dim.name {
subscripts.push(active_subscripts[off]);
break;
}
}
}
if subscripts.len() != dims.len() {
return sim_err!(MismatchedDimensions, ident.to_owned());
}
Ok(subscripts)
}
fn get_implicit_subscript_off(&self, dims: &[Dimension], ident: &str) -> Result<usize> {
let subscripts = self.get_implicit_subscripts(dims, ident)?;
let off = dims
.iter()
.zip(subscripts)
.fold(0_usize, |acc, (dim, subscript)| {
acc * dim.elements.len() + dim.get_offset(subscript).unwrap()
});
Ok(off)
}
fn get_dimension_name_subscript(&self, dim_name: &str) -> Option<usize> {
let active_dims = self.active_dimension.as_ref()?;
let active_subscripts = self.active_subscript.as_ref().unwrap();
for (dim, subscript) in active_dims.iter().zip(active_subscripts) {
if dim.name == dim_name {
return dim.get_offset(subscript);
}
}
None
}
fn get_submodel_metadata(&self, model: &str, ident: &str) -> Result<&VariableMetadata> {
let metadata = &self.metadata[model];
if let Some(pos) = ident.find('·') {
let submodel_module_name = &ident[..pos];
let submodel_name = &self.module_models[model][submodel_module_name];
let submodel_var = &ident[pos + '·'.len_utf8()..];
self.get_submodel_metadata(submodel_name, submodel_var)
} else {
Ok(&metadata[ident])
}
}
fn get_submodel_offset(&self, model: &str, ident: &str, ignore_arrays: bool) -> Result<usize> {
let metadata = &self.metadata[model];
if let Some(pos) = ident.find('·') {
let submodel_module_name = &ident[..pos];
let submodel_name = &self.module_models[model][submodel_module_name];
let submodel_var = &ident[pos + '·'.len_utf8()..];
let submodel_off = metadata[submodel_module_name].offset;
Ok(submodel_off
+ self.get_submodel_offset(submodel_name, submodel_var, ignore_arrays)?)
} else if !ignore_arrays {
if !metadata.contains_key(ident) {
return sim_err!(DoesNotExist);
}
if let Some(dims) = metadata[ident].var.get_dimensions() {
let off = self.get_implicit_subscript_off(dims, ident)?;
Ok(metadata[ident].offset + off)
} else {
Ok(metadata[ident].offset)
}
} else {
Ok(metadata[ident].offset)
}
}
fn lower(&self, expr: &ast::Expr) -> Result<Expr> {
let expr = match expr {
ast::Expr::Const(_, n, loc) => Expr::Const(*n, *loc),
ast::Expr::Var(id, loc) => {
if let Some((off, _)) = self
.inputs
.iter()
.enumerate()
.find(|(_, input)| id == *input)
{
Expr::ModuleInput(off, *loc)
} else {
match self.get_offset(id) {
Ok(off) => Expr::Var(off, *loc),
Err(err) => {
return Err(err);
}
}
}
}
ast::Expr::App(builtin, loc) => {
use crate::builtins::BuiltinFn as BFn;
let builtin: BuiltinFn = match builtin {
BFn::Lookup(id, expr, loc) => {
BuiltinFn::Lookup(id.clone(), Box::new(self.lower(expr)?), *loc)
}
BFn::Abs(a) => BuiltinFn::Abs(Box::new(self.lower(a)?)),
BFn::Arccos(a) => BuiltinFn::Arccos(Box::new(self.lower(a)?)),
BFn::Arcsin(a) => BuiltinFn::Arcsin(Box::new(self.lower(a)?)),
BFn::Arctan(a) => BuiltinFn::Arctan(Box::new(self.lower(a)?)),
BFn::Cos(a) => BuiltinFn::Cos(Box::new(self.lower(a)?)),
BFn::Exp(a) => BuiltinFn::Exp(Box::new(self.lower(a)?)),
BFn::Inf => BuiltinFn::Inf,
BFn::Int(a) => BuiltinFn::Int(Box::new(self.lower(a)?)),
BFn::IsModuleInput(id, loc) => BuiltinFn::IsModuleInput(id.clone(), *loc),
BFn::Ln(a) => BuiltinFn::Ln(Box::new(self.lower(a)?)),
BFn::Log10(a) => BuiltinFn::Log10(Box::new(self.lower(a)?)),
BFn::Max(a, b) => {
BuiltinFn::Max(Box::new(self.lower(a)?), Box::new(self.lower(b)?))
}
BFn::Mean(args) => {
let args = args
.iter()
.map(|arg| self.lower(arg))
.collect::<Result<Vec<Expr>>>();
BuiltinFn::Mean(args?)
}
BFn::Min(a, b) => {
BuiltinFn::Min(Box::new(self.lower(a)?), Box::new(self.lower(b)?))
}
BFn::Pi => BuiltinFn::Pi,
BFn::Pulse(a, b, c) => {
let c = match c {
Some(c) => Some(Box::new(self.lower(c)?)),
None => None,
};
BuiltinFn::Pulse(Box::new(self.lower(a)?), Box::new(self.lower(b)?), c)
}
BFn::Ramp(a, b, c) => {
let c = match c {
Some(c) => Some(Box::new(self.lower(c)?)),
None => None,
};
BuiltinFn::Ramp(Box::new(self.lower(a)?), Box::new(self.lower(b)?), c)
}
BFn::SafeDiv(a, b, c) => {
let c = match c {
Some(c) => Some(Box::new(self.lower(c)?)),
None => None,
};
BuiltinFn::SafeDiv(Box::new(self.lower(a)?), Box::new(self.lower(b)?), c)
}
BFn::Sin(a) => BuiltinFn::Sin(Box::new(self.lower(a)?)),
BFn::Sqrt(a) => BuiltinFn::Sqrt(Box::new(self.lower(a)?)),
BFn::Step(a, b) => {
BuiltinFn::Step(Box::new(self.lower(a)?), Box::new(self.lower(b)?))
}
BFn::Tan(a) => BuiltinFn::Tan(Box::new(self.lower(a)?)),
BFn::Time => BuiltinFn::Time,
BFn::TimeStep => BuiltinFn::TimeStep,
BFn::StartTime => BuiltinFn::StartTime,
BFn::FinalTime => BuiltinFn::FinalTime,
};
Expr::App(builtin, *loc)
}
ast::Expr::Subscript(id, args, loc) => {
let off = self.get_base_offset(id)?;
let metadata = self.get_metadata(id)?;
let dims = metadata.var.get_dimensions().unwrap();
if args.len() != dims.len() {
return sim_err!(MismatchedDimensions, id.clone());
}
let args = args
.iter()
.enumerate()
.map(|(i, arg)| {
if let ast::Expr::Var(ident, loc) = arg {
let dim = &dims[i];
// we need to check to make sure that any explicit subscript names are
// converted to offsets here and not passed to self.lower
if let Some(subscript_off) = dim.get_offset(ident) {
Expr::Const((subscript_off + 1) as f64, *loc)
} else if let Some(subscript_off) =
self.get_dimension_name_subscript(ident)
{
// some modelers do `Variable[SubscriptName]` in their A2A equations
Expr::Const((subscript_off + 1) as f64, *loc)
} else {
self.lower(&args[0]).unwrap()
}
} else {
self.lower(&args[0]).unwrap()
}
})
.collect();
let bounds = dims.iter().map(|dim| dim.elements.len()).collect();
Expr::Subscript(off, args, bounds, *loc)
}
ast::Expr::Op1(op, l, loc) => {
let l = self.lower(l)?;
match op {
ast::UnaryOp::Negative => Expr::Op2(
BinaryOp::Sub,
Box::new(Expr::Const(0.0, *loc)),
Box::new(l),
*loc,
),
ast::UnaryOp::Positive => l,
ast::UnaryOp::Not => Expr::Op1(UnaryOp::Not, Box::new(l), *loc),
}
}
ast::Expr::Op2(op, l, r, loc) => {
let l = self.lower(l)?;
let r = self.lower(r)?;
let op = match op {
ast::BinaryOp::Add => BinaryOp::Add,
ast::BinaryOp::Sub => BinaryOp::Sub,
ast::BinaryOp::Exp => BinaryOp::Exp,
ast::BinaryOp::Mul => BinaryOp::Mul,
ast::BinaryOp::Div => BinaryOp::Div,
ast::BinaryOp::Mod => BinaryOp::Mod,
ast::BinaryOp::Gt => BinaryOp::Gt,
ast::BinaryOp::Gte => BinaryOp::Gte,
ast::BinaryOp::Lt => BinaryOp::Lt,
ast::BinaryOp::Lte => BinaryOp::Lte,
ast::BinaryOp::Eq => BinaryOp::Eq,
ast::BinaryOp::Neq => BinaryOp::Neq,
ast::BinaryOp::And => BinaryOp::And,
ast::BinaryOp::Or => BinaryOp::Or,
};
Expr::Op2(op, Box::new(l), Box::new(r), *loc)
}
ast::Expr::If(cond, t, f, loc) => {
let cond = self.lower(cond)?;
let t = self.lower(t)?;
let f = self.lower(f)?;
Expr::If(Box::new(cond), Box::new(t), Box::new(f), *loc)
}
};
Ok(expr)
}
fn fold_flows(&self, flows: &[String]) -> Option<Expr> {
if flows.is_empty() {
return None;
}
let mut loads = flows
.iter()
.map(|flow| Expr::Var(self.get_offset(flow).unwrap(), Loc::default()));
let first = loads.next().unwrap();
Some(loads.fold(first, |acc, flow| {
Expr::Op2(BinaryOp::Add, Box::new(acc), Box::new(flow), Loc::default())
}))
}
fn build_stock_update_expr(&self, stock_off: usize, var: &Variable) -> Expr {
if let Variable::Stock {
inflows, outflows, ..
} = var
{
// TODO: simplify the expressions we generate
let inflows = match self.fold_flows(inflows) {
None => Expr::Const(0.0, Loc::default()),
Some(flows) => flows,
};
let outflows = match self.fold_flows(outflows) {
None => Expr::Const(0.0, Loc::default()),
Some(flows) => flows,
};
let dt_update = Expr::Op2(
BinaryOp::Mul,
Box::new(Expr::Op2(
BinaryOp::Sub,
Box::new(inflows),
Box::new(outflows),
Loc::default(),
)),
Box::new(Expr::Dt(Loc::default())),
Loc::default(),
);
Expr::Op2(
BinaryOp::Add,
Box::new(Expr::Var(stock_off, Loc::default())),
Box::new(dt_update),
Loc::default(),
)
} else {
panic!(
"build_stock_update_expr called with non-stock {}",
var.ident()
);
}
}
}
#[test]
fn test_lower() {
let input = {
use ast::BinaryOp::*;
use ast::Expr::*;
Box::new(If(
Box::new(Op2(
And,
Box::new(Var("true_input".to_string(), Loc::default())),
Box::new(Var("false_input".to_string(), Loc::default())),
Loc::default(),
)),
Box::new(Const("1".to_string(), 1.0, Loc::default())),
Box::new(Const("0".to_string(), 0.0, Loc::default())),
Loc::default(),
))
};
let inputs = &BTreeSet::new();
let module_models: HashMap<Ident, HashMap<Ident, Ident>> = HashMap::new();
let mut metadata: HashMap<String, VariableMetadata> = HashMap::new();
metadata.insert(
"true_input".to_string(),
VariableMetadata {
offset: 7,
size: 1,
var: Variable::Var {
ident: "".to_string(),
ast: None,
eqn: None,
units: None,
table: None,
non_negative: false,
is_flow: false,
is_table_only: false,
errors: vec![],
unit_errors: vec![],
},
},
);
metadata.insert(
"false_input".to_string(),
VariableMetadata {
offset: 8,
size: 1,
var: Variable::Var {
ident: "".to_string(),
ast: None,
eqn: None,
units: None,
table: None,
non_negative: false,
is_flow: false,
is_table_only: false,
errors: vec![],
unit_errors: vec![],
},
},
);
let mut metadata2 = HashMap::new();
metadata2.insert("main".to_string(), metadata);
let dimensions: Vec<datamodel::Dimension> = vec![];
let context = Context {
dimensions: &dimensions,
model_name: "main",
ident: "test",
active_dimension: None,
active_subscript: None,
metadata: &metadata2,
module_models: &module_models,
is_initial: false,
inputs,
};
let expected = Expr::If(
Box::new(Expr::Op2(
BinaryOp::And,
Box::new(Expr::Var(7, Loc::default())),
Box::new(Expr::Var(8, Loc::default())),
Loc::default(),
)),
Box::new(Expr::Const(1.0, Loc::default())),
Box::new(Expr::Const(0.0, Loc::default())),
Loc::default(),
);
let output = context.lower(&input);
assert!(output.is_ok());
assert_eq!(expected, output.unwrap());
let input = {
use ast::BinaryOp::*;
use ast::Expr::*;
Box::new(If(
Box::new(Op2(
Or,
Box::new(Var("true_input".to_string(), Loc::default())),
Box::new(Var("false_input".to_string(), Loc::default())),
Loc::default(),
)),
Box::new(Const("1".to_string(), 1.0, Loc::default())),
Box::new(Const("0".to_string(), 0.0, Loc::default())),
Loc::default(),
))
};
let inputs = &BTreeSet::new();
let module_models: HashMap<Ident, HashMap<Ident, Ident>> = HashMap::new();
let mut metadata: HashMap<String, VariableMetadata> = HashMap::new();
metadata.insert(
"true_input".to_string(),
VariableMetadata {
offset: 7,
size: 1,
var: Variable::Var {
ident: "".to_string(),
ast: None,
eqn: None,
units: None,
table: None,
non_negative: false,
is_flow: false,
is_table_only: false,
errors: vec![],
unit_errors: vec![],
},
},
);
metadata.insert(
"false_input".to_string(),
VariableMetadata {
offset: 8,
size: 1,
var: Variable::Var {
ident: "".to_string(),
ast: None,
eqn: None,
units: None,
table: None,
non_negative: false,
is_flow: false,
is_table_only: false,
errors: vec![],
unit_errors: vec![],
},
},
);
let mut metadata2 = HashMap::new();
metadata2.insert("main".to_string(), metadata);
let context = Context {
dimensions: &dimensions,
model_name: "main",
ident: "test",
active_dimension: None,
active_subscript: None,
metadata: &metadata2,
module_models: &module_models,
is_initial: false,
inputs,
};
let expected = Expr::If(
Box::new(Expr::Op2(
BinaryOp::Or,
Box::new(Expr::Var(7, Loc::default())),
Box::new(Expr::Var(8, Loc::default())),
Loc::default(),
)),
Box::new(Expr::Const(1.0, Loc::default())),
Box::new(Expr::Const(0.0, Loc::default())),
Loc::default(),
);
let output = context.lower(&input);
assert!(output.is_ok());
assert_eq!(expected, output.unwrap());
}
#[derive(Clone, Debug, PartialEq)]
pub struct Var {
ident: Ident,
ast: Vec<Expr>,
}
#[test]
fn test_fold_flows() {
let inputs = &BTreeSet::new();
let module_models: HashMap<Ident, HashMap<Ident, Ident>> = HashMap::new();
let mut metadata: HashMap<String, VariableMetadata> = HashMap::new();
metadata.insert(
"a".to_string(),
VariableMetadata {
offset: 1,
size: 1,
var: Variable::Var {
ident: "".to_string(),
ast: None,
eqn: None,
units: None,
table: None,
non_negative: false,
is_flow: false,
is_table_only: false,
errors: vec![],
unit_errors: vec![],
},
},
);
metadata.insert(
"b".to_string(),
VariableMetadata {
offset: 2,
size: 1,
var: Variable::Var {
ident: "".to_string(),
ast: None,
eqn: None,
units: None,
table: None,
non_negative: false,
is_flow: false,
is_table_only: false,
errors: vec![],
unit_errors: vec![],
},
},
);
metadata.insert(
"c".to_string(),
VariableMetadata {
offset: 3,
size: 1,
var: Variable::Var {
ident: "".to_string(),
ast: None,
eqn: None,
units: None,
table: None,
non_negative: false,
is_flow: false,
is_table_only: false,
errors: vec![],
unit_errors: vec![],
},
},
);
metadata.insert(
"d".to_string(),
VariableMetadata {
offset: 4,
size: 1,
var: Variable::Var {
ident: "".to_string(),
ast: None,
eqn: None,
units: None,
table: None,
non_negative: false,
is_flow: false,
is_table_only: false,
errors: vec![],
unit_errors: vec![],
},
},
);
let mut metadata2 = HashMap::new();
metadata2.insert("main".to_string(), metadata);
let dimensions: Vec<datamodel::Dimension> = vec![];
let ctx = Context {
dimensions: &dimensions,
model_name: "main",
ident: "test",
active_dimension: None,
active_subscript: None,
metadata: &metadata2,
module_models: &module_models,
is_initial: false,
inputs,
};
assert_eq!(None, ctx.fold_flows(&[]));
assert_eq!(
Some(Expr::Var(1, Loc::default())),
ctx.fold_flows(&["a".to_string()])
);
assert_eq!(
Some(Expr::Op2(
BinaryOp::Add,
Box::new(Expr::Var(1, Loc::default())),
Box::new(Expr::Var(4, Loc::default())),
Loc::default(),
)),
ctx.fold_flows(&["a".to_string(), "d".to_string()])
);
}
impl Var {
fn new(ctx: &Context, var: &Variable) -> Result<Self> {
// if this variable is overriden by a module input, our expression is easy
let ast: Vec<Expr> = if let Some((off, ident)) = ctx
.inputs
.iter()
.enumerate()
.find(|(_i, n)| *n == var.ident())
{
vec![Expr::AssignCurr(
ctx.get_offset(ident)?,
Box::new(Expr::ModuleInput(off, Loc::default())),
)]
} else {
match var {
Variable::Module {
ident,
model_name,
inputs,
..
} => {
let mut inputs = inputs.clone();
inputs.sort_unstable_by(|a, b| a.dst.partial_cmp(&b.dst).unwrap());
let inputs: Vec<Expr> = inputs
.into_iter()
.map(|mi| Expr::Var(ctx.get_offset(&mi.src).unwrap(), Loc::default()))
.collect();
vec![Expr::EvalModule(ident.clone(), model_name.clone(), inputs)]
}
Variable::Stock { ast, .. } => {
let off = ctx.get_base_offset(var.ident())?;
if ctx.is_initial {
if ast.is_none() {
return sim_err!(EmptyEquation, var.ident().to_string());
}
match ast.as_ref().unwrap() {
Ast::Scalar(ast) => {
vec![Expr::AssignCurr(off, Box::new(ctx.lower(ast)?))]
}
Ast::ApplyToAll(dims, ast) => {
let exprs: Result<Vec<Expr>> = SubscriptIterator::new(dims)
.enumerate()
.map(|(i, subscripts)| {
let mut ctx = ctx.clone();
ctx.active_dimension = Some(dims.clone());
ctx.active_subscript = Some(subscripts);
ctx.lower(ast)
.map(|ast| Expr::AssignCurr(off + i, Box::new(ast)))
})
.collect();
exprs?
}
Ast::Arrayed(dims, elements) => {
let exprs: Result<Vec<Expr>> = SubscriptIterator::new(dims)
.enumerate()
.map(|(i, subscripts)| {
let subscript_str = subscripts.join(",");
let ast = &elements[&subscript_str];
let mut ctx = ctx.clone();
ctx.active_dimension = Some(dims.clone());
ctx.active_subscript = Some(subscripts);
ctx.lower(ast)
.map(|ast| Expr::AssignCurr(off + i, Box::new(ast)))
})
.collect();
exprs?
}
}
} else {
match ast.as_ref().unwrap() {
Ast::Scalar(_) => vec![Expr::AssignNext(
off,
Box::new(ctx.build_stock_update_expr(off, var)),
)],
Ast::ApplyToAll(dims, _) | Ast::Arrayed(dims, _) => {
let exprs: Result<Vec<Expr>> = SubscriptIterator::new(dims)
.enumerate()
.map(|(i, subscripts)| {
let mut ctx = ctx.clone();
ctx.active_dimension = Some(dims.clone());
ctx.active_subscript = Some(subscripts);
// when building the stock update expression, we need
// the specific index of this subscript, not the base offset
let update_expr = ctx.build_stock_update_expr(
ctx.get_offset(var.ident())?,
var,
);
Ok(Expr::AssignNext(off + i, Box::new(update_expr)))
})
.collect();
exprs?
}
}
}
}
Variable::Var {
ident, table, ast, ..
} => {
let off = ctx.get_base_offset(var.ident())?;
if ast.is_none() {
return sim_err!(EmptyEquation, var.ident().to_string());
}
match ast.as_ref().unwrap() {
Ast::Scalar(ast) => {
let expr = ctx.lower(ast)?;
let expr = if table.is_some() {
let loc = expr.get_loc();
Expr::App(
BuiltinFn::Lookup(ident.clone(), Box::new(expr), loc),
loc,
)
} else {
expr
};
vec![Expr::AssignCurr(off, Box::new(expr))]
}
Ast::ApplyToAll(dims, ast) => {
let exprs: Result<Vec<Expr>> = SubscriptIterator::new(dims)
.enumerate()
.map(|(i, subscripts)| {
let mut ctx = ctx.clone();
ctx.active_dimension = Some(dims.clone());
ctx.active_subscript = Some(subscripts);
ctx.lower(ast)
.map(|ast| Expr::AssignCurr(off + i, Box::new(ast)))
})
.collect();
exprs?
}
Ast::Arrayed(dims, elements) => {
let exprs: Result<Vec<Expr>> = SubscriptIterator::new(dims)
.enumerate()
.map(|(i, subscripts)| {
let subscript_str = subscripts.join(",");
let ast = &elements[&subscript_str];
let mut ctx = ctx.clone();
ctx.active_dimension = Some(dims.clone());
ctx.active_subscript = Some(subscripts);
ctx.lower(ast)
.map(|ast| Expr::AssignCurr(off + i, Box::new(ast)))
})
.collect();
exprs?
}
}
}
}
};
Ok(Var {
ident: var.ident().to_owned(),
ast,
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Module {
pub(crate) ident: Ident,
inputs: HashSet<Ident>,
n_slots: usize, // number of f64s we need storage for
pub(crate) runlist_initials: Vec<Expr>,
pub(crate) runlist_flows: Vec<Expr>,
pub(crate) runlist_stocks: Vec<Expr>,
pub(crate) offsets: HashMap<Ident, HashMap<Ident, (usize, usize)>>,
pub(crate) runlist_order: Vec<Ident>,
tables: HashMap<Ident, Table>,
}
// calculate a mapping of module variable name -> module model name
fn calc_module_model_map(
project: &Project,
model_name: &str,
) -> HashMap<Ident, HashMap<Ident, Ident>> {
let mut all_models: HashMap<Ident, HashMap<Ident, Ident>> = HashMap::new();
let model = Rc::clone(&project.models[model_name]);
let var_names: Vec<&str> = {
let mut var_names: Vec<_> = model.variables.keys().map(|s| s.as_str()).collect();
var_names.sort_unstable();
var_names
};
let mut current_mapping: HashMap<Ident, Ident> = HashMap::new();
for ident in var_names.iter() {
if let Variable::Module { model_name, .. } = &model.variables[*ident] {
current_mapping.insert(ident.to_string(), model_name.clone());
let all_sub_models = calc_module_model_map(project, model_name);
all_models.extend(all_sub_models);
};
}
all_models.insert(model_name.to_string(), current_mapping);
all_models
}
// TODO: this should memoize
fn build_metadata(
project: &Project,
model_name: &str,
is_root: bool,
) -> HashMap<Ident, HashMap<Ident, VariableMetadata>> {
let mut all_offsets: HashMap<Ident, HashMap<Ident, VariableMetadata>> = HashMap::new();
let mut offsets: HashMap<Ident, VariableMetadata> = HashMap::new();
let mut i = 0;
if is_root {
offsets.insert(
"time".to_string(),
VariableMetadata {
offset: 0,
size: 1,
var: Variable::Var {
ident: "time".to_string(),
ast: None,
eqn: None,
units: None,
table: None,
non_negative: false,
is_flow: false,
is_table_only: false,
errors: vec![],
unit_errors: vec![],
},
},
);
offsets.insert(
"dt".to_string(),
VariableMetadata {
offset: 1,
size: 1,
var: Variable::Var {
ident: "dt".to_string(),
ast: None,
eqn: None,
units: None,
table: None,
non_negative: false,
is_flow: false,
is_table_only: false,
errors: vec![],
unit_errors: vec![],
},
},
);
offsets.insert(
"initial_time".to_string(),
VariableMetadata {
offset: 2,
size: 1,
var: Variable::Var {
ident: "initial_time".to_string(),
ast: None,
eqn: None,
units: None,
table: None,
non_negative: false,
is_flow: false,
is_table_only: false,
errors: vec![],
unit_errors: vec![],
},
},
);
offsets.insert(
"final_time".to_string(),
VariableMetadata {
offset: 3,
size: 1,
var: Variable::Var {
ident: "final_time".to_string(),
ast: None,
eqn: None,
units: None,
table: None,
non_negative: false,
is_flow: false,
is_table_only: false,
errors: vec![],
unit_errors: vec![],
},
},
);
i += IMPLICIT_VAR_COUNT;
}
let model = Rc::clone(&project.models[model_name]);
let var_names: Vec<&str> = {
let mut var_names: Vec<_> = model.variables.keys().map(|s| s.as_str()).collect();
var_names.sort_unstable();
var_names
};
for ident in var_names.iter() {
let size = if let Variable::Module { model_name, .. } = &model.variables[*ident] {
let all_sub_offsets = build_metadata(project, model_name, false);
let sub_offsets = &all_sub_offsets[model_name];
let sub_size: usize = sub_offsets.values().map(|metadata| metadata.size).sum();
all_offsets.extend(all_sub_offsets);
sub_size
} else if let Some(Ast::ApplyToAll(dims, _)) = model.variables[*ident].ast() {
dims.iter().map(|dim| dim.elements.len()).product()
} else if let Some(Ast::Arrayed(dims, _)) = model.variables[*ident].ast() {
dims.iter().map(|dim| dim.elements.len()).product()
} else {
1
};
offsets.insert(
(*ident).to_owned(),
VariableMetadata {
offset: i,
size,
var: model.variables[*ident].clone(),
},
);
i += size;
}
all_offsets.insert(model_name.to_string(), offsets);
all_offsets
}
/// calc_flattened_offsets generates a mapping from name to offset
/// for all individual variables and subscripts in a model, including
/// in submodels. For example a variable named "offset" in a module
/// instantiated with name "sector" will produce the key "sector.offset".
fn calc_flattened_offsets(project: &Project, model_name: &str) -> HashMap<Ident, (usize, usize)> {
let is_root = model_name == "main";
let mut offsets: HashMap<Ident, (usize, usize)> = HashMap::new();
let mut i = 0;
if is_root {
offsets.insert("time".to_string(), (0, 1));
offsets.insert("dt".to_string(), (1, 1));
offsets.insert("initial_time".to_string(), (2, 1));
offsets.insert("final_time".to_string(), (3, 1));
i += IMPLICIT_VAR_COUNT;
}
let model = Rc::clone(&project.models[model_name]);
let var_names: Vec<&str> = {
let mut var_names: Vec<_> = model.variables.keys().map(|s| s.as_str()).collect();
var_names.sort_unstable();
var_names
};
for ident in var_names.iter() {
let size = if let Variable::Module { model_name, .. } = &model.variables[*ident] {
let sub_offsets = calc_flattened_offsets(project, model_name);
let mut sub_var_names: Vec<&str> = sub_offsets.keys().map(|v| v.as_str()).collect();
sub_var_names.sort_unstable();
for sub_name in sub_var_names {
let (sub_off, sub_size) = sub_offsets[sub_name];
offsets.insert(
format!("{}.{}", quoteize(ident), quoteize(sub_name)),
(i + sub_off, sub_size),
);
}
let sub_size: usize = sub_offsets.iter().map(|(_, (_, size))| size).sum();
sub_size
} else if let Some(Ast::ApplyToAll(dims, _)) = &model.variables[*ident].ast() {
for (j, subscripts) in SubscriptIterator::new(dims).enumerate() {
let subscript = subscripts.join(",");
let subscripted_ident = format!("{}[{}]", quoteize(ident), subscript);
offsets.insert(subscripted_ident, (i + j, 1));
}
dims.iter().map(|dim| dim.elements.len()).product()
} else if let Some(Ast::Arrayed(dims, _)) = &model.variables[*ident].ast() {
for (j, subscripts) in SubscriptIterator::new(dims).enumerate() {
let subscript = subscripts.join(",");
let subscripted_ident = format!("{}[{}]", quoteize(ident), subscript);
offsets.insert(subscripted_ident, (i + j, 1));
}
dims.iter().map(|dim| dim.elements.len()).product()
} else {
offsets.insert(quoteize(ident), (i, 1));
1
};
i += size;
}
offsets
}
fn calc_flattened_order(sim: &Simulation, model_name: &str) -> Vec<Ident> {
let is_root = model_name == "main";
let module = &sim.modules[model_name];
let mut offsets: Vec<Ident> = Vec::with_capacity(module.runlist_order.len() + 1);
if is_root {
offsets.push("time".to_owned());
}
for ident in module.runlist_order.iter() {
// FIXME: this isnt' quite right (assumes no regular var has same name as module)
if sim.modules.get(ident).is_some() {
let sub_var_names = calc_flattened_order(sim, ident);
for sub_name in sub_var_names.iter() {
offsets.push(format!("{}.{}", quoteize(ident), quoteize(sub_name)));
}
} else {
offsets.push(quoteize(ident));
}
}
offsets
}
fn calc_n_slots(
all_metadata: &HashMap<Ident, HashMap<Ident, VariableMetadata>>,
model_name: &str,
) -> usize {
let metadata = &all_metadata[model_name];
metadata.values().map(|v| v.size).sum()
}
impl Module {
fn new(
project: &Project,
model: Rc<ModelStage1>,
inputs: &BTreeSet<Ident>,
is_root: bool,
) -> Result<Self> {
let inputs_set = inputs.iter().cloned().collect::<BTreeSet<_>>();
let instantiation = model
.instantiations
.as_ref()
.and_then(|instantiations| instantiations.get(&inputs_set))
.ok_or(Error {
kind: ErrorKind::Simulation,
code: ErrorCode::NotSimulatable,
details: Some(model.name.clone()),
})?;
// TODO: eventually we should try to simulate subsets of the model in the face of errors
if model.errors.is_some() && !model.errors.as_ref().unwrap().is_empty() {
return sim_err!(NotSimulatable, model.name.clone());
}
let model_name: &str = &model.name;
let metadata = build_metadata(project, model_name, is_root);
let n_slots = calc_n_slots(&metadata, model_name);
let var_names: Vec<&str> = {
let mut var_names: Vec<_> = model.variables.keys().map(|s| s.as_str()).collect();
var_names.sort_unstable();
var_names
};
let module_models = calc_module_model_map(project, model_name);
let build_var = |ident, is_initial| {
Var::new(
&Context {
dimensions: &project.datamodel.dimensions,
model_name,
ident,
active_dimension: None,
active_subscript: None,
metadata: &metadata,
module_models: &module_models,
is_initial,
inputs,
},
&model.variables[ident],
)
};
let runlist_initials = instantiation
.runlist_initials
.iter()
.map(|ident| build_var(ident, true))
.collect::<Result<Vec<Var>>>()?;
let runlist_flows = instantiation
.runlist_flows
.iter()
.map(|ident| build_var(ident, false))
.collect::<Result<Vec<Var>>>()?;
let runlist_stocks = instantiation
.runlist_stocks
.iter()
.map(|ident| build_var(ident, false))
.collect::<Result<Vec<Var>>>()?;
let mut runlist_order = Vec::with_capacity(runlist_flows.len() + runlist_stocks.len());
runlist_order.extend(runlist_flows.iter().map(|v| v.ident.clone()));
runlist_order.extend(runlist_stocks.iter().map(|v| v.ident.clone()));
// flatten out the variables so that we're just dealing with lists of expressions
let runlist_initials = runlist_initials.into_iter().flat_map(|v| v.ast).collect();
let runlist_flows = runlist_flows.into_iter().flat_map(|v| v.ast).collect();
let runlist_stocks = runlist_stocks.into_iter().flat_map(|v| v.ast).collect();
let tables: Result<HashMap<String, Table>> = var_names
.iter()
.map(|id| (id, &model.variables[*id]))
.filter(|(_, v)| v.table().is_some())
.map(|(id, v)| (id, Table::new(id, v.table().unwrap())))
.map(|(id, t)| match t {
Ok(table) => Ok((id.to_string(), table)),
Err(err) => Err(err),
})
.collect();
let tables = tables?;
let offsets = metadata
.into_iter()
.map(|(k, v)| {
(
k,
v.iter()
.map(|(k, v)| (k.clone(), (v.offset, v.size)))
.collect(),
)
})
.collect();
Ok(Module {
ident: model_name.to_string(),
inputs: inputs_set.into_iter().collect(),
n_slots,
runlist_initials,
runlist_flows,
runlist_stocks,
offsets,
runlist_order,
tables,
})
}
pub fn compile(&self) -> Result<CompiledModule> {
Compiler::new(self).compile()
}
}
struct Compiler<'module> {
module: &'module Module,
module_decls: Vec<ModuleDeclaration>,
graphical_functions: Vec<Vec<(f64, f64)>>,
curr_code: ByteCodeBuilder,
}
impl<'module> Compiler<'module> {
fn new(module: &'module Module) -> Compiler {
Compiler {
module,
module_decls: vec![],
graphical_functions: vec![],
curr_code: ByteCodeBuilder::default(),
}
}
fn walk(&mut self, exprs: &[Expr]) -> Result<ByteCode> {
for expr in exprs.iter() {
self.walk_expr(expr)?;
}
self.push(Opcode::Ret);
let curr = std::mem::take(&mut self.curr_code);
Ok(curr.finish())
}
fn walk_expr(&mut self, expr: &Expr) -> Result<Option<()>> {
let result = match expr {
Expr::Const(value, _) => {
let id = self.curr_code.intern_literal(*value);
self.push(Opcode::LoadConstant { id });
Some(())
}
Expr::Var(off, _) => {
self.push(Opcode::LoadVar {
off: *off as VariableOffset,
});
Some(())
}
Expr::Subscript(off, indices, bounds, _) => {
for (i, expr) in indices.iter().enumerate() {
self.walk_expr(expr).unwrap().unwrap();
let bounds = bounds[i] as VariableOffset;
self.push(Opcode::PushSubscriptIndex { bounds });
}
assert!(indices.len() == bounds.len());
self.push(Opcode::LoadSubscript {
off: *off as VariableOffset,
});
Some(())
}
Expr::Dt(_) => {
self.push(Opcode::LoadGlobalVar {
off: DT_OFF as VariableOffset,
});
Some(())
}
Expr::App(builtin, _) => {
// lookups are special
if let BuiltinFn::Lookup(ident, index, _loc) = builtin {
let table = &self.module.tables[ident];
self.graphical_functions.push(table.data.clone());
let gf = (self.graphical_functions.len() - 1) as GraphicalFunctionId;
self.walk_expr(index)?.unwrap();
self.push(Opcode::Lookup { gf });
return Ok(Some(()));
};
// so are module builtins
if let BuiltinFn::IsModuleInput(ident, _loc) = builtin {
let id = if self.module.inputs.contains(ident) {
self.curr_code.intern_literal(1.0)
} else {
self.curr_code.intern_literal(0.0)
};
self.push(Opcode::LoadConstant { id });
return Ok(Some(()));
};
match builtin {
BuiltinFn::Time
| BuiltinFn::TimeStep
| BuiltinFn::StartTime
| BuiltinFn::FinalTime => {
let off = match builtin {
BuiltinFn::Time => TIME_OFF,
BuiltinFn::TimeStep => DT_OFF,
BuiltinFn::StartTime => INITIAL_TIME_OFF,
BuiltinFn::FinalTime => FINAL_TIME_OFF,
_ => unreachable!(),
} as u16;
self.push(Opcode::LoadGlobalVar { off });
return Ok(Some(()));
}
BuiltinFn::Lookup(_, _, _) | BuiltinFn::IsModuleInput(_, _) => unreachable!(),
BuiltinFn::Inf | BuiltinFn::Pi => {
let lit = match builtin {
BuiltinFn::Inf => std::f64::INFINITY,
BuiltinFn::Pi => std::f64::consts::PI,
_ => unreachable!(),
};
let id = self.curr_code.intern_literal(lit);
self.push(Opcode::LoadConstant { id });
return Ok(Some(()));
}
BuiltinFn::Abs(a)
| BuiltinFn::Arccos(a)
| BuiltinFn::Arcsin(a)
| BuiltinFn::Arctan(a)
| BuiltinFn::Cos(a)
| BuiltinFn::Exp(a)
| BuiltinFn::Int(a)
| BuiltinFn::Ln(a)
| BuiltinFn::Log10(a)
| BuiltinFn::Sin(a)
| BuiltinFn::Sqrt(a)
| BuiltinFn::Tan(a) => {
self.walk_expr(a)?.unwrap();
let id = self.curr_code.intern_literal(0.0);
self.push(Opcode::LoadConstant { id });
self.push(Opcode::LoadConstant { id });
}
BuiltinFn::Max(a, b) | BuiltinFn::Min(a, b) | BuiltinFn::Step(a, b) => {
self.walk_expr(a)?.unwrap();
self.walk_expr(b)?.unwrap();
let id = self.curr_code.intern_literal(0.0);
self.push(Opcode::LoadConstant { id });
}
BuiltinFn::Pulse(a, b, c) => {
self.walk_expr(a)?.unwrap();
self.walk_expr(b)?.unwrap();
if c.is_some() {
self.walk_expr(c.as_ref().unwrap())?.unwrap()
} else {
let id = self.curr_code.intern_literal(0.0);
self.push(Opcode::LoadConstant { id });
};
}
BuiltinFn::Ramp(a, b, c) => {
self.walk_expr(a)?.unwrap();
self.walk_expr(b)?.unwrap();
if c.is_some() {
self.walk_expr(c.as_ref().unwrap())?.unwrap()
} else {
self.push(Opcode::LoadVar {
off: FINAL_TIME_OFF as u16,
});
};
}
BuiltinFn::SafeDiv(a, b, c) => {
self.walk_expr(a)?.unwrap();
self.walk_expr(b)?.unwrap();
let c = c.as_ref().map(|c| self.walk_expr(c).unwrap().unwrap());
if c.is_none() {
let id = self.curr_code.intern_literal(0.0);
self.push(Opcode::LoadConstant { id });
}
}
BuiltinFn::Mean(args) => {
let id = self.curr_code.intern_literal(0.0);
self.push(Opcode::LoadConstant { id });
for arg in args.iter() {
self.walk_expr(arg)?.unwrap();
self.push(Opcode::Op2 { op: Op2::Add });
}
let id = self.curr_code.intern_literal(args.len() as f64);
self.push(Opcode::LoadConstant { id });
self.push(Opcode::Op2 { op: Op2::Div });
return Ok(Some(()));
}
};
let func = match builtin {
BuiltinFn::Lookup(_, _, _) => unreachable!(),
BuiltinFn::Abs(_) => BuiltinId::Abs,
BuiltinFn::Arccos(_) => BuiltinId::Arccos,
BuiltinFn::Arcsin(_) => BuiltinId::Arcsin,
BuiltinFn::Arctan(_) => BuiltinId::Arctan,
BuiltinFn::Cos(_) => BuiltinId::Cos,
BuiltinFn::Exp(_) => BuiltinId::Exp,
BuiltinFn::Inf => BuiltinId::Inf,
BuiltinFn::Int(_) => BuiltinId::Int,
BuiltinFn::IsModuleInput(_, _) => unreachable!(),
BuiltinFn::Ln(_) => BuiltinId::Ln,
BuiltinFn::Log10(_) => BuiltinId::Log10,
BuiltinFn::Max(_, _) => BuiltinId::Max,
BuiltinFn::Mean(_) => unreachable!(),
BuiltinFn::Min(_, _) => BuiltinId::Min,
BuiltinFn::Pi => BuiltinId::Pi,
BuiltinFn::Pulse(_, _, _) => BuiltinId::Pulse,
BuiltinFn::Ramp(_, _, _) => BuiltinId::Ramp,
BuiltinFn::SafeDiv(_, _, _) => BuiltinId::SafeDiv,
BuiltinFn::Sin(_) => BuiltinId::Sin,
BuiltinFn::Sqrt(_) => BuiltinId::Sqrt,
BuiltinFn::Step(_, _) => BuiltinId::Step,
BuiltinFn::Tan(_) => BuiltinId::Tan,
// handled above; we exit early
BuiltinFn::Time
| BuiltinFn::TimeStep
| BuiltinFn::StartTime
| BuiltinFn::FinalTime => unreachable!(),
};
self.push(Opcode::Apply { func });
Some(())
}
Expr::EvalModule(ident, model_name, args) => {
for arg in args.iter() {
self.walk_expr(arg).unwrap().unwrap()
}
let module_offsets = &self.module.offsets[&self.module.ident];
self.module_decls.push(ModuleDeclaration {
model_name: model_name.clone(),
off: module_offsets[ident].0,
});
let id = (self.module_decls.len() - 1) as ModuleId;
self.push(Opcode::EvalModule {
id,
n_inputs: args.len() as u8,
});
None
}
Expr::ModuleInput(off, _) => {
self.push(Opcode::LoadModuleInput {
input: *off as ModuleInputOffset,
});
Some(())
}
Expr::Op2(op, lhs, rhs, _) => {
self.walk_expr(lhs)?.unwrap();
self.walk_expr(rhs)?.unwrap();
let opcode = match op {
BinaryOp::Add => Opcode::Op2 { op: Op2::Add },
BinaryOp::Sub => Opcode::Op2 { op: Op2::Sub },
BinaryOp::Exp => Opcode::Op2 { op: Op2::Exp },
BinaryOp::Mul => Opcode::Op2 { op: Op2::Mul },
BinaryOp::Div => Opcode::Op2 { op: Op2::Div },
BinaryOp::Mod => Opcode::Op2 { op: Op2::Mod },
BinaryOp::Gt => Opcode::Op2 { op: Op2::Gt },
BinaryOp::Gte => Opcode::Op2 { op: Op2::Gte },
BinaryOp::Lt => Opcode::Op2 { op: Op2::Lt },
BinaryOp::Lte => Opcode::Op2 { op: Op2::Lte },
BinaryOp::Eq => Opcode::Op2 { op: Op2::Eq },
BinaryOp::Neq => {
self.push(Opcode::Op2 { op: Op2::Eq });
Opcode::Not {}
}
BinaryOp::And => Opcode::Op2 { op: Op2::And },
BinaryOp::Or => Opcode::Op2 { op: Op2::Or },
};
self.push(opcode);
Some(())
}
Expr::Op1(op, rhs, _) => {
self.walk_expr(rhs)?.unwrap();
match op {
UnaryOp::Not => self.push(Opcode::Not {}),
};
Some(())
}
Expr::If(cond, t, f, _) => {
self.walk_expr(t)?.unwrap();
self.walk_expr(f)?.unwrap();
self.walk_expr(cond)?.unwrap();
self.push(Opcode::SetCond {});
self.push(Opcode::If {});
Some(())
}
Expr::AssignCurr(off, rhs) => {
self.walk_expr(rhs)?.unwrap();
self.push(Opcode::AssignCurr {
off: *off as VariableOffset,
});
None
}
Expr::AssignNext(off, rhs) => {
self.walk_expr(rhs)?.unwrap();
self.push(Opcode::AssignNext {
off: *off as VariableOffset,
});
None
}
};
Ok(result)
}
fn push(&mut self, op: Opcode) {
self.curr_code.push_opcode(op)
}
fn compile(mut self) -> Result<CompiledModule> {
let compiled_initials = Rc::new(self.walk(&self.module.runlist_initials)?);
let compiled_flows = Rc::new(self.walk(&self.module.runlist_flows)?);
let compiled_stocks = Rc::new(self.walk(&self.module.runlist_stocks)?);
Ok(CompiledModule {
ident: self.module.ident.clone(),
n_slots: self.module.n_slots,
context: Rc::new(ByteCodeContext {
graphical_functions: self.graphical_functions,
modules: self.module_decls,
}),
compiled_initials,
compiled_flows,
compiled_stocks,
})
}
}
pub struct ModuleEvaluator<'a> {
step_part: StepPart,
off: usize,
inputs: &'a [f64],
curr: &'a mut [f64],
next: &'a mut [f64],
module: &'a Module,
sim: &'a Simulation,
}
impl<'a> ModuleEvaluator<'a> {
fn eval(&mut self, expr: &Expr) -> f64 {
match expr {
Expr::Const(n, _) => *n,
Expr::Dt(_) => self.curr[DT_OFF],
Expr::ModuleInput(off, _) => self.inputs[*off],
Expr::EvalModule(ident, model_name, args) => {
let args: Vec<f64> = args.iter().map(|arg| self.eval(arg)).collect();
let module_offsets = &self.module.offsets[&self.module.ident];
let off = self.off + module_offsets[ident].0;
let module = &self.sim.modules[model_name.as_str()];
self.sim
.calc(self.step_part, module, off, &args, self.curr, self.next);
0.0
}
Expr::Var(off, _) => self.curr[self.off + *off],
Expr::Subscript(off, r, bounds, _) => {
let indices: Vec<_> = r.iter().map(|r| self.eval(r)).collect();
let mut index = 0;
let max_bounds = bounds.iter().product();
let mut ok = true;
assert_eq!(indices.len(), bounds.len());
for (i, rhs) in indices.into_iter().enumerate() {
let bounds = bounds[i];
let one_index = rhs.floor() as usize;
if one_index == 0 || one_index > bounds {
ok = false;
break;
} else {
index *= bounds;
index += one_index - 1;
}
}
if !ok || index > max_bounds {
// 3.7.1 Arrays: If a subscript expression results in an invalid subscript index (i.e., it is out of range), a zero (0) MUST be returned[10]
// note 10: Note this can be NaN if so specified in the <uses_arrays> tag of the header options block
// 0 makes less sense than NaN, so lets do that until real models force us to do otherwise
f64::NAN
} else {
self.curr[self.off + *off + index]
}
}
Expr::AssignCurr(off, r) => {
let rhs = self.eval(r);
if self.off + *off > self.curr.len() {
unreachable!();
}
self.curr[self.off + *off] = rhs;
0.0
}
Expr::AssignNext(off, r) => {
let rhs = self.eval(r);
self.next[self.off + *off] = rhs;
0.0
}
Expr::If(cond, t, f, _) => {
let cond: f64 = self.eval(cond);
if is_truthy(cond) {
self.eval(t)
} else {
self.eval(f)
}
}
Expr::Op1(op, l, _) => {
let l = self.eval(l);
match op {
UnaryOp::Not => (!is_truthy(l)) as i8 as f64,
}
}
Expr::Op2(op, l, r, _) => {
let l = self.eval(l);
let r = self.eval(r);
match op {
BinaryOp::Add => l + r,
BinaryOp::Sub => l - r,
BinaryOp::Exp => l.powf(r),
BinaryOp::Mul => l * r,
BinaryOp::Div => l / r,
BinaryOp::Mod => l.rem_euclid(r),
BinaryOp::Gt => (l > r) as i8 as f64,
BinaryOp::Gte => (l >= r) as i8 as f64,
BinaryOp::Lt => (l < r) as i8 as f64,
BinaryOp::Lte => (l <= r) as i8 as f64,
BinaryOp::Eq => approx_eq!(f64, l, r) as i8 as f64,
BinaryOp::Neq => !approx_eq!(f64, l, r) as i8 as f64,
BinaryOp::And => (is_truthy(l) && is_truthy(r)) as i8 as f64,
BinaryOp::Or => (is_truthy(l) || is_truthy(r)) as i8 as f64,
}
}
Expr::App(builtin, _) => {
match builtin {
BuiltinFn::Time
| BuiltinFn::TimeStep
| BuiltinFn::StartTime
| BuiltinFn::FinalTime => {
let off = match builtin {
BuiltinFn::Time => TIME_OFF,
BuiltinFn::TimeStep => DT_OFF,
BuiltinFn::StartTime => INITIAL_TIME_OFF,
BuiltinFn::FinalTime => FINAL_TIME_OFF,
_ => unreachable!(),
};
self.curr[off]
}
BuiltinFn::Abs(a) => self.eval(a).abs(),
BuiltinFn::Cos(a) => self.eval(a).cos(),
BuiltinFn::Sin(a) => self.eval(a).sin(),
BuiltinFn::Tan(a) => self.eval(a).tan(),
BuiltinFn::Arccos(a) => self.eval(a).acos(),
BuiltinFn::Arcsin(a) => self.eval(a).asin(),
BuiltinFn::Arctan(a) => self.eval(a).atan(),
BuiltinFn::Exp(a) => self.eval(a).exp(),
BuiltinFn::Inf => std::f64::INFINITY,
BuiltinFn::Pi => std::f64::consts::PI,
BuiltinFn::Int(a) => self.eval(a).floor(),
BuiltinFn::IsModuleInput(ident, _) => {
self.module.inputs.contains(ident) as i8 as f64
}
BuiltinFn::Ln(a) => self.eval(a).ln(),
BuiltinFn::Log10(a) => self.eval(a).log10(),
BuiltinFn::SafeDiv(a, b, default) => {
let a = self.eval(a);
let b = self.eval(b);
if b != 0.0 {
a / b
} else if let Some(c) = default {
self.eval(c)
} else {
0.0
}
}
BuiltinFn::Sqrt(a) => self.eval(a).sqrt(),
BuiltinFn::Min(a, b) => {
let a = self.eval(a);
let b = self.eval(b);
// we can't use std::cmp::min here, becuase f64 is only
// PartialOrd
if a < b {
a
} else {
b
}
}
BuiltinFn::Mean(args) => {
let count = args.len() as f64;
let sum: f64 = args.iter().map(|arg| self.eval(arg)).sum();
sum / count
}
BuiltinFn::Max(a, b) => {
let a = self.eval(a);
let b = self.eval(b);
// we can't use std::cmp::min here, becuase f64 is only
// PartialOrd
if a > b {
a
} else {
b
}
}
BuiltinFn::Lookup(id, index, _) => {
if !self.module.tables.contains_key(id) {
eprintln!("bad lookup for {}", id);
unreachable!();
}
let table = &self.module.tables[id].data;
if table.is_empty() {
return f64::NAN;
}
let index = self.eval(index);
if index.is_nan() {
// things get wonky below if we try to binary search for NaN
return f64::NAN;
}
// check if index is below the start of the table
{
let (x, y) = table[0];
if index < x {
return y;
}
}
let size = table.len();
{
let (x, y) = table[size - 1];
if index > x {
return y;
}
}
// binary search seems to be the most appropriate choice here.
let mut low = 0;
let mut high = size;
while low < high {
let mid = low + (high - low) / 2;
if table[mid].0 < index {
low = mid + 1;
} else {
high = mid;
}
}
let i = low;
if approx_eq!(f64, table[i].0, index) {
table[i].1
} else {
// slope = deltaY/deltaX
let slope =
(table[i].1 - table[i - 1].1) / (table[i].0 - table[i - 1].0);
// y = m*x + b
(index - table[i - 1].0) * slope + table[i - 1].1
}
}
BuiltinFn::Pulse(a, b, c) => {
let time = self.curr[TIME_OFF];
let dt = self.curr[DT_OFF];
let volume = self.eval(a);
let first_pulse = self.eval(b);
let interval = match c.as_ref() {
Some(c) => self.eval(c),
None => 0.0,
};
pulse(time, dt, volume, first_pulse, interval)
}
BuiltinFn::Ramp(a, b, c) => {
let time = self.curr[TIME_OFF];
let slope = self.eval(a);
let start_time = self.eval(b);
let end_time = c.as_ref().map(|c| self.eval(c));
ramp(time, slope, start_time, end_time)
}
BuiltinFn::Step(a, b) => {
let time = self.curr[TIME_OFF];
let dt = self.curr[DT_OFF];
let height = self.eval(a);
let step_time = self.eval(b);
step(time, dt, height, step_time)
}
}
}
}
}
}
fn child_needs_parens(parent: &Expr, child: &Expr) -> bool {
match parent {
// no children so doesn't matter
Expr::Const(_, _) | Expr::Var(_, _) => false,
// children are comma separated, so no ambiguity possible
Expr::App(_, _) | Expr::Subscript(_, _, _, _) => false,
// these don't need it
Expr::Dt(_)
| Expr::EvalModule(_, _, _)
| Expr::ModuleInput(_, _)
| Expr::AssignCurr(_, _)
| Expr::AssignNext(_, _) => false,
Expr::Op1(_, _, _) => matches!(child, Expr::Op2(_, _, _, _)),
Expr::Op2(parent_op, _, _, _) => match child {
Expr::Const(_, _)
| Expr::Var(_, _)
| Expr::App(_, _)
| Expr::Subscript(_, _, _, _)
| Expr::If(_, _, _, _)
| Expr::Dt(_)
| Expr::EvalModule(_, _, _)
| Expr::ModuleInput(_, _)
| Expr::AssignCurr(_, _)
| Expr::AssignNext(_, _)
| Expr::Op1(_, _, _) => false,
// 3 * 2 + 1
Expr::Op2(child_op, _, _, _) => {
// if we have `3 * (2 + 3)`, the parent's precedence
// is higher than the child and we need enclosing parens
parent_op.precedence() > child_op.precedence()
}
},
Expr::If(_, _, _, _) => false,
}
}
fn paren_if_necessary(parent: &Expr, child: &Expr, eqn: String) -> String {
if child_needs_parens(parent, child) {
format!("({})", eqn)
} else {
eqn
}
}
#[allow(dead_code)]
pub fn pretty(expr: &Expr) -> String {
match expr {
Expr::Const(n, _) => format!("{}", n),
Expr::Var(off, _) => format!("curr[{}]", off),
Expr::Subscript(off, args, bounds, _) => {
let args: Vec<_> = args.iter().map(|arg| pretty(arg)).collect();
let string_args = args.join(", ");
let bounds: Vec<_> = bounds.iter().map(|bounds| format!("{}", bounds)).collect();
let string_bounds = bounds.join(", ");
format!(
"curr[{} + (({}) - 1); bounds: {}]",
off, string_args, string_bounds
)
}
Expr::Dt(_) => "dt".to_string(),
Expr::App(builtin, _) => match builtin {
BuiltinFn::Time => "time".to_string(),
BuiltinFn::TimeStep => "time_step".to_string(),
BuiltinFn::StartTime => "initial_time".to_string(),
BuiltinFn::FinalTime => "final_time".to_string(),
BuiltinFn::Lookup(table, idx, _loc) => format!("lookup({}, {})", table, pretty(idx)),
BuiltinFn::Abs(l) => format!("abs({})", pretty(l)),
BuiltinFn::Arccos(l) => format!("arccos({})", pretty(l)),
BuiltinFn::Arcsin(l) => format!("arcsin({})", pretty(l)),
BuiltinFn::Arctan(l) => format!("arctan({})", pretty(l)),
BuiltinFn::Cos(l) => format!("cos({})", pretty(l)),
BuiltinFn::Exp(l) => format!("exp({})", pretty(l)),
BuiltinFn::Inf => "∞".to_string(),
BuiltinFn::Int(l) => format!("int({})", pretty(l)),
BuiltinFn::IsModuleInput(ident, _loc) => format!("isModuleInput({})", ident),
BuiltinFn::Ln(l) => format!("ln({})", pretty(l)),
BuiltinFn::Log10(l) => format!("log10({})", pretty(l)),
BuiltinFn::Max(l, r) => format!("max({}, {})", pretty(l), pretty(r)),
BuiltinFn::Mean(args) => {
let args: Vec<_> = args.iter().map(|arg| pretty(arg)).collect();
let string_args = args.join(", ");
format!("mean({})", string_args)
}
BuiltinFn::Min(l, r) => format!("min({}, {})", pretty(l), pretty(r)),
BuiltinFn::Pi => "𝜋".to_string(),
BuiltinFn::Pulse(a, b, c) => {
let c = match c.as_ref() {
Some(c) => pretty(c),
None => "0<default>".to_owned(),
};
format!("pulse({}, {}, {})", pretty(a), pretty(b), c)
}
BuiltinFn::Ramp(a, b, c) => {
let c = match c.as_ref() {
Some(c) => pretty(c),
None => "0<default>".to_owned(),
};
format!("ramp({}, {}, {})", pretty(a), pretty(b), c)
}
BuiltinFn::SafeDiv(a, b, c) => format!(
"safediv({}, {}, {})",
pretty(a),
pretty(b),
c.as_ref()
.map(|expr| pretty(expr))
.unwrap_or_else(|| "<None>".to_string())
),
BuiltinFn::Sin(l) => format!("sin({})", pretty(l)),
BuiltinFn::Sqrt(l) => format!("sqrt({})", pretty(l)),
BuiltinFn::Step(a, b) => {
format!("step({}, {})", pretty(a), pretty(b))
}
BuiltinFn::Tan(l) => format!("tan({})", pretty(l)),
},
Expr::EvalModule(module, model_name, args) => {
let args: Vec<_> = args.iter().map(|arg| pretty(arg)).collect();
let string_args = args.join(", ");
format!("eval<{}::{}>({})", module, model_name, string_args)
}
Expr::ModuleInput(a, _) => format!("mi<{}>", a),
Expr::Op2(op, l, r, _) => {
let op: &str = match op {
BinaryOp::Add => "+",
BinaryOp::Sub => "-",
BinaryOp::Exp => "^",
BinaryOp::Mul => "*",
BinaryOp::Div => "/",
BinaryOp::Mod => "%",
BinaryOp::Gt => ">",
BinaryOp::Gte => ">=",
BinaryOp::Lt => "<",
BinaryOp::Lte => "<=",
BinaryOp::Eq => "==",
BinaryOp::Neq => "!=",
BinaryOp::And => "&&",
BinaryOp::Or => "||",
};
format!(
"{} {} {}",
paren_if_necessary(expr, l, pretty(l)),
op,
paren_if_necessary(expr, r, pretty(r))
)
}
Expr::Op1(op, l, _) => {
let op: &str = match op {
UnaryOp::Not => "!",
};
format!("{}{}", op, paren_if_necessary(expr, l, pretty(l)))
}
Expr::If(cond, l, r, _) => {
format!("if {} then {} else {}", pretty(cond), pretty(l), pretty(r))
}
Expr::AssignCurr(off, rhs) => format!("curr[{}] := {}", off, pretty(rhs)),
Expr::AssignNext(off, rhs) => format!("next[{}] := {}", off, pretty(rhs)),
}
}
#[derive(Debug)]
pub struct Simulation {
pub(crate) modules: HashMap<Ident, Module>,
specs: Specs,
root: String,
offsets: HashMap<Ident, usize>,
}
impl Simulation {
pub fn new(project: &Project, main_model_name: &str) -> Result<Self> {
if !project.models.contains_key(main_model_name) {
return sim_err!(
NotSimulatable,
format!("no model named '{}' to simulate", main_model_name)
);
}
let modules = {
let project_models: HashMap<_, _> = project
.models
.iter()
.map(|(name, model)| (name.as_str(), model.as_ref()))
.collect();
// then pull in all the module instantiations the main model depends on
enumerate_modules(&project_models, main_model_name, |model| model.name.clone())?
};
let module_names: Vec<&str> = {
let mut module_names: Vec<&str> = modules.iter().map(|(id, _)| id.as_str()).collect();
module_names.sort_unstable();
let mut sorted_names = vec![main_model_name];
sorted_names.extend(module_names.into_iter().filter(|n| *n != main_model_name));
sorted_names
};
let mut compiled_modules: HashMap<Ident, Module> = HashMap::new();
for name in module_names {
let distinct_inputs = &modules[name];
for inputs in distinct_inputs.iter() {
let model = Rc::clone(&project.models[name]);
let is_root = name == main_model_name;
let module = Module::new(project, model, inputs, is_root)?;
compiled_modules.insert(name.to_string(), module);
}
}
let specs = Specs::from(&project.datamodel.sim_specs);
let offsets = calc_flattened_offsets(project, main_model_name);
let offsets: HashMap<Ident, usize> =
offsets.into_iter().map(|(k, (off, _))| (k, off)).collect();
Ok(Simulation {
modules: compiled_modules,
specs,
root: main_model_name.to_string(),
offsets,
})
}
pub fn compile(&self) -> Result<CompiledSimulation> {
let modules: Result<HashMap<String, CompiledModule>> = self
.modules
.iter()
.map(|(name, module)| module.compile().map(|module| (name.clone(), module)))
.collect();
Ok(CompiledSimulation {
modules: modules?,
specs: self.specs.clone(),
root: self.root.clone(),
offsets: self.offsets.clone(),
})
}
pub fn runlist_order(&self) -> Vec<Ident> {
calc_flattened_order(self, "main")
}
pub fn debug_print_runlists(&self, _model_name: &str) {
let mut model_names: Vec<_> = self.modules.keys().collect();
model_names.sort_unstable();
for model_name in model_names {
eprintln!("\n\nMODEL: {}", model_name);
let module = &self.modules[model_name];
let offsets = &module.offsets[model_name];
let mut idents: Vec<_> = offsets.keys().collect();
idents.sort_unstable();
eprintln!("offsets");
for ident in idents {
let (off, size) = offsets[ident];
eprintln!("\t{}: {}, {}", ident, off, size);
}
eprintln!("\ninital runlist:");
for expr in module.runlist_initials.iter() {
eprintln!("\t{}", pretty(expr));
}
eprintln!("\nflows runlist:");
for expr in module.runlist_flows.iter() {
eprintln!("\t{}", pretty(expr));
}
eprintln!("\nstocks runlist:");
for expr in module.runlist_stocks.iter() {
eprintln!("\t{}", pretty(expr));
}
}
}
fn calc(
&self,
step_part: StepPart,
module: &Module,
module_off: usize,
module_inputs: &[f64],
curr: &mut [f64],
next: &mut [f64],
) {
let runlist = match step_part {
StepPart::Initials => &module.runlist_initials,
StepPart::Flows => &module.runlist_flows,
StepPart::Stocks => &module.runlist_stocks,
};
let mut step = ModuleEvaluator {
step_part,
off: module_off,
curr,
next,
module,
inputs: module_inputs,
sim: self,
};
for expr in runlist.iter() {
step.eval(expr);
}
}
fn n_slots(&self, module_name: &str) -> usize {
self.modules[module_name].n_slots
}
pub fn run_to_end(&self) -> Result<Results> {
let spec = &self.specs;
if spec.stop < spec.start {
return sim_err!(BadSimSpecs, "".to_string());
}
let save_step = if spec.save_step > spec.dt {
spec.save_step
} else {
spec.dt
};
let n_chunks: usize = ((spec.stop - spec.start) / save_step + 1.0) as usize;
let save_every = std::cmp::max(1, (spec.save_step / spec.dt + 0.5).floor() as usize);
let dt = spec.dt;
let stop = spec.stop;
let n_slots = self.n_slots(&self.root);
let module = &self.modules[&self.root];
let slab: Vec<f64> = vec![0.0; n_slots * (n_chunks + 1)];
let mut boxed_slab = slab.into_boxed_slice();
{
let mut slabs = boxed_slab.chunks_mut(n_slots);
// let mut results: Vec<&[f64]> = Vec::with_capacity(n_chunks + 1);
let module_inputs: &[f64] = &[];
let mut curr = slabs.next().unwrap();
let mut next = slabs.next().unwrap();
curr[TIME_OFF] = self.specs.start;
curr[DT_OFF] = dt;
curr[INITIAL_TIME_OFF] = self.specs.start;
curr[FINAL_TIME_OFF] = self.specs.stop;
self.calc(StepPart::Initials, module, 0, module_inputs, curr, next);
let mut is_initial_timestep = true;
let mut step = 0;
loop {
self.calc(StepPart::Flows, module, 0, module_inputs, curr, next);
self.calc(StepPart::Stocks, module, 0, module_inputs, curr, next);
next[TIME_OFF] = curr[TIME_OFF] + dt;
next[DT_OFF] = dt;
curr[INITIAL_TIME_OFF] = self.specs.start;
curr[FINAL_TIME_OFF] = self.specs.stop;
step += 1;
if step != save_every && !is_initial_timestep {
let curr = curr.borrow_mut();
curr.copy_from_slice(next);
} else {
curr = next;
let maybe_next = slabs.next();
if maybe_next.is_none() {
break;
}
next = maybe_next.unwrap();
step = 0;
is_initial_timestep = false;
}
}
// ensure we've calculated stock + flow values for the dt <= end_time
assert!(curr[TIME_OFF] > stop);
}
Ok(Results {
offsets: self.offsets.clone(),
data: boxed_slab,
step_size: n_slots,
step_count: n_chunks,
specs: spec.clone(),
})
}
}
#[test]
fn test_arrays() {
let project = {
use crate::datamodel::*;
Project {
name: "arrays".to_owned(),
source: None,
sim_specs: SimSpecs {
start: 0.0,
stop: 12.0,
dt: Dt::Dt(0.25),
save_step: None,
sim_method: SimMethod::Euler,
time_units: Some("time".to_owned()),
},
dimensions: vec![Dimension {
name: "letters".to_owned(),
elements: vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
}],
units: vec![],
models: vec![Model {
name: "main".to_owned(),
variables: vec![
Variable::Aux(Aux {
ident: "constants".to_owned(),
equation: Equation::Arrayed(
vec!["letters".to_owned()],
vec![
("a".to_owned(), "9".to_owned()),
("b".to_owned(), "7".to_owned()),
("c".to_owned(), "5".to_owned()),
],
),
documentation: "".to_owned(),
units: None,
gf: None,
can_be_module_input: false,
visibility: Visibility::Private,
}),
Variable::Aux(Aux {
ident: "picked".to_owned(),
equation: Equation::Scalar("aux[INT(TIME MOD 5) + 1]".to_owned()),
documentation: "".to_owned(),
units: None,
gf: None,
can_be_module_input: false,
visibility: Visibility::Private,
}),
Variable::Aux(Aux {
ident: "aux".to_owned(),
equation: Equation::ApplyToAll(
vec!["letters".to_owned()],
"constants".to_owned(),
),
documentation: "".to_owned(),
units: None,
gf: None,
can_be_module_input: false,
visibility: Visibility::Private,
}),
Variable::Aux(Aux {
ident: "picked2".to_owned(),
equation: Equation::Scalar("aux[b]".to_owned()),
documentation: "".to_owned(),
units: None,
gf: None,
can_be_module_input: false,
visibility: Visibility::Private,
}),
],
views: vec![],
}],
}
};
let parsed_project = Rc::new(Project::from(project));
{
let actual = calc_flattened_offsets(&parsed_project, "main");
let expected: HashMap<_, _> = vec![
("time".to_owned(), (0, 1)),
("dt".to_owned(), (1, 1)),
("initial_time".to_owned(), (2, 1)),
("final_time".to_owned(), (3, 1)),
("aux[a]".to_owned(), (4, 1)),
("aux[b]".to_owned(), (5, 1)),
("aux[c]".to_owned(), (6, 1)),
("constants[a]".to_owned(), (7, 1)),
("constants[b]".to_owned(), (8, 1)),
("constants[c]".to_owned(), (9, 1)),
("picked".to_owned(), (10, 1)),
("picked2".to_owned(), (11, 1)),
]
.into_iter()
.collect();
assert_eq!(actual, expected);
}
let metadata = build_metadata(&parsed_project, "main", true);
let main_metadata = &metadata["main"];
assert_eq!(main_metadata["aux"].offset, 4);
assert_eq!(main_metadata["aux"].size, 3);
assert_eq!(main_metadata["constants"].offset, 7);
assert_eq!(main_metadata["constants"].size, 3);
assert_eq!(main_metadata["picked"].offset, 10);
assert_eq!(main_metadata["picked"].size, 1);
assert_eq!(main_metadata["picked2"].offset, 11);
assert_eq!(main_metadata["picked2"].size, 1);
let module_models = calc_module_model_map(&parsed_project, "main");
let arrayed_constants_var = &parsed_project.models["main"].variables["constants"];
let parsed_var = Var::new(
&Context {
dimensions: &parsed_project.datamodel.dimensions,
model_name: "main",
ident: arrayed_constants_var.ident(),
active_dimension: None,
active_subscript: None,
metadata: &metadata,
module_models: &module_models,
is_initial: false,
inputs: &BTreeSet::new(),
},
arrayed_constants_var,
);
assert!(parsed_var.is_ok());
let expected = Var {
ident: arrayed_constants_var.ident().to_owned(),
ast: vec![
Expr::AssignCurr(7, Box::new(Expr::Const(9.0, Loc::default()))),
Expr::AssignCurr(8, Box::new(Expr::Const(7.0, Loc::default()))),
Expr::AssignCurr(9, Box::new(Expr::Const(5.0, Loc::default()))),
],
};
let mut parsed_var = parsed_var.unwrap();
for expr in parsed_var.ast.iter_mut() {
*expr = expr.clone().strip_loc();
}
assert_eq!(expected, parsed_var);
let arrayed_aux_var = &parsed_project.models["main"].variables["aux"];
let parsed_var = Var::new(
&Context {
dimensions: &parsed_project.datamodel.dimensions,
model_name: "main",
ident: arrayed_aux_var.ident(),
active_dimension: None,
active_subscript: None,
metadata: &metadata,
module_models: &module_models,
is_initial: false,
inputs: &BTreeSet::new(),
},
arrayed_aux_var,
);
assert!(parsed_var.is_ok());
let expected = Var {
ident: arrayed_aux_var.ident().to_owned(),
ast: vec![
Expr::AssignCurr(4, Box::new(Expr::Var(7, Loc::default()))),
Expr::AssignCurr(5, Box::new(Expr::Var(8, Loc::default()))),
Expr::AssignCurr(6, Box::new(Expr::Var(9, Loc::default()))),
],
};
let mut parsed_var = parsed_var.unwrap();
for expr in parsed_var.ast.iter_mut() {
*expr = expr.clone().strip_loc();
}
assert_eq!(expected, parsed_var);
let var = &parsed_project.models["main"].variables["picked2"];
let parsed_var = Var::new(
&Context {
dimensions: &parsed_project.datamodel.dimensions,
model_name: "main",
ident: var.ident(),
active_dimension: None,
active_subscript: None,
metadata: &metadata,
module_models: &module_models,
is_initial: false,
inputs: &BTreeSet::new(),
},
var,
);
assert!(parsed_var.is_ok());
let expected = Var {
ident: var.ident().to_owned(),
ast: vec![Expr::AssignCurr(
11,
Box::new(Expr::Subscript(
4,
vec![Expr::Const(2.0, Loc::default())],
vec![3],
Loc::default(),
)),
)],
};
let mut parsed_var = parsed_var.unwrap();
for expr in parsed_var.ast.iter_mut() {
*expr = expr.clone().strip_loc();
}
assert_eq!(expected, parsed_var);
let var = &parsed_project.models["main"].variables["picked"];
let parsed_var = Var::new(
&Context {
dimensions: &parsed_project.datamodel.dimensions,
model_name: "main",
ident: var.ident(),
active_dimension: None,
active_subscript: None,
metadata: &metadata,
module_models: &module_models,
is_initial: false,
inputs: &BTreeSet::new(),
},
var,
);
assert!(parsed_var.is_ok());
let expected = Var {
ident: var.ident().to_owned(),
ast: vec![Expr::AssignCurr(
10,
Box::new(Expr::Subscript(
4,
vec![Expr::Op2(
BinaryOp::Add,
Box::new(Expr::App(
BuiltinFn::Int(Box::new(Expr::Op2(
BinaryOp::Mod,
Box::new(Expr::App(BuiltinFn::Time, Loc::default())),
Box::new(Expr::Const(5.0, Loc::default())),
Loc::default(),
))),
Loc::default(),
)),
Box::new(Expr::Const(1.0, Loc::default())),
Loc::default(),
)],
vec![3],
Loc::default(),
)),
)],
};
let mut parsed_var = parsed_var.unwrap();
for expr in parsed_var.ast.iter_mut() {
*expr = expr.clone().strip_loc();
}
assert_eq!(expected, parsed_var);
let sim = Simulation::new(&parsed_project, "main");
assert!(sim.is_ok());
}
#[test]
fn nan_is_approx_eq() {
assert!(approx_eq!(f64, f64::NAN, f64::NAN));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.